Merge changes made in Gnus trunk.
[bpt/emacs.git] / lisp / textmodes / reftex-cite.el
CommitLineData
3afbc435 1;;; reftex-cite.el --- creating citations with RefTeX
f2e3589a 2
73b0cd50 3;; Copyright (C) 1997-2011 Free Software Foundation, Inc.
3ba2590f 4
6fbeb429 5;; Author: Carsten Dominik <dominik@science.uva.nl>
ce545621 6;; Maintainer: auctex-devel@gnu.org
5d2a58e0 7;; Version: 4.31
bd78fa1d 8;; Package: reftex
3ba2590f
RS
9
10;; This file is part of GNU Emacs.
11
1fecc8fe 12;; GNU Emacs is free software: you can redistribute it and/or modify
3ba2590f 13;; it under the terms of the GNU General Public License as published by
1fecc8fe
GM
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
3ba2590f
RS
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
1fecc8fe 23;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
1a9461d0 24
3afbc435
PJ
25;;; Commentary:
26
27;;; Code:
28
7c4d13cc 29(eval-when-compile (require 'cl))
1a9461d0
CD
30(provide 'reftex-cite)
31(require 'reftex)
32;;;
33
34;; Variables and constants
35
36;; The history list of regular expressions used for citations
37(defvar reftex-cite-regexp-hist nil)
38
39;; Prompt and help string for citation selection
40(defconst reftex-citation-prompt
41 "Select: [n]ext [p]revious [r]estrict [ ]full_entry [q]uit RET [?]Help+more")
42
43(defconst reftex-citation-help
44 " n / p Go to next/previous entry (Cursor motion works as well).
45 g / r Start over with new regexp / Refine with additional regexp.
46 SPC Show full database entry in other window.
47 f Toggle follow mode: Other window will follow with full db entry.
48 . Show insertion point.
49 q Quit without inserting \\cite macro into buffer.
50 TAB Enter citation key with completion.
51 RET Accept current entry (also on mouse-2) and create \\cite macro.
52 m / u Mark/Unmark the entry.
f3c18bd0 53 e / E Create BibTeX file with all (marked/unmarked) entries
1a9461d0
CD
54 a / A Put all (marked) entries into one/many \\cite commands.")
55
56;; Find bibtex files
57
6fbeb429
CD
58(defmacro reftex-with-special-syntax-for-bib (&rest body)
59 `(let ((saved-syntax (syntax-table)))
60 (unwind-protect
3666daf6
CD
61 (progn
62 (set-syntax-table reftex-syntax-table-for-bib)
63 ,@body)
6fbeb429
CD
64 (set-syntax-table saved-syntax))))
65
1a9461d0
CD
66(defun reftex-default-bibliography ()
67 ;; Return the expanded value of `reftex-default-bibliography'.
68 ;; The expanded value is cached.
69 (unless (eq (get 'reftex-default-bibliography :reftex-raw)
3666daf6 70 reftex-default-bibliography)
1a9461d0 71 (put 'reftex-default-bibliography :reftex-expanded
7b07114a 72 (reftex-locate-bibliography-files
3666daf6 73 default-directory reftex-default-bibliography))
1a9461d0 74 (put 'reftex-default-bibliography :reftex-raw
3666daf6 75 reftex-default-bibliography))
1a9461d0
CD
76 (get 'reftex-default-bibliography :reftex-expanded))
77
20cd3579
CD
78(defun reftex-bib-or-thebib ()
79 ;; Tests if BibTeX or \begin{tehbibliography} should be used for the
80 ;; citation
81 ;; Find the bof of the current file
82 (let* ((docstruct (symbol-value reftex-docstruct-symbol))
3666daf6
CD
83 (rest (or (member (list 'bof (buffer-file-name)) docstruct)
84 docstruct))
85 (bib (assq 'bib rest))
86 (thebib (assq 'thebib rest))
87 (bibmem (memq bib rest))
88 (thebibmem (memq thebib rest)))
20cd3579
CD
89 (when (not (or thebib bib))
90 (setq bib (assq 'bib docstruct)
3666daf6
CD
91 thebib (assq 'thebib docstruct)
92 bibmem (memq bib docstruct)
93 thebibmem (memq thebib docstruct)))
20cd3579 94 (if (> (length bibmem) (length thebibmem))
3666daf6 95 (if bib 'bib nil)
20cd3579
CD
96 (if thebib 'thebib nil))))
97
1a9461d0
CD
98(defun reftex-get-bibfile-list ()
99 ;; Return list of bibfiles for current document.
100 ;; When using the chapterbib or bibunits package you should either
101 ;; use the same database files everywhere, or separate parts using
102 ;; different databases into different files (included into the mater file).
103 ;; Then this function will return the applicable database files.
104
105 ;; Ensure access to scanning info
106 (reftex-access-scan-info)
107 (or
108 ;; Try inside this file (and its includes)
109 (cdr (reftex-last-assoc-before-elt
110 'bib (list 'eof (buffer-file-name))
111 (member (list 'bof (buffer-file-name))
112 (symbol-value reftex-docstruct-symbol))))
113 ;; Try after the beginning of this file
114 (cdr (assq 'bib (member (list 'bof (buffer-file-name))
115 (symbol-value reftex-docstruct-symbol))))
116 ;; Anywhere in the entire document
117 (cdr (assq 'bib (symbol-value reftex-docstruct-symbol)))
118 (error "\\bibliography statement missing or .bib files not found")))
119
120;; Find a certain reference in any of the BibTeX files.
121
122(defun reftex-pop-to-bibtex-entry (key file-list &optional mark-to-kill
3666daf6 123 highlight item return)
1a9461d0
CD
124 ;; Find BibTeX KEY in any file in FILE-LIST in another window.
125 ;; If MARK-TO-KILL is non-nil, mark new buffer to kill.
126 ;; If HIGHLIGHT is non-nil, highlight the match.
127 ;; If ITEM in non-nil, search for bibitem instead of database entry.
759f7eed 128 ;; If RETURN is non-nil, just return the entry and restore point.
1a9461d0
CD
129
130 (let* ((re
7b07114a 131 (if item
3666daf6
CD
132 (concat "\\\\bibitem\\(\\[[^]]*\\]\\)?{" (regexp-quote key) "}")
133 (concat "@[a-zA-Z]+[ \t\n\r]*[{(][ \t\n\r]*" (regexp-quote key)
134 "[, \t\r\n}]")))
135 (buffer-conf (current-buffer))
759f7eed 136 file buf pos oldpos)
1a9461d0
CD
137
138 (catch 'exit
139 (while file-list
140 (setq file (car file-list)
141 file-list (cdr file-list))
142 (unless (setq buf (reftex-get-file-buffer-force file mark-to-kill))
143 (error "No such file %s" file))
144 (set-buffer buf)
759f7eed 145 (setq oldpos (point))
1a9461d0
CD
146 (widen)
147 (goto-char (point-min))
759f7eed
CD
148 (if (not (re-search-forward re nil t))
149 (goto-char oldpos) ;; restore previous position of point
1a9461d0 150 (goto-char (match-beginning 0))
3666daf6
CD
151 (setq pos (point))
152 (when return
153 ;; Just return the relevant entry
154 (if item (goto-char (match-end 0)))
7b07114a 155 (setq return (buffer-substring
3666daf6 156 (point) (reftex-end-of-bib-entry item)))
759f7eed 157 (goto-char oldpos) ;; restore point.
3666daf6
CD
158 (set-buffer buffer-conf)
159 (throw 'exit return))
160 (switch-to-buffer-other-window buf)
161 (goto-char pos)
1a9461d0
CD
162 (recenter 0)
163 (if highlight
164 (reftex-highlight 0 (match-beginning 0) (match-end 0)))
165 (throw 'exit (selected-window))))
166 (set-buffer buffer-conf)
167 (if item
3666daf6
CD
168 (error "No \\bibitem with citation key %s" key)
169 (error "No BibTeX entry with citation key %s" key)))))
1a9461d0
CD
170
171(defun reftex-end-of-bib-entry (item)
7b07114a 172 (save-excursion
1a9461d0 173 (condition-case nil
7b07114a 174 (if item
3666daf6
CD
175 (progn (end-of-line)
176 (re-search-forward
177 "\\\\bibitem\\|\\end{thebibliography}")
178 (1- (match-beginning 0)))
179 (progn (forward-list 1) (point)))
1a9461d0
CD
180 (error (min (point-max) (+ 300 (point)))))))
181
182;; Parse bibtex buffers
183
3666daf6 184(defun reftex-extract-bib-entries (buffers)
1a9461d0
CD
185 ;; Extract bib entries which match regexps from BUFFERS.
186 ;; BUFFERS is a list of buffers or file names.
187 ;; Return list with entries."
3666daf6
CD
188 (let* (re-list first-re rest-re
189 (buffer-list (if (listp buffers) buffers (list buffers)))
190 found-list entry buffer1 buffer alist
191 key-point start-point end-point default)
192
193 ;; Read a regexp, completing on known citation keys.
194 (setq default (regexp-quote (reftex-get-bibkey-default)))
7b07114a
CD
195 (setq re-list
196 (split-string
197 (completing-read
3666daf6
CD
198 (concat
199 "Regex { && Regex...}: "
200 "[" default "]: ")
201 (if reftex-mode
202 (if (fboundp 'LaTeX-bibitem-list)
203 (LaTeX-bibitem-list)
7b07114a 204 (cdr (assoc 'bibview-cache
3666daf6
CD
205 (symbol-value reftex-docstruct-symbol))))
206 nil)
207 nil nil nil 'reftex-cite-regexp-hist)
208 "[ \t]*&&[ \t]*"))
209
210 (if (or (null re-list ) (equal re-list '("")))
211 (setq re-list (list default)))
212
213 (setq first-re (car re-list) ; We'll use the first re to find things,
214 rest-re (cdr re-list)) ; the others to narrow down.
215 (if (string-match "\\`[ \t]*\\'" (or first-re ""))
216 (error "Empty regular expression"))
1a9461d0
CD
217
218 (save-excursion
219 (save-window-excursion
220
221 ;; Walk through all bibtex files
222 (while buffer-list
223 (setq buffer (car buffer-list)
224 buffer-list (cdr buffer-list))
225 (if (and (bufferp buffer)
226 (buffer-live-p buffer))
227 (setq buffer1 buffer)
228 (setq buffer1 (reftex-get-file-buffer-force
229 buffer (not reftex-keep-temporary-buffers))))
230 (if (not buffer1)
231 (message "No such BibTeX file %s (ignored)" buffer)
232 (message "Scanning bibliography database %s" buffer1))
233
234 (set-buffer buffer1)
3666daf6
CD
235 (reftex-with-special-syntax-for-bib
236 (save-excursion
237 (goto-char (point-min))
238 (while (re-search-forward first-re nil t)
239 (catch 'search-again
240 (setq key-point (point))
241 (unless (re-search-backward
242 "\\(\\`\\|[\n\r]\\)[ \t]*@\\([a-zA-Z]+\\)[ \t\n\r]*[{(]" nil t)
243 (throw 'search-again nil))
244 (setq start-point (point))
245 (goto-char (match-end 0))
246 (condition-case nil
247 (up-list 1)
248 (error (goto-char key-point)
1a9461d0 249 (throw 'search-again nil)))
3666daf6 250 (setq end-point (point))
7b07114a 251
3666daf6
CD
252 ;; Ignore @string, @comment and @c entries or things
253 ;; outside entries
254 (when (or (string= (downcase (match-string 2)) "string")
255 (string= (downcase (match-string 2)) "comment")
256 (string= (downcase (match-string 2)) "c")
257 (< (point) key-point)) ; this means match not in {}
258 (goto-char key-point)
259 (throw 'search-again nil))
7b07114a 260
3666daf6
CD
261 ;; Well, we have got a match
262 ;;(setq entry (concat
263 ;; (buffer-substring start-point (point)) "\n"))
264 (setq entry (buffer-substring start-point (point)))
7b07114a 265
3666daf6
CD
266 ;; Check if other regexp match as well
267 (setq re-list rest-re)
268 (while re-list
269 (unless (string-match (car re-list) entry)
270 ;; nope - move on
271 (throw 'search-again nil))
272 (pop re-list))
7b07114a 273
3666daf6
CD
274 (setq alist (reftex-parse-bibtex-entry
275 nil start-point end-point))
276 (push (cons "&entry" entry) alist)
7b07114a 277
3666daf6
CD
278 ;; check for crossref entries
279 (if (assoc "crossref" alist)
280 (setq alist
281 (append
282 alist (reftex-get-crossref-alist alist))))
7b07114a 283
3666daf6
CD
284 ;; format the entry
285 (push (cons "&formatted" (reftex-format-bib-entry alist))
286 alist)
7b07114a 287
3666daf6
CD
288 ;; make key the first element
289 (push (reftex-get-bib-field "&key" alist) alist)
7b07114a 290
3666daf6
CD
291 ;; add it to the list
292 (push alist found-list)))))
293 (reftex-kill-temporary-buffers))))
1a9461d0
CD
294 (setq found-list (nreverse found-list))
295
296 ;; Sorting
297 (cond
298 ((eq 'author reftex-sort-bibtex-matches)
299 (sort found-list 'reftex-bib-sort-author))
300 ((eq 'year reftex-sort-bibtex-matches)
301 (sort found-list 'reftex-bib-sort-year))
302 ((eq 'reverse-year reftex-sort-bibtex-matches)
303 (sort found-list 'reftex-bib-sort-year-reverse))
304 (t found-list))))
305
306(defun reftex-bib-sort-author (e1 e2)
307 (let ((al1 (reftex-get-bib-names "author" e1))
308 (al2 (reftex-get-bib-names "author" e2)))
309 (while (and al1 al2 (string= (car al1) (car al2)))
310 (pop al1)
311 (pop al2))
312 (if (and (stringp (car al1))
313 (stringp (car al2)))
314 (string< (car al1) (car al2))
315 (not (stringp (car al1))))))
316
317(defun reftex-bib-sort-year (e1 e2)
027a4b6b
JB
318 (< (string-to-number (or (cdr (assoc "year" e1)) "0"))
319 (string-to-number (or (cdr (assoc "year" e2)) "0"))))
1a9461d0
CD
320
321(defun reftex-bib-sort-year-reverse (e1 e2)
027a4b6b
JB
322 (> (string-to-number (or (cdr (assoc "year" e1)) "0"))
323 (string-to-number (or (cdr (assoc "year" e2)) "0"))))
1a9461d0
CD
324
325(defun reftex-get-crossref-alist (entry)
326 ;; return the alist from a crossref entry
327 (let ((crkey (cdr (assoc "crossref" entry)))
328 start)
329 (save-excursion
330 (save-restriction
331 (widen)
332 (if (re-search-forward
333 (concat "@\\w+[{(][ \t\n\r]*" (regexp-quote crkey)
334 "[ \t\n\r]*,") nil t)
335 (progn
336 (setq start (match-beginning 0))
337 (condition-case nil
338 (up-list 1)
339 (error nil))
340 (reftex-parse-bibtex-entry nil start (point)))
341 nil)))))
342
aa87aafc 343;; Parse the bibliography environment
3666daf6 344(defun reftex-extract-bib-entries-from-thebibliography (files)
1a9461d0
CD
345 ;; Extract bib-entries from the \begin{thebibliography} environment.
346 ;; Parsing is not as good as for the BibTeX database stuff.
347 ;; The environment should be located in file FILE.
348
3666daf6 349 (let* (start end buf entries re re-list file default)
09308e63 350 (unless files
1a9461d0 351 (error "Need file name to find thebibliography environment"))
09308e63 352 (while (setq file (pop files))
7b07114a 353 (setq buf (reftex-get-file-buffer-force
3666daf6 354 file (not reftex-keep-temporary-buffers)))
09308e63 355 (unless buf
3666daf6 356 (error "No such file %s" file))
09308e63 357 (message "Scanning thebibliography environment in %s" file)
1a9461d0 358
9a529312 359 (with-current-buffer buf
99f65cfa
RA
360 (save-excursion
361 (save-restriction
362 (widen)
363 (goto-char (point-min))
364 (while (re-search-forward
365 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
366 (beginning-of-line 2)
367 (setq start (point))
368 (if (re-search-forward
369 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\end{thebibliography}" nil t)
370 (progn
371 (beginning-of-line 1)
372 (setq end (point))))
373 (when (and start end)
374 (setq entries
375 (append entries
376 (mapcar 'reftex-parse-bibitem
377 (delete ""
378 (split-string
379 (buffer-substring-no-properties
380 start end)
5d8f9169 381 "[ \t\n\r]*\\\\bibitem[ \t]*\
99f65cfa
RA
382\\(\\[[^]]*]\\)*\[ \t]*"))))))
383 (goto-char end))))))
1a9461d0
CD
384 (unless entries
385 (error "No bibitems found"))
386
3666daf6
CD
387 ;; Read a regexp, completing on known citation keys.
388 (setq default (regexp-quote (reftex-get-bibkey-default)))
7b07114a
CD
389 (setq re-list
390 (split-string
391 (completing-read
3666daf6
CD
392 (concat
393 "Regex { && Regex...}: "
394 "[" default "]: ")
395 (if reftex-mode
396 (if (fboundp 'LaTeX-bibitem-list)
397 (LaTeX-bibitem-list)
7b07114a 398 (cdr (assoc 'bibview-cache
3666daf6
CD
399 (symbol-value reftex-docstruct-symbol))))
400 nil)
401 nil nil nil 'reftex-cite-regexp-hist)
402 "[ \t]*&&[ \t]*"))
403
404 (if (or (null re-list ) (equal re-list '("")))
405 (setq re-list (list default)))
406
407 (if (string-match "\\`[ \t]*\\'" (car re-list))
408 (error "Empty regular expression"))
409
1a9461d0 410 (while (and (setq re (pop re-list)) entries)
7b07114a 411 (setq entries
3666daf6
CD
412 (delq nil (mapcar
413 (lambda (x)
414 (if (string-match re (cdr (assoc "&entry" x)))
415 x nil))
416 entries))))
7b07114a
CD
417 (setq entries
418 (mapcar
3666daf6
CD
419 (lambda (x)
420 (push (cons "&formatted" (reftex-format-bibitem x)) x)
421 (push (reftex-get-bib-field "&key" x) x)
422 x)
423 entries))
1a9461d0
CD
424
425 entries))
426
7ac7387b
CD
427(defun reftex-get-bibkey-default ()
428 ;; Return the word before the cursor. If the cursor is in a
429 ;; citation macro, return the word before the macro.
430 (let* ((macro (reftex-what-macro 1)))
431 (save-excursion
432 (if (and macro (string-match "cite" (car macro)))
3666daf6 433 (goto-char (cdr macro)))
7ac7387b
CD
434 (skip-chars-backward "^a-zA-Z0-9")
435 (reftex-this-word))))
436
1a9461d0
CD
437;; Parse and format individual entries
438
439(defun reftex-get-bib-names (field entry)
440 ;; Return a list with the author or editor names in ENTRY
441 (let ((names (reftex-get-bib-field field entry)))
442 (if (equal "" names)
443 (setq names (reftex-get-bib-field "editor" entry)))
444 (while (string-match "\\band\\b[ \t]*" names)
445 (setq names (replace-match "\n" nil t names)))
446 (while (string-match "[\\.a-zA-Z\\-]+\\.[ \t]*\\|,.*\\|[{}]+" names)
447 (setq names (replace-match "" nil t names)))
448 (while (string-match "^[ \t]+\\|[ \t]+$" names)
449 (setq names (replace-match "" nil t names)))
450 (while (string-match "[ \t][ \t]+" names)
451 (setq names (replace-match " " nil t names)))
452 (split-string names "\n")))
453
454(defun reftex-parse-bibtex-entry (entry &optional from to)
455 (let (alist key start field)
456 (save-excursion
457 (save-restriction
458 (if entry
459 (progn
460 (set-buffer (get-buffer-create " *RefTeX-scratch*"))
461 (fundamental-mode)
3666daf6 462 (set-syntax-table reftex-syntax-table-for-bib)
1a9461d0
CD
463 (erase-buffer)
464 (insert entry))
465 (widen)
466 (narrow-to-region from to))
467 (goto-char (point-min))
468
469 (if (re-search-forward
470 "@\\(\\w+\\)[ \t\n\r]*[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
471 (setq alist
472 (list
473 (cons "&type" (downcase (reftex-match-string 1)))
474 (cons "&key" (reftex-match-string 2)))))
475 (while (re-search-forward "\\(\\w+\\)[ \t\n\r]*=[ \t\n\r]*" nil t)
476 (setq key (downcase (reftex-match-string 1)))
477 (cond
478 ((= (following-char) ?{)
479 (forward-char 1)
480 (setq start (point))
481 (condition-case nil
482 (up-list 1)
483 (error nil)))
484 ((= (following-char) ?\")
485 (forward-char 1)
486 (setq start (point))
487 (while (and (search-forward "\"" nil t)
488 (= ?\\ (char-after (- (point) 2))))))
489 (t
490 (setq start (point))
491 (re-search-forward "[ \t]*[\n\r,}]" nil 1)))
492 (setq field (buffer-substring-no-properties start (1- (point))))
493 ;; remove extra whitespace
494 (while (string-match "[\n\t\r]\\|[ \t][ \t]+" field)
495 (setq field (replace-match " " nil t field)))
496 ;; remove leading garbage
497 (if (string-match "^[ \t{]+" field)
498 (setq field (replace-match "" nil t field)))
499 ;; remove trailing garbage
500 (if (string-match "[ \t}]+$" field)
501 (setq field (replace-match "" nil t field)))
502 (push (cons key field) alist))))
503 alist))
504
505(defun reftex-get-bib-field (fieldname entry &optional format)
506 ;; Extract the field FIELDNAME from an ENTRY
507 (let ((cell (assoc fieldname entry)))
508 (if cell
3666daf6
CD
509 (if format
510 (format format (cdr cell))
511 (cdr cell))
1a9461d0
CD
512 "")))
513
514(defun reftex-format-bib-entry (entry)
515 ;; Format a BibTeX ENTRY so that it is nice to look at
516 (let*
517 ((auth-list (reftex-get-bib-names "author" entry))
518 (authors (mapconcat 'identity auth-list ", "))
519 (year (reftex-get-bib-field "year" entry))
520 (title (reftex-get-bib-field "title" entry))
521 (type (reftex-get-bib-field "&type" entry))
522 (key (reftex-get-bib-field "&key" entry))
523 (extra
524 (cond
525 ((equal type "article")
526 (concat (reftex-get-bib-field "journal" entry) " "
527 (reftex-get-bib-field "volume" entry) ", "
528 (reftex-get-bib-field "pages" entry)))
529 ((equal type "book")
530 (concat "book (" (reftex-get-bib-field "publisher" entry) ")"))
531 ((equal type "phdthesis")
532 (concat "PhD: " (reftex-get-bib-field "school" entry)))
533 ((equal type "mastersthesis")
534 (concat "Master: " (reftex-get-bib-field "school" entry)))
535 ((equal type "inbook")
536 (concat "Chap: " (reftex-get-bib-field "chapter" entry)
537 ", pp. " (reftex-get-bib-field "pages" entry)))
538 ((or (equal type "conference")
539 (equal type "incollection")
540 (equal type "inproceedings"))
541 (reftex-get-bib-field "booktitle" entry "in: %s"))
542 (t ""))))
543 (setq authors (reftex-truncate authors 30 t t))
544 (when (reftex-use-fonts)
545 (put-text-property 0 (length key) 'face
3666daf6
CD
546 (reftex-verified-face reftex-label-face
547 'font-lock-constant-face
548 'font-lock-reference-face)
1a9461d0
CD
549 key)
550 (put-text-property 0 (length authors) 'face reftex-bib-author-face
551 authors)
552 (put-text-property 0 (length year) 'face reftex-bib-year-face
553 year)
554 (put-text-property 0 (length title) 'face reftex-bib-title-face
555 title)
556 (put-text-property 0 (length extra) 'face reftex-bib-extra-face
557 extra))
558 (concat key "\n " authors " " year " " extra "\n " title "\n\n")))
559
560(defun reftex-parse-bibitem (item)
561 ;; Parse a \bibitem entry
562 (let ((key "") (text ""))
70d797cd 563 (when (string-match "\\`{\\([^}]+\\)}\\([^\000]*\\)" item)
1a9461d0 564 (setq key (match-string 1 item)
3666daf6 565 text (match-string 2 item)))
1a9461d0
CD
566 ;; Clean up the text a little bit
567 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
568 (setq text (replace-match " " nil t text)))
569 (if (string-match "\\`[ \t]+" text)
3666daf6 570 (setq text (replace-match "" nil t text)))
1a9461d0
CD
571 (list
572 (cons "&key" key)
573 (cons "&text" text)
574 (cons "&entry" (concat key " " text)))))
575
576(defun reftex-format-bibitem (item)
577 ;; Format a \bibitem entry so that it is (relatively) nice to look at.
578 (let ((text (reftex-get-bib-field "&text" item))
3666daf6
CD
579 (key (reftex-get-bib-field "&key" item))
580 (lines nil))
1a9461d0
CD
581
582 ;; Wrap the text into several lines.
583 (while (and (> (length text) 70)
3666daf6
CD
584 (string-match " " (substring text 60)))
585 (push (substring text 0 (+ 60 (match-beginning 0))) lines)
586 (setq text (substring text (+ 61 (match-beginning 0)))))
1a9461d0
CD
587 (push text lines)
588 (setq text (mapconcat 'identity (nreverse lines) "\n "))
589
590 (when (reftex-use-fonts)
591 (put-text-property 0 (length text) 'face reftex-bib-author-face text))
592 (concat key "\n " text "\n\n")))
593
594;; Make a citation
595
596;;;###autoload
7c4d13cc 597(defun reftex-citation (&optional no-insert format-key)
1a9461d0
CD
598 "Make a citation using BibTeX database files.
599After prompting for a regular expression, scans the buffers with
600bibtex entries (taken from the \\bibliography command) and offers the
9e3e72cb 601matching entries for selection. The selected entry is formatted according
1a9461d0
CD
602to `reftex-cite-format' and inserted into the buffer.
603
604If NO-INSERT is non-nil, nothing is inserted, only the selected key returned.
605
42187e99 606FORMAT-KEY can be used to pre-select a citation format.
7c4d13cc 607
f3c18bd0
CD
608When called with a `C-u' prefix, prompt for optional arguments in
609cite macros. When called with a numeric prefix, make that many
610citations. When called with point inside the braces of a `\\cite'
611command, it will add another key, ignoring the value of
612`reftex-cite-format'.
1a9461d0
CD
613
614The regular expression uses an expanded syntax: && is interpreted as `and'.
615Thus, `aaaa&&bbb' matches entries which contain both `aaaa' and `bbb'.
616While entering the regexp, completion on knows citation keys is possible.
617`=' is a good regular expression to match all entries in all files."
618
619 (interactive)
620
621 ;; check for recursive edit
622 (reftex-check-recursive-edit)
623
624 ;; This function may also be called outside reftex-mode.
625 ;; Thus look for the scanning info only if in reftex-mode.
626
627 (when reftex-mode
f3c18bd0 628 (reftex-access-scan-info nil))
1a9461d0
CD
629
630 ;; Call reftex-do-citation, but protected
631 (unwind-protect
7c4d13cc 632 (reftex-do-citation current-prefix-arg no-insert format-key)
1a9461d0
CD
633 (reftex-kill-temporary-buffers)))
634
7c4d13cc 635(defun reftex-do-citation (&optional arg no-insert format-key)
1a9461d0
CD
636 ;; This really does the work of reftex-citation.
637
7c4d13cc 638 (let* ((format (reftex-figure-out-cite-format arg no-insert format-key))
3666daf6
CD
639 (docstruct-symbol reftex-docstruct-symbol)
640 (selected-entries (reftex-offer-bib-menu))
641 (insert-entries selected-entries)
642 entry string cite-view)
1a9461d0 643
f3c18bd0
CD
644 (when (stringp selected-entries)
645 (error selected-entries))
1a9461d0
CD
646 (unless selected-entries (error "Quit"))
647
648 (if (stringp selected-entries)
3666daf6
CD
649 ;; Nonexistent entry
650 (setq selected-entries nil
651 insert-entries (list (list selected-entries
652 (cons "&key" selected-entries))))
1a9461d0
CD
653 ;; It makes sense to compute the cite-view strings.
654 (setq cite-view t))
655
656 (when (eq (car selected-entries) 'concat)
657 ;; All keys go into a single command - we need to trick a little
f3c18bd0 658 ;; FIXME: Unfortunately, this meens that commenting does not work right.
1a9461d0
CD
659 (pop selected-entries)
660 (let ((concat-keys (mapconcat 'car selected-entries ",")))
7b07114a 661 (setq insert-entries
3666daf6 662 (list (list concat-keys (cons "&key" concat-keys))))))
7b07114a 663
1a9461d0
CD
664 (unless no-insert
665
666 ;; We shall insert this into the buffer...
667 (message "Formatting...")
42187e99 668
1a9461d0 669 (while (setq entry (pop insert-entries))
3666daf6
CD
670 ;; Format the citation and insert it
671 (setq string (if reftex-format-cite-function
672 (funcall reftex-format-cite-function
673 (reftex-get-bib-field "&key" entry)
674 format)
675 (reftex-format-citation entry format)))
f3c18bd0
CD
676 (when (or (eq reftex-cite-prompt-optional-args t)
677 (and reftex-cite-prompt-optional-args
678 (equal arg '(4))))
679 (let ((start 0) (nth 0) value)
680 (while (setq start (string-match "\\[\\]" string start))
681 (setq value (read-string (format "Optional argument %d: "
682 (setq nth (1+ nth)))))
683 (setq string (replace-match (concat "[" value "]") t t string))
684 (setq start (1+ start)))))
685 ;; Should we cleanup empty optional arguments?
686 ;; if the first is empty, it can be removed. If the second is empty,
3ee26b0c 687 ;; it has to go. If there is only a single arg and empty, it can go
3a1e8128 688 ;; as well.
f3c18bd0 689 (when reftex-cite-cleanup-optional-args
d63eb0e7 690 (cond
3ee26b0c
CD
691 ((string-match "\\([a-zA-Z0-9]\\)\\[\\]{" string)
692 (setq string (replace-match "\\1{" nil nil string)))
f3c18bd0
CD
693 ((string-match "\\[\\]\\(\\[[a-zA-Z0-9., ]+\\]\\)" string)
694 (setq string (replace-match "\\1" nil nil string)))
695 ((string-match "\\[\\]\\[\\]" string)
696 (setq string (replace-match "" t t string)))))
3666daf6 697 (insert string))
1a9461d0
CD
698
699 ;; Reposition cursor?
700 (when (string-match "\\?" string)
3666daf6
CD
701 (search-backward "?")
702 (delete-char 1))
1a9461d0
CD
703
704 ;; Tell AUCTeX
551e625f 705 (when (and reftex-mode
3666daf6
CD
706 (fboundp 'LaTeX-add-bibitems)
707 reftex-plug-into-AUCTeX)
708 (apply 'LaTeX-add-bibitems (mapcar 'car selected-entries)))
551e625f 709
1a9461d0
CD
710 ;; Produce the cite-view strings
711 (when (and reftex-mode reftex-cache-cite-echo cite-view)
551e625f
GM
712 (mapc (lambda (entry)
713 (reftex-make-cite-echo-string entry docstruct-symbol))
714 selected-entries))
1a9461d0
CD
715
716 (message ""))
717
718 (set-marker reftex-select-return-marker nil)
719 (reftex-kill-buffer "*RefTeX Select*")
551e625f 720
1a9461d0
CD
721 ;; Check if the prefix arg was numeric, and call recursively
722 (when (integerp arg)
723 (if (> arg 1)
551e625f 724 (progn
3666daf6
CD
725 (skip-chars-backward "}")
726 (decf arg)
727 (reftex-do-citation arg))
728 (forward-char 1)))
d63eb0e7 729
1a9461d0
CD
730 ;; Return the citation key
731 (car (car selected-entries))))
732
7c4d13cc 733(defun reftex-figure-out-cite-format (arg &optional no-insert format-key)
1a9461d0
CD
734 ;; Check if there is already a cite command at point and change cite format
735 ;; in order to only add another reference in the same cite command.
736 (let ((macro (car (reftex-what-macro 1)))
3666daf6
CD
737 (cite-format-value (reftex-get-cite-format))
738 key format)
1a9461d0
CD
739 (cond
740 (no-insert
741 ;; Format does not really matter because nothing will be inserted.
742 (setq format "%l"))
d63eb0e7 743
1a9461d0 744 ((and (stringp macro)
3666daf6 745 (string-match "\\`\\\\cite\\|cite\\'" macro))
1a9461d0
CD
746 ;; We are already inside a cite macro
747 (if (or (not arg) (not (listp arg)))
3666daf6
CD
748 (setq format
749 (concat
750 (if (member (preceding-char) '(?\{ ?,)) "" ",")
751 "%l"
752 (if (member (following-char) '(?\} ?,)) "" ",")))
753 (setq format "%l")))
1a9461d0
CD
754 (t
755 ;; Figure out the correct format
756 (setq format
757 (if (and (symbolp cite-format-value)
3666daf6
CD
758 (assq cite-format-value reftex-cite-format-builtin))
759 (nth 2 (assq cite-format-value reftex-cite-format-builtin))
760 cite-format-value))
1a9461d0 761 (when (listp format)
3666daf6
CD
762 (setq key
763 (or format-key
d63eb0e7 764 (reftex-select-with-char
3666daf6
CD
765 "" (concat "SELECT A CITATION FORMAT\n\n"
766 (mapconcat
767 (lambda (x)
768 (format "[%c] %s %s" (car x)
769 (if (> (car x) 31) " " "")
770 (cdr x)))
771 format "\n")))))
772 (if (assq key format)
773 (setq format (cdr (assq key format)))
774 (error "No citation format associated with key `%c'" key)))))
1a9461d0
CD
775 format))
776
7c4d13cc
CD
777(defun reftex-citep ()
778 "Call `reftex-citation' with a format selector `?p'."
779 (interactive)
780 (reftex-citation nil ?p))
781
782(defun reftex-citet ()
783 "Call `reftex-citation' with a format selector `?t'."
784 (interactive)
785 (reftex-citation nil ?t))
786
1a9461d0
CD
787(defvar reftex-select-bib-map)
788(defun reftex-offer-bib-menu ()
789 ;; Offer bib menu and return list of selected items
790
20cd3579 791 (let ((bibtype (reftex-bib-or-thebib))
3666daf6 792 found-list rtn key data selected-entries)
d63eb0e7
GM
793 (while
794 (not
3666daf6
CD
795 (catch 'done
796 ;; Scan bibtex files
797 (setq found-list
798 (cond
799 ((eq bibtype 'bib)
800; ((assq 'bib (symbol-value reftex-docstruct-symbol))
801 ;; using BibTeX database files.
802 (reftex-extract-bib-entries (reftex-get-bibfile-list)))
803 ((eq bibtype 'thebib)
804; ((assq 'thebib (symbol-value reftex-docstruct-symbol))
805 ;; using thebibliography environment.
806 (reftex-extract-bib-entries-from-thebibliography
807 (reftex-uniquify
808 (mapcar 'cdr
d63eb0e7 809 (reftex-all-assq
3666daf6
CD
810 'thebib (symbol-value reftex-docstruct-symbol))))))
811 (reftex-default-bibliography
812 (message "Using default bibliography")
813 (reftex-extract-bib-entries (reftex-default-bibliography)))
814 (t (error "No valid bibliography in this document, and no default available"))))
d63eb0e7 815
3666daf6
CD
816 (unless found-list
817 (error "Sorry, no matches found"))
d63eb0e7 818
3666daf6
CD
819 ;; Remember where we came from
820 (setq reftex-call-back-to-this-buffer (current-buffer))
821 (set-marker reftex-select-return-marker (point))
d63eb0e7 822
3666daf6
CD
823 ;; Offer selection
824 (save-window-excursion
825 (delete-other-windows)
d63eb0e7
GM
826 (reftex-kill-buffer "*RefTeX Select*")
827 (switch-to-buffer-other-window "*RefTeX Select*")
828 (unless (eq major-mode 'reftex-select-bib-mode)
829 (reftex-select-bib-mode))
830 (let ((buffer-read-only nil))
831 (erase-buffer)
832 (reftex-insert-bib-matches found-list))
3666daf6
CD
833 (setq buffer-read-only t)
834 (if (= 0 (buffer-size))
835 (error "No matches found"))
836 (setq truncate-lines t)
837 (goto-char 1)
838 (while t
839 (setq rtn
840 (reftex-select-item
841 reftex-citation-prompt
842 reftex-citation-help
843 reftex-select-bib-map
844 nil
845 'reftex-bibtex-selection-callback nil))
846 (setq key (car rtn)
847 data (nth 1 rtn))
848 (unless key (throw 'done t))
849 (cond
850 ((eq key ?g)
851 ;; Start over
852 (throw 'done nil))
853 ((eq key ?r)
854 ;; Restrict with new regular expression
855 (setq found-list (reftex-restrict-bib-matches found-list))
856 (let ((buffer-read-only nil))
857 (erase-buffer)
858 (reftex-insert-bib-matches found-list))
859 (goto-char 1))
860 ((eq key ?A)
861 ;; Take all (marked)
d63eb0e7 862 (setq selected-entries
3666daf6
CD
863 (if reftex-select-marked
864 (mapcar 'car (nreverse reftex-select-marked))
865 found-list))
866 (throw 'done t))
867 ((eq key ?a)
868 ;; Take all (marked), and push the symbol 'concat
d63eb0e7
GM
869 (setq selected-entries
870 (cons 'concat
3666daf6
CD
871 (if reftex-select-marked
872 (mapcar 'car (nreverse reftex-select-marked))
873 found-list)))
874 (throw 'done t))
f3c18bd0
CD
875 ((eq key ?e)
876 ;; Take all (marked), and push the symbol 'concat
877 (reftex-extract-bib-file found-list reftex-select-marked)
878 (setq selected-entries "BibTeX database file created")
879 (throw 'done t))
880 ((eq key ?E)
881 ;; Take all (marked), and push the symbol 'concat
882 (reftex-extract-bib-file found-list reftex-select-marked
883 'complement)
884 (setq selected-entries "BibTeX database file created")
885 (throw 'done t))
3666daf6
CD
886 ((or (eq key ?\C-m)
887 (eq key 'return))
888 ;; Take selected
d63eb0e7 889 (setq selected-entries
3666daf6 890 (if reftex-select-marked
d63eb0e7 891 (cons 'concat
3666daf6
CD
892 (mapcar 'car (nreverse reftex-select-marked)))
893 (if data (list data) nil)))
894 (throw 'done t))
895 ((stringp key)
896 ;; Got this one with completion
897 (setq selected-entries key)
898 (throw 'done t))
899 (t
900 (ding))))))))
1a9461d0
CD
901 selected-entries))
902
903(defun reftex-restrict-bib-matches (found-list)
904 ;; Limit FOUND-LIST with more regular expressions
905 (let ((re-list (split-string (read-string
3666daf6
CD
906 "RegExp [ && RegExp...]: "
907 nil 'reftex-cite-regexp-hist)
908 "[ \t]*&&[ \t]*"))
909 (found-list-r found-list)
910 re)
1a9461d0
CD
911 (while (setq re (pop re-list))
912 (setq found-list-r
3666daf6
CD
913 (delq nil
914 (mapcar
915 (lambda (x)
916 (if (string-match
917 re (cdr (assoc "&entry" x)))
918 x
919 nil))
920 found-list-r))))
1a9461d0 921 (if found-list-r
3666daf6 922 found-list-r
1a9461d0
CD
923 (ding)
924 found-list)))
925
f3c18bd0
CD
926(defun reftex-extract-bib-file (all &optional marked complement)
927 ;; Limit FOUND-LIST with more regular expressions
928 (let ((file (read-file-name "File to create: ")))
929 (find-file-other-window file)
930 (if (> (buffer-size) 0)
d63eb0e7 931 (unless (yes-or-no-p
f3c18bd0
CD
932 (format "Overwrite non-empty file %s? " file))
933 (error "Abort")))
934 (erase-buffer)
935 (setq all (delq nil
936 (mapcar
937 (lambda (x)
938 (if marked
939 (if (or (and (assoc x marked) (not complement))
940 (and (not (assoc x marked)) complement))
941 (cdr (assoc "&entry" x))
942 nil)
943 (cdr (assoc "&entry" x))))
944 all)))
945 (insert (mapconcat 'identity all "\n\n"))
946 (save-buffer)
947 (goto-char (point-min))))
948
1a9461d0
CD
949(defun reftex-insert-bib-matches (list)
950 ;; Insert the bib matches and number them correctly
951 (let ((mouse-face
3666daf6
CD
952 (if (memq reftex-highlight-selection '(mouse both))
953 reftex-mouse-selected-face
954 nil))
955 tmp len)
551e625f 956 (mapc
1a9461d0
CD
957 (lambda (x)
958 (setq tmp (cdr (assoc "&formatted" x))
3666daf6 959 len (length tmp))
1a9461d0
CD
960 (put-text-property 0 len :data x tmp)
961 (put-text-property 0 (1- len) 'mouse-face mouse-face tmp)
962 (insert tmp))
963 list))
964 (run-hooks 'reftex-display-copied-context-hook))
965
966(defun reftex-format-names (namelist n)
967 (let (last (len (length namelist)))
6fbeb429 968 (if (= n 0) (setq n len))
1a9461d0
CD
969 (cond
970 ((< len 1) "")
971 ((= 1 len) (car namelist))
972 ((> len n) (concat (car namelist) (nth 2 reftex-cite-punctuation)))
973 (t
974 (setq n (min len n)
975 last (nth (1- n) namelist))
976 (setcdr (nthcdr (- n 2) namelist) nil)
977 (concat
978 (mapconcat 'identity namelist (nth 0 reftex-cite-punctuation))
979 (nth 1 reftex-cite-punctuation)
980 last)))))
981
982(defun reftex-format-citation (entry format)
983 ;; Format a citation from the info in the BibTeX ENTRY
984
985 (unless (stringp format) (setq format "\\cite{%l}"))
986
987 (if (and reftex-comment-citations
988 (string-match "%l" reftex-cite-comment-format))
5181ff9f 989 (error "reftex-cite-comment-format contains invalid %%l"))
1a9461d0
CD
990
991 (while (string-match
992 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
993 format)
027a4b6b 994 (let ((n (string-to-number (match-string 4 format)))
1a9461d0
CD
995 (l (string-to-char (match-string 5 format)))
996 rpl b e)
997 (save-match-data
998 (setq rpl
999 (cond
1000 ((= l ?l) (concat
1001 (reftex-get-bib-field "&key" entry)
1002 (if reftex-comment-citations
1003 reftex-cite-comment-format
1004 "")))
1005 ((= l ?a) (reftex-format-names
1006 (reftex-get-bib-names "author" entry)
1007 (or n 2)))
1008 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
1009 ((= l ?b) (reftex-get-bib-field "booktitle" entry "in: %s"))
1010 ((= l ?B) (reftex-abbreviate-title
3666daf6 1011 (reftex-get-bib-field "booktitle" entry "in: %s")))
1a9461d0
CD
1012 ((= l ?c) (reftex-get-bib-field "chapter" entry))
1013 ((= l ?d) (reftex-get-bib-field "edition" entry))
1014 ((= l ?e) (reftex-format-names
1015 (reftex-get-bib-names "editor" entry)
1016 (or n 2)))
1017 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
1018 ((= l ?h) (reftex-get-bib-field "howpublished" entry))
1019 ((= l ?i) (reftex-get-bib-field "institution" entry))
1020 ((= l ?j) (reftex-get-bib-field "journal" entry))
1021 ((= l ?k) (reftex-get-bib-field "key" entry))
1022 ((= l ?m) (reftex-get-bib-field "month" entry))
1023 ((= l ?n) (reftex-get-bib-field "number" entry))
1024 ((= l ?o) (reftex-get-bib-field "organization" entry))
1025 ((= l ?p) (reftex-get-bib-field "pages" entry))
1026 ((= l ?P) (car (split-string
1027 (reftex-get-bib-field "pages" entry)
1028 "[- .]+")))
1029 ((= l ?s) (reftex-get-bib-field "school" entry))
1030 ((= l ?u) (reftex-get-bib-field "publisher" entry))
1031 ((= l ?r) (reftex-get-bib-field "address" entry))
1032 ((= l ?t) (reftex-get-bib-field "title" entry))
1033 ((= l ?T) (reftex-abbreviate-title
3666daf6 1034 (reftex-get-bib-field "title" entry)))
1a9461d0
CD
1035 ((= l ?v) (reftex-get-bib-field "volume" entry))
1036 ((= l ?y) (reftex-get-bib-field "year" entry)))))
1037
1038 (if (string= rpl "")
1039 (setq b (match-beginning 2) e (match-end 2))
1040 (setq b (match-beginning 3) e (match-end 3)))
1041 (setq format (concat (substring format 0 b) rpl (substring format e)))))
1042 (while (string-match "%%" format)
1043 (setq format (replace-match "%" t t format)))
1044 (while (string-match "[ ,.;:]*%<" format)
1045 (setq format (replace-match "" t t format)))
1046 format)
1047
1048(defun reftex-make-cite-echo-string (entry docstruct-symbol)
1049 ;; Format a bibtex entry for the echo area and cache the result.
1050 (let* ((key (reftex-get-bib-field "&key" entry))
d63eb0e7 1051 (string
3666daf6
CD
1052 (let* ((reftex-cite-punctuation '(" " " & " " etal.")))
1053 (reftex-format-citation entry reftex-cite-view-format)))
1054 (cache (assq 'bibview-cache (symbol-value docstruct-symbol)))
1055 (cache-entry (assoc key (cdr cache))))
1a9461d0
CD
1056 (unless cache
1057 ;; This docstruct has no cache - make one.
1058 (set docstruct-symbol (cons (cons 'bibview-cache nil)
3666daf6 1059 (symbol-value docstruct-symbol))))
1a9461d0
CD
1060 (when reftex-cache-cite-echo
1061 (setq key (copy-sequence key))
1062 (set-text-properties 0 (length key) nil key)
1063 (set-text-properties 0 (length string) nil string)
1064 (if cache-entry
3666daf6
CD
1065 (unless (string= (cdr cache-entry) string)
1066 (setcdr cache-entry string)
1067 (put reftex-docstruct-symbol 'modified t))
1068 (push (cons key string) (cdr cache))
1069 (put reftex-docstruct-symbol 'modified t)))
1a9461d0
CD
1070 string))
1071
1072(defun reftex-bibtex-selection-callback (data ignore no-revisit)
1073 ;; Callback function to be called from the BibTeX selection, in
1074 ;; order to display context. This function is relatively slow and not
1075 ;; recommended for follow mode. It works OK for individual lookups.
1076 (let ((win (selected-window))
1077 (key (reftex-get-bib-field "&key" data))
20cd3579 1078 bibfile-list item bibtype)
1a9461d0
CD
1079
1080 (catch 'exit
9a529312 1081 (with-current-buffer reftex-call-back-to-this-buffer
3666daf6
CD
1082 (setq bibtype (reftex-bib-or-thebib))
1083 (cond
1084 ((eq bibtype 'bib)
1085; ((assq 'bib (symbol-value reftex-docstruct-symbol))
1086 (setq bibfile-list (reftex-get-bibfile-list)))
1087 ((eq bibtype 'thebib)
1088; ((assq 'thebib (symbol-value reftex-docstruct-symbol))
1089 (setq bibfile-list
1090 (reftex-uniquify
1091 (mapcar 'cdr
d63eb0e7 1092 (reftex-all-assq
3666daf6
CD
1093 'thebib (symbol-value reftex-docstruct-symbol))))
1094 item t))
1095 (reftex-default-bibliography
1096 (setq bibfile-list (reftex-default-bibliography)))
1097 (t (ding) (throw 'exit nil))))
1a9461d0
CD
1098
1099 (when no-revisit
3666daf6 1100 (setq bibfile-list (reftex-visited-files bibfile-list)))
1a9461d0
CD
1101
1102 (condition-case nil
d63eb0e7 1103 (reftex-pop-to-bibtex-entry
3666daf6
CD
1104 key bibfile-list (not reftex-keep-temporary-buffers) t item)
1105 (error (ding))))
d63eb0e7 1106
1a9461d0
CD
1107 (select-window win)))
1108
f3c18bd0
CD
1109;;; Global BibTeX file
1110(defun reftex-all-used-citation-keys ()
1111 (reftex-access-scan-info)
7b07114a 1112 (let ((files (reftex-all-document-files)) file keys kk k)
9a529312 1113 (save-current-buffer
f3c18bd0
CD
1114 (while (setq file (pop files))
1115 (set-buffer (reftex-get-file-buffer-force file 'mark))
1116 (save-excursion
1117 (save-restriction
1118 (widen)
1119 (goto-char (point-min))
1120 (while (re-search-forward "^[^%\n\r]*\\\\\\(bibentry\\|[a-zA-Z]*cite[a-zA-Z]*\\)\\(\\[[^\\]]*\\]\\)?{\\([^}]+\\)}" nil t)
1121 (setq kk (match-string-no-properties 3))
1122 (while (string-match "%.*\n?" kk)
1123 (setq kk (replace-match "" t t kk)))
1124 (setq kk (split-string kk "[, \t\r\n]+"))
1125 (while (setq k (pop kk))
1126 (or (member k keys)
1127 (setq keys (cons k keys)))))))))
1128 (reftex-kill-temporary-buffers)
1129 keys))
1130
1131(defun reftex-create-bibtex-file (bibfile)
1132 "Create a new BibTeX database file with all entries referenced in document.
1133The command prompts for a filename and writes the collected entries to
1134that file. Only entries referenced in the current document with
d63eb0e7 1135any \\cite-like macros are used.
f3c18bd0
CD
1136The sequence in the new file is the same as it was in the old database."
1137 (interactive "FNew BibTeX file: ")
1138 (let ((keys (reftex-all-used-citation-keys))
1139 (files (reftex-get-bibfile-list))
1140 file key entries beg end entry)
9a529312 1141 (save-current-buffer
f3c18bd0
CD
1142 (while (setq file (pop files))
1143 (set-buffer (reftex-get-file-buffer-force file 'mark))
1144 (reftex-with-special-syntax-for-bib
1145 (save-excursion
1146 (save-restriction
1147 (widen)
1148 (goto-char (point-min))
5d8f9169
RA
1149 (while (re-search-forward "^[ \t]*@\\(?:\\w\\|\\s_\\)+[ \t\n\r]*\
1150\[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
f3c18bd0
CD
1151 (setq key (match-string 1)
1152 beg (match-beginning 0)
1153 end (progn
1154 (goto-char (match-beginning 1))
1155 (condition-case nil
1156 (up-list 1)
1157 (error (goto-char (match-end 0))))
1158 (point)))
1159 (when (member key keys)
1160 (setq entry (buffer-substring beg end)
1161 entries (cons entry entries)
1162 keys (delete key keys)))))))))
1163 (find-file-other-window bibfile)
1164 (if (> (buffer-size) 0)
d63eb0e7 1165 (unless (yes-or-no-p
f3c18bd0
CD
1166 (format "Overwrite non-empty file %s? " bibfile))
1167 (error "Abort")))
1168 (erase-buffer)
1169 (insert (mapconcat 'identity (reverse entries) "\n\n"))
1170 (goto-char (point-min))
1171 (save-buffer)
1172 (message "%d entries extracted and copied to new database"
1173 (length entries))))
1174
1175
1a9461d0 1176;;; reftex-cite.el ends here