org-protocol.el 28 KB

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