1 ;;; org-bibtex.el --- Org links to BibTeX entries
3 ;; Copyright (C) 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
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
11 ;; This file is part of GNU Emacs.
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.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; This file implements links to database entries in BibTeX files.
29 ;; Instead of defining a special link prefix, it uses the normal file
30 ;; links combined with a custom search mechanism to find entries
31 ;; by reference key. And it constructs a nice description tag for
32 ;; the link that contains the author name, the year and a short title.
34 ;; It also stores detailed information about the entry so that
35 ;; remember templates can access and enter this information easily.
37 ;; The available properties for each entry are listed here:
39 ;; :author :publisher :volume :pages
40 ;; :editor :url :number :journal
41 ;; :title :year :series :address
42 ;; :booktitle :month :annote :abstract
45 ;; Here is an example of a remember template that use some of this
46 ;; information (:author :year :title :journal :pages):
48 ;; (setq org-remember-templates
49 ;; '((?b "* READ %?\n\n%a\n\n%:author (%:year): %:title\n \
50 ;; In %:journal, %:pages.")))
52 ;; Let's say you want to remember this BibTeX entry:
55 ;; author = {Danny Dolev and Andrew C. Yao},
56 ;; title = {On the security of public-key protocols},
57 ;; journal = {IEEE Transaction on Information Theory},
61 ;; pages = {198--208},
65 ;; M-x `org-remember' on this entry will produce this buffer:
67 ;; =====================================================================
68 ;; * READ <== [point here]
70 ;; [[file:file.bib::dolev83][Dolev & Yao 1983: security of public key protocols]]
72 ;; Danny Dolev and Andrew C. Yao (1983): On the security of public-key protocols
73 ;; In IEEE Transaction on Information Theory, 198--208.
74 ;; =====================================================================
76 ;; Additionally, the following functions are now available for storing
77 ;; bibtex entries within Org-mode documents.
79 ;; - Run `org-bibtex' to export the current file to a .bib.
81 ;; - Run `org-bibtex-check' or `org-bibtex-check-all' to check and
82 ;; fill in missing field of either the current, or all headlines
84 ;; - Run `org-bibtex-create' to add a bibtex entry
86 ;; - Use `org-bibtex-read' to read a bibtex entry after `point' or in
87 ;; the active region, then call `org-bibtex-write' in a .org file to
88 ;; insert a heading for the read bibtex entry
90 ;; - All Bibtex information is taken from the document compiled by
91 ;; Andrew Roberts from the Bibtex manual, available at
92 ;; http://www.andy-roberts.net/misc/latex/sessions/bibtex/bibentries.pdf
96 ;; The link creation part has been part of Org-mode for a long time.
98 ;; Creating better remember template information was inspired by a request
99 ;; of Austin Frank: http://article.gmane.org/gmane.emacs.orgmode/4112
100 ;; and then implemented by Bastien Guerry.
102 ;; Eric Schulte eventually added the functions for translating between
103 ;; Org-mode headlines and Bibtex entries, and for fleshing out the Bibtex
104 ;; fields of existing Org-mode headlines.
106 ;; Org-mode loads this module by default - if this is not what you want,
107 ;; configure the variable `org-modules'.
114 (defvar description nil
) ; dynamically scoped from org.el
116 (declare-function bibtex-beginning-of-entry
"bibtex" ())
117 (declare-function bibtex-generate-autokey
"bibtex" ())
118 (declare-function bibtex-parse-entry
"bibtex" (&optional content
))
119 (declare-function bibtex-url
"bibtex" (&optional pos no-browse
))
120 (declare-function longlines-mode
"longlines" (&optional arg
))
124 (defvar org-bibtex-types
126 (:description .
"An article from a journal or magazine")
127 (:required
:author
:title
:journal
:year
)
128 (:optional
:volume
:number
:pages
:month
:note
))
130 (:description .
"A book with an explicit publisher")
131 (:required
(:editor
:author
) :title
:publisher
:year
)
132 (:optional
(:volume
:number
) :series
:address
:edition
:month
:note
))
134 (:description .
"A work that is printed and bound, but without a named publisher or sponsoring institution.")
136 (:optional
:author
:howpublished
:address
:month
:year
:note
))
139 (:required
:author
:title
:booktitle
:year
)
140 (:optional
:editor
:pages
:organization
:publisher
:address
:month
:note
))
142 (:description .
"A part of a book, which may be a chapter (or section or whatever) and/or a range of pages.")
143 (:required
(:author
:editor
) :title
(:chapter
:pages
) :publisher
:year
)
144 (:optional
(:volume
:number
) :series
:type
:address
:edition
:month
:note
))
146 (:description .
"A part of a book having its own title.")
147 (:required
:author
:title
:booktitle
:publisher
:year
)
148 (:optional
:editor
(:volume
:number
) :series
:type
:chapter
:pages
:address
:edition
:month
:note
))
150 (:description .
"An article in a conference proceedings")
151 (:required
:author
:title
:booktitle
:year
)
152 (:optional
:editor
(:volume
:number
) :series
:pages
:address
:month
:organization
:publisher
:note
))
154 (:description .
"Technical documentation.")
156 (:optional
:author
:organization
:address
:edition
:month
:year
:note
))
158 (:description .
"A Master’s thesis.")
159 (:required
:author
:title
:school
:year
)
160 (:optional
:type
:address
:month
:note
))
162 (:description .
"Use this type when nothing else fits.")
164 (:optional
:author
:title
:howpublished
:month
:year
:note
))
166 (:description .
"A PhD thesis.")
167 (:required
:author
:title
:school
:year
)
168 (:optional
:type
:address
:month
:note
))
170 (:description .
"The proceedings of a conference.")
171 (:required
:title
:year
)
172 (:optional
:editor
(:volume
:number
) :series
:address
:month
:organization
:publisher
:note
))
174 (:description .
"A report published by a school or other institution.")
175 (:required
:author
:title
:institution
:year
)
176 (:optional
:type
:address
:month
:note
))
178 (:description .
"A document having an author and title, but not formally published.")
179 (:required
:author
:title
:note
)
180 (:optional
:month
:year
)))
181 "Bibtex entry types with required and optional parameters.")
183 (defvar org-bibtex-fields
184 '((: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.")
185 (:annote .
"An annotation. It is not used by the standard bibliography styles, but may be used by others that produce an annotated bibliography.")
186 (: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.")
187 (: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.")
188 (:chapter .
"A chapter (or section or whatever) number.")
189 (:crossref .
"The database key of the entry being cross referenced.")
190 (: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.")
191 (: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.")
192 (:howpublished .
"How something strange has been published. The first word should be capitalized.")
193 (:institution .
"The sponsoring institution of a technical report.")
194 (:journal .
"A journal name.")
195 (: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.")
196 (: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,")
197 (:note .
"Any additional information that can help the reader. The first word should be capitalized.")
198 (:number .
"Any additional information that can help the reader. The first word should be capitalized.")
199 (:organization .
"The organization that sponsors a conference or that publishes a manual.")
200 (: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 (--).")
201 (:publisher .
"The publisher’s name.")
202 (:school .
"The name of the school where a thesis was written.")
203 (: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.")
204 (:title .
"The work’s title, typed as explained in the LaTeX book.")
205 (:type .
"The type of a technical report for example, 'Research Note'.")
206 (:volume .
"The volume of a journal or multi-volume book.")
207 (: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)'"))
208 "Bibtex fields with descriptions.")
210 (defvar *org-bibtex-entries
* nil
211 "List to hold parsed bibtex entries.")
213 (defcustom org-bibtex-autogen-keys nil
214 "Set to a truthy value to use `bibtex-generate-autokey' to generate keys."
218 (defcustom org-bibtex-prefix nil
219 "Optional prefix for all bibtex property names.
220 For example setting to 'BIB_' would allow interoperability with fireforg."
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."
232 ;; TODO if ID, test to make sure ID is unique
233 (defcustom org-bibtex-key-property
"CUSTOM_ID"
234 "Property that holds the bibtex key.
235 By default, this is CUSTOM_ID, which enables easy linking to
236 bibtex headlines from within an org file. This can be set to ID
237 to enable global links, but only with great caution, as global
243 ;;; Utility functions
244 (defun org-bibtex-get (property)
245 (or (org-entry-get (point) (upcase property
))
246 (org-entry-get (point) (concat org-bibtex-prefix
(upcase property
)))))
248 (defun org-bibtex-put (property value
)
249 (let ((prop (upcase (if (keywordp property
)
250 (substring (symbol-name property
) 1)
253 (concat (unless (string= org-bibtex-key-property prop
) org-bibtex-prefix
)
257 (defun org-bibtex-headline ()
258 "Return a bibtex entry of the given headline as a string."
259 (flet ((val (key lst
) (cdr (assoc key lst
)))
260 (to (string) (intern (concat ":" string
)))
261 (from (key) (substring (symbol-name key
) 1))
262 (flatten (&rest lsts
)
263 (apply #'append
(mapcar
265 (if (listp e
) (apply #'flatten e
) (list e
)))
267 (let ((notes (buffer-string))
268 (id (org-bibtex-get org-bibtex-key-property
))
269 (type (org-bibtex-get "type")))
272 "@%s{%s,\n%s\n}\n" type id
274 (lambda (pair) (format " %s={%s}" (car pair
) (cdr pair
)))
276 (if (and org-bibtex-export-arbitrary-fields
280 (when (string-match org-bibtex-prefix
(car kv
))
281 (cons (downcase (replace-regexp-in-string
285 (org-entry-properties nil
'standard
))
288 (let ((value (or (org-bibtex-get (from field
))
289 (and (equal :title field
)
290 (org-get-heading)))))
291 (when value
(cons (from field
) value
))))
293 (val :required
(val (to type
) org-bibtex-types
))
294 (val :optional
(val (to type
) org-bibtex-types
))))))
298 (bibtex-reformat) (buffer-string)))))))
300 (defun org-bibtex-ask (field)
301 (unless (assoc field org-bibtex-fields
)
302 (error "field:%s is not known" field
))
303 (save-window-excursion
304 (let* ((name (substring (symbol-name field
) 1))
305 (buf-name (format "*Bibtex Help %s*" name
)))
306 (with-output-to-temp-buffer buf-name
307 (princ (cdr (assoc field org-bibtex-fields
))))
308 (with-current-buffer buf-name
(longlines-mode t
))
309 (org-fit-window-to-buffer (get-buffer-window buf-name
))
310 ((lambda (result) (when (> (length result
) 0) result
))
311 (read-from-minibuffer (format "%s: " name
))))))
313 (defun org-bibtex-autokey ()
314 "Generate an autokey for the current headline"
315 (org-bibtex-put org-bibtex-key-property
316 (if org-bibtex-autogen-keys
317 (let ((entry (org-bibtex-headline)))
320 (bibtex-generate-autokey)))
321 (read-from-minibuffer "id: "))))
323 (defun org-bibtex-fleshout (type &optional optional
)
324 "Fleshout the current heading, ensuring that all required fields are present.
325 With optional argument OPTIONAL, also prompt for optional fields."
326 (flet ((val (key lst
) (cdr (assoc key lst
)))
327 (keyword (name) (intern (concat ":" (downcase name
))))
328 (name (keyword) (upcase (substring (symbol-name keyword
) 1))))
329 (dolist (field (append
330 (remove :title
(val :required
(val type org-bibtex-types
)))
331 (when optional
(val :optional
(val type org-bibtex-types
)))))
332 (when (consp field
) ; or'd pair of fields e.g., (:editor :author)
333 (let ((present (first (remove nil
335 (lambda (f) (when (org-bibtex-get (name f
)) f
))
337 (setf field
(or present
(keyword (org-icompleting-read
338 "Field: " (mapcar #'name field
)))))))
339 (let ((name (name field
)))
340 (unless (org-bibtex-get name
)
341 (let ((prop (org-bibtex-ask field
)))
342 (when prop
(org-bibtex-put name prop
)))))))
343 (when (and type
(assoc type org-bibtex-types
)
344 (not (org-bibtex-get org-bibtex-key-property
)))
345 (org-bibtex-autokey)))
348 ;;; Bibtex link functions
349 (org-add-link-type "bibtex" 'org-bibtex-open
)
350 (add-hook 'org-store-link-functions
'org-bibtex-store-link
)
352 (defun org-bibtex-open (path)
353 "Visit the bibliography entry on PATH."
354 (let* ((search (when (string-match "::\\(.+\\)\\'" path
)
355 (match-string 1 path
)))
356 (path (substring path
0 (match-beginning 0))))
357 (org-open-file path t nil search
)))
359 (defun org-bibtex-store-link ()
360 "Store a link to a BibTeX entry."
361 (when (eq major-mode
'bibtex-mode
)
362 (let* ((search (org-create-file-search-in-bibtex))
363 (link (concat "file:" (abbreviate-file-name buffer-file-name
)
365 (entry (mapcar ; repair strings enclosed in "..." or {...}
368 "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c
))
369 (cons (car c
) (match-string 1 (cdr c
))) c
))
371 (bibtex-beginning-of-entry)
372 (bibtex-parse-entry)))))
373 (org-store-link-props
374 :key
(cdr (assoc "=key=" entry
))
375 :author
(or (cdr (assoc "author" entry
)) "[no author]")
376 :editor
(or (cdr (assoc "editor" entry
)) "[no editor]")
377 :title
(or (cdr (assoc "title" entry
)) "[no title]")
378 :booktitle
(or (cdr (assoc "booktitle" entry
)) "[no booktitle]")
379 :journal
(or (cdr (assoc "journal" entry
)) "[no journal]")
380 :publisher
(or (cdr (assoc "publisher" entry
)) "[no publisher]")
381 :pages
(or (cdr (assoc "pages" entry
)) "[no pages]")
382 :url
(or (cdr (assoc "url" entry
)) "[no url]")
383 :year
(or (cdr (assoc "year" entry
)) "[no year]")
384 :month
(or (cdr (assoc "month" entry
)) "[no month]")
385 :address
(or (cdr (assoc "address" entry
)) "[no address]")
386 :volume
(or (cdr (assoc "volume" entry
)) "[no volume]")
387 :number
(or (cdr (assoc "number" entry
)) "[no number]")
388 :annote
(or (cdr (assoc "annote" entry
)) "[no annotation]")
389 :series
(or (cdr (assoc "series" entry
)) "[no series]")
390 :abstract
(or (cdr (assoc "abstract" entry
)) "[no abstract]")
391 :btype
(or (cdr (assoc "=type=" entry
)) "[no type]")
394 :description description
))))
396 (defun org-create-file-search-in-bibtex ()
397 "Create the search string and description for a BibTeX database entry."
398 ;; Make a good description for this entry, using names, year and the title
399 ;; Put it into the `description' variable which is dynamically scoped.
400 (let ((bibtex-autokey-names 1)
401 (bibtex-autokey-names-stretch 1)
402 (bibtex-autokey-name-case-convert-function 'identity
)
403 (bibtex-autokey-name-separator " & ")
404 (bibtex-autokey-additional-names " et al.")
405 (bibtex-autokey-year-length 4)
406 (bibtex-autokey-name-year-separator " ")
407 (bibtex-autokey-titlewords 3)
408 (bibtex-autokey-titleword-separator " ")
409 (bibtex-autokey-titleword-case-convert-function 'identity
)
410 (bibtex-autokey-titleword-length 'infty
)
411 (bibtex-autokey-year-title-separator ": "))
412 (setq description
(bibtex-generate-autokey)))
413 ;; Now parse the entry, get the key and return it.
415 (bibtex-beginning-of-entry)
416 (cdr (assoc "=key=" (bibtex-parse-entry)))))
418 (defun org-execute-file-search-in-bibtex (s)
419 "Find the link search string S as a key for a database entry."
420 (when (eq major-mode
'bibtex-mode
)
421 ;; Yes, we want to do the search in this file.
422 ;; We construct a regexp that searches for "@entrytype{" followed by the key
423 (goto-char (point-min))
424 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
425 (regexp-quote s
) "[ \t\n]*,") nil t
)
426 (goto-char (match-beginning 0)))
427 (if (and (match-beginning 0) (equal current-prefix-arg
'(16)))
428 ;; Use double prefix to indicate that any web link should be browsed
429 (let ((b (current-buffer)) (p (point)))
430 ;; Restore the window configuration because we just use the web link
431 (set-window-configuration org-window-config-before-follow-link
)
432 (with-current-buffer b
435 (recenter 0)) ; Move entry start to beginning of window
436 ;; return t to indicate that the search is done.
439 ;; Finally add the link search function to the right hook.
440 (add-hook 'org-execute-file-search-functions
'org-execute-file-search-in-bibtex
)
443 ;;; Bibtex <-> Org-mode headline translation functions
445 "Export each headline in the current file to a bibtex entry.
446 Headlines are exported using `org-bibtex-export-headline'."
448 (let ((bibtex-entries (remove nil
(org-map-entries #'org-bibtex-headline
))))
449 (with-temp-file (concat (file-name-sans-extension (buffer-file-name)) ".bib")
450 (insert (mapconcat #'identity bibtex-entries
"\n")))))
452 (defun org-bibtex-check (&optional optional
)
453 "Check the current headline for required fields.
454 With prefix argument OPTIONAL also prompt for optional fields."
457 (org-narrow-to-subtree)
458 (let ((type ((lambda (name) (when name
(intern (concat ":" name
))))
459 (org-bibtex-get "TYPE"))))
460 (when type
(org-bibtex-fleshout type optional
)))))
462 (defun org-bibtex-check-all (&optional optional
)
463 "Check all headlines in the current file.
464 With prefix argument OPTIONAL also prompt for optional fields."
465 (interactive) (org-map-entries (lambda () (org-bibtex-check optional
))))
467 (defun org-bibtex-create (&optional arg
)
468 "Create a new entry at the given level."
470 (let* ((type (org-icompleting-read
471 "Type: " (mapcar (lambda (type) (symbol-name (car type
)))
473 (type (if (keywordp type
) type
(intern type
))))
474 (unless (assoc type org-bibtex-types
)
475 (error "type:%s is not known" type
))
477 (let ((title (org-bibtex-ask :title
)))
478 (insert title
) (org-bibtex-put "TITLE" title
))
479 (org-bibtex-put "TYPE" (substring (symbol-name type
) 1))
480 (org-bibtex-fleshout type arg
)))
482 (defun org-bibtex-read ()
483 "Read a bibtex entry and save to `*org-bibtex-entries*'.
484 This uses `bibtex-parse-entry'."
486 (flet ((keyword (str) (intern (concat ":" (downcase str
))))
487 (clean-space (str) (replace-regexp-in-string
488 "[[:space:]\n\r]+" " " str
))
489 (strip-delim (str) ; strip enclosing "..." and {...}
490 (dolist (pair '((34 .
34) (123 .
125) (123 .
125)))
491 (when (and (= (aref str
0) (car pair
))
492 (= (aref str
(1- (length str
))) (cdr pair
)))
493 (setf str
(substring str
1 (1- (length str
)))))) str
))
496 (cons (let ((field (keyword (car pair
))))
501 (clean-space (strip-delim (cdr pair
)))))
502 (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
503 *org-bibtex-entries
*)))
505 (defun org-bibtex-write ()
506 "Insert a heading built from the first element of `*org-bibtex-entries*'."
508 (when (= (length *org-bibtex-entries
*) 0)
509 (error "No entries in `*org-bibtex-entries*'."))
510 (let ((entry (pop *org-bibtex-entries
*))
511 (org-special-properties nil
)) ; avoids errors with `org-entry-put'
512 (flet ((val (field) (cdr (assoc field entry
))))
514 (insert (val :title
))
515 (org-bibtex-put "TITLE" (val :title
))
516 (org-bibtex-put "TYPE" (downcase (val :type
)))
521 (:key
(org-bibtex-put org-bibtex-key-property
(cdr pair
)))
522 (otherwise (org-bibtex-put (car pair
) (cdr pair
))))))))
524 (defun org-bibtex-yank ()
525 "If kill ring holds a bibtex entry yank it as an Org-mode headline."
528 (with-temp-buffer (yank 1) (setf entry
(org-bibtex-read)))
531 (error "yanked text does not appear to contain a bibtex entry"))))
533 (provide 'org-bibtex
)
535 ;; arch-tag: 83987d5a-01b8-41c7-85bc-77700f1285f5
537 ;;; org-bibtex.el ends here