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 (org-get-tags)
  331. (org-get-tags nil t)))))))
  332. (when type
  333. (let ((entry (format
  334. "@%s{%s,\n%s\n}\n" type id
  335. (mapconcat
  336. (lambda (pair)
  337. (format " %s={%s}" (car pair) (cdr pair)))
  338. (remove nil
  339. (if (and org-bibtex-export-arbitrary-fields
  340. org-bibtex-prefix)
  341. (mapcar
  342. (lambda (kv)
  343. (let ((key (car kv)) (val0 (cdr kv)))
  344. (when (and
  345. (string-match org-bibtex-prefix key)
  346. (not (string=
  347. (downcase (concat org-bibtex-prefix
  348. org-bibtex-type-property-name))
  349. (downcase key))))
  350. (cons (downcase (replace-regexp-in-string
  351. org-bibtex-prefix "" key))
  352. val0))))
  353. (org-entry-properties nil 'standard))
  354. (mapcar
  355. (lambda (field)
  356. (let ((value (or (org-bibtex-get (funcall from field))
  357. (and (eq :title field)
  358. (nth 4 (org-heading-components))))))
  359. (when value (cons (funcall from field) value))))
  360. (funcall flatten
  361. (funcall val :required (funcall val (funcall to type) org-bibtex-types))
  362. (funcall val :optional (funcall val (funcall to type) org-bibtex-types))))))
  363. ",\n"))))
  364. (with-temp-buffer
  365. (insert entry)
  366. (when tags
  367. (bibtex-beginning-of-entry)
  368. (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
  369. (progn (goto-char (match-end 1)) (insert ", "))
  370. (search-forward ",\n" nil t)
  371. (insert " keywords={},\n")
  372. (search-backward "}," nil t))
  373. (insert (mapconcat #'identity tags ", ")))
  374. (buffer-string))))))
  375. (defun org-bibtex-ask (field)
  376. (unless (assoc field org-bibtex-fields)
  377. (error "Field:%s is not known" field))
  378. (save-window-excursion
  379. (let* ((name (substring (symbol-name field) 1))
  380. (buf-name (format "*Bibtex Help %s*" name)))
  381. (with-output-to-temp-buffer buf-name
  382. (princ (cdr (assoc field org-bibtex-fields))))
  383. (with-current-buffer buf-name (visual-line-mode 1))
  384. (org-fit-window-to-buffer (get-buffer-window buf-name))
  385. (let ((result (read-from-minibuffer (format "%s: " name))))
  386. (when (> (length result) 0) result)))))
  387. (defun org-bibtex-autokey ()
  388. "Generate an autokey for the current headline."
  389. (org-bibtex-put org-bibtex-key-property
  390. (if org-bibtex-autogen-keys
  391. (let* ((entry (org-bibtex-headline))
  392. (key
  393. (with-temp-buffer
  394. (insert entry)
  395. (bibtex-generate-autokey))))
  396. ;; test for duplicate IDs if using global ID
  397. (when (and
  398. (equal org-bibtex-key-property "ID")
  399. (featurep 'org-id)
  400. (hash-table-p org-id-locations)
  401. (gethash key org-id-locations))
  402. (warn "Another entry has the same ID"))
  403. key)
  404. (read-from-minibuffer "id: "))))
  405. (defun org-bibtex-fleshout (type &optional optional)
  406. "Fleshout current heading, ensuring all required fields are present.
  407. With optional argument OPTIONAL, also prompt for optional fields."
  408. (let ((val (lambda (key lst) (cdr (assoc key lst))))
  409. (keyword (lambda (name) (intern (concat ":" (downcase name)))))
  410. (name (lambda (keyword) (substring (symbol-name keyword) 1))))
  411. (dolist (field (append
  412. (if org-bibtex-treat-headline-as-title
  413. (remove :title (funcall val :required (funcall val type org-bibtex-types)))
  414. (funcall val :required (funcall val type org-bibtex-types)))
  415. (when optional (funcall val :optional (funcall val type org-bibtex-types)))))
  416. (when (consp field) ; or'd pair of fields e.g., (:editor :author)
  417. (let ((present (nth 0 (remove
  418. nil
  419. (mapcar
  420. (lambda (f)
  421. (when (org-bibtex-get (funcall name f)) f))
  422. field)))))
  423. (setf field (or present (funcall keyword
  424. (completing-read
  425. "Field: " (mapcar name field)))))))
  426. (let ((name (funcall name field)))
  427. (unless (org-bibtex-get name)
  428. (let ((prop (org-bibtex-ask field)))
  429. (when prop (org-bibtex-put name prop)))))))
  430. (when (and type (assoc type org-bibtex-types)
  431. (not (org-bibtex-get org-bibtex-key-property)))
  432. (org-bibtex-autokey)))
  433. ;;; Bibtex link functions
  434. (org-link-set-parameters "bibtex"
  435. :follow #'org-bibtex-open
  436. :store #'org-bibtex-store-link)
  437. (defun org-bibtex-open (path)
  438. "Visit the bibliography entry on PATH."
  439. (let* ((search (when (string-match "::\\(.+\\)\\'" path)
  440. (match-string 1 path)))
  441. (path (substring path 0 (match-beginning 0))))
  442. (org-open-file path t nil search)))
  443. (defun org-bibtex-store-link ()
  444. "Store a link to a BibTeX entry."
  445. (when (eq major-mode 'bibtex-mode)
  446. (let* ((search (org-create-file-search-in-bibtex))
  447. (link (concat "file:" (abbreviate-file-name buffer-file-name)
  448. "::" search))
  449. (entry (mapcar ; repair strings enclosed in "..." or {...}
  450. (lambda(c)
  451. (if (string-match
  452. "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c))
  453. (cons (car c) (match-string 1 (cdr c))) c))
  454. (save-excursion
  455. (bibtex-beginning-of-entry)
  456. (bibtex-parse-entry)))))
  457. (org-store-link-props
  458. :key (cdr (assoc "=key=" entry))
  459. :author (or (cdr (assoc "author" entry)) "[no author]")
  460. :editor (or (cdr (assoc "editor" entry)) "[no editor]")
  461. :title (or (cdr (assoc "title" entry)) "[no title]")
  462. :booktitle (or (cdr (assoc "booktitle" entry)) "[no booktitle]")
  463. :journal (or (cdr (assoc "journal" entry)) "[no journal]")
  464. :publisher (or (cdr (assoc "publisher" entry)) "[no publisher]")
  465. :pages (or (cdr (assoc "pages" entry)) "[no pages]")
  466. :url (or (cdr (assoc "url" entry)) "[no url]")
  467. :year (or (cdr (assoc "year" entry)) "[no year]")
  468. :month (or (cdr (assoc "month" entry)) "[no month]")
  469. :address (or (cdr (assoc "address" entry)) "[no address]")
  470. :volume (or (cdr (assoc "volume" entry)) "[no volume]")
  471. :number (or (cdr (assoc "number" entry)) "[no number]")
  472. :annote (or (cdr (assoc "annote" entry)) "[no annotation]")
  473. :series (or (cdr (assoc "series" entry)) "[no series]")
  474. :abstract (or (cdr (assoc "abstract" entry)) "[no abstract]")
  475. :btype (or (cdr (assoc "=type=" entry)) "[no type]")
  476. :type "bibtex"
  477. :link link
  478. :description org-bibtex-description))))
  479. (defun org-create-file-search-in-bibtex ()
  480. "Create the search string and description for a BibTeX database entry."
  481. ;; Make a good description for this entry, using names, year and the title
  482. ;; Put it into the `description' variable which is dynamically scoped.
  483. (let ((bibtex-autokey-names 1)
  484. (bibtex-autokey-names-stretch 1)
  485. (bibtex-autokey-name-case-convert-function 'identity)
  486. (bibtex-autokey-name-separator " & ")
  487. (bibtex-autokey-additional-names " et al.")
  488. (bibtex-autokey-year-length 4)
  489. (bibtex-autokey-name-year-separator " ")
  490. (bibtex-autokey-titlewords 3)
  491. (bibtex-autokey-titleword-separator " ")
  492. (bibtex-autokey-titleword-case-convert-function 'identity)
  493. (bibtex-autokey-titleword-length 'infty)
  494. (bibtex-autokey-year-title-separator ": "))
  495. (setq org-bibtex-description (bibtex-generate-autokey)))
  496. ;; Now parse the entry, get the key and return it.
  497. (save-excursion
  498. (bibtex-beginning-of-entry)
  499. (cdr (assoc "=key=" (bibtex-parse-entry)))))
  500. (defun org-execute-file-search-in-bibtex (s)
  501. "Find the link search string S as a key for a database entry."
  502. (when (eq major-mode 'bibtex-mode)
  503. ;; Yes, we want to do the search in this file.
  504. ;; We construct a regexp that searches for "@entrytype{" followed by the key
  505. (goto-char (point-min))
  506. (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
  507. (regexp-quote s) "[ \t\n]*,") nil t)
  508. (goto-char (match-beginning 0)))
  509. (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
  510. ;; Use double prefix to indicate that any web link should be browsed
  511. (let ((b (current-buffer)) (p (point)))
  512. ;; Restore the window configuration because we just use the web link
  513. (set-window-configuration org-window-config-before-follow-link)
  514. (with-current-buffer b
  515. (goto-char p)
  516. (bibtex-url)))
  517. (recenter 0)) ; Move entry start to beginning of window
  518. ;; return t to indicate that the search is done.
  519. t))
  520. ;; Finally add the link search function to the right hook.
  521. (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
  522. ;;; Bibtex <-> Org headline translation functions
  523. (defun org-bibtex (filename)
  524. "Export each headline in the current file to a bibtex entry.
  525. Headlines are exported using `org-bibtex-headline'."
  526. (interactive
  527. (list (read-file-name
  528. "Bibtex file: " nil nil nil
  529. (let ((file (buffer-file-name (buffer-base-buffer))))
  530. (and file
  531. (file-name-nondirectory
  532. (concat (file-name-sans-extension file) ".bib")))))))
  533. (let ((error-point
  534. (catch 'bib
  535. (let ((bibtex-entries
  536. (remove nil (org-map-entries
  537. (lambda ()
  538. (condition-case nil
  539. (org-bibtex-headline)
  540. (error (throw 'bib (point)))))))))
  541. (with-temp-file filename
  542. (insert (mapconcat #'identity bibtex-entries "\n")))
  543. (message "Successfully exported %d BibTeX entries to %s"
  544. (length bibtex-entries) filename) nil))))
  545. (when error-point
  546. (goto-char error-point)
  547. (message "Bibtex error at %S" (nth 4 (org-heading-components))))))
  548. (defun org-bibtex-check (&optional optional)
  549. "Check the current headline for required fields.
  550. With prefix argument OPTIONAL also prompt for optional fields."
  551. (interactive "P")
  552. (save-restriction
  553. (org-narrow-to-subtree)
  554. (let ((type (let ((name (org-bibtex-get org-bibtex-type-property-name)))
  555. (when name (intern (concat ":" name))))))
  556. (when type (org-bibtex-fleshout type optional)))))
  557. (defun org-bibtex-check-all (&optional optional)
  558. "Check all headlines in the current file.
  559. With prefix argument OPTIONAL also prompt for optional fields."
  560. (interactive) (org-map-entries (lambda () (org-bibtex-check optional))))
  561. (defun org-bibtex-create (&optional arg nonew)
  562. "Create a new entry at the given level.
  563. With a prefix arg, query for optional fields as well.
  564. If nonew is t, add data to the headline of the entry at point."
  565. (interactive "P")
  566. (let* ((type (completing-read
  567. "Type: " (mapcar (lambda (type)
  568. (substring (symbol-name (car type)) 1))
  569. org-bibtex-types)
  570. nil nil (when nonew
  571. (org-bibtex-get org-bibtex-type-property-name))))
  572. (type (if (keywordp type) type (intern (concat ":" type))))
  573. (org-bibtex-treat-headline-as-title (if nonew nil t)))
  574. (unless (assoc type org-bibtex-types)
  575. (error "Type:%s is not known" type))
  576. (if nonew
  577. (org-back-to-heading)
  578. (org-insert-heading)
  579. (let ((title (org-bibtex-ask :title)))
  580. (insert title)
  581. (org-bibtex-put "TITLE" title)))
  582. (org-bibtex-put org-bibtex-type-property-name
  583. (substring (symbol-name type) 1))
  584. (org-bibtex-fleshout type arg)
  585. (dolist (tag org-bibtex-tags) (org-toggle-tag tag 'on))))
  586. (defun org-bibtex-create-in-current-entry (&optional arg)
  587. "Add bibliographical data to the current entry.
  588. With a prefix arg, query for optional fields."
  589. (interactive "P")
  590. (org-bibtex-create arg t))
  591. (defun org-bibtex-read ()
  592. "Read a bibtex entry and save to `org-bibtex-entries'.
  593. This uses `bibtex-parse-entry'."
  594. (interactive)
  595. (let ((keyword (lambda (str) (intern (concat ":" (downcase str)))))
  596. (clean-space (lambda (str) (replace-regexp-in-string
  597. "[[:space:]\n\r]+" " " str)))
  598. (strip-delim
  599. (lambda (str) ; strip enclosing "..." and {...}
  600. (dolist (pair '((34 . 34) (123 . 125)))
  601. (when (and (> (length str) 1)
  602. (= (aref str 0) (car pair))
  603. (= (aref str (1- (length str))) (cdr pair)))
  604. (setf str (substring str 1 (1- (length str)))))) str)))
  605. (push (mapcar
  606. (lambda (pair)
  607. (cons (let ((field (funcall keyword (car pair))))
  608. (pcase field
  609. (:=type= :type)
  610. (:=key= :key)
  611. (_ field)))
  612. (funcall clean-space (funcall strip-delim (cdr pair)))))
  613. (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
  614. org-bibtex-entries)))
  615. (defun org-bibtex-read-buffer (buffer)
  616. "Read all bibtex entries in BUFFER and save to `org-bibtex-entries'.
  617. Return the number of saved entries."
  618. (interactive "bBuffer: ")
  619. (let ((start-length (length org-bibtex-entries)))
  620. (with-current-buffer buffer
  621. (save-excursion
  622. (goto-char (point-max))
  623. (while (not (= (point) (point-min)))
  624. (backward-char 1)
  625. (org-bibtex-read)
  626. (bibtex-beginning-of-entry))))
  627. (let ((added (- (length org-bibtex-entries) start-length)))
  628. (message "Parsed %d entries" added)
  629. added)))
  630. (defun org-bibtex-read-file (file)
  631. "Read FILE with `org-bibtex-read-buffer'."
  632. (interactive "fFile: ")
  633. (org-bibtex-read-buffer (find-file-noselect file 'nowarn 'rawfile)))
  634. (defun org-bibtex-write ()
  635. "Insert a heading built from the first element of `org-bibtex-entries'."
  636. (interactive)
  637. (when (= (length org-bibtex-entries) 0)
  638. (error "No entries in `org-bibtex-entries'"))
  639. (let* ((entry (pop org-bibtex-entries))
  640. (org-special-properties nil) ; avoids errors with `org-entry-put'
  641. (val (lambda (field) (cdr (assoc field entry))))
  642. (togtag (lambda (tag) (org-toggle-tag tag 'on))))
  643. (org-insert-heading)
  644. (insert (funcall org-bibtex-headline-format-function entry))
  645. (org-bibtex-put "TITLE" (funcall val :title))
  646. (org-bibtex-put org-bibtex-type-property-name
  647. (downcase (funcall val :type)))
  648. (dolist (pair entry)
  649. (pcase (car pair)
  650. (:title nil)
  651. (:type nil)
  652. (:key (org-bibtex-put org-bibtex-key-property (cdr pair)))
  653. (:keywords (if org-bibtex-tags-are-keywords
  654. (dolist (kw (split-string (cdr pair) ", *"))
  655. (funcall
  656. togtag
  657. (replace-regexp-in-string
  658. "[^[:alnum:]_@#%]" ""
  659. (replace-regexp-in-string "[ \t]+" "_" kw))))
  660. (org-bibtex-put (car pair) (cdr pair))))
  661. (_ (org-bibtex-put (car pair) (cdr pair)))))
  662. (mapc togtag org-bibtex-tags)))
  663. (defun org-bibtex-yank ()
  664. "If kill ring holds a bibtex entry yank it as an Org headline."
  665. (interactive)
  666. (let (entry)
  667. (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
  668. (if entry
  669. (org-bibtex-write)
  670. (error "Yanked text does not appear to contain a BibTeX entry"))))
  671. (defun org-bibtex-import-from-file (file)
  672. "Read bibtex entries from FILE and insert as Org headlines after point."
  673. (interactive "fFile: ")
  674. (dotimes (_ (org-bibtex-read-file file))
  675. (save-excursion (org-bibtex-write))
  676. (re-search-forward org-property-end-re)
  677. (open-line 1) (forward-char 1)))
  678. (defun org-bibtex-export-to-kill-ring ()
  679. "Export current headline to kill ring as bibtex entry."
  680. (interactive)
  681. (let ((result (org-bibtex-headline)))
  682. (kill-new result) result))
  683. (defun org-bibtex-search (string)
  684. "Search for bibliographical entries in agenda files.
  685. This function relies `org-search-view' to locate results."
  686. (interactive "sSearch string: ")
  687. (let ((org-agenda-overriding-header "Bib search results:")
  688. (org-agenda-search-view-always-boolean t))
  689. (org-search-view nil
  690. (format "%s +{:%s%s:}"
  691. string (or org-bibtex-prefix "")
  692. org-bibtex-type-property-name))))
  693. (provide 'org-bibtex)
  694. ;;; org-bibtex.el ends here