ol.el 70 KB

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