org-protocol.el 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. ;;; org-protocol.el --- Intercept calls from emacsclient to trigger custom actions.
  2. ;;
  3. ;; Copyright (C) 2008, 2009, 2010
  4. ;; Free Software Foundation, Inc.
  5. ;;
  6. ;; Author: Bastien Guerry <bzg AT altern DOT org>
  7. ;; Author: Daniel M German <dmg AT uvic DOT org>
  8. ;; Author: Sebastian Rose <sebastian_rose AT gmx DOT de>
  9. ;; Author: Ross Patterson <me AT rpatterson DOT net>
  10. ;; Maintainer: Sebastian Rose <sebastian_rose AT gmx DOT de>
  11. ;; Keywords: org, emacsclient, wp
  12. ;; Version: 7.4
  13. ;; This file is part of GNU Emacs.
  14. ;;
  15. ;; GNU Emacs is free software: you can redistribute it and/or modify
  16. ;; it under the terms of the GNU General Public License as published by
  17. ;; the Free Software Foundation, either version 3 of the License, or
  18. ;; (at your option) any later version.
  19. ;; GNU Emacs is distributed in the hope that it will be useful,
  20. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. ;; GNU General Public License for more details.
  23. ;; You should have received a copy of the GNU General Public License
  24. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  25. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  26. ;;; Commentary:
  27. ;;
  28. ;; Intercept calls from emacsclient to trigger custom actions.
  29. ;;
  30. ;; This is done by advising `server-visit-files' to scan the list of filenames
  31. ;; for `org-protocol-the-protocol' and sub-protocols defined in
  32. ;; `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'.
  33. ;;
  34. ;; Any application that supports calling external programs with an URL
  35. ;; as argument may be used with this functionality.
  36. ;;
  37. ;;
  38. ;; Usage:
  39. ;; ------
  40. ;;
  41. ;; 1.) Add this to your init file (.emacs probably):
  42. ;;
  43. ;; (add-to-list 'load-path "/path/to/org-protocol/")
  44. ;; (require 'org-protocol)
  45. ;;
  46. ;; 3.) Ensure emacs-server is up and running.
  47. ;; 4.) Try this from the command line (adjust the URL as needed):
  48. ;;
  49. ;; $ emacsclient \
  50. ;; org-protocol://store-link://http:%2F%2Flocalhost%2Findex.html/The%20title
  51. ;;
  52. ;; 5.) Optionally add custom sub-protocols and handlers:
  53. ;;
  54. ;; (setq org-protocol-protocol-alist
  55. ;; '(("my-protocol"
  56. ;; :protocol "my-protocol"
  57. ;; :function my-protocol-handler-function)))
  58. ;;
  59. ;; A "sub-protocol" will be found in URLs like this:
  60. ;;
  61. ;; org-protocol://sub-protocol://data
  62. ;;
  63. ;; If it works, you can now setup other applications for using this feature.
  64. ;;
  65. ;;
  66. ;; As of March 2009 Firefox users follow the steps documented on
  67. ;; http://kb.mozillazine.org/Register_protocol, Opera setup is described here:
  68. ;; http://www.opera.com/support/kb/view/535/
  69. ;;
  70. ;;
  71. ;; Documentation
  72. ;; -------------
  73. ;;
  74. ;; org-protocol.el comes with and installs handlers to open sources of published
  75. ;; online content, store and insert the browser's URLs and cite online content
  76. ;; by clicking on a bookmark in Firefox, Opera and probably other browsers and
  77. ;; applications:
  78. ;;
  79. ;; * `org-protocol-open-source' uses the sub-protocol \"open-source\" and maps
  80. ;; URLs to local filenames defined in `org-protocol-project-alist'.
  81. ;;
  82. ;; * `org-protocol-store-link' stores an Org-link (if Org-mode is present) and
  83. ;; pushes the browsers URL to the `kill-ring' for yanking. This handler is
  84. ;; triggered through the sub-protocol \"store-link\".
  85. ;;
  86. ;; * Call `org-protocol-capture' by using the sub-protocol \"capture\". If
  87. ;; Org-mode is loaded, Emacs will pop-up a capture buffer and fill the
  88. ;; template with the data provided. I.e. the browser's URL is inserted as an
  89. ;; Org-link of which the page title will be the description part. If text
  90. ;; was select in the browser, that text will be the body of the entry.
  91. ;;
  92. ;; * Call `org-protocol-remember' by using the sub-protocol \"remember\".
  93. ;; This is provided for backward compatibility.
  94. ;; You may read `org-capture' as `org-remember' throughout this file if
  95. ;; you still use `org-remember'.
  96. ;;
  97. ;; You may use the same bookmark URL for all those standard handlers and just
  98. ;; adjust the sub-protocol used:
  99. ;;
  100. ;; location.href='org-protocol://sub-protocol://'+
  101. ;; encodeURIComponent(location.href)+'/'+
  102. ;; encodeURIComponent(document.title)+'/'+
  103. ;; encodeURIComponent(window.getSelection())
  104. ;;
  105. ;; The handler for the sub-protocol \"capture\" detects an optional template
  106. ;; char that, if present, triggers the use of a special template.
  107. ;; Example:
  108. ;;
  109. ;; location.href='org-protocol://sub-protocol://x/'+ ...
  110. ;;
  111. ;; use template ?x.
  112. ;;
  113. ;; Note, that using double slashes is optional from org-protocol.el's point of
  114. ;; view because emacsclient squashes the slashes to one.
  115. ;;
  116. ;;
  117. ;; provides: 'org-protocol
  118. ;;
  119. ;;; Code:
  120. (require 'org)
  121. (eval-when-compile
  122. (require 'cl))
  123. (declare-function org-publish-get-project-from-filename "org-publish"
  124. (filename &optional up))
  125. (declare-function server-edit "server" (&optional arg))
  126. (defgroup org-protocol nil
  127. "Intercept calls from emacsclient to trigger custom actions.
  128. This is done by advising `server-visit-files' to scann the list of filenames
  129. for `org-protocol-the-protocol' and sub-procols defined in
  130. `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'."
  131. :version "22.1"
  132. :group 'convenience
  133. :group 'org)
  134. ;;; Variables:
  135. (defconst org-protocol-protocol-alist-default
  136. '(("org-remember" :protocol "remember" :function org-protocol-remember :kill-client t)
  137. ("org-capture" :protocol "capture" :function org-protocol-capture :kill-client t)
  138. ("org-store-link" :protocol "store-link" :function org-protocol-store-link)
  139. ("org-open-source" :protocol "open-source" :function org-protocol-open-source))
  140. "Default protocols to use.
  141. See `org-protocol-protocol-alist' for a description of this variable.")
  142. (defconst org-protocol-the-protocol "org-protocol"
  143. "This is the protocol to detect if org-protocol.el is loaded.
  144. `org-protocol-protocol-alist-default' and `org-protocol-protocol-alist' hold
  145. the sub-protocols that trigger the required action. You will have to define
  146. just one protocol handler OS-wide (MS-Windows) or per application (Linux).
  147. That protocol handler should call emacsclient.")
  148. ;;; User variables:
  149. (defcustom org-protocol-reverse-list-of-files t
  150. "* Non-nil means re-reverse the list of filenames passed on the command line.
  151. The filenames passed on the command line are passed to the emacs-server in
  152. reverse order. Set to t (default) to re-reverse the list, i.e. use the
  153. sequence on the command line. If nil, the sequence of the filenames is
  154. unchanged."
  155. :group 'org-protocol
  156. :type 'boolean)
  157. (defcustom org-protocol-project-alist nil
  158. "* Map URLs to local filenames for `org-protocol-open-source' (open-source).
  159. Each element of this list must be of the form:
  160. (module-name :property value property: value ...)
  161. where module-name is an arbitrary name. All the values are strings.
  162. Possible properties are:
  163. :online-suffix - the suffix to strip from the published URLs
  164. :working-suffix - the replacement for online-suffix
  165. :base-url - the base URL, e.g. http://www.example.com/project/
  166. Last slash required.
  167. :working-directory - the local working directory. This is, what base-url will
  168. be replaced with.
  169. :redirects - A list of cons cells, each of which maps a regular
  170. expression to match to a path relative to :working-directory.
  171. Example:
  172. (setq org-protocol-project-alist
  173. '((\"http://orgmode.org/worg/\"
  174. :online-suffix \".php\"
  175. :working-suffix \".org\"
  176. :base-url \"http://orgmode.org/worg/\"
  177. :working-directory \"/home/user/org/Worg/\")
  178. (\"http://localhost/org-notes/\"
  179. :online-suffix \".html\"
  180. :working-suffix \".org\"
  181. :base-url \"http://localhost/org/\"
  182. :working-directory \"/home/user/org/\"
  183. :rewrites ((\"org/?$\" . \"index.php\")))))
  184. The last line tells `org-protocol-open-source' to open
  185. /home/user/org/index.php, if the URL cannot be mapped to an existing
  186. file, and ends with either \"org\" or \"org/\".
  187. Consider using the interactive functions `org-protocol-create' and
  188. `org-protocol-create-for-org' to help you filling this variable with valid contents."
  189. :group 'org-protocol
  190. :type 'alist)
  191. (defcustom org-protocol-protocol-alist nil
  192. "* Register custom handlers for org-protocol.
  193. Each element of this list must be of the form:
  194. (module-name :protocol protocol :function func :kill-client nil)
  195. protocol - protocol to detect in a filename without trailing colon and slashes.
  196. See rfc1738 section 2.1 for more on this.
  197. If you define a protocol \"my-protocol\", `org-protocol-check-filename-for-protocol'
  198. will search filenames for \"org-protocol:/my-protocol:/\"
  199. and trigger your action for every match. `org-protocol' is defined in
  200. `org-protocol-the-protocol'. Double and triple slashes are compressed
  201. to one by emacsclient.
  202. function - function that handles requests with protocol and takes exactly one
  203. argument: the filename with all protocols stripped. If the function
  204. returns nil, emacsclient and -server do nothing. Any non-nil return
  205. value is considered a valid filename and thus passed to the server.
  206. `org-protocol.el provides some support for handling those filenames,
  207. if you stay with the conventions used for the standard handlers in
  208. `org-protocol-protocol-alist-default'. See `org-protocol-split-data'.
  209. kill-client - If t, kill the client immediately, once the sub-protocol is
  210. detected. This is necessary for actions that can be interrupted by
  211. `C-g' to avoid dangling emacsclients. Note, that all other command
  212. line arguments but the this one will be discarded, greedy handlers
  213. still receive the whole list of arguments though.
  214. Here is an example:
  215. (setq org-protocol-protocol-alist
  216. '((\"my-protocol\"
  217. :protocol \"my-protocol\"
  218. :function my-protocol-handler-function)
  219. (\"your-protocol\"
  220. :protocol \"your-protocol\"
  221. :function your-protocol-handler-function)))"
  222. :group 'org-protocol
  223. :type '(alist))
  224. (defcustom org-protocol-default-template-key nil
  225. "The default org-remember-templates key to use."
  226. :group 'org-protocol
  227. :type 'string)
  228. ;;; Helper functions:
  229. (defun org-protocol-sanitize-uri (uri)
  230. "emacsclient compresses double and triple slashes.
  231. Slashes are sanitized to double slashes here."
  232. (when (string-match "^\\([a-z]+\\):/" uri)
  233. (let* ((splitparts (split-string uri "/+")))
  234. (setq uri (concat (car splitparts) "//" (mapconcat 'identity (cdr splitparts) "/")))))
  235. uri)
  236. (defun org-protocol-split-data(data &optional unhexify separator)
  237. "Split, what an org-protocol handler function gets as only argument.
  238. DATA is that one argument. DATA is split at each occurrence of
  239. SEPARATOR (regexp). If no SEPARATOR is specified or SEPARATOR is
  240. nil, assume \"/+\". The results of that splitting are returned
  241. as a list. If UNHEXIFY is non-nil, hex-decode each split part. If
  242. UNHEXIFY is a function, use that function to decode each split
  243. part."
  244. (let* ((sep (or separator "/+"))
  245. (split-parts (split-string data sep)))
  246. (if unhexify
  247. (if (fboundp unhexify)
  248. (mapcar unhexify split-parts)
  249. (mapcar 'org-protocol-unhex-string split-parts))
  250. split-parts)))
  251. (defun org-protocol-unhex-string(str)
  252. "Unhex hexified unicode strings as returned from the JavaScript function
  253. encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
  254. (setq str (or str ""))
  255. (let ((tmp "")
  256. (case-fold-search t))
  257. (while (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str)
  258. (let* ((start (match-beginning 0))
  259. (end (match-end 0))
  260. (hex (match-string 0 str))
  261. (replacement (org-protocol-unhex-compound (upcase hex))))
  262. (setq tmp (concat tmp (substring str 0 start) replacement))
  263. (setq str (substring str end))))
  264. (setq tmp (concat tmp str))
  265. tmp))
  266. (defun org-protocol-unhex-compound (hex)
  267. "Unhexify unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
  268. Note: this function also decodes single byte encodings like
  269. `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
  270. (let* ((bytes (remove "" (split-string hex "%")))
  271. (ret "")
  272. (eat 0)
  273. (sum 0))
  274. (while bytes
  275. (let* ((b (pop bytes))
  276. (a (elt b 0))
  277. (b (elt b 1))
  278. (c1 (if (> a ?9) (+ 10 (- a ?A)) (- a ?0)))
  279. (c2 (if (> b ?9) (+ 10 (- b ?A)) (- b ?0)))
  280. (val (+ (lsh c1 4) c2))
  281. (shift
  282. (if (= 0 eat) ;; new byte
  283. (if (>= val 252) 6
  284. (if (>= val 248) 5
  285. (if (>= val 240) 4
  286. (if (>= val 224) 3
  287. (if (>= val 192) 2 0)))))
  288. 6))
  289. (xor
  290. (if (= 0 eat) ;; new byte
  291. (if (>= val 252) 252
  292. (if (>= val 248) 248
  293. (if (>= val 240) 240
  294. (if (>= val 224) 224
  295. (if (>= val 192) 192 0)))))
  296. 128)))
  297. (if (>= val 192) (setq eat shift))
  298. (setq val (logxor val xor))
  299. (setq sum (+ (lsh sum shift) val))
  300. (if (> eat 0) (setq eat (- eat 1)))
  301. (cond
  302. ((= 0 eat) ;multi byte
  303. (setq ret (concat ret (org-char-to-string sum)))
  304. (setq sum 0))
  305. ((not bytes) ; single byte(s)
  306. (setq ret (org-protocol-unhex-single-byte-sequence hex))))
  307. )) ;; end (while bytes
  308. ret ))
  309. (defun org-protocol-unhex-single-byte-sequence(hex)
  310. "Unhexify hex-encoded single byte character sequences."
  311. (let ((bytes (remove "" (split-string hex "%")))
  312. (ret ""))
  313. (while bytes
  314. (let* ((b (pop bytes))
  315. (a (elt b 0))
  316. (b (elt b 1))
  317. (c1 (if (> a ?9) (+ 10 (- a ?A)) (- a ?0)))
  318. (c2 (if (> b ?9) (+ 10 (- b ?A)) (- b ?0))))
  319. (setq ret
  320. (concat ret (char-to-string
  321. (+ (lsh c1 4) c2))))))
  322. ret))
  323. (defun org-protocol-flatten-greedy (param-list &optional strip-path replacement)
  324. "Greedy handlers might receive a list like this from emacsclient:
  325. '( (\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\")
  326. where \"/dir/\" is the absolute path to emacsclients working directory. This
  327. function transforms it into a flat list utilizing `org-protocol-flatten' and
  328. transforms the elements of that list as follows:
  329. If strip-path is non-nil, remove the \"/dir/\" prefix from all members of
  330. param-list.
  331. If replacement is string, replace the \"/dir/\" prefix with it.
  332. The first parameter, the one that contains the protocols, is always changed.
  333. Everything up to the end of the protocols is stripped.
  334. Note, that this function will always behave as if
  335. `org-protocol-reverse-list-of-files' was set to t and the returned list will
  336. reflect that. I.e. emacsclients first parameter will be the first one in the
  337. returned list."
  338. (let* ((l (org-protocol-flatten (if org-protocol-reverse-list-of-files
  339. param-list
  340. (reverse param-list))))
  341. (trigger (car l))
  342. (len 0)
  343. dir
  344. ret)
  345. (when (string-match "^\\(.*\\)\\(org-protocol:/+[a-zA-z0-9][-_a-zA-z0-9]*:/+\\)\\(.*\\)" trigger)
  346. (setq dir (match-string 1 trigger))
  347. (setq len (length dir))
  348. (setcar l (concat dir (match-string 3 trigger))))
  349. (if strip-path
  350. (progn
  351. (dolist (e l ret)
  352. (setq ret
  353. (append ret
  354. (list
  355. (if (stringp e)
  356. (if (stringp replacement)
  357. (setq e (concat replacement (substring e len)))
  358. (setq e (substring e len)))
  359. e)))))
  360. ret)
  361. l)))
  362. (defun org-protocol-flatten (l)
  363. "Greedy handlers might receive a list like this from emacsclient:
  364. '( (\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\")
  365. where \"/dir/\" is the absolute path to emacsclients working directory.
  366. This function transforms it into a flat list."
  367. (if (null l) ()
  368. (if (listp l)
  369. (append (org-protocol-flatten (car l)) (org-protocol-flatten (cdr l)))
  370. (list l))))
  371. ;;; Standard protocol handlers:
  372. (defun org-protocol-store-link (fname)
  373. "Process an org-protocol://store-link:// style url.
  374. Additionally store a browser URL as an org link. Also pushes the
  375. link's URL to the `kill-ring'.
  376. The location for a browser's bookmark has to look like this:
  377. javascript:location.href='org-protocol://store-link://'+ \\
  378. encodeURIComponent(location.href)
  379. encodeURIComponent(document.title)+'/'+ \\
  380. Don't use `escape()'! Use `encodeURIComponent()' instead. The title of the page
  381. could contain slashes and the location definitely will.
  382. The sub-protocol used to reach this function is set in
  383. `org-protocol-protocol-alist'."
  384. (let* ((splitparts (org-protocol-split-data fname t))
  385. (uri (org-protocol-sanitize-uri (car splitparts)))
  386. (title (cadr splitparts))
  387. orglink)
  388. (if (boundp 'org-stored-links)
  389. (setq org-stored-links (cons (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-remember (info)
  397. "Process an org-protocol://remember:// style url.
  398. The location for a browser's bookmark has to look like this:
  399. javascript:location.href='org-protocol://remember://'+ \\
  400. encodeURIComponent(location.href)+'/' \\
  401. encodeURIComponent(document.title)+'/'+ \\
  402. encodeURIComponent(window.getSelection())
  403. See the docs for `org-protocol-capture' for more information."
  404. (if (and (boundp 'org-stored-links)
  405. (or (fboundp 'org-capture))
  406. (org-protocol-do-capture info 'org-remember))
  407. (message "Org-mode not loaded."))
  408. nil)
  409. (defun org-protocol-capture (info)
  410. "Process an org-protocol://capture:// style url.
  411. The sub-protocol used to reach this function is set in
  412. `org-protocol-protocol-alist'.
  413. This function detects an URL, title and optional text, separated by '/'
  414. The location for a browser's bookmark has to look like this:
  415. javascript:location.href='org-protocol://capture://'+ \\
  416. encodeURIComponent(location.href)+'/' \\
  417. encodeURIComponent(document.title)+'/'+ \\
  418. encodeURIComponent(window.getSelection())
  419. By default, it uses the character `org-protocol-default-template-key',
  420. which should be associated with a template in `org-capture-templates'.
  421. But you may prepend the encoded URL with a character and a slash like so:
  422. javascript:location.href='org-protocol://capture://b/'+ ...
  423. Now template ?b will be used."
  424. (if (and (boundp 'org-stored-links)
  425. (or (fboundp 'org-capture))
  426. (org-protocol-do-capture info 'org-capture))
  427. (message "Org-mode not loaded."))
  428. nil)
  429. (defun org-protocol-do-capture (info capture-func)
  430. "Support `org-capture' and `org-remember' alike.
  431. CAPTURE-FUNC is either the symbol `org-remember' or `org-capture'."
  432. (let* ((parts (org-protocol-split-data info t))
  433. (template (or (and (= 1 (length (car parts))) (pop parts))
  434. org-protocol-default-template-key))
  435. (url (org-protocol-sanitize-uri (car parts)))
  436. (type (if (string-match "^\\([a-z]+\\):" url)
  437. (match-string 1 url)))
  438. (title(or (cadr parts) ""))
  439. (region (or (caddr parts) ""))
  440. (orglink (org-make-link-string
  441. url (if (string-match "[^[:space:]]" title) title url)))
  442. (org-capture-link-is-already-stored t) ;; avoid call to org-store-link
  443. remember-annotation-functions)
  444. (setq org-stored-links
  445. (cons (list url title) org-stored-links))
  446. (kill-new orglink)
  447. (org-store-link-props :type type
  448. :link url
  449. :description title
  450. :annotation orglink
  451. :initial region)
  452. (raise-frame)
  453. (funcall capture-func nil template)))
  454. (defun org-protocol-open-source (fname)
  455. "Process an org-protocol://open-source:// style url.
  456. Change a filename by mapping URLs to local filenames as set
  457. in `org-protocol-project-alist'.
  458. The location for a browser's bookmark should look like this:
  459. javascript:location.href='org-protocol://open-source://'+ \\
  460. encodeURIComponent(location.href)"
  461. ;; As we enter this function for a match on our protocol, the return value
  462. ;; defaults to nil.
  463. (let ((result nil)
  464. (f (org-protocol-unhex-string fname)))
  465. (catch 'result
  466. (dolist (prolist org-protocol-project-alist)
  467. (let* ((base-url (plist-get (cdr prolist) :base-url))
  468. (wsearch (regexp-quote base-url)))
  469. (when (string-match wsearch f)
  470. (let* ((wdir (plist-get (cdr prolist) :working-directory))
  471. (strip-suffix (plist-get (cdr prolist) :online-suffix))
  472. (add-suffix (plist-get (cdr prolist) :working-suffix))
  473. ;; Strip "[?#].*$" if `f' is a redirect with another
  474. ;; ending than strip-suffix here:
  475. (f1 (substring f 0 (string-match "\\([\\?#].*\\)?$" f)))
  476. (start-pos (+ (string-match wsearch f1) (length base-url)))
  477. (end-pos (string-match
  478. (regexp-quote strip-suffix) f1))
  479. ;; We have to compare redirects without suffix below:
  480. (f2 (concat wdir (substring f1 start-pos end-pos)))
  481. (the-file (concat f2 add-suffix)))
  482. ;; Note: the-file may still contain `%C3' et al here because browsers
  483. ;; tend to encode `&auml;' in URLs to `%25C3' - `%25' being `%'.
  484. ;; So the results may vary.
  485. ;; -- start redirects --
  486. (unless (file-exists-p the-file)
  487. (message "File %s does not exist.\nTesting for rewritten URLs." the-file)
  488. (let ((rewrites (plist-get (cdr prolist) :rewrites)))
  489. (when rewrites
  490. (message "Rewrites found: %S" rewrites)
  491. (mapc
  492. (lambda (rewrite)
  493. "Try to match a rewritten URL and map it to a real file."
  494. ;; Compare redirects without suffix:
  495. (if (string-match (car rewrite) f2)
  496. (throw 'result (concat wdir (cdr rewrite)))))
  497. rewrites))))
  498. ;; -- end of redirects --
  499. (if (file-readable-p the-file)
  500. (throw 'result the-file))
  501. (if (file-exists-p the-file)
  502. (message "%s: permission denied!" the-file)
  503. (message "%s: no such file or directory." the-file))))))
  504. result)))
  505. ;;; Core functions:
  506. (defun org-protocol-check-filename-for-protocol (fname restoffiles client)
  507. "Detect if `org-protocol-the-protocol' and a known sub-protocol is used in fname.
  508. Sub-protocols are registered in `org-protocol-protocol-alist' and
  509. `org-protocol-protocol-alist-default'.
  510. This is, how the matching is done:
  511. (string-match \"protocol:/+sub-protocol:/+\" ...)
  512. protocol and sub-protocol are regexp-quoted.
  513. If a matching protocol is found, the protocol is stripped from fname and the
  514. result is passed to the protocols function as the only parameter. If the
  515. function returns nil, the filename is removed from the list of filenames
  516. passed from emacsclient to the server.
  517. If the function returns a non nil value, that value is passed to the server
  518. as filename."
  519. (let ((sub-protocols (append org-protocol-protocol-alist org-protocol-protocol-alist-default)))
  520. (catch 'fname
  521. (let ((the-protocol (concat (regexp-quote org-protocol-the-protocol) ":/+")))
  522. (when (string-match the-protocol fname)
  523. (dolist (prolist sub-protocols)
  524. (let ((proto (concat the-protocol (regexp-quote (plist-get (cdr prolist) :protocol)) ":/+")))
  525. (when (string-match proto fname)
  526. (let* ((func (plist-get (cdr prolist) :function))
  527. (greedy (plist-get (cdr prolist) :greedy))
  528. (splitted (split-string fname proto))
  529. (result (if greedy restoffiles (cadr splitted))))
  530. (when (plist-get (cdr prolist) :kill-client)
  531. (message "Greedy org-protocol handler. Killing client.")
  532. (server-edit))
  533. (when (fboundp func)
  534. (unless greedy
  535. (throw 'fname (funcall func result)))
  536. (funcall func result)
  537. (throw 'fname t))))))))
  538. ;; (message "fname: %s" fname)
  539. fname)))
  540. (defadvice server-visit-files (before org-protocol-detect-protocol-server activate)
  541. "Advice server-visit-flist to call `org-protocol-modify-filename-for-protocol'."
  542. (let ((flist (if org-protocol-reverse-list-of-files
  543. (reverse (ad-get-arg 0))
  544. (ad-get-arg 0)))
  545. (client (ad-get-arg 1)))
  546. (catch 'greedy
  547. (dolist (var flist)
  548. (let ((fname (expand-file-name (car var)))) ;; `\' to `/' on windows. FIXME: could this be done any better?
  549. (setq fname (org-protocol-check-filename-for-protocol 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. ))))
  558. ;;; Org specific functions:
  559. (defun org-protocol-create-for-org ()
  560. "Create a org-protocol project for the current file's Org-mode project.
  561. This works, if the file visited is part of a publishing project in
  562. `org-publish-project-alist'. This function calls `org-protocol-create' to do
  563. most of the work."
  564. (interactive)
  565. (require 'org-publish)
  566. (let ((all (or (org-publish-get-project-from-filename buffer-file-name))))
  567. (if all (org-protocol-create (cdr all))
  568. (message "Not in an org-project. Did mean %s?"
  569. (substitute-command-keys"\\[org-protocol-create]")))))
  570. (defun org-protocol-create(&optional project-plist)
  571. "Create a new org-protocol project interactively.
  572. An org-protocol project is an entry in `org-protocol-project-alist'
  573. which is used by `org-protocol-open-source'.
  574. Optionally use project-plist to initialize the defaults for this project. If
  575. project-plist is 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(or (plist-get project-plist :base-directory) default-directory)))
  579. (base-url "http://orgmode.org/worg/")
  580. (strip-suffix (or (plist-get project-plist :html-extension) ".html"))
  581. (working-suffix (if (plist-get project-plist :base-extension)
  582. (concat "." (plist-get project-plist :base-extension))
  583. ".org"))
  584. (worglet-buffer nil)
  585. (insert-default-directory t)
  586. (minibuffer-allow-text-properties nil))
  587. (setq base-url (read-string "Base URL of published content: " base-url nil base-url t))
  588. (if (not (string-match "\\/$" base-url))
  589. (setq base-url (concat base-url "/")))
  590. (setq working-dir
  591. (expand-file-name
  592. (read-directory-name "Local working directory: " working-dir working-dir t)))
  593. (if (not (string-match "\\/$" working-dir))
  594. (setq working-dir (concat working-dir "/")))
  595. (setq strip-suffix
  596. (read-string
  597. (concat "Extension to strip from published URLs ("strip-suffix"): ")
  598. strip-suffix nil strip-suffix t))
  599. (setq working-suffix
  600. (read-string
  601. (concat "Extension of editable files ("working-suffix"): ")
  602. working-suffix nil working-suffix t))
  603. (when (yes-or-no-p "Save the new org-protocol-project to your init file? ")
  604. (setq org-protocol-project-alist
  605. (cons `(,base-url . (:base-url ,base-url
  606. :working-directory ,working-dir
  607. :online-suffix ,strip-suffix
  608. :working-suffix ,working-suffix))
  609. org-protocol-project-alist))
  610. (customize-save-variable 'org-protocol-project-alist org-protocol-project-alist))))
  611. (provide 'org-protocol)
  612. ;; arch-tag: b5c5c2ac-77cf-4a94-a649-2163dff95846
  613. ;;; org-protocol.el ends here