ol.el 72 KB

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