org-protocol.el 29 KB

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