dotemacs

My Emacs configuration
git clone git://git.entf.net/dotemacs
Log | Files | Refs | LICENSE

org-protocol.el (30961B)


      1 ;;; org-protocol.el --- Intercept Calls from Emacsclient to Trigger Custom Actions -*- lexical-binding: t; -*-
      2 ;;
      3 ;; Copyright (C) 2008-2023 Free Software Foundation, Inc.
      4 ;;
      5 ;; Authors: Bastien Guerry <bzg@gnu.org>
      6 ;;       Daniel M German <dmg AT uvic DOT org>
      7 ;;       Sebastian Rose <sebastian_rose AT gmx DOT de>
      8 ;;       Ross Patterson <me AT rpatterson DOT net>
      9 ;; Maintainer: Sebastian Rose <sebastian_rose AT gmx DOT de>
     10 ;; Keywords: org, emacsclient, wp
     11 
     12 ;; This file is part of GNU Emacs.
     13 ;;
     14 ;; GNU Emacs is free software: you can redistribute it and/or modify
     15 ;; it under the terms of the GNU General Public License as published by
     16 ;; the Free Software Foundation, either version 3 of the License, or
     17 ;; (at your option) any later version.
     18 
     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 
     24 ;; You should have received a copy of the GNU General Public License
     25 ;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
     26 
     27 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
     28 ;;; Commentary:
     29 ;;
     30 ;; Intercept calls from emacsclient to trigger custom actions.
     31 ;;
     32 ;; This is done by advising `server-visit-files' to scan the list of filenames
     33 ;; for `org-protocol-the-protocol' and sub-protocols defined in
     34 ;; `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'.
     35 ;;
     36 ;; Any application that supports calling external programs with an URL
     37 ;; as argument may be used with this functionality.
     38 ;;
     39 ;;
     40 ;; Usage:
     41 ;; ------
     42 ;;
     43 ;;   1.) Add this to your init file (.emacs probably):
     44 ;;
     45 ;;       (require 'org-protocol)
     46 ;;
     47 ;;   3.) Ensure emacs-server is up and running.
     48 ;;   4.) Try this from the command line (adjust the URL as needed):
     49 ;;
     50 ;;       $ emacsclient \
     51 ;;         "org-protocol://store-link?url=http:%2F%2Flocalhost%2Findex.html&title=The%20title"
     52 ;;
     53 ;;   5.) Optionally add custom sub-protocols and handlers:
     54 ;;
     55 ;;       (setq org-protocol-protocol-alist
     56 ;;             '(("my-protocol"
     57 ;;                :protocol "my-protocol"
     58 ;;                :function my-protocol-handler-function)))
     59 ;;
     60 ;;       A "sub-protocol" will be found in URLs like this:
     61 ;;
     62 ;;           org-protocol://sub-protocol?key=val&key2=val2
     63 ;;
     64 ;; If it works, you can now setup other applications for using this feature.
     65 ;;
     66 ;;
     67 ;; As of March 2009 Firefox users follow the steps documented on
     68 ;; https://kb.mozillazine.org/Register_protocol, Opera setup is described here:
     69 ;; http://www.opera.com/support/kb/view/535/
     70 ;;
     71 ;;
     72 ;; Documentation
     73 ;; -------------
     74 ;;
     75 ;; org-protocol.el comes with and installs handlers to open sources of published
     76 ;; online content, store and insert the browser's URLs and cite online content
     77 ;; by clicking on a bookmark in Firefox, Opera and probably other browsers and
     78 ;; applications:
     79 ;;
     80 ;;   * `org-protocol-open-source' uses the sub-protocol \"open-source\" and maps
     81 ;;     URLs to local filenames defined in `org-protocol-project-alist'.
     82 ;;
     83 ;;   * `org-protocol-store-link' stores an Org link (if Org is present) and
     84 ;;     pushes the browsers URL to the `kill-ring' for yanking.  This handler is
     85 ;;     triggered through the sub-protocol \"store-link\".
     86 ;;
     87 ;;   * Call `org-protocol-capture' by using the sub-protocol \"capture\".  If
     88 ;;     Org is loaded, Emacs will pop-up a capture buffer and fill the
     89 ;;     template with the data provided.  I.e. the browser's URL is inserted as an
     90 ;;     Org-link of which the page title will be the description part.  If text
     91 ;;     was select in the browser, that text will be the body of the entry.
     92 ;;
     93 ;; You may use the same bookmark URL for all those standard handlers and just
     94 ;; adjust the sub-protocol used:
     95 ;;
     96 ;;     javascript:location.href='org-protocol://sub-protocol?'+
     97 ;;           new URLSearchParams({
     98 ;;                 url: location.href,
     99 ;;                 title: document.title,
    100 ;;                 body: window.getSelection()})
    101 ;;
    102 ;; Alternatively use the following expression that encodes space as \"%20\"
    103 ;; instead of \"+\", so it is compatible with Org versions from 9.0 to 9.4:
    104 ;;
    105 ;;     location.href='org-protocol://sub-protocol?url='+
    106 ;;           encodeURIComponent(location.href)+'&title='+
    107 ;;           encodeURIComponent(document.title)+'&body='+
    108 ;;           encodeURIComponent(window.getSelection())
    109 ;;
    110 ;; The handler for the sub-protocol \"capture\" detects an optional template
    111 ;; char that, if present, triggers the use of a special template.
    112 ;; Example:
    113 ;;
    114 ;;     location.href='org-protocol://capture?'+
    115 ;;           new URLSearchParams({template:'x', /* ... */})
    116 ;;
    117 ;; or
    118 ;;
    119 ;;     location.href='org-protocol://capture?template=x'+ ...
    120 ;;
    121 ;;  uses template ?x.
    122 ;;
    123 ;; Note that using double slashes is optional from org-protocol.el's point of
    124 ;; view because emacsclient squashes the slashes to one.
    125 ;;
    126 ;;
    127 ;; provides: 'org-protocol
    128 ;;
    129 ;;; Code:
    130 
    131 (require 'org-macs)
    132 (org-assert-version)
    133 
    134 (require 'org)
    135 (require 'ol)
    136 
    137 (declare-function org-publish-get-project-from-filename "ox-publish"
    138 		  (filename &optional up))
    139 
    140 (defvar org-capture-link-is-already-stored)
    141 (defvar org-capture-templates)
    142 
    143 (defgroup org-protocol nil
    144   "Intercept calls from emacsclient to trigger custom actions.
    145 
    146 This is done by advising `server-visit-files' to scan the list of filenames
    147 for `org-protocol-the-protocol' and sub-protocols defined in
    148 `org-protocol-protocol-alist' and `org-protocol-protocol-alist-default'."
    149   :version "22.1"
    150   :group 'convenience
    151   :group 'org)
    152 
    153 
    154 ;;; Variables:
    155 
    156 (defconst org-protocol-protocol-alist-default
    157   '(("org-capture"     :protocol "capture"     :function org-protocol-capture  :kill-client t)
    158     ("org-store-link"  :protocol "store-link"  :function org-protocol-store-link)
    159     ("org-open-source" :protocol "open-source" :function org-protocol-open-source))
    160   "Default protocols to use.
    161 See `org-protocol-protocol-alist' for a description of this variable.")
    162 
    163 (defconst org-protocol-the-protocol "org-protocol"
    164   "This is the protocol to detect if org-protocol.el is loaded.
    165 `org-protocol-protocol-alist-default' and `org-protocol-protocol-alist' hold
    166 the sub-protocols that trigger the required action.  You will have to define
    167 just one protocol handler OS-wide (MS-Windows) or per application (Linux).
    168 That protocol handler should call emacsclient.")
    169 
    170 ;;; User variables:
    171 
    172 (defcustom org-protocol-reverse-list-of-files t
    173   "Non-nil means re-reverse the list of filenames passed on the command line.
    174 The filenames passed on the command line are passed to the emacs-server in
    175 reverse order.  Set to t (default) to re-reverse the list, i.e. use the
    176 sequence on the command line.  If nil, the sequence of the filenames is
    177 unchanged."
    178   :type 'boolean)
    179 
    180 (defcustom org-protocol-project-alist nil
    181   "Map URLs to local filenames for `org-protocol-open-source' (open-source).
    182 
    183 Each element of this list must be of the form:
    184 
    185   (module-name :property value property: value ...)
    186 
    187 where module-name is an arbitrary name.  All the values are strings.
    188 
    189 Possible properties are:
    190 
    191   :online-suffix     - the suffix to strip from the published URLs
    192   :working-suffix    - the replacement for online-suffix
    193   :base-url          - the base URL, e.g. https://www.example.com/project/
    194                        Last slash required.
    195   :working-directory - the local working directory.  This is what
    196                        base-url will be replaced with.
    197   :redirects         - A list of cons cells, each of which maps a
    198                        regular expression to match to a path relative
    199                        to `:working-directory'.
    200 
    201 Example:
    202 
    203    (setq org-protocol-project-alist
    204        \\='((\"https://orgmode.org/worg/\"
    205           :online-suffix \".php\"
    206           :working-suffix \".org\"
    207           :base-url \"https://orgmode.org/worg/\"
    208           :working-directory \"/home/user/org/Worg/\")
    209          (\"localhost org-notes/\"
    210           :online-suffix \".html\"
    211           :working-suffix \".org\"
    212           :base-url \"http://localhost/org/\"
    213           :working-directory \"/home/user/org/\"
    214           :rewrites ((\"org/?$\" . \"index.php\")))
    215          (\"Hugo based blog\"
    216           :base-url \"https://www.site.com/\"
    217           :working-directory \"~/site/content/post/\"
    218           :online-suffix \".html\"
    219           :working-suffix \".md\"
    220           :rewrites ((\"\\(https://site.com/[0-9]+/[0-9]+/[0-9]+/\\)\"
    221                      . \".md\")))
    222          (\"GNU emacs OpenGrok\"
    223           :base-url \"https://opengrok.housegordon.com/source/xref/emacs/\"
    224           :working-directory \"~/dev/gnu-emacs/\")))
    225 
    226    The :rewrites line of \"localhost org-notes\" entry tells
    227    `org-protocol-open-source' to open /home/user/org/index.php,
    228    if the URL cannot be mapped to an existing file, and ends with
    229    either \"org\" or \"org/\".  The \"GNU emacs OpenGrok\" entry
    230    does not include any suffix properties, allowing local source
    231    file to be opened as found by OpenGrok.
    232 
    233 Consider using the interactive functions `org-protocol-create'
    234 and `org-protocol-create-for-org' to help you filling this
    235 variable with valid contents."
    236   :type 'alist)
    237 
    238 (defcustom org-protocol-protocol-alist nil
    239   "Register custom handlers for org-protocol.
    240 
    241 Each element of this list must be of the form:
    242 
    243   (module-name :protocol protocol :function func :kill-client nil)
    244 
    245 protocol - protocol to detect in a filename without trailing
    246            colon and slashes.  See rfc1738 section 2.1 for more
    247            on this.  If you define a protocol \"my-protocol\",
    248            `org-protocol-check-filename-for-protocol' will search
    249            filenames for \"org-protocol:/my-protocol\" and
    250            trigger your action for every match.  `org-protocol'
    251            is defined in `org-protocol-the-protocol'.  Double and
    252            triple slashes are compressed to one by emacsclient.
    253 
    254 function - function that handles requests with protocol and takes
    255            one argument.  If a new-style link (key=val&key2=val2)
    256            is given, the argument will be a property list with
    257            the values from the link.  If an old-style link is
    258            given (val1/val2), the argument will be the filename
    259            with all protocols stripped.
    260 
    261            If the function returns nil, emacsclient and -server
    262            do nothing.  Any non-nil return value is considered a
    263            valid filename and thus passed to the server.
    264 
    265            `org-protocol.el' provides some support for handling
    266            old-style filenames, if you follow the conventions
    267            used for the standard handlers in
    268            `org-protocol-protocol-alist-default'.  See
    269            `org-protocol-parse-parameters'.
    270 
    271 kill-client - If t, kill the client immediately, once the sub-protocol is
    272            detected.  This is necessary for actions that can be interrupted by
    273            `C-g' to avoid dangling emacsclients.  Note that all other command
    274            line arguments but the this one will be discarded.  Greedy handlers
    275            still receive the whole list of arguments though.
    276 
    277 Here is an example:
    278 
    279   (setq org-protocol-protocol-alist
    280       \\='((\"my-protocol\"
    281          :protocol \"my-protocol\"
    282          :function my-protocol-handler-function)
    283         (\"your-protocol\"
    284          :protocol \"your-protocol\"
    285          :function your-protocol-handler-function)))"
    286   :type '(alist))
    287 
    288 (defcustom org-protocol-default-template-key nil
    289   "The default template key to use.
    290 This is usually a single character string but can also be a
    291 string with two characters."
    292   :type '(choice (const nil) (string)))
    293 
    294 (defcustom org-protocol-data-separator "/+\\|\\?"
    295   "The default data separator to use.
    296 This should be a single regexp string."
    297   :version "24.4"
    298   :package-version '(Org . "8.0")
    299   :type 'regexp)
    300 
    301 ;;; Helper functions:
    302 
    303 (defun org-protocol-sanitize-uri (uri)
    304   "Sanitize slashes to double-slashes in URI.
    305 Emacsclient compresses double and triple slashes."
    306   (when (string-match "^\\([a-z]+\\):/" uri)
    307     (let* ((splitparts (split-string uri "/+")))
    308       (setq uri (concat (car splitparts) "//"
    309                         (mapconcat #'identity (cdr splitparts) "/")))))
    310   uri)
    311 
    312 (defun org-protocol-split-data (data &optional unhexify separator)
    313   "Split the DATA argument for an org-protocol handler function.
    314 If UNHEXIFY is non-nil, hex-decode each split part.  If UNHEXIFY
    315 is a function, use that function to decode each split part.  The
    316 string is split at each occurrence of SEPARATOR (regexp).  If no
    317 SEPARATOR is specified or SEPARATOR is nil, assume \"/+\".  The
    318 results of that splitting are returned as a list."
    319   (let* ((sep (or separator "/+\\|\\?"))
    320          (split-parts (split-string data sep)))
    321     (cond ((not unhexify) split-parts)
    322 	  ((fboundp unhexify) (mapcar unhexify split-parts))
    323 	  (t (mapcar #'org-link-decode split-parts)))))
    324 
    325 (defun org-protocol-flatten-greedy (param-list &optional strip-path replacement)
    326   "Transform PARAM-LIST into a flat list for greedy handlers.
    327 
    328 Greedy handlers might receive a list like this from emacsclient:
    329 \((\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\"))
    330 where \"/dir/\" is the absolute path to emacsclient's working directory.  This
    331 function transforms it into a flat list using `org-protocol-flatten' and
    332 transforms the elements of that list as follows:
    333 
    334 If STRIP-PATH is non-nil, remove the \"/dir/\" prefix from all members of
    335 param-list.
    336 
    337 If REPLACEMENT is string, replace the \"/dir/\" prefix with it.
    338 
    339 The first parameter, the one that contains the protocols, is always changed.
    340 Everything up to the end of the protocols is stripped.
    341 
    342 Note, that this function will always behave as if
    343 `org-protocol-reverse-list-of-files' was set to t and the returned list will
    344 reflect that.  emacsclient's first parameter will be the first one in the
    345 returned list."
    346   (let* ((l (org-protocol-flatten (if org-protocol-reverse-list-of-files
    347 				      param-list
    348 				    (reverse param-list))))
    349 	 (trigger (car l))
    350 	 (len 0)
    351 	 dir
    352 	 ret)
    353     (when (string-match "^\\(.*\\)\\(org-protocol:/+[a-zA-Z0-9][-_a-zA-Z0-9]*:/+\\)\\(.*\\)" trigger)
    354       (setq dir (match-string 1 trigger))
    355       (setq len (length dir))
    356       (setcar l (concat dir (match-string 3 trigger))))
    357     (if strip-path
    358 	(progn
    359 	  (dolist (e l ret)
    360 	    (setq ret
    361 		  (append ret
    362 			  (list
    363 			   (if (stringp e)
    364 			       (if (stringp replacement)
    365 				   (setq e (concat replacement (substring e len)))
    366 				 (setq e (substring e len)))
    367 			     e)))))
    368 	  ret)
    369       l)))
    370 
    371 ;; `flatten-tree' was added in Emacs 27.1.
    372 (defalias 'org-protocol-flatten
    373   (if (fboundp 'flatten-tree) 'flatten-tree
    374     (lambda (list)
    375       "Transform LIST into a flat list.
    376 
    377 Greedy handlers might receive a list like this from emacsclient:
    378 \((\"/dir/org-protocol:/greedy:/~/path1\" (23 . 12)) (\"/dir/param\"))
    379 where \"/dir/\" is the absolute path to emacsclients working directory.
    380 This function transforms it into a flat list."
    381       (if list
    382 	  (if (consp list)
    383 	      (append (org-protocol-flatten (car list))
    384 		      (org-protocol-flatten (cdr list)))
    385 	    (list list))))))
    386 
    387 (defun org-protocol-parse-parameters (info &optional new-style default-order)
    388   "Return a property list of parameters from INFO.
    389 If NEW-STYLE is non-nil, treat INFO as a query string (ex:
    390 url=URL&title=TITLE).  If old-style links are used (ex:
    391 org-protocol://store-link/url/title), assign them to attributes
    392 following DEFAULT-ORDER.
    393 
    394 If no DEFAULT-ORDER is specified, return the list of values.
    395 
    396 If INFO is already a property list, return it unchanged."
    397   (if (listp info)
    398       info
    399     (if new-style
    400 	(let ((data (org-protocol-convert-query-to-plist info))
    401 	      result)
    402 	  (while data
    403 	    (setq result
    404 		  (append result
    405 			  (list (pop data) (org-link-decode (pop data))))))
    406 	  result)
    407       (let ((data (org-protocol-split-data info t org-protocol-data-separator)))
    408 	(if default-order
    409 	    (org-protocol-assign-parameters data default-order)
    410 	  data)))))
    411 
    412 (defun org-protocol-assign-parameters (data default-order)
    413   "Return a property list of parameters from DATA.
    414 Key names are taken from DEFAULT-ORDER, which should be a list of
    415 symbols.  If DEFAULT-ORDER is shorter than the number of values
    416 specified, the rest of the values are treated as :key value pairs."
    417   (let (result)
    418     (while default-order
    419       (setq result
    420 	    (append result
    421 		    (list (pop default-order)
    422 			  (pop data)))))
    423     (while data
    424       (setq result
    425 	    (append result
    426 		    (list (intern (concat ":" (pop data)))
    427 			  (pop data)))))
    428     result))
    429 
    430 ;;; Standard protocol handlers:
    431 
    432 (defun org-protocol-store-link (fname)
    433   "Process an org-protocol://store-link style url.
    434 Additionally store a browser URL as an org link.  Also pushes the
    435 link's URL to the `kill-ring'.
    436 
    437 Parameters: url, title (optional), body (optional)
    438 
    439 Old-style links such as org-protocol://store-link://URL/TITLE are
    440 also recognized.
    441 
    442 The location for a browser's bookmark may look like this:
    443 
    444   javascript:location.href = \\='org-protocol://store-link?\\=' +
    445        new URLSearchParams({url:location.href, title:document.title});
    446 
    447 or to keep compatibility with Org versions from 9.0 to 9.4 it may be:
    448 
    449   javascript:location.href = \\
    450       \\='org-protocol://store-link?url=\\=' + \\
    451       encodeURIComponent(location.href) + \\='&title=\\=' + \\
    452       encodeURIComponent(document.title);
    453 
    454 Don't use `escape()'!  Use `encodeURIComponent()' instead.  The
    455 title of the page could contain slashes and the location
    456 definitely will.  Org 9.4 and earlier could not decode \"+\"
    457 to space, that is why less readable latter expression may be necessary
    458 for backward compatibility.
    459 
    460 The sub-protocol used to reach this function is set in
    461 `org-protocol-protocol-alist'.
    462 
    463 FNAME should be a property list.  If not, an old-style link of the
    464 form URL/TITLE can also be used."
    465   (let* ((splitparts (org-protocol-parse-parameters fname nil '(:url :title)))
    466          (uri (org-protocol-sanitize-uri (plist-get splitparts :url)))
    467          (title (plist-get splitparts :title)))
    468     (when (boundp 'org-stored-links)
    469       (push (list uri title) org-stored-links))
    470     (kill-new uri)
    471     (message "`%s' to insert new Org link, `%s' to insert %S"
    472              (substitute-command-keys "\\[org-insert-link]")
    473              (substitute-command-keys "\\[yank]")
    474              uri))
    475   nil)
    476 
    477 (defun org-protocol-capture (info)
    478   "Process an org-protocol://capture style url with INFO.
    479 
    480 The sub-protocol used to reach this function is set in
    481 `org-protocol-protocol-alist'.
    482 
    483 This function detects an URL, title and optional text, separated
    484 by `/'.  The location for a browser's bookmark looks like this:
    485 
    486   javascript:location.href = \\='org-protocol://capture?\\=' +
    487         new URLSearchParams({
    488               url: location.href,
    489               title: document.title,
    490               body: window.getSelection()})
    491 
    492 or to keep compatibility with Org versions from 9.0 to 9.4:
    493 
    494   javascript:location.href = \\='org-protocol://capture?url=\\='+ \\
    495         encodeURIComponent(location.href) + \\='&title=\\=' + \\
    496         encodeURIComponent(document.title) + \\='&body=\\=' + \\
    497         encodeURIComponent(window.getSelection())
    498 
    499 By default, it uses the character `org-protocol-default-template-key',
    500 which should be associated with a template in `org-capture-templates'.
    501 You may specify the template with a template= query parameter, like this:
    502 
    503   javascript:location.href = \\='org-protocol://capture?template=b\\='+ ...
    504 
    505 Now template ?b will be used."
    506   (let* ((parts
    507 	  (pcase (org-protocol-parse-parameters info)
    508 	    ;; New style links are parsed as a plist.
    509 	    ((let `(,(pred keywordp) . ,_) info) info)
    510 	    ;; Old style links, with or without template key, are
    511 	    ;; parsed as a list of strings.
    512 	    (p
    513 	     (let ((k (if (= 1 (length (car p)))
    514 			  '(:template :url :title :body)
    515 			'(:url :title :body))))
    516 	       (org-protocol-assign-parameters p k)))))
    517 	 (template (or (plist-get parts :template)
    518 		       org-protocol-default-template-key))
    519 	 (url (and (plist-get parts :url)
    520 		   (org-protocol-sanitize-uri (plist-get parts :url))))
    521 	 (type (and url
    522 		    (string-match "^\\([a-z]+\\):" url)
    523 		    (match-string 1 url)))
    524 	 (title (or (plist-get parts :title) ""))
    525 	 (region (or (plist-get parts :body) ""))
    526 	 (orglink
    527 	  (if (null url) title
    528 	    (org-link-make-string url (or (org-string-nw-p title) url))))
    529 	 ;; Avoid call to `org-store-link'.
    530 	 (org-capture-link-is-already-stored t))
    531     ;; Only store link if there's a URL to insert later on.
    532     (when url (push (list url title) org-stored-links))
    533     (org-link-store-props :type type
    534 			  :link url
    535 			  :description title
    536 			  :annotation orglink
    537 			  :initial region
    538 			  :query parts)
    539     (raise-frame)
    540     (org-capture nil template)
    541     (message "Item captured.")
    542     ;; Make sure we do not return a string, as `server-visit-files',
    543     ;; through `server-edit', would interpret it as a file name.
    544     nil))
    545 
    546 (defun org-protocol-convert-query-to-plist (query)
    547   "Convert QUERY key=value pairs in the URL to a property list."
    548   (when query
    549     (let ((plus-decoded (replace-regexp-in-string "\\+" " " query t t)))
    550       (cl-mapcan (lambda (x)
    551 		   (let ((c (split-string x "=")))
    552 		     (list (intern (concat ":" (car c))) (cadr c))))
    553 		 (split-string plus-decoded "&")))))
    554 
    555 (defun org-protocol-open-source (fname)
    556   "Process an org-protocol://open-source?url= style URL with FNAME.
    557 
    558 Change a filename by mapping URLs to local filenames as set
    559 in `org-protocol-project-alist'.
    560 
    561 The location for a browser's bookmark should look like this:
    562 
    563   javascript:location.href = \\='org-protocol://open-source?\\=' +
    564         new URLSearchParams({url: location.href})
    565 
    566 or if you prefer to keep compatibility with older Org versions (9.0 to 9.4),
    567 consider the following expression:
    568 
    569   javascript:location.href = \\='org-protocol://open-source?url=\\=' + \\
    570         encodeURIComponent(location.href)"
    571   ;; As we enter this function for a match on our protocol, the return value
    572   ;; defaults to nil.
    573   (let (;; (result nil)
    574 	(f (org-protocol-sanitize-uri
    575 	    (plist-get (org-protocol-parse-parameters fname nil '(:url))
    576 		       :url))))
    577     (catch 'result
    578       (dolist (prolist org-protocol-project-alist)
    579         (let* ((base-url (plist-get (cdr prolist) :base-url))
    580                (wsearch (regexp-quote base-url)))
    581 
    582           (when (string-match wsearch f)
    583             (let* ((wdir (plist-get (cdr prolist) :working-directory))
    584                    (strip-suffix (plist-get (cdr prolist) :online-suffix))
    585                    (add-suffix (plist-get (cdr prolist) :working-suffix))
    586 		   ;; Strip "[?#].*$" if `f' is a redirect with another
    587 		   ;; ending than strip-suffix here:
    588 		   (f1 (substring f 0 (string-match "\\([\\?#].*\\)?$" f)))
    589                    (start-pos (+ (string-match wsearch f1) (length base-url)))
    590                    (end-pos (if strip-suffix
    591 			        (string-match (regexp-quote strip-suffix) f1)
    592 			      (length f1)))
    593 		   ;; We have to compare redirects without suffix below:
    594 		   (f2 (concat wdir (substring f1 start-pos end-pos)))
    595                    (the-file (if add-suffix (concat f2 add-suffix) f2)))
    596 
    597 	      ;; Note: the-file may still contain `%C3' et al here because browsers
    598 	      ;; tend to encode `&auml;' in URLs to `%25C3' - `%25' being `%'.
    599 	      ;; So the results may vary.
    600 
    601 	      ;; -- start redirects --
    602 	      (unless (file-exists-p the-file)
    603 		(message "File %s does not exist.\nTesting for rewritten URLs." the-file)
    604 		(let ((rewrites (plist-get (cdr prolist) :rewrites)))
    605 		  (when rewrites
    606 		    (message "Rewrites found: %S" rewrites)
    607 		    (dolist (rewrite rewrites)
    608 		      ;; Try to match a rewritten URL and map it to
    609 		      ;; a real file.  Compare redirects without
    610 		      ;; suffix.
    611 		      (when (string-match (car rewrite) f1)
    612 			(let ((replacement
    613 			       (concat (directory-file-name
    614 					(replace-match "" nil nil f1 1))
    615 				       (cdr rewrite))))
    616 			  (throw 'result (concat wdir replacement))))))))
    617 	      ;; -- end of redirects --
    618 
    619               (if (file-readable-p the-file)
    620                   (throw 'result the-file))
    621               (if (file-exists-p the-file)
    622                   (message "%s: permission denied!" the-file)
    623                 (message "%s: no such file or directory." the-file))))))
    624       nil))) ;; FIXME: Really?
    625 
    626 
    627 ;;; Core functions:
    628 
    629 (defun org-protocol-check-filename-for-protocol (fname restoffiles _client)
    630   "Check if `org-protocol-the-protocol' and a valid protocol are used in FNAME.
    631 Sub-protocols are registered in `org-protocol-protocol-alist' and
    632 `org-protocol-protocol-alist-default'.  This is how the matching is done:
    633 
    634   (string-match \"protocol:/+sub-protocol\\\\(://\\\\|\\\\?\\\\)\" ...)
    635 
    636 protocol and sub-protocol are regexp-quoted.
    637 
    638 Old-style links such as \"protocol://sub-protocol://param1/param2\" are
    639 also recognized.
    640 
    641 If a matching protocol is found, the protocol is stripped from
    642 FNAME and the result is passed to the protocol function as the
    643 first parameter.  The second parameter will be non-nil if FNAME
    644 uses key=val&key2=val2-type arguments, or nil if FNAME uses
    645 val/val2-type arguments.  If the function returns nil, the
    646 filename is removed from the list of filenames passed from
    647 emacsclient to the server.  If the function returns a non-nil
    648 value, that value is passed to the server as filename.
    649 
    650 If the handler function is greedy, RESTOFFILES will also be passed to it.
    651 
    652 CLIENT is ignored."
    653   (let ((sub-protocols (append org-protocol-protocol-alist
    654 			       org-protocol-protocol-alist-default)))
    655     (catch 'fname
    656       (let ((the-protocol (concat (regexp-quote org-protocol-the-protocol)
    657 				  ":/+")))
    658         (when (string-match the-protocol fname)
    659           (dolist (prolist sub-protocols)
    660             (let ((proto
    661 		   (concat the-protocol
    662 			   (regexp-quote (plist-get (cdr prolist) :protocol))
    663 			   "\\(:/+\\|/*\\?\\)")))
    664               (when (string-match proto fname)
    665                 (let* ((func (plist-get (cdr prolist) :function))
    666                        (greedy (plist-get (cdr prolist) :greedy))
    667                        (split (split-string fname proto))
    668                        (result (if greedy restoffiles (cadr split)))
    669 		       (new-style (not (= ?: (aref (match-string 1 fname) 0)))))
    670                   (when (plist-get (cdr prolist) :kill-client)
    671 		    (message "Greedy org-protocol handler.  Killing client.")
    672 		    ;; If not fboundp, there's no client to kill.
    673 		    (if (fboundp 'server-edit) (server-edit)))
    674                   (when (fboundp func)
    675                     (unless greedy
    676                       (throw 'fname
    677 			     (if new-style
    678 				 (funcall func (org-protocol-parse-parameters
    679 						result new-style))
    680 			       (warn "Please update your Org Protocol handler \
    681 to deal with new-style links.")
    682 			       (funcall func result))))
    683 		    ;; Greedy protocol handlers are responsible for
    684 		    ;; parsing their own filenames.
    685 		    (funcall func result)
    686                     (throw 'fname t))))))))
    687       fname)))
    688 
    689 (advice-add 'server-visit-files :around #'org--protocol-detect-protocol-server)
    690 (defun org--protocol-detect-protocol-server (orig-fun files client &rest args)
    691   "Advice server-visit-flist to call `org-protocol-check-filename-for-protocol'."
    692   (let ((flist (if org-protocol-reverse-list-of-files
    693                    (reverse files)
    694                  files)))
    695     (catch 'greedy
    696       (dolist (var flist)
    697 	;; `\' to `/' on windows.  FIXME: could this be done any better?
    698         (let ((fname  (expand-file-name (car var))))
    699           (setq fname (org-protocol-check-filename-for-protocol
    700 		       fname (member var flist)  client))
    701           (if (eq fname t) ;; greedy? We need the t return value.
    702               (progn
    703                 ;; FIXME: Doesn't this just ignore all the files before
    704                 ;; this one (the remaining ones have been passed to
    705                 ;; `org-protocol-check-filename-for-protocol' but not
    706                 ;; the ones before).
    707                 (setq files nil)
    708                 (throw 'greedy t))
    709             (if (stringp fname) ;; probably filename
    710                 (setcar var fname)
    711               (setq files (delq var files)))))))
    712     (apply orig-fun files client args)))
    713 
    714 ;;; Org specific functions:
    715 
    716 (defun org-protocol-create-for-org ()
    717   "Create an Org protocol project for the current file's project.
    718 The visited file needs to be part of a publishing project in
    719 `org-publish-project-alist' for this to work.  The function
    720 delegates most of the work to `org-protocol-create'."
    721   (interactive)
    722   (require 'ox-publish)
    723   (let ((all (or (org-publish-get-project-from-filename buffer-file-name))))
    724     (if all (org-protocol-create (cdr all))
    725       (message "%s"
    726 	       (substitute-command-keys
    727 		"Not in an Org project.  \
    728 Did you mean `\\[org-protocol-create]'?")))))
    729 
    730 (defun org-protocol-create (&optional project-plist)
    731   "Create a new org-protocol project interactively.
    732 An org-protocol project is an entry in
    733 `org-protocol-project-alist' which is used by
    734 `org-protocol-open-source'.  Optionally use PROJECT-PLIST to
    735 initialize the defaults for this project.  If PROJECT-PLIST is
    736 the cdr of an element in `org-publish-project-alist', reuse
    737 :base-directory, :html-extension and :base-extension."
    738   (interactive)
    739   (let ((working-dir (expand-file-name
    740 		      (or (plist-get project-plist :base-directory)
    741 			  default-directory)))
    742         (base-url "https://orgmode.org/worg/")
    743         (strip-suffix (or (plist-get project-plist :html-extension) ".html"))
    744         (working-suffix (if (plist-get project-plist :base-extension)
    745                             (concat "." (plist-get project-plist :base-extension))
    746                           ".org"))
    747         (insert-default-directory t)
    748         (minibuffer-allow-text-properties nil))
    749 
    750     (setq base-url (read-string "Base URL of published content: " base-url nil base-url t))
    751     (or (string-suffix-p "/" base-url)
    752 	(setq base-url (concat base-url "/")))
    753 
    754     (setq working-dir
    755           (expand-file-name
    756            (read-directory-name "Local working directory: " working-dir working-dir t)))
    757     (or (string-suffix-p "/" working-dir)
    758 	(setq working-dir (concat working-dir "/")))
    759 
    760     (setq strip-suffix
    761           (read-string
    762            (concat "Extension to strip from published URLs (" strip-suffix "): ")
    763 	   strip-suffix nil strip-suffix t))
    764 
    765     (setq working-suffix
    766           (read-string
    767            (concat "Extension of editable files (" working-suffix "): ")
    768 	   working-suffix nil working-suffix t))
    769 
    770     (when (yes-or-no-p "Save the new org-protocol-project to your init file? ")
    771       (setq org-protocol-project-alist
    772             (cons `(,base-url . (:base-url ,base-url
    773 					   :working-directory ,working-dir
    774 					   :online-suffix ,strip-suffix
    775 					   :working-suffix ,working-suffix))
    776                   org-protocol-project-alist))
    777       (customize-save-variable 'org-protocol-project-alist org-protocol-project-alist))))
    778 
    779 (provide 'org-protocol)
    780 
    781 ;;; org-protocol.el ends here