ol.el 75 KB

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