org-bibtex.el 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. ;;; org-bibtex.el --- Org links to BibTeX entries
  2. ;;
  3. ;; Copyright (C) 2007-2011 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Bastien Guerry <bzg at altern dot 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, remember
  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 <http://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. ;; remember 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 remember template that use some of this
  43. ;; information (:author :year :title :journal :pages):
  44. ;;
  45. ;; (setq org-remember-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 remember 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-remember' 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-mode 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/misc/latex/sessions/bibtex/bibentries.pdf
  90. ;;
  91. ;;; History:
  92. ;;
  93. ;; The link creation part has been part of Org-mode for a long time.
  94. ;;
  95. ;; Creating better remember 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-mode headlines and Bibtex entries, and for fleshing out the Bibtex
  101. ;; fields of existing Org-mode 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. (eval-when-compile
  109. (require 'cl))
  110. (defvar description nil) ; dynamically scoped from org.el
  111. (defvar org-id-locations)
  112. (declare-function bibtex-beginning-of-entry "bibtex" ())
  113. (declare-function bibtex-generate-autokey "bibtex" ())
  114. (declare-function bibtex-parse-entry "bibtex" (&optional content))
  115. (declare-function bibtex-url "bibtex" (&optional pos no-browse))
  116. (declare-function longlines-mode "longlines" (&optional arg))
  117. (declare-function org-babel-trim "ob" (string &optional regexp))
  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 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. :type 'boolean)
  209. (defcustom org-bibtex-prefix nil
  210. "Optional prefix for all bibtex property names.
  211. For example setting to 'BIB_' would allow interoperability with fireforg."
  212. :group 'org-bibtex
  213. :type 'string)
  214. (defcustom org-bibtex-treat-headline-as-title t
  215. "Treat headline text as title if title property is absent.
  216. If an entry is missing a title property, use the headline text as
  217. the property. If this value is t, `org-bibtex-check' will ignore
  218. a missing title field."
  219. :group 'org-bibtex
  220. :type 'boolean)
  221. (defcustom org-bibtex-export-arbitrary-fields nil
  222. "When converting to bibtex allow fields not defined in `org-bibtex-fields'.
  223. This only has effect if `org-bibtex-prefix' is defined, so as to
  224. ensure that other org-properties, such as CATEGORY or LOGGING are
  225. not placed in the exported bibtex entry."
  226. :group 'org-bibtex
  227. :type 'boolean)
  228. (defcustom org-bibtex-key-property "CUSTOM_ID"
  229. "Property that holds the bibtex key.
  230. By default, this is CUSTOM_ID, which enables easy linking to
  231. bibtex headlines from within an org file. This can be set to ID
  232. to enable global links, but only with great caution, as global
  233. IDs must be unique."
  234. :group 'org-bibtex
  235. :type 'string)
  236. (defcustom org-bibtex-tags nil
  237. "List of tag(s) that should be added to new bib entries."
  238. :group 'org-bibtex
  239. :type '(repeat :tag "Tag" (string)))
  240. (defcustom org-bibtex-tags-are-keywords nil
  241. "Convert the value of the keywords field to tags and vice versa.
  242. If set to t, comma-separated entries in a bibtex entry's keywords
  243. field will be converted to org tags. Note: spaces will be escaped
  244. with underscores, and characters that are not permitted in org
  245. tags will be removed.
  246. If t, local tags in an org entry will be exported as a
  247. comma-separated string of keywords when exported to bibtex. Tags
  248. defined in `org-bibtex-tags' or `org-bibtex-no-export-tags' will
  249. not be exported."
  250. :group 'org-bibtex
  251. :type 'boolean)
  252. (defcustom org-bibtex-no-export-tags nil
  253. "List of tag(s) that should not be converted to keywords.
  254. This variable is relevant only if `org-bibtex-export-tags-as-keywords` is t."
  255. :group 'org-bibtex
  256. :type '(repeat :tag "Tag" (string)))
  257. (defcustom org-bibtex-type-property-name "btype"
  258. "Property in which to store bibtex entry type (e.g., article)."
  259. :group 'org-bibtex
  260. :type 'string)
  261. ;;; Utility functions
  262. (defun org-bibtex-get (property)
  263. ((lambda (it) (when it (org-babel-trim it)))
  264. (let ((org-special-properties
  265. (delete "FILE" (copy-sequence org-special-properties))))
  266. (or
  267. (org-entry-get (point) (upcase property))
  268. (org-entry-get (point) (concat org-bibtex-prefix (upcase property)))))))
  269. (defun org-bibtex-put (property value)
  270. (let ((prop (upcase (if (keywordp property)
  271. (substring (symbol-name property) 1)
  272. property))))
  273. (org-set-property
  274. (concat (unless (string= org-bibtex-key-property prop) org-bibtex-prefix)
  275. prop)
  276. value)))
  277. (defun org-bibtex-headline ()
  278. "Return a bibtex entry of the given headline as a string."
  279. (flet ((val (key lst) (cdr (assoc key lst)))
  280. (to (string) (intern (concat ":" string)))
  281. (from (key) (substring (symbol-name key) 1))
  282. (flatten (&rest lsts)
  283. (apply #'append (mapcar
  284. (lambda (e)
  285. (if (listp e) (apply #'flatten e) (list e)))
  286. lsts))))
  287. (let ((notes (buffer-string))
  288. (id (org-bibtex-get org-bibtex-key-property))
  289. (type (org-bibtex-get org-bibtex-type-property-name))
  290. (tags (when org-bibtex-tags-are-keywords
  291. (delq nil
  292. (mapcar
  293. (lambda (tag)
  294. (unless (member tag
  295. (append org-bibtex-tags
  296. org-bibtex-no-export-tags))
  297. tag))
  298. (org-get-local-tags-at))))))
  299. (when type
  300. (let ((entry (format
  301. "@%s{%s,\n%s\n}\n" type id
  302. (mapconcat
  303. (lambda (pair)
  304. (format " %s={%s}" (car pair) (cdr pair)))
  305. (remove nil
  306. (if (and org-bibtex-export-arbitrary-fields
  307. org-bibtex-prefix)
  308. (mapcar
  309. (lambda (kv)
  310. (let ((key (car kv)) (val (cdr kv)))
  311. (when (and
  312. (string-match org-bibtex-prefix key)
  313. (not (string=
  314. (downcase (concat org-bibtex-prefix
  315. org-bibtex-type-property-name))
  316. (downcase key))))
  317. (cons (downcase (replace-regexp-in-string
  318. org-bibtex-prefix "" key))
  319. val))))
  320. (org-entry-properties nil 'standard))
  321. (mapcar
  322. (lambda (field)
  323. (let ((value (or (org-bibtex-get (from field))
  324. (and (equal :title field)
  325. (nth 4 (org-heading-components))))))
  326. (when value (cons (from field) value))))
  327. (flatten
  328. (val :required (val (to type) org-bibtex-types))
  329. (val :optional (val (to type) org-bibtex-types))))))
  330. ",\n"))))
  331. (with-temp-buffer
  332. (insert entry)
  333. (when tags
  334. (bibtex-beginning-of-entry)
  335. (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
  336. (progn (goto-char (match-end 1)) (insert ", "))
  337. (bibtex-make-field "keywords" t t))
  338. (insert (mapconcat #'identity tags ", ")))
  339. (bibtex-reformat) (buffer-string)))))))
  340. (defun org-bibtex-ask (field)
  341. (unless (assoc field org-bibtex-fields)
  342. (error "field:%s is not known" field))
  343. (save-window-excursion
  344. (let* ((name (substring (symbol-name field) 1))
  345. (buf-name (format "*Bibtex Help %s*" name)))
  346. (with-output-to-temp-buffer buf-name
  347. (princ (cdr (assoc field org-bibtex-fields))))
  348. (with-current-buffer buf-name (longlines-mode t))
  349. (org-fit-window-to-buffer (get-buffer-window buf-name))
  350. ((lambda (result) (when (> (length result) 0) result))
  351. (read-from-minibuffer (format "%s: " name))))))
  352. (defun org-bibtex-autokey ()
  353. "Generate an autokey for the current headline"
  354. (org-bibtex-put org-bibtex-key-property
  355. (if org-bibtex-autogen-keys
  356. (let* ((entry (org-bibtex-headline))
  357. (key
  358. (with-temp-buffer
  359. (insert entry)
  360. (bibtex-generate-autokey))))
  361. ;; test for duplicate IDs if using global ID
  362. (when (and
  363. (equal org-bibtex-key-property "ID")
  364. (featurep 'org-id)
  365. (hash-table-p org-id-locations)
  366. (gethash key org-id-locations))
  367. (warn "Another entry has the same ID"))
  368. key)
  369. (read-from-minibuffer "id: "))))
  370. (defun org-bibtex-fleshout (type &optional optional)
  371. "Fleshout the current heading, ensuring that all required fields are present.
  372. With optional argument OPTIONAL, also prompt for optional fields."
  373. (flet ((val (key lst) (cdr (assoc key lst)))
  374. (keyword (name) (intern (concat ":" (downcase name))))
  375. (name (keyword) (substring (symbol-name keyword) 1)))
  376. (dolist (field (append
  377. (if org-bibtex-treat-headline-as-title
  378. (remove :title (val :required (val type org-bibtex-types)))
  379. (val :required (val type org-bibtex-types)))
  380. (when optional (val :optional (val type org-bibtex-types)))))
  381. (when (consp field) ; or'd pair of fields e.g., (:editor :author)
  382. (let ((present (first (remove nil
  383. (mapcar
  384. (lambda (f) (when (org-bibtex-get (name f)) f))
  385. field)))))
  386. (setf field (or present (keyword (org-icompleting-read
  387. "Field: " (mapcar #'name field)))))))
  388. (let ((name (name field)))
  389. (unless (org-bibtex-get name)
  390. (let ((prop (org-bibtex-ask field)))
  391. (when prop (org-bibtex-put name prop)))))))
  392. (when (and type (assoc type org-bibtex-types)
  393. (not (org-bibtex-get org-bibtex-key-property)))
  394. (org-bibtex-autokey)))
  395. ;;; Bibtex link functions
  396. (org-add-link-type "bibtex" 'org-bibtex-open)
  397. (add-hook 'org-store-link-functions 'org-bibtex-store-link)
  398. (defun org-bibtex-open (path)
  399. "Visit the bibliography entry on PATH."
  400. (let* ((search (when (string-match "::\\(.+\\)\\'" path)
  401. (match-string 1 path)))
  402. (path (substring path 0 (match-beginning 0))))
  403. (org-open-file path t nil search)))
  404. (defun org-bibtex-store-link ()
  405. "Store a link to a BibTeX entry."
  406. (when (eq major-mode 'bibtex-mode)
  407. (let* ((search (org-create-file-search-in-bibtex))
  408. (link (concat "file:" (abbreviate-file-name buffer-file-name)
  409. "::" search))
  410. (entry (mapcar ; repair strings enclosed in "..." or {...}
  411. (lambda(c)
  412. (if (string-match
  413. "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c))
  414. (cons (car c) (match-string 1 (cdr c))) c))
  415. (save-excursion
  416. (bibtex-beginning-of-entry)
  417. (bibtex-parse-entry)))))
  418. (org-store-link-props
  419. :key (cdr (assoc "=key=" entry))
  420. :author (or (cdr (assoc "author" entry)) "[no author]")
  421. :editor (or (cdr (assoc "editor" entry)) "[no editor]")
  422. :title (or (cdr (assoc "title" entry)) "[no title]")
  423. :booktitle (or (cdr (assoc "booktitle" entry)) "[no booktitle]")
  424. :journal (or (cdr (assoc "journal" entry)) "[no journal]")
  425. :publisher (or (cdr (assoc "publisher" entry)) "[no publisher]")
  426. :pages (or (cdr (assoc "pages" entry)) "[no pages]")
  427. :url (or (cdr (assoc "url" entry)) "[no url]")
  428. :year (or (cdr (assoc "year" entry)) "[no year]")
  429. :month (or (cdr (assoc "month" entry)) "[no month]")
  430. :address (or (cdr (assoc "address" entry)) "[no address]")
  431. :volume (or (cdr (assoc "volume" entry)) "[no volume]")
  432. :number (or (cdr (assoc "number" entry)) "[no number]")
  433. :annote (or (cdr (assoc "annote" entry)) "[no annotation]")
  434. :series (or (cdr (assoc "series" entry)) "[no series]")
  435. :abstract (or (cdr (assoc "abstract" entry)) "[no abstract]")
  436. :btype (or (cdr (assoc "=type=" entry)) "[no type]")
  437. :type "bibtex"
  438. :link link
  439. :description description))))
  440. (defun org-create-file-search-in-bibtex ()
  441. "Create the search string and description for a BibTeX database entry."
  442. ;; Make a good description for this entry, using names, year and the title
  443. ;; Put it into the `description' variable which is dynamically scoped.
  444. (let ((bibtex-autokey-names 1)
  445. (bibtex-autokey-names-stretch 1)
  446. (bibtex-autokey-name-case-convert-function 'identity)
  447. (bibtex-autokey-name-separator " & ")
  448. (bibtex-autokey-additional-names " et al.")
  449. (bibtex-autokey-year-length 4)
  450. (bibtex-autokey-name-year-separator " ")
  451. (bibtex-autokey-titlewords 3)
  452. (bibtex-autokey-titleword-separator " ")
  453. (bibtex-autokey-titleword-case-convert-function 'identity)
  454. (bibtex-autokey-titleword-length 'infty)
  455. (bibtex-autokey-year-title-separator ": "))
  456. (setq description (bibtex-generate-autokey)))
  457. ;; Now parse the entry, get the key and return it.
  458. (save-excursion
  459. (bibtex-beginning-of-entry)
  460. (cdr (assoc "=key=" (bibtex-parse-entry)))))
  461. (defun org-execute-file-search-in-bibtex (s)
  462. "Find the link search string S as a key for a database entry."
  463. (when (eq major-mode 'bibtex-mode)
  464. ;; Yes, we want to do the search in this file.
  465. ;; We construct a regexp that searches for "@entrytype{" followed by the key
  466. (goto-char (point-min))
  467. (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
  468. (regexp-quote s) "[ \t\n]*,") nil t)
  469. (goto-char (match-beginning 0)))
  470. (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
  471. ;; Use double prefix to indicate that any web link should be browsed
  472. (let ((b (current-buffer)) (p (point)))
  473. ;; Restore the window configuration because we just use the web link
  474. (set-window-configuration org-window-config-before-follow-link)
  475. (with-current-buffer b
  476. (goto-char p)
  477. (bibtex-url)))
  478. (recenter 0)) ; Move entry start to beginning of window
  479. ;; return t to indicate that the search is done.
  480. t))
  481. ;; Finally add the link search function to the right hook.
  482. (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
  483. ;;; Bibtex <-> Org-mode headline translation functions
  484. (defun org-bibtex (&optional filename)
  485. "Export each headline in the current file to a bibtex entry.
  486. Headlines are exported using `org-bibtex-export-headline'."
  487. (interactive
  488. (list (read-file-name
  489. "Bibtex file: " nil nil nil
  490. (file-name-nondirectory
  491. (concat (file-name-sans-extension (buffer-file-name)) ".bib")))))
  492. ((lambda (error-point)
  493. (when error-point
  494. (goto-char error-point)
  495. (message "Bibtex error at %S" (nth 4 (org-heading-components)))))
  496. (catch 'bib
  497. (let ((bibtex-entries (remove nil (org-map-entries
  498. (lambda ()
  499. (condition-case foo
  500. (org-bibtex-headline)
  501. (error (throw 'bib (point)))))))))
  502. (with-temp-file filename
  503. (insert (mapconcat #'identity bibtex-entries "\n")))
  504. (message "Successfully exported %d bibtex entries to %s"
  505. (length bibtex-entries) filename) nil))))
  506. (defun org-bibtex-check (&optional optional)
  507. "Check the current headline for required fields.
  508. With prefix argument OPTIONAL also prompt for optional fields."
  509. (interactive "P")
  510. (save-restriction
  511. (org-narrow-to-subtree)
  512. (let ((type ((lambda (name) (when name (intern (concat ":" name))))
  513. (org-bibtex-get org-bibtex-type-property-name))))
  514. (when type (org-bibtex-fleshout type optional)))))
  515. (defun org-bibtex-check-all (&optional optional)
  516. "Check all headlines in the current file.
  517. With prefix argument OPTIONAL also prompt for optional fields."
  518. (interactive) (org-map-entries (lambda () (org-bibtex-check optional))))
  519. (defun org-bibtex-create (&optional arg nonew)
  520. "Create a new entry at the given level.
  521. With a prefix arg, query for optional fields as well.
  522. If nonew is t, add data to the headline of the entry at point."
  523. (interactive "P")
  524. (let* ((type (org-icompleting-read
  525. "Type: " (mapcar (lambda (type)
  526. (substring (symbol-name (car type)) 1))
  527. org-bibtex-types)
  528. nil nil (when nonew
  529. (org-bibtex-get org-bibtex-type-property-name))))
  530. (type (if (keywordp type) type (intern (concat ":" type))))
  531. (org-bibtex-treat-headline-as-title (if nonew nil t)))
  532. (unless (assoc type org-bibtex-types)
  533. (error "type:%s is not known" type))
  534. (if nonew
  535. (org-back-to-heading)
  536. (org-insert-heading)
  537. (let ((title (org-bibtex-ask :title)))
  538. (insert title)
  539. (org-bibtex-put "TITLE" title)))
  540. (org-bibtex-put org-bibtex-type-property-name
  541. (substring (symbol-name type) 1))
  542. (org-bibtex-fleshout type arg)
  543. (mapc (lambda (tag) (org-toggle-tag tag 'on)) org-bibtex-tags)))
  544. (defun org-bibtex-create-in-current-entry (&optional arg)
  545. "Add bibliographical data to the current entry.
  546. With a prefix arg, query for optional fields."
  547. (interactive "P")
  548. (org-bibtex-create arg t))
  549. (defun org-bibtex-read ()
  550. "Read a bibtex entry and save to `*org-bibtex-entries*'.
  551. This uses `bibtex-parse-entry'."
  552. (interactive)
  553. (flet ((keyword (str) (intern (concat ":" (downcase str))))
  554. (clean-space (str) (replace-regexp-in-string
  555. "[[:space:]\n\r]+" " " str))
  556. (strip-delim (str) ; strip enclosing "..." and {...}
  557. (dolist (pair '((34 . 34) (123 . 125) (123 . 125)))
  558. (when (and (= (aref str 0) (car pair))
  559. (= (aref str (1- (length str))) (cdr pair)))
  560. (setf str (substring str 1 (1- (length str)))))) str))
  561. (push (mapcar
  562. (lambda (pair)
  563. (cons (let ((field (keyword (car pair))))
  564. (case field
  565. (:=type= :type)
  566. (:=key= :key)
  567. (otherwise field)))
  568. (clean-space (strip-delim (cdr pair)))))
  569. (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
  570. *org-bibtex-entries*)))
  571. (defun org-bibtex-write ()
  572. "Insert a heading built from the first element of `*org-bibtex-entries*'."
  573. (interactive)
  574. (when (= (length *org-bibtex-entries*) 0)
  575. (error "No entries in `*org-bibtex-entries*'."))
  576. (let ((entry (pop *org-bibtex-entries*))
  577. (org-special-properties nil)) ; avoids errors with `org-entry-put'
  578. (flet ((val (field) (cdr (assoc field entry)))
  579. (togtag (tag) (org-toggle-tag tag 'on)))
  580. (org-insert-heading)
  581. (insert (val :title))
  582. (org-bibtex-put "TITLE" (val :title))
  583. (org-bibtex-put org-bibtex-type-property-name (downcase (val :type)))
  584. (dolist (pair entry)
  585. (case (car pair)
  586. (:title nil)
  587. (:type nil)
  588. (:key (org-bibtex-put org-bibtex-key-property (cdr pair)))
  589. (:keywords (if org-bibtex-tags-are-keywords
  590. (mapc
  591. (lambda (kw)
  592. (togtag
  593. (replace-regexp-in-string
  594. "[^[:alnum:]_@#%]" ""
  595. (replace-regexp-in-string "[ \t]+" "_" kw))))
  596. (split-string (cdr pair) ", *"))
  597. (org-bibtex-put (car pair) (cdr pair))))
  598. (otherwise (org-bibtex-put (car pair) (cdr pair)))))
  599. (mapc #'togtag org-bibtex-tags))))
  600. (defun org-bibtex-yank ()
  601. "If kill ring holds a bibtex entry yank it as an Org-mode headline."
  602. (interactive)
  603. (let (entry)
  604. (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
  605. (if entry
  606. (org-bibtex-write)
  607. (error "yanked text does not appear to contain a bibtex entry"))))
  608. (defun org-bibtex-export-to-kill-ring ()
  609. "Export current headline to kill ring as bibtex entry."
  610. (interactive)
  611. (kill-new (org-bibtex-headline)))
  612. (defun org-bibtex-search (string)
  613. "Search for bibliographical entries in agenda files.
  614. This function relies `org-search-view' to locate results."
  615. (interactive "sSearch string: ")
  616. (let ((org-agenda-overriding-header "Bib search results:")
  617. (org-agenda-search-view-always-boolean t))
  618. (org-search-view nil
  619. (format "%s +{:%s%s:}"
  620. string org-bibtex-prefix
  621. org-bibtex-type-property-name))))
  622. (provide 'org-bibtex)
  623. ;;; org-bibtex.el ends here