org-protocol.el 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. ;;; org-protocol.el --- Intercept Calls from Emacsclient to Trigger Custom Actions -*- lexical-binding: t; -*-
  2. ;;
  3. ;; Copyright (C) 2008-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Authors: Bastien Guerry <bzg@gnu.org>
  6. ;; Daniel M German <dmg AT uvic DOT org>
  7. ;; Sebastian Rose <sebastian_rose AT gmx DOT de>
  8. ;; Ross Patterson <me AT rpatterson DOT net>
  9. ;; Maintainer: Sebastian Rose <sebastian_rose AT gmx DOT de>
  10. ;; Keywords: org, emacsclient, wp
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Intercept calls from emacsclient to trigger custom actions.
  27. ;;
  28. ;; This is done by advising `server-visit-files' to scan the list of filenames
  29. ;; for `org-protocol-the-protocol' and sub-protocols defined in
  30. ;; `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'.
  31. ;;
  32. ;; Any application that supports calling external programs with an URL
  33. ;; as argument may be used with this functionality.
  34. ;;
  35. ;;
  36. ;; Usage:
  37. ;; ------
  38. ;;
  39. ;; 1.) Add this to your init file (.emacs probably):
  40. ;;
  41. ;; (add-to-list 'load-path "/path/to/org-protocol/")
  42. ;; (require 'org-protocol)
  43. ;;
  44. ;; 3.) Ensure emacs-server is up and running.
  45. ;; 4.) Try this from the command line (adjust the URL as needed):
  46. ;;
  47. ;; $ emacsclient \
  48. ;; "org-protocol://store-link?url=http:%2F%2Flocalhost%2Findex.html&title=The%20title"
  49. ;;
  50. ;; 5.) Optionally add custom sub-protocols and handlers:
  51. ;;
  52. ;; (setq org-protocol-protocol-alist
  53. ;; '(("my-protocol"
  54. ;; :protocol "my-protocol"
  55. ;; :function my-protocol-handler-function)))
  56. ;;
  57. ;; A "sub-protocol" will be found in URLs like this:
  58. ;;
  59. ;; org-protocol://sub-protocol?key=val&key2=val2
  60. ;;
  61. ;; If it works, you can now setup other applications for using this feature.
  62. ;;
  63. ;;
  64. ;; As of March 2009 Firefox users follow the steps documented on
  65. ;; http://kb.mozillazine.org/Register_protocol, Opera setup is described here:
  66. ;; http://www.opera.com/support/kb/view/535/
  67. ;;
  68. ;;
  69. ;; Documentation
  70. ;; -------------
  71. ;;
  72. ;; org-protocol.el comes with and installs handlers to open sources of published
  73. ;; online content, store and insert the browser's URLs and cite online content
  74. ;; by clicking on a bookmark in Firefox, Opera and probably other browsers and
  75. ;; applications:
  76. ;;
  77. ;; * `org-protocol-open-source' uses the sub-protocol \"open-source\" and maps
  78. ;; URLs to local filenames defined in `org-protocol-project-alist'.
  79. ;;
  80. ;; * `org-protocol-store-link' stores an Org link (if Org is present) and
  81. ;; pushes the browsers URL to the `kill-ring' for yanking. This handler is
  82. ;; triggered through the sub-protocol \"store-link\".
  83. ;;
  84. ;; * Call `org-protocol-capture' by using the sub-protocol \"capture\". If
  85. ;; Org is loaded, Emacs will pop-up a capture buffer and fill the
  86. ;; template with the data provided. I.e. the browser's URL is inserted as an
  87. ;; Org-link of which the page title will be the description part. If text
  88. ;; was select in the browser, that text will be the body of the entry.
  89. ;;
  90. ;; You may use the same bookmark URL for all those standard handlers and just
  91. ;; adjust the sub-protocol used:
  92. ;;
  93. ;; javascript:location.href='org-protocol://sub-protocol?'+
  94. ;; new URLSearchParams({
  95. ;; url: location.href,
  96. ;; title: document.title,
  97. ;; body: window.getSelection()})
  98. ;;
  99. ;; Alternatively use the following expression that encodes space as \"%20\"
  100. ;; instead of \"+\", so it is compatible with Org versions from 9.0 to 9.4:
  101. ;;
  102. ;; location.href='org-protocol://sub-protocol?url='+
  103. ;; encodeURIComponent(location.href)+'&title='+
  104. ;; encodeURIComponent(document.title)+'&body='+
  105. ;; encodeURIComponent(window.getSelection())
  106. ;;
  107. ;; The handler for the sub-protocol \"capture\" detects an optional template
  108. ;; char that, if present, triggers the use of a special template.
  109. ;; Example:
  110. ;;
  111. ;; location.href='org-protocol://capture?'+
  112. ;; new URLSearchParams({template:'x', /* ... */})
  113. ;;
  114. ;; or
  115. ;;
  116. ;; location.href='org-protocol://capture?template=x'+ ...
  117. ;;
  118. ;; uses template ?x.
  119. ;;
  120. ;; Note that using double slashes is optional from org-protocol.el's point of
  121. ;; view because emacsclient squashes the slashes to one.
  122. ;;
  123. ;;
  124. ;; provides: 'org-protocol
  125. ;;
  126. ;;; Code:
  127. (require 'org)
  128. (require 'ol)
  129. (declare-function org-publish-get-project-from-filename "ox-publish"
  130. (filename &optional up))
  131. (declare-function server-edit "server" (&optional arg))
  132. (defvar org-capture-link-is-already-stored)
  133. (defvar org-capture-templates)
  134. (defgroup org-protocol nil
  135. "Intercept calls from emacsclient to trigger custom actions.
  136. This is done by advising `server-visit-files' to scan the list of filenames
  137. for `org-protocol-the-protocol' and sub-protocols defined in
  138. `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'."
  139. :version "22.1"
  140. :group 'convenience
  141. :group 'org)
  142. ;;; Variables:
  143. (defconst org-protocol-protocol-alist-default
  144. '(("org-capture" :protocol "capture" :function org-protocol-capture :kill-client t)
  145. ("org-store-link" :protocol "store-link" :function org-protocol-store-link)
  146. ("org-open-source" :protocol "open-source" :function org-protocol-open-source))
  147. "Default protocols to use.
  148. See `org-protocol-protocol-alist' for a description of this variable.")
  149. (defconst org-protocol-the-protocol "org-protocol"
  150. "This is the protocol to detect if org-protocol.el is loaded.
  151. `org-protocol-protocol-alist-default' and `org-protocol-protocol-alist' hold
  152. the sub-protocols that trigger the required action. You will have to define
  153. just one protocol handler OS-wide (MS-Windows) or per application (Linux).
  154. That protocol handler should call emacsclient.")
  155. ;;; User variables:
  156. (defcustom org-protocol-reverse-list-of-files t
  157. "Non-nil means re-reverse the list of filenames passed on the command line.
  158. The filenames passed on the command line are passed to the emacs-server in
  159. reverse order. Set to t (default) to re-reverse the list, i.e. use the
  160. sequence on the command line. If nil, the sequence of the filenames is
  161. unchanged."
  162. :type 'boolean)
  163. (defcustom org-protocol-project-alist nil
  164. "Map URLs to local filenames for `org-protocol-open-source' (open-source).
  165. Each element of this list must be of the form:
  166. (module-name :property value property: value ...)
  167. where module-name is an arbitrary name. All the values are strings.
  168. Possible properties are:
  169. :online-suffix - the suffix to strip from the published URLs
  170. :working-suffix - the replacement for online-suffix
  171. :base-url - the base URL, e.g. https://www.example.com/project/
  172. Last slash required.
  173. :working-directory - the local working directory. This is what
  174. base-url will be replaced with.
  175. :redirects - A list of cons cells, each of which maps a
  176. regular expression to match to a path relative
  177. to `:working-directory'.
  178. Example:
  179. (setq org-protocol-project-alist
  180. \\='((\"https://orgmode.org/worg/\"
  181. :online-suffix \".php\"
  182. :working-suffix \".org\"
  183. :base-url \"https://orgmode.org/worg/\"
  184. :working-directory \"/home/user/org/Worg/\")
  185. (\"localhost org-notes/\"
  186. :online-suffix \".html\"
  187. :working-suffix \".org\"
  188. :base-url \"http://localhost/org/\"
  189. :working-directory \"/home/user/org/\"
  190. :rewrites ((\"org/?$\" . \"index.php\")))
  191. (\"Hugo based blog\"
  192. :base-url \"https://www.site.com/\"
  193. :working-directory \"~/site/content/post/\"
  194. :online-suffix \".html\"
  195. :working-suffix \".md\"
  196. :rewrites ((\"\\(https://site.com/[0-9]+/[0-9]+/[0-9]+/\\)\"
  197. . \".md\")))
  198. (\"GNU emacs OpenGrok\"
  199. :base-url \"https://opengrok.housegordon.com/source/xref/emacs/\"
  200. :working-directory \"~/dev/gnu-emacs/\")))
  201. The :rewrites line of \"localhost org-notes\" entry tells
  202. `org-protocol-open-source' to open /home/user/org/index.php,
  203. if the URL cannot be mapped to an existing file, and ends with
  204. either \"org\" or \"org/\". The \"GNU emacs OpenGrok\" entry
  205. does not include any suffix properties, allowing local source
  206. file to be opened as found by OpenGrok.
  207. Consider using the interactive functions `org-protocol-create'
  208. and `org-protocol-create-for-org' to help you filling this
  209. variable with valid contents."
  210. :type 'alist)
  211. (defcustom org-protocol-protocol-alist nil
  212. "Register custom handlers for org-protocol.
  213. Each element of this list must be of the form:
  214. (module-name :protocol protocol :function func :kill-client nil)
  215. protocol - protocol to detect in a filename without trailing
  216. colon and slashes. See rfc1738 section 2.1 for more
  217. on this. If you define a protocol \"my-protocol\",
  218. `org-protocol-check-filename-for-protocol' will search
  219. filenames for \"org-protocol:/my-protocol\" and
  220. trigger your action for every match. `org-protocol'
  221. is defined in `org-protocol-the-protocol'. Double and
  222. triple slashes are compressed to one by emacsclient.
  223. function - function that handles requests with protocol and takes
  224. one argument. If a new-style link (key=val&key2=val2)
  225. is given, the argument will be a property list with
  226. the values from the link. If an old-style link is
  227. given (val1/val2), the argument will be the filename
  228. with all protocols stripped.
  229. If the function returns nil, emacsclient and -server
  230. do nothing. Any non-nil return value is considered a
  231. valid filename and thus passed to the server.
  232. `org-protocol.el' provides some support for handling
  233. old-style filenames, if you follow the conventions
  234. used for the standard handlers in
  235. `org-protocol-protocol-alist-default'. See
  236. `org-protocol-parse-parameters'.
  237. kill-client - If t, kill the client immediately, once the sub-protocol is
  238. detected. This is necessary for actions that can be interrupted by
  239. `C-g' to avoid dangling emacsclients. Note that all other command
  240. line arguments but the this one will be discarded. Greedy handlers
  241. still receive the whole list of arguments though.
  242. Here is an example:
  243. (setq org-protocol-protocol-alist
  244. \\='((\"my-protocol\"
  245. :protocol \"my-protocol\"
  246. :function my-protocol-handler-function)
  247. (\"your-protocol\"
  248. :protocol \"your-protocol\"
  249. :function your-protocol-handler-function)))"
  250. :type '(alist))
  251. (defcustom org-protocol-default-template-key nil
  252. "The default template key to use.
  253. This is usually a single character string but can also be a
  254. string with two characters."
  255. :type '(choice (const nil) (string)))
  256. (defcustom org-protocol-data-separator "/+\\|\\?"
  257. "The default data separator to use.
  258. This should be a single regexp string."
  259. :version "24.4"
  260. :package-version '(Org . "8.0")
  261. :type 'regexp)
  262. ;;; Helper functions:
  263. (defun org-protocol-sanitize-uri (uri)
  264. "Sanitize slashes to double-slashes in URI.
  265. Emacsclient compresses double and triple slashes."
  266. (when (string-match "^\\([a-z]+\\):/" uri)
  267. (let* ((splitparts (split-string uri "/+")))
  268. (setq uri (concat (car splitparts) "//"
  269. (mapconcat #'identity (cdr splitparts) "/")))))
  270. uri)
  271. (defun org-protocol-split-data (data &optional unhexify separator)
  272. "Split the DATA argument for an org-protocol handler function.
  273. If UNHEXIFY is non-nil, hex-decode each split part. If UNHEXIFY
  274. is a function, use that function to decode each split part. The
  275. string is split at each occurrence of SEPARATOR (regexp). If no
  276. SEPARATOR is specified or SEPARATOR is nil, assume \"/+\". The
  277. results of that splitting are returned as a list."
  278. (let* ((sep (or separator "/+\\|\\?"))
  279. (split-parts (split-string data sep)))
  280. (cond ((not unhexify) split-parts)
  281. ((fboundp unhexify) (mapcar unhexify split-parts))
  282. (t (mapcar #'org-link-decode split-parts)))))
  283. (defun org-protocol-flatten-greedy (param-list &optional strip-path replacement)
  284. "Transform PARAM-LIST into a flat list for greedy handlers.
  285. Greedy handlers might receive a list like this from emacsclient:
  286. \((\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\"))
  287. where \"/dir/\" is the absolute path to emacsclient's working directory. This
  288. function transforms it into a flat list using `org-protocol-flatten' and
  289. transforms the elements of that list as follows:
  290. If STRIP-PATH is non-nil, remove the \"/dir/\" prefix from all members of
  291. param-list.
  292. If REPLACEMENT is string, replace the \"/dir/\" prefix with it.
  293. The first parameter, the one that contains the protocols, is always changed.
  294. Everything up to the end of the protocols is stripped.
  295. Note, that this function will always behave as if
  296. `org-protocol-reverse-list-of-files' was set to t and the returned list will
  297. reflect that. emacsclient's first parameter will be the first one in the
  298. returned list."
  299. (let* ((l (org-protocol-flatten (if org-protocol-reverse-list-of-files
  300. param-list
  301. (reverse param-list))))
  302. (trigger (car l))
  303. (len 0)
  304. dir
  305. ret)
  306. (when (string-match "^\\(.*\\)\\(org-protocol:/+[a-zA-Z0-9][-_a-zA-Z0-9]*:/+\\)\\(.*\\)" trigger)
  307. (setq dir (match-string 1 trigger))
  308. (setq len (length dir))
  309. (setcar l (concat dir (match-string 3 trigger))))
  310. (if strip-path
  311. (progn
  312. (dolist (e l ret)
  313. (setq ret
  314. (append ret
  315. (list
  316. (if (stringp e)
  317. (if (stringp replacement)
  318. (setq e (concat replacement (substring e len)))
  319. (setq e (substring e len)))
  320. e)))))
  321. ret)
  322. l)))
  323. ;; `flatten-tree' was added in Emacs 27.1.
  324. (defalias 'org-protocol-flatten
  325. (if (fboundp 'flatten-tree) 'flatten-tree
  326. (lambda (list)
  327. "Transform LIST into a flat list.
  328. Greedy handlers might receive a list like this from emacsclient:
  329. \((\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\"))
  330. where \"/dir/\" is the absolute path to emacsclients working directory.
  331. This function transforms it into a flat list."
  332. (if list
  333. (if (consp list)
  334. (append (org-protocol-flatten (car list))
  335. (org-protocol-flatten (cdr list)))
  336. (list list))))))
  337. (defun org-protocol-parse-parameters (info &optional new-style default-order)
  338. "Return a property list of parameters from INFO.
  339. If NEW-STYLE is non-nil, treat INFO as a query string (ex:
  340. url=URL&title=TITLE). If old-style links are used (ex:
  341. org-protocol://store-link/url/title), assign them to attributes
  342. following DEFAULT-ORDER.
  343. If no DEFAULT-ORDER is specified, return the list of values.
  344. If INFO is already a property list, return it unchanged."
  345. (if (listp info)
  346. info
  347. (if new-style
  348. (let ((data (org-protocol-convert-query-to-plist info))
  349. result)
  350. (while data
  351. (setq result
  352. (append result
  353. (list (pop data) (org-link-decode (pop data))))))
  354. result)
  355. (let ((data (org-protocol-split-data info t org-protocol-data-separator)))
  356. (if default-order
  357. (org-protocol-assign-parameters data default-order)
  358. data)))))
  359. (defun org-protocol-assign-parameters (data default-order)
  360. "Return a property list of parameters from DATA.
  361. Key names are taken from DEFAULT-ORDER, which should be a list of
  362. symbols. If DEFAULT-ORDER is shorter than the number of values
  363. specified, the rest of the values are treated as :key value pairs."
  364. (let (result)
  365. (while default-order
  366. (setq result
  367. (append result
  368. (list (pop default-order)
  369. (pop data)))))
  370. (while data
  371. (setq result
  372. (append result
  373. (list (intern (concat ":" (pop data)))
  374. (pop data)))))
  375. result))
  376. ;;; Standard protocol handlers:
  377. (defun org-protocol-store-link (fname)
  378. "Process an org-protocol://store-link style url.
  379. Additionally store a browser URL as an org link. Also pushes the
  380. link's URL to the `kill-ring'.
  381. Parameters: url, title (optional), body (optional)
  382. Old-style links such as org-protocol://store-link://URL/TITLE are
  383. also recognized.
  384. The location for a browser's bookmark may look like this:
  385. javascript:location.href = \\='org-protocol://store-link?\\=' +
  386. new URLSearchParams({url:location.href, title:document.title});
  387. or to keep compatibility with Org versions from 9.0 to 9.4 it may be:
  388. javascript:location.href = \\
  389. \\='org-protocol://store-link?url=\\=' + \\
  390. encodeURIComponent(location.href) + \\='&title=\\=' + \\
  391. encodeURIComponent(document.title);
  392. Don't use `escape()'! Use `encodeURIComponent()' instead. The
  393. title of the page could contain slashes and the location
  394. definitely will. Org 9.4 and earlier could not decode \"+\"
  395. to space, that is why less readable latter expression may be necessary
  396. for backward compatibility.
  397. The sub-protocol used to reach this function is set in
  398. `org-protocol-protocol-alist'.
  399. FNAME should be a property list. If not, an old-style link of the
  400. form URL/TITLE can also be used."
  401. (let* ((splitparts (org-protocol-parse-parameters fname nil '(:url :title)))
  402. (uri (org-protocol-sanitize-uri (plist-get splitparts :url)))
  403. (title (plist-get splitparts :title)))
  404. (when (boundp 'org-stored-links)
  405. (push (list uri title) org-stored-links))
  406. (kill-new uri)
  407. (message "`%s' to insert new Org link, `%s' to insert %S"
  408. (substitute-command-keys "\\[org-insert-link]")
  409. (substitute-command-keys "\\[yank]")
  410. uri))
  411. nil)
  412. (defun org-protocol-capture (info)
  413. "Process an org-protocol://capture style url with INFO.
  414. The sub-protocol used to reach this function is set in
  415. `org-protocol-protocol-alist'.
  416. This function detects an URL, title and optional text, separated
  417. by `/'. The location for a browser's bookmark looks like this:
  418. javascript:location.href = \\='org-protocol://capture?\\=' +
  419. new URLSearchParams({
  420. url: location.href,
  421. title: document.title,
  422. body: window.getSelection()})
  423. or to keep compatibility with Org versions from 9.0 to 9.4:
  424. javascript:location.href = \\='org-protocol://capture?url=\\='+ \\
  425. encodeURIComponent(location.href) + \\='&title=\\=' + \\
  426. encodeURIComponent(document.title) + \\='&body=\\=' + \\
  427. encodeURIComponent(window.getSelection())
  428. By default, it uses the character `org-protocol-default-template-key',
  429. which should be associated with a template in `org-capture-templates'.
  430. You may specify the template with a template= query parameter, like this:
  431. javascript:location.href = \\='org-protocol://capture?template=b\\='+ ...
  432. Now template ?b will be used."
  433. (let* ((parts
  434. (pcase (org-protocol-parse-parameters info)
  435. ;; New style links are parsed as a plist.
  436. ((let `(,(pred keywordp) . ,_) info) info)
  437. ;; Old style links, with or without template key, are
  438. ;; parsed as a list of strings.
  439. (p
  440. (let ((k (if (= 1 (length (car p)))
  441. '(:template :url :title :body)
  442. '(:url :title :body))))
  443. (org-protocol-assign-parameters p k)))))
  444. (template (or (plist-get parts :template)
  445. org-protocol-default-template-key))
  446. (url (and (plist-get parts :url)
  447. (org-protocol-sanitize-uri (plist-get parts :url))))
  448. (type (and url
  449. (string-match "^\\([a-z]+\\):" url)
  450. (match-string 1 url)))
  451. (title (or (plist-get parts :title) ""))
  452. (region (or (plist-get parts :body) ""))
  453. (orglink
  454. (if (null url) title
  455. (org-link-make-string url (or (org-string-nw-p title) url))))
  456. ;; Avoid call to `org-store-link'.
  457. (org-capture-link-is-already-stored t))
  458. ;; Only store link if there's a URL to insert later on.
  459. (when url (push (list url title) org-stored-links))
  460. (org-link-store-props :type type
  461. :link url
  462. :description title
  463. :annotation orglink
  464. :initial region
  465. :query parts)
  466. (raise-frame)
  467. (org-capture nil template)
  468. (message "Item captured.")
  469. ;; Make sure we do not return a string, as `server-visit-files',
  470. ;; through `server-edit', would interpret it as a file name.
  471. nil))
  472. (defun org-protocol-convert-query-to-plist (query)
  473. "Convert QUERY key=value pairs in the URL to a property list."
  474. (when query
  475. (let ((plus-decoded (replace-regexp-in-string "\\+" " " query t t)))
  476. (cl-mapcan (lambda (x)
  477. (let ((c (split-string x "=")))
  478. (list (intern (concat ":" (car c))) (cadr c))))
  479. (split-string plus-decoded "&")))))
  480. (defun org-protocol-open-source (fname)
  481. "Process an org-protocol://open-source?url= style URL with FNAME.
  482. Change a filename by mapping URLs to local filenames as set
  483. in `org-protocol-project-alist'.
  484. The location for a browser's bookmark should look like this:
  485. javascript:location.href = \\='org-protocol://open-source?\\=' +
  486. new URLSearchParams({url: location.href})
  487. or if you prefer to keep compatibility with older Org versions (9.0 to 9.4),
  488. consider the following expression:
  489. javascript:location.href = \\='org-protocol://open-source?url=\\=' + \\
  490. encodeURIComponent(location.href)"
  491. ;; As we enter this function for a match on our protocol, the return value
  492. ;; defaults to nil.
  493. (let (;; (result nil)
  494. (f (org-protocol-sanitize-uri
  495. (plist-get (org-protocol-parse-parameters fname nil '(:url))
  496. :url))))
  497. (catch 'result
  498. (dolist (prolist org-protocol-project-alist)
  499. (let* ((base-url (plist-get (cdr prolist) :base-url))
  500. (wsearch (regexp-quote base-url)))
  501. (when (string-match wsearch f)
  502. (let* ((wdir (plist-get (cdr prolist) :working-directory))
  503. (strip-suffix (plist-get (cdr prolist) :online-suffix))
  504. (add-suffix (plist-get (cdr prolist) :working-suffix))
  505. ;; Strip "[?#].*$" if `f' is a redirect with another
  506. ;; ending than strip-suffix here:
  507. (f1 (substring f 0 (string-match "\\([\\?#].*\\)?$" f)))
  508. (start-pos (+ (string-match wsearch f1) (length base-url)))
  509. (end-pos (if strip-suffix
  510. (string-match (regexp-quote strip-suffix) f1)
  511. (length f1)))
  512. ;; We have to compare redirects without suffix below:
  513. (f2 (concat wdir (substring f1 start-pos end-pos)))
  514. (the-file (if add-suffix (concat f2 add-suffix) f2)))
  515. ;; Note: the-file may still contain `%C3' et al here because browsers
  516. ;; tend to encode `&auml;' in URLs to `%25C3' - `%25' being `%'.
  517. ;; So the results may vary.
  518. ;; -- start redirects --
  519. (unless (file-exists-p the-file)
  520. (message "File %s does not exist.\nTesting for rewritten URLs." the-file)
  521. (let ((rewrites (plist-get (cdr prolist) :rewrites)))
  522. (when rewrites
  523. (message "Rewrites found: %S" rewrites)
  524. (dolist (rewrite rewrites)
  525. ;; Try to match a rewritten URL and map it to
  526. ;; a real file. Compare redirects without
  527. ;; suffix.
  528. (when (string-match (car rewrite) f1)
  529. (let ((replacement
  530. (concat (directory-file-name
  531. (replace-match "" nil nil f1 1))
  532. (cdr rewrite))))
  533. (throw 'result (concat wdir replacement))))))))
  534. ;; -- end of redirects --
  535. (if (file-readable-p the-file)
  536. (throw 'result the-file))
  537. (if (file-exists-p the-file)
  538. (message "%s: permission denied!" the-file)
  539. (message "%s: no such file or directory." the-file))))))
  540. nil))) ;; FIXME: Really?
  541. ;;; Core functions:
  542. (defun org-protocol-check-filename-for-protocol (fname restoffiles _client)
  543. "Check if `org-protocol-the-protocol' and a valid protocol are used in FNAME.
  544. Sub-protocols are registered in `org-protocol-protocol-alist' and
  545. `org-protocol-protocol-alist-default'. This is how the matching is done:
  546. (string-match \"protocol:/+sub-protocol\\\\(://\\\\|\\\\?\\\\)\" ...)
  547. protocol and sub-protocol are regexp-quoted.
  548. Old-style links such as \"protocol://sub-protocol://param1/param2\" are
  549. also recognized.
  550. If a matching protocol is found, the protocol is stripped from
  551. FNAME and the result is passed to the protocol function as the
  552. first parameter. The second parameter will be non-nil if FNAME
  553. uses key=val&key2=val2-type arguments, or nil if FNAME uses
  554. val/val2-type arguments. If the function returns nil, the
  555. filename is removed from the list of filenames passed from
  556. emacsclient to the server. If the function returns a non-nil
  557. value, that value is passed to the server as filename.
  558. If the handler function is greedy, RESTOFFILES will also be passed to it.
  559. CLIENT is ignored."
  560. (let ((sub-protocols (append org-protocol-protocol-alist
  561. org-protocol-protocol-alist-default)))
  562. (catch 'fname
  563. (let ((the-protocol (concat (regexp-quote org-protocol-the-protocol)
  564. ":/+")))
  565. (when (string-match the-protocol fname)
  566. (dolist (prolist sub-protocols)
  567. (let ((proto
  568. (concat the-protocol
  569. (regexp-quote (plist-get (cdr prolist) :protocol))
  570. "\\(:/+\\|/*\\?\\)")))
  571. (when (string-match proto fname)
  572. (let* ((func (plist-get (cdr prolist) :function))
  573. (greedy (plist-get (cdr prolist) :greedy))
  574. (split (split-string fname proto))
  575. (result (if greedy restoffiles (cadr split)))
  576. (new-style (not (= ?: (aref (match-string 1 fname) 0)))))
  577. (when (plist-get (cdr prolist) :kill-client)
  578. (message "Greedy org-protocol handler. Killing client.")
  579. (server-edit))
  580. (when (fboundp func)
  581. (unless greedy
  582. (throw 'fname
  583. (if new-style
  584. (funcall func (org-protocol-parse-parameters
  585. result new-style))
  586. (warn "Please update your Org Protocol handler \
  587. to deal with new-style links.")
  588. (funcall func result))))
  589. ;; Greedy protocol handlers are responsible for
  590. ;; parsing their own filenames.
  591. (funcall func result)
  592. (throw 'fname t))))))))
  593. fname)))
  594. (advice-add 'server-visit-files :around #'org--protocol-detect-protocol-server)
  595. (defun org--protocol-detect-protocol-server (orig-fun files client &rest args)
  596. "Advice server-visit-flist to call `org-protocol-modify-filename-for-protocol'."
  597. (let ((flist (if org-protocol-reverse-list-of-files
  598. (reverse files)
  599. files)))
  600. (catch 'greedy
  601. (dolist (var flist)
  602. ;; `\' to `/' on windows. FIXME: could this be done any better?
  603. (let ((fname (expand-file-name (car var))))
  604. (setq fname (org-protocol-check-filename-for-protocol
  605. fname (member var flist) client))
  606. (if (eq fname t) ;; greedy? We need the t return value.
  607. (progn
  608. ;; FIXME: Doesn't this just ignore all the files before
  609. ;; this one (the remaining ones have been passed to
  610. ;; `org-protocol-check-filename-for-protocol' but not
  611. ;; the ones before).
  612. (setq files nil)
  613. (throw 'greedy t))
  614. (if (stringp fname) ;; probably filename
  615. (setcar var fname)
  616. (setq files (delq var files)))))))
  617. (apply orig-fun files client args)))
  618. ;;; Org specific functions:
  619. (defun org-protocol-create-for-org ()
  620. "Create an Org protocol project for the current file's project.
  621. The visited file needs to be part of a publishing project in
  622. `org-publish-project-alist' for this to work. The function
  623. delegates most of the work to `org-protocol-create'."
  624. (interactive)
  625. (require 'ox-publish)
  626. (let ((all (or (org-publish-get-project-from-filename buffer-file-name))))
  627. (if all (org-protocol-create (cdr all))
  628. (message "%s"
  629. (substitute-command-keys
  630. "Not in an Org project. \
  631. Did you mean `\\[org-protocol-create]'?")))))
  632. (defun org-protocol-create (&optional project-plist)
  633. "Create a new org-protocol project interactively.
  634. An org-protocol project is an entry in
  635. `org-protocol-project-alist' which is used by
  636. `org-protocol-open-source'. Optionally use PROJECT-PLIST to
  637. initialize the defaults for this project. If PROJECT-PLIST is
  638. the cdr of an element in `org-publish-project-alist', reuse
  639. :base-directory, :html-extension and :base-extension."
  640. (interactive)
  641. (let ((working-dir (expand-file-name
  642. (or (plist-get project-plist :base-directory)
  643. default-directory)))
  644. (base-url "https://orgmode.org/worg/")
  645. (strip-suffix (or (plist-get project-plist :html-extension) ".html"))
  646. (working-suffix (if (plist-get project-plist :base-extension)
  647. (concat "." (plist-get project-plist :base-extension))
  648. ".org"))
  649. (insert-default-directory t)
  650. (minibuffer-allow-text-properties nil))
  651. (setq base-url (read-string "Base URL of published content: " base-url nil base-url t))
  652. (or (string-suffix-p "/" base-url)
  653. (setq base-url (concat base-url "/")))
  654. (setq working-dir
  655. (expand-file-name
  656. (read-directory-name "Local working directory: " working-dir working-dir t)))
  657. (or (string-suffix-p "/" working-dir)
  658. (setq working-dir (concat working-dir "/")))
  659. (setq strip-suffix
  660. (read-string
  661. (concat "Extension to strip from published URLs (" strip-suffix "): ")
  662. strip-suffix nil strip-suffix t))
  663. (setq working-suffix
  664. (read-string
  665. (concat "Extension of editable files (" working-suffix "): ")
  666. working-suffix nil working-suffix t))
  667. (when (yes-or-no-p "Save the new org-protocol-project to your init file? ")
  668. (setq org-protocol-project-alist
  669. (cons `(,base-url . (:base-url ,base-url
  670. :working-directory ,working-dir
  671. :online-suffix ,strip-suffix
  672. :working-suffix ,working-suffix))
  673. org-protocol-project-alist))
  674. (customize-save-variable 'org-protocol-project-alist org-protocol-project-alist))))
  675. (provide 'org-protocol)
  676. ;;; org-protocol.el ends here