ol.el 77 KB

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