ol.el 72 KB

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