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