1 ;;; org-protocol.el --- Intercept calls from emacsclient to trigger custom actions.
3 ;; Copyright (C) 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
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
14 ;; This file is part of GNU Emacs.
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
32 ;; Intercept calls from emacsclient to trigger custom actions.
34 ;; This is done by advising `server-visit-files' to scan the list of filenames
35 ;; for `org-protocol-the-protocol' and sub-protocols defined in
36 ;; `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'.
38 ;; Any application that supports calling external programs with an URL
39 ;; as argument may be used with this functionality.
45 ;; 1.) Add this to your init file (.emacs probably):
47 ;; (add-to-list 'load-path "/path/to/org-protocol/")
48 ;; (require 'org-protocol)
50 ;; 3.) Ensure emacs-server is up and running.
51 ;; 4.) Try this from the command line (adjust the URL as needed):
54 ;; org-protocol://store-link://http:%2F%2Flocalhost%2Findex.html/The%20title
56 ;; 5.) Optionally add custom sub-protocols and handlers:
58 ;; (setq org-protocol-protocol-alist
60 ;; :protocol "my-protocol"
61 ;; :function my-protocol-handler-function)))
63 ;; A "sub-protocol" will be found in URLs like this:
65 ;; org-protocol://sub-protocol://data
67 ;; If it works, you can now setup other applications for using this feature.
70 ;; As of March 2009 Firefox users follow the steps documented on
71 ;; http://kb.mozillazine.org/Register_protocol, Opera setup is described here:
72 ;; http://www.opera.com/support/kb/view/535/
78 ;; org-protocol.el comes with and installs handlers to open sources of published
79 ;; online content, store and insert the browser's URLs and cite online content
80 ;; by clicking on a bookmark in Firefox, Opera and probably other browsers and
83 ;; * `org-protocol-open-source' uses the sub-protocol \"open-source\" and maps
84 ;; URLs to local filenames defined in `org-protocol-project-alist'.
86 ;; * `org-protocol-store-link' stores an Org-link (if Org-mode is present) and
87 ;; pushes the browsers URL to the `kill-ring' for yanking. This handler is
88 ;; triggered through the sub-protocol \"store-link\".
90 ;; * Call `org-protocol-capture' by using the sub-protocol \"capture\". If
91 ;; Org-mode is loaded, Emacs will pop-up a capture buffer and fill the
92 ;; template with the data provided. I.e. the browser's URL is inserted as an
93 ;; Org-link of which the page title will be the description part. If text
94 ;; was select in the browser, that text will be the body of the entry.
96 ;; * Call `org-protocol-remember' by using the sub-protocol \"remember\".
97 ;; This is provided for backward compatibility.
98 ;; You may read `org-capture' as `org-remember' throughout this file if
99 ;; you still use `org-remember'.
101 ;; You may use the same bookmark URL for all those standard handlers and just
102 ;; adjust the sub-protocol used:
104 ;; location.href='org-protocol://sub-protocol://'+
105 ;; encodeURIComponent(location.href)+'/'+
106 ;; encodeURIComponent(document.title)+'/'+
107 ;; encodeURIComponent(window.getSelection())
109 ;; The handler for the sub-protocol \"capture\" detects an optional template
110 ;; char that, if present, triggers the use of a special template.
113 ;; location.href='org-protocol://sub-protocol://x/'+ ...
117 ;; Note, that using double slashes is optional from org-protocol.el's point of
118 ;; view because emacsclient squashes the slashes to one.
121 ;; provides: 'org-protocol
129 (declare-function org-publish-get-project-from-filename
"org-publish"
130 (filename &optional up
))
131 (declare-function server-edit
"server" (&optional arg
))
133 (define-obsolete-function-alias
134 'org-protocol-unhex-compound
'org-link-unescape-compound
137 (define-obsolete-function-alias
138 'org-protocol-unhex-string
'org-link-unescape
141 (define-obsolete-function-alias
142 'org-protocol-unhex-single-byte-sequence
143 'org-link-unescape-single-byte-sequence
146 (defgroup org-protocol nil
147 "Intercept calls from emacsclient to trigger custom actions.
149 This is done by advising `server-visit-files' to scann the list of filenames
150 for `org-protocol-the-protocol' and sub-procols defined in
151 `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'."
159 (defconst org-protocol-protocol-alist-default
160 '(("org-remember" :protocol
"remember" :function org-protocol-remember
:kill-client t
)
161 ("org-capture" :protocol
"capture" :function org-protocol-capture
:kill-client t
)
162 ("org-store-link" :protocol
"store-link" :function org-protocol-store-link
)
163 ("org-open-source" :protocol
"open-source" :function org-protocol-open-source
))
164 "Default protocols to use.
165 See `org-protocol-protocol-alist' for a description of this variable.")
167 (defconst org-protocol-the-protocol
"org-protocol"
168 "This is the protocol to detect if org-protocol.el is loaded.
169 `org-protocol-protocol-alist-default' and `org-protocol-protocol-alist' hold
170 the sub-protocols that trigger the required action. You will have to define
171 just one protocol handler OS-wide (MS-Windows) or per application (Linux).
172 That protocol handler should call emacsclient.")
176 (defcustom org-protocol-reverse-list-of-files t
177 "Non-nil means re-reverse the list of filenames passed on the command line.
178 The filenames passed on the command line are passed to the emacs-server in
179 reverse order. Set to t (default) to re-reverse the list, i.e. use the
180 sequence on the command line. If nil, the sequence of the filenames is
185 (defcustom org-protocol-project-alist nil
186 "Map URLs to local filenames for `org-protocol-open-source' (open-source).
188 Each element of this list must be of the form:
190 (module-name :property value property: value ...)
192 where module-name is an arbitrary name. All the values are strings.
194 Possible properties are:
196 :online-suffix - the suffix to strip from the published URLs
197 :working-suffix - the replacement for online-suffix
198 :base-url - the base URL, e.g. http://www.example.com/project/
200 :working-directory - the local working directory. This is, what base-url will
202 :redirects - A list of cons cells, each of which maps a regular
203 expression to match to a path relative to :working-directory.
207 (setq org-protocol-project-alist
208 '((\"http://orgmode.org/worg/\"
209 :online-suffix \".php\"
210 :working-suffix \".org\"
211 :base-url \"http://orgmode.org/worg/\"
212 :working-directory \"/home/user/org/Worg/\")
213 (\"http://localhost/org-notes/\"
214 :online-suffix \".html\"
215 :working-suffix \".org\"
216 :base-url \"http://localhost/org/\"
217 :working-directory \"/home/user/org/\"
218 :rewrites ((\"org/?$\" . \"index.php\")))))
220 The last line tells `org-protocol-open-source' to open
221 /home/user/org/index.php, if the URL cannot be mapped to an existing
222 file, and ends with either \"org\" or \"org/\".
224 Consider using the interactive functions `org-protocol-create' and
225 `org-protocol-create-for-org' to help you filling this variable with valid contents."
229 (defcustom org-protocol-protocol-alist nil
230 "* Register custom handlers for org-protocol.
232 Each element of this list must be of the form:
234 (module-name :protocol protocol :function func :kill-client nil)
236 protocol - protocol to detect in a filename without trailing colon and slashes.
237 See rfc1738 section 2.1 for more on this.
238 If you define a protocol \"my-protocol\", `org-protocol-check-filename-for-protocol'
239 will search filenames for \"org-protocol:/my-protocol:/\"
240 and trigger your action for every match. `org-protocol' is defined in
241 `org-protocol-the-protocol'. Double and triple slashes are compressed
242 to one by emacsclient.
244 function - function that handles requests with protocol and takes exactly one
245 argument: the filename with all protocols stripped. If the function
246 returns nil, emacsclient and -server do nothing. Any non-nil return
247 value is considered a valid filename and thus passed to the server.
249 `org-protocol.el provides some support for handling those filenames,
250 if you stay with the conventions used for the standard handlers in
251 `org-protocol-protocol-alist-default'. See `org-protocol-split-data'.
253 kill-client - If t, kill the client immediately, once the sub-protocol is
254 detected. This is necessary for actions that can be interrupted by
255 `C-g' to avoid dangling emacsclients. Note, that all other command
256 line arguments but the this one will be discarded, greedy handlers
257 still receive the whole list of arguments though.
261 (setq org-protocol-protocol-alist
263 :protocol \"my-protocol\"
264 :function my-protocol-handler-function)
266 :protocol \"your-protocol\"
267 :function your-protocol-handler-function)))"
271 (defcustom org-protocol-default-template-key nil
272 "The default template key to use.
273 This is usually a single character string but can also be a
274 string with two characters."
278 ;;; Helper functions:
280 (defun org-protocol-sanitize-uri (uri)
281 "emacsclient compresses double and triple slashes.
282 Slashes are sanitized to double slashes here."
283 (when (string-match "^\\([a-z]+\\):/" uri
)
284 (let* ((splitparts (split-string uri
"/+")))
285 (setq uri
(concat (car splitparts
) "//" (mapconcat 'identity
(cdr splitparts
) "/")))))
288 (defun org-protocol-split-data (data &optional unhexify separator
)
289 "Split what an org-protocol handler function gets as only argument.
290 DATA is that one argument. DATA is split at each occurrence of
291 SEPARATOR (regexp). If no SEPARATOR is specified or SEPARATOR is
292 nil, assume \"/+\". The results of that splitting are returned
293 as a list. If UNHEXIFY is non-nil, hex-decode each split part.
294 If UNHEXIFY is a function, use that function to decode each split
296 (let* ((sep (or separator
"/+"))
297 (split-parts (split-string data sep
)))
299 (if (fboundp unhexify
)
300 (mapcar unhexify split-parts
)
301 (mapcar 'org-link-unescape split-parts
))
304 (defun org-protocol-flatten-greedy (param-list &optional strip-path replacement
)
305 "Greedy handlers might receive a list like this from emacsclient:
306 '((\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\")
307 where \"/dir/\" is the absolute path to emacsclients working directory. This
308 function transforms it into a flat list using `org-protocol-flatten' and
309 transforms the elements of that list as follows:
311 If strip-path is non-nil, remove the \"/dir/\" prefix from all members of
314 If replacement is string, replace the \"/dir/\" prefix with it.
316 The first parameter, the one that contains the protocols, is always changed.
317 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
323 (let* ((l (org-protocol-flatten (if org-protocol-reverse-list-of-files
325 (reverse param-list
))))
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
))))
341 (if (stringp replacement
)
342 (setq e
(concat replacement
(substring e len
)))
343 (setq e
(substring e len
)))
348 (defun org-protocol-flatten (l)
349 "Greedy handlers might receive a list like this from emacsclient:
350 '( (\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\")
351 where \"/dir/\" is the absolute path to emacsclients working directory.
352 This function transforms it into a flat list."
355 (append (org-protocol-flatten (car l
)) (org-protocol-flatten (cdr l
)))
359 ;;; Standard protocol handlers:
361 (defun org-protocol-store-link (fname)
362 "Process an org-protocol://store-link:// style url.
363 Additionally store a browser URL as an org link. Also pushes the
364 link's URL to the `kill-ring'.
366 The location for a browser's bookmark has to look like this:
368 javascript:location.href='org-protocol://store-link://'+ \\
369 encodeURIComponent(location.href)
370 encodeURIComponent(document.title)+'/'+ \\
372 Don't use `escape()'! Use `encodeURIComponent()' instead. The title of the page
373 could contain slashes and the location definitely will.
375 The sub-protocol used to reach this function is set in
376 `org-protocol-protocol-alist'."
377 (let* ((splitparts (org-protocol-split-data fname t
))
378 (uri (org-protocol-sanitize-uri (car splitparts
)))
379 (title (cadr splitparts
))
381 (if (boundp 'org-stored-links
)
382 (setq org-stored-links
(cons (list uri title
) org-stored-links
)))
384 (message "`%s' to insert new org-link, `%s' to insert `%s'"
385 (substitute-command-keys"\\[org-insert-link]")
386 (substitute-command-keys"\\[yank]")
390 (defun org-protocol-remember (info)
391 "Process an org-protocol://remember:// style url.
393 The location for a browser's bookmark has to look like this:
395 javascript:location.href='org-protocol://remember://'+ \\
396 encodeURIComponent(location.href)+'/' \\
397 encodeURIComponent(document.title)+'/'+ \\
398 encodeURIComponent(window.getSelection())
400 See the docs for `org-protocol-capture' for more information."
402 (if (and (boundp 'org-stored-links
)
403 (fboundp 'org-capture
)
404 (org-protocol-do-capture info
'org-remember
))
405 (message "Item remembered."))
408 (defun org-protocol-capture (info)
409 "Process an org-protocol://capture:// style url.
411 The sub-protocol used to reach this function is set in
412 `org-protocol-protocol-alist'.
414 This function detects an URL, title and optional text, separated by '/'
415 The location for a browser's bookmark has to look like this:
417 javascript:location.href='org-protocol://capture://'+ \\
418 encodeURIComponent(location.href)+'/' \\
419 encodeURIComponent(document.title)+'/'+ \\
420 encodeURIComponent(window.getSelection())
422 By default, it uses the character `org-protocol-default-template-key',
423 which should be associated with a template in `org-capture-templates'.
424 But you may prepend the encoded URL with a character and a slash like so:
426 javascript:location.href='org-protocol://capture://b/'+ ...
428 Now template ?b will be used."
429 (if (and (boundp 'org-stored-links
)
430 (fboundp 'org-capture
)
431 (org-protocol-do-capture info
'org-capture
))
432 (message "Item captured."))
435 (defun org-protocol-do-capture (info capture-func
)
436 "Support `org-capture' and `org-remember' alike.
437 CAPTURE-FUNC is either the symbol `org-remember' or `org-capture'."
438 (let* ((parts (org-protocol-split-data info t
))
439 (template (or (and (>= 2 (length (car parts
))) (pop parts
))
440 org-protocol-default-template-key
))
441 (url (org-protocol-sanitize-uri (car parts
)))
442 (type (if (string-match "^\\([a-z]+\\):" url
)
443 (match-string 1 url
)))
444 (title (or (cadr parts
) ""))
445 (region (or (caddr parts
) ""))
446 (orglink (org-make-link-string
447 url
(if (string-match "[^[:space:]]" title
) title url
)))
448 (org-capture-link-is-already-stored t
) ;; avoid call to org-store-link
449 remember-annotation-functions
)
450 (setq org-stored-links
451 (cons (list url title
) org-stored-links
))
453 (org-store-link-props :type type
459 (funcall capture-func nil template
)))
461 (defun org-protocol-open-source (fname)
462 "Process an org-protocol://open-source:// style url.
464 Change a filename by mapping URLs to local filenames as set
465 in `org-protocol-project-alist'.
467 The location for a browser's bookmark should look like this:
469 javascript:location.href='org-protocol://open-source://'+ \\
470 encodeURIComponent(location.href)"
471 ;; As we enter this function for a match on our protocol, the return value
474 (f (org-link-unescape fname
)))
476 (dolist (prolist org-protocol-project-alist
)
477 (let* ((base-url (plist-get (cdr prolist
) :base-url
))
478 (wsearch (regexp-quote base-url
)))
480 (when (string-match wsearch f
)
481 (let* ((wdir (plist-get (cdr prolist
) :working-directory
))
482 (strip-suffix (plist-get (cdr prolist
) :online-suffix
))
483 (add-suffix (plist-get (cdr prolist
) :working-suffix
))
484 ;; Strip "[?#].*$" if `f' is a redirect with another
485 ;; ending than strip-suffix here:
486 (f1 (substring f
0 (string-match "\\([\\?#].*\\)?$" f
)))
487 (start-pos (+ (string-match wsearch f1
) (length base-url
)))
488 (end-pos (string-match
489 (regexp-quote strip-suffix
) f1
))
490 ;; We have to compare redirects without suffix below:
491 (f2 (concat wdir
(substring f1 start-pos end-pos
)))
492 (the-file (concat f2 add-suffix
)))
494 ;; Note: the-file may still contain `%C3' et al here because browsers
495 ;; tend to encode `ä' in URLs to `%25C3' - `%25' being `%'.
496 ;; So the results may vary.
498 ;; -- start redirects --
499 (unless (file-exists-p the-file
)
500 (message "File %s does not exist.\nTesting for rewritten URLs." the-file
)
501 (let ((rewrites (plist-get (cdr prolist
) :rewrites
)))
503 (message "Rewrites found: %S" rewrites
)
506 "Try to match a rewritten URL and map it to a real file."
507 ;; Compare redirects without suffix:
508 (if (string-match (car rewrite
) f2
)
509 (throw 'result
(concat wdir
(cdr rewrite
)))))
511 ;; -- end of redirects --
513 (if (file-readable-p the-file
)
514 (throw 'result the-file
))
515 (if (file-exists-p the-file
)
516 (message "%s: permission denied!" the-file
)
517 (message "%s: no such file or directory." the-file
))))))
523 (defun org-protocol-check-filename-for-protocol (fname restoffiles client
)
524 "Detect if `org-protocol-the-protocol' and a known sub-protocol is used in fname.
525 Sub-protocols are registered in `org-protocol-protocol-alist' and
526 `org-protocol-protocol-alist-default'.
527 This is, how the matching is done:
529 (string-match \"protocol:/+sub-protocol:/+\" ...)
531 protocol and sub-protocol are regexp-quoted.
533 If a matching protocol is found, the protocol is stripped from fname and the
534 result is passed to the protocols function as the only parameter. If the
535 function returns nil, the filename is removed from the list of filenames
536 passed from emacsclient to the server.
537 If the function returns a non nil value, that value is passed to the server
539 (let ((sub-protocols (append org-protocol-protocol-alist
540 org-protocol-protocol-alist-default
)))
542 (let ((the-protocol (concat (regexp-quote org-protocol-the-protocol
) ":/+")))
543 (when (string-match the-protocol fname
)
544 (dolist (prolist sub-protocols
)
545 (let ((proto (concat the-protocol
546 (regexp-quote (plist-get (cdr prolist
) :protocol
)) ":/+")))
547 (when (string-match proto fname
)
548 (let* ((func (plist-get (cdr prolist
) :function
))
549 (greedy (plist-get (cdr prolist
) :greedy
))
550 (splitted (split-string fname proto
))
551 (result (if greedy restoffiles
(cadr splitted
))))
552 (when (plist-get (cdr prolist
) :kill-client
)
553 (message "Greedy org-protocol handler. Killing client.")
557 (throw 'fname
(funcall func result
)))
558 (funcall func result
)
559 (throw 'fname t
))))))))
560 ;; (message "fname: %s" fname)
563 (defadvice server-visit-files
(before org-protocol-detect-protocol-server activate
)
564 "Advice server-visit-flist to call `org-protocol-modify-filename-for-protocol'."
565 (let ((flist (if org-protocol-reverse-list-of-files
566 (reverse (ad-get-arg 0))
568 (client (ad-get-arg 1)))
571 ;; `\' to `/' on windows. FIXME: could this be done any better?
572 (let ((fname (expand-file-name (car var
))))
573 (setq fname
(org-protocol-check-filename-for-protocol
574 fname
(member var flist
) client
))
575 (if (eq fname t
) ;; greedy? We need the `t' return value.
579 (if (stringp fname
) ;; probably filename
581 (ad-set-arg 0 (delq var
(ad-get-arg 0))))))))))
583 ;;; Org specific functions:
585 (defun org-protocol-create-for-org ()
586 "Create a org-protocol project for the current file's Org-mode project.
587 This works, if the file visited is part of a publishing project in
588 `org-publish-project-alist'. This function calls `org-protocol-create' to do
591 (require 'org-publish
)
592 (let ((all (or (org-publish-get-project-from-filename buffer-file-name
))))
593 (if all
(org-protocol-create (cdr all
))
594 (message "Not in an org-project. Did mean %s?"
595 (substitute-command-keys"\\[org-protocol-create]")))))
597 (defun org-protocol-create (&optional project-plist
)
598 "Create a new org-protocol project interactively.
599 An org-protocol project is an entry in `org-protocol-project-alist'
600 which is used by `org-protocol-open-source'.
601 Optionally use project-plist to initialize the defaults for this project. If
602 project-plist is the CDR of an element in `org-publish-project-alist', reuse
603 :base-directory, :html-extension and :base-extension."
605 (let ((working-dir (expand-file-name
606 (or (plist-get project-plist
:base-directory
)
608 (base-url "http://orgmode.org/worg/")
609 (strip-suffix (or (plist-get project-plist
:html-extension
) ".html"))
610 (working-suffix (if (plist-get project-plist
:base-extension
)
611 (concat "." (plist-get project-plist
:base-extension
))
614 (insert-default-directory t
)
615 (minibuffer-allow-text-properties nil
))
617 (setq base-url
(read-string "Base URL of published content: " base-url nil base-url t
))
618 (if (not (string-match "\\/$" base-url
))
619 (setq base-url
(concat base-url
"/")))
623 (read-directory-name "Local working directory: " working-dir working-dir t
)))
624 (if (not (string-match "\\/$" working-dir
))
625 (setq working-dir
(concat working-dir
"/")))
629 (concat "Extension to strip from published URLs (" strip-suffix
"): ")
630 strip-suffix nil strip-suffix t
))
634 (concat "Extension of editable files (" working-suffix
"): ")
635 working-suffix nil working-suffix t
))
637 (when (yes-or-no-p "Save the new org-protocol-project to your init file? ")
638 (setq org-protocol-project-alist
639 (cons `(,base-url .
(:base-url
,base-url
640 :working-directory
,working-dir
641 :online-suffix
,strip-suffix
642 :working-suffix
,working-suffix
))
643 org-protocol-project-alist
))
644 (customize-save-variable 'org-protocol-project-alist org-protocol-project-alist
))))
646 (provide 'org-protocol
)
648 ;; arch-tag: b5c5c2ac-77cf-4a94-a649-2163dff95846
649 ;;; org-protocol.el ends here