ol-bibtex.el 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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 'bibtex)
  107. (require 'cl-lib)
  108. (require 'org-compat)
  109. (require 'org-macs)
  110. (require 'ol)
  111. (defvar org-agenda-overriding-header)
  112. (defvar org-agenda-search-view-always-boolean)
  113. (defvar org-bibtex-description nil)
  114. (defvar org-id-locations)
  115. (defvar org-property-end-re)
  116. (defvar org-special-properties)
  117. (defvar org-window-config-before-follow-link)
  118. (declare-function bibtex-beginning-of-entry "bibtex" ())
  119. (declare-function bibtex-generate-autokey "bibtex" ())
  120. (declare-function bibtex-parse-entry "bibtex" (&optional content))
  121. (declare-function bibtex-url "bibtex" (&optional pos no-browse))
  122. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  123. (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
  124. (declare-function org-entry-properties "org" (&optional pom which))
  125. (declare-function org-get-tags "org" (&optional pos local))
  126. (declare-function org-heading-components "org" ())
  127. (declare-function org-insert-heading "org" (&optional arg invisible-ok top))
  128. (declare-function org-map-entries "org" (func &optional match scope &rest skip))
  129. (declare-function org-narrow-to-subtree "org" ())
  130. (declare-function org-set-property "org" (property value))
  131. (declare-function org-toggle-tag "org" (tag &optional onoff))
  132. (declare-function org-search-view "org-agenda" (&optional todo-only string edit-at))
  133. ;;; Bibtex data
  134. (defvar org-bibtex-types
  135. '((:article
  136. (:description . "An article from a journal or magazine")
  137. (:required :author :title :journal :year)
  138. (:optional :volume :number :pages :month :note :doi))
  139. (:book
  140. (:description . "A book with an explicit publisher")
  141. (:required (:editor :author) :title :publisher :year)
  142. (:optional (:volume :number) :series :address :edition :month :note :doi))
  143. (:booklet
  144. (:description . "A work that is printed and bound, but without a named publisher or sponsoring institution.")
  145. (:required :title)
  146. (:optional :author :howpublished :address :month :year :note :doi :url))
  147. (:conference
  148. (:description . "")
  149. (:required :author :title :booktitle :year)
  150. (:optional :editor :pages :organization :publisher :address :month :note :doi :url))
  151. (:inbook
  152. (:description . "A part of a book, which may be a chapter (or section or whatever) and/or a range of pages.")
  153. (:required (:author :editor) :title (:chapter :pages) :publisher :year)
  154. (:optional :crossref (:volume :number) :series :type :address :edition :month :note :doi))
  155. (:incollection
  156. (:description . "A part of a book having its own title.")
  157. (:required :author :title :booktitle :publisher :year)
  158. (:optional :crossref :editor (:volume :number) :series :type :chapter :pages :address :edition :month :note :doi))
  159. (:inproceedings
  160. (:description . "An article in a conference proceedings")
  161. (:required :author :title :booktitle :year)
  162. (:optional :crossref :editor (:volume :number) :series :pages :address :month :organization :publisher :note :doi))
  163. (:manual
  164. (:description . "Technical documentation.")
  165. (:required :title)
  166. (:optional :author :organization :address :edition :month :year :note :doi :url))
  167. (:mastersthesis
  168. (:description . "A Master’s thesis.")
  169. (:required :author :title :school :year)
  170. (:optional :type :address :month :note :doi :url))
  171. (:misc
  172. (:description . "Use this type when nothing else fits.")
  173. (:required)
  174. (:optional :author :title :howpublished :month :year :note :doi :url))
  175. (:phdthesis
  176. (:description . "A PhD thesis.")
  177. (:required :author :title :school :year)
  178. (:optional :type :address :month :note :doi :url))
  179. (:proceedings
  180. (:description . "The proceedings of a conference.")
  181. (:required :title :year)
  182. (:optional :editor (:volume :number) :series :address :month :organization :publisher :note :doi))
  183. (:techreport
  184. (:description . "A report published by a school or other institution.")
  185. (:required :author :title :institution :year)
  186. (:optional :type :address :month :note :doi :url))
  187. (:unpublished
  188. (:description . "A document having an author and title, but not formally published.")
  189. (:required :author :title :note)
  190. (:optional :month :year :doi :url)))
  191. "Bibtex entry types with required and optional parameters.")
  192. (defvar org-bibtex-fields
  193. '((: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.")
  194. (:annote . "An annotation. It is not used by the standard bibliography styles, but may be used by others that produce an annotated bibliography.")
  195. (: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.")
  196. (: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.")
  197. (:chapter . "A chapter (or section or whatever) number.")
  198. (:crossref . "The database key of the entry being cross referenced.")
  199. (:doi . "The digital object identifier.")
  200. (: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.")
  201. (: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.")
  202. (:howpublished . "How something strange has been published. The first word should be capitalized.")
  203. (:institution . "The sponsoring institution of a technical report.")
  204. (:journal . "A journal name.")
  205. (: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.")
  206. (: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,")
  207. (:note . "Any additional information that can help the reader. The first word should be capitalized.")
  208. (:number . "Any additional information that can help the reader. The first word should be capitalized.")
  209. (:organization . "The organization that sponsors a conference or that publishes a manual.")
  210. (: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 (--).")
  211. (:publisher . "The publisher’s name.")
  212. (:school . "The name of the school where a thesis was written.")
  213. (: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.")
  214. (:title . "The work’s title, typed as explained in the LaTeX book.")
  215. (:type . "The type of a technical report for example, 'Research Note'.")
  216. (:url . "Uniform resource locator.")
  217. (:volume . "The volume of a journal or multi-volume book.")
  218. (: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)'"))
  219. "Bibtex fields with descriptions.")
  220. (defvar org-bibtex-entries nil
  221. "List to hold parsed bibtex entries.")
  222. (defcustom org-bibtex-autogen-keys nil
  223. "Set to a truth value to use `bibtex-generate-autokey' to generate keys."
  224. :group 'org-bibtex
  225. :version "24.1"
  226. :type 'boolean)
  227. (defcustom org-bibtex-prefix nil
  228. "Optional prefix for all bibtex property names.
  229. For example setting to `BIB_' would allow interoperability with fireforg."
  230. :group 'org-bibtex
  231. :version "24.1"
  232. :type '(choice
  233. (const nil)
  234. (string)))
  235. (defcustom org-bibtex-treat-headline-as-title t
  236. "Treat headline text as title if title property is absent.
  237. If an entry is missing a title property, use the headline text as
  238. the property. If this value is t, `org-bibtex-check' will ignore
  239. a missing title field."
  240. :group 'org-bibtex
  241. :version "24.1"
  242. :type 'boolean)
  243. (defcustom org-bibtex-headline-format-function
  244. (lambda (entry) (cdr (assq :title entry)))
  245. "Function returning the headline text for `org-bibtex-write'.
  246. It should take a single argument, the bibtex entry (an alist as
  247. returned by `org-bibtex-read'). The default value simply returns
  248. the entry title."
  249. :group 'org-bibtex
  250. :version "26.1"
  251. :package-version '(Org . "9.1")
  252. :type 'function)
  253. (defcustom org-bibtex-export-arbitrary-fields nil
  254. "When converting to bibtex allow fields not defined in `org-bibtex-fields'.
  255. This only has effect if `org-bibtex-prefix' is defined, so as to
  256. ensure that other org-properties, such as CATEGORY or LOGGING are
  257. not placed in the exported bibtex entry."
  258. :group 'org-bibtex
  259. :version "24.1"
  260. :type 'boolean)
  261. (defcustom org-bibtex-key-property "CUSTOM_ID"
  262. "Property that holds the bibtex key.
  263. By default, this is CUSTOM_ID, which enables easy linking to
  264. bibtex headlines from within an org file. This can be set to ID
  265. to enable global links, but only with great caution, as global
  266. IDs must be unique."
  267. :group 'org-bibtex
  268. :version "24.1"
  269. :type 'string)
  270. (defcustom org-bibtex-tags nil
  271. "List of tag(s) that should be added to new bib entries."
  272. :group 'org-bibtex
  273. :version "24.1"
  274. :type '(repeat :tag "Tag" (string)))
  275. (defcustom org-bibtex-tags-are-keywords nil
  276. "Convert the value of the keywords field to tags and vice versa.
  277. When non-nil, comma-separated entries in a bibtex entry's keywords
  278. field will be converted to Org tags. Note: spaces will be escaped
  279. with underscores, and characters that are not permitted in Org
  280. tags will be removed.
  281. When non-nil, local tags in an Org entry will be exported as
  282. a comma-separated string of keywords when exported to bibtex.
  283. If `org-bibtex-inherit-tags' is non-nil, inherited tags will also
  284. be exported as keywords. Tags defined in `org-bibtex-tags' or
  285. `org-bibtex-no-export-tags' will not be exported."
  286. :group 'org-bibtex
  287. :version "24.1"
  288. :type 'boolean)
  289. (defcustom org-bibtex-no-export-tags nil
  290. "List of tag(s) that should not be converted to keywords.
  291. This variable is relevant only if `org-bibtex-tags-are-keywords'
  292. is non-nil."
  293. :group 'org-bibtex
  294. :version "24.1"
  295. :type '(repeat :tag "Tag" (string)))
  296. (defcustom org-bibtex-inherit-tags nil
  297. "Controls whether inherited tags are converted to bibtex keywords.
  298. It is relevant only if `org-bibtex-tags-are-keywords' is non-nil.
  299. Tag inheritance itself is controlled by `org-use-tag-inheritance'
  300. and `org-tags-exclude-from-inheritance'."
  301. :group 'org-bibtex
  302. :version "26.1"
  303. :package-version '(Org . "8.3")
  304. :type 'boolean)
  305. (defcustom org-bibtex-type-property-name "btype"
  306. "Property in which to store bibtex entry type (e.g., article)."
  307. :group 'org-bibtex
  308. :version "24.1"
  309. :type 'string)
  310. ;;; Utility functions
  311. (defun org-bibtex-get (property)
  312. (let ((it (let ((org-special-properties
  313. (delete "FILE" (copy-sequence org-special-properties))))
  314. (or
  315. (org-entry-get (point) (upcase property))
  316. (org-entry-get (point) (concat org-bibtex-prefix
  317. (upcase property)))))))
  318. (when it (org-trim it))))
  319. (defun org-bibtex-put (property value)
  320. (let ((prop (upcase (if (keywordp property)
  321. (substring (symbol-name property) 1)
  322. property))))
  323. (org-set-property
  324. (concat (unless (string= org-bibtex-key-property prop) org-bibtex-prefix)
  325. prop)
  326. value)))
  327. (defun org-bibtex-headline ()
  328. "Return a bibtex entry of the given headline as a string."
  329. (letrec ((val (lambda (key lst) (cdr (assoc key lst))))
  330. (to (lambda (string) (intern (concat ":" string))))
  331. (from (lambda (key) (substring (symbol-name key) 1)))
  332. (flatten (lambda (&rest lsts)
  333. (apply #'append (mapcar
  334. (lambda (e)
  335. (if (listp e) (apply flatten e) (list e)))
  336. lsts))))
  337. (id (org-bibtex-get org-bibtex-key-property))
  338. (type (org-bibtex-get org-bibtex-type-property-name))
  339. (tags (when org-bibtex-tags-are-keywords
  340. (delq nil
  341. (mapcar
  342. (lambda (tag)
  343. (unless (member tag
  344. (append org-bibtex-tags
  345. org-bibtex-no-export-tags))
  346. tag))
  347. (if org-bibtex-inherit-tags (org-get-tags)
  348. (org-get-tags nil t)))))))
  349. (when type
  350. (let ((entry (format
  351. "@%s{%s,\n%s\n}\n" type id
  352. (mapconcat
  353. (lambda (pair)
  354. (format " %s={%s}" (car pair) (cdr pair)))
  355. (remove nil
  356. (if (and org-bibtex-export-arbitrary-fields
  357. org-bibtex-prefix)
  358. (mapcar
  359. (lambda (kv)
  360. (let ((key (car kv)) (val0 (cdr kv)))
  361. (when (and
  362. (string-match org-bibtex-prefix key)
  363. (not (string=
  364. (downcase (concat org-bibtex-prefix
  365. org-bibtex-type-property-name))
  366. (downcase key))))
  367. (cons (downcase (replace-regexp-in-string
  368. org-bibtex-prefix "" key))
  369. val0))))
  370. (org-entry-properties nil 'standard))
  371. (mapcar
  372. (lambda (field)
  373. (let ((value (or (org-bibtex-get (funcall from field))
  374. (and (eq :title field)
  375. (nth 4 (org-heading-components))))))
  376. (when value (cons (funcall from field) value))))
  377. (funcall flatten
  378. (funcall val :required (funcall val (funcall to type) org-bibtex-types))
  379. (funcall val :optional (funcall val (funcall to type) org-bibtex-types))))))
  380. ",\n"))))
  381. (with-temp-buffer
  382. (insert entry)
  383. (when tags
  384. (bibtex-beginning-of-entry)
  385. (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
  386. (progn (goto-char (match-end 1)) (insert ", "))
  387. (search-forward ",\n" nil t)
  388. (insert " keywords={},\n")
  389. (search-backward "}," nil t))
  390. (insert (mapconcat #'identity tags ", ")))
  391. (buffer-string))))))
  392. (defun org-bibtex-ask (field)
  393. (unless (assoc field org-bibtex-fields)
  394. (error "Field:%s is not known" field))
  395. (save-window-excursion
  396. (let* ((name (substring (symbol-name field) 1))
  397. (buf-name (format "*Bibtex Help %s*" name)))
  398. (with-output-to-temp-buffer buf-name
  399. (princ (cdr (assoc field org-bibtex-fields))))
  400. (with-current-buffer buf-name (visual-line-mode 1))
  401. (org-fit-window-to-buffer (get-buffer-window buf-name))
  402. (let ((result (read-from-minibuffer (format "%s: " name))))
  403. (when (> (length result) 0) result)))))
  404. (defun org-bibtex-autokey ()
  405. "Generate an autokey for the current headline."
  406. (org-bibtex-put org-bibtex-key-property
  407. (if org-bibtex-autogen-keys
  408. (let* ((entry (org-bibtex-headline))
  409. (key
  410. (with-temp-buffer
  411. (insert entry)
  412. (bibtex-generate-autokey))))
  413. ;; test for duplicate IDs if using global ID
  414. (when (and
  415. (equal org-bibtex-key-property "ID")
  416. (featurep 'org-id)
  417. (hash-table-p org-id-locations)
  418. (gethash key org-id-locations))
  419. (warn "Another entry has the same ID"))
  420. key)
  421. (read-from-minibuffer "id: "))))
  422. (defun org-bibtex-fleshout (type &optional optional)
  423. "Fleshout current heading, ensuring all required fields are present.
  424. With optional argument OPTIONAL, also prompt for optional fields."
  425. (let ((val (lambda (key lst) (cdr (assoc key lst))))
  426. (keyword (lambda (name) (intern (concat ":" (downcase name)))))
  427. (name (lambda (keyword) (substring (symbol-name keyword) 1))))
  428. (dolist (field (append
  429. (if org-bibtex-treat-headline-as-title
  430. (remove :title (funcall val :required (funcall val type org-bibtex-types)))
  431. (funcall val :required (funcall val type org-bibtex-types)))
  432. (when optional (funcall val :optional (funcall val type org-bibtex-types)))))
  433. (when (consp field) ; or'd pair of fields e.g., (:editor :author)
  434. (let ((present (nth 0 (remove
  435. nil
  436. (mapcar
  437. (lambda (f)
  438. (when (org-bibtex-get (funcall name f)) f))
  439. field)))))
  440. (setf field (or present (funcall keyword
  441. (completing-read
  442. "Field: " (mapcar name field)))))))
  443. (let ((name (funcall name field)))
  444. (unless (org-bibtex-get name)
  445. (let ((prop (org-bibtex-ask field)))
  446. (when prop (org-bibtex-put name prop)))))))
  447. (when (and type (assoc type org-bibtex-types)
  448. (not (org-bibtex-get org-bibtex-key-property)))
  449. (org-bibtex-autokey)))
  450. ;;; Bibtex link functions
  451. (org-link-set-parameters "bibtex"
  452. :follow #'org-bibtex-open
  453. :store #'org-bibtex-store-link)
  454. (defun org-bibtex-open (path arg)
  455. "Visit the bibliography entry on PATH.
  456. ARG, when non-nil, is a universal prefix argument. See
  457. `org-open-file' for details."
  458. (org-link-open-as-file path arg))
  459. (defun org-bibtex-store-link ()
  460. "Store a link to a BibTeX entry."
  461. (when (eq major-mode 'bibtex-mode)
  462. (let* ((search (org-create-file-search-in-bibtex))
  463. (link (concat "file:" (abbreviate-file-name buffer-file-name)
  464. "::" search))
  465. (entry (mapcar ; repair strings enclosed in "..." or {...}
  466. (lambda(c)
  467. (if (string-match
  468. "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c))
  469. (cons (car c) (match-string 1 (cdr c))) c))
  470. (save-excursion
  471. (bibtex-beginning-of-entry)
  472. (bibtex-parse-entry)))))
  473. (org-link-store-props
  474. :key (cdr (assoc "=key=" entry))
  475. :author (or (cdr (assoc "author" entry)) "[no author]")
  476. :doi (or (cdr (assoc "doi" entry)) "[no doi]")
  477. :editor (or (cdr (assoc "editor" entry)) "[no editor]")
  478. :title (or (cdr (assoc "title" entry)) "[no title]")
  479. :booktitle (or (cdr (assoc "booktitle" entry)) "[no booktitle]")
  480. :journal (or (cdr (assoc "journal" entry)) "[no journal]")
  481. :publisher (or (cdr (assoc "publisher" entry)) "[no publisher]")
  482. :pages (or (cdr (assoc "pages" entry)) "[no pages]")
  483. :url (or (cdr (assoc "url" entry)) "[no url]")
  484. :year (or (cdr (assoc "year" entry)) "[no year]")
  485. :month (or (cdr (assoc "month" entry)) "[no month]")
  486. :address (or (cdr (assoc "address" entry)) "[no address]")
  487. :volume (or (cdr (assoc "volume" entry)) "[no volume]")
  488. :number (or (cdr (assoc "number" entry)) "[no number]")
  489. :annote (or (cdr (assoc "annote" entry)) "[no annotation]")
  490. :series (or (cdr (assoc "series" entry)) "[no series]")
  491. :abstract (or (cdr (assoc "abstract" entry)) "[no abstract]")
  492. :btype (or (cdr (assoc "=type=" entry)) "[no type]")
  493. :type "bibtex"
  494. :link link
  495. :description org-bibtex-description))))
  496. (defun org-create-file-search-in-bibtex ()
  497. "Create the search string and description for a BibTeX database entry."
  498. ;; Make a good description for this entry, using names, year and the title
  499. ;; Put it into the `description' variable which is dynamically scoped.
  500. (let ((bibtex-autokey-names 1)
  501. (bibtex-autokey-names-stretch 1)
  502. (bibtex-autokey-name-case-convert-function 'identity)
  503. (bibtex-autokey-name-separator " & ")
  504. (bibtex-autokey-additional-names " et al.")
  505. (bibtex-autokey-year-length 4)
  506. (bibtex-autokey-name-year-separator " ")
  507. (bibtex-autokey-titlewords 3)
  508. (bibtex-autokey-titleword-separator " ")
  509. (bibtex-autokey-titleword-case-convert-function 'identity)
  510. (bibtex-autokey-titleword-length 'infty)
  511. (bibtex-autokey-year-title-separator ": "))
  512. (setq org-bibtex-description (bibtex-generate-autokey)))
  513. ;; Now parse the entry, get the key and return it.
  514. (save-excursion
  515. (bibtex-beginning-of-entry)
  516. (cdr (assoc "=key=" (bibtex-parse-entry)))))
  517. (defun org-execute-file-search-in-bibtex (s)
  518. "Find the link search string S as a key for a database entry."
  519. (when (eq major-mode 'bibtex-mode)
  520. ;; Yes, we want to do the search in this file.
  521. ;; We construct a regexp that searches for "@entrytype{" followed by the key
  522. (goto-char (point-min))
  523. (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
  524. (regexp-quote s) "[ \t\n]*,")
  525. nil t)
  526. (goto-char (match-beginning 0)))
  527. (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
  528. ;; Use double prefix to indicate that any web link should be browsed
  529. (let ((b (current-buffer)) (p (point)))
  530. ;; Restore the window configuration because we just use the web link
  531. (set-window-configuration org-window-config-before-follow-link)
  532. (with-current-buffer b
  533. (goto-char p)
  534. (bibtex-url)))
  535. (recenter 0)) ; Move entry start to beginning of window
  536. ;; return t to indicate that the search is done.
  537. t))
  538. ;; Finally add the link search function to the right hook.
  539. (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
  540. ;;; Bibtex <-> Org headline translation functions
  541. (defun org-bibtex (filename)
  542. "Export each headline in the current file to a bibtex entry.
  543. Headlines are exported using `org-bibtex-headline'."
  544. (interactive
  545. (list (read-file-name
  546. "Bibtex file: " nil nil nil
  547. (let ((file (buffer-file-name (buffer-base-buffer))))
  548. (and file
  549. (file-name-nondirectory
  550. (concat (file-name-sans-extension file) ".bib")))))))
  551. (let ((error-point
  552. (catch 'bib
  553. (let ((bibtex-entries
  554. (remove nil (org-map-entries
  555. (lambda ()
  556. (condition-case nil
  557. (org-bibtex-headline)
  558. (error (throw 'bib (point)))))))))
  559. (with-temp-file filename
  560. (insert (mapconcat #'identity bibtex-entries "\n")))
  561. (message "Successfully exported %d BibTeX entries to %s"
  562. (length bibtex-entries) filename)
  563. nil))))
  564. (when error-point
  565. (goto-char error-point)
  566. (message "Bibtex error at %S" (nth 4 (org-heading-components))))))
  567. (defun org-bibtex-check (&optional optional)
  568. "Check the current headline for required fields.
  569. With prefix argument OPTIONAL also prompt for optional fields."
  570. (interactive "P")
  571. (save-restriction
  572. (org-narrow-to-subtree)
  573. (let ((type (let ((name (org-bibtex-get org-bibtex-type-property-name)))
  574. (when name (intern (concat ":" name))))))
  575. (when type (org-bibtex-fleshout type optional)))))
  576. (defun org-bibtex-check-all (&optional optional)
  577. "Check all headlines in the current file.
  578. With prefix argument OPTIONAL also prompt for optional fields."
  579. (interactive) (org-map-entries (lambda () (org-bibtex-check optional))))
  580. (defun org-bibtex-create (&optional arg nonew)
  581. "Create a new entry at the given level.
  582. With a prefix arg, query for optional fields as well.
  583. If nonew is t, add data to the headline of the entry at point."
  584. (interactive "P")
  585. (let* ((type (completing-read
  586. "Type: " (mapcar (lambda (type)
  587. (substring (symbol-name (car type)) 1))
  588. org-bibtex-types)
  589. nil nil (when nonew
  590. (org-bibtex-get org-bibtex-type-property-name))))
  591. (type (if (keywordp type) type (intern (concat ":" type))))
  592. (org-bibtex-treat-headline-as-title (if nonew nil t)))
  593. (unless (assoc type org-bibtex-types)
  594. (error "Type:%s is not known" type))
  595. (if nonew
  596. (org-back-to-heading)
  597. (org-insert-heading)
  598. (let ((title (org-bibtex-ask :title)))
  599. (insert title)
  600. (org-bibtex-put "TITLE" title)))
  601. (org-bibtex-put org-bibtex-type-property-name
  602. (substring (symbol-name type) 1))
  603. (org-bibtex-fleshout type arg)
  604. (dolist (tag org-bibtex-tags) (org-toggle-tag tag 'on))))
  605. (defun org-bibtex-create-in-current-entry (&optional arg)
  606. "Add bibliographical data to the current entry.
  607. With a prefix arg, query for optional fields."
  608. (interactive "P")
  609. (org-bibtex-create arg t))
  610. (defun org-bibtex-read ()
  611. "Read a bibtex entry and save to `org-bibtex-entries'.
  612. This uses `bibtex-parse-entry'.
  613. Return the new value of `org-bibtex-entries'."
  614. (interactive)
  615. (let ((keyword (lambda (str) (intern (concat ":" (downcase str)))))
  616. (clean-space (lambda (str) (replace-regexp-in-string
  617. "[[:space:]\n\r]+" " " str)))
  618. (strip-delim
  619. (lambda (str) ; strip enclosing "..." and {...}
  620. (dolist (pair '((34 . 34) (123 . 125)))
  621. (when (and (> (length str) 1)
  622. (= (aref str 0) (car pair))
  623. (= (aref str (1- (length str))) (cdr pair)))
  624. (setf str (substring str 1 (1- (length str))))))
  625. str)))
  626. (push (mapcar
  627. (lambda (pair)
  628. (cons (let ((field (funcall keyword (car pair))))
  629. (pcase field
  630. (:=type= :type)
  631. (:=key= :key)
  632. (_ field)))
  633. (funcall clean-space (funcall strip-delim (cdr pair)))))
  634. (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
  635. org-bibtex-entries)
  636. (unless (car org-bibtex-entries) (pop org-bibtex-entries))
  637. org-bibtex-entries))
  638. (defun org-bibtex-read-buffer (buffer)
  639. "Read all bibtex entries in BUFFER and save to `org-bibtex-entries'.
  640. Return the number of saved entries."
  641. (interactive "bBuffer: ")
  642. (let ((start-length (length org-bibtex-entries)))
  643. (with-current-buffer buffer
  644. (save-excursion
  645. (goto-char (point-max))
  646. (while (not (= (point) (point-min)))
  647. (backward-char 1)
  648. (org-bibtex-read)
  649. (bibtex-beginning-of-entry))))
  650. (let ((added (- (length org-bibtex-entries) start-length)))
  651. (message "Parsed %d entries" added)
  652. added)))
  653. (defun org-bibtex-read-file (file)
  654. "Read FILE with `org-bibtex-read-buffer'."
  655. (interactive "fFile: ")
  656. (org-bibtex-read-buffer (find-file-noselect file 'nowarn 'rawfile)))
  657. (defun org-bibtex-write ()
  658. "Insert a heading built from the first element of `org-bibtex-entries'."
  659. (interactive)
  660. (when (= (length org-bibtex-entries) 0)
  661. (error "No entries in `org-bibtex-entries'"))
  662. (let* ((entry (pop org-bibtex-entries))
  663. (org-special-properties nil) ; avoids errors with `org-entry-put'
  664. (val (lambda (field) (cdr (assoc field entry))))
  665. (togtag (lambda (tag) (org-toggle-tag tag 'on))))
  666. (org-insert-heading)
  667. (insert (funcall org-bibtex-headline-format-function entry))
  668. (org-bibtex-put "TITLE" (funcall val :title))
  669. (org-bibtex-put org-bibtex-type-property-name
  670. (downcase (funcall val :type)))
  671. (dolist (pair entry)
  672. (pcase (car pair)
  673. (:title nil)
  674. (:type nil)
  675. (:key (org-bibtex-put org-bibtex-key-property (cdr pair)))
  676. (:keywords (if org-bibtex-tags-are-keywords
  677. (dolist (kw (split-string (cdr pair) ", *"))
  678. (funcall
  679. togtag
  680. (replace-regexp-in-string
  681. "[^[:alnum:]_@#%]" ""
  682. (replace-regexp-in-string "[ \t]+" "_" kw))))
  683. (org-bibtex-put (car pair) (cdr pair))))
  684. (_ (org-bibtex-put (car pair) (cdr pair)))))
  685. (mapc togtag org-bibtex-tags)))
  686. (defun org-bibtex-yank ()
  687. "If kill ring holds a bibtex entry yank it as an Org headline."
  688. (interactive)
  689. (let (entry)
  690. (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
  691. (if entry
  692. (org-bibtex-write)
  693. (error "Yanked text does not appear to contain a BibTeX entry"))))
  694. (defun org-bibtex-import-from-file (file)
  695. "Read bibtex entries from FILE and insert as Org headlines after point."
  696. (interactive "fFile: ")
  697. (dotimes (_ (org-bibtex-read-file file))
  698. (save-excursion (org-bibtex-write))
  699. (re-search-forward org-property-end-re)
  700. (open-line 1) (forward-char 1)))
  701. (defun org-bibtex-export-to-kill-ring ()
  702. "Export current headline to kill ring as bibtex entry."
  703. (interactive)
  704. (let ((result (org-bibtex-headline)))
  705. (kill-new result) result))
  706. (defun org-bibtex-search (string)
  707. "Search for bibliographical entries in agenda files.
  708. This function relies `org-search-view' to locate results."
  709. (interactive "sSearch string: ")
  710. (let ((org-agenda-overriding-header "Bib search results:")
  711. (org-agenda-search-view-always-boolean t))
  712. (org-search-view nil
  713. (format "%s +{:%s%s:}"
  714. string (or org-bibtex-prefix "")
  715. org-bibtex-type-property-name))))
  716. (provide 'ol-bibtex)
  717. ;;; ol-bibtex.el ends here