ol.el 70 KB

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