ol-bibtex.el 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. ;;; ol-bibtex.el --- Links to BibTeX entries -*- lexical-binding: t; -*-
  2. ;;
  3. ;; Copyright (C) 2007-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Authors: Bastien Guerry <bzg@gnu.org>
  6. ;; Carsten Dominik <carsten dot dominik at gmail dot com>
  7. ;; Eric Schulte <schulte dot eric at gmail dot com>
  8. ;; Keywords: org, wp, capture
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; This file implements links to database entries in BibTeX files.
  26. ;; Instead of defining a special link prefix, it uses the normal file
  27. ;; links combined with a custom search mechanism to find entries
  28. ;; by reference key. And it constructs a nice description tag for
  29. ;; the link that contains the author name, the year and a short title.
  30. ;;
  31. ;; It also stores detailed information about the entry so that
  32. ;; capture templates can access and enter this information easily.
  33. ;;
  34. ;; The available properties for each entry are listed here:
  35. ;;
  36. ;; :author :publisher :volume :pages
  37. ;; :editor :url :number :journal
  38. ;; :title :year :series :address
  39. ;; :booktitle :month :annote :abstract
  40. ;; :key :btype
  41. ;;
  42. ;; Here is an example of a capture template that use some of this
  43. ;; information (:author :year :title :journal :pages):
  44. ;;
  45. ;; (setq org-capture-templates
  46. ;; '((?b "* READ %?\n\n%a\n\n%:author (%:year): %:title\n \
  47. ;; In %:journal, %:pages.")))
  48. ;;
  49. ;; Let's say you want to capture this BibTeX entry:
  50. ;;
  51. ;; @Article{dolev83,
  52. ;; author = {Danny Dolev and Andrew C. Yao},
  53. ;; title = {On the security of public-key protocols},
  54. ;; journal = {IEEE Transaction on Information Theory},
  55. ;; year = 1983,
  56. ;; volume = 2,
  57. ;; number = 29,
  58. ;; pages = {198--208},
  59. ;; month = {Mars}
  60. ;; }
  61. ;;
  62. ;; M-x `org-capture' on this entry will produce this buffer:
  63. ;;
  64. ;; =====================================================================
  65. ;; * READ <== [point here]
  66. ;;
  67. ;; [[file:file.bib::dolev83][Dolev & Yao 1983: security of public key protocols]]
  68. ;;
  69. ;; Danny Dolev and Andrew C. Yao (1983): On the security of public-key protocols
  70. ;; In IEEE Transaction on Information Theory, 198--208.
  71. ;; =====================================================================
  72. ;;
  73. ;; Additionally, the following functions are now available for storing
  74. ;; bibtex entries within Org documents.
  75. ;;
  76. ;; - Run `org-bibtex' to export the current file to a .bib.
  77. ;;
  78. ;; - Run `org-bibtex-check' or `org-bibtex-check-all' to check and
  79. ;; fill in missing field of either the current, or all headlines
  80. ;;
  81. ;; - Run `org-bibtex-create' to add a bibtex entry
  82. ;;
  83. ;; - Use `org-bibtex-read' to read a bibtex entry after `point' or in
  84. ;; the active region, then call `org-bibtex-write' in a .org file to
  85. ;; insert a heading for the read bibtex entry
  86. ;;
  87. ;; - All Bibtex information is taken from the document compiled by
  88. ;; Andrew Roberts from the Bibtex manual, available at
  89. ;; https://www.andy-roberts.net/res/writing/latex/bibentries.pdf
  90. ;;
  91. ;;; History:
  92. ;;
  93. ;; The link creation part has been part of Org for a long time.
  94. ;;
  95. ;; Creating better capture template information was inspired by a request
  96. ;; of Austin Frank: https://orgmode.org/list/m0myu03vbx.fsf@gmail.com
  97. ;; and then implemented by Bastien Guerry.
  98. ;;
  99. ;; Eric Schulte eventually added the functions for translating between
  100. ;; Org headlines and Bibtex entries, and for fleshing out the Bibtex
  101. ;; fields of existing Org headlines.
  102. ;;
  103. ;; Org mode loads this module by default - if this is not what you want,
  104. ;; configure the variable `org-modules'.
  105. ;;; Code:
  106. (require 'org-macs)
  107. (org-assert-version)
  108. (require 'bibtex)
  109. (require 'cl-lib)
  110. (require 'org-compat)
  111. (require 'org-macs)
  112. (require 'ol)
  113. (defvar org-agenda-overriding-header)
  114. (defvar org-agenda-search-view-always-boolean)
  115. (defvar org-bibtex-description nil)
  116. (defvar org-id-locations)
  117. (defvar org-property-end-re)
  118. (defvar org-special-properties)
  119. (defvar org-window-config-before-follow-link)
  120. (declare-function bibtex-beginning-of-entry "bibtex" ())
  121. (declare-function bibtex-generate-autokey "bibtex" ())
  122. (declare-function bibtex-parse-entry "bibtex" (&optional content))
  123. (declare-function bibtex-url "bibtex" (&optional pos no-browse))
  124. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  125. (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
  126. (declare-function org-entry-properties "org" (&optional pom which))
  127. (declare-function org-get-tags "org" (&optional pos local))
  128. (declare-function org-heading-components "org" ())
  129. (declare-function org-insert-heading "org" (&optional arg invisible-ok top))
  130. (declare-function org-map-entries "org" (func &optional match scope &rest skip))
  131. (declare-function org-narrow-to-subtree "org" (&optional element))
  132. (declare-function org-set-property "org" (property value))
  133. (declare-function org-toggle-tag "org" (tag &optional onoff))
  134. (declare-function org-indent-region "org" (start end))
  135. (declare-function org-search-view "org-agenda" (&optional todo-only string edit-at))
  136. ;;; Bibtex data
  137. (defvar org-bibtex-types
  138. '((:article
  139. (:description . "An article from a journal or magazine")
  140. (:required :author :title :journal :year)
  141. (:optional :volume :number :pages :month :note :doi))
  142. (:book
  143. (:description . "A book with an explicit publisher")
  144. (:required (:editor :author) :title :publisher :year)
  145. (:optional (:volume :number) :series :address :edition :month :note :doi))
  146. (:booklet
  147. (:description . "A work that is printed and bound, but without a named publisher or sponsoring institution.")
  148. (:required :title)
  149. (:optional :author :howpublished :address :month :year :note :doi :url))
  150. (:conference
  151. (:description . "")
  152. (:required :author :title :booktitle :year)
  153. (:optional :editor :pages :organization :publisher :address :month :note :doi :url))
  154. (:inbook
  155. (:description . "A part of a book, which may be a chapter (or section or whatever) and/or a range of pages.")
  156. (:required (:author :editor) :title (:chapter :pages) :publisher :year)
  157. (:optional :crossref (:volume :number) :series :type :address :edition :month :note :doi))
  158. (:incollection
  159. (:description . "A part of a book having its own title.")
  160. (:required :author :title :booktitle :publisher :year)
  161. (:optional :crossref :editor (:volume :number) :series :type :chapter :pages :address :edition :month :note :doi))
  162. (:inproceedings
  163. (:description . "An article in a conference proceedings")
  164. (:required :author :title :booktitle :year)
  165. (:optional :crossref :editor (:volume :number) :series :pages :address :month :organization :publisher :note :doi))
  166. (:manual
  167. (:description . "Technical documentation.")
  168. (:required :title)
  169. (:optional :author :organization :address :edition :month :year :note :doi :url))
  170. (:mastersthesis
  171. (:description . "A Master’s thesis.")
  172. (:required :author :title :school :year)
  173. (:optional :type :address :month :note :doi :url))
  174. (:misc
  175. (:description . "Use this type when nothing else fits.")
  176. (:required)
  177. (:optional :author :title :howpublished :month :year :note :doi :url))
  178. (:phdthesis
  179. (:description . "A PhD thesis.")
  180. (:required :author :title :school :year)
  181. (:optional :type :address :month :note :doi :url))
  182. (:proceedings
  183. (:description . "The proceedings of a conference.")
  184. (:required :title :year)
  185. (:optional :editor (:volume :number) :series :address :month :organization :publisher :note :doi))
  186. (:techreport
  187. (:description . "A report published by a school or other institution.")
  188. (:required :author :title :institution :year)
  189. (:optional :type :address :month :note :doi :url))
  190. (:unpublished
  191. (:description . "A document having an author and title, but not formally published.")
  192. (:required :author :title :note)
  193. (:optional :month :year :doi :url)))
  194. "Bibtex entry types with required and optional parameters.")
  195. (defvar org-bibtex-fields
  196. '((:address . "Usually the address of the publisher or other type of institution. For major publishing houses, van Leunen recommends omitting the information entirely. For small publishers, on the other hand, you can help the reader by giving the complete address.")
  197. (:annote . "An annotation. It is not used by the standard bibliography styles, but may be used by others that produce an annotated bibliography.")
  198. (:author . "The name(s) of the author(s), in the format described in the LaTeX book. Remember, all names are separated with the and keyword, and not commas.")
  199. (:booktitle . "Title of a book, part of which is being cited. See the LaTeX book for how to type titles. For book entries, use the title field instead.")
  200. (:chapter . "A chapter (or section or whatever) number.")
  201. (:crossref . "The database key of the entry being cross referenced.")
  202. (:doi . "The digital object identifier.")
  203. (:edition . "The edition of a book for example, 'Second'. This should be an ordinal, and should have the first letter capitalized, as shown here; the standard styles convert to lower case when necessary.")
  204. (:editor . "Name(s) of editor(s), typed as indicated in the LaTeX book. If there is also an author field, then the editor field gives the editor of the book or collection in which the reference appears.")
  205. (:howpublished . "How something strange has been published. The first word should be capitalized.")
  206. (:institution . "The sponsoring institution of a technical report.")
  207. (:journal . "A journal name.")
  208. (:key . "Used for alphabetizing, cross-referencing, and creating a label when the author information is missing. This field should not be confused with the key that appears in the \\cite command and at the beginning of the database entry.")
  209. (:month . "The month in which the work was published or, for an unpublished work, in which it was written. You should use the standard three-letter abbreviation,")
  210. (:note . "Any additional information that can help the reader. The first word should be capitalized.")
  211. (:number . "Any additional information that can help the reader. The first word should be capitalized.")
  212. (:organization . "The organization that sponsors a conference or that publishes a manual.")
  213. (:pages . "One or more page numbers or range of numbers, such as 42-111 or 7,41,73-97 or 43+ (the ‘+’ in this last example indicates pages following that don’t form simple range). BibTEX requires double dashes for page ranges (--).")
  214. (:publisher . "The publisher’s name.")
  215. (:school . "The name of the school where a thesis was written.")
  216. (:series . "The name of a series or set of books. When citing an entire book, the title field gives its title and an optional series field gives the name of a series or multi-volume set in which the book is published.")
  217. (:title . "The work’s title, typed as explained in the LaTeX book.")
  218. (:type . "The type of a technical report for example, 'Research Note'.")
  219. (:url . "Uniform resource locator.")
  220. (:volume . "The volume of a journal or multi-volume book.")
  221. (:year . "The year of publication or, for an unpublished work, the year it was written. Generally it should consist of four numerals, such as 1984, although the standard styles can handle any year whose last four nonpunctuation characters are numerals, such as '(about 1984)'"))
  222. "Bibtex fields with descriptions.")
  223. (defvar org-bibtex-entries nil
  224. "List to hold parsed bibtex entries.")
  225. (defcustom org-bibtex-autogen-keys nil
  226. "Set to a truth value to use `bibtex-generate-autokey' to generate keys."
  227. :group 'org-bibtex
  228. :version "24.1"
  229. :type 'boolean)
  230. (defcustom org-bibtex-prefix nil
  231. "Optional prefix for all bibtex property names.
  232. For example setting to `BIB_' would allow interoperability with fireforg."
  233. :group 'org-bibtex
  234. :version "24.1"
  235. :type '(choice
  236. (const nil)
  237. (string)))
  238. (defcustom org-bibtex-treat-headline-as-title t
  239. "Treat headline text as title if title property is absent.
  240. If an entry is missing a title property, use the headline text as
  241. the property. If this value is t, `org-bibtex-check' will ignore
  242. a missing title field."
  243. :group 'org-bibtex
  244. :version "24.1"
  245. :type 'boolean)
  246. (defcustom org-bibtex-headline-format-function
  247. (lambda (entry) (cdr (assq :title entry)))
  248. "Function returning the headline text for `org-bibtex-write'.
  249. It should take a single argument, the bibtex entry (an alist as
  250. returned by `org-bibtex-read'). The default value simply returns
  251. the entry title."
  252. :group 'org-bibtex
  253. :version "26.1"
  254. :package-version '(Org . "9.1")
  255. :type 'function)
  256. (defcustom org-bibtex-export-arbitrary-fields nil
  257. "When converting to bibtex allow fields not defined in `org-bibtex-fields'.
  258. This only has effect if `org-bibtex-prefix' is defined, so as to
  259. ensure that other org-properties, such as CATEGORY or LOGGING are
  260. not placed in the exported bibtex entry."
  261. :group 'org-bibtex
  262. :version "24.1"
  263. :type 'boolean)
  264. (defcustom org-bibtex-key-property "CUSTOM_ID"
  265. "Property that holds the bibtex key.
  266. By default, this is CUSTOM_ID, which enables easy linking to
  267. bibtex headlines from within an org file. This can be set to ID
  268. to enable global links, but only with great caution, as global
  269. IDs must be unique."
  270. :group 'org-bibtex
  271. :version "24.1"
  272. :type 'string)
  273. (defcustom org-bibtex-tags nil
  274. "List of tag(s) that should be added to new bib entries."
  275. :group 'org-bibtex
  276. :version "24.1"
  277. :type '(repeat :tag "Tag" (string)))
  278. (defcustom org-bibtex-tags-are-keywords nil
  279. "Convert the value of the keywords field to tags and vice versa.
  280. When non-nil, comma-separated entries in a bibtex entry's keywords
  281. field will be converted to Org tags. Note: spaces will be escaped
  282. with underscores, and characters that are not permitted in Org
  283. tags will be removed.
  284. When non-nil, local tags in an Org entry will be exported as
  285. a comma-separated string of keywords when exported to bibtex.
  286. If `org-bibtex-inherit-tags' is non-nil, inherited tags will also
  287. be exported as keywords. Tags defined in `org-bibtex-tags' or
  288. `org-bibtex-no-export-tags' will not be exported."
  289. :group 'org-bibtex
  290. :version "24.1"
  291. :type 'boolean)
  292. (defcustom org-bibtex-no-export-tags nil
  293. "List of tag(s) that should not be converted to keywords.
  294. This variable is relevant only if `org-bibtex-tags-are-keywords'
  295. is non-nil."
  296. :group 'org-bibtex
  297. :version "24.1"
  298. :type '(repeat :tag "Tag" (string)))
  299. (defcustom org-bibtex-inherit-tags nil
  300. "Controls whether inherited tags are converted to bibtex keywords.
  301. It is relevant only if `org-bibtex-tags-are-keywords' is non-nil.
  302. Tag inheritance itself is controlled by `org-use-tag-inheritance'
  303. and `org-tags-exclude-from-inheritance'."
  304. :group 'org-bibtex
  305. :version "26.1"
  306. :package-version '(Org . "8.3")
  307. :type 'boolean)
  308. (defcustom org-bibtex-type-property-name "btype"
  309. "Property in which to store bibtex entry type (e.g., article)."
  310. :group 'org-bibtex
  311. :version "24.1"
  312. :type 'string)
  313. ;;; Utility functions
  314. (defun org-bibtex-get (property)
  315. (let ((it (let ((org-special-properties
  316. (delete "FILE" (copy-sequence org-special-properties))))
  317. (or
  318. (org-entry-get (point) (upcase property))
  319. (org-entry-get (point) (concat org-bibtex-prefix
  320. (upcase property)))))))
  321. (when it (org-trim it))))
  322. (defun org-bibtex-put (property value &optional insert-raw)
  323. "Set PROPERTY of headline at point to VALUE.
  324. The PROPERTY will be prefixed with `org-bibtex-prefix' when necessary.
  325. With non-nil optional argument INSERT-RAW, insert node property string
  326. at point."
  327. (let* ((prop (upcase (if (keywordp property)
  328. (substring (symbol-name property) 1)
  329. property)))
  330. (prop (concat (unless (string= org-bibtex-key-property prop)
  331. org-bibtex-prefix)
  332. prop)))
  333. (if insert-raw
  334. (insert (format ":%s: %s\n" prop value))
  335. (org-set-property prop value))))
  336. (defun org-bibtex-headline ()
  337. "Return a bibtex entry of the given headline as a string."
  338. (letrec ((val (lambda (key lst) (cdr (assoc key lst))))
  339. (to (lambda (string) (intern (concat ":" string))))
  340. (from (lambda (key) (substring (symbol-name key) 1)))
  341. (flatten (lambda (&rest lsts)
  342. (apply #'append (mapcar
  343. (lambda (e)
  344. (if (listp e) (apply flatten e) (list e)))
  345. lsts))))
  346. (id (org-bibtex-get org-bibtex-key-property))
  347. (type (org-bibtex-get org-bibtex-type-property-name))
  348. (tags (when org-bibtex-tags-are-keywords
  349. (delq nil
  350. (mapcar
  351. (lambda (tag)
  352. (unless (member tag
  353. (append org-bibtex-tags
  354. org-bibtex-no-export-tags))
  355. tag))
  356. (if org-bibtex-inherit-tags (org-get-tags)
  357. (org-get-tags nil t)))))))
  358. (when type
  359. (let ((entry (format
  360. "@%s{%s,\n%s\n}\n" type id
  361. (mapconcat
  362. (lambda (pair)
  363. (format " %s={%s}" (car pair) (cdr pair)))
  364. (remove nil
  365. (if (and org-bibtex-export-arbitrary-fields
  366. org-bibtex-prefix)
  367. (mapcar
  368. (lambda (kv)
  369. (let ((key (car kv)) (val0 (cdr kv)))
  370. (when (and
  371. (string-match org-bibtex-prefix key)
  372. (not (string=
  373. (downcase (concat org-bibtex-prefix
  374. org-bibtex-type-property-name))
  375. (downcase key))))
  376. (cons (downcase (replace-regexp-in-string
  377. org-bibtex-prefix "" key))
  378. val0))))
  379. (org-entry-properties nil 'standard))
  380. (mapcar
  381. (lambda (field)
  382. (let ((value (or (org-bibtex-get (funcall from field))
  383. (and (eq :title field)
  384. (nth 4 (org-heading-components))))))
  385. (when value (cons (funcall from field) value))))
  386. (funcall flatten
  387. (funcall val :required (funcall val (funcall to type) org-bibtex-types))
  388. (funcall val :optional (funcall val (funcall to type) org-bibtex-types))))))
  389. ",\n"))))
  390. (with-temp-buffer
  391. (insert entry)
  392. (when tags
  393. (bibtex-beginning-of-entry)
  394. (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
  395. (progn (goto-char (match-end 1)) (insert ", "))
  396. (search-forward ",\n" nil t)
  397. (insert " keywords={},\n")
  398. (search-backward "}," nil t))
  399. (insert (mapconcat #'identity tags ", ")))
  400. (buffer-string))))))
  401. (defun org-bibtex-ask (field)
  402. (unless (assoc field org-bibtex-fields)
  403. (error "Field:%s is not known" field))
  404. (save-window-excursion
  405. (let* ((name (substring (symbol-name field) 1))
  406. (buf-name (format "*Bibtex Help %s*" name)))
  407. (with-output-to-temp-buffer buf-name
  408. (princ (cdr (assoc field org-bibtex-fields))))
  409. (with-current-buffer buf-name (visual-line-mode 1))
  410. (org-fit-window-to-buffer (get-buffer-window buf-name))
  411. (let ((result (read-from-minibuffer (format "%s: " name))))
  412. (when (> (length result) 0) result)))))
  413. (defun org-bibtex-autokey ()
  414. "Generate an autokey for the current headline."
  415. (org-bibtex-put org-bibtex-key-property
  416. (if org-bibtex-autogen-keys
  417. (let* ((entry (org-bibtex-headline))
  418. (key
  419. (with-temp-buffer
  420. (insert entry)
  421. (bibtex-generate-autokey))))
  422. ;; test for duplicate IDs if using global ID
  423. (when (and
  424. (equal org-bibtex-key-property "ID")
  425. (featurep 'org-id)
  426. (hash-table-p org-id-locations)
  427. (gethash key org-id-locations))
  428. (warn "Another entry has the same ID"))
  429. key)
  430. (read-from-minibuffer "id: "))))
  431. (defun org-bibtex-fleshout (type &optional optional)
  432. "Fleshout current heading, ensuring all required fields are present.
  433. With optional argument OPTIONAL, also prompt for optional fields."
  434. (let ((val (lambda (key lst) (cdr (assoc key lst))))
  435. (keyword (lambda (name) (intern (concat ":" (downcase name)))))
  436. (name (lambda (keyword) (substring (symbol-name keyword) 1))))
  437. (dolist (field (append
  438. (if org-bibtex-treat-headline-as-title
  439. (remove :title (funcall val :required (funcall val type org-bibtex-types)))
  440. (funcall val :required (funcall val type org-bibtex-types)))
  441. (when optional (funcall val :optional (funcall val type org-bibtex-types)))))
  442. (when (consp field) ; or'd pair of fields e.g., (:editor :author)
  443. (let ((present (nth 0 (remove
  444. nil
  445. (mapcar
  446. (lambda (f)
  447. (when (org-bibtex-get (funcall name f)) f))
  448. field)))))
  449. (setf field (or present (funcall keyword
  450. (completing-read
  451. "Field: " (mapcar name field)))))))
  452. (let ((name (funcall name field)))
  453. (unless (org-bibtex-get name)
  454. (let ((prop (org-bibtex-ask field)))
  455. (when prop (org-bibtex-put name prop)))))))
  456. (when (and type (assoc type org-bibtex-types)
  457. (not (org-bibtex-get org-bibtex-key-property)))
  458. (org-bibtex-autokey)))
  459. ;;; Bibtex link functions
  460. (org-link-set-parameters "bibtex"
  461. :follow #'org-bibtex-open
  462. :store #'org-bibtex-store-link)
  463. (defun org-bibtex-open (path arg)
  464. "Visit the bibliography entry on PATH.
  465. ARG, when non-nil, is a universal prefix argument. See
  466. `org-open-file' for details."
  467. (org-link-open-as-file path arg))
  468. (defun org-bibtex-store-link ()
  469. "Store a link to a BibTeX entry."
  470. (when (eq major-mode 'bibtex-mode)
  471. (let* ((search (org-create-file-search-in-bibtex))
  472. (link (concat "file:" (abbreviate-file-name buffer-file-name)
  473. "::" search))
  474. (entry (mapcar ; repair strings enclosed in "..." or {...}
  475. (lambda(c)
  476. (if (string-match
  477. "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c))
  478. (cons (car c) (match-string 1 (cdr c))) c))
  479. (save-excursion
  480. (bibtex-beginning-of-entry)
  481. (bibtex-parse-entry)))))
  482. (org-link-store-props
  483. :key (cdr (assoc "=key=" entry))
  484. :author (or (cdr (assoc "author" entry)) "[no author]")
  485. :doi (or (cdr (assoc "doi" entry)) "[no doi]")
  486. :editor (or (cdr (assoc "editor" entry)) "[no editor]")
  487. :title (or (cdr (assoc "title" entry)) "[no title]")
  488. :booktitle (or (cdr (assoc "booktitle" entry)) "[no booktitle]")
  489. :journal (or (cdr (assoc "journal" entry)) "[no journal]")
  490. :publisher (or (cdr (assoc "publisher" entry)) "[no publisher]")
  491. :pages (or (cdr (assoc "pages" entry)) "[no pages]")
  492. :url (or (cdr (assoc "url" entry)) "[no url]")
  493. :year (or (cdr (assoc "year" entry)) "[no year]")
  494. :month (or (cdr (assoc "month" entry)) "[no month]")
  495. :address (or (cdr (assoc "address" entry)) "[no address]")
  496. :volume (or (cdr (assoc "volume" entry)) "[no volume]")
  497. :number (or (cdr (assoc "number" entry)) "[no number]")
  498. :annote (or (cdr (assoc "annote" entry)) "[no annotation]")
  499. :series (or (cdr (assoc "series" entry)) "[no series]")
  500. :abstract (or (cdr (assoc "abstract" entry)) "[no abstract]")
  501. :btype (or (cdr (assoc "=type=" entry)) "[no type]")
  502. :type "bibtex"
  503. :link link
  504. :description org-bibtex-description))))
  505. (defun org-create-file-search-in-bibtex ()
  506. "Create the search string and description for a BibTeX database entry."
  507. ;; Make a good description for this entry, using names, year and the title
  508. ;; Put it into the `description' variable which is dynamically scoped.
  509. (let ((bibtex-autokey-names 1)
  510. (bibtex-autokey-names-stretch 1)
  511. (bibtex-autokey-name-case-convert-function 'identity)
  512. (bibtex-autokey-name-separator " & ")
  513. (bibtex-autokey-additional-names " et al.")
  514. (bibtex-autokey-year-length 4)
  515. (bibtex-autokey-name-year-separator " ")
  516. (bibtex-autokey-titlewords 3)
  517. (bibtex-autokey-titleword-separator " ")
  518. (bibtex-autokey-titleword-case-convert-function 'identity)
  519. (bibtex-autokey-titleword-length 'infty)
  520. (bibtex-autokey-year-title-separator ": "))
  521. (setq org-bibtex-description (bibtex-generate-autokey)))
  522. ;; Now parse the entry, get the key and return it.
  523. (save-excursion
  524. (bibtex-beginning-of-entry)
  525. (cdr (assoc "=key=" (bibtex-parse-entry)))))
  526. (defun org-execute-file-search-in-bibtex (s)
  527. "Find the link search string S as a key for a database entry."
  528. (when (eq major-mode 'bibtex-mode)
  529. ;; Yes, we want to do the search in this file.
  530. ;; We construct a regexp that searches for "@entrytype{" followed by the key
  531. (goto-char (point-min))
  532. (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
  533. (regexp-quote s) "[ \t\n]*,")
  534. nil t)
  535. (goto-char (match-beginning 0)))
  536. (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
  537. ;; Use double prefix to indicate that any web link should be browsed
  538. (let ((b (current-buffer)) (p (point)))
  539. ;; Restore the window configuration because we just use the web link
  540. (set-window-configuration org-window-config-before-follow-link)
  541. (with-current-buffer b
  542. (goto-char p)
  543. (bibtex-url)))
  544. (recenter 0)) ; Move entry start to beginning of window
  545. ;; return t to indicate that the search is done.
  546. t))
  547. ;; Finally add the link search function to the right hook.
  548. (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
  549. ;;; Bibtex <-> Org headline translation functions
  550. (defun org-bibtex (filename)
  551. "Export each headline in the current file to a bibtex entry.
  552. Headlines are exported using `org-bibtex-headline'."
  553. (interactive
  554. (list (read-file-name
  555. "Bibtex file: " nil nil nil
  556. (let ((file (buffer-file-name (buffer-base-buffer))))
  557. (and file
  558. (file-name-nondirectory
  559. (concat (file-name-sans-extension file) ".bib")))))))
  560. (let ((error-point
  561. (catch 'bib
  562. (let ((bibtex-entries
  563. (remove nil (org-map-entries
  564. (lambda ()
  565. (condition-case nil
  566. (org-bibtex-headline)
  567. (error (throw 'bib (point)))))))))
  568. (with-temp-file filename
  569. (insert (mapconcat #'identity bibtex-entries "\n")))
  570. (message "Successfully exported %d BibTeX entries to %s"
  571. (length bibtex-entries) filename)
  572. nil))))
  573. (when error-point
  574. (goto-char error-point)
  575. (message "Bibtex error at %S" (nth 4 (org-heading-components))))))
  576. (defun org-bibtex-check (&optional optional)
  577. "Check the current headline for required fields.
  578. With prefix argument OPTIONAL also prompt for optional fields."
  579. (interactive "P")
  580. (save-restriction
  581. (org-narrow-to-subtree)
  582. (let ((type (let ((name (org-bibtex-get org-bibtex-type-property-name)))
  583. (when name (intern (concat ":" name))))))
  584. (when type (org-bibtex-fleshout type optional)))))
  585. (defun org-bibtex-check-all (&optional optional)
  586. "Check all headlines in the current file.
  587. With prefix argument OPTIONAL also prompt for optional fields."
  588. (interactive) (org-map-entries (lambda () (org-bibtex-check optional))))
  589. (defun org-bibtex-create (&optional arg nonew)
  590. "Create a new entry at the given level.
  591. With a prefix arg, query for optional fields as well.
  592. If nonew is t, add data to the headline of the entry at point."
  593. (interactive "P")
  594. (let* ((type (completing-read
  595. "Type: " (mapcar (lambda (type)
  596. (substring (symbol-name (car type)) 1))
  597. org-bibtex-types)
  598. nil nil (when nonew
  599. (org-bibtex-get org-bibtex-type-property-name))))
  600. (type (if (keywordp type) type (intern (concat ":" type))))
  601. (org-bibtex-treat-headline-as-title (if nonew nil t)))
  602. (unless (assoc type org-bibtex-types)
  603. (error "Type:%s is not known" type))
  604. (if nonew
  605. (org-back-to-heading)
  606. (org-insert-heading)
  607. (let ((title (org-bibtex-ask :title)))
  608. (insert title)
  609. (org-bibtex-put "TITLE" title)))
  610. (org-bibtex-put org-bibtex-type-property-name
  611. (substring (symbol-name type) 1))
  612. (org-bibtex-fleshout type arg)
  613. (dolist (tag org-bibtex-tags) (org-toggle-tag tag 'on))))
  614. (defun org-bibtex-create-in-current-entry (&optional arg)
  615. "Add bibliographical data to the current entry.
  616. With a prefix arg, query for optional fields."
  617. (interactive "P")
  618. (org-bibtex-create arg t))
  619. (defun org-bibtex-read ()
  620. "Read a bibtex entry and save to `org-bibtex-entries'.
  621. This uses `bibtex-parse-entry'.
  622. Return the new value of `org-bibtex-entries'."
  623. (interactive)
  624. (let ((keyword (lambda (str) (intern (concat ":" (downcase str)))))
  625. (clean-space (lambda (str) (replace-regexp-in-string
  626. "[[:space:]\n\r]+" " " str)))
  627. (strip-delim
  628. (lambda (str) ; strip enclosing "..." and {...}
  629. (dolist (pair '((34 . 34) (123 . 125)))
  630. (when (and (> (length str) 1)
  631. (= (aref str 0) (car pair))
  632. (= (aref str (1- (length str))) (cdr pair)))
  633. (setf str (substring str 1 (1- (length str))))))
  634. str)))
  635. (push (mapcar
  636. (lambda (pair)
  637. (cons (let ((field (funcall keyword (car pair))))
  638. (pcase field
  639. (:=type= :type)
  640. (:=key= :key)
  641. (_ field)))
  642. (funcall clean-space (funcall strip-delim (cdr pair)))))
  643. (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
  644. org-bibtex-entries)
  645. (unless (car org-bibtex-entries) (pop org-bibtex-entries))
  646. org-bibtex-entries))
  647. (defun org-bibtex-read-buffer (buffer)
  648. "Read all bibtex entries in BUFFER and save to `org-bibtex-entries'.
  649. Return the number of saved entries."
  650. (interactive "bBuffer: ")
  651. (let ((start-length (length org-bibtex-entries)))
  652. (with-current-buffer buffer
  653. (save-excursion
  654. (goto-char (point-max))
  655. (while (not (= (point) (point-min)))
  656. (backward-char 1)
  657. (org-bibtex-read)
  658. (bibtex-beginning-of-entry))))
  659. (let ((added (- (length org-bibtex-entries) start-length)))
  660. (message "Parsed %d entries" added)
  661. added)))
  662. (defun org-bibtex-read-file (file)
  663. "Read FILE with `org-bibtex-read-buffer'."
  664. (interactive "fFile: ")
  665. (org-bibtex-read-buffer (find-file-noselect file 'nowarn 'rawfile)))
  666. (defun org-bibtex-write (&optional noindent)
  667. "Insert a heading built from the first element of `org-bibtex-entries'.
  668. When optional argument NOINDENT is non-nil, do not indent the properties
  669. drawer."
  670. (interactive)
  671. (unless org-bibtex-entries
  672. (error "No entries in `org-bibtex-entries'"))
  673. (let* ((entry (pop org-bibtex-entries))
  674. (org-special-properties nil) ; avoids errors with `org-entry-put'
  675. (val (lambda (field) (cdr (assoc field entry))))
  676. (togtag (lambda (tag) (org-toggle-tag tag 'on))))
  677. (org-insert-heading)
  678. (insert (funcall org-bibtex-headline-format-function entry))
  679. (insert "\n:PROPERTIES:\n")
  680. (org-bibtex-put "TITLE" (funcall val :title) 'insert)
  681. (org-bibtex-put org-bibtex-type-property-name
  682. (downcase (funcall val :type))
  683. 'insert)
  684. (dolist (pair entry)
  685. (pcase (car pair)
  686. (:title nil)
  687. (:type nil)
  688. (:key (org-bibtex-put org-bibtex-key-property (cdr pair) 'insert))
  689. (:keywords (if org-bibtex-tags-are-keywords
  690. (dolist (kw (split-string (cdr pair) ", *"))
  691. (funcall
  692. togtag
  693. (replace-regexp-in-string
  694. "[^[:alnum:]_@#%]" ""
  695. (replace-regexp-in-string "[ \t]+" "_" kw))))
  696. (org-bibtex-put (car pair) (cdr pair) 'insert)))
  697. (_ (org-bibtex-put (car pair) (cdr pair) 'insert))))
  698. (insert ":END:\n")
  699. (mapc togtag org-bibtex-tags)
  700. (unless noindent
  701. (org-indent-region
  702. (save-excursion (org-back-to-heading t) (point))
  703. (point)))))
  704. (defun org-bibtex-yank ()
  705. "If kill ring holds a bibtex entry yank it as an Org headline."
  706. (interactive)
  707. (let (entry)
  708. (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
  709. (if entry
  710. (org-bibtex-write)
  711. (error "Yanked text does not appear to contain a BibTeX entry"))))
  712. (defun org-bibtex-import-from-file (file)
  713. "Read bibtex entries from FILE and insert as Org headlines after point."
  714. (interactive "fFile: ")
  715. (let ((pos (point)))
  716. (dotimes (_ (org-bibtex-read-file file))
  717. (save-excursion (org-bibtex-write 'noindent))
  718. (re-search-forward org-property-end-re)
  719. (insert "\n"))
  720. (org-indent-region pos (point))))
  721. (defun org-bibtex-export-to-kill-ring ()
  722. "Export current headline to kill ring as bibtex entry."
  723. (interactive)
  724. (let ((result (org-bibtex-headline)))
  725. (kill-new result) result))
  726. (defun org-bibtex-search (string)
  727. "Search for bibliographical entries in agenda files.
  728. This function relies `org-search-view' to locate results."
  729. (interactive "sSearch string: ")
  730. (let ((org-agenda-overriding-header "Bib search results:")
  731. (org-agenda-search-view-always-boolean t))
  732. (org-search-view nil
  733. (format "%s +{:%s%s:}"
  734. string (or org-bibtex-prefix "")
  735. org-bibtex-type-property-name))))
  736. (provide 'ol-bibtex)
  737. ;;; ol-bibtex.el ends here