Spelling fixes.
[bpt/emacs.git] / lisp / org / org-bibtex.el
CommitLineData
20908596
CD
1;;; org-bibtex.el --- Org links to BibTeX entries
2;;
cbd20947 3;; Copyright (C) 2007-2011 Free Software Foundation, Inc.
20908596
CD
4;;
5;; Author: Bastien Guerry <bzg at altern dot org>
6;; Carsten Dominik <carsten dot dominik at gmail dot com>
3ab2c837 7;; Eric Schulte <schulte dot eric at gmail dot com>
20908596 8;; Keywords: org, wp, remember
3ab2c837 9;; Version: 7.7
20908596
CD
10;;
11;; This file is part of GNU Emacs.
12;;
b1fc2b50 13;; GNU Emacs is free software: you can redistribute it and/or modify
20908596 14;; it under the terms of the GNU General Public License as published by
b1fc2b50
GM
15;; the Free Software Foundation, either version 3 of the License, or
16;; (at your option) any later version.
20908596
CD
17
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.
22
23;; You should have received a copy of the GNU General Public License
b1fc2b50 24;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
20908596
CD
25;;
26;;; Commentary:
27;;
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
33306645 31;; by reference key. And it constructs a nice description tag for
20908596
CD
32;; the link that contains the author name, the year and a short title.
33;;
34;; It also stores detailed information about the entry so that
35;; remember templates can access and enter this information easily.
36;;
37;; The available properties for each entry are listed here:
38;;
39;; :author :publisher :volume :pages
40;; :editor :url :number :journal
41;; :title :year :series :address
42;; :booktitle :month :annote :abstract
43;; :key :btype
44;;
45;; Here is an example of a remember template that use some of this
46;; information (:author :year :title :journal :pages):
47;;
48;; (setq org-remember-templates
49;; '((?b "* READ %?\n\n%a\n\n%:author (%:year): %:title\n \
50;; In %:journal, %:pages.")))
51;;
52;; Let's say you want to remember this BibTeX entry:
53;;
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;; }
64;;
65;; M-x `org-remember' on this entry will produce this buffer:
66;;
67;; =====================================================================
68;; * READ <== [point here]
69;;
3ab2c837 70;; [[file:file.bib::dolev83][Dolev & Yao 1983: security of public key protocols]]
20908596
CD
71;;
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;; =====================================================================
75;;
3ab2c837
BG
76;; Additionally, the following functions are now available for storing
77;; bibtex entries within Org-mode documents.
78;;
79;; - Run `org-bibtex' to export the current file to a .bib.
80;;
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
83;;
84;; - Run `org-bibtex-create' to add a bibtex entry
85;;
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
89;;
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
93;;
20908596
CD
94;;; History:
95;;
96;; The link creation part has been part of Org-mode for a long time.
97;;
98;; Creating better remember template information was inspired by a request
99;; of Austin Frank: http://article.gmane.org/gmane.emacs.orgmode/4112
8bfe682a 100;; and then implemented by Bastien Guerry.
20908596 101;;
3ab2c837
BG
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.
105;;
20908596
CD
106;; Org-mode loads this module by default - if this is not what you want,
107;; configure the variable `org-modules'.
108
109;;; Code:
110
111(require 'org)
3ab2c837
BG
112(require 'bibtex)
113(eval-when-compile
114 (require 'cl))
20908596
CD
115
116(defvar description nil) ; dynamically scoped from org.el
3ab2c837 117(defvar org-id-locations)
20908596
CD
118
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))
3ab2c837
BG
123(declare-function longlines-mode "longlines" (&optional arg))
124(declare-function org-babel-trim "ob" (string &optional regexp))
125
126\f
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.")
186
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.")
58179cce 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.")
3ab2c837
BG
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.")
213
214(defvar *org-bibtex-entries* nil
215 "List to hold parsed bibtex entries.")
216
217(defcustom org-bibtex-autogen-keys nil
ee7683eb 218 "Set to a truth value to use `bibtex-generate-autokey' to generate keys."
3ab2c837
BG
219 :group 'org-bibtex
220 :type 'boolean)
221
222(defcustom org-bibtex-prefix nil
223 "Optional prefix for all bibtex property names.
c5e87d10 224For example setting to 'BIB_' would allow interoperability with Fireforg."
3ab2c837
BG
225 :group 'org-bibtex
226 :type 'string)
227
228(defcustom org-bibtex-treat-headline-as-title t
229 "Treat headline text as title if title property is absent.
230If an entry is missing a title property, use the headline text as
231the property. If this value is t, `org-bibtex-check' will ignore
232a missing title field."
233 :group 'org-bibtex
234 :type 'boolean)
235
236(defcustom org-bibtex-export-arbitrary-fields nil
237 "When converting to bibtex allow fields not defined in `org-bibtex-fields'.
238This only has effect if `org-bibtex-prefix' is defined, so as to
239ensure that other org-properties, such as CATEGORY or LOGGING are
240not placed in the exported bibtex entry."
241 :group 'org-bibtex
242 :type 'boolean)
243
244(defcustom org-bibtex-key-property "CUSTOM_ID"
245 "Property that holds the bibtex key.
246By default, this is CUSTOM_ID, which enables easy linking to
247bibtex headlines from within an org file. This can be set to ID
248to enable global links, but only with great caution, as global
249IDs must be unique."
250 :group 'org-bibtex
251 :type 'string)
252
253(defcustom org-bibtex-tags nil
254 "List of tag(s) that should be added to new bib entries."
255 :group 'org-bibtex
256 :type '(repeat :tag "Tag" (string)))
257
258(defcustom org-bibtex-tags-are-keywords nil
259 "Convert the value of the keywords field to tags and vice versa.
260If set to t, comma-separated entries in a bibtex entry's keywords
261field will be converted to org tags. Note: spaces will be escaped
262with underscores, and characters that are not permitted in org
263tags will be removed.
264
265If t, local tags in an org entry will be exported as a
266comma-separated string of keywords when exported to bibtex. Tags
267defined in `org-bibtex-tags' or `org-bibtex-no-export-tags' will
268not be exported."
269 :group 'org-bibtex
270 :type 'boolean)
20908596 271
3ab2c837
BG
272(defcustom org-bibtex-no-export-tags nil
273 "List of tag(s) that should not be converted to keywords.
274This variable is relevant only if `org-bibtex-export-tags-as-keywords` is t."
275 :group 'org-bibtex
276 :type '(repeat :tag "Tag" (string)))
277
278\f
279;;; Utility functions
280(defun org-bibtex-get (property)
281 ((lambda (it) (when it (org-babel-trim it)))
282 (or (org-entry-get (point) (upcase property))
283 (org-entry-get (point) (concat org-bibtex-prefix (upcase property))))))
284
285(defun org-bibtex-put (property value)
286 (let ((prop (upcase (if (keywordp property)
287 (substring (symbol-name property) 1)
288 property))))
289 (org-set-property
290 (concat (unless (string= org-bibtex-key-property prop) org-bibtex-prefix)
291 prop)
292 value)))
293
294(defun org-bibtex-headline ()
295 "Return a bibtex entry of the given headline as a string."
296 (flet ((val (key lst) (cdr (assoc key lst)))
297 (to (string) (intern (concat ":" string)))
298 (from (key) (substring (symbol-name key) 1))
299 (flatten (&rest lsts)
300 (apply #'append (mapcar
301 (lambda (e)
302 (if (listp e) (apply #'flatten e) (list e)))
303 lsts))))
304 (let ((notes (buffer-string))
305 (id (org-bibtex-get org-bibtex-key-property))
306 (type (org-bibtex-get "type"))
307 (tags (when org-bibtex-tags-are-keywords
308 (delq nil
309 (mapcar
310 (lambda (tag)
311 (unless (member tag
312 (append org-bibtex-tags
313 org-bibtex-no-export-tags))
314 tag))
315 (org-get-local-tags-at))))))
316 (when type
317 (let ((entry (format
318 "@%s{%s,\n%s\n}\n" type id
319 (mapconcat
320 (lambda (pair) (format " %s={%s}" (car pair) (cdr pair)))
321 (remove nil
322 (if (and org-bibtex-export-arbitrary-fields
323 org-bibtex-prefix)
324 (mapcar
325 (lambda (kv)
326 (let ((key (car kv)) (val (cdr kv)))
327 (when (and (string-match org-bibtex-prefix key)
328 (not (string=
329 (downcase (concat org-bibtex-prefix "TYPE")) (downcase key))))
330 (cons (downcase (replace-regexp-in-string
331 org-bibtex-prefix "" key))
332 val))))
333 (org-entry-properties nil 'standard))
334 (mapcar
335 (lambda (field)
336 (let ((value (or (org-bibtex-get (from field))
337 (and (equal :title field)
338 (nth 4 (org-heading-components))))))
339 (when value (cons (from field) value))))
340 (flatten
341 (val :required (val (to type) org-bibtex-types))
342 (val :optional (val (to type) org-bibtex-types))))))
343 ",\n"))))
344 (with-temp-buffer
345 (insert entry)
346 (when tags
347 (bibtex-beginning-of-entry)
348 (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
349 (progn (goto-char (match-end 1)) (insert ", "))
350 (bibtex-make-field "keywords" t t))
351 (insert (mapconcat #'identity tags ", ")))
352 (bibtex-reformat) (buffer-string)))))))
353
354(defun org-bibtex-ask (field)
355 (unless (assoc field org-bibtex-fields)
356 (error "field:%s is not known" field))
357 (save-window-excursion
358 (let* ((name (substring (symbol-name field) 1))
359 (buf-name (format "*Bibtex Help %s*" name)))
360 (with-output-to-temp-buffer buf-name
361 (princ (cdr (assoc field org-bibtex-fields))))
362 (with-current-buffer buf-name (longlines-mode t))
363 (org-fit-window-to-buffer (get-buffer-window buf-name))
364 ((lambda (result) (when (> (length result) 0) result))
365 (read-from-minibuffer (format "%s: " name))))))
366
367(defun org-bibtex-autokey ()
368 "Generate an autokey for the current headline"
369 (org-bibtex-put org-bibtex-key-property
370 (if org-bibtex-autogen-keys
371 (let* ((entry (org-bibtex-headline))
372 (key
373 (with-temp-buffer
374 (insert entry)
375 (bibtex-generate-autokey))))
376 ;; test for duplicate IDs if using global ID
377 (when (and
378 (equal org-bibtex-key-property "ID")
379 (featurep 'org-id)
380 (hash-table-p org-id-locations)
381 (gethash key org-id-locations))
382 (warn "Another entry has the same ID"))
383 key)
384 (read-from-minibuffer "id: "))))
385
386(defun org-bibtex-fleshout (type &optional optional)
387 "Fleshout the current heading, ensuring that all required fields are present.
388With optional argument OPTIONAL, also prompt for optional fields."
389 (flet ((val (key lst) (cdr (assoc key lst)))
390 (keyword (name) (intern (concat ":" (downcase name))))
391 (name (keyword) (substring (symbol-name keyword) 1)))
392 (dolist (field (append
393 (if org-bibtex-treat-headline-as-title
394 (remove :title (val :required (val type org-bibtex-types)))
395 (val :required (val type org-bibtex-types)))
396 (when optional (val :optional (val type org-bibtex-types)))))
397 (when (consp field) ; or'd pair of fields e.g., (:editor :author)
398 (let ((present (first (remove nil
399 (mapcar
400 (lambda (f) (when (org-bibtex-get (name f)) f))
401 field)))))
402 (setf field (or present (keyword (org-icompleting-read
403 "Field: " (mapcar #'name field)))))))
404 (let ((name (name field)))
405 (unless (org-bibtex-get name)
406 (let ((prop (org-bibtex-ask field)))
407 (when prop (org-bibtex-put name prop)))))))
408 (when (and type (assoc type org-bibtex-types)
409 (not (org-bibtex-get org-bibtex-key-property)))
410 (org-bibtex-autokey)))
411
412\f
413;;; Bibtex link functions
20908596
CD
414(org-add-link-type "bibtex" 'org-bibtex-open)
415(add-hook 'org-store-link-functions 'org-bibtex-store-link)
416
20908596
CD
417(defun org-bibtex-open (path)
418 "Visit the bibliography entry on PATH."
419 (let* ((search (when (string-match "::\\(.+\\)\\'" path)
420 (match-string 1 path)))
421 (path (substring path 0 (match-beginning 0))))
422 (org-open-file path t nil search)))
423
424(defun org-bibtex-store-link ()
425 "Store a link to a BibTeX entry."
426 (when (eq major-mode 'bibtex-mode)
427 (let* ((search (org-create-file-search-in-bibtex))
428 (link (concat "file:" (abbreviate-file-name buffer-file-name)
429 "::" search))
430 (entry (mapcar ; repair strings enclosed in "..." or {...}
431 (lambda(c)
432 (if (string-match
433 "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c))
434 (cons (car c) (match-string 1 (cdr c))) c))
435 (save-excursion
436 (bibtex-beginning-of-entry)
437 (bibtex-parse-entry)))))
438 (org-store-link-props
439 :key (cdr (assoc "=key=" entry))
440 :author (or (cdr (assoc "author" entry)) "[no author]")
441 :editor (or (cdr (assoc "editor" entry)) "[no editor]")
442 :title (or (cdr (assoc "title" entry)) "[no title]")
443 :booktitle (or (cdr (assoc "booktitle" entry)) "[no booktitle]")
444 :journal (or (cdr (assoc "journal" entry)) "[no journal]")
445 :publisher (or (cdr (assoc "publisher" entry)) "[no publisher]")
446 :pages (or (cdr (assoc "pages" entry)) "[no pages]")
447 :url (or (cdr (assoc "url" entry)) "[no url]")
448 :year (or (cdr (assoc "year" entry)) "[no year]")
449 :month (or (cdr (assoc "month" entry)) "[no month]")
450 :address (or (cdr (assoc "address" entry)) "[no address]")
451 :volume (or (cdr (assoc "volume" entry)) "[no volume]")
452 :number (or (cdr (assoc "number" entry)) "[no number]")
453 :annote (or (cdr (assoc "annote" entry)) "[no annotation]")
454 :series (or (cdr (assoc "series" entry)) "[no series]")
455 :abstract (or (cdr (assoc "abstract" entry)) "[no abstract]")
456 :btype (or (cdr (assoc "=type=" entry)) "[no type]")
457 :type "bibtex"
458 :link link
459 :description description))))
460
461(defun org-create-file-search-in-bibtex ()
462 "Create the search string and description for a BibTeX database entry."
463 ;; Make a good description for this entry, using names, year and the title
464 ;; Put it into the `description' variable which is dynamically scoped.
465 (let ((bibtex-autokey-names 1)
466 (bibtex-autokey-names-stretch 1)
467 (bibtex-autokey-name-case-convert-function 'identity)
468 (bibtex-autokey-name-separator " & ")
469 (bibtex-autokey-additional-names " et al.")
470 (bibtex-autokey-year-length 4)
471 (bibtex-autokey-name-year-separator " ")
472 (bibtex-autokey-titlewords 3)
473 (bibtex-autokey-titleword-separator " ")
474 (bibtex-autokey-titleword-case-convert-function 'identity)
475 (bibtex-autokey-titleword-length 'infty)
476 (bibtex-autokey-year-title-separator ": "))
477 (setq description (bibtex-generate-autokey)))
478 ;; Now parse the entry, get the key and return it.
479 (save-excursion
480 (bibtex-beginning-of-entry)
481 (cdr (assoc "=key=" (bibtex-parse-entry)))))
482
483(defun org-execute-file-search-in-bibtex (s)
484 "Find the link search string S as a key for a database entry."
485 (when (eq major-mode 'bibtex-mode)
486 ;; Yes, we want to do the search in this file.
487 ;; We construct a regexp that searches for "@entrytype{" followed by the key
488 (goto-char (point-min))
489 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
490 (regexp-quote s) "[ \t\n]*,") nil t)
491 (goto-char (match-beginning 0)))
492 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
493 ;; Use double prefix to indicate that any web link should be browsed
494 (let ((b (current-buffer)) (p (point)))
495 ;; Restore the window configuration because we just use the web link
496 (set-window-configuration org-window-config-before-follow-link)
81ad75af 497 (with-current-buffer b
8bfe682a
CD
498 (goto-char p)
499 (bibtex-url)))
20908596 500 (recenter 0)) ; Move entry start to beginning of window
3ab2c837 501 ;; return t to indicate that the search is done.
20908596
CD
502 t))
503
504;; Finally add the link search function to the right hook.
505(add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
506
3ab2c837
BG
507\f
508;;; Bibtex <-> Org-mode headline translation functions
509(defun org-bibtex (&optional filename)
510 "Export each headline in the current file to a bibtex entry.
511Headlines are exported using `org-bibtex-export-headline'."
512 (interactive
513 (list (read-file-name
514 "Bibtex file: " nil nil nil
515 (file-name-nondirectory
516 (concat (file-name-sans-extension (buffer-file-name)) ".bib")))))
517 (let ((bibtex-entries (remove nil (org-map-entries #'org-bibtex-headline))))
518 (with-temp-file filename
519 (insert (mapconcat #'identity bibtex-entries "\n")))))
520
521(defun org-bibtex-check (&optional optional)
522 "Check the current headline for required fields.
523With prefix argument OPTIONAL also prompt for optional fields."
524 (interactive "P")
525 (save-restriction
526 (org-narrow-to-subtree)
527 (let ((type ((lambda (name) (when name (intern (concat ":" name))))
528 (org-bibtex-get "TYPE"))))
529 (when type (org-bibtex-fleshout type optional)))))
530
531(defun org-bibtex-check-all (&optional optional)
532 "Check all headlines in the current file.
533With prefix argument OPTIONAL also prompt for optional fields."
534 (interactive) (org-map-entries (lambda () (org-bibtex-check optional))))
535
536(defun org-bibtex-create (&optional arg nonew)
537 "Create a new entry at the given level.
538With a prefix arg, query for optional fields as well.
539If nonew is t, add data to the headline of the entry at point."
540 (interactive "P")
541 (let* ((type (org-icompleting-read
542 "Type: " (mapcar (lambda (type)
543 (substring (symbol-name (car type)) 1))
544 org-bibtex-types)
545 nil nil (when nonew (org-bibtex-get "TYPE"))))
546 (type (if (keywordp type) type (intern (concat ":" type))))
547 (org-bibtex-treat-headline-as-title (if nonew nil t)))
548 (unless (assoc type org-bibtex-types)
549 (error "type:%s is not known" type))
550 (if nonew
551 (org-back-to-heading)
552 (org-insert-heading)
553 (let ((title (org-bibtex-ask :title)))
554 (insert title)
555 (org-bibtex-put "TITLE" title)))
556 (org-bibtex-put "TYPE" (substring (symbol-name type) 1))
557 (org-bibtex-fleshout type arg)
558 (mapc (lambda (tag) (org-toggle-tag tag 'on)) org-bibtex-tags)))
559
560(defun org-bibtex-create-in-current-entry (&optional arg)
561 "Add bibliographical data to the current entry.
562With a prefix arg, query for optional fields."
563 (interactive "P")
564 (org-bibtex-create arg t))
565
566(defun org-bibtex-read ()
567 "Read a bibtex entry and save to `*org-bibtex-entries*'.
568This uses `bibtex-parse-entry'."
569 (interactive)
570 (flet ((keyword (str) (intern (concat ":" (downcase str))))
571 (clean-space (str) (replace-regexp-in-string
572 "[[:space:]\n\r]+" " " str))
573 (strip-delim (str) ; strip enclosing "..." and {...}
574 (dolist (pair '((34 . 34) (123 . 125) (123 . 125)))
575 (when (and (= (aref str 0) (car pair))
576 (= (aref str (1- (length str))) (cdr pair)))
577 (setf str (substring str 1 (1- (length str)))))) str))
578 (push (mapcar
579 (lambda (pair)
580 (cons (let ((field (keyword (car pair))))
581 (case field
582 (:=type= :type)
583 (:=key= :key)
584 (otherwise field)))
585 (clean-space (strip-delim (cdr pair)))))
586 (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
587 *org-bibtex-entries*)))
588
589(defun org-bibtex-write ()
590 "Insert a heading built from the first element of `*org-bibtex-entries*'."
591 (interactive)
592 (when (= (length *org-bibtex-entries*) 0)
593 (error "No entries in `*org-bibtex-entries*'."))
594 (let ((entry (pop *org-bibtex-entries*))
595 (org-special-properties nil)) ; avoids errors with `org-entry-put'
596 (flet ((val (field) (cdr (assoc field entry)))
597 (togtag (tag) (org-toggle-tag tag 'on)))
598 (org-insert-heading)
599 (insert (val :title))
600 (org-bibtex-put "TITLE" (val :title))
601 (org-bibtex-put "TYPE" (downcase (val :type)))
602 (dolist (pair entry)
603 (case (car pair)
604 (:title nil)
605 (:type nil)
606 (:key (org-bibtex-put org-bibtex-key-property (cdr pair)))
607 (:keywords (if org-bibtex-tags-are-keywords
608 (mapc
609 (lambda (kw)
610 (togtag
611 (replace-regexp-in-string
612 "[^[:alnum:]_@#%]" ""
613 (replace-regexp-in-string "[ \t]+" "_" kw))))
614 (split-string (cdr pair) ", *"))
615 (org-bibtex-put (car pair) (cdr pair))))
616 (otherwise (org-bibtex-put (car pair) (cdr pair)))))
617 (mapc #'togtag org-bibtex-tags))))
618
619(defun org-bibtex-yank ()
620 "If kill ring holds a bibtex entry yank it as an Org-mode headline."
621 (interactive)
622 (let (entry)
623 (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
624 (if entry
625 (org-bibtex-write)
626 (error "yanked text does not appear to contain a bibtex entry"))))
627
628(defun org-bibtex-export-to-kill-ring ()
629 "Export current headline to kill ring as bibtex entry."
630 (interactive)
631 (kill-new (org-bibtex-headline)))
632
633(defun org-bibtex-search (string)
634 "Search for bibliographical entries in agenda files.
635This function relies `org-search-view' to locate results."
636 (interactive "sSearch string: ")
637 (let ((org-agenda-overriding-header "Bib search results:")
638 (org-agenda-search-view-always-boolean t))
639 (org-search-view nil
640 (format "%s +{:%sTYPE:}"
641 string org-bibtex-prefix))))
642
20908596
CD
643(provide 'org-bibtex)
644
5b409b39 645
b349f79f 646
20908596 647;;; org-bibtex.el ends here