ol.el 72 KB

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