org-bibtex.el 29 KB

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