ol.el 72 KB

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