ol.el 72 KB

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