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