dotemacs

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

oc-biblatex.el (18007B)


      1 ;;; oc-biblatex.el --- biblatex citation processor for Org  -*- lexical-binding: t; -*-
      2 
      3 ;; Copyright (C) 2021-2023 Free Software Foundation, Inc.
      4 
      5 ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
      6 
      7 ;; This file is part of GNU Emacs.
      8 
      9 ;; GNU Emacs is free software: you can redistribute it and/or modify
     10 ;; it under the terms of the GNU General Public License as published by
     11 ;; the Free Software Foundation, either version 3 of the License, or
     12 ;; (at your option) any later version.
     13 
     14 ;; GNU Emacs is distributed in the hope that it will be useful,
     15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     17 ;; GNU General Public License for more details.
     18 
     19 ;; You should have received a copy of the GNU General Public License
     20 ;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
     21 
     22 ;;; Commentary:
     23 
     24 ;; This library registers the `biblatex' citation processor, which provides
     25 ;; the "export" capability for citations.
     26 
     27 ;; The processor relies on "biblatex" LaTeX package.  As such it ensures that
     28 ;; the package is properly required in the document's preamble.  More
     29 ;; accurately, it will re-use any "\usepackage{biblatex}" already present in
     30 ;; the document (e.g., through `org-latex-packages-alist'), or insert one using
     31 ;; options defined in `org-cite-biblatex-options'.
     32 
     33 ;; In any case, the library will override style-related options with those
     34 ;; specified with the citation processor, in `org-cite-export-processors' or
     35 ;; "cite_export" keyword.  If you need to use different styles for bibliography
     36 ;; and citations, you can separate them with "bibstyle/citestyle" syntax.  E.g.,
     37 ;;
     38 ;;   #+cite_export: biblatex authortitle/authortitle-ibid
     39 
     40 ;; The library supports the following citation styles:
     41 ;;
     42 ;; - author (a), including caps (c), full (f) and caps-full (cf) variants,
     43 ;; - locators (l), including bare (b), caps (c) and bare-caps (bc) variants,
     44 ;; - noauthor (na), including bare (b) variant,
     45 ;; - nocite (n),
     46 ;; - text (t), including caps (c) variant,
     47 ;; - default style, including bare (b), caps (c) and bare-caps (bc) variants.
     48 
     49 ;; When citation and style permit, the library automatically generates
     50 ;; "multicite" versions of the commands above.
     51 
     52 ;; Bibliography is printed using "\printbibliography" command.  Additional
     53 ;; options may be passed to it through a property list attached to the
     54 ;; "print_bibliography" keyword.  E.g.,
     55 ;;
     56 ;;    #+print_bibliography: :section 2 :heading subbibliography
     57 ;;
     58 ;; Values including spaces must be surrounded with double quotes.  If you need
     59 ;; to use a key multiple times, you can separate its values with commas, but
     60 ;; without any space in-between:
     61 ;;
     62 ;;    #+print_bibliography: :keyword abc,xyz :title "Primary Sources"
     63 
     64 ;;; Code:
     65 
     66 (require 'org-macs)
     67 (org-assert-version)
     68 
     69 (require 'map)
     70 (require 'org-macs)
     71 (require 'oc)
     72 
     73 (declare-function org-element-property "org-element" (property element))
     74 (declare-function org-export-data "org-export" (data info))
     75 
     76 
     77 ;;; Customization
     78 (defcustom org-cite-biblatex-options nil
     79   "Options added to \"biblatex\" package.
     80 If \"biblatex\" package is already required in the document, e.g., through
     81 `org-latex-packages-alist' variable, these options are ignored."
     82   :group 'org-cite
     83   :package-version '(Org . "9.5")
     84   :type '(choice
     85           (string :tag "Options (key=value,key2=value2...)")
     86           (const :tag "No option" nil))
     87   :safe #'string-or-null-p)
     88 
     89 (defcustom org-cite-biblatex-styles
     90   '(("author"   "caps"      "Citeauthor*" nil         nil)
     91     ("author"   "full"      "citeauthor"  nil         nil)
     92     ("author"   "caps-full" "Citeauthor"  nil         nil)
     93     ("author"   nil         "citeauthor*" nil         nil)
     94     ("locators" "bare"      "notecite"    nil         nil)
     95     ("locators" "caps"      "Pnotecite"   nil         nil)
     96     ("locators" "bare-caps" "Notecite"    nil         nil)
     97     ("locators" nil         "pnotecite"   nil         nil)
     98     ("noauthor" "bare"      "cite*"       nil         nil)
     99     ("noauthor" nil         "autocite*"   nil         nil)
    100     ("nocite"   nil         "nocite"      nil         t)
    101     ("text"     "caps"      "Textcite"    "Textcites" nil)
    102     ("text"     nil         "textcite"    "textcites" nil)
    103     (nil        "bare"      "cite"        "cites"     nil)
    104     (nil        "caps"      "Autocite"    "Autocites" nil)
    105     (nil        "bare-caps" "Cite"        "Cites"     nil)
    106     (nil        nil         "autocite"    "autocites" nil))
    107   "List of styles and variants, with associated BibLaTeX commands.
    108 
    109 Each style follows the pattern
    110 
    111   (NAME VARIANT COMMAND MULTI-COMMAND NO-OPTION)
    112 
    113 where:
    114 
    115   NAME is the name of the style, as a string, or nil.  The nil
    116   style is the default style.  As such, it must have an entry in
    117   the list.
    118 
    119   VARIANT is the name of the style variant, as a string or nil.
    120   The nil variant is the default variant for the current style.
    121   As such, each style name must be associated to a nil variant.
    122 
    123   COMMAND is the LaTeX command to use, as a string.  It should
    124   not contain the leading backslash character.
    125 
    126   MULTI-COMMAND is the LaTeX command to use when a multi-cite
    127   command is appropriate.  When nil, the style is deemed
    128   inappropriate for multi-cites.  The command should not contain
    129   the leading backslash character.
    130 
    131   NO-OPTION is a boolean.  When non-nil, no optional argument
    132   should be added to the LaTeX command.
    133 
    134 Each NAME-VARIANT pair should be unique in the list.
    135 
    136 It is also possible to provide shortcuts for style and variant
    137 names.  See `org-cite-biblatex-style-shortcuts'."
    138   :group 'org-cite
    139   :package-version '(Org . "9.6")
    140   :type '(repeat
    141           (list :tag "Style/variant combination"
    142                 ;; Name part.
    143                 (choice :tag "Style"
    144                         (string :tag "Name")
    145                         (const :tag "Default style" nil))
    146                 ;; Variant part.
    147                 (choice :tag "Variant"
    148                         (string :tag "Name")
    149                         (const :tag "Default variant" nil))
    150                 ;; Command part.
    151                 (string :tag "Command name")
    152                 (choice :tag "Multicite command"
    153                         (string :tag "Command name")
    154                         (const :tag "No multicite support" nil))
    155                 (choice :tag "Skip optional arguments"
    156                         (const :tag "Yes" t)
    157                         (const :tag "No" nil)))))
    158 
    159 (defcustom org-cite-biblatex-style-shortcuts
    160   '(("a"  . "author")
    161     ("b"  . "bare")
    162     ("bc" . "bare-caps")
    163     ("c"  . "caps")
    164     ("cf" . "caps-full")
    165     ("f"  . "full")
    166     ("l"  . "locators")
    167     ("n"  . "nocite")
    168     ("na" . "noauthor")
    169     ("t"  . "text"))
    170   "List of shortcuts associated to style or variant names.
    171 
    172 Each entry is a pair (NAME . STYLE-NAME) where NAME is the name
    173 of the shortcut, as a string, and STYLE-NAME is the name of
    174 a style in `org-cite-biblatex-styles'."
    175   :group 'org-cite
    176   :package-version '(Org . "9.6")
    177   :type '(repeat
    178           (cons :tag "Shortcut"
    179                 (string :tag "Name")
    180                 (string :tag "Full name")))
    181   :safe t)
    182 
    183 
    184 ;;; Internal functions
    185 (defun org-cite-biblatex--package-options (initial style)
    186   "Return options string for \"biblatex\" package.
    187 
    188 INITIAL is an initial style of comma-separated options, as a string or nil.
    189 STYLE is the style definition as a string or nil.
    190 
    191 Return a string."
    192   (let ((options-no-style
    193          (and initial
    194               (let ((re (rx string-start (or "bibstyle" "citestyle" "style"))))
    195                 (seq-filter
    196                  (lambda (option) (not (string-match re option)))
    197                  (split-string (org-unbracket-string "[" "]" initial)
    198                                "," t " \t")))))
    199         (style-options
    200          (cond
    201           ((null style) nil)
    202           ((not (string-match "/" style)) (list (concat "style=" style)))
    203           (t
    204            (list (concat "bibstyle=" (substring style nil (match-beginning 0)))
    205                  (concat "citestyle=" (substring style (match-end 0))))))))
    206     (if (or options-no-style style-options)
    207         (format "[%s]"
    208                 (mapconcat #'identity
    209                            (append options-no-style style-options)
    210                            ","))
    211       "")))
    212 
    213 (defun org-cite-biblatex--multicite-p  (citation)
    214   "Non-nil when citation could make use of a \"multicite\" command."
    215   (let ((references (org-cite-get-references citation)))
    216     (and (< 1 (length references))
    217          (seq-some (lambda (r)
    218                      (or (org-element-property :prefix r)
    219                          (org-element-property :suffix r)))
    220                    references))))
    221 
    222 (defun org-cite-biblatex--atomic-arguments (references info &optional no-opt)
    223   "Build argument for the list of citation REFERENCES.
    224 When NO-OPT argument is non-nil, only provide mandatory arguments."
    225   (let ((mandatory
    226          (format "{%s}"
    227                  (mapconcat (lambda (r) (org-element-property :key r))
    228                             references
    229                             ","))))
    230     (if no-opt mandatory
    231       (let* ((origin (pcase references
    232                        (`(,reference) reference)
    233                        (`(,reference . ,_)
    234                         (org-element-property :parent reference))))
    235              (suffix (org-element-property :suffix origin))
    236              (prefix (org-element-property :prefix origin)))
    237         (concat (and prefix
    238                      (format "[%s]" (org-trim (org-export-data prefix info))))
    239                 (cond
    240                  (suffix (format "[%s]"
    241                                  (org-trim (org-export-data suffix info))))
    242                  (prefix "[]")
    243                  (t nil))
    244                 mandatory)))))
    245 
    246 (defun org-cite-biblatex--multi-arguments (citation info)
    247   "Build \"multicite\" command arguments for CITATION object.
    248 INFO is the export state, as a property list."
    249   (let ((global-prefix (org-element-property :prefix citation))
    250         (global-suffix (org-element-property :suffix citation)))
    251     (concat (and global-prefix
    252                  (format "(%s)"
    253                          (org-trim (org-export-data global-prefix info))))
    254             (cond
    255              ;; Global pre/post-notes.
    256              (global-suffix
    257               (format "(%s)"
    258                       (org-trim (org-export-data global-suffix info))))
    259              (global-prefix "()")
    260              (t nil))
    261             ;; All arguments.
    262             (mapconcat (lambda (r)
    263                          (org-cite-biblatex--atomic-arguments (list r) info))
    264                        (org-cite-get-references citation)
    265                        ""))))
    266 
    267 (defun org-cite-biblatex--command (citation info name &optional multi no-opt)
    268   "Return BibLaTeX command NAME for CITATION object.
    269 
    270 INFO is the export state, as a property list.
    271 
    272 When optional argument MULTI is non-nil, use it as a multicite
    273 command name when appropriate.  When optional argument NO-OPT is
    274 non-nil, do not add optional arguments to the command."
    275   (if (and multi (org-cite-biblatex--multicite-p citation))
    276       (format "\\%s%s" multi (org-cite-biblatex--multi-arguments citation info))
    277     (format "\\%s%s"
    278             name
    279             (org-cite-biblatex--atomic-arguments
    280              (org-cite-get-references citation) info no-opt))))
    281 
    282 (defun org-cite-biblatex--expand-shortcuts (style)
    283   "Return STYLE pair with shortcuts expanded."
    284   (pcase style
    285     (`(,style . ,variant)
    286      (cons (or (alist-get style org-cite-biblatex-style-shortcuts
    287                           nil nil #'equal)
    288                style)
    289            (or (alist-get variant org-cite-biblatex-style-shortcuts
    290                           nil nil #'equal)
    291                variant)))
    292     (_ (error "This should not happen"))))
    293 
    294 (defun org-cite-biblatex-list-styles ()
    295   "List styles and variants supported in `biblatex' citation processor.
    296 The output format is appropriate as a value for `:cite-styles' keyword
    297 in `org-cite-register-processor', which see."
    298   (let ((shortcuts (make-hash-table :test #'equal))
    299         (variants (make-hash-table :test #'equal)))
    300     (pcase-dolist (`(,name . ,full-name) org-cite-biblatex-style-shortcuts)
    301       (push name (gethash full-name shortcuts)))
    302     (pcase-dolist (`(,name ,variant . ,_) org-cite-biblatex-styles)
    303       (unless (null variant) (push variant (gethash name variants))))
    304     (map-apply (lambda (style-name variants)
    305                  (cons (cons (or style-name "nil")
    306                              (gethash style-name shortcuts))
    307                        (mapcar (lambda (v)
    308                                  (cons v (gethash v shortcuts)))
    309                                variants)))
    310                variants)))
    311 
    312 
    313 ;;; Export capability
    314 (defun org-cite-biblatex-export-bibliography (_keys _files _style props &rest _)
    315   "Print references from bibliography.
    316 PROPS is the local properties of the bibliography, as a property list."
    317   (concat "\\printbibliography"
    318           (and props
    319                (let ((key nil)
    320                      (results nil))
    321                  (dolist (datum props)
    322                    (cond
    323                     ((keywordp datum)
    324                      (when key (push key results))
    325                      (setq key (substring (symbol-name datum) 1)))
    326                     (t
    327                      ;; Comma-separated values are associated to the
    328                      ;; same keyword.
    329                      (push (mapconcat (lambda (v) (concat key "=" v))
    330                                       (split-string datum "," t)
    331                                       ",")
    332                            results)
    333                      (setq key nil))))
    334                  (format "[%s]"
    335                          (mapconcat #'identity (nreverse results) ","))))))
    336 
    337 (defun org-cite-biblatex-export-citation (citation style _ info)
    338   "Export CITATION object.
    339 STYLE is the citation style, as a pair of either strings or nil.
    340 INFO is the export state, as a property list."
    341   (pcase-let* ((`(,name . ,variant) (org-cite-biblatex--expand-shortcuts style))
    342                (candidates nil)
    343                (style-match-flag nil))
    344     (catch :match
    345       ;; Walk `org-cite-biblatex-styles' and prioritize matching
    346       ;; candidates.  At the end of the process, the optimal candidate
    347       ;; should appear in front of CANDIDATES.
    348       (dolist (style org-cite-biblatex-styles)
    349         (pcase style
    350           ;; A matching style-variant pair trumps anything else.
    351           ;; Return it.
    352           (`(,(pred (equal name)) ,(pred (equal variant)) . ,_)
    353            (throw :match (setq candidates (list style))))
    354           ;; nil-nil style-variant is the fallback value.  Consider it
    355           ;; only if nothing else matches.
    356           (`(nil nil . ,_)
    357            (unless candidates (push style candidates)))
    358           ;; A matching style with default variant trumps a matching
    359           ;; variant without the adequate style.  Ensure the former
    360           ;; appears first in the list.
    361           (`(,(pred (equal name)) nil . ,_)
    362            (push style candidates)
    363            (setq style-match-flag t))
    364           (`(nil ,(pred (equal variant)) . ,_)
    365            (unless style-match-flag (push style candidates)))
    366           ;; Discard anything else.
    367           (_ nil))))
    368     (apply
    369      #'org-cite-biblatex--command citation info
    370      (pcase (seq-elt candidates 0) ;; `seq-first' is not available in Emacs 26.
    371        (`(,_ ,_ . ,command-parameters) command-parameters)
    372        ('nil
    373         (user-error
    374          "Missing default style or variant in `org-cite-biblatex-styles'"))
    375        (other
    376         (user-error "Invalid entry %S in `org-cite-biblatex-styles'" other))))))
    377 
    378 (defun org-cite-biblatex-prepare-preamble (output _keys files style &rest _)
    379   "Prepare document preamble for \"biblatex\" usage.
    380 
    381 OUTPUT is the final output of the export process.  FILES is the list of file
    382 names used as the bibliography.
    383 
    384 This function ensures \"biblatex\" package is required.  It also adds resources
    385 to the document, and set styles."
    386   (with-temp-buffer
    387     (save-excursion (insert output))
    388     (when (search-forward "\\begin{document}" nil t)
    389       ;; Ensure there is a \usepackage{biblatex} somewhere or add one.
    390       ;; Then set options.
    391       (goto-char (match-beginning 0))
    392       (let ((re (rx "\\usepackage"
    393                     (opt (group "[" (*? anything) "]"))
    394                     "{biblatex}")))
    395         (cond
    396          ;; No "biblatex" package loaded.  Insert "usepackage" command
    397          ;; with appropriate options, including style.
    398          ((not (re-search-backward re nil t))
    399           (save-excursion
    400             (insert
    401              (format "\\usepackage%s{biblatex}\n"
    402                      (org-cite-biblatex--package-options
    403                       org-cite-biblatex-options style)))))
    404          ;; "biblatex" package loaded, but without any option.
    405          ;; Include style only.
    406          ((not (match-beginning 1))
    407           (search-forward "{" nil t)
    408           (insert (org-cite-biblatex--package-options nil style)))
    409          ;; "biblatex" package loaded with some options set.  Override
    410          ;; style-related options with ours.
    411          (t
    412           (replace-match
    413            (save-match-data
    414              (org-cite-biblatex--package-options (match-string 1) style))
    415            nil nil nil 1))))
    416       ;; Insert resources below.
    417       (forward-line)
    418       (insert (mapconcat (lambda (f)
    419                            (format "\\addbibresource%s{%s}"
    420                                    (if (org-url-p f) "[location=remote]" "")
    421                                    f))
    422                          files
    423                          "\n")
    424               "\n"))
    425     (buffer-string)))
    426 
    427 
    428 ;;; Register `biblatex' processor
    429 (org-cite-register-processor 'biblatex
    430   :export-bibliography #'org-cite-biblatex-export-bibliography
    431   :export-citation #'org-cite-biblatex-export-citation
    432   :export-finalizer #'org-cite-biblatex-prepare-preamble
    433   :cite-styles #'org-cite-biblatex-list-styles)
    434 
    435 (provide 'oc-biblatex)
    436 ;;; oc-biblatex.el ends here