org-bibtex.el 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. ;;; org-bibtex.el --- Org links to BibTeX entries
  2. ;;
  3. ;; Copyright (C) 2007, 2008, 2009, 2010, 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. ;; Version: 7.7
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; This file implements links to database entries in BibTeX files.
  27. ;; Instead of defining a special link prefix, it uses the normal file
  28. ;; links combined with a custom search mechanism to find entries
  29. ;; by reference key. And it constructs a nice description tag for
  30. ;; the link that contains the author name, the year and a short title.
  31. ;;
  32. ;; It also stores detailed information about the entry so that
  33. ;; remember templates can access and enter this information easily.
  34. ;;
  35. ;; The available properties for each entry are listed here:
  36. ;;
  37. ;; :author :publisher :volume :pages
  38. ;; :editor :url :number :journal
  39. ;; :title :year :series :address
  40. ;; :booktitle :month :annote :abstract
  41. ;; :key :btype
  42. ;;
  43. ;; Here is an example of a remember template that use some of this
  44. ;; information (:author :year :title :journal :pages):
  45. ;;
  46. ;; (setq org-remember-templates
  47. ;; '((?b "* READ %?\n\n%a\n\n%:author (%:year): %:title\n \
  48. ;; In %:journal, %:pages.")))
  49. ;;
  50. ;; Let's say you want to remember this BibTeX entry:
  51. ;;
  52. ;; @Article{dolev83,
  53. ;; author = {Danny Dolev and Andrew C. Yao},
  54. ;; title = {On the security of public-key protocols},
  55. ;; journal = {IEEE Transaction on Information Theory},
  56. ;; year = 1983,
  57. ;; volume = 2,
  58. ;; number = 29,
  59. ;; pages = {198--208},
  60. ;; month = {Mars}
  61. ;; }
  62. ;;
  63. ;; M-x `org-remember' on this entry will produce this buffer:
  64. ;;
  65. ;; =====================================================================
  66. ;; * READ <== [point here]
  67. ;;
  68. ;; [[file:file.bib::dolev83][Dolev & Yao 1983: security of public key protocols]]
  69. ;;
  70. ;; Danny Dolev and Andrew C. Yao (1983): On the security of public-key protocols
  71. ;; In IEEE Transaction on Information Theory, 198--208.
  72. ;; =====================================================================
  73. ;;
  74. ;; Additionally, the following functions are now available for storing
  75. ;; bibtex entries within Org-mode documents.
  76. ;;
  77. ;; - Run `org-bibtex' to export the current file to a .bib.
  78. ;;
  79. ;; - Run `org-bibtex-check' or `org-bibtex-check-all' to check and
  80. ;; fill in missing field of either the current, or all headlines
  81. ;;
  82. ;; - Run `org-bibtex-create' to add a bibtex entry
  83. ;;
  84. ;; - Use `org-bibtex-read' to read a bibtex entry after `point' or in
  85. ;; the active region, then call `org-bibtex-write' in a .org file to
  86. ;; insert a heading for the read bibtex entry
  87. ;;
  88. ;; - All Bibtex information is taken from the document compiled by
  89. ;; Andrew Roberts from the Bibtex manual, available at
  90. ;; http://www.andy-roberts.net/misc/latex/sessions/bibtex/bibentries.pdf
  91. ;;
  92. ;;; History:
  93. ;;
  94. ;; The link creation part has been part of Org-mode for a long time.
  95. ;;
  96. ;; Creating better remember template information was inspired by a request
  97. ;; of Austin Frank: http://article.gmane.org/gmane.emacs.orgmode/4112
  98. ;; and then implemented by Bastien Guerry.
  99. ;;
  100. ;; Eric Schulte eventually added the functions for translating between
  101. ;; Org-mode headlines and Bibtex entries, and for fleshing out the Bibtex
  102. ;; fields of existing Org-mode headlines.
  103. ;;
  104. ;; Org-mode loads this module by default - if this is not what you want,
  105. ;; configure the variable `org-modules'.
  106. ;;; Code:
  107. (require 'org)
  108. (require 'bibtex)
  109. (eval-when-compile
  110. (require 'cl))
  111. (defvar 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 truthy value to use `bibtex-generate-autokey' to generate keys."
  208. :group 'org-bibtex
  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. :type 'string)
  215. (defcustom org-bibtex-treat-headline-as-title t
  216. "Treat headline text as title if title property is absent.
  217. If an entry is missing a title property, use the headline text as
  218. the property. If this value is t, `org-bibtex-check' will ignore
  219. a missing title field."
  220. :group 'org-bibtex
  221. :type 'boolean)
  222. (defcustom org-bibtex-export-arbitrary-fields nil
  223. "When converting to bibtex allow fields not defined in `org-bibtex-fields'.
  224. This only has effect if `org-bibtex-prefix' is defined, so as to
  225. ensure that other org-properties, such as CATEGORY or LOGGING are
  226. not placed in the exported bibtex entry."
  227. :group 'org-bibtex
  228. :type 'boolean)
  229. (defcustom org-bibtex-key-property "CUSTOM_ID"
  230. "Property that holds the bibtex key.
  231. By default, this is CUSTOM_ID, which enables easy linking to
  232. bibtex headlines from within an org file. This can be set to ID
  233. to enable global links, but only with great caution, as global
  234. IDs must be unique."
  235. :group 'org-bibtex
  236. :type 'string)
  237. (defcustom org-bibtex-tags nil
  238. "List of tag(s) that should be added to new bib entries."
  239. :group 'org-bibtex
  240. :type '(repeat :tag "Tag" (string)))
  241. (defcustom org-bibtex-tags-are-keywords nil
  242. "Convert the value of the keywords field to tags and vice versa.
  243. If set to t, comma-separated entries in a bibtex entry's keywords
  244. field will be converted to org tags. Note: spaces will be escaped
  245. with underscores, and characters that are not permitted in org
  246. tags will be removed.
  247. If t, local tags in an org entry will be exported as a
  248. comma-separated string of keywords when exported to bibtex. Tags
  249. defined in `org-bibtex-tags' or `org-bibtex-no-export-tags' will
  250. not be exported."
  251. :group 'org-bibtex
  252. :type 'boolean)
  253. (defcustom org-bibtex-no-export-tags nil
  254. "List of tag(s) that should not be converted to keywords.
  255. This variable is relevant only if `org-bibtex-export-tags-as-keywords` is t."
  256. :group 'org-bibtex
  257. :type '(repeat :tag "Tag" (string)))
  258. ;;; Utility functions
  259. (defun org-bibtex-get (property)
  260. ((lambda (it) (when it (org-babel-trim it)))
  261. (let ((org-special-properties
  262. (delete "FILE" (copy-sequence org-special-properties))))
  263. (or
  264. (org-entry-get (point) (upcase property))
  265. (org-entry-get (point) (concat org-bibtex-prefix (upcase property)))))))
  266. (defun org-bibtex-put (property value)
  267. (let ((prop (upcase (if (keywordp property)
  268. (substring (symbol-name property) 1)
  269. property))))
  270. (org-set-property
  271. (concat (unless (string= org-bibtex-key-property prop) org-bibtex-prefix)
  272. prop)
  273. value)))
  274. (defun org-bibtex-headline ()
  275. "Return a bibtex entry of the given headline as a string."
  276. (flet ((val (key lst) (cdr (assoc key lst)))
  277. (to (string) (intern (concat ":" string)))
  278. (from (key) (substring (symbol-name key) 1))
  279. (flatten (&rest lsts)
  280. (apply #'append (mapcar
  281. (lambda (e)
  282. (if (listp e) (apply #'flatten e) (list e)))
  283. lsts))))
  284. (let ((notes (buffer-string))
  285. (id (org-bibtex-get org-bibtex-key-property))
  286. (type (org-bibtex-get "type"))
  287. (tags (when org-bibtex-tags-are-keywords
  288. (delq nil
  289. (mapcar
  290. (lambda (tag)
  291. (unless (member tag
  292. (append org-bibtex-tags
  293. org-bibtex-no-export-tags))
  294. tag))
  295. (org-get-local-tags-at))))))
  296. (when type
  297. (let ((entry (format
  298. "@%s{%s,\n%s\n}\n" type id
  299. (mapconcat
  300. (lambda (pair) (format " %s={%s}" (car pair) (cdr pair)))
  301. (remove nil
  302. (if (and org-bibtex-export-arbitrary-fields
  303. org-bibtex-prefix)
  304. (mapcar
  305. (lambda (kv)
  306. (let ((key (car kv)) (val (cdr kv)))
  307. (when (and (string-match org-bibtex-prefix key)
  308. (not (string=
  309. (downcase (concat org-bibtex-prefix "TYPE")) (downcase key))))
  310. (cons (downcase (replace-regexp-in-string
  311. org-bibtex-prefix "" key))
  312. val))))
  313. (org-entry-properties nil 'standard))
  314. (mapcar
  315. (lambda (field)
  316. (let ((value (or (org-bibtex-get (from field))
  317. (and (equal :title field)
  318. (nth 4 (org-heading-components))))))
  319. (when value (cons (from field) value))))
  320. (flatten
  321. (val :required (val (to type) org-bibtex-types))
  322. (val :optional (val (to type) org-bibtex-types))))))
  323. ",\n"))))
  324. (with-temp-buffer
  325. (insert entry)
  326. (when tags
  327. (bibtex-beginning-of-entry)
  328. (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
  329. (progn (goto-char (match-end 1)) (insert ", "))
  330. (bibtex-make-field "keywords" t t))
  331. (insert (mapconcat #'identity tags ", ")))
  332. (bibtex-reformat) (buffer-string)))))))
  333. (defun org-bibtex-ask (field)
  334. (unless (assoc field org-bibtex-fields)
  335. (error "field:%s is not known" field))
  336. (save-window-excursion
  337. (let* ((name (substring (symbol-name field) 1))
  338. (buf-name (format "*Bibtex Help %s*" name)))
  339. (with-output-to-temp-buffer buf-name
  340. (princ (cdr (assoc field org-bibtex-fields))))
  341. (with-current-buffer buf-name (longlines-mode t))
  342. (org-fit-window-to-buffer (get-buffer-window buf-name))
  343. ((lambda (result) (when (> (length result) 0) result))
  344. (read-from-minibuffer (format "%s: " name))))))
  345. (defun org-bibtex-autokey ()
  346. "Generate an autokey for the current headline"
  347. (org-bibtex-put org-bibtex-key-property
  348. (if org-bibtex-autogen-keys
  349. (let* ((entry (org-bibtex-headline))
  350. (key
  351. (with-temp-buffer
  352. (insert entry)
  353. (bibtex-generate-autokey))))
  354. ;; test for duplicate IDs if using global ID
  355. (when (and
  356. (equal org-bibtex-key-property "ID")
  357. (featurep 'org-id)
  358. (hash-table-p org-id-locations)
  359. (gethash key org-id-locations))
  360. (warn "Another entry has the same ID"))
  361. key)
  362. (read-from-minibuffer "id: "))))
  363. (defun org-bibtex-fleshout (type &optional optional)
  364. "Fleshout the current heading, ensuring that all required fields are present.
  365. With optional argument OPTIONAL, also prompt for optional fields."
  366. (flet ((val (key lst) (cdr (assoc key lst)))
  367. (keyword (name) (intern (concat ":" (downcase name))))
  368. (name (keyword) (substring (symbol-name keyword) 1)))
  369. (dolist (field (append
  370. (if org-bibtex-treat-headline-as-title
  371. (remove :title (val :required (val type org-bibtex-types)))
  372. (val :required (val type org-bibtex-types)))
  373. (when optional (val :optional (val type org-bibtex-types)))))
  374. (when (consp field) ; or'd pair of fields e.g., (:editor :author)
  375. (let ((present (first (remove nil
  376. (mapcar
  377. (lambda (f) (when (org-bibtex-get (name f)) f))
  378. field)))))
  379. (setf field (or present (keyword (org-icompleting-read
  380. "Field: " (mapcar #'name field)))))))
  381. (let ((name (name field)))
  382. (unless (org-bibtex-get name)
  383. (let ((prop (org-bibtex-ask field)))
  384. (when prop (org-bibtex-put name prop)))))))
  385. (when (and type (assoc type org-bibtex-types)
  386. (not (org-bibtex-get org-bibtex-key-property)))
  387. (org-bibtex-autokey)))
  388. ;;; Bibtex link functions
  389. (org-add-link-type "bibtex" 'org-bibtex-open)
  390. (add-hook 'org-store-link-functions 'org-bibtex-store-link)
  391. (defun org-bibtex-open (path)
  392. "Visit the bibliography entry on PATH."
  393. (let* ((search (when (string-match "::\\(.+\\)\\'" path)
  394. (match-string 1 path)))
  395. (path (substring path 0 (match-beginning 0))))
  396. (org-open-file path t nil search)))
  397. (defun org-bibtex-store-link ()
  398. "Store a link to a BibTeX entry."
  399. (when (eq major-mode 'bibtex-mode)
  400. (let* ((search (org-create-file-search-in-bibtex))
  401. (link (concat "file:" (abbreviate-file-name buffer-file-name)
  402. "::" search))
  403. (entry (mapcar ; repair strings enclosed in "..." or {...}
  404. (lambda(c)
  405. (if (string-match
  406. "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c))
  407. (cons (car c) (match-string 1 (cdr c))) c))
  408. (save-excursion
  409. (bibtex-beginning-of-entry)
  410. (bibtex-parse-entry)))))
  411. (org-store-link-props
  412. :key (cdr (assoc "=key=" entry))
  413. :author (or (cdr (assoc "author" entry)) "[no author]")
  414. :editor (or (cdr (assoc "editor" entry)) "[no editor]")
  415. :title (or (cdr (assoc "title" entry)) "[no title]")
  416. :booktitle (or (cdr (assoc "booktitle" entry)) "[no booktitle]")
  417. :journal (or (cdr (assoc "journal" entry)) "[no journal]")
  418. :publisher (or (cdr (assoc "publisher" entry)) "[no publisher]")
  419. :pages (or (cdr (assoc "pages" entry)) "[no pages]")
  420. :url (or (cdr (assoc "url" entry)) "[no url]")
  421. :year (or (cdr (assoc "year" entry)) "[no year]")
  422. :month (or (cdr (assoc "month" entry)) "[no month]")
  423. :address (or (cdr (assoc "address" entry)) "[no address]")
  424. :volume (or (cdr (assoc "volume" entry)) "[no volume]")
  425. :number (or (cdr (assoc "number" entry)) "[no number]")
  426. :annote (or (cdr (assoc "annote" entry)) "[no annotation]")
  427. :series (or (cdr (assoc "series" entry)) "[no series]")
  428. :abstract (or (cdr (assoc "abstract" entry)) "[no abstract]")
  429. :btype (or (cdr (assoc "=type=" entry)) "[no type]")
  430. :type "bibtex"
  431. :link link
  432. :description description))))
  433. (defun org-create-file-search-in-bibtex ()
  434. "Create the search string and description for a BibTeX database entry."
  435. ;; Make a good description for this entry, using names, year and the title
  436. ;; Put it into the `description' variable which is dynamically scoped.
  437. (let ((bibtex-autokey-names 1)
  438. (bibtex-autokey-names-stretch 1)
  439. (bibtex-autokey-name-case-convert-function 'identity)
  440. (bibtex-autokey-name-separator " & ")
  441. (bibtex-autokey-additional-names " et al.")
  442. (bibtex-autokey-year-length 4)
  443. (bibtex-autokey-name-year-separator " ")
  444. (bibtex-autokey-titlewords 3)
  445. (bibtex-autokey-titleword-separator " ")
  446. (bibtex-autokey-titleword-case-convert-function 'identity)
  447. (bibtex-autokey-titleword-length 'infty)
  448. (bibtex-autokey-year-title-separator ": "))
  449. (setq description (bibtex-generate-autokey)))
  450. ;; Now parse the entry, get the key and return it.
  451. (save-excursion
  452. (bibtex-beginning-of-entry)
  453. (cdr (assoc "=key=" (bibtex-parse-entry)))))
  454. (defun org-execute-file-search-in-bibtex (s)
  455. "Find the link search string S as a key for a database entry."
  456. (when (eq major-mode 'bibtex-mode)
  457. ;; Yes, we want to do the search in this file.
  458. ;; We construct a regexp that searches for "@entrytype{" followed by the key
  459. (goto-char (point-min))
  460. (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
  461. (regexp-quote s) "[ \t\n]*,") nil t)
  462. (goto-char (match-beginning 0)))
  463. (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
  464. ;; Use double prefix to indicate that any web link should be browsed
  465. (let ((b (current-buffer)) (p (point)))
  466. ;; Restore the window configuration because we just use the web link
  467. (set-window-configuration org-window-config-before-follow-link)
  468. (with-current-buffer b
  469. (goto-char p)
  470. (bibtex-url)))
  471. (recenter 0)) ; Move entry start to beginning of window
  472. ;; return t to indicate that the search is done.
  473. t))
  474. ;; Finally add the link search function to the right hook.
  475. (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
  476. ;;; Bibtex <-> Org-mode headline translation functions
  477. (defun org-bibtex (&optional filename)
  478. "Export each headline in the current file to a bibtex entry.
  479. Headlines are exported using `org-bibtex-export-headline'."
  480. (interactive
  481. (list (read-file-name
  482. "Bibtex file: " nil nil nil
  483. (file-name-nondirectory
  484. (concat (file-name-sans-extension (buffer-file-name)) ".bib")))))
  485. (let ((bibtex-entries (remove nil (org-map-entries #'org-bibtex-headline))))
  486. (with-temp-file filename
  487. (insert (mapconcat #'identity bibtex-entries "\n")))))
  488. (defun org-bibtex-check (&optional optional)
  489. "Check the current headline for required fields.
  490. With prefix argument OPTIONAL also prompt for optional fields."
  491. (interactive "P")
  492. (save-restriction
  493. (org-narrow-to-subtree)
  494. (let ((type ((lambda (name) (when name (intern (concat ":" name))))
  495. (org-bibtex-get "TYPE"))))
  496. (when type (org-bibtex-fleshout type optional)))))
  497. (defun org-bibtex-check-all (&optional optional)
  498. "Check all headlines in the current file.
  499. With prefix argument OPTIONAL also prompt for optional fields."
  500. (interactive) (org-map-entries (lambda () (org-bibtex-check optional))))
  501. (defun org-bibtex-create (&optional arg nonew)
  502. "Create a new entry at the given level.
  503. With a prefix arg, query for optional fields as well.
  504. If nonew is t, add data to the headline of the entry at point."
  505. (interactive "P")
  506. (let* ((type (org-icompleting-read
  507. "Type: " (mapcar (lambda (type)
  508. (substring (symbol-name (car type)) 1))
  509. org-bibtex-types)
  510. nil nil (when nonew (org-bibtex-get "TYPE"))))
  511. (type (if (keywordp type) type (intern (concat ":" type))))
  512. (org-bibtex-treat-headline-as-title (if nonew nil t)))
  513. (unless (assoc type org-bibtex-types)
  514. (error "type:%s is not known" type))
  515. (if nonew
  516. (org-back-to-heading)
  517. (org-insert-heading)
  518. (let ((title (org-bibtex-ask :title)))
  519. (insert title)
  520. (org-bibtex-put "TITLE" title)))
  521. (org-bibtex-put "TYPE" (substring (symbol-name type) 1))
  522. (org-bibtex-fleshout type arg)
  523. (mapc (lambda (tag) (org-toggle-tag tag 'on)) org-bibtex-tags)))
  524. (defun org-bibtex-create-in-current-entry (&optional arg)
  525. "Add bibliographical data to the current entry.
  526. With a prefix arg, query for optional fields."
  527. (interactive "P")
  528. (org-bibtex-create arg t))
  529. (defun org-bibtex-read ()
  530. "Read a bibtex entry and save to `*org-bibtex-entries*'.
  531. This uses `bibtex-parse-entry'."
  532. (interactive)
  533. (flet ((keyword (str) (intern (concat ":" (downcase str))))
  534. (clean-space (str) (replace-regexp-in-string
  535. "[[:space:]\n\r]+" " " str))
  536. (strip-delim (str) ; strip enclosing "..." and {...}
  537. (dolist (pair '((34 . 34) (123 . 125) (123 . 125)))
  538. (when (and (= (aref str 0) (car pair))
  539. (= (aref str (1- (length str))) (cdr pair)))
  540. (setf str (substring str 1 (1- (length str)))))) str))
  541. (push (mapcar
  542. (lambda (pair)
  543. (cons (let ((field (keyword (car pair))))
  544. (case field
  545. (:=type= :type)
  546. (:=key= :key)
  547. (otherwise field)))
  548. (clean-space (strip-delim (cdr pair)))))
  549. (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
  550. *org-bibtex-entries*)))
  551. (defun org-bibtex-write ()
  552. "Insert a heading built from the first element of `*org-bibtex-entries*'."
  553. (interactive)
  554. (when (= (length *org-bibtex-entries*) 0)
  555. (error "No entries in `*org-bibtex-entries*'."))
  556. (let ((entry (pop *org-bibtex-entries*))
  557. (org-special-properties nil)) ; avoids errors with `org-entry-put'
  558. (flet ((val (field) (cdr (assoc field entry)))
  559. (togtag (tag) (org-toggle-tag tag 'on)))
  560. (org-insert-heading)
  561. (insert (val :title))
  562. (org-bibtex-put "TITLE" (val :title))
  563. (org-bibtex-put "TYPE" (downcase (val :type)))
  564. (dolist (pair entry)
  565. (case (car pair)
  566. (:title nil)
  567. (:type nil)
  568. (:key (org-bibtex-put org-bibtex-key-property (cdr pair)))
  569. (:keywords (if org-bibtex-tags-are-keywords
  570. (mapc
  571. (lambda (kw)
  572. (togtag
  573. (replace-regexp-in-string
  574. "[^[:alnum:]_@#%]" ""
  575. (replace-regexp-in-string "[ \t]+" "_" kw))))
  576. (split-string (cdr pair) ", *"))
  577. (org-bibtex-put (car pair) (cdr pair))))
  578. (otherwise (org-bibtex-put (car pair) (cdr pair)))))
  579. (mapc #'togtag org-bibtex-tags))))
  580. (defun org-bibtex-yank ()
  581. "If kill ring holds a bibtex entry yank it as an Org-mode headline."
  582. (interactive)
  583. (let (entry)
  584. (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
  585. (if entry
  586. (org-bibtex-write)
  587. (error "yanked text does not appear to contain a bibtex entry"))))
  588. (defun org-bibtex-export-to-kill-ring ()
  589. "Export current headline to kill ring as bibtex entry."
  590. (interactive)
  591. (kill-new (org-bibtex-headline)))
  592. (defun org-bibtex-search (string)
  593. "Search for bibliographical entries in agenda files.
  594. This function relies `org-search-view' to locate results."
  595. (interactive "sSearch string: ")
  596. (let ((org-agenda-overriding-header "Bib search results:")
  597. (org-agenda-search-view-always-boolean t))
  598. (org-search-view nil
  599. (format "%s +{:%sTYPE:}"
  600. string org-bibtex-prefix))))
  601. (provide 'org-bibtex)
  602. ;; arch-tag: 83987d5a-01b8-41c7-85bc-77700f1285f5
  603. ;;; org-bibtex.el ends here