ol.el 69 KB

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