ol.el 71 KB

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