Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org-bibtex.el
blob08410cd6a8c463fae91ec6f0007518bd18501373
1 ;;; org-bibtex.el --- Org links to BibTeX entries -*- lexical-binding: t; -*-
2 ;;
3 ;; Copyright (C) 2007-2016 Free Software Foundation, Inc.
4 ;;
5 ;; Authors: Bastien Guerry <bzg@gnu.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, capture
9 ;;
10 ;; This file is part of GNU Emacs.
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.
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.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; This file implements links to database entries in BibTeX files.
28 ;; Instead of defining a special link prefix, it uses the normal file
29 ;; links combined with a custom search mechanism to find entries
30 ;; by reference key. And it constructs a nice description tag for
31 ;; the link that contains the author name, the year and a short title.
33 ;; It also stores detailed information about the entry so that
34 ;; capture templates can access and enter this information easily.
36 ;; The available properties for each entry are listed here:
38 ;; :author :publisher :volume :pages
39 ;; :editor :url :number :journal
40 ;; :title :year :series :address
41 ;; :booktitle :month :annote :abstract
42 ;; :key :btype
44 ;; Here is an example of a capture template that use some of this
45 ;; information (:author :year :title :journal :pages):
47 ;; (setq org-capture-templates
48 ;; '((?b "* READ %?\n\n%a\n\n%:author (%:year): %:title\n \
49 ;; In %:journal, %:pages.")))
51 ;; Let's say you want to capture this BibTeX entry:
53 ;; @Article{dolev83,
54 ;; author = {Danny Dolev and Andrew C. Yao},
55 ;; title = {On the security of public-key protocols},
56 ;; journal = {IEEE Transaction on Information Theory},
57 ;; year = 1983,
58 ;; volume = 2,
59 ;; number = 29,
60 ;; pages = {198--208},
61 ;; month = {Mars}
62 ;; }
64 ;; M-x `org-capture' on this entry will produce this buffer:
66 ;; =====================================================================
67 ;; * READ <== [point here]
69 ;; [[file:file.bib::dolev83][Dolev & Yao 1983: security of public key protocols]]
71 ;; Danny Dolev and Andrew C. Yao (1983): On the security of public-key protocols
72 ;; In IEEE Transaction on Information Theory, 198--208.
73 ;; =====================================================================
75 ;; Additionally, the following functions are now available for storing
76 ;; bibtex entries within Org-mode documents.
78 ;; - Run `org-bibtex' to export the current file to a .bib.
80 ;; - Run `org-bibtex-check' or `org-bibtex-check-all' to check and
81 ;; fill in missing field of either the current, or all headlines
83 ;; - Run `org-bibtex-create' to add a bibtex entry
85 ;; - Use `org-bibtex-read' to read a bibtex entry after `point' or in
86 ;; the active region, then call `org-bibtex-write' in a .org file to
87 ;; insert a heading for the read bibtex entry
89 ;; - All Bibtex information is taken from the document compiled by
90 ;; Andrew Roberts from the Bibtex manual, available at
91 ;; http://www.andy-roberts.net/res/writing/latex/bibentries.pdf
93 ;;; History:
95 ;; The link creation part has been part of Org-mode for a long time.
97 ;; Creating better capture template information was inspired by a request
98 ;; of Austin Frank: http://article.gmane.org/gmane.emacs.orgmode/4112
99 ;; and then implemented by Bastien Guerry.
101 ;; Eric Schulte eventually added the functions for translating between
102 ;; Org-mode headlines and Bibtex entries, and for fleshing out the Bibtex
103 ;; fields of existing Org-mode headlines.
105 ;; Org-mode loads this module by default - if this is not what you want,
106 ;; configure the variable `org-modules'.
108 ;;; Code:
110 (require 'org)
111 (require 'bibtex)
112 (require 'cl-lib)
113 (require 'org-compat)
115 (defvar org-agenda-overriding-header)
116 (defvar org-agenda-search-view-always-boolean)
117 (defvar org-bibtex-description nil) ; dynamically scoped from org.el
118 (defvar org-id-locations)
120 (declare-function bibtex-beginning-of-entry "bibtex" ())
121 (declare-function bibtex-generate-autokey "bibtex" ())
122 (declare-function bibtex-parse-entry "bibtex" (&optional content))
123 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
124 (declare-function org-babel-trim "ob-core" (string &optional regexp))
127 ;;; Bibtex data
128 (defvar org-bibtex-types
129 '((:article
130 (:description . "An article from a journal or magazine")
131 (:required :author :title :journal :year)
132 (:optional :volume :number :pages :month :note))
133 (:book
134 (:description . "A book with an explicit publisher")
135 (:required (:editor :author) :title :publisher :year)
136 (:optional (:volume :number) :series :address :edition :month :note))
137 (:booklet
138 (:description . "A work that is printed and bound, but without a named publisher or sponsoring institution.")
139 (:required :title)
140 (:optional :author :howpublished :address :month :year :note))
141 (:conference
142 (:description . "")
143 (:required :author :title :booktitle :year)
144 (:optional :editor :pages :organization :publisher :address :month :note))
145 (:inbook
146 (:description . "A part of a book, which may be a chapter (or section or whatever) and/or a range of pages.")
147 (:required (:author :editor) :title (:chapter :pages) :publisher :year)
148 (:optional :crossref (:volume :number) :series :type :address :edition :month :note))
149 (:incollection
150 (:description . "A part of a book having its own title.")
151 (:required :author :title :booktitle :publisher :year)
152 (:optional :crossref :editor (:volume :number) :series :type :chapter :pages :address :edition :month :note))
153 (:inproceedings
154 (:description . "An article in a conference proceedings")
155 (:required :author :title :booktitle :year)
156 (:optional :crossref :editor (:volume :number) :series :pages :address :month :organization :publisher :note))
157 (:manual
158 (:description . "Technical documentation.")
159 (:required :title)
160 (:optional :author :organization :address :edition :month :year :note))
161 (:mastersthesis
162 (:description . "A Master’s thesis.")
163 (:required :author :title :school :year)
164 (:optional :type :address :month :note))
165 (:misc
166 (:description . "Use this type when nothing else fits.")
167 (:required)
168 (:optional :author :title :howpublished :month :year :note))
169 (:phdthesis
170 (:description . "A PhD thesis.")
171 (:required :author :title :school :year)
172 (:optional :type :address :month :note))
173 (:proceedings
174 (:description . "The proceedings of a conference.")
175 (:required :title :year)
176 (:optional :editor (:volume :number) :series :address :month :organization :publisher :note))
177 (:techreport
178 (:description . "A report published by a school or other institution.")
179 (:required :author :title :institution :year)
180 (:optional :type :address :month :note))
181 (:unpublished
182 (:description . "A document having an author and title, but not formally published.")
183 (:required :author :title :note)
184 (:optional :month :year)))
185 "Bibtex entry types with required and optional parameters.")
187 (defvar org-bibtex-fields
188 '((: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.")
189 (:annote . "An annotation. It is not used by the standard bibliography styles, but may be used by others that produce an annotated bibliography.")
190 (: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.")
191 (: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.")
192 (:chapter . "A chapter (or section or whatever) number.")
193 (:crossref . "The database key of the entry being cross referenced.")
194 (: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.")
195 (: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.")
196 (:howpublished . "How something strange has been published. The first word should be capitalized.")
197 (:institution . "The sponsoring institution of a technical report.")
198 (:journal . "A journal name.")
199 (: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.")
200 (: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,")
201 (:note . "Any additional information that can help the reader. The first word should be capitalized.")
202 (:number . "Any additional information that can help the reader. The first word should be capitalized.")
203 (:organization . "The organization that sponsors a conference or that publishes a manual.")
204 (: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 (--).")
205 (:publisher . "The publisher’s name.")
206 (:school . "The name of the school where a thesis was written.")
207 (:series . "The name of a series or set of books. When citing an entire book, 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.")
208 (:title . "The work’s title, typed as explained in the LaTeX book.")
209 (:type . "The type of a technical report for example, 'Research Note'.")
210 (:volume . "The volume of a journal or multi-volume book.")
211 (: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)'"))
212 "Bibtex fields with descriptions.")
214 (defvar org-bibtex-entries nil
215 "List to hold parsed bibtex entries.")
217 (defcustom org-bibtex-autogen-keys nil
218 "Set to a truth value to use `bibtex-generate-autokey' to generate keys."
219 :group 'org-bibtex
220 :version "24.1"
221 :type 'boolean)
223 (defcustom org-bibtex-prefix nil
224 "Optional prefix for all bibtex property names.
225 For example setting to `BIB_' would allow interoperability with fireforg."
226 :group 'org-bibtex
227 :version "24.1"
228 :type '(choice
229 (const nil)
230 (string)))
232 (defcustom org-bibtex-treat-headline-as-title t
233 "Treat headline text as title if title property is absent.
234 If an entry is missing a title property, use the headline text as
235 the property. If this value is t, `org-bibtex-check' will ignore
236 a missing title field."
237 :group 'org-bibtex
238 :version "24.1"
239 :type 'boolean)
241 (defcustom org-bibtex-export-arbitrary-fields nil
242 "When converting to bibtex allow fields not defined in `org-bibtex-fields'.
243 This only has effect if `org-bibtex-prefix' is defined, so as to
244 ensure that other org-properties, such as CATEGORY or LOGGING are
245 not placed in the exported bibtex entry."
246 :group 'org-bibtex
247 :version "24.1"
248 :type 'boolean)
250 (defcustom org-bibtex-key-property "CUSTOM_ID"
251 "Property that holds the bibtex key.
252 By default, this is CUSTOM_ID, which enables easy linking to
253 bibtex headlines from within an org file. This can be set to ID
254 to enable global links, but only with great caution, as global
255 IDs must be unique."
256 :group 'org-bibtex
257 :version "24.1"
258 :type 'string)
260 (defcustom org-bibtex-tags nil
261 "List of tag(s) that should be added to new bib entries."
262 :group 'org-bibtex
263 :version "24.1"
264 :type '(repeat :tag "Tag" (string)))
266 (defcustom org-bibtex-tags-are-keywords nil
267 "Convert the value of the keywords field to tags and vice versa.
269 When non-nil, comma-separated entries in a bibtex entry's keywords
270 field will be converted to Org tags. Note: spaces will be escaped
271 with underscores, and characters that are not permitted in Org
272 tags will be removed.
274 When non-nil, local tags in an Org entry will be exported as
275 a comma-separated string of keywords when exported to bibtex.
276 If `org-bibtex-inherit-tags' is non-nil, inherited tags will also
277 be exported as keywords. Tags defined in `org-bibtex-tags' or
278 `org-bibtex-no-export-tags' will not be exported."
279 :group 'org-bibtex
280 :version "24.1"
281 :type 'boolean)
283 (defcustom org-bibtex-no-export-tags nil
284 "List of tag(s) that should not be converted to keywords.
285 This variable is relevant only if `org-bibtex-tags-are-keywords'
286 is non-nil."
287 :group 'org-bibtex
288 :version "24.1"
289 :type '(repeat :tag "Tag" (string)))
291 (defcustom org-bibtex-inherit-tags nil
292 "Controls whether inherited tags are converted to bibtex keywords.
293 It is relevant only if `org-bibtex-tags-are-keywords' is non-nil.
294 Tag inheritence itself is controlled by `org-use-tag-inheritence'
295 and `org-exclude-tags-from-inheritence'."
296 :group 'org-bibtex
297 :version "25.1"
298 :package-version '(Org . "8.3")
299 :type 'boolean)
301 (defcustom org-bibtex-type-property-name "btype"
302 "Property in which to store bibtex entry type (e.g., article)."
303 :group 'org-bibtex
304 :version "24.1"
305 :type 'string)
308 ;;; Utility functions
309 (defun org-bibtex-get (property)
310 (let ((it (let ((org-special-properties
311 (delete "FILE" (copy-sequence org-special-properties))))
313 (org-entry-get (point) (upcase property))
314 (org-entry-get (point) (concat org-bibtex-prefix
315 (upcase property)))))))
316 (when it (org-babel-trim it))))
318 (defun org-bibtex-put (property value)
319 (let ((prop (upcase (if (keywordp property)
320 (substring (symbol-name property) 1)
321 property))))
322 (org-set-property
323 (concat (unless (string= org-bibtex-key-property prop) org-bibtex-prefix)
324 prop)
325 value)))
327 (defun org-bibtex-headline ()
328 "Return a bibtex entry of the given headline as a string."
329 (letrec ((val (lambda (key lst) (cdr (assoc key lst))))
330 (to (lambda (string) (intern (concat ":" string))))
331 (from (lambda (key) (substring (symbol-name key) 1)))
332 (flatten (lambda (&rest lsts)
333 (apply #'append (mapcar
334 (lambda (e)
335 (if (listp e) (apply flatten e) (list e)))
336 lsts))))
337 (id (org-bibtex-get org-bibtex-key-property))
338 (type (org-bibtex-get org-bibtex-type-property-name))
339 (tags (when org-bibtex-tags-are-keywords
340 (delq nil
341 (mapcar
342 (lambda (tag)
343 (unless (member tag
344 (append org-bibtex-tags
345 org-bibtex-no-export-tags))
346 tag))
347 (if org-bibtex-inherit-tags
348 (org-get-tags-at)
349 (org-get-local-tags-at)))))))
350 (when type
351 (let ((entry (format
352 "@%s{%s,\n%s\n}\n" type id
353 (mapconcat
354 (lambda (pair)
355 (format " %s={%s}" (car pair) (cdr pair)))
356 (remove nil
357 (if (and org-bibtex-export-arbitrary-fields
358 org-bibtex-prefix)
359 (mapcar
360 (lambda (kv)
361 (let ((key (car kv)) (val0 (cdr kv)))
362 (when (and
363 (string-match org-bibtex-prefix key)
364 (not (string=
365 (downcase (concat org-bibtex-prefix
366 org-bibtex-type-property-name))
367 (downcase key))))
368 (cons (downcase (replace-regexp-in-string
369 org-bibtex-prefix "" key))
370 val0))))
371 (org-entry-properties nil 'standard))
372 (mapcar
373 (lambda (field)
374 (let ((value (or (org-bibtex-get (funcall from field))
375 (and (equal :title field)
376 (nth 4 (org-heading-components))))))
377 (when value (cons (funcall from field) value))))
378 (funcall flatten
379 (funcall val :required (funcall val (funcall to type) org-bibtex-types))
380 (funcall val :optional (funcall val (funcall to type) org-bibtex-types))))))
381 ",\n"))))
382 (with-temp-buffer
383 (insert entry)
384 (when tags
385 (bibtex-beginning-of-entry)
386 (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
387 (progn (goto-char (match-end 1)) (insert ", "))
388 (search-forward ",\n" nil t)
389 (insert " keywords={},\n")
390 (search-backward "}," nil t))
391 (insert (mapconcat #'identity tags ", ")))
392 (buffer-string))))))
394 (defun org-bibtex-ask (field)
395 (unless (assoc field org-bibtex-fields)
396 (error "Field:%s is not known" field))
397 (save-window-excursion
398 (let* ((name (substring (symbol-name field) 1))
399 (buf-name (format "*Bibtex Help %s*" name)))
400 (with-output-to-temp-buffer buf-name
401 (princ (cdr (assoc field org-bibtex-fields))))
402 (with-current-buffer buf-name (visual-line-mode 1))
403 (org-fit-window-to-buffer (get-buffer-window buf-name))
404 (let ((result (read-from-minibuffer (format "%s: " name))))
405 (when (> (length result) 0) result)))))
407 (defun org-bibtex-autokey ()
408 "Generate an autokey for the current headline."
409 (org-bibtex-put org-bibtex-key-property
410 (if org-bibtex-autogen-keys
411 (let* ((entry (org-bibtex-headline))
412 (key
413 (with-temp-buffer
414 (insert entry)
415 (bibtex-generate-autokey))))
416 ;; test for duplicate IDs if using global ID
417 (when (and
418 (equal org-bibtex-key-property "ID")
419 (featurep 'org-id)
420 (hash-table-p org-id-locations)
421 (gethash key org-id-locations))
422 (warn "Another entry has the same ID"))
423 key)
424 (read-from-minibuffer "id: "))))
426 (defun org-bibtex-fleshout (type &optional optional)
427 "Fleshout current heading, ensuring all required fields are present.
428 With optional argument OPTIONAL, also prompt for optional fields."
429 (let ((val (lambda (key lst) (cdr (assoc key lst))))
430 (keyword (lambda (name) (intern (concat ":" (downcase name)))))
431 (name (lambda (keyword) (substring (symbol-name keyword) 1))))
432 (dolist (field (append
433 (if org-bibtex-treat-headline-as-title
434 (remove :title (funcall val :required (funcall val type org-bibtex-types)))
435 (funcall val :required (funcall val type org-bibtex-types)))
436 (when optional (funcall val :optional (funcall val type org-bibtex-types)))))
437 (when (consp field) ; or'd pair of fields e.g., (:editor :author)
438 (let ((present (first (remove
440 (mapcar
441 (lambda (f) (when (org-bibtex-get (funcall name f)) f))
442 field)))))
443 (setf field (or present (funcall keyword
444 (completing-read
445 "Field: " (mapcar name field)))))))
446 (let ((name (funcall name field)))
447 (unless (org-bibtex-get name)
448 (let ((prop (org-bibtex-ask field)))
449 (when prop (org-bibtex-put name prop)))))))
450 (when (and type (assoc type org-bibtex-types)
451 (not (org-bibtex-get org-bibtex-key-property)))
452 (org-bibtex-autokey)))
455 ;;; Bibtex link functions
456 (org-add-link-type "bibtex" 'org-bibtex-open)
457 (add-hook 'org-store-link-functions 'org-bibtex-store-link)
459 (defun org-bibtex-open (path)
460 "Visit the bibliography entry on PATH."
461 (let* ((search (when (string-match "::\\(.+\\)\\'" path)
462 (match-string 1 path)))
463 (path (substring path 0 (match-beginning 0))))
464 (org-open-file path t nil search)))
466 (defun org-bibtex-store-link ()
467 "Store a link to a BibTeX entry."
468 (when (eq major-mode 'bibtex-mode)
469 (let* ((search (org-create-file-search-in-bibtex))
470 (link (concat "file:" (abbreviate-file-name buffer-file-name)
471 "::" search))
472 (entry (mapcar ; repair strings enclosed in "..." or {...}
473 (lambda(c)
474 (if (string-match
475 "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c))
476 (cons (car c) (match-string 1 (cdr c))) c))
477 (save-excursion
478 (bibtex-beginning-of-entry)
479 (bibtex-parse-entry)))))
480 (org-store-link-props
481 :key (cdr (assoc "=key=" entry))
482 :author (or (cdr (assoc "author" entry)) "[no author]")
483 :editor (or (cdr (assoc "editor" entry)) "[no editor]")
484 :title (or (cdr (assoc "title" entry)) "[no title]")
485 :booktitle (or (cdr (assoc "booktitle" entry)) "[no booktitle]")
486 :journal (or (cdr (assoc "journal" entry)) "[no journal]")
487 :publisher (or (cdr (assoc "publisher" entry)) "[no publisher]")
488 :pages (or (cdr (assoc "pages" entry)) "[no pages]")
489 :url (or (cdr (assoc "url" entry)) "[no url]")
490 :year (or (cdr (assoc "year" entry)) "[no year]")
491 :month (or (cdr (assoc "month" entry)) "[no month]")
492 :address (or (cdr (assoc "address" entry)) "[no address]")
493 :volume (or (cdr (assoc "volume" entry)) "[no volume]")
494 :number (or (cdr (assoc "number" entry)) "[no number]")
495 :annote (or (cdr (assoc "annote" entry)) "[no annotation]")
496 :series (or (cdr (assoc "series" entry)) "[no series]")
497 :abstract (or (cdr (assoc "abstract" entry)) "[no abstract]")
498 :btype (or (cdr (assoc "=type=" entry)) "[no type]")
499 :type "bibtex"
500 :link link
501 :description org-bibtex-description))))
503 (defun org-create-file-search-in-bibtex ()
504 "Create the search string and description for a BibTeX database entry."
505 ;; Make a good description for this entry, using names, year and the title
506 ;; Put it into the `description' variable which is dynamically scoped.
507 (let ((bibtex-autokey-names 1)
508 (bibtex-autokey-names-stretch 1)
509 (bibtex-autokey-name-case-convert-function 'identity)
510 (bibtex-autokey-name-separator " & ")
511 (bibtex-autokey-additional-names " et al.")
512 (bibtex-autokey-year-length 4)
513 (bibtex-autokey-name-year-separator " ")
514 (bibtex-autokey-titlewords 3)
515 (bibtex-autokey-titleword-separator " ")
516 (bibtex-autokey-titleword-case-convert-function 'identity)
517 (bibtex-autokey-titleword-length 'infty)
518 (bibtex-autokey-year-title-separator ": "))
519 (setq org-bibtex-description (bibtex-generate-autokey)))
520 ;; Now parse the entry, get the key and return it.
521 (save-excursion
522 (bibtex-beginning-of-entry)
523 (cdr (assoc "=key=" (bibtex-parse-entry)))))
525 (defun org-execute-file-search-in-bibtex (s)
526 "Find the link search string S as a key for a database entry."
527 (when (eq major-mode 'bibtex-mode)
528 ;; Yes, we want to do the search in this file.
529 ;; We construct a regexp that searches for "@entrytype{" followed by the key
530 (goto-char (point-min))
531 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
532 (regexp-quote s) "[ \t\n]*,") nil t)
533 (goto-char (match-beginning 0)))
534 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
535 ;; Use double prefix to indicate that any web link should be browsed
536 (let ((b (current-buffer)) (p (point)))
537 ;; Restore the window configuration because we just use the web link
538 (set-window-configuration org-window-config-before-follow-link)
539 (with-current-buffer b
540 (goto-char p)
541 (bibtex-url)))
542 (recenter 0)) ; Move entry start to beginning of window
543 ;; return t to indicate that the search is done.
546 ;; Finally add the link search function to the right hook.
547 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
550 ;;; Bibtex <-> Org-mode headline translation functions
551 (defun org-bibtex (filename)
552 "Export each headline in the current file to a bibtex entry.
553 Headlines are exported using `org-bibtex-headline'."
554 (interactive
555 (list (read-file-name
556 "Bibtex file: " nil nil nil
557 (let ((file (buffer-file-name (buffer-base-buffer))))
558 (and file
559 (file-name-nondirectory
560 (concat (file-name-sans-extension file) ".bib")))))))
561 (let ((error-point
562 (catch 'bib
563 (let ((bibtex-entries
564 (remove nil (org-map-entries
565 (lambda ()
566 (condition-case nil
567 (org-bibtex-headline)
568 (error (throw 'bib (point)))))))))
569 (with-temp-file filename
570 (insert (mapconcat #'identity bibtex-entries "\n")))
571 (message "Successfully exported %d BibTeX entries to %s"
572 (length bibtex-entries) filename) nil))))
573 (when error-point
574 (goto-char error-point)
575 (message "Bibtex error at %S" (nth 4 (org-heading-components))))))
577 (defun org-bibtex-check (&optional optional)
578 "Check the current headline for required fields.
579 With prefix argument OPTIONAL also prompt for optional fields."
580 (interactive "P")
581 (save-restriction
582 (org-narrow-to-subtree)
583 (let ((type (let ((name (org-bibtex-get org-bibtex-type-property-name)))
584 (when name (intern (concat ":" name))))))
585 (when type (org-bibtex-fleshout type optional)))))
587 (defun org-bibtex-check-all (&optional optional)
588 "Check all headlines in the current file.
589 With prefix argument OPTIONAL also prompt for optional fields."
590 (interactive) (org-map-entries (lambda () (org-bibtex-check optional))))
592 (defun org-bibtex-create (&optional arg nonew)
593 "Create a new entry at the given level.
594 With a prefix arg, query for optional fields as well.
595 If nonew is t, add data to the headline of the entry at point."
596 (interactive "P")
597 (let* ((type (completing-read
598 "Type: " (mapcar (lambda (type)
599 (substring (symbol-name (car type)) 1))
600 org-bibtex-types)
601 nil nil (when nonew
602 (org-bibtex-get org-bibtex-type-property-name))))
603 (type (if (keywordp type) type (intern (concat ":" type))))
604 (org-bibtex-treat-headline-as-title (if nonew nil t)))
605 (unless (assoc type org-bibtex-types)
606 (error "Type:%s is not known" type))
607 (if nonew
608 (org-back-to-heading)
609 (org-insert-heading)
610 (let ((title (org-bibtex-ask :title)))
611 (insert title)
612 (org-bibtex-put "TITLE" title)))
613 (org-bibtex-put org-bibtex-type-property-name
614 (substring (symbol-name type) 1))
615 (org-bibtex-fleshout type arg)
616 (dolist (tag org-bibtex-tags) (org-toggle-tag tag 'on))))
618 (defun org-bibtex-create-in-current-entry (&optional arg)
619 "Add bibliographical data to the current entry.
620 With a prefix arg, query for optional fields."
621 (interactive "P")
622 (org-bibtex-create arg t))
624 (defun org-bibtex-read ()
625 "Read a bibtex entry and save to `org-bibtex-entries'.
626 This uses `bibtex-parse-entry'."
627 (interactive)
628 (let ((keyword (lambda (str) (intern (concat ":" (downcase str)))))
629 (clean-space (lambda (str) (replace-regexp-in-string
630 "[[:space:]\n\r]+" " " str)))
631 (strip-delim
632 (lambda (str) ; strip enclosing "..." and {...}
633 (dolist (pair '((34 . 34) (123 . 125)))
634 (when (and (> (length str) 1)
635 (= (aref str 0) (car pair))
636 (= (aref str (1- (length str))) (cdr pair)))
637 (setf str (substring str 1 (1- (length str)))))) str)))
638 (push (mapcar
639 (lambda (pair)
640 (cons (let ((field (funcall keyword (car pair))))
641 (case field
642 (:=type= :type)
643 (:=key= :key)
644 (otherwise field)))
645 (funcall clean-space (funcall strip-delim (cdr pair)))))
646 (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
647 org-bibtex-entries)))
649 (defun org-bibtex-read-buffer (buffer)
650 "Read all bibtex entries in BUFFER and save to `org-bibtex-entries'.
651 Return the number of saved entries."
652 (interactive "bBuffer: ")
653 (let ((start-length (length org-bibtex-entries)))
654 (with-current-buffer buffer
655 (save-excursion
656 (goto-char (point-max))
657 (while (not (= (point) (point-min)))
658 (backward-char 1)
659 (org-bibtex-read)
660 (bibtex-beginning-of-entry))))
661 (let ((added (- (length org-bibtex-entries) start-length)))
662 (message "Parsed %d entries" added)
663 added)))
665 (defun org-bibtex-read-file (file)
666 "Read FILE with `org-bibtex-read-buffer'."
667 (interactive "fFile: ")
668 (org-bibtex-read-buffer (find-file-noselect file 'nowarn 'rawfile)))
670 (defun org-bibtex-write ()
671 "Insert a heading built from the first element of `org-bibtex-entries'."
672 (interactive)
673 (when (= (length org-bibtex-entries) 0)
674 (error "No entries in `org-bibtex-entries'"))
675 (let* ((entry (pop org-bibtex-entries))
676 (org-special-properties nil) ; avoids errors with `org-entry-put'
677 (val (lambda (field) (cdr (assoc field entry))))
678 (togtag (lambda (tag) (org-toggle-tag tag 'on))))
679 (org-insert-heading)
680 (insert (funcall val :title))
681 (org-bibtex-put "TITLE" (funcall val :title))
682 (org-bibtex-put org-bibtex-type-property-name
683 (downcase (funcall val :type)))
684 (dolist (pair entry)
685 (case (car pair)
686 (:title nil)
687 (:type nil)
688 (:key (org-bibtex-put org-bibtex-key-property (cdr pair)))
689 (:keywords (if org-bibtex-tags-are-keywords
690 (dolist (kw (split-string (cdr pair) ", *"))
691 (funcall
692 togtag
693 (replace-regexp-in-string
694 "[^[:alnum:]_@#%]" ""
695 (replace-regexp-in-string "[ \t]+" "_" kw))))
696 (org-bibtex-put (car pair) (cdr pair))))
697 (otherwise (org-bibtex-put (car pair) (cdr pair)))))
698 (mapc togtag org-bibtex-tags)))
700 (defun org-bibtex-yank ()
701 "If kill ring holds a bibtex entry yank it as an Org-mode headline."
702 (interactive)
703 (let (entry)
704 (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
705 (if entry
706 (org-bibtex-write)
707 (error "Yanked text does not appear to contain a BibTeX entry"))))
709 (defun org-bibtex-import-from-file (file)
710 "Read bibtex entries from FILE and insert as Org-mode headlines after point."
711 (interactive "fFile: ")
712 (dotimes (_ (org-bibtex-read-file file))
713 (save-excursion (org-bibtex-write))
714 (re-search-forward org-property-end-re)
715 (open-line 1) (forward-char 1)))
717 (defun org-bibtex-export-to-kill-ring ()
718 "Export current headline to kill ring as bibtex entry."
719 (interactive)
720 (let ((result (org-bibtex-headline)))
721 (kill-new result) result))
723 (defun org-bibtex-search (string)
724 "Search for bibliographical entries in agenda files.
725 This function relies `org-search-view' to locate results."
726 (interactive "sSearch string: ")
727 (let ((org-agenda-overriding-header "Bib search results:")
728 (org-agenda-search-view-always-boolean t))
729 (org-search-view nil
730 (format "%s +{:%s%s:}"
731 string (or org-bibtex-prefix "")
732 org-bibtex-type-property-name))))
734 (provide 'org-bibtex)
736 ;;; org-bibtex.el ends here