org-bibtex.el 26 KB

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