org-bibtex.el 29 KB

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