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