ol.el 73 KB

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