ol-bibtex.el 32 KB

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