org-bibtex.el 31 KB

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