ob-tests: adding tests of new un-named arguments
[org-mode/org-jambu.git] / lisp / org-bibtex.el
blob6c46b28d605959c98cbb73d153576d735d217a3e
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
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/>.
26 ;;; Commentary:
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
43 ;; :key :btype
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:
54 ;; @Article{dolev83,
55 ;; author = {Danny Dolev and Andrew C. Yao},
56 ;; title = {On the security of public-key protocols},
57 ;; journal = {IEEE Transaction on Information Theory},
58 ;; year = 1983,
59 ;; volume = 2,
60 ;; number = 29,
61 ;; pages = {198--208},
62 ;; month = {Mars}
63 ;; }
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
94 ;;; History:
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'.
109 ;;; Code:
111 (require 'org)
112 (require 'bibtex)
113 (eval-when-compile
114 (require 'cl))
116 (defvar description nil) ; dynamically scoped from org.el
117 (defvar org-id-locations)
119 (declare-function bibtex-beginning-of-entry "bibtex" ())
120 (declare-function bibtex-generate-autokey "bibtex" ())
121 (declare-function bibtex-parse-entry "bibtex" (&optional content))
122 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
123 (declare-function longlines-mode "longlines" (&optional arg))
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)))
278 ;;; Utility functions
279 (defun org-bibtex-get (property)
280 (or (org-entry-get (point) (upcase property))
281 (org-entry-get (point) (concat org-bibtex-prefix (upcase property)))))
283 (defun org-bibtex-put (property value)
284 (let ((prop (upcase (if (keywordp property)
285 (substring (symbol-name property) 1)
286 property))))
287 (org-set-property
288 (concat (unless (string= org-bibtex-key-property prop) org-bibtex-prefix)
289 prop)
290 value)))
292 (defun org-bibtex-headline ()
293 "Return a bibtex entry of the given headline as a string."
294 (flet ((val (key lst) (cdr (assoc key lst)))
295 (to (string) (intern (concat ":" string)))
296 (from (key) (substring (symbol-name key) 1))
297 (flatten (&rest lsts)
298 (apply #'append (mapcar
299 (lambda (e)
300 (if (listp e) (apply #'flatten e) (list e)))
301 lsts))))
302 (let ((notes (buffer-string))
303 (id (org-bibtex-get org-bibtex-key-property))
304 (type (org-bibtex-get "type"))
305 (tags (when org-bibtex-tags-are-keywords
306 (delq nil
307 (mapcar
308 (lambda (tag)
309 (unless (member tag
310 (append org-bibtex-tags
311 org-bibtex-no-export-tags))
312 tag))
313 (org-get-local-tags-at))))))
314 (when type
315 (let ((entry (format
316 "@%s{%s,\n%s\n}\n" type id
317 (mapconcat
318 (lambda (pair) (format " %s={%s}" (car pair) (cdr pair)))
319 (remove nil
320 (if (and org-bibtex-export-arbitrary-fields
321 org-bibtex-prefix)
322 (mapcar
323 (lambda (kv)
324 (let ((key (car kv)) (val (cdr kv)))
325 (when (and (string-match org-bibtex-prefix key)
326 (not (string=
327 (downcase (concat org-bibtex-prefix "TYPE")) (downcase key))))
328 (cons (downcase (replace-regexp-in-string
329 org-bibtex-prefix "" key))
330 val))))
331 (org-entry-properties nil 'standard))
332 (mapcar
333 (lambda (field)
334 (let ((value (or (org-bibtex-get (from field))
335 (and (equal :title field)
336 (nth 4 (org-heading-components))))))
337 (when value (cons (from field) value))))
338 (flatten
339 (val :required (val (to type) org-bibtex-types))
340 (val :optional (val (to type) org-bibtex-types))))))
341 ",\n"))))
342 (with-temp-buffer
343 (insert entry)
344 (when tags
345 (bibtex-beginning-of-entry)
346 (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
347 (progn (goto-char (match-end 1)) (insert ", "))
348 (bibtex-make-field "keywords" t t))
349 (insert (mapconcat #'identity tags ", ")))
350 (bibtex-reformat) (buffer-string)))))))
352 (defun org-bibtex-ask (field)
353 (unless (assoc field org-bibtex-fields)
354 (error "field:%s is not known" field))
355 (save-window-excursion
356 (let* ((name (substring (symbol-name field) 1))
357 (buf-name (format "*Bibtex Help %s*" name)))
358 (with-output-to-temp-buffer buf-name
359 (princ (cdr (assoc field org-bibtex-fields))))
360 (with-current-buffer buf-name (longlines-mode t))
361 (org-fit-window-to-buffer (get-buffer-window buf-name))
362 ((lambda (result) (when (> (length result) 0) result))
363 (read-from-minibuffer (format "%s: " name))))))
365 (defun org-bibtex-autokey ()
366 "Generate an autokey for the current headline"
367 (org-bibtex-put org-bibtex-key-property
368 (if org-bibtex-autogen-keys
369 (let* ((entry (org-bibtex-headline))
370 (key
371 (with-temp-buffer
372 (insert entry)
373 (bibtex-generate-autokey))))
374 ;; test for duplicate IDs if using global ID
375 (when (and
376 (equal org-bibtex-key-property "ID")
377 (featurep 'org-id)
378 (hash-table-p org-id-locations)
379 (gethash key org-id-locations))
380 (warn "Another entry has the same ID"))
381 key)
382 (read-from-minibuffer "id: "))))
384 (defun org-bibtex-fleshout (type &optional optional)
385 "Fleshout the current heading, ensuring that all required fields are present.
386 With optional argument OPTIONAL, also prompt for optional fields."
387 (flet ((val (key lst) (cdr (assoc key lst)))
388 (keyword (name) (intern (concat ":" (downcase name))))
389 (name (keyword) (substring (symbol-name keyword) 1)))
390 (dolist (field (append
391 (if org-bibtex-treat-headline-as-title
392 (remove :title (val :required (val type org-bibtex-types)))
393 (val :required (val type org-bibtex-types)))
394 (when optional (val :optional (val type org-bibtex-types)))))
395 (when (consp field) ; or'd pair of fields e.g., (:editor :author)
396 (let ((present (first (remove nil
397 (mapcar
398 (lambda (f) (when (org-bibtex-get (name f)) f))
399 field)))))
400 (setf field (or present (keyword (org-icompleting-read
401 "Field: " (mapcar #'name field)))))))
402 (let ((name (name field)))
403 (unless (org-bibtex-get name)
404 (let ((prop (org-bibtex-ask field)))
405 (when prop (org-bibtex-put name prop)))))))
406 (when (and type (assoc type org-bibtex-types)
407 (not (org-bibtex-get org-bibtex-key-property)))
408 (org-bibtex-autokey)))
411 ;;; Bibtex link functions
412 (org-add-link-type "bibtex" 'org-bibtex-open)
413 (add-hook 'org-store-link-functions 'org-bibtex-store-link)
415 (defun org-bibtex-open (path)
416 "Visit the bibliography entry on PATH."
417 (let* ((search (when (string-match "::\\(.+\\)\\'" path)
418 (match-string 1 path)))
419 (path (substring path 0 (match-beginning 0))))
420 (org-open-file path t nil search)))
422 (defun org-bibtex-store-link ()
423 "Store a link to a BibTeX entry."
424 (when (eq major-mode 'bibtex-mode)
425 (let* ((search (org-create-file-search-in-bibtex))
426 (link (concat "file:" (abbreviate-file-name buffer-file-name)
427 "::" search))
428 (entry (mapcar ; repair strings enclosed in "..." or {...}
429 (lambda(c)
430 (if (string-match
431 "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c))
432 (cons (car c) (match-string 1 (cdr c))) c))
433 (save-excursion
434 (bibtex-beginning-of-entry)
435 (bibtex-parse-entry)))))
436 (org-store-link-props
437 :key (cdr (assoc "=key=" entry))
438 :author (or (cdr (assoc "author" entry)) "[no author]")
439 :editor (or (cdr (assoc "editor" entry)) "[no editor]")
440 :title (or (cdr (assoc "title" entry)) "[no title]")
441 :booktitle (or (cdr (assoc "booktitle" entry)) "[no booktitle]")
442 :journal (or (cdr (assoc "journal" entry)) "[no journal]")
443 :publisher (or (cdr (assoc "publisher" entry)) "[no publisher]")
444 :pages (or (cdr (assoc "pages" entry)) "[no pages]")
445 :url (or (cdr (assoc "url" entry)) "[no url]")
446 :year (or (cdr (assoc "year" entry)) "[no year]")
447 :month (or (cdr (assoc "month" entry)) "[no month]")
448 :address (or (cdr (assoc "address" entry)) "[no address]")
449 :volume (or (cdr (assoc "volume" entry)) "[no volume]")
450 :number (or (cdr (assoc "number" entry)) "[no number]")
451 :annote (or (cdr (assoc "annote" entry)) "[no annotation]")
452 :series (or (cdr (assoc "series" entry)) "[no series]")
453 :abstract (or (cdr (assoc "abstract" entry)) "[no abstract]")
454 :btype (or (cdr (assoc "=type=" entry)) "[no type]")
455 :type "bibtex"
456 :link link
457 :description description))))
459 (defun org-create-file-search-in-bibtex ()
460 "Create the search string and description for a BibTeX database entry."
461 ;; Make a good description for this entry, using names, year and the title
462 ;; Put it into the `description' variable which is dynamically scoped.
463 (let ((bibtex-autokey-names 1)
464 (bibtex-autokey-names-stretch 1)
465 (bibtex-autokey-name-case-convert-function 'identity)
466 (bibtex-autokey-name-separator " & ")
467 (bibtex-autokey-additional-names " et al.")
468 (bibtex-autokey-year-length 4)
469 (bibtex-autokey-name-year-separator " ")
470 (bibtex-autokey-titlewords 3)
471 (bibtex-autokey-titleword-separator " ")
472 (bibtex-autokey-titleword-case-convert-function 'identity)
473 (bibtex-autokey-titleword-length 'infty)
474 (bibtex-autokey-year-title-separator ": "))
475 (setq description (bibtex-generate-autokey)))
476 ;; Now parse the entry, get the key and return it.
477 (save-excursion
478 (bibtex-beginning-of-entry)
479 (cdr (assoc "=key=" (bibtex-parse-entry)))))
481 (defun org-execute-file-search-in-bibtex (s)
482 "Find the link search string S as a key for a database entry."
483 (when (eq major-mode 'bibtex-mode)
484 ;; Yes, we want to do the search in this file.
485 ;; We construct a regexp that searches for "@entrytype{" followed by the key
486 (goto-char (point-min))
487 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
488 (regexp-quote s) "[ \t\n]*,") nil t)
489 (goto-char (match-beginning 0)))
490 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
491 ;; Use double prefix to indicate that any web link should be browsed
492 (let ((b (current-buffer)) (p (point)))
493 ;; Restore the window configuration because we just use the web link
494 (set-window-configuration org-window-config-before-follow-link)
495 (with-current-buffer b
496 (goto-char p)
497 (bibtex-url)))
498 (recenter 0)) ; Move entry start to beginning of window
499 ;; return t to indicate that the search is done.
502 ;; Finally add the link search function to the right hook.
503 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
506 ;;; Bibtex <-> Org-mode headline translation functions
507 (defun org-bibtex (&optional filename)
508 "Export each headline in the current file to a bibtex entry.
509 Headlines are exported using `org-bibtex-export-headline'."
510 (interactive
511 (list (read-file-name
512 "Bibtex file: " nil nil nil
513 (file-name-nondirectory
514 (concat (file-name-sans-extension (buffer-file-name)) ".bib")))))
515 (let ((bibtex-entries (remove nil (org-map-entries #'org-bibtex-headline))))
516 (with-temp-file filename
517 (insert (mapconcat #'identity bibtex-entries "\n")))))
519 (defun org-bibtex-check (&optional optional)
520 "Check the current headline for required fields.
521 With prefix argument OPTIONAL also prompt for optional fields."
522 (interactive "P")
523 (save-restriction
524 (org-narrow-to-subtree)
525 (let ((type ((lambda (name) (when name (intern (concat ":" name))))
526 (org-bibtex-get "TYPE"))))
527 (when type (org-bibtex-fleshout type optional)))))
529 (defun org-bibtex-check-all (&optional optional)
530 "Check all headlines in the current file.
531 With prefix argument OPTIONAL also prompt for optional fields."
532 (interactive) (org-map-entries (lambda () (org-bibtex-check optional))))
534 (defun org-bibtex-create (&optional arg nonew)
535 "Create a new entry at the given level.
536 With a prefix arg, query for optional fields as well.
537 If nonew is t, add data to the headline of the entry at point."
538 (interactive "P")
539 (let* ((type (org-icompleting-read
540 "Type: " (mapcar (lambda (type)
541 (substring (symbol-name (car type)) 1))
542 org-bibtex-types)
543 nil nil (when nonew (org-bibtex-get "TYPE"))))
544 (type (if (keywordp type) type (intern (concat ":" type))))
545 (org-bibtex-treat-headline-as-title (if nonew nil t)))
546 (unless (assoc type org-bibtex-types)
547 (error "type:%s is not known" type))
548 (if nonew
549 (org-back-to-heading)
550 (org-insert-heading)
551 (let ((title (org-bibtex-ask :title)))
552 (insert title)
553 (org-bibtex-put "TITLE" title)))
554 (org-bibtex-put "TYPE" (substring (symbol-name type) 1))
555 (org-bibtex-fleshout type arg)
556 (mapc (lambda (tag) (org-toggle-tag tag t)) org-bibtex-tags)))
558 (defun org-bibtex-create-in-current-entry (&optional arg)
559 "Add bibliographical data to the current entry.
560 With a prefix arg, query for optional fields."
561 (interactive "P")
562 (org-bibtex-create arg t))
564 (defun org-bibtex-read ()
565 "Read a bibtex entry and save to `*org-bibtex-entries*'.
566 This uses `bibtex-parse-entry'."
567 (interactive)
568 (flet ((keyword (str) (intern (concat ":" (downcase str))))
569 (clean-space (str) (replace-regexp-in-string
570 "[[:space:]\n\r]+" " " str))
571 (strip-delim (str) ; strip enclosing "..." and {...}
572 (dolist (pair '((34 . 34) (123 . 125) (123 . 125)))
573 (when (and (= (aref str 0) (car pair))
574 (= (aref str (1- (length str))) (cdr pair)))
575 (setf str (substring str 1 (1- (length str)))))) str))
576 (push (mapcar
577 (lambda (pair)
578 (cons (let ((field (keyword (car pair))))
579 (case field
580 (:=type= :type)
581 (:=key= :key)
582 (otherwise field)))
583 (clean-space (strip-delim (cdr pair)))))
584 (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
585 *org-bibtex-entries*)))
587 (defun org-bibtex-write ()
588 "Insert a heading built from the first element of `*org-bibtex-entries*'."
589 (interactive)
590 (when (= (length *org-bibtex-entries*) 0)
591 (error "No entries in `*org-bibtex-entries*'."))
592 (let ((entry (pop *org-bibtex-entries*))
593 (org-special-properties nil)) ; avoids errors with `org-entry-put'
594 (flet ((val (field) (cdr (assoc field entry)))
595 (togtag (tag) (org-toggle-tag tag t)))
596 (org-insert-heading)
597 (insert (val :title))
598 (org-bibtex-put "TITLE" (val :title))
599 (org-bibtex-put "TYPE" (downcase (val :type)))
600 (dolist (pair entry)
601 (case (car pair)
602 (:title nil)
603 (:type nil)
604 (:key (org-bibtex-put org-bibtex-key-property (cdr pair)))
605 (:keywords (if org-bibtex-tags-are-keywords
606 (mapc
607 (lambda (kw)
608 (togtag
609 (replace-regexp-in-string
610 "[^[:alnum:]_@#%]" ""
611 (replace-regexp-in-string "[ \t]+" "_" kw))))
612 (split-string (cdr pair) ", *"))
613 (org-bibtex-put (car pair) (cdr pair))))
614 (otherwise (org-bibtex-put (car pair) (cdr pair)))))
615 (mapc #'togtag org-bibtex-tags))))
617 (defun org-bibtex-yank ()
618 "If kill ring holds a bibtex entry yank it as an Org-mode headline."
619 (interactive)
620 (let (entry)
621 (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
622 (if entry
623 (org-bibtex-write)
624 (error "yanked text does not appear to contain a bibtex entry"))))
626 (defun org-bibtex-export-to-kill-ring ()
627 "Export current headline to kill ring as bibtex entry."
628 (interactive)
629 (kill-new (org-bibtex-headline)))
631 (defun org-bibtex-search (string)
632 "Search for bibliographical entries in agenda files.
633 This function relies `org-search-view' to locate results."
634 (interactive "sSearch string: ")
635 (let ((org-agenda-overriding-header "Bib search results:")
636 (org-agenda-search-view-always-boolean t))
637 (org-search-view nil
638 (format "%s +{:%sTYPE:}"
639 string org-bibtex-prefix))))
641 (provide 'org-bibtex)
643 ;; arch-tag: 83987d5a-01b8-41c7-85bc-77700f1285f5
645 ;;; org-bibtex.el ends here