ol.el 69 KB

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