ol.el 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048
  1. ;;; ol.el --- Org links library -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2018-2021 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software; you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; This library provides tooling to handle both external and internal
  18. ;; links.
  19. ;;; Code:
  20. (require 'org-compat)
  21. (require 'org-macs)
  22. (defvar clean-buffer-list-kill-buffer-names)
  23. (defvar org-agenda-buffer-name)
  24. (defvar org-comment-string)
  25. (defvar org-highlight-links)
  26. (defvar org-id-link-to-org-use-id)
  27. (defvar org-inhibit-startup)
  28. (defvar org-outline-regexp-bol)
  29. (defvar org-src-source-file-name)
  30. (defvar org-time-stamp-formats)
  31. (defvar org-ts-regexp)
  32. (declare-function calendar-cursor-to-date "calendar" (&optional error event))
  33. (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
  34. (declare-function org-at-heading-p "org" (&optional _))
  35. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  36. (declare-function org-before-first-heading-p "org" ())
  37. (declare-function org-do-occur "org" (regexp &optional cleanup))
  38. (declare-function org-element-at-point "org-element" ())
  39. (declare-function org-element-cache-refresh "org-element" (pos))
  40. (declare-function org-element-context "org-element" (&optional element))
  41. (declare-function org-element-lineage "org-element" (datum &optional types with-self))
  42. (declare-function org-element-link-parser "org-element" ())
  43. (declare-function org-element-property "org-element" (property element))
  44. (declare-function org-element-type "org-element" (element))
  45. (declare-function org-element-update-syntax "org-element" ())
  46. (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
  47. (declare-function org-find-property "org" (property &optional value))
  48. (declare-function org-get-heading "org" (&optional no-tags no-todo no-priority no-comment))
  49. (declare-function org-id-find-id-file "org-id" (id))
  50. (declare-function org-id-store-link "org-id" ())
  51. (declare-function org-insert-heading "org" (&optional arg invisible-ok top))
  52. (declare-function org-load-modules-maybe "org" (&optional force))
  53. (declare-function org-mark-ring-push "org" (&optional pos buffer))
  54. (declare-function org-mode "org" ())
  55. (declare-function org-occur "org" (regexp &optional keep-previous callback))
  56. (declare-function org-open-file "org" (path &optional in-emacs line search))
  57. (declare-function org-overview "org" ())
  58. (declare-function org-restart-font-lock "org" ())
  59. (declare-function org-run-like-in-org-mode "org" (cmd))
  60. (declare-function org-show-context "org" (&optional key))
  61. (declare-function org-src-coderef-format "org-src" (&optional element))
  62. (declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
  63. (declare-function org-src-edit-buffer-p "org-src" (&optional buffer))
  64. (declare-function org-src-source-buffer "org-src" ())
  65. (declare-function org-src-source-type "org-src" ())
  66. (declare-function org-time-stamp-format "org" (&optional long inactive))
  67. (declare-function outline-next-heading "outline" ())
  68. ;;; Customization
  69. (defgroup org-link nil
  70. "Options concerning links in Org mode."
  71. :tag "Org Link"
  72. :group 'org)
  73. (defcustom org-link-parameters nil
  74. "Alist of properties that defines all the links in Org mode.
  75. The key in each association is a string of the link type.
  76. Subsequent optional elements make up a property list for that
  77. type.
  78. All properties are optional. However, the most important ones
  79. are, in this order, `:follow', `:export', and `:store', described
  80. below.
  81. `:follow'
  82. Function used to follow the link, when the `org-open-at-point'
  83. command runs on it. It is called with two arguments: the path,
  84. as a string, and a universal prefix argument.
  85. Here, you may use `org-link-open-as-file' helper function for
  86. types similar to \"file\".
  87. `:export'
  88. Function that accepts four arguments:
  89. - the path, as a string,
  90. - the description as a string, or nil,
  91. - the export back-end,
  92. - the export communication channel, as a plist.
  93. When nil, export for that type of link is delegated to the
  94. back-end.
  95. `:store'
  96. Function responsible for storing the link. See the function
  97. `org-store-link-functions' for a description of the expected
  98. arguments.
  99. Additional properties provide more specific control over the
  100. link.
  101. `:activate-func'
  102. Function to run at the end of Font Lock activation. It must
  103. accept four arguments:
  104. - the buffer position at the start of the link,
  105. - the buffer position at its end,
  106. - the path, as a string,
  107. - a boolean, non-nil when the link has brackets.
  108. `:complete'
  109. Function that inserts a link with completion. The function
  110. takes one optional prefix argument.
  111. `:display'
  112. Value for `invisible' text property on the hidden parts of the
  113. link. The most useful value is `full', which will not fold the
  114. link in descriptive display. Default is `org-link'.
  115. `:face'
  116. Face for the link, or a function returning a face. The
  117. function takes one argument, which is the path.
  118. The default face is `org-link'.
  119. `:help-echo'
  120. String or function used as a value for the `help-echo' text
  121. property. The function is called with one argument, the help
  122. string to display, and should return a string.
  123. `:htmlize-link'
  124. Function or plist for the `htmlize-link' text property. The
  125. function takes no argument.
  126. Default is (:uri \"type:path\")
  127. `:keymap'
  128. Active keymap when point is on the link. Default is
  129. `org-mouse-map'.
  130. `:mouse-face'
  131. Face used when hovering over the link. Default is
  132. `highlight'."
  133. :group 'org-link
  134. :package-version '(Org . "9.1")
  135. :type '(alist :tag "Link display parameters"
  136. :value-type plist)
  137. :safe nil)
  138. (defcustom org-link-descriptive t
  139. "Non-nil means Org displays descriptive links.
  140. E.g. [[https://orgmode.org][Org website]] is be displayed as
  141. \"Org Website\", hiding the link itself and just displaying its
  142. description. When set to nil, Org displays the full links
  143. literally.
  144. You can interactively set the value of this variable by calling
  145. `org-toggle-link-display' or from the \"Org > Hyperlinks\" menu."
  146. :group 'org-link
  147. :type 'boolean
  148. :safe #'booleanp)
  149. (defcustom org-link-make-description-function nil
  150. "Function to use for generating link descriptions from links.
  151. This function must take two parameters: the first one is the
  152. link, the second one is the description generated by
  153. `org-insert-link'. The function should return the description to
  154. use."
  155. :group 'org-link
  156. :type '(choice (const nil) (function))
  157. :safe #'null)
  158. (defcustom org-link-file-path-type 'adaptive
  159. "How the path name in file links should be stored.
  160. Valid values are:
  161. relative Relative to the current directory, i.e. the directory of the file
  162. into which the link is being inserted.
  163. absolute Absolute path, if possible with ~ for home directory.
  164. noabbrev Absolute path, no abbreviation of home directory.
  165. adaptive Use relative path for files in the current directory and sub-
  166. directories of it. For other files, use an absolute path."
  167. :group 'org-link
  168. :type '(choice
  169. (const relative)
  170. (const absolute)
  171. (const noabbrev)
  172. (const adaptive))
  173. :safe #'symbolp)
  174. (defcustom org-link-abbrev-alist nil
  175. "Alist of link abbreviations.
  176. The car of each element is a string, to be replaced at the start of a link.
  177. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  178. links in Org buffers can have an optional tag after a double colon, e.g.,
  179. [[linkkey:tag][description]]
  180. The `linkkey' must be a single word, starting with a letter, followed
  181. by letters, numbers, `-' or `_'.
  182. If REPLACE is a string, the tag will simply be appended to create the link.
  183. If the string contains \"%s\", the tag will be inserted there. If the string
  184. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  185. at that point (see the function `url-hexify-string'). If the string contains
  186. the specifier \"%(my-function)\", then the custom function `my-function' will
  187. be invoked: this function takes the tag as its only argument and must return
  188. a string.
  189. REPLACE may also be a function that will be called with the tag as the
  190. only argument to create the link, which should be returned as a string.
  191. See the manual for examples."
  192. :group 'org-link
  193. :type '(repeat
  194. (cons (string :tag "Protocol")
  195. (choice
  196. (string :tag "Format")
  197. (function))))
  198. :safe (lambda (val)
  199. (pcase val
  200. (`(,(pred stringp) . ,(pred stringp)) t)
  201. (_ nil))))
  202. (defgroup org-link-follow nil
  203. "Options concerning following links in Org mode."
  204. :tag "Org Follow Link"
  205. :group 'org-link)
  206. (defcustom org-link-translation-function nil
  207. "Function to translate links with different syntax to Org syntax.
  208. This can be used to translate links created for example by the Planner
  209. or emacs-wiki packages to Org syntax.
  210. The function must accept two parameters, a TYPE containing the link
  211. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  212. which is everything after the link protocol. It should return a cons
  213. with possibly modified values of type and path.
  214. Org contains a function for this, so if you set this variable to
  215. `org-translate-link-from-planner', you should be able follow many
  216. links created by planner."
  217. :group 'org-link-follow
  218. :type '(choice (const nil) (function))
  219. :safe #'null)
  220. (defcustom org-link-doi-server-url "https://doi.org/"
  221. "The URL of the DOI server."
  222. :group 'org-link-follow
  223. :version "24.3"
  224. :type 'string
  225. :safe #'stringp)
  226. (defcustom org-link-frame-setup
  227. '((vm . vm-visit-folder-other-frame)
  228. (vm-imap . vm-visit-imap-folder-other-frame)
  229. (gnus . org-gnus-no-new-news)
  230. (file . find-file-other-window)
  231. (wl . wl-other-frame))
  232. "Setup the frame configuration for following links.
  233. When following a link with Emacs, it may often be useful to display
  234. this link in another window or frame. This variable can be used to
  235. set this up for the different types of links.
  236. For VM, use any of
  237. `vm-visit-folder'
  238. `vm-visit-folder-other-window'
  239. `vm-visit-folder-other-frame'
  240. For Gnus, use any of
  241. `gnus'
  242. `gnus-other-frame'
  243. `org-gnus-no-new-news'
  244. For FILE, use any of
  245. `find-file'
  246. `find-file-other-window'
  247. `find-file-other-frame'
  248. For Wanderlust use any of
  249. `wl'
  250. `wl-other-frame'
  251. For the calendar, use the variable `calendar-setup'.
  252. For BBDB, it is currently only possible to display the matches in
  253. another window."
  254. :group 'org-link-follow
  255. :type '(list
  256. (cons (const vm)
  257. (choice
  258. (const vm-visit-folder)
  259. (const vm-visit-folder-other-window)
  260. (const vm-visit-folder-other-frame)))
  261. (cons (const vm-imap)
  262. (choice
  263. (const vm-visit-imap-folder)
  264. (const vm-visit-imap-folder-other-window)
  265. (const vm-visit-imap-folder-other-frame)))
  266. (cons (const gnus)
  267. (choice
  268. (const gnus)
  269. (const gnus-other-frame)
  270. (const org-gnus-no-new-news)))
  271. (cons (const file)
  272. (choice
  273. (const find-file)
  274. (const find-file-other-window)
  275. (const find-file-other-frame)))
  276. (cons (const wl)
  277. (choice
  278. (const wl)
  279. (const wl-other-frame))))
  280. :safe nil)
  281. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  282. "Non-nil means internal fuzzy links can only match headlines.
  283. When nil, the a fuzzy link may point to a target or a named
  284. construct in the document. When set to the special value
  285. `query-to-create', offer to create a new headline when none
  286. matched.
  287. Spaces and statistics cookies are ignored during heading searches."
  288. :group 'org-link-follow
  289. :version "24.1"
  290. :type '(choice
  291. (const :tag "Use fuzzy text search" nil)
  292. (const :tag "Match only exact headline" t)
  293. (const :tag "Match exact headline or query to create it"
  294. query-to-create))
  295. :safe #'symbolp)
  296. (defcustom org-link-use-indirect-buffer-for-internals nil
  297. "Non-nil means use indirect buffer to display infile links.
  298. Activating internal links (from one location in a file to another location
  299. in the same file) normally just jumps to the location. When the link is
  300. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  301. is displayed in
  302. another window. When this option is set, the other window actually displays
  303. an indirect buffer clone of the current buffer, to avoid any visibility
  304. changes to the current buffer."
  305. :group 'org-link-follow
  306. :type 'boolean
  307. :safe #'booleanp)
  308. (defcustom org-link-shell-confirm-function 'yes-or-no-p
  309. "Non-nil means ask for confirmation before executing shell links.
  310. Shell links can be dangerous: just think about a link
  311. [[shell:rm -rf ~/*][Google Search]]
  312. This link would show up in your Org document as \"Google Search\",
  313. but really it would remove your entire home directory.
  314. Therefore we advise against setting this variable to nil.
  315. Just change it to `y-or-n-p' if you want to confirm with a
  316. single keystroke rather than having to type \"yes\"."
  317. :group 'org-link-follow
  318. :type '(choice
  319. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  320. (const :tag "with y-or-n (faster)" y-or-n-p)
  321. (const :tag "no confirmation (dangerous)" nil))
  322. :safe nil)
  323. (defcustom org-link-shell-skip-confirm-regexp ""
  324. "Regexp to skip confirmation for shell links."
  325. :group 'org-link-follow
  326. :version "24.1"
  327. :type 'regexp
  328. :safe nil)
  329. (defcustom org-link-elisp-confirm-function 'yes-or-no-p
  330. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  331. Elisp links can be dangerous: just think about a link
  332. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  333. This link would show up in your Org document as \"Google Search\",
  334. but really it would remove your entire home directory.
  335. Therefore we advise against setting this variable to nil.
  336. Just change it to `y-or-n-p' if you want to confirm with a
  337. single keystroke rather than having to type \"yes\"."
  338. :group 'org-link-follow
  339. :type '(choice
  340. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  341. (const :tag "with y-or-n (faster)" y-or-n-p)
  342. (const :tag "no confirmation (dangerous)" nil))
  343. :safe nil)
  344. (defcustom org-link-elisp-skip-confirm-regexp ""
  345. "A regexp to skip confirmation for Elisp links."
  346. :group 'org-link-follow
  347. :version "24.1"
  348. :type 'regexp
  349. :safe nil)
  350. (defgroup org-link-store nil
  351. "Options concerning storing links in Org mode."
  352. :tag "Org Store Link"
  353. :group 'org-link)
  354. (defcustom org-link-context-for-files t
  355. "Non-nil means file links from `org-store-link' contain context.
  356. \\<org-mode-map>
  357. A search string is added to the file name with \"::\" as separator
  358. and used to find the context when the link is activated by the command
  359. `org-open-at-point'. When this option is t, the entire active region
  360. is be placed in the search string of the file link. If set to a
  361. positive integer N, only the first N lines of context are stored.
  362. Using a prefix argument to the command `org-store-link' \
  363. \(`\\[universal-argument] \\[org-store-link]')
  364. negates this setting for the duration of the command."
  365. :group 'org-link-store
  366. :type '(choice boolean integer)
  367. :safe (lambda (val) (or (booleanp val) (integerp val))))
  368. (defcustom org-link-email-description-format "Email %c: %s"
  369. "Format of the description part of a link to an email or usenet message.
  370. The following %-escapes will be replaced by corresponding information:
  371. %F full \"From\" field
  372. %f name, taken from \"From\" field, address if no name
  373. %T full \"To\" field
  374. %t first name in \"To\" field, address if no name
  375. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  376. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  377. %s subject
  378. %d date
  379. %m message-id.
  380. You may use normal field width specification between the % and the letter.
  381. This is for example useful to limit the length of the subject.
  382. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  383. :group 'org-link-store
  384. :package-version '(Org . "9.3")
  385. :type 'string
  386. :safe #'stringp)
  387. (defcustom org-link-from-user-regexp
  388. (let ((mail (and (org-string-nw-p user-mail-address)
  389. (format "\\<%s\\>" (regexp-quote user-mail-address))))
  390. (name (and (org-string-nw-p user-full-name)
  391. (format "\\<%s\\>" (regexp-quote user-full-name)))))
  392. (if (and mail name) (concat mail "\\|" name) (or mail name)))
  393. "Regexp matched against the \"From:\" header of an email or Usenet message.
  394. It should match if the message is from the user him/herself."
  395. :group 'org-link-store
  396. :type 'regexp
  397. :safe #'stringp)
  398. (defcustom org-link-keep-stored-after-insertion nil
  399. "Non-nil means keep link in list for entire session.
  400. \\<org-mode-map>
  401. The command `org-store-link' adds a link pointing to the current
  402. location to an internal list. These links accumulate during a session.
  403. The command `org-insert-link' can be used to insert links into any
  404. Org file (offering completion for all stored links).
  405. When this option is nil, every link which has been inserted once using
  406. `\\[org-insert-link]' will be removed from the list, to make completing the \
  407. unused
  408. links more efficient."
  409. :group 'org-link-store
  410. :type 'boolean
  411. :safe #'booleanp)
  412. ;;; Public variables
  413. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  414. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  415. border border border))
  416. "Regular expression matching a link target.")
  417. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  418. "Regular expression matching a radio target.")
  419. (defvar-local org-target-link-regexp nil
  420. "Regular expression matching radio targets in plain text.")
  421. (defvar org-link-types-re nil
  422. "Matches a link that has a url-like prefix like \"http:\"")
  423. (defvar org-link-angle-re nil
  424. "Matches link with angular brackets, spaces are allowed.")
  425. (defvar org-link-plain-re nil
  426. "Matches plain link, without spaces.
  427. Group 1 must contain the link type (i.e. https).
  428. Group 2 must contain the link path (i.e. //example.com).
  429. Used by `org-element-link-parser'.")
  430. (defvar org-link-bracket-re nil
  431. "Matches a link in double brackets.")
  432. (defvar org-link-any-re nil
  433. "Regular expression matching any link.")
  434. (defvar-local org-link-abbrev-alist-local nil
  435. "Buffer-local version of `org-link-abbrev-alist', which see.
  436. The value of this is taken from the LINK keywords.")
  437. (defvar org-stored-links nil
  438. "Contains the links stored with `org-store-link'.")
  439. (defvar org-store-link-plist nil
  440. "Plist with info about the most recently link created with `org-store-link'.")
  441. (defvar org-create-file-search-functions nil
  442. "List of functions to construct the right search string for a file link.
  443. These functions are called in turn with point at the location to
  444. which the link should point.
  445. A function in the hook should first test if it would like to
  446. handle this file type, for example by checking the `major-mode'
  447. or the file extension. If it decides not to handle this file, it
  448. should just return nil to give other functions a chance. If it
  449. does handle the file, it must return the search string to be used
  450. when following the link. The search string will be part of the
  451. file link, given after a double colon, and `org-open-at-point'
  452. will automatically search for it. If special measures must be
  453. taken to make the search successful, another function should be
  454. added to the companion hook `org-execute-file-search-functions',
  455. which see.
  456. A function in this hook may also use `setq' to set the variable
  457. `description' to provide a suggestion for the descriptive text to
  458. be used for this link when it gets inserted into an Org buffer
  459. with \\[org-insert-link].")
  460. (defvar org-execute-file-search-functions nil
  461. "List of functions to execute a file search triggered by a link.
  462. Functions added to this hook must accept a single argument, the
  463. search string that was part of the file link, the part after the
  464. double colon. The function must first check if it would like to
  465. handle this search, for example by checking the `major-mode' or
  466. the file extension. If it decides not to handle this search, it
  467. should just return nil to give other functions a chance. If it
  468. does handle the search, it must return a non-nil value to keep
  469. other functions from trying.
  470. Each function can access the current prefix argument through the
  471. variable `current-prefix-arg'. Note that a single prefix is used
  472. to force opening a link in Emacs, so it may be good to only use a
  473. numeric or double prefix to guide the search function.
  474. In case this is needed, a function in this hook can also restore
  475. the window configuration before `org-open-at-point' was called using:
  476. (set-window-configuration org-window-config-before-follow-link)")
  477. (defvar org-open-link-functions nil
  478. "Hook for functions finding a plain text link.
  479. These functions must take a single argument, the link content.
  480. They will be called for links that look like [[link text][description]]
  481. when LINK TEXT does not have a protocol like \"http:\" and does not look
  482. like a filename (e.g. \"./blue.png\").
  483. These functions will be called *before* Org attempts to resolve the
  484. link by doing text searches in the current buffer - so if you want a
  485. link \"[[target]]\" to still find \"<<target>>\", your function should
  486. handle this as a special case.
  487. When the function does handle the link, it must return a non-nil value.
  488. If it decides that it is not responsible for this link, it must return
  489. nil to indicate that that Org can continue with other options like
  490. exact and fuzzy text search.")
  491. ;;; Internal Variables
  492. (defconst org-link--forbidden-chars "]\t\n\r<>"
  493. "Characters forbidden within a link, as a string.")
  494. (defvar org-link--history nil
  495. "History for inserted links.")
  496. (defvar org-link--insert-history nil
  497. "Minibuffer history for links inserted with `org-insert-link'.")
  498. (defvar org-link--search-failed nil
  499. "Non-nil when last link search failed.")
  500. ;;; Internal Functions
  501. (defun org-link--try-special-completion (type)
  502. "If there is completion support for link type TYPE, offer it."
  503. (let ((fun (org-link-get-parameter type :complete)))
  504. (if (functionp fun)
  505. (funcall fun)
  506. (read-string "Link (no completion support): " (concat type ":")))))
  507. (defun org-link--prettify (link)
  508. "Return a human-readable representation of LINK.
  509. The car of LINK must be a raw link. The cdr of LINK must be
  510. either a link description or nil."
  511. (let ((desc (or (cadr link) "<no description>")))
  512. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  513. "<" (car link) ">")))
  514. (defun org-link--decode-compound (hex)
  515. "Unhexify Unicode hex-chars HEX.
  516. E.g. \"%C3%B6\" is the German o-Umlaut. Note: this function also
  517. decodes single byte encodings like \"%E1\" (a-acute) if not
  518. followed by another \"%[A-F0-9]{2}\" group."
  519. (save-match-data
  520. (let* ((bytes (cdr (split-string hex "%")))
  521. (ret "")
  522. (eat 0)
  523. (sum 0))
  524. (while bytes
  525. (let* ((val (string-to-number (pop bytes) 16))
  526. (shift-xor
  527. (if (= 0 eat)
  528. (cond
  529. ((>= val 252) (cons 6 252))
  530. ((>= val 248) (cons 5 248))
  531. ((>= val 240) (cons 4 240))
  532. ((>= val 224) (cons 3 224))
  533. ((>= val 192) (cons 2 192))
  534. (t (cons 0 0)))
  535. (cons 6 128))))
  536. (when (>= val 192) (setq eat (car shift-xor)))
  537. (setq val (logxor val (cdr shift-xor)))
  538. (setq sum (+ (lsh sum (car shift-xor)) val))
  539. (when (> eat 0) (setq eat (- eat 1)))
  540. (cond
  541. ((= 0 eat) ;multi byte
  542. (setq ret (concat ret (char-to-string sum)))
  543. (setq sum 0))
  544. ((not bytes) ; single byte(s)
  545. (setq ret (org-link--decode-single-byte-sequence hex))))))
  546. ret)))
  547. (defun org-link--decode-single-byte-sequence (hex)
  548. "Unhexify hex-encoded single byte character sequence HEX."
  549. (mapconcat (lambda (byte)
  550. (char-to-string (string-to-number byte 16)))
  551. (cdr (split-string hex "%"))
  552. ""))
  553. (defun org-link--fontify-links-to-this-file ()
  554. "Fontify links to the current file in `org-stored-links'."
  555. (let ((f (buffer-file-name)) a b)
  556. (setq a (mapcar (lambda(l)
  557. (let ((ll (car l)))
  558. (when (and (string-match "^file:\\(.+\\)::" ll)
  559. (equal f (expand-file-name (match-string 1 ll))))
  560. ll)))
  561. org-stored-links))
  562. (when (featurep 'org-id)
  563. (setq b (mapcar (lambda(l)
  564. (let ((ll (car l)))
  565. (when (and (string-match "^id:\\(.+\\)$" ll)
  566. (equal f (expand-file-name
  567. (or (org-id-find-id-file
  568. (match-string 1 ll)) ""))))
  569. ll)))
  570. org-stored-links)))
  571. (mapcar (lambda(l)
  572. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  573. (delq nil (append a b)))))
  574. (defun org-link--buffer-for-internals ()
  575. "Return buffer used for displaying the target of internal links."
  576. (cond
  577. ((not org-link-use-indirect-buffer-for-internals) (current-buffer))
  578. ((string-suffix-p "(Clone)" (buffer-name))
  579. (message "Buffer is already a clone, not making another one")
  580. ;; We also do not modify visibility in this case.
  581. (current-buffer))
  582. (t ;make a new indirect buffer for displaying the link
  583. (let* ((indirect-buffer-name (concat (buffer-name) "(Clone)"))
  584. (indirect-buffer
  585. (or (get-buffer indirect-buffer-name)
  586. (make-indirect-buffer (current-buffer)
  587. indirect-buffer-name
  588. 'clone))))
  589. (with-current-buffer indirect-buffer (org-overview))
  590. indirect-buffer))))
  591. (defun org-link--search-radio-target (target)
  592. "Search a radio target matching TARGET in current buffer.
  593. White spaces are not significant."
  594. (let ((re (format "<<<%s>>>"
  595. (mapconcat #'regexp-quote
  596. (split-string target)
  597. "[ \t]+\\(?:\n[ \t]*\\)?")))
  598. (origin (point)))
  599. (goto-char (point-min))
  600. (catch :radio-match
  601. (while (re-search-forward re nil t)
  602. (forward-char -1)
  603. (let ((object (org-element-context)))
  604. (when (eq (org-element-type object) 'radio-target)
  605. (goto-char (org-element-property :begin object))
  606. (org-show-context 'link-search)
  607. (throw :radio-match nil))))
  608. (goto-char origin)
  609. (user-error "No match for radio target: %s" target))))
  610. (defun org-link--context-from-region ()
  611. "Return context string from active region, or nil."
  612. (when (org-region-active-p)
  613. (let ((context (buffer-substring (region-beginning) (region-end))))
  614. (when (and (wholenump org-link-context-for-files)
  615. (> org-link-context-for-files 0))
  616. (let ((lines (org-split-string context "\n")))
  617. (setq context
  618. (mapconcat #'identity
  619. (cl-subseq lines 0 org-link-context-for-files)
  620. "\n"))))
  621. context)))
  622. (defun org-link--normalize-string (string &optional context)
  623. "Remove ignored contents from STRING string and return it.
  624. This function removes contiguous white spaces and statistics
  625. cookies. When optional argument CONTEXT is non-nil, it assumes
  626. STRING is a context string, and also removes special search
  627. syntax around the string."
  628. (let ((string
  629. (org-trim
  630. (replace-regexp-in-string
  631. (rx (one-or-more (any " \t")))
  632. " "
  633. (replace-regexp-in-string
  634. ;; Statistics cookie regexp.
  635. (rx (seq "[" (0+ digit) (or "%" (seq "/" (0+ digit))) "]"))
  636. " "
  637. string)))))
  638. (when context
  639. (while (cond ((and (string-prefix-p "(" string)
  640. (string-suffix-p ")" string))
  641. (setq string (org-trim (substring string 1 -1))))
  642. ((string-match "\\`[#*]+[ \t]*" string)
  643. (setq string (substring string (match-end 0))))
  644. (t nil))))
  645. string))
  646. ;;; Public API
  647. (defun org-link-types ()
  648. "Return a list of known link types."
  649. (mapcar #'car org-link-parameters))
  650. (defun org-link-get-parameter (type key)
  651. "Get TYPE link property for KEY.
  652. TYPE is a string and KEY is a plist keyword. See
  653. `org-link-parameters' for supported keywords."
  654. (plist-get (cdr (assoc type org-link-parameters))
  655. key))
  656. (defun org-link-set-parameters (type &rest parameters)
  657. "Set link TYPE properties to PARAMETERS.
  658. PARAMETERS should be keyword value pairs. See
  659. `org-link-parameters' for supported keys."
  660. (when (member type '("coderef" "custom-id" "fuzzy" "radio"))
  661. (error "Cannot override reserved link type: %S" type))
  662. (let ((data (assoc type org-link-parameters)))
  663. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  664. (push (cons type parameters) org-link-parameters)
  665. (org-link-make-regexps)
  666. (when (featurep 'org-element) (org-element-update-syntax)))))
  667. (defun org-link-make-regexps ()
  668. "Update the link regular expressions.
  669. This should be called after the variable `org-link-parameters' has changed."
  670. (let ((types-re (regexp-opt (org-link-types) t)))
  671. (setq org-link-types-re
  672. (concat "\\`" types-re ":")
  673. org-link-angle-re
  674. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  675. types-re)
  676. org-link-plain-re
  677. (let* ((non-space-bracket "[^][ \t\n()<>]")
  678. (parenthesis
  679. `(seq "("
  680. (0+ (or (regex ,non-space-bracket)
  681. (seq "("
  682. (0+ (regex ,non-space-bracket))
  683. ")")))
  684. ")")))
  685. ;; Heuristics for an URL link inspired by
  686. ;; https://daringfireball.net/2010/07/improved_regex_for_matching_urls
  687. (rx-to-string
  688. `(seq word-start
  689. ;; Link type: match group 1.
  690. (regexp ,types-re)
  691. ":"
  692. ;; Link path: match group 2.
  693. (group
  694. (1+ (or (regex ,non-space-bracket)
  695. ,parenthesis))
  696. (or (regexp "[^[:punct:] \t\n]")
  697. ?/
  698. ,parenthesis)))))
  699. org-link-bracket-re
  700. (rx (seq "[["
  701. ;; URI part: match group 1.
  702. (group
  703. (one-or-more
  704. (or (not (any "[]\\"))
  705. (and "\\" (zero-or-more "\\\\") (any "[]"))
  706. (and (one-or-more "\\") (not (any "[]"))))))
  707. "]"
  708. ;; Description (optional): match group 2.
  709. (opt "[" (group (+? anything)) "]")
  710. "]"))
  711. org-link-any-re
  712. (concat "\\(" org-link-bracket-re "\\)\\|\\("
  713. org-link-angle-re "\\)\\|\\("
  714. org-link-plain-re "\\)"))))
  715. (defun org-link-complete-file (&optional arg)
  716. "Create a file link using completion."
  717. (let ((file (read-file-name "File: "))
  718. (pwd (file-name-as-directory (expand-file-name ".")))
  719. (pwd1 (file-name-as-directory (abbreviate-file-name
  720. (expand-file-name ".")))))
  721. (cond ((equal arg '(16))
  722. (concat "file:"
  723. (abbreviate-file-name (expand-file-name file))))
  724. ((string-match
  725. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  726. (concat "file:" (match-string 1 file)))
  727. ((string-match
  728. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  729. (expand-file-name file))
  730. (concat "file:"
  731. (match-string 1 (expand-file-name file))))
  732. (t (concat "file:" file)))))
  733. (defun org-link-email-description (&optional fmt)
  734. "Return the description part of an email link.
  735. This takes information from `org-store-link-plist' and formats it
  736. according to FMT (default from `org-link-email-description-format')."
  737. (setq fmt (or fmt org-link-email-description-format))
  738. (let* ((p org-store-link-plist)
  739. (to (plist-get p :toaddress))
  740. (from (plist-get p :fromaddress))
  741. (table
  742. (list
  743. (cons "%c" (plist-get p :fromto))
  744. (cons "%F" (plist-get p :from))
  745. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  746. (cons "%T" (plist-get p :to))
  747. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  748. (cons "%s" (plist-get p :subject))
  749. (cons "%d" (plist-get p :date))
  750. (cons "%m" (plist-get p :message-id)))))
  751. (when (string-match "%c" fmt)
  752. ;; Check if the user wrote this message
  753. (if (and org-link-from-user-regexp from to
  754. (save-match-data (string-match org-link-from-user-regexp from)))
  755. (setq fmt (replace-match "to %t" t t fmt))
  756. (setq fmt (replace-match "from %f" t t fmt))))
  757. (org-replace-escapes fmt table)))
  758. (defun org-link-store-props (&rest plist)
  759. "Store link properties.
  760. The properties are pre-processed by extracting names, addresses
  761. and dates."
  762. (let ((x (plist-get plist :from)))
  763. (when x
  764. (let ((adr (mail-extract-address-components x)))
  765. (setq plist (plist-put plist :fromname (car adr)))
  766. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  767. (let ((x (plist-get plist :to)))
  768. (when x
  769. (let ((adr (mail-extract-address-components x)))
  770. (setq plist (plist-put plist :toname (car adr)))
  771. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  772. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  773. (when x
  774. (setq plist (plist-put plist :date-timestamp
  775. (format-time-string
  776. (org-time-stamp-format t) x)))
  777. (setq plist (plist-put plist :date-timestamp-inactive
  778. (format-time-string
  779. (org-time-stamp-format t t) x)))))
  780. (let ((from (plist-get plist :from))
  781. (to (plist-get plist :to)))
  782. (when (and from to org-link-from-user-regexp)
  783. (setq plist
  784. (plist-put plist :fromto
  785. (if (string-match org-link-from-user-regexp from)
  786. (concat "to %t")
  787. (concat "from %f"))))))
  788. (setq org-store-link-plist plist))
  789. (defun org-link-add-props (&rest plist)
  790. "Add these properties to the link property list."
  791. (let (key value)
  792. (while plist
  793. (setq key (pop plist) value (pop plist))
  794. (setq org-store-link-plist
  795. (plist-put org-store-link-plist key value)))))
  796. (defun org-link-encode (text table)
  797. "Return percent escaped representation of string TEXT.
  798. TEXT is a string with the text to escape. TABLE is a list of
  799. characters that should be escaped."
  800. (mapconcat
  801. (lambda (c)
  802. (if (memq c table)
  803. (mapconcat (lambda (e) (format "%%%.2X" e))
  804. (or (encode-coding-char c 'utf-8)
  805. (error "Unable to percent escape character: %c" c))
  806. "")
  807. (char-to-string c)))
  808. text ""))
  809. (defun org-link-decode (s)
  810. "Decode percent-encoded parts in string S.
  811. E.g. \"%C3%B6\" becomes the german o-Umlaut."
  812. (replace-regexp-in-string "\\(%[0-9A-Za-z]\\{2\\}\\)+"
  813. #'org-link--decode-compound s t t))
  814. (defun org-link-escape (link)
  815. "Backslash-escape sensitive characters in string LINK."
  816. (replace-regexp-in-string
  817. (rx (seq (group (zero-or-more "\\")) (group (or string-end (any "[]")))))
  818. (lambda (m)
  819. (concat (match-string 1 m)
  820. (match-string 1 m)
  821. (and (/= (match-beginning 2) (match-end 2)) "\\")))
  822. link nil t 1))
  823. (defun org-link-unescape (link)
  824. "Remove escaping backslash characters from string LINK."
  825. (replace-regexp-in-string
  826. (rx (group (one-or-more "\\")) (or string-end (any "[]")))
  827. (lambda (_)
  828. (concat (make-string (/ (- (match-end 1) (match-beginning 1)) 2) ?\\)))
  829. link nil t 1))
  830. (defun org-link-make-string (link &optional description)
  831. "Make a bracket link, consisting of LINK and DESCRIPTION.
  832. LINK is escaped with backslashes for inclusion in buffer."
  833. (let* ((zero-width-space (string ?\x200B))
  834. (description
  835. (and (org-string-nw-p description)
  836. ;; Description cannot contain two consecutive square
  837. ;; brackets, or end with a square bracket. To prevent
  838. ;; this, insert a zero width space character between
  839. ;; the brackets, or at the end of the description.
  840. (replace-regexp-in-string
  841. "\\(]\\)\\(]\\)"
  842. (concat "\\1" zero-width-space "\\2")
  843. (replace-regexp-in-string "]\\'"
  844. (concat "\\&" zero-width-space)
  845. (org-trim description))))))
  846. (if (not (org-string-nw-p link)) description
  847. (format "[[%s]%s]"
  848. (org-link-escape link)
  849. (if description (format "[%s]" description) "")))))
  850. (defun org-store-link-functions ()
  851. "List of functions that are called to create and store a link.
  852. The functions are defined in the `:store' property of
  853. `org-link-parameters'.
  854. Each function will be called in turn until one returns a non-nil
  855. value. Each function should check if it is responsible for
  856. creating this link (for example by looking at the major mode).
  857. If not, it must exit and return nil. If yes, it should return
  858. a non-nil value after calling `org-link-store-props' with a list
  859. of properties and values. Special properties are:
  860. :type The link prefix, like \"http\". This must be given.
  861. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  862. This is obligatory as well.
  863. :description Optional default description for the second pair
  864. of brackets in an Org mode link. The user can still change
  865. this when inserting this link into an Org mode buffer.
  866. In addition to these, any additional properties can be specified
  867. and then used in capture templates."
  868. (cl-loop for link in org-link-parameters
  869. with store-func
  870. do (setq store-func (org-link-get-parameter (car link) :store))
  871. if store-func
  872. collect store-func))
  873. (defun org-link-expand-abbrev (link)
  874. "Replace link abbreviations in LINK string.
  875. Abbreviations are defined in `org-link-abbrev-alist'."
  876. (if (not (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)) link
  877. (let* ((key (match-string 1 link))
  878. (as (or (assoc key org-link-abbrev-alist-local)
  879. (assoc key org-link-abbrev-alist)))
  880. (tag (and (match-end 2) (match-string 3 link)))
  881. rpl)
  882. (if (not as)
  883. link
  884. (setq rpl (cdr as))
  885. (cond
  886. ((symbolp rpl) (funcall rpl tag))
  887. ((string-match "%(\\([^)]+\\))" rpl)
  888. (replace-match
  889. (save-match-data
  890. (funcall (intern-soft (match-string 1 rpl)) tag))
  891. t t rpl))
  892. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  893. ((string-match "%h" rpl)
  894. (replace-match (url-hexify-string (or tag "")) t t rpl))
  895. (t (concat rpl tag)))))))
  896. (defun org-link-open (link &optional arg)
  897. "Open a link object LINK.
  898. ARG is an optional prefix argument. Some link types may handle
  899. it. For example, it determines what application to run when
  900. opening a \"file\" link.
  901. Functions responsible for opening the link are either hard-coded
  902. for internal and \"file\" links, or stored as a parameter in
  903. `org-link-parameters', which see."
  904. (let ((type (org-element-property :type link))
  905. (path (org-element-property :path link)))
  906. (pcase type
  907. ;; Opening a "file" link requires special treatment since we
  908. ;; first need to integrate search option, if any.
  909. ("file"
  910. (let* ((option (org-element-property :search-option link))
  911. (path (if option (concat path "::" option) path)))
  912. (org-link-open-as-file path
  913. (pcase (org-element-property :application link)
  914. ((guard arg) arg)
  915. ("emacs" 'emacs)
  916. ("sys" 'system)))))
  917. ;; Internal links.
  918. ((or "coderef" "custom-id" "fuzzy" "radio")
  919. (unless (run-hook-with-args-until-success 'org-open-link-functions path)
  920. (if (not arg) (org-mark-ring-push)
  921. (switch-to-buffer-other-window (org-link--buffer-for-internals)))
  922. (let ((destination
  923. (org-with-wide-buffer
  924. (if (equal type "radio")
  925. (org-link--search-radio-target path)
  926. (org-link-search
  927. (pcase type
  928. ("custom-id" (concat "#" path))
  929. ("coderef" (format "(%s)" path))
  930. (_ path))
  931. ;; Prevent fuzzy links from matching themselves.
  932. (and (equal type "fuzzy")
  933. (+ 2 (org-element-property :begin link)))))
  934. (point))))
  935. (unless (and (<= (point-min) destination)
  936. (>= (point-max) destination))
  937. (widen))
  938. (goto-char destination))))
  939. (_
  940. ;; Look for a dedicated "follow" function in custom links.
  941. (let ((f (org-link-get-parameter type :follow)))
  942. (when (functionp f)
  943. ;; Function defined in `:follow' parameter may use a single
  944. ;; argument, as it was mandatory before Org 9.4. This is
  945. ;; deprecated, but support it for now.
  946. (condition-case nil
  947. (funcall (org-link-get-parameter type :follow) path arg)
  948. (wrong-number-of-arguments
  949. (funcall (org-link-get-parameter type :follow) path)))))))))
  950. (defun org-link-open-from-string (s &optional arg)
  951. "Open a link in the string S, as if it was in Org mode.
  952. Optional argument is passed to `org-open-file' when S is
  953. a \"file\" link."
  954. (interactive "sLink: \nP")
  955. (pcase (with-temp-buffer
  956. (let ((org-inhibit-startup nil))
  957. (insert s)
  958. (org-mode)
  959. (goto-char (point-min))
  960. (org-element-link-parser)))
  961. (`nil (user-error "No valid link in %S" s))
  962. (link (org-link-open link arg))))
  963. (defun org-link-search (s &optional avoid-pos stealth)
  964. "Search for a search string S.
  965. If S starts with \"#\", it triggers a custom ID search.
  966. If S is enclosed within parenthesis, it initiates a coderef
  967. search.
  968. If S is surrounded by forward slashes, it is interpreted as
  969. a regular expression. In Org mode files, this will create an
  970. `org-occur' sparse tree. In ordinary files, `occur' will be used
  971. to list matches. If the current buffer is in `dired-mode', grep
  972. will be used to search in all files.
  973. When AVOID-POS is given, ignore matches near that position.
  974. When optional argument STEALTH is non-nil, do not modify
  975. visibility around point, thus ignoring `org-show-context-detail'
  976. variable.
  977. Search is case-insensitive and ignores white spaces. Return type
  978. of matched result, which is either `dedicated' or `fuzzy'."
  979. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  980. (let* ((case-fold-search t)
  981. (origin (point))
  982. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  983. (starred (eq (string-to-char normalized) ?*))
  984. (words (split-string (if starred (substring s 1) s)))
  985. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  986. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  987. type)
  988. (cond
  989. ;; Check if there are any special search functions.
  990. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  991. ((eq (string-to-char s) ?#)
  992. ;; Look for a custom ID S if S starts with "#".
  993. (let* ((id (substring normalized 1))
  994. (match (org-find-property "CUSTOM_ID" id)))
  995. (if match (progn (goto-char match) (setf type 'dedicated))
  996. (error "No match for custom ID: %s" id))))
  997. ((string-match "\\`(\\(.*\\))\\'" normalized)
  998. ;; Look for coderef targets if S is enclosed within parenthesis.
  999. (let ((coderef (match-string-no-properties 1 normalized))
  1000. (re (substring s-single-re 1 -1)))
  1001. (goto-char (point-min))
  1002. (catch :coderef-match
  1003. (while (re-search-forward re nil t)
  1004. (let ((element (org-element-at-point)))
  1005. (when (and (memq (org-element-type element)
  1006. '(example-block src-block))
  1007. (org-match-line
  1008. (concat ".*?" (org-src-coderef-regexp
  1009. (org-src-coderef-format element)
  1010. coderef))))
  1011. (setq type 'dedicated)
  1012. (goto-char (match-beginning 2))
  1013. (throw :coderef-match nil))))
  1014. (goto-char origin)
  1015. (error "No match for coderef: %s" coderef))))
  1016. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  1017. ;; Look for a regular expression.
  1018. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  1019. (match-string 1 s)))
  1020. ;; From here, we handle fuzzy links.
  1021. ;;
  1022. ;; Look for targets, only if not in a headline search.
  1023. ((and (not starred)
  1024. (let ((target (format "<<%s>>" s-multi-re)))
  1025. (catch :target-match
  1026. (goto-char (point-min))
  1027. (while (re-search-forward target nil t)
  1028. (backward-char)
  1029. (let ((context (org-element-context)))
  1030. (when (eq (org-element-type context) 'target)
  1031. (setq type 'dedicated)
  1032. (goto-char (org-element-property :begin context))
  1033. (throw :target-match t))))
  1034. nil))))
  1035. ;; Look for elements named after S, only if not in a headline
  1036. ;; search.
  1037. ((and (not starred)
  1038. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  1039. (catch :name-match
  1040. (goto-char (point-min))
  1041. (while (re-search-forward name nil t)
  1042. (let* ((element (org-element-at-point))
  1043. (name (org-element-property :name element)))
  1044. (when (and name (equal words (split-string name)))
  1045. (setq type 'dedicated)
  1046. (beginning-of-line)
  1047. (throw :name-match t))))
  1048. nil))))
  1049. ;; Regular text search. Prefer headlines in Org mode buffers.
  1050. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  1051. ;; statistics cookies and tags.
  1052. ((and (derived-mode-p 'org-mode)
  1053. (let ((title-re
  1054. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  1055. org-outline-regexp-bol
  1056. org-comment-string
  1057. (mapconcat #'regexp-quote words ".+"))))
  1058. (goto-char (point-min))
  1059. (catch :found
  1060. (while (re-search-forward title-re nil t)
  1061. (when (equal words
  1062. (split-string
  1063. (org-link--normalize-string
  1064. (org-get-heading t t t t))))
  1065. (throw :found t)))
  1066. nil)))
  1067. (beginning-of-line)
  1068. (setq type 'dedicated))
  1069. ;; Offer to create non-existent headline depending on
  1070. ;; `org-link-search-must-match-exact-headline'.
  1071. ((and (derived-mode-p 'org-mode)
  1072. (eq org-link-search-must-match-exact-headline 'query-to-create)
  1073. (yes-or-no-p "No match - create this as a new heading? "))
  1074. (goto-char (point-max))
  1075. (unless (bolp) (newline))
  1076. (org-insert-heading nil t t)
  1077. (insert s "\n")
  1078. (beginning-of-line 0))
  1079. ;; Only headlines are looked after. No need to process
  1080. ;; further: throw an error.
  1081. ((and (derived-mode-p 'org-mode)
  1082. (or starred org-link-search-must-match-exact-headline))
  1083. (goto-char origin)
  1084. (error "No match for fuzzy expression: %s" normalized))
  1085. ;; Regular text search.
  1086. ((catch :fuzzy-match
  1087. (goto-char (point-min))
  1088. (while (re-search-forward s-multi-re nil t)
  1089. ;; Skip match if it contains AVOID-POS or it is included in
  1090. ;; a link with a description but outside the description.
  1091. (unless (or (and avoid-pos
  1092. (<= (match-beginning 0) avoid-pos)
  1093. (> (match-end 0) avoid-pos))
  1094. (and (save-match-data
  1095. (org-in-regexp org-link-bracket-re))
  1096. (match-beginning 3)
  1097. (or (> (match-beginning 3) (point))
  1098. (<= (match-end 3) (point)))
  1099. (org-element-lineage
  1100. (save-match-data (org-element-context))
  1101. '(link) t)))
  1102. (goto-char (match-beginning 0))
  1103. (setq type 'fuzzy)
  1104. (throw :fuzzy-match t)))
  1105. nil))
  1106. ;; All failed. Throw an error.
  1107. (t (goto-char origin)
  1108. (error "No match for fuzzy expression: %s" normalized)))
  1109. ;; Disclose surroundings of match, if appropriate.
  1110. (when (and (derived-mode-p 'org-mode) (not stealth))
  1111. (org-show-context 'link-search))
  1112. type))
  1113. (defun org-link-heading-search-string (&optional string)
  1114. "Make search string for the current headline or STRING.
  1115. Search string starts with an asterisk. COMMENT keyword and
  1116. statistics cookies are removed, and contiguous spaces are packed
  1117. into a single one.
  1118. When optional argument STRING is non-nil, assume it a headline,
  1119. without any asterisk, TODO or COMMENT keyword, and without any
  1120. priority cookie or tag."
  1121. (concat "*"
  1122. (org-link--normalize-string
  1123. (or string (org-get-heading t t t t)))))
  1124. (defun org-link-open-as-file (path arg)
  1125. "Pretend PATH is a file name and open it.
  1126. According to \"file\"-link syntax, PATH may include additional
  1127. search options, separated from the file name with \"::\".
  1128. This function is meant to be used as a possible tool for
  1129. `:follow' property in `org-link-parameters'."
  1130. (let* ((option (and (string-match "::\\(.*\\)\\'" path)
  1131. (match-string 1 path)))
  1132. (file-name (if (not option) path
  1133. (substring path 0 (match-beginning 0)))))
  1134. (if (string-match "[*?{]" (file-name-nondirectory file-name))
  1135. (dired file-name)
  1136. (apply #'org-open-file
  1137. file-name
  1138. arg
  1139. (cond ((not option) nil)
  1140. ((string-match-p "\\`[0-9]+\\'" option)
  1141. (list (string-to-number option)))
  1142. (t (list nil option)))))))
  1143. (defun org-link-display-format (s)
  1144. "Replace links in string S with their description.
  1145. If there is no description, use the link target."
  1146. (save-match-data
  1147. (replace-regexp-in-string
  1148. org-link-bracket-re
  1149. (lambda (m) (or (match-string 2 m) (match-string 1 m)))
  1150. s nil t)))
  1151. (defun org-link-add-angle-brackets (s)
  1152. "Wrap string S within angle brackets."
  1153. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  1154. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  1155. s)
  1156. ;;; Built-in link types
  1157. ;;;; "doi" link type
  1158. (defun org-link--open-doi (path arg)
  1159. "Open a \"doi\" type link.
  1160. PATH is a the path to search for, as a string."
  1161. (browse-url (url-encode-url (concat org-link-doi-server-url path)) arg))
  1162. (org-link-set-parameters "doi" :follow #'org-link--open-doi)
  1163. ;;;; "elisp" link type
  1164. (defun org-link--open-elisp (path _)
  1165. "Open a \"elisp\" type link.
  1166. PATH is the sexp to evaluate, as a string."
  1167. (if (or (and (org-string-nw-p org-link-elisp-skip-confirm-regexp)
  1168. (string-match-p org-link-elisp-skip-confirm-regexp path))
  1169. (not org-link-elisp-confirm-function)
  1170. (funcall org-link-elisp-confirm-function
  1171. (format "Execute %S as Elisp? "
  1172. (org-add-props path nil 'face 'org-warning))))
  1173. (message "%s => %s" path
  1174. (if (eq ?\( (string-to-char path))
  1175. (eval (read path))
  1176. (call-interactively (read path))))
  1177. (user-error "Abort")))
  1178. (org-link-set-parameters "elisp" :follow #'org-link--open-elisp)
  1179. ;;;; "file" link type
  1180. (org-link-set-parameters "file" :complete #'org-link-complete-file)
  1181. ;;;; "help" link type
  1182. (defun org-link--open-help (path _)
  1183. "Open a \"help\" type link.
  1184. PATH is a symbol name, as a string."
  1185. (pcase (intern path)
  1186. ((and (pred fboundp) function) (describe-function function))
  1187. ((and (pred boundp) variable) (describe-variable variable))
  1188. (name (user-error "Unknown function or variable: %s" name))))
  1189. (org-link-set-parameters "help" :follow #'org-link--open-help)
  1190. ;;;; "http", "https", "mailto", "ftp", and "news" link types
  1191. (dolist (scheme '("ftp" "http" "https" "mailto" "news"))
  1192. (org-link-set-parameters scheme
  1193. :follow
  1194. (lambda (url arg)
  1195. (browse-url (concat scheme ":" url) arg))))
  1196. ;;;; "shell" link type
  1197. (defun org-link--open-shell (path _)
  1198. "Open a \"shell\" type link.
  1199. PATH is the command to execute, as a string."
  1200. (if (or (and (org-string-nw-p org-link-shell-skip-confirm-regexp)
  1201. (string-match-p org-link-shell-skip-confirm-regexp path))
  1202. (not org-link-shell-confirm-function)
  1203. (funcall org-link-shell-confirm-function
  1204. (format "Execute %S in shell? "
  1205. (org-add-props path nil 'face 'org-warning))))
  1206. (let ((buf (generate-new-buffer "*Org Shell Output*")))
  1207. (message "Executing %s" path)
  1208. (shell-command path buf)
  1209. (when (featurep 'midnight)
  1210. (setq clean-buffer-list-kill-buffer-names
  1211. (cons (buffer-name buf)
  1212. clean-buffer-list-kill-buffer-names))))
  1213. (user-error "Abort")))
  1214. (org-link-set-parameters "shell" :follow #'org-link--open-shell)
  1215. ;;; Interactive Functions
  1216. ;;;###autoload
  1217. (defun org-next-link (&optional search-backward)
  1218. "Move forward to the next link.
  1219. If the link is in hidden text, expose it. When SEARCH-BACKWARD
  1220. is non-nil, move backward."
  1221. (interactive)
  1222. (let ((pos (point))
  1223. (search-fun (if search-backward #'re-search-backward
  1224. #'re-search-forward)))
  1225. ;; Tweak initial position. If last search failed, wrap around.
  1226. ;; Otherwise, make sure we do not match current link.
  1227. (cond
  1228. ((not (and org-link--search-failed (eq this-command last-command)))
  1229. (cond
  1230. ((and (not search-backward) (looking-at org-link-any-re))
  1231. (goto-char (match-end 0)))
  1232. (search-backward
  1233. (pcase (org-in-regexp org-link-any-re nil t)
  1234. (`(,beg . ,_) (goto-char beg))
  1235. (_ nil)))
  1236. (t nil)))
  1237. (search-backward
  1238. (goto-char (point-max))
  1239. (message "Link search wrapped back to end of buffer"))
  1240. (t
  1241. (goto-char (point-min))
  1242. (message "Link search wrapped back to beginning of buffer")))
  1243. (setq org-link--search-failed nil)
  1244. (catch :found
  1245. (while (funcall search-fun org-link-any-re nil t)
  1246. (let ((context (save-excursion
  1247. (unless search-backward (forward-char -1))
  1248. (org-element-context))))
  1249. (pcase (org-element-lineage context '(link) t)
  1250. (`nil nil)
  1251. (link
  1252. (goto-char (org-element-property :begin link))
  1253. (when (org-invisible-p) (org-show-context))
  1254. (throw :found t)))))
  1255. (goto-char pos)
  1256. (setq org-link--search-failed t)
  1257. (message "No further link found"))))
  1258. ;;;###autoload
  1259. (defun org-previous-link ()
  1260. "Move backward to the previous link.
  1261. If the link is in hidden text, expose it."
  1262. (interactive)
  1263. (org-next-link t))
  1264. ;;;###autoload
  1265. (defun org-toggle-link-display ()
  1266. "Toggle the literal or descriptive display of links."
  1267. (interactive)
  1268. (if org-link-descriptive (remove-from-invisibility-spec '(org-link))
  1269. (add-to-invisibility-spec '(org-link)))
  1270. (org-restart-font-lock)
  1271. (setq org-link-descriptive (not org-link-descriptive)))
  1272. ;;;###autoload
  1273. (defun org-store-link (arg &optional interactive?)
  1274. "Store a link to the current location.
  1275. \\<org-mode-map>
  1276. This link is added to `org-stored-links' and can later be inserted
  1277. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  1278. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  1279. A single
  1280. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  1281. `org-gnus-prefer-web-links' for links to Usenet articles.
  1282. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  1283. skipping storing functions that are not
  1284. part of Org core.
  1285. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  1286. prefix ARG forces storing a link for each line in the
  1287. active region.
  1288. Assume the function is called interactively if INTERACTIVE? is
  1289. non-nil."
  1290. (interactive "P\np")
  1291. (org-load-modules-maybe)
  1292. (if (and (equal arg '(64)) (org-region-active-p))
  1293. (save-excursion
  1294. (let ((end (region-end)))
  1295. (goto-char (region-beginning))
  1296. (set-mark (point))
  1297. (while (< (point-at-eol) end)
  1298. (move-end-of-line 1) (activate-mark)
  1299. (let (current-prefix-arg)
  1300. (call-interactively 'org-store-link))
  1301. (move-beginning-of-line 2)
  1302. (set-mark (point)))))
  1303. (setq org-store-link-plist nil)
  1304. (let (link cpltxt desc description search custom-id agenda-link)
  1305. (cond
  1306. ;; Store a link using an external link type, if any function is
  1307. ;; available. If more than one can generate a link from current
  1308. ;; location, ask which one to use.
  1309. ((and (not (equal arg '(16)))
  1310. (let ((results-alist nil))
  1311. (dolist (f (org-store-link-functions))
  1312. (when (funcall f)
  1313. ;; XXX: return value is not link's plist, so we
  1314. ;; store the new value before it is modified. It
  1315. ;; would be cleaner to ask store link functions to
  1316. ;; return the plist instead.
  1317. (push (cons f (copy-sequence org-store-link-plist))
  1318. results-alist)))
  1319. (pcase results-alist
  1320. (`nil nil)
  1321. (`((,_ . ,_)) t) ;single choice: nothing to do
  1322. (`((,name . ,_) . ,_)
  1323. ;; Reinstate link plist associated to the chosen
  1324. ;; function.
  1325. (apply #'org-link-store-props
  1326. (cdr (assoc-string
  1327. (completing-read
  1328. "Which function for creating the link? "
  1329. (mapcar #'car results-alist)
  1330. nil t (symbol-name name))
  1331. results-alist)))
  1332. t))))
  1333. (setq link (plist-get org-store-link-plist :link))
  1334. (setq desc (or (plist-get org-store-link-plist :description)
  1335. link)))
  1336. ;; Store a link from a remote editing buffer.
  1337. ((org-src-edit-buffer-p)
  1338. (let ((coderef-format (org-src-coderef-format))
  1339. (format-link
  1340. (lambda (label)
  1341. (if org-src-source-file-name
  1342. (format "file:%s::(%s)" org-src-source-file-name label)
  1343. (format "(%s)" label)))))
  1344. (cond
  1345. ;; Code references do not exist in this type of buffer.
  1346. ;; Pretend we're linking from the source buffer directly.
  1347. ((not (memq (org-src-source-type) '(example-block src-block)))
  1348. (with-current-buffer (org-src-source-buffer)
  1349. (org-store-link arg interactive?))
  1350. (setq link nil))
  1351. ;; A code reference exists. Use it.
  1352. ((save-excursion
  1353. (beginning-of-line)
  1354. (re-search-forward (org-src-coderef-regexp coderef-format)
  1355. (line-end-position)
  1356. t))
  1357. (setq link (funcall format-link (match-string-no-properties 3))))
  1358. ;; No code reference. Create a new one then store the link
  1359. ;; to it, but only in the function is called interactively.
  1360. (interactive?
  1361. (end-of-line)
  1362. (let* ((label (read-string "Code line label: "))
  1363. (reference (format coderef-format label))
  1364. (gc (- 79 (length reference))))
  1365. (if (< (current-column) gc)
  1366. (org-move-to-column gc t)
  1367. (insert " "))
  1368. (insert reference)
  1369. (setq link (funcall format-link label))))
  1370. ;; No code reference, and non-interactive call. Don't know
  1371. ;; what to do. Give up.
  1372. (t (setq link nil)))))
  1373. ;; We are in the agenda, link to referenced location
  1374. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  1375. (let ((m (or (get-text-property (point) 'org-hd-marker)
  1376. (get-text-property (point) 'org-marker))))
  1377. (when m
  1378. (org-with-point-at m
  1379. (setq agenda-link (org-store-link nil interactive?))))))
  1380. ((eq major-mode 'calendar-mode)
  1381. (let ((cd (calendar-cursor-to-date)))
  1382. (setq link
  1383. (format-time-string
  1384. (car org-time-stamp-formats)
  1385. (apply 'encode-time
  1386. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  1387. nil nil nil))))
  1388. (org-link-store-props :type "calendar" :date cd)))
  1389. ((eq major-mode 'help-mode)
  1390. (let ((symbol (replace-regexp-in-string
  1391. ;; Help mode escapes backquotes and backslashes
  1392. ;; before displaying them. E.g., "`" appears
  1393. ;; as "\'" for reasons. Work around this.
  1394. (rx "\\" (group (or "`" "\\"))) "\\1"
  1395. (save-excursion
  1396. (goto-char (point-min))
  1397. (looking-at "^[^ ]+")
  1398. (match-string 0)))))
  1399. (setq link (concat "help:" symbol)))
  1400. (org-link-store-props :type "help"))
  1401. ((eq major-mode 'w3-mode)
  1402. (setq cpltxt (if (and (buffer-name)
  1403. (not (string-match "Untitled" (buffer-name))))
  1404. (buffer-name)
  1405. (url-view-url t))
  1406. link (url-view-url t))
  1407. (org-link-store-props :type "w3" :url (url-view-url t)))
  1408. ((eq major-mode 'image-mode)
  1409. (setq cpltxt (concat "file:"
  1410. (abbreviate-file-name buffer-file-name))
  1411. link cpltxt)
  1412. (org-link-store-props :type "image" :file buffer-file-name))
  1413. ;; In dired, store a link to the file of the current line
  1414. ((derived-mode-p 'dired-mode)
  1415. (let ((file (dired-get-filename nil t)))
  1416. (setq file (if file
  1417. (abbreviate-file-name
  1418. (expand-file-name (dired-get-filename nil t)))
  1419. ;; otherwise, no file so use current directory.
  1420. default-directory))
  1421. (setq cpltxt (concat "file:" file)
  1422. link cpltxt)))
  1423. ((setq search (run-hook-with-args-until-success
  1424. 'org-create-file-search-functions))
  1425. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  1426. "::" search))
  1427. (setq cpltxt (or description link)))
  1428. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  1429. (org-with-limited-levels
  1430. (cond
  1431. ;; Store a link using the target at point.
  1432. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  1433. (setq cpltxt
  1434. (concat "file:"
  1435. (abbreviate-file-name
  1436. (buffer-file-name (buffer-base-buffer)))
  1437. "::" (match-string 1))
  1438. link cpltxt))
  1439. ;; Store a link using the CUSTOM_ID property.
  1440. ((setq custom-id (org-entry-get nil "CUSTOM_ID"))
  1441. (setq cpltxt
  1442. (concat "file:"
  1443. (abbreviate-file-name
  1444. (buffer-file-name (buffer-base-buffer)))
  1445. "::#" custom-id)
  1446. link cpltxt))
  1447. ;; Store a link using (and perhaps creating) the ID property.
  1448. ((and (featurep 'org-id)
  1449. (or (eq org-id-link-to-org-use-id t)
  1450. (and interactive?
  1451. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  1452. (and (eq org-id-link-to-org-use-id
  1453. 'create-if-interactive-and-no-custom-id)
  1454. (not custom-id))))
  1455. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  1456. (setq link (condition-case nil
  1457. (prog1 (org-id-store-link)
  1458. (setq desc (or (plist-get org-store-link-plist
  1459. :description)
  1460. "")))
  1461. (error
  1462. ;; Probably before first headline, link only to file.
  1463. (concat "file:"
  1464. (abbreviate-file-name
  1465. (buffer-file-name (buffer-base-buffer))))))))
  1466. (t
  1467. ;; Just link to current headline.
  1468. (setq cpltxt (concat "file:"
  1469. (abbreviate-file-name
  1470. (buffer-file-name (buffer-base-buffer)))))
  1471. ;; Add a context search string.
  1472. (when (org-xor org-link-context-for-files (equal arg '(4)))
  1473. (let* ((element (org-element-at-point))
  1474. (name (org-element-property :name element))
  1475. (context
  1476. (cond
  1477. ((let ((region (org-link--context-from-region)))
  1478. (and region (org-link--normalize-string region t))))
  1479. (name)
  1480. ((org-before-first-heading-p)
  1481. (org-link--normalize-string (org-current-line-string) t))
  1482. (t (org-link-heading-search-string)))))
  1483. (when (org-string-nw-p context)
  1484. (setq cpltxt (format "%s::%s" cpltxt context))
  1485. (setq desc
  1486. (or name
  1487. ;; Although description is not a search
  1488. ;; string, use `org-link--normalize-string'
  1489. ;; to prettify it (contiguous white spaces)
  1490. ;; and remove volatile contents (statistics
  1491. ;; cookies).
  1492. (and (not (org-before-first-heading-p))
  1493. (org-link--normalize-string
  1494. (org-get-heading t t t t)))
  1495. "NONE")))))
  1496. (setq link cpltxt)))))
  1497. ((buffer-file-name (buffer-base-buffer))
  1498. ;; Just link to this file here.
  1499. (setq cpltxt (concat "file:"
  1500. (abbreviate-file-name
  1501. (buffer-file-name (buffer-base-buffer)))))
  1502. ;; Add a context search string.
  1503. (when (org-xor org-link-context-for-files (equal arg '(4)))
  1504. (let ((context (org-link--normalize-string
  1505. (or (org-link--context-from-region)
  1506. (org-current-line-string))
  1507. t)))
  1508. ;; Only use search option if there is some text.
  1509. (when (org-string-nw-p context)
  1510. (setq cpltxt (format "%s::%s" cpltxt context))
  1511. (setq desc "NONE"))))
  1512. (setq link cpltxt))
  1513. (interactive?
  1514. (user-error "No method for storing a link from this buffer"))
  1515. (t (setq link nil)))
  1516. ;; We're done setting link and desc, clean up
  1517. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  1518. (setq link (or link cpltxt)
  1519. desc (or desc cpltxt))
  1520. (cond ((not desc))
  1521. ((equal desc "NONE") (setq desc nil))
  1522. (t (setq desc (org-link-display-format desc))))
  1523. ;; Store and return the link
  1524. (if (not (and interactive? link))
  1525. (or agenda-link (and link (org-link-make-string link desc)))
  1526. (if (member (list link desc) org-stored-links)
  1527. (message "This link already exists")
  1528. (push (list link desc) org-stored-links)
  1529. (message "Stored: %s" (or desc link))
  1530. (when custom-id
  1531. (setq link (concat "file:"
  1532. (abbreviate-file-name
  1533. (buffer-file-name (buffer-base-buffer)))
  1534. "::#" custom-id))
  1535. (push (list link desc) org-stored-links)))
  1536. (car org-stored-links)))))
  1537. ;;;###autoload
  1538. (defun org-insert-link (&optional complete-file link-location description)
  1539. "Insert a link. At the prompt, enter the link.
  1540. Completion can be used to insert any of the link protocol prefixes in use.
  1541. The history can be used to select a link previously stored with
  1542. `org-store-link'. When the empty string is entered (i.e. if you just
  1543. press `RET' at the prompt), the link defaults to the most recently
  1544. stored link. As `SPC' triggers completion in the minibuffer, you need to
  1545. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  1546. You will also be prompted for a description, and if one is given, it will
  1547. be displayed in the buffer instead of the link.
  1548. If there is already a link at point, this command will allow you to edit
  1549. link and description parts.
  1550. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  1551. file name can be
  1552. selected using completion. The path to the file will be relative to the
  1553. current directory if the file is in the current directory or a subdirectory.
  1554. Otherwise, the link will be the absolute path as completed in the minibuffer
  1555. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  1556. option `org-link-file-path-type'.
  1557. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  1558. absolute path even if the file is in
  1559. the current directory or below.
  1560. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  1561. prefix negates `org-link-keep-stored-after-insertion'.
  1562. If the LINK-LOCATION parameter is non-nil, this value will be used as
  1563. the link location instead of reading one interactively.
  1564. If the DESCRIPTION parameter is non-nil, this value will be used as the
  1565. default description. Otherwise, if `org-link-make-description-function'
  1566. is non-nil, this function will be called with the link target, and the
  1567. result will be the default link description. When called non-interactively,
  1568. don't allow to edit the default description."
  1569. (interactive "P")
  1570. (let* ((wcf (current-window-configuration))
  1571. (origbuf (current-buffer))
  1572. (region (when (org-region-active-p)
  1573. (buffer-substring (region-beginning) (region-end))))
  1574. (remove (and region (list (region-beginning) (region-end))))
  1575. (desc region)
  1576. (link link-location)
  1577. (abbrevs org-link-abbrev-alist-local)
  1578. entry all-prefixes auto-desc)
  1579. (cond
  1580. (link-location) ; specified by arg, just use it.
  1581. ((org-in-regexp org-link-bracket-re 1)
  1582. ;; We do have a link at point, and we are going to edit it.
  1583. (setq remove (list (match-beginning 0) (match-end 0)))
  1584. (setq desc (when (match-end 2) (match-string-no-properties 2)))
  1585. (setq link (read-string "Link: "
  1586. (org-link-unescape
  1587. (match-string-no-properties 1)))))
  1588. ((or (org-in-regexp org-link-angle-re)
  1589. (org-in-regexp org-link-plain-re))
  1590. ;; Convert to bracket link
  1591. (setq remove (list (match-beginning 0) (match-end 0))
  1592. link (read-string "Link: "
  1593. (org-unbracket-string "<" ">" (match-string 0)))))
  1594. ((member complete-file '((4) (16)))
  1595. ;; Completing read for file names.
  1596. (setq link (org-link-complete-file complete-file)))
  1597. (t
  1598. ;; Read link, with completion for stored links.
  1599. (org-link--fontify-links-to-this-file)
  1600. (org-switch-to-buffer-other-window "*Org Links*")
  1601. (with-current-buffer "*Org Links*"
  1602. (erase-buffer)
  1603. (insert "Insert a link.
  1604. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  1605. (when org-stored-links
  1606. (insert "\nStored links are available with <up>/<down> or M-p/n \
  1607. \(most recent with RET):\n\n")
  1608. (insert (mapconcat #'org-link--prettify
  1609. (reverse org-stored-links)
  1610. "\n")))
  1611. (goto-char (point-min)))
  1612. (let ((cw (selected-window)))
  1613. (select-window (get-buffer-window "*Org Links*" 'visible))
  1614. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  1615. (unless (pos-visible-in-window-p (point-max))
  1616. (org-fit-window-to-buffer))
  1617. (and (window-live-p cw) (select-window cw)))
  1618. (setq all-prefixes (append (mapcar #'car abbrevs)
  1619. (mapcar #'car org-link-abbrev-alist)
  1620. (org-link-types)))
  1621. (unwind-protect
  1622. ;; Fake a link history, containing the stored links.
  1623. (let ((org-link--history
  1624. (append (mapcar #'car org-stored-links)
  1625. org-link--insert-history)))
  1626. (setq link
  1627. (org-completing-read
  1628. "Link: "
  1629. (append
  1630. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  1631. (mapcar #'car org-stored-links))
  1632. nil nil nil
  1633. 'org-link--history
  1634. (caar org-stored-links)))
  1635. (unless (org-string-nw-p link) (user-error "No link selected"))
  1636. (dolist (l org-stored-links)
  1637. (when (equal link (cadr l))
  1638. (setq link (car l))
  1639. (setq auto-desc t)))
  1640. (when (or (member link all-prefixes)
  1641. (and (equal ":" (substring link -1))
  1642. (member (substring link 0 -1) all-prefixes)
  1643. (setq link (substring link 0 -1))))
  1644. (setq link (with-current-buffer origbuf
  1645. (org-link--try-special-completion link)))))
  1646. (set-window-configuration wcf)
  1647. (kill-buffer "*Org Links*"))
  1648. (setq entry (assoc link org-stored-links))
  1649. (or entry (push link org-link--insert-history))
  1650. (setq desc (or desc (nth 1 entry)))))
  1651. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  1652. (not org-link-keep-stored-after-insertion))
  1653. (setq org-stored-links (delq (assoc link org-stored-links)
  1654. org-stored-links)))
  1655. (when (and (string-match org-link-plain-re link)
  1656. (not (string-match org-ts-regexp link)))
  1657. ;; URL-like link, normalize the use of angular brackets.
  1658. (setq link (org-unbracket-string "<" ">" link)))
  1659. ;; Check if we are linking to the current file with a search
  1660. ;; option If yes, simplify the link by using only the search
  1661. ;; option.
  1662. (when (and (buffer-file-name (buffer-base-buffer))
  1663. (let ((case-fold-search nil))
  1664. (string-match "\\`file:\\(.+?\\)::" link)))
  1665. (let ((path (match-string-no-properties 1 link))
  1666. (search (substring-no-properties link (match-end 0))))
  1667. (save-match-data
  1668. (when (equal (file-truename (buffer-file-name (buffer-base-buffer)))
  1669. (file-truename path))
  1670. ;; We are linking to this same file, with a search option
  1671. (setq link search)))))
  1672. ;; Check if we can/should use a relative path. If yes, simplify
  1673. ;; the link.
  1674. (let ((case-fold-search nil))
  1675. (when (string-match "\\`\\(file\\|docview\\):" link)
  1676. (let* ((type (match-string-no-properties 0 link))
  1677. (path-start (match-end 0))
  1678. (search (and (string-match "::\\(.*\\)\\'" link)
  1679. (match-string 1 link)))
  1680. (path
  1681. (if search
  1682. (substring-no-properties
  1683. link path-start (match-beginning 0))
  1684. (substring-no-properties link (match-end 0))))
  1685. (origpath path))
  1686. (cond
  1687. ((or (eq org-link-file-path-type 'absolute)
  1688. (equal complete-file '(16)))
  1689. (setq path (abbreviate-file-name (expand-file-name path))))
  1690. ((eq org-link-file-path-type 'noabbrev)
  1691. (setq path (expand-file-name path)))
  1692. ((eq org-link-file-path-type 'relative)
  1693. (setq path (file-relative-name path)))
  1694. (t
  1695. (save-match-data
  1696. (if (string-match (concat "^" (regexp-quote
  1697. (expand-file-name
  1698. (file-name-as-directory
  1699. default-directory))))
  1700. (expand-file-name path))
  1701. ;; We are linking a file with relative path name.
  1702. (setq path (substring (expand-file-name path)
  1703. (match-end 0)))
  1704. (setq path (abbreviate-file-name (expand-file-name path)))))))
  1705. (setq link (concat type path (and search (concat "::" search))))
  1706. (when (equal desc origpath)
  1707. (setq desc path)))))
  1708. (unless auto-desc
  1709. (let ((initial-input
  1710. (cond
  1711. (description)
  1712. ((not org-link-make-description-function) desc)
  1713. (t (condition-case nil
  1714. (funcall org-link-make-description-function link desc)
  1715. (error
  1716. (message "Can't get link description from %S"
  1717. (symbol-name org-link-make-description-function))
  1718. (sit-for 2)
  1719. nil))))))
  1720. (setq desc (if (called-interactively-p 'any)
  1721. (read-string "Description: " initial-input)
  1722. initial-input))))
  1723. (unless (org-string-nw-p desc) (setq desc nil))
  1724. (when remove (apply #'delete-region remove))
  1725. (insert (org-link-make-string link desc))
  1726. ;; Redisplay so as the new link has proper invisible characters.
  1727. (sit-for 0)))
  1728. ;;;###autoload
  1729. (defun org-insert-all-links (arg &optional pre post)
  1730. "Insert all links in `org-stored-links'.
  1731. When a universal prefix, do not delete the links from `org-stored-links'.
  1732. When `ARG' is a number, insert the last N link(s).
  1733. `PRE' and `POST' are optional arguments to define a string to
  1734. prepend or to append."
  1735. (interactive "P")
  1736. (let ((org-link-keep-stored-after-insertion (equal arg '(4)))
  1737. (links (copy-sequence org-stored-links))
  1738. (pr (or pre "- "))
  1739. (po (or post "\n"))
  1740. (cnt 1) l)
  1741. (if (null org-stored-links)
  1742. (message "No link to insert")
  1743. (while (and (or (listp arg) (>= arg cnt))
  1744. (setq l (if (listp arg)
  1745. (pop links)
  1746. (pop org-stored-links))))
  1747. (setq cnt (1+ cnt))
  1748. (insert pr)
  1749. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  1750. (insert po)))))
  1751. ;;;###autoload
  1752. (defun org-insert-last-stored-link (arg)
  1753. "Insert the last link stored in `org-stored-links'."
  1754. (interactive "p")
  1755. (org-insert-all-links arg "" "\n"))
  1756. ;;;###autoload
  1757. (defun org-insert-link-global ()
  1758. "Insert a link like Org mode does.
  1759. This command can be called in any mode to insert a link in Org syntax."
  1760. (interactive)
  1761. (org-load-modules-maybe)
  1762. (org-run-like-in-org-mode 'org-insert-link))
  1763. ;;;###autoload
  1764. (defun org-update-radio-target-regexp ()
  1765. "Find all radio targets in this file and update the regular expression.
  1766. Also refresh fontification if needed."
  1767. (interactive)
  1768. (let ((old-regexp org-target-link-regexp)
  1769. ;; Some languages, e.g., Chinese, do not use spaces to
  1770. ;; separate words. Also allow to surround radio targets with
  1771. ;; line-breakable characters.
  1772. (before-re "\\(?:^\\|[^[:alnum:]]\\|\\c|\\)\\(")
  1773. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\|\\c|\\)")
  1774. (targets
  1775. (org-with-wide-buffer
  1776. (goto-char (point-min))
  1777. (let (rtn)
  1778. (while (re-search-forward org-radio-target-regexp nil t)
  1779. ;; Make sure point is really within the object.
  1780. (backward-char)
  1781. (let ((obj (org-element-context)))
  1782. (when (eq (org-element-type obj) 'radio-target)
  1783. (cl-pushnew (org-element-property :value obj) rtn
  1784. :test #'equal))))
  1785. rtn))))
  1786. (setq org-target-link-regexp
  1787. (and targets
  1788. (concat before-re
  1789. (mapconcat
  1790. (lambda (x)
  1791. (replace-regexp-in-string
  1792. " +" "\\s-+" (regexp-quote x) t t))
  1793. targets
  1794. "\\|")
  1795. after-re)))
  1796. (unless (equal old-regexp org-target-link-regexp)
  1797. ;; Clean-up cache.
  1798. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  1799. ((not org-target-link-regexp) old-regexp)
  1800. (t
  1801. (concat before-re
  1802. (mapconcat
  1803. (lambda (re)
  1804. (substring re (length before-re)
  1805. (- (length after-re))))
  1806. (list old-regexp org-target-link-regexp)
  1807. "\\|")
  1808. after-re)))))
  1809. (when (featurep 'org-element)
  1810. (org-with-point-at 1
  1811. (while (re-search-forward regexp nil t)
  1812. (org-element-cache-refresh (match-beginning 1))))))
  1813. ;; Re fontify buffer.
  1814. (when (memq 'radio org-highlight-links)
  1815. (org-restart-font-lock)))))
  1816. ;;; Initialize Regexps
  1817. (org-link-make-regexps)
  1818. (provide 'ol)
  1819. ;; Local variables:
  1820. ;; generated-autoload-file: "org-loaddefs.el"
  1821. ;; End:
  1822. ;;; ol.el ends here