Release 6.25b
[org-mode.git] / lisp / org-protocol.el
blob6ad0008750e60e6eed38ab0b6bed4c32d00ab850
1 ;;; org-protocol.el --- Intercept calls from emacsclient to trigger custom actions.
2 ;;
3 ;; Copyright (c) 2008, 2009
4 ;; Bastien Guerry <bzg AT altern DOT org>,
5 ;; Daniel German <dmg AT uvic DOT org>,
6 ;; Sebastian Rose <sebastian_rose AT gmx DOT de>,
7 ;; Ross Patterson <me AT rpatterson DOT net>
8 ;; David Moffat
9 ;; (will be FSF when done)
12 ;; Filename: org-protocol.el
13 ;; Version: 6.25b
14 ;; Author: Bastien Guerry <bzg AT altern DOT org>
15 ;; Author: Daniel M German <dmg AT uvic DOT org>
16 ;; Author: Sebastian Rose <sebastian_rose AT gmx DOT de>
17 ;; Author: Ross Patterson <me AT rpatterson DOT net>
18 ;; Maintainer: Sebastian Rose <sebastian_rose AT gmx DOT de>
19 ;; Keywords: org, emacsclient, wp
21 ;; This file is not part of GNU Emacs.
23 ;; This program is free software: you can redistribute it and/or modify
24 ;; it under the terms of the GNU General Public License as published by
25 ;; the Free Software Foundation, either version 3 of the License, or
26 ;; (at your option) any later version.
28 ;; This program is distributed in the hope that it will be useful,
29 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
30 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 ;; GNU General Public License for more details.
33 ;; See <http://www.gnu.org/licenses/>.
35 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
36 ;;; Commentary:
38 ;; Intercept calls from emacsclient to trigger custom actions.
40 ;; This is done by advising `server-visit-files' to scann the list of filenames
41 ;; for `org-protocol-the-protocol' and sub-procols defined in
42 ;; `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'.
44 ;; Any application that supports calling external programs with an URL
45 ;; as argument may be used with this functionality.
48 ;; Usage:
49 ;; ------
51 ;; 1.) Add this to your init file (.emacs probably):
53 ;; (add-to-list 'load-path "/path/to/org-protocol/")
54 ;; (require 'org-protocol)
56 ;; 3.) Ensure emacs-server is up and running.
57 ;; 4.) Try this from the command line (adjust the URL as needed):
59 ;; $ emacsclient \
60 ;; org-protocol://store-link://http:%2F%2Flocalhost%2Findex.html/The%20title
62 ;; 5.) Optionally add custom sub-protocols and handlers:
64 ;; (setq org-protocol-protocol-alist
65 ;; '(("my-protocol"
66 ;; :protocol "my-protocol"
67 ;; :function my-protocol-handler-fuction)))
69 ;; A "sub-protocol" will be found in URLs like this:
71 ;; org-protocol://sub-protocol://data
73 ;; If it works, you can now setup other applications for using this feature.
76 ;; As of March 2009 Firefox users follow the steps documented on
77 ;; http://kb.mozillazine.org/Register_protocol, Opera setup is described here:
78 ;; http://www.opera.com/support/kb/view/535/
81 ;; Documentation
82 ;; -------------
84 ;; org-protocol.el comes with and installs handlers to open sources of published
85 ;; online content, store and insert the browser's URLs and cite online content
86 ;; by clicking on a bookmark in Firefox, Opera and probably other browsers and
87 ;; applications:
89 ;; * `org-protocol-open-source' uses the sub-protocol \"open-source\" and maps
90 ;; URLs to local filenames defined in `org-protocol-project-alist'.
92 ;; * `org-protocol-store-link' stores an Org-link (if Org-mode is present) and
93 ;; pushes the browsers URL to the `kill-ring' for yanking. This handler is
94 ;; triggered through the sub-protocol \"store-link\".
96 ;; * Call `org-protocol-remember' by using the sub-protocol \"remember\". If
97 ;; Org-mode is loaded, emacs will popup a remember buffer and fill the
98 ;; template with the data provided. I.e. the browser's URL is inserted as an
99 ;; Org-link of which the page title will be the description part. If text
100 ;; was select in the browser, that text will be the body of the entry.
102 ;; You may use the same bookmark URL for all those standard handlers and just
103 ;; adjust the sub-protocol used:
105 ;; location.href='org-protocol://sub-protocol://'+
106 ;; encodeURIComponent(location.href)+'/'+
107 ;; encodeURIComponent(document.title)+'/'+
108 ;; encodeURIComponent(window.getSelection())
110 ;; The handler for the sub-protocol \"remember\" detects an optional template
111 ;; char that, if present, triggers the use of a special template.
112 ;; Example:
114 ;; location.href='org-protocol://sub-protocol://x/'+ ...
116 ;; use template ?x.
118 ;; Note, that using double shlashes is optional from org-protocol.el's point of
119 ;; view because emacsclient sqashes the slashes to one.
122 ;; provides: 'org-protocol
124 ;;; Code:
126 (require 'org)
127 (require 'url)
128 (eval-when-compile
129 (require 'cl))
131 (declare-function org-publish-initialize-files-alist "org-publish"
132 (&optional refresh))
133 (declare-function org-publish-get-project-from-filename "org-publish"
134 (filename &optional up))
136 (defgroup org-protocol nil
137 "Intercept calls from emacsclient to trigger custom actions.
139 This is done by advising `server-visit-files' to scann the list of filenames
140 for `org-protocol-the-protocol' and sub-procols defined in
141 `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'."
142 :version "22.1"
143 :group 'convenience
144 :group 'org)
147 ;;; Variables:
149 (defconst org-protocol-protocol-alist-default
150 '(("org-remember" :protocol "remember" :function org-protocol-remember :kill-client t)
151 ("org-store-link" :protocol "store-link" :function org-protocol-store-link)
152 ("org-open-source" :protocol "open-source" :function org-protocol-open-source))
153 "Default protocols to use.
154 See `org-protocol-protocol-alist' for a description of this variable.")
157 (defconst org-protocol-the-protocol "org-protocol"
158 "This is the protocol to detect if org-protocol.el is loaded.
159 `org-protocol-protocol-alist-default' and `org-protocol-protocol-alist' hold the
160 sub-protocols that trigger the required action. You will have to define just one
161 protocol handler OS-wide (MS-Windows) or per application (Linux). That protocol
162 handler should call emacsclient.")
165 ;;; User variables:
167 (defcustom org-protocol-reverse-list-of-files t
168 "* The filenames passed on the commandline are passed to the emacs-server in
169 reversed order. Set to `t' (default) to re-reverse the list, i.e. use the
170 sequence on the command line. If nil, the sequence of the filenames is
171 unchanged."
172 :group 'org-protocol
173 :type 'boolean)
176 (defcustom org-protocol-project-alist nil
177 "* Map URLs to local filenames for `org-protocol-open-source' (open-source).
179 Each element of this list must be of the form:
181 (module-name :property value property: value ...)
183 where module-name is an arbitrary name. All the values are strings.
185 Possible properties are:
187 :online-suffix - the suffix to strip from the published URLs
188 :working-suffix - the replacement for online-suffix
189 :base-url - the base URL, e.g. http://www.example.com/project/
190 Last slash required.
191 :working-directory - the local working directory. This is, what base-url will
192 be replaced with.
194 Example:
196 (setq org-protocol-project-alist
197 '((\"http://orgmode.org/worg/\"
198 :online-suffix \".php\"
199 :working-suffix \".org\"
200 :base-url \"http://orgmode.org/worg/\"
201 :working-directory \"/home/user/org/Worg/\")
202 (\"http://localhost/org-notes/\"
203 :online-suffix \".html\"
204 :working-suffix \".org\"
205 :base-url \"http://localhost/org/\"
206 :working-directory \"/home/user/org/\")))
208 Consider using the interactive functions `org-protocol-create' and
209 `org-protocol-create-for-org' to help you filling this variable with valid contents."
210 :group 'org-protocol
211 :type 'alist)
214 (defcustom org-protocol-protocol-alist nil
215 "* Register custom handlers for org-protocol.
217 Each element of this list must be of the form:
219 (module-name :protocol protocol :function func :kill-client nil)
221 protocol - protocol to detect in a filename without trailing colon and slashes.
222 See rfc1738 section 2.1 for more on this.
223 If you define a protocol \"my-protocol\", `org-protocol-check-filename-for-protocol'
224 will search filenames for \"org-protocol:/my-protocol:/\"
225 and trigger your action for every match. `org-protocol' is defined in
226 `org-protocol-the-protocol'. Double and tripple slashes are compressed
227 to one by emacsclient.
229 function - function that handles requests with protocol and takes exactly one
230 argument: the filename with all protocols stripped. If the function
231 returns nil, emacsclient and -server do nothing. Any non-nil return
232 value is considered a valid filename and thus passed to the server.
234 `org-protocol.el provides some support for handling those filenames,
235 if you stay with the conventions used for the standard handlers in
236 `org-protocol-protocol-alist-default'. See `org-protocol-split-data'.
238 kill-client - If t, kill the client immediately, once the sub-protocol is
239 detected. This is neccessary for actions that can be interupted by
240 `C-g' to avoid dangeling emacsclients. Note, that all other command
241 line arguments but the this one will be discarded, greedy handlers
242 still receive the whole list of arguments though.
244 Here is an example:
246 (setq org-protocol-protocol-alist
247 '((\"my-protocol\"
248 :protocol \"my-protocol\"
249 :function my-protocol-handler-fuction)
250 (\"your-protocol\"
251 :protocol \"your-protocol\"
252 :function your-protocol-handler-fuction)))"
253 :group 'org-protocol
254 :type '(alist))
257 ;;; Helper functions:
259 (defun org-protocol-sanitize-uri (uri)
260 "emacsclient compresses double and tripple slashes.
261 Slashes are sanitized to double slashes here."
262 (when (string-match "^\\([a-z]+\\):/" uri)
263 (let* ((splitparts (split-string uri "/+")))
264 (setq uri (concat (car splitparts) "//" (mapconcat 'identity (cdr splitparts) "/")))))
265 uri)
268 (defun org-protocol-split-data(data &optional unhexify separator)
269 "Split, what a org-protocol handler function gets as only argument.
270 data is that one argument. Data is splitted at each occurrence of separator
271 (regexp). If no separator is specified or separator is nil, assume \"/+\".
272 The results of that splitting are return as a list. If unhexify is non-nil,
273 hex-decode each split part."
274 (let* ((sep (or separator "/+"))
275 (split-parts (split-string data sep)))
276 (if unhexify
277 (mapcar 'url-unhex-string split-parts)
278 split-parts)))
281 ;;; Standard protocol handlers:
283 (defun org-protocol-store-link (fname)
284 "Process an org-protocol://store-link:// style url
285 and store a browser URL as an org link. Also pushes the links URL to the
286 `kill-ring'.
288 The location for a browser's bookmark has to look like this:
290 javascript:location.href='org-protocol://store-link://'+ \\
291 encodeURIComponent(location.href)
292 encodeURIComponent(document.title)+'/'+ \\
294 Don't use `escape()'! Use `encodeURIComponent()' instead. The title of the page
295 could contain slashes and the location definitely will.
297 The sub-protocol used to reach this function is set in
298 `org-protocol-protocol-alist'."
299 (let* ((splitparts (org-protocol-split-data fname t))
300 (uri (org-protocol-sanitize-uri (car splitparts)))
301 (title (cadr splitparts))
302 orglink)
303 (if (boundp 'org-stored-links)
304 (setq org-stored-links (cons (list uri title) org-stored-links)))
305 (kill-new uri)
306 (message "`%s' to insert new org-link, `%s' to insert `%s'"
307 (substitute-command-keys"\\[org-insert-link]")
308 (substitute-command-keys"\\[yank]")
309 uri))
310 nil)
313 (defun org-protocol-remember (info)
314 "Process an org-protocol://remember:// style url.
316 The sub-protocol used to reach this function is set in
317 `org-protocol-protocol-alist'.
319 This function detects an URL, title and optinal text, separated by '/'
320 The location for a browser's bookmark has to look like this:
322 javascript:location.href='org-protocol://remember://'+ \\
323 encodeURIComponent(location.href)+ \\
324 encodeURIComponent(document.title)+'/'+ \\
325 encodeURIComponent(window.getSelection())
327 By default the template character ?w is used. But you may prepend the encoded
328 URL with a character and a slash like so:
330 javascript:location.href='org-protocol://org-store-link://b/'+ ...
332 Now template ?b will be used."
334 (if (and (boundp 'org-stored-links)
335 (fboundp 'org-remember))
336 (let* ((parts (org-protocol-split-data info t))
337 (template (or (and (= 1 (length (car parts))) (pop parts)) "w"))
338 (url (org-protocol-sanitize-uri (car parts)))
339 (type (if (string-match "^\\([a-z]+\\):" url)
340 (match-string 1 url)))
341 (title (cadr parts))
342 (region (caddr parts))
343 (orglink (org-make-link-string url title))
344 remember-annotation-functions)
345 (setq org-stored-links
346 (cons (list url title) org-stored-links))
347 (kill-new orglink)
348 (org-store-link-props :type type
349 :link url
350 :description title
351 :initial region)
352 (raise-frame)
353 (org-remember nil (string-to-char template)))
355 (message "Org-mode not loaded."))
356 nil)
359 (defun org-protocol-open-source (fname)
360 "Process an org-protocol://open-source:// style url.
362 Change a filename by mapping URLs to local filenames as set
363 in `org-protocol-project-alist'.
365 The location for a browser's bookmark should look like this:
367 javascript:location.href='org-protocol://open-source://'+ \\
368 encodeURIComponent(location.href)"
370 ;; As we enter this function for a match on our protocol, the return value
371 ;; defaults to nil.
372 (let ((result nil)
373 (f (url-unhex-string fname)))
374 (catch 'result
375 (dolist (prolist org-protocol-project-alist)
376 (let* ((base-url (plist-get (cdr prolist) :base-url))
377 (wsearch (regexp-quote base-url)))
379 (when (string-match wsearch f)
380 (let* ((wdir (plist-get (cdr prolist) :working-directory))
381 (strip-suffix (plist-get (cdr prolist) :online-suffix))
382 (add-suffix (plist-get (cdr prolist) :working-suffix))
383 (start-pos (+ (string-match wsearch f) (length base-url)))
384 (end-pos (string-match
385 (concat (regexp-quote strip-suffix) "\\([?#].*\\)?$") f))
386 (the-file (concat wdir (substring f start-pos end-pos) add-suffix)))
387 (if (file-readable-p the-file)
388 (throw 'result the-file))
389 (if (file-exists-p the-file)
390 (message "%s: permission denied!" the-file)
391 (message "%s: no such file or directory." the-file))))))
392 result)))
395 ;;; Core functions:
397 (defun org-protocol-check-filename-for-protocol (fname restoffiles client)
398 "Detect if `org-protocol-the-protocol' and a known sub-protocol is used in fname.
399 Sub-protocols are registered in `org-protocol-protocol-alist' and
400 `org-protocol-protocol-alist-default'.
401 This is, how the matching is done:
403 (string-match \"protocol:/+sub-protocol:/+\" ...)
405 protocol and sub-protocol are regexp-quoted.
407 If a matching protcol is found, the protcol is stripped from fname and the
408 result is passed to the protocols function as the only parameter. If the
409 function returns nil, the filename is removed from the list of filenames
410 passed from emacsclient to the server.
411 If the function returns a non nil value, that value is passed to the server
412 as filename."
413 (let ((sub-protocols (append org-protocol-protocol-alist org-protocol-protocol-alist-default)))
414 (catch 'fname
415 (let ((the-protocol (concat (regexp-quote org-protocol-the-protocol) ":/+")))
416 (when (string-match the-protocol fname)
417 (dolist (prolist sub-protocols)
418 (let ((proto (concat the-protocol (regexp-quote (plist-get (cdr prolist) :protocol)) ":/+")))
419 (when (string-match proto fname)
420 (let* ((func (plist-get (cdr prolist) :function))
421 (greedy (plist-get (cdr prolist) :greedy))
422 (splitted (split-string fname proto))
423 (result (if greedy restoffiles (cadr splitted))))
424 (if (plist-get (cdr prolist) :kill-client)
425 (server-delete-client client t))
426 (when (fboundp func)
427 (unless greedy
428 (throw 'fname (funcall func result)))
429 (funcall func result)
430 (throw 'fname t))))))))
431 ;; (message "fname: %s" fname)
432 fname)))
435 (defadvice server-visit-files (before org-protocol-detect-protocol-server activate)
436 "Advice server-visit-flist to call `org-protocol-modify-filename-for-protocol'."
437 (let ((flist (if org-protocol-reverse-list-of-files
438 (reverse (ad-get-arg 0))
439 (ad-get-arg 0)))
440 (client (ad-get-arg 1)))
441 (catch 'greedy
442 (dolist (var flist)
443 (let ((fname (expand-file-name (car var)))) ;; `\' to `/' on windows. FIXME: could this be done any better?
444 (setq fname (org-protocol-check-filename-for-protocol fname (member var flist) client))
445 (if (eq fname t) ;; greedy? We need the `t' return value.
446 (progn
447 (ad-set-arg 0 nil)
448 (throw 'greedy t))
449 (if (stringp fname) ;; probably filename
450 (setcar var fname)
451 (ad-set-arg 0 (delq var (ad-get-arg 0))))))
452 ))))
454 ;;; Org specific functions:
456 (defun org-protocol-create-for-org ()
457 "Create a org-protocol project for the current file's Org-mode project.
458 This works, if the file visited is part of a publishing project in
459 `org-publish-project-alist'. This functions calls `org-protocol-create' to do
460 most of the work."
461 (interactive)
462 (require 'org-publish)
463 (org-publish-initialize-files-alist)
464 (let ((all (or (org-publish-get-project-from-filename buffer-file-name))))
465 (if all (org-protocol-create (cdr all))
466 (message "Not in an org-project. Did mean %s?"
467 (substitute-command-keys"\\[org-protocol-create]")))))
471 (defun org-protocol-create(&optional project-plist)
472 "Create a new org-protocol project interactively.
473 An org-protocol project is an entry in `org-protocol-project-alist'
474 which is used by `org-protocol-open-source'.
475 Optionally use project-plist to initialize the defaults for this worglet. If
476 project-plist is the CDR of an element in `org-publish-project-alist', reuse
477 :base-directory, :html-extension and :base-extension."
478 (interactive)
479 (let ((working-dir (expand-file-name(or (plist-get project-plist :base-directory) default-directory)))
480 (base-url "http://orgmode.org/worg/")
481 (strip-suffix (or (plist-get project-plist :html-extension) ".html"))
482 (working-suffix (if (plist-get project-plist :base-extension)
483 (concat "." (plist-get project-plist :base-extension))
484 ".org"))
486 (worglet-buffer nil)
488 (insert-default-directory t)
489 (minibuffer-allow-text-properties nil))
491 (setq base-url (read-string "Base URL of published content: " base-url nil base-url t))
492 (if (not (string-match "\\/$" base-url))
493 (setq base-url (concat base-url "/")))
495 (setq working-dir
496 (expand-file-name
497 (read-directory-name "Local working directory: " working-dir working-dir t)))
498 (if (not (string-match "\\/$" working-dir))
499 (setq working-dir (concat working-dir "/")))
501 (setq strip-suffix
502 (read-string
503 (concat "Extension to strip from published URLs ("strip-suffix"): ")
504 strip-suffix nil strip-suffix t))
506 (setq working-suffix
507 (read-string
508 (concat "Extension of editable files ("working-suffix"): ")
509 working-suffix nil working-suffix t))
511 (when (yes-or-no-p "Save the new worglet to your init file? ")
512 (setq org-protocol-project-alist
513 (cons `(,base-url . (:base-url ,base-url
514 :working-directory ,working-dir
515 :online-suffix ,strip-suffix
516 :working-suffix ,working-suffix))
517 org-protocol-project-alist))
518 (customize-save-variable 'org-protocol-project-alist org-protocol-project-alist))
521 (provide 'org-protocol)
522 ;;; org-protocol.el ends here