org-protocol.el 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. ;;; org-protocol.el --- Intercept calls from emacsclient to trigger custom actions.
  2. ;;
  3. ;; Copyright (C) 2008, 2009
  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: 6.34trans
  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 scann the list of filenames
  31. ;; for `org-protocol-the-protocol' and sub-procols 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-fuction)))
  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-remember' by using the sub-protocol \"remember\". If
  87. ;; Org-mode is loaded, emacs will pop-up a remember 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. ;; You may use the same bookmark URL for all those standard handlers and just
  93. ;; adjust the sub-protocol used:
  94. ;;
  95. ;; location.href='org-protocol://sub-protocol://'+
  96. ;; encodeURIComponent(location.href)+'/'+
  97. ;; encodeURIComponent(document.title)+'/'+
  98. ;; encodeURIComponent(window.getSelection())
  99. ;;
  100. ;; The handler for the sub-protocol \"remember\" detects an optional template
  101. ;; char that, if present, triggers the use of a special template.
  102. ;; Example:
  103. ;;
  104. ;; location.href='org-protocol://sub-protocol://x/'+ ...
  105. ;;
  106. ;; use template ?x.
  107. ;;
  108. ;; Note, that using double slashes is optional from org-protocol.el's point of
  109. ;; view because emacsclient squashes the slashes to one.
  110. ;;
  111. ;;
  112. ;; provides: 'org-protocol
  113. ;;
  114. ;;; Code:
  115. (require 'org)
  116. (eval-when-compile
  117. (require 'cl))
  118. (declare-function org-publish-initialize-files-alist "org-publish"
  119. (&optional refresh))
  120. (declare-function org-publish-get-project-from-filename "org-publish"
  121. (filename &optional up))
  122. (declare-function server-edit "server" (&optional arg))
  123. (defgroup org-protocol nil
  124. "Intercept calls from emacsclient to trigger custom actions.
  125. This is done by advising `server-visit-files' to scann the list of filenames
  126. for `org-protocol-the-protocol' and sub-procols defined in
  127. `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'."
  128. :version "22.1"
  129. :group 'convenience
  130. :group 'org)
  131. ;;; Variables:
  132. (defconst org-protocol-protocol-alist-default
  133. '(("org-remember" :protocol "remember" :function org-protocol-remember :kill-client t)
  134. ("org-store-link" :protocol "store-link" :function org-protocol-store-link)
  135. ("org-open-source" :protocol "open-source" :function org-protocol-open-source))
  136. "Default protocols to use.
  137. See `org-protocol-protocol-alist' for a description of this variable.")
  138. (defconst org-protocol-the-protocol "org-protocol"
  139. "This is the protocol to detect if org-protocol.el is loaded.
  140. `org-protocol-protocol-alist-default' and `org-protocol-protocol-alist' hold the
  141. sub-protocols that trigger the required action. You will have to define just one
  142. protocol handler OS-wide (MS-Windows) or per application (Linux). That protocol
  143. handler should call emacsclient.")
  144. ;;; User variables:
  145. (defcustom org-protocol-reverse-list-of-files t
  146. "* The filenames passed on the commandline are passed to the emacs-server in
  147. reversed order. Set to `t' (default) to re-reverse the list, i.e. use the
  148. sequence on the command line. If nil, the sequence of the filenames is
  149. unchanged."
  150. :group 'org-protocol
  151. :type 'boolean)
  152. (defcustom org-protocol-project-alist nil
  153. "* Map URLs to local filenames for `org-protocol-open-source' (open-source).
  154. Each element of this list must be of the form:
  155. (module-name :property value property: value ...)
  156. where module-name is an arbitrary name. All the values are strings.
  157. Possible properties are:
  158. :online-suffix - the suffix to strip from the published URLs
  159. :working-suffix - the replacement for online-suffix
  160. :base-url - the base URL, e.g. http://www.example.com/project/
  161. Last slash required.
  162. :working-directory - the local working directory. This is, what base-url will
  163. be replaced with.
  164. :redirects - A list of cons cells, each of which maps a regular
  165. expression to match to a path relative to :working-directory.
  166. Example:
  167. (setq org-protocol-project-alist
  168. '((\"http://orgmode.org/worg/\"
  169. :online-suffix \".php\"
  170. :working-suffix \".org\"
  171. :base-url \"http://orgmode.org/worg/\"
  172. :working-directory \"/home/user/org/Worg/\")
  173. (\"http://localhost/org-notes/\"
  174. :online-suffix \".html\"
  175. :working-suffix \".org\"
  176. :base-url \"http://localhost/org/\"
  177. :working-directory \"/home/user/org/\"
  178. :rewrites ((\"org/?$\" . \"index.php\")))))
  179. The last line tells `org-protocol-open-source' to open
  180. /home/user/org/index.php, if the URL cannot be mapped to an existing
  181. file, and ends with either \"org\" or \"org/\".
  182. Consider using the interactive functions `org-protocol-create' and
  183. `org-protocol-create-for-org' to help you filling this variable with valid contents."
  184. :group 'org-protocol
  185. :type 'alist)
  186. (defcustom org-protocol-protocol-alist nil
  187. "* Register custom handlers for org-protocol.
  188. Each element of this list must be of the form:
  189. (module-name :protocol protocol :function func :kill-client nil)
  190. protocol - protocol to detect in a filename without trailing colon and slashes.
  191. See rfc1738 section 2.1 for more on this.
  192. If you define a protocol \"my-protocol\", `org-protocol-check-filename-for-protocol'
  193. will search filenames for \"org-protocol:/my-protocol:/\"
  194. and trigger your action for every match. `org-protocol' is defined in
  195. `org-protocol-the-protocol'. Double and tripple slashes are compressed
  196. to one by emacsclient.
  197. function - function that handles requests with protocol and takes exactly one
  198. argument: the filename with all protocols stripped. If the function
  199. returns nil, emacsclient and -server do nothing. Any non-nil return
  200. value is considered a valid filename and thus passed to the server.
  201. `org-protocol.el provides some support for handling those filenames,
  202. if you stay with the conventions used for the standard handlers in
  203. `org-protocol-protocol-alist-default'. See `org-protocol-split-data'.
  204. kill-client - If t, kill the client immediately, once the sub-protocol is
  205. detected. This is necessary for actions that can be interrupted by
  206. `C-g' to avoid dangeling emacsclients. Note, that all other command
  207. line arguments but the this one will be discarded, greedy handlers
  208. still receive the whole list of arguments though.
  209. Here is an example:
  210. (setq org-protocol-protocol-alist
  211. '((\"my-protocol\"
  212. :protocol \"my-protocol\"
  213. :function my-protocol-handler-fuction)
  214. (\"your-protocol\"
  215. :protocol \"your-protocol\"
  216. :function your-protocol-handler-fuction)))"
  217. :group 'org-protocol
  218. :type '(alist))
  219. (defcustom org-protocol-default-template-key "w"
  220. "The default org-remember-templates key to use."
  221. :group 'org-protocol
  222. :type 'string)
  223. ;;; Helper functions:
  224. (defun org-protocol-sanitize-uri (uri)
  225. "emacsclient compresses double and tripple slashes.
  226. Slashes are sanitized to double slashes here."
  227. (when (string-match "^\\([a-z]+\\):/" uri)
  228. (let* ((splitparts (split-string uri "/+")))
  229. (setq uri (concat (car splitparts) "//" (mapconcat 'identity (cdr splitparts) "/")))))
  230. uri)
  231. (defun org-protocol-split-data(data &optional unhexify separator)
  232. "Split, what a org-protocol handler function gets as only argument.
  233. data is that one argument. Data is splitted at each occurrence of separator
  234. (regexp). If no separator is specified or separator is nil, assume \"/+\".
  235. The results of that splitting are return as a list. If unhexify is non-nil,
  236. hex-decode each split part. If unhexify is a function, use that function to
  237. decode each split part."
  238. (let* ((sep (or separator "/+"))
  239. (split-parts (split-string data sep)))
  240. (if unhexify
  241. (if (fboundp unhexify)
  242. (mapcar unhexify split-parts)
  243. (mapcar 'org-protocol-unhex-string split-parts))
  244. split-parts)))
  245. ;; This inline function is needed in org-protocol-unhex-compound to do
  246. ;; the right thing to decode UTF-8 char integer values.
  247. (eval-when-compile
  248. (if (>= emacs-major-version 23)
  249. (defsubst org-protocol-char-to-string(c)
  250. "Defsubst to decode UTF-8 character values in emacs 23 and beyond."
  251. (char-to-string c))
  252. (defsubst org-protocol-char-to-string (c)
  253. "Defsubst to decode UTF-8 character values in emacs 22."
  254. (string (decode-char 'ucs c)))))
  255. (defun org-protocol-unhex-string(str)
  256. "Unhex hexified unicode strings as returned from the JavaScript function
  257. encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ü'."
  258. (setq str (or str ""))
  259. (let ((tmp "")
  260. (case-fold-search t))
  261. (while (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str)
  262. (let* ((start (match-beginning 0))
  263. (end (match-end 0))
  264. (hex (match-string 0 str))
  265. (replacement (org-protocol-unhex-compound hex)))
  266. (setq tmp (concat tmp (substring str 0 start) replacement))
  267. (setq str (substring str end))))
  268. (setq tmp (concat tmp str))
  269. tmp))
  270. (defun org-protocol-unhex-compound (hex)
  271. "Unhexify unicode hex-chars. E.g. `%C3%B6' is the german Umlaut `ü'."
  272. (let* ((bytes (remove "" (split-string hex "%")))
  273. (ret "")
  274. (eat 0)
  275. (sum 0))
  276. (while bytes
  277. (let* ((b (pop bytes))
  278. (a (elt b 0))
  279. (b (elt b 1))
  280. (c1 (if (> a ?9) (+ 10 (- a ?A)) (- a ?0)))
  281. (c2 (if (> b ?9) (+ 10 (- b ?A)) (- b ?0)))
  282. (val (+ (lsh c1 4) c2))
  283. (shift
  284. (if (= 0 eat) ;; new byte
  285. (if (>= val 252) 6
  286. (if (>= val 248) 5
  287. (if (>= val 240) 4
  288. (if (>= val 224) 3
  289. (if (>= val 192) 2 0)))))
  290. 6))
  291. (xor
  292. (if (= 0 eat) ;; new byte
  293. (if (>= val 252) 252
  294. (if (>= val 248) 248
  295. (if (>= val 240) 240
  296. (if (>= val 224) 224
  297. (if (>= val 192) 192 0)))))
  298. 128)))
  299. (if (>= val 192) (setq eat shift))
  300. (setq val (logxor val xor))
  301. (setq sum (+ (lsh sum shift) val))
  302. (if (> eat 0) (setq eat (- eat 1)))
  303. (when (= 0 eat)
  304. (setq ret (concat ret (org-protocol-char-to-string sum)))
  305. (setq sum 0))
  306. )) ;; end (while bytes
  307. ret ))
  308. (defun org-protocol-flatten-greedy (param-list &optional strip-path replacement)
  309. "Greedy handlers might recieve a list like this from emacsclient:
  310. '( (\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\")
  311. where \"/dir/\" is the absolute path to emacsclients working directory. This
  312. function transforms it into a flat list utilizing `org-protocol-flatten' and
  313. transforms the elements of that list as follows:
  314. If strip-path is non-nil, remove the \"/dir/\" prefix from all members of
  315. param-list.
  316. If replacement is string, replace the \"/dir/\" prefix with it.
  317. The first parameter, the one that contains the protocols, is always changed.
  318. Everything up to the end of the protocols is stripped.
  319. Note, that this function will always behave as if
  320. `org-protocol-reverse-list-of-files' was set to t and the returned list will
  321. reflect that. I.e. emacsclients first parameter will be the first one in the
  322. returned list."
  323. (let* ((l (org-protocol-flatten (if org-protocol-reverse-list-of-files
  324. param-list
  325. (reverse param-list))))
  326. (trigger (car l))
  327. (len 0)
  328. dir
  329. ret)
  330. (when (string-match "^\\(.*\\)\\(org-protocol:/+[a-zA-z0-9][-_a-zA-z0-9]*:/+\\)\\(.*\\)" trigger)
  331. (setq dir (match-string 1 trigger))
  332. (setq len (length dir))
  333. (setcar l (concat dir (match-string 3 trigger))))
  334. (if strip-path
  335. (progn
  336. (dolist (e l ret)
  337. (setq ret
  338. (append ret
  339. (list
  340. (if (stringp e)
  341. (if (stringp replacement)
  342. (setq e (concat replacement (substring e len)))
  343. (setq e (substring e len)))
  344. e)))))
  345. ret)
  346. l)))
  347. (defun org-protocol-flatten (l)
  348. "Greedy handlers might recieve a list like this from emacsclient:
  349. '( (\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\")
  350. where \"/dir/\" is the absolute path to emacsclients working directory. This
  351. function transforms it into a flat list."
  352. (if (null l) ()
  353. (if (listp l)
  354. (append (org-protocol-flatten (car l)) (org-protocol-flatten (cdr l)))
  355. (list l))))
  356. ;;; Standard protocol handlers:
  357. (defun org-protocol-store-link (fname)
  358. "Process an org-protocol://store-link:// style url
  359. and store a browser URL as an org link. Also pushes the links URL to the
  360. `kill-ring'.
  361. The location for a browser's bookmark has to look like this:
  362. javascript:location.href='org-protocol://store-link://'+ \\
  363. encodeURIComponent(location.href)
  364. encodeURIComponent(document.title)+'/'+ \\
  365. Don't use `escape()'! Use `encodeURIComponent()' instead. The title of the page
  366. could contain slashes and the location definitely will.
  367. The sub-protocol used to reach this function is set in
  368. `org-protocol-protocol-alist'."
  369. (let* ((splitparts (org-protocol-split-data fname t))
  370. (uri (org-protocol-sanitize-uri (car splitparts)))
  371. (title (cadr splitparts))
  372. orglink)
  373. (if (boundp 'org-stored-links)
  374. (setq org-stored-links (cons (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-remember (info)
  382. "Process an org-protocol://remember:// style url.
  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 by '/'
  386. The location for a browser's bookmark has to look like this:
  387. javascript:location.href='org-protocol://remember://'+ \\
  388. encodeURIComponent(location.href)+'/' \\
  389. encodeURIComponent(document.title)+'/'+ \\
  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-remember-templates'.
  393. But you may prepend the encoded URL with a character and a slash like so:
  394. javascript:location.href='org-protocol://org-store-link://b/'+ ...
  395. Now template ?b will be used."
  396. (if (and (boundp 'org-stored-links)
  397. (fboundp 'org-remember))
  398. (let* ((parts (org-protocol-split-data info t))
  399. (template (or (and (= 1 (length (car parts))) (pop parts))
  400. org-protocol-default-template-key))
  401. (url (org-protocol-sanitize-uri (car parts)))
  402. (type (if (string-match "^\\([a-z]+\\):" url)
  403. (match-string 1 url)))
  404. (title (or (cadr parts) ""))
  405. (region (or (caddr parts) ""))
  406. (orglink (org-make-link-string
  407. url (if (string-match "[^[:space:]]" title) title url)))
  408. remember-annotation-functions)
  409. (setq org-stored-links
  410. (cons (list url title) org-stored-links))
  411. (kill-new orglink)
  412. (org-store-link-props :type type
  413. :link url
  414. :description title
  415. :initial region)
  416. (raise-frame)
  417. (org-remember nil (string-to-char template)))
  418. (message "Org-mode not loaded."))
  419. nil)
  420. (defun org-protocol-open-source (fname)
  421. "Process an org-protocol://open-source:// style url.
  422. Change a filename by mapping URLs to local filenames as set
  423. in `org-protocol-project-alist'.
  424. The location for a browser's bookmark should look like this:
  425. javascript:location.href='org-protocol://open-source://'+ \\
  426. encodeURIComponent(location.href)"
  427. ;; As we enter this function for a match on our protocol, the return value
  428. ;; defaults to nil.
  429. (let ((result nil)
  430. (f (org-protocol-unhex-string fname)))
  431. (catch 'result
  432. (dolist (prolist org-protocol-project-alist)
  433. (let* ((base-url (plist-get (cdr prolist) :base-url))
  434. (wsearch (regexp-quote base-url)))
  435. (when (string-match wsearch f)
  436. (let* ((wdir (plist-get (cdr prolist) :working-directory))
  437. (strip-suffix (plist-get (cdr prolist) :online-suffix))
  438. (add-suffix (plist-get (cdr prolist) :working-suffix))
  439. ;; Strip "[?#].*$" if `f' is a redirect with another
  440. ;; ending than strip-suffix here:
  441. (f1 (substring f 0 (string-match "\\([\\?#].*\\)?$" f)))
  442. (start-pos (+ (string-match wsearch f1) (length base-url)))
  443. (end-pos (string-match
  444. (regexp-quote strip-suffix) f1))
  445. ;; We have to compare redirects without suffix below:
  446. (f2 (concat wdir (substring f1 start-pos end-pos)))
  447. (the-file (concat f2 add-suffix)))
  448. ;; Note: the-file may still contain `%C3' et al here because browsers
  449. ;; tend to encode `&auml;' in URLs to `%25C3' - `%25' being `%'.
  450. ;; So the results may vary.
  451. ;; -- start redirects --
  452. (unless (file-exists-p the-file)
  453. (message "File %s does not exist.\nTesting for rewritten URLs." the-file)
  454. (let ((rewrites (plist-get (cdr prolist) :rewrites)))
  455. (when rewrites
  456. (message "Rewrites found: %S" rewrites)
  457. (mapc
  458. (lambda (rewrite)
  459. "Try to match a rewritten URL and map it to a real file."
  460. ;; Compare redirects without suffix:
  461. (if (string-match (car rewrite) f2)
  462. (throw 'result (concat wdir (cdr rewrite)))))
  463. rewrites))))
  464. ;; -- end of redirects --
  465. (if (file-readable-p the-file)
  466. (throw 'result the-file))
  467. (if (file-exists-p the-file)
  468. (message "%s: permission denied!" the-file)
  469. (message "%s: no such file or directory." the-file))))))
  470. result)))
  471. ;;; Core functions:
  472. (defun org-protocol-check-filename-for-protocol (fname restoffiles client)
  473. "Detect if `org-protocol-the-protocol' and a known sub-protocol is used in fname.
  474. Sub-protocols are registered in `org-protocol-protocol-alist' and
  475. `org-protocol-protocol-alist-default'.
  476. This is, how the matching is done:
  477. (string-match \"protocol:/+sub-protocol:/+\" ...)
  478. protocol and sub-protocol are regexp-quoted.
  479. If a matching protcol is found, the protcol is stripped from fname and the
  480. result is passed to the protocols function as the only parameter. If the
  481. function returns nil, the filename is removed from the list of filenames
  482. passed from emacsclient to the server.
  483. If the function returns a non nil value, that value is passed to the server
  484. as filename."
  485. (let ((sub-protocols (append org-protocol-protocol-alist org-protocol-protocol-alist-default)))
  486. (catch 'fname
  487. (let ((the-protocol (concat (regexp-quote org-protocol-the-protocol) ":/+")))
  488. (when (string-match the-protocol fname)
  489. (dolist (prolist sub-protocols)
  490. (let ((proto (concat the-protocol (regexp-quote (plist-get (cdr prolist) :protocol)) ":/+")))
  491. (when (string-match proto fname)
  492. (let* ((func (plist-get (cdr prolist) :function))
  493. (greedy (plist-get (cdr prolist) :greedy))
  494. (splitted (split-string fname proto))
  495. (result (if greedy restoffiles (cadr splitted))))
  496. (when (plist-get (cdr prolist) :kill-client)
  497. (message "Greedy org-protocol handler. Killing client.")
  498. (server-edit))
  499. (when (fboundp func)
  500. (unless greedy
  501. (throw 'fname (funcall func result)))
  502. (funcall func result)
  503. (throw 'fname t))))))))
  504. ;; (message "fname: %s" fname)
  505. fname)))
  506. (defadvice server-visit-files (before org-protocol-detect-protocol-server activate)
  507. "Advice server-visit-flist to call `org-protocol-modify-filename-for-protocol'."
  508. (let ((flist (if org-protocol-reverse-list-of-files
  509. (reverse (ad-get-arg 0))
  510. (ad-get-arg 0)))
  511. (client (ad-get-arg 1)))
  512. (catch 'greedy
  513. (dolist (var flist)
  514. (let ((fname (expand-file-name (car var)))) ;; `\' to `/' on windows. FIXME: could this be done any better?
  515. (setq fname (org-protocol-check-filename-for-protocol fname (member var flist) client))
  516. (if (eq fname t) ;; greedy? We need the `t' return value.
  517. (progn
  518. (ad-set-arg 0 nil)
  519. (throw 'greedy t))
  520. (if (stringp fname) ;; probably filename
  521. (setcar var fname)
  522. (ad-set-arg 0 (delq var (ad-get-arg 0))))))
  523. ))))
  524. ;;; Org specific functions:
  525. (defun org-protocol-create-for-org ()
  526. "Create a org-protocol project for the current file's Org-mode project.
  527. This works, if the file visited is part of a publishing project in
  528. `org-publish-project-alist'. This functions calls `org-protocol-create' to do
  529. most of the work."
  530. (interactive)
  531. (require 'org-publish)
  532. (org-publish-initialize-files-alist)
  533. (let ((all (or (org-publish-get-project-from-filename buffer-file-name))))
  534. (if all (org-protocol-create (cdr all))
  535. (message "Not in an org-project. Did mean %s?"
  536. (substitute-command-keys"\\[org-protocol-create]")))))
  537. (defun org-protocol-create(&optional project-plist)
  538. "Create a new org-protocol project interactively.
  539. An org-protocol project is an entry in `org-protocol-project-alist'
  540. which is used by `org-protocol-open-source'.
  541. Optionally use project-plist to initialize the defaults for this project. If
  542. project-plist is the CDR of an element in `org-publish-project-alist', reuse
  543. :base-directory, :html-extension and :base-extension."
  544. (interactive)
  545. (let ((working-dir (expand-file-name(or (plist-get project-plist :base-directory) default-directory)))
  546. (base-url "http://orgmode.org/worg/")
  547. (strip-suffix (or (plist-get project-plist :html-extension) ".html"))
  548. (working-suffix (if (plist-get project-plist :base-extension)
  549. (concat "." (plist-get project-plist :base-extension))
  550. ".org"))
  551. (worglet-buffer nil)
  552. (insert-default-directory t)
  553. (minibuffer-allow-text-properties nil))
  554. (setq base-url (read-string "Base URL of published content: " base-url nil base-url t))
  555. (if (not (string-match "\\/$" base-url))
  556. (setq base-url (concat base-url "/")))
  557. (setq working-dir
  558. (expand-file-name
  559. (read-directory-name "Local working directory: " working-dir working-dir t)))
  560. (if (not (string-match "\\/$" working-dir))
  561. (setq working-dir (concat working-dir "/")))
  562. (setq strip-suffix
  563. (read-string
  564. (concat "Extension to strip from published URLs ("strip-suffix"): ")
  565. strip-suffix nil strip-suffix t))
  566. (setq working-suffix
  567. (read-string
  568. (concat "Extension of editable files ("working-suffix"): ")
  569. working-suffix nil working-suffix t))
  570. (when (yes-or-no-p "Save the new org-protocol-project to your init file? ")
  571. (setq org-protocol-project-alist
  572. (cons `(,base-url . (:base-url ,base-url
  573. :working-directory ,working-dir
  574. :online-suffix ,strip-suffix
  575. :working-suffix ,working-suffix))
  576. org-protocol-project-alist))
  577. (customize-save-variable 'org-protocol-project-alist org-protocol-project-alist))))
  578. (provide 'org-protocol)
  579. ;; arch-tag: b5c5c2ac-77cf-4a94-a649-2163dff95846
  580. ;;; org-protocol.el ends here