ol.el 73 KB

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