config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

org-protocol.el (31137B)


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