ol.el 73 KB

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