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