(vc-path): Mark as obsolete.
[emacs.git] / lisp / textmodes / reftex-cite.el
blob3972a1df31c5dad33f641639510b8936129a6abf
1 ;;; reftex-cite.el --- creating citations with RefTeX
3 ;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4 ;; 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <dominik@science.uva.nl>
7 ;; Maintainer: auctex-devel@gnu.org
8 ;; Version: 4.31
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
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.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;;; Code:
29 (eval-when-compile (require 'cl))
30 (provide 'reftex-cite)
31 (require 'reftex)
32 ;;;
34 ;; Variables and constants
36 ;; The history list of regular expressions used for citations
37 (defvar reftex-cite-regexp-hist nil)
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")
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.
53 e / E Create BibTeX file with all (marked/unmarked) entries
54 a / A Put all (marked) entries into one/many \\cite commands.")
56 ;; Find bibtex files
58 (defmacro reftex-with-special-syntax-for-bib (&rest body)
59 `(let ((saved-syntax (syntax-table)))
60 (unwind-protect
61 (progn
62 (set-syntax-table reftex-syntax-table-for-bib)
63 ,@body)
64 (set-syntax-table saved-syntax))))
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)
70 reftex-default-bibliography)
71 (put 'reftex-default-bibliography :reftex-expanded
72 (reftex-locate-bibliography-files
73 default-directory reftex-default-bibliography))
74 (put 'reftex-default-bibliography :reftex-raw
75 reftex-default-bibliography))
76 (get 'reftex-default-bibliography :reftex-expanded))
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))
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)))
89 (when (not (or thebib bib))
90 (setq bib (assq 'bib docstruct)
91 thebib (assq 'thebib docstruct)
92 bibmem (memq bib docstruct)
93 thebibmem (memq thebib docstruct)))
94 (if (> (length bibmem) (length thebibmem))
95 (if bib 'bib nil)
96 (if thebib 'thebib nil))))
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.
105 ;; Ensure access to scanning info
106 (reftex-access-scan-info)
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")))
120 ;; Find a certain reference in any of the BibTeX files.
122 (defun reftex-pop-to-bibtex-entry (key file-list &optional mark-to-kill
123 highlight item return)
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.
128 ;; If RETURN is non-nil, just return the entry and restore point.
130 (let* ((re
131 (if item
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))
136 file buf pos oldpos)
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)
145 (setq oldpos (point))
146 (widen)
147 (goto-char (point-min))
148 (if (not (re-search-forward re nil t))
149 (goto-char oldpos) ;; restore previous position of point
150 (goto-char (match-beginning 0))
151 (setq pos (point))
152 (when return
153 ;; Just return the relevant entry
154 (if item (goto-char (match-end 0)))
155 (setq return (buffer-substring
156 (point) (reftex-end-of-bib-entry item)))
157 (goto-char oldpos) ;; restore point.
158 (set-buffer buffer-conf)
159 (throw 'exit return))
160 (switch-to-buffer-other-window buf)
161 (goto-char pos)
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
168 (error "No \\bibitem with citation key %s" key)
169 (error "No BibTeX entry with citation key %s" key)))))
171 (defun reftex-end-of-bib-entry (item)
172 (save-excursion
173 (condition-case nil
174 (if item
175 (progn (end-of-line)
176 (re-search-forward
177 "\\\\bibitem\\|\\end{thebibliography}")
178 (1- (match-beginning 0)))
179 (progn (forward-list 1) (point)))
180 (error (min (point-max) (+ 300 (point)))))))
182 ;; Parse bibtex buffers
184 (defun reftex-extract-bib-entries (buffers)
185 ;; Extract bib entries which match regexps from BUFFERS.
186 ;; BUFFERS is a list of buffers or file names.
187 ;; Return list with entries."
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)
193 ;; Read a regexp, completing on known citation keys.
194 (setq default (regexp-quote (reftex-get-bibkey-default)))
195 (setq re-list
196 (split-string
197 (completing-read
198 (concat
199 "Regex { && Regex...}: "
200 "[" default "]: ")
201 (if reftex-mode
202 (if (fboundp 'LaTeX-bibitem-list)
203 (LaTeX-bibitem-list)
204 (cdr (assoc 'bibview-cache
205 (symbol-value reftex-docstruct-symbol))))
206 nil)
207 nil nil nil 'reftex-cite-regexp-hist)
208 "[ \t]*&&[ \t]*"))
210 (if (or (null re-list ) (equal re-list '("")))
211 (setq re-list (list default)))
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"))
218 (save-excursion
219 (save-window-excursion
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))
234 (set-buffer buffer1)
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)
249 (throw 'search-again nil)))
250 (setq end-point (point))
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))
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)))
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))
274 (setq alist (reftex-parse-bibtex-entry
275 nil start-point end-point))
276 (push (cons "&entry" entry) alist)
278 ;; check for crossref entries
279 (if (assoc "crossref" alist)
280 (setq alist
281 (append
282 alist (reftex-get-crossref-alist alist))))
284 ;; format the entry
285 (push (cons "&formatted" (reftex-format-bib-entry alist))
286 alist)
288 ;; make key the first element
289 (push (reftex-get-bib-field "&key" alist) alist)
291 ;; add it to the list
292 (push alist found-list)))))
293 (reftex-kill-temporary-buffers))))
294 (setq found-list (nreverse found-list))
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))))
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))))))
317 (defun reftex-bib-sort-year (e1 e2)
318 (< (string-to-number (or (cdr (assoc "year" e1)) "0"))
319 (string-to-number (or (cdr (assoc "year" e2)) "0"))))
321 (defun reftex-bib-sort-year-reverse (e1 e2)
322 (> (string-to-number (or (cdr (assoc "year" e1)) "0"))
323 (string-to-number (or (cdr (assoc "year" e2)) "0"))))
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)))))
343 ;; Parse the bibliography environment
344 (defun reftex-extract-bib-entries-from-thebibliography (files)
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.
349 (let* (start end buf entries re re-list file default)
350 (unless files
351 (error "Need file name to find thebibliography environment"))
352 (while (setq file (pop files))
353 (setq buf (reftex-get-file-buffer-force
354 file (not reftex-keep-temporary-buffers)))
355 (unless buf
356 (error "No such file %s" file))
357 (message "Scanning thebibliography environment in %s" file)
359 (with-current-buffer buf
360 (save-restriction
361 (widen)
362 (goto-char (point-min))
363 (while (re-search-forward
364 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
365 (beginning-of-line 2)
366 (setq start (point))
367 (if (re-search-forward
368 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\end{thebibliography}" nil t)
369 (progn
370 (beginning-of-line 1)
371 (setq end (point))))
372 (when (and start end)
373 (setq entries
374 (append entries
375 (mapcar 'reftex-parse-bibitem
376 (delete ""
377 (split-string
378 (buffer-substring-no-properties start end)
379 "[ \t\n\r]*\\\\bibitem\\(\\[[^]]*]\\)*"))))))
380 (goto-char end)))))
381 (unless entries
382 (error "No bibitems found"))
384 ;; Read a regexp, completing on known citation keys.
385 (setq default (regexp-quote (reftex-get-bibkey-default)))
386 (setq re-list
387 (split-string
388 (completing-read
389 (concat
390 "Regex { && Regex...}: "
391 "[" default "]: ")
392 (if reftex-mode
393 (if (fboundp 'LaTeX-bibitem-list)
394 (LaTeX-bibitem-list)
395 (cdr (assoc 'bibview-cache
396 (symbol-value reftex-docstruct-symbol))))
397 nil)
398 nil nil nil 'reftex-cite-regexp-hist)
399 "[ \t]*&&[ \t]*"))
401 (if (or (null re-list ) (equal re-list '("")))
402 (setq re-list (list default)))
404 (if (string-match "\\`[ \t]*\\'" (car re-list))
405 (error "Empty regular expression"))
407 (while (and (setq re (pop re-list)) entries)
408 (setq entries
409 (delq nil (mapcar
410 (lambda (x)
411 (if (string-match re (cdr (assoc "&entry" x)))
412 x nil))
413 entries))))
414 (setq entries
415 (mapcar
416 (lambda (x)
417 (push (cons "&formatted" (reftex-format-bibitem x)) x)
418 (push (reftex-get-bib-field "&key" x) x)
420 entries))
422 entries))
424 (defun reftex-get-bibkey-default ()
425 ;; Return the word before the cursor. If the cursor is in a
426 ;; citation macro, return the word before the macro.
427 (let* ((macro (reftex-what-macro 1)))
428 (save-excursion
429 (if (and macro (string-match "cite" (car macro)))
430 (goto-char (cdr macro)))
431 (skip-chars-backward "^a-zA-Z0-9")
432 (reftex-this-word))))
434 ;; Parse and format individual entries
436 (defun reftex-get-bib-names (field entry)
437 ;; Return a list with the author or editor names in ENTRY
438 (let ((names (reftex-get-bib-field field entry)))
439 (if (equal "" names)
440 (setq names (reftex-get-bib-field "editor" entry)))
441 (while (string-match "\\band\\b[ \t]*" names)
442 (setq names (replace-match "\n" nil t names)))
443 (while (string-match "[\\.a-zA-Z\\-]+\\.[ \t]*\\|,.*\\|[{}]+" names)
444 (setq names (replace-match "" nil t names)))
445 (while (string-match "^[ \t]+\\|[ \t]+$" names)
446 (setq names (replace-match "" nil t names)))
447 (while (string-match "[ \t][ \t]+" names)
448 (setq names (replace-match " " nil t names)))
449 (split-string names "\n")))
451 (defun reftex-parse-bibtex-entry (entry &optional from to)
452 (let (alist key start field)
453 (save-excursion
454 (save-restriction
455 (if entry
456 (progn
457 (set-buffer (get-buffer-create " *RefTeX-scratch*"))
458 (fundamental-mode)
459 (set-syntax-table reftex-syntax-table-for-bib)
460 (erase-buffer)
461 (insert entry))
462 (widen)
463 (narrow-to-region from to))
464 (goto-char (point-min))
466 (if (re-search-forward
467 "@\\(\\w+\\)[ \t\n\r]*[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
468 (setq alist
469 (list
470 (cons "&type" (downcase (reftex-match-string 1)))
471 (cons "&key" (reftex-match-string 2)))))
472 (while (re-search-forward "\\(\\w+\\)[ \t\n\r]*=[ \t\n\r]*" nil t)
473 (setq key (downcase (reftex-match-string 1)))
474 (cond
475 ((= (following-char) ?{)
476 (forward-char 1)
477 (setq start (point))
478 (condition-case nil
479 (up-list 1)
480 (error nil)))
481 ((= (following-char) ?\")
482 (forward-char 1)
483 (setq start (point))
484 (while (and (search-forward "\"" nil t)
485 (= ?\\ (char-after (- (point) 2))))))
487 (setq start (point))
488 (re-search-forward "[ \t]*[\n\r,}]" nil 1)))
489 (setq field (buffer-substring-no-properties start (1- (point))))
490 ;; remove extra whitespace
491 (while (string-match "[\n\t\r]\\|[ \t][ \t]+" field)
492 (setq field (replace-match " " nil t field)))
493 ;; remove leading garbage
494 (if (string-match "^[ \t{]+" field)
495 (setq field (replace-match "" nil t field)))
496 ;; remove trailing garbage
497 (if (string-match "[ \t}]+$" field)
498 (setq field (replace-match "" nil t field)))
499 (push (cons key field) alist))))
500 alist))
502 (defun reftex-get-bib-field (fieldname entry &optional format)
503 ;; Extract the field FIELDNAME from an ENTRY
504 (let ((cell (assoc fieldname entry)))
505 (if cell
506 (if format
507 (format format (cdr cell))
508 (cdr cell))
509 "")))
511 (defun reftex-format-bib-entry (entry)
512 ;; Format a BibTeX ENTRY so that it is nice to look at
513 (let*
514 ((auth-list (reftex-get-bib-names "author" entry))
515 (authors (mapconcat 'identity auth-list ", "))
516 (year (reftex-get-bib-field "year" entry))
517 (title (reftex-get-bib-field "title" entry))
518 (type (reftex-get-bib-field "&type" entry))
519 (key (reftex-get-bib-field "&key" entry))
520 (extra
521 (cond
522 ((equal type "article")
523 (concat (reftex-get-bib-field "journal" entry) " "
524 (reftex-get-bib-field "volume" entry) ", "
525 (reftex-get-bib-field "pages" entry)))
526 ((equal type "book")
527 (concat "book (" (reftex-get-bib-field "publisher" entry) ")"))
528 ((equal type "phdthesis")
529 (concat "PhD: " (reftex-get-bib-field "school" entry)))
530 ((equal type "mastersthesis")
531 (concat "Master: " (reftex-get-bib-field "school" entry)))
532 ((equal type "inbook")
533 (concat "Chap: " (reftex-get-bib-field "chapter" entry)
534 ", pp. " (reftex-get-bib-field "pages" entry)))
535 ((or (equal type "conference")
536 (equal type "incollection")
537 (equal type "inproceedings"))
538 (reftex-get-bib-field "booktitle" entry "in: %s"))
539 (t ""))))
540 (setq authors (reftex-truncate authors 30 t t))
541 (when (reftex-use-fonts)
542 (put-text-property 0 (length key) 'face
543 (reftex-verified-face reftex-label-face
544 'font-lock-constant-face
545 'font-lock-reference-face)
546 key)
547 (put-text-property 0 (length authors) 'face reftex-bib-author-face
548 authors)
549 (put-text-property 0 (length year) 'face reftex-bib-year-face
550 year)
551 (put-text-property 0 (length title) 'face reftex-bib-title-face
552 title)
553 (put-text-property 0 (length extra) 'face reftex-bib-extra-face
554 extra))
555 (concat key "\n " authors " " year " " extra "\n " title "\n\n")))
557 (defun reftex-parse-bibitem (item)
558 ;; Parse a \bibitem entry
559 (let ((key "") (text ""))
560 (when (string-match "\\`{\\([^}]+\\)}\\([^\000]*\\)" item)
561 (setq key (match-string 1 item)
562 text (match-string 2 item)))
563 ;; Clean up the text a little bit
564 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
565 (setq text (replace-match " " nil t text)))
566 (if (string-match "\\`[ \t]+" text)
567 (setq text (replace-match "" nil t text)))
568 (list
569 (cons "&key" key)
570 (cons "&text" text)
571 (cons "&entry" (concat key " " text)))))
573 (defun reftex-format-bibitem (item)
574 ;; Format a \bibitem entry so that it is (relatively) nice to look at.
575 (let ((text (reftex-get-bib-field "&text" item))
576 (key (reftex-get-bib-field "&key" item))
577 (lines nil))
579 ;; Wrap the text into several lines.
580 (while (and (> (length text) 70)
581 (string-match " " (substring text 60)))
582 (push (substring text 0 (+ 60 (match-beginning 0))) lines)
583 (setq text (substring text (+ 61 (match-beginning 0)))))
584 (push text lines)
585 (setq text (mapconcat 'identity (nreverse lines) "\n "))
587 (when (reftex-use-fonts)
588 (put-text-property 0 (length text) 'face reftex-bib-author-face text))
589 (concat key "\n " text "\n\n")))
591 ;; Make a citation
593 ;;;###autoload
594 (defun reftex-citation (&optional no-insert format-key)
595 "Make a citation using BibTeX database files.
596 After prompting for a regular expression, scans the buffers with
597 bibtex entries (taken from the \\bibliography command) and offers the
598 matching entries for selection. The selected entry is formatted according
599 to `reftex-cite-format' and inserted into the buffer.
601 If NO-INSERT is non-nil, nothing is inserted, only the selected key returned.
603 FORMAT-KEY can be used to pre-select a citation format.
605 When called with a `C-u' prefix, prompt for optional arguments in
606 cite macros. When called with a numeric prefix, make that many
607 citations. When called with point inside the braces of a `\\cite'
608 command, it will add another key, ignoring the value of
609 `reftex-cite-format'.
611 The regular expression uses an expanded syntax: && is interpreted as `and'.
612 Thus, `aaaa&&bbb' matches entries which contain both `aaaa' and `bbb'.
613 While entering the regexp, completion on knows citation keys is possible.
614 `=' is a good regular expression to match all entries in all files."
616 (interactive)
618 ;; check for recursive edit
619 (reftex-check-recursive-edit)
621 ;; This function may also be called outside reftex-mode.
622 ;; Thus look for the scanning info only if in reftex-mode.
624 (when reftex-mode
625 (reftex-access-scan-info nil))
627 ;; Call reftex-do-citation, but protected
628 (unwind-protect
629 (reftex-do-citation current-prefix-arg no-insert format-key)
630 (reftex-kill-temporary-buffers)))
632 (defun reftex-do-citation (&optional arg no-insert format-key)
633 ;; This really does the work of reftex-citation.
635 (let* ((format (reftex-figure-out-cite-format arg no-insert format-key))
636 (docstruct-symbol reftex-docstruct-symbol)
637 (selected-entries (reftex-offer-bib-menu))
638 (insert-entries selected-entries)
639 entry string cite-view)
641 (when (stringp selected-entries)
642 (error selected-entries))
643 (unless selected-entries (error "Quit"))
645 (if (stringp selected-entries)
646 ;; Nonexistent entry
647 (setq selected-entries nil
648 insert-entries (list (list selected-entries
649 (cons "&key" selected-entries))))
650 ;; It makes sense to compute the cite-view strings.
651 (setq cite-view t))
653 (when (eq (car selected-entries) 'concat)
654 ;; All keys go into a single command - we need to trick a little
655 ;; FIXME: Unfortunately, this meens that commenting does not work right.
656 (pop selected-entries)
657 (let ((concat-keys (mapconcat 'car selected-entries ",")))
658 (setq insert-entries
659 (list (list concat-keys (cons "&key" concat-keys))))))
661 (unless no-insert
663 ;; We shall insert this into the buffer...
664 (message "Formatting...")
666 (while (setq entry (pop insert-entries))
667 ;; Format the citation and insert it
668 (setq string (if reftex-format-cite-function
669 (funcall reftex-format-cite-function
670 (reftex-get-bib-field "&key" entry)
671 format)
672 (reftex-format-citation entry format)))
673 (when (or (eq reftex-cite-prompt-optional-args t)
674 (and reftex-cite-prompt-optional-args
675 (equal arg '(4))))
676 (let ((start 0) (nth 0) value)
677 (while (setq start (string-match "\\[\\]" string start))
678 (setq value (read-string (format "Optional argument %d: "
679 (setq nth (1+ nth)))))
680 (setq string (replace-match (concat "[" value "]") t t string))
681 (setq start (1+ start)))))
682 ;; Should we cleanup empty optional arguments?
683 ;; if the first is empty, it can be removed. If the second is empty,
684 ;; it has to go. If there is only a single arg and empty, it can go
685 ;; as well.
686 (when reftex-cite-cleanup-optional-args
687 (cond
688 ((string-match "\\([a-zA-Z0-9]\\)\\[\\]{" string)
689 (setq string (replace-match "\\1{" nil nil string)))
690 ((string-match "\\[\\]\\(\\[[a-zA-Z0-9., ]+\\]\\)" string)
691 (setq string (replace-match "\\1" nil nil string)))
692 ((string-match "\\[\\]\\[\\]" string)
693 (setq string (replace-match "" t t string)))))
694 (insert string))
696 ;; Reposition cursor?
697 (when (string-match "\\?" string)
698 (search-backward "?")
699 (delete-char 1))
701 ;; Tell AUCTeX
702 (when (and reftex-mode
703 (fboundp 'LaTeX-add-bibitems)
704 reftex-plug-into-AUCTeX)
705 (apply 'LaTeX-add-bibitems (mapcar 'car selected-entries)))
707 ;; Produce the cite-view strings
708 (when (and reftex-mode reftex-cache-cite-echo cite-view)
709 (mapc (lambda (entry)
710 (reftex-make-cite-echo-string entry docstruct-symbol))
711 selected-entries))
713 (message ""))
715 (set-marker reftex-select-return-marker nil)
716 (reftex-kill-buffer "*RefTeX Select*")
718 ;; Check if the prefix arg was numeric, and call recursively
719 (when (integerp arg)
720 (if (> arg 1)
721 (progn
722 (skip-chars-backward "}")
723 (decf arg)
724 (reftex-do-citation arg))
725 (forward-char 1)))
727 ;; Return the citation key
728 (car (car selected-entries))))
730 (defun reftex-figure-out-cite-format (arg &optional no-insert format-key)
731 ;; Check if there is already a cite command at point and change cite format
732 ;; in order to only add another reference in the same cite command.
733 (let ((macro (car (reftex-what-macro 1)))
734 (cite-format-value (reftex-get-cite-format))
735 key format)
736 (cond
737 (no-insert
738 ;; Format does not really matter because nothing will be inserted.
739 (setq format "%l"))
741 ((and (stringp macro)
742 (string-match "\\`\\\\cite\\|cite\\'" macro))
743 ;; We are already inside a cite macro
744 (if (or (not arg) (not (listp arg)))
745 (setq format
746 (concat
747 (if (member (preceding-char) '(?\{ ?,)) "" ",")
748 "%l"
749 (if (member (following-char) '(?\} ?,)) "" ",")))
750 (setq format "%l")))
752 ;; Figure out the correct format
753 (setq format
754 (if (and (symbolp cite-format-value)
755 (assq cite-format-value reftex-cite-format-builtin))
756 (nth 2 (assq cite-format-value reftex-cite-format-builtin))
757 cite-format-value))
758 (when (listp format)
759 (setq key
760 (or format-key
761 (reftex-select-with-char
762 "" (concat "SELECT A CITATION FORMAT\n\n"
763 (mapconcat
764 (lambda (x)
765 (format "[%c] %s %s" (car x)
766 (if (> (car x) 31) " " "")
767 (cdr x)))
768 format "\n")))))
769 (if (assq key format)
770 (setq format (cdr (assq key format)))
771 (error "No citation format associated with key `%c'" key)))))
772 format))
774 (defun reftex-citep ()
775 "Call `reftex-citation' with a format selector `?p'."
776 (interactive)
777 (reftex-citation nil ?p))
779 (defun reftex-citet ()
780 "Call `reftex-citation' with a format selector `?t'."
781 (interactive)
782 (reftex-citation nil ?t))
784 (defvar reftex-select-bib-map)
785 (defun reftex-offer-bib-menu ()
786 ;; Offer bib menu and return list of selected items
788 (let ((bibtype (reftex-bib-or-thebib))
789 found-list rtn key data selected-entries)
790 (while
791 (not
792 (catch 'done
793 ;; Scan bibtex files
794 (setq found-list
795 (cond
796 ((eq bibtype 'bib)
797 ; ((assq 'bib (symbol-value reftex-docstruct-symbol))
798 ;; using BibTeX database files.
799 (reftex-extract-bib-entries (reftex-get-bibfile-list)))
800 ((eq bibtype 'thebib)
801 ; ((assq 'thebib (symbol-value reftex-docstruct-symbol))
802 ;; using thebibliography environment.
803 (reftex-extract-bib-entries-from-thebibliography
804 (reftex-uniquify
805 (mapcar 'cdr
806 (reftex-all-assq
807 'thebib (symbol-value reftex-docstruct-symbol))))))
808 (reftex-default-bibliography
809 (message "Using default bibliography")
810 (reftex-extract-bib-entries (reftex-default-bibliography)))
811 (t (error "No valid bibliography in this document, and no default available"))))
813 (unless found-list
814 (error "Sorry, no matches found"))
816 ;; Remember where we came from
817 (setq reftex-call-back-to-this-buffer (current-buffer))
818 (set-marker reftex-select-return-marker (point))
820 ;; Offer selection
821 (save-window-excursion
822 (delete-other-windows)
823 (reftex-kill-buffer "*RefTeX Select*")
824 (switch-to-buffer-other-window "*RefTeX Select*")
825 (unless (eq major-mode 'reftex-select-bib-mode)
826 (reftex-select-bib-mode))
827 (let ((buffer-read-only nil))
828 (erase-buffer)
829 (reftex-insert-bib-matches found-list))
830 (setq buffer-read-only t)
831 (if (= 0 (buffer-size))
832 (error "No matches found"))
833 (setq truncate-lines t)
834 (goto-char 1)
835 (while t
836 (setq rtn
837 (reftex-select-item
838 reftex-citation-prompt
839 reftex-citation-help
840 reftex-select-bib-map
842 'reftex-bibtex-selection-callback nil))
843 (setq key (car rtn)
844 data (nth 1 rtn))
845 (unless key (throw 'done t))
846 (cond
847 ((eq key ?g)
848 ;; Start over
849 (throw 'done nil))
850 ((eq key ?r)
851 ;; Restrict with new regular expression
852 (setq found-list (reftex-restrict-bib-matches found-list))
853 (let ((buffer-read-only nil))
854 (erase-buffer)
855 (reftex-insert-bib-matches found-list))
856 (goto-char 1))
857 ((eq key ?A)
858 ;; Take all (marked)
859 (setq selected-entries
860 (if reftex-select-marked
861 (mapcar 'car (nreverse reftex-select-marked))
862 found-list))
863 (throw 'done t))
864 ((eq key ?a)
865 ;; Take all (marked), and push the symbol 'concat
866 (setq selected-entries
867 (cons 'concat
868 (if reftex-select-marked
869 (mapcar 'car (nreverse reftex-select-marked))
870 found-list)))
871 (throw 'done t))
872 ((eq key ?e)
873 ;; Take all (marked), and push the symbol 'concat
874 (reftex-extract-bib-file found-list reftex-select-marked)
875 (setq selected-entries "BibTeX database file created")
876 (throw 'done t))
877 ((eq key ?E)
878 ;; Take all (marked), and push the symbol 'concat
879 (reftex-extract-bib-file found-list reftex-select-marked
880 'complement)
881 (setq selected-entries "BibTeX database file created")
882 (throw 'done t))
883 ((or (eq key ?\C-m)
884 (eq key 'return))
885 ;; Take selected
886 (setq selected-entries
887 (if reftex-select-marked
888 (cons 'concat
889 (mapcar 'car (nreverse reftex-select-marked)))
890 (if data (list data) nil)))
891 (throw 'done t))
892 ((stringp key)
893 ;; Got this one with completion
894 (setq selected-entries key)
895 (throw 'done t))
897 (ding))))))))
898 selected-entries))
900 (defun reftex-restrict-bib-matches (found-list)
901 ;; Limit FOUND-LIST with more regular expressions
902 (let ((re-list (split-string (read-string
903 "RegExp [ && RegExp...]: "
904 nil 'reftex-cite-regexp-hist)
905 "[ \t]*&&[ \t]*"))
906 (found-list-r found-list)
908 (while (setq re (pop re-list))
909 (setq found-list-r
910 (delq nil
911 (mapcar
912 (lambda (x)
913 (if (string-match
914 re (cdr (assoc "&entry" x)))
916 nil))
917 found-list-r))))
918 (if found-list-r
919 found-list-r
920 (ding)
921 found-list)))
923 (defun reftex-extract-bib-file (all &optional marked complement)
924 ;; Limit FOUND-LIST with more regular expressions
925 (let ((file (read-file-name "File to create: ")))
926 (find-file-other-window file)
927 (if (> (buffer-size) 0)
928 (unless (yes-or-no-p
929 (format "Overwrite non-empty file %s? " file))
930 (error "Abort")))
931 (erase-buffer)
932 (setq all (delq nil
933 (mapcar
934 (lambda (x)
935 (if marked
936 (if (or (and (assoc x marked) (not complement))
937 (and (not (assoc x marked)) complement))
938 (cdr (assoc "&entry" x))
939 nil)
940 (cdr (assoc "&entry" x))))
941 all)))
942 (insert (mapconcat 'identity all "\n\n"))
943 (save-buffer)
944 (goto-char (point-min))))
946 (defun reftex-insert-bib-matches (list)
947 ;; Insert the bib matches and number them correctly
948 (let ((mouse-face
949 (if (memq reftex-highlight-selection '(mouse both))
950 reftex-mouse-selected-face
951 nil))
952 tmp len)
953 (mapc
954 (lambda (x)
955 (setq tmp (cdr (assoc "&formatted" x))
956 len (length tmp))
957 (put-text-property 0 len :data x tmp)
958 (put-text-property 0 (1- len) 'mouse-face mouse-face tmp)
959 (insert tmp))
960 list))
961 (run-hooks 'reftex-display-copied-context-hook))
963 (defun reftex-format-names (namelist n)
964 (let (last (len (length namelist)))
965 (if (= n 0) (setq n len))
966 (cond
967 ((< len 1) "")
968 ((= 1 len) (car namelist))
969 ((> len n) (concat (car namelist) (nth 2 reftex-cite-punctuation)))
971 (setq n (min len n)
972 last (nth (1- n) namelist))
973 (setcdr (nthcdr (- n 2) namelist) nil)
974 (concat
975 (mapconcat 'identity namelist (nth 0 reftex-cite-punctuation))
976 (nth 1 reftex-cite-punctuation)
977 last)))))
979 (defun reftex-format-citation (entry format)
980 ;; Format a citation from the info in the BibTeX ENTRY
982 (unless (stringp format) (setq format "\\cite{%l}"))
984 (if (and reftex-comment-citations
985 (string-match "%l" reftex-cite-comment-format))
986 (error "reftex-cite-comment-format contains invalid %%l"))
988 (while (string-match
989 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
990 format)
991 (let ((n (string-to-number (match-string 4 format)))
992 (l (string-to-char (match-string 5 format)))
993 rpl b e)
994 (save-match-data
995 (setq rpl
996 (cond
997 ((= l ?l) (concat
998 (reftex-get-bib-field "&key" entry)
999 (if reftex-comment-citations
1000 reftex-cite-comment-format
1001 "")))
1002 ((= l ?a) (reftex-format-names
1003 (reftex-get-bib-names "author" entry)
1004 (or n 2)))
1005 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
1006 ((= l ?b) (reftex-get-bib-field "booktitle" entry "in: %s"))
1007 ((= l ?B) (reftex-abbreviate-title
1008 (reftex-get-bib-field "booktitle" entry "in: %s")))
1009 ((= l ?c) (reftex-get-bib-field "chapter" entry))
1010 ((= l ?d) (reftex-get-bib-field "edition" entry))
1011 ((= l ?e) (reftex-format-names
1012 (reftex-get-bib-names "editor" entry)
1013 (or n 2)))
1014 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
1015 ((= l ?h) (reftex-get-bib-field "howpublished" entry))
1016 ((= l ?i) (reftex-get-bib-field "institution" entry))
1017 ((= l ?j) (reftex-get-bib-field "journal" entry))
1018 ((= l ?k) (reftex-get-bib-field "key" entry))
1019 ((= l ?m) (reftex-get-bib-field "month" entry))
1020 ((= l ?n) (reftex-get-bib-field "number" entry))
1021 ((= l ?o) (reftex-get-bib-field "organization" entry))
1022 ((= l ?p) (reftex-get-bib-field "pages" entry))
1023 ((= l ?P) (car (split-string
1024 (reftex-get-bib-field "pages" entry)
1025 "[- .]+")))
1026 ((= l ?s) (reftex-get-bib-field "school" entry))
1027 ((= l ?u) (reftex-get-bib-field "publisher" entry))
1028 ((= l ?r) (reftex-get-bib-field "address" entry))
1029 ((= l ?t) (reftex-get-bib-field "title" entry))
1030 ((= l ?T) (reftex-abbreviate-title
1031 (reftex-get-bib-field "title" entry)))
1032 ((= l ?v) (reftex-get-bib-field "volume" entry))
1033 ((= l ?y) (reftex-get-bib-field "year" entry)))))
1035 (if (string= rpl "")
1036 (setq b (match-beginning 2) e (match-end 2))
1037 (setq b (match-beginning 3) e (match-end 3)))
1038 (setq format (concat (substring format 0 b) rpl (substring format e)))))
1039 (while (string-match "%%" format)
1040 (setq format (replace-match "%" t t format)))
1041 (while (string-match "[ ,.;:]*%<" format)
1042 (setq format (replace-match "" t t format)))
1043 format)
1045 (defun reftex-make-cite-echo-string (entry docstruct-symbol)
1046 ;; Format a bibtex entry for the echo area and cache the result.
1047 (let* ((key (reftex-get-bib-field "&key" entry))
1048 (string
1049 (let* ((reftex-cite-punctuation '(" " " & " " etal.")))
1050 (reftex-format-citation entry reftex-cite-view-format)))
1051 (cache (assq 'bibview-cache (symbol-value docstruct-symbol)))
1052 (cache-entry (assoc key (cdr cache))))
1053 (unless cache
1054 ;; This docstruct has no cache - make one.
1055 (set docstruct-symbol (cons (cons 'bibview-cache nil)
1056 (symbol-value docstruct-symbol))))
1057 (when reftex-cache-cite-echo
1058 (setq key (copy-sequence key))
1059 (set-text-properties 0 (length key) nil key)
1060 (set-text-properties 0 (length string) nil string)
1061 (if cache-entry
1062 (unless (string= (cdr cache-entry) string)
1063 (setcdr cache-entry string)
1064 (put reftex-docstruct-symbol 'modified t))
1065 (push (cons key string) (cdr cache))
1066 (put reftex-docstruct-symbol 'modified t)))
1067 string))
1069 (defun reftex-bibtex-selection-callback (data ignore no-revisit)
1070 ;; Callback function to be called from the BibTeX selection, in
1071 ;; order to display context. This function is relatively slow and not
1072 ;; recommended for follow mode. It works OK for individual lookups.
1073 (let ((win (selected-window))
1074 (key (reftex-get-bib-field "&key" data))
1075 bibfile-list item bibtype)
1077 (catch 'exit
1078 (with-current-buffer reftex-call-back-to-this-buffer
1079 (setq bibtype (reftex-bib-or-thebib))
1080 (cond
1081 ((eq bibtype 'bib)
1082 ; ((assq 'bib (symbol-value reftex-docstruct-symbol))
1083 (setq bibfile-list (reftex-get-bibfile-list)))
1084 ((eq bibtype 'thebib)
1085 ; ((assq 'thebib (symbol-value reftex-docstruct-symbol))
1086 (setq bibfile-list
1087 (reftex-uniquify
1088 (mapcar 'cdr
1089 (reftex-all-assq
1090 'thebib (symbol-value reftex-docstruct-symbol))))
1091 item t))
1092 (reftex-default-bibliography
1093 (setq bibfile-list (reftex-default-bibliography)))
1094 (t (ding) (throw 'exit nil))))
1096 (when no-revisit
1097 (setq bibfile-list (reftex-visited-files bibfile-list)))
1099 (condition-case nil
1100 (reftex-pop-to-bibtex-entry
1101 key bibfile-list (not reftex-keep-temporary-buffers) t item)
1102 (error (ding))))
1104 (select-window win)))
1106 ;;; Global BibTeX file
1107 (defun reftex-all-used-citation-keys ()
1108 (reftex-access-scan-info)
1109 (let ((files (reftex-all-document-files)) file keys kk k)
1110 (save-current-buffer
1111 (while (setq file (pop files))
1112 (set-buffer (reftex-get-file-buffer-force file 'mark))
1113 (save-excursion
1114 (save-restriction
1115 (widen)
1116 (goto-char (point-min))
1117 (while (re-search-forward "^[^%\n\r]*\\\\\\(bibentry\\|[a-zA-Z]*cite[a-zA-Z]*\\)\\(\\[[^\\]]*\\]\\)?{\\([^}]+\\)}" nil t)
1118 (setq kk (match-string-no-properties 3))
1119 (while (string-match "%.*\n?" kk)
1120 (setq kk (replace-match "" t t kk)))
1121 (setq kk (split-string kk "[, \t\r\n]+"))
1122 (while (setq k (pop kk))
1123 (or (member k keys)
1124 (setq keys (cons k keys)))))))))
1125 (reftex-kill-temporary-buffers)
1126 keys))
1128 (defun reftex-create-bibtex-file (bibfile)
1129 "Create a new BibTeX database file with all entries referenced in document.
1130 The command prompts for a filename and writes the collected entries to
1131 that file. Only entries referenced in the current document with
1132 any \\cite-like macros are used.
1133 The sequence in the new file is the same as it was in the old database."
1134 (interactive "FNew BibTeX file: ")
1135 (let ((keys (reftex-all-used-citation-keys))
1136 (files (reftex-get-bibfile-list))
1137 file key entries beg end entry)
1138 (save-current-buffer
1139 (while (setq file (pop files))
1140 (set-buffer (reftex-get-file-buffer-force file 'mark))
1141 (reftex-with-special-syntax-for-bib
1142 (save-excursion
1143 (save-restriction
1144 (widen)
1145 (goto-char (point-min))
1146 (while (re-search-forward
1147 "^[ \t]*@[a-zA-Z]+[ \t]*{\\([^ \t\r\n]+\\),"
1148 nil t)
1149 (setq key (match-string 1)
1150 beg (match-beginning 0)
1151 end (progn
1152 (goto-char (match-beginning 1))
1153 (condition-case nil
1154 (up-list 1)
1155 (error (goto-char (match-end 0))))
1156 (point)))
1157 (when (member key keys)
1158 (setq entry (buffer-substring beg end)
1159 entries (cons entry entries)
1160 keys (delete key keys)))))))))
1161 (find-file-other-window bibfile)
1162 (if (> (buffer-size) 0)
1163 (unless (yes-or-no-p
1164 (format "Overwrite non-empty file %s? " bibfile))
1165 (error "Abort")))
1166 (erase-buffer)
1167 (insert (mapconcat 'identity (reverse entries) "\n\n"))
1168 (goto-char (point-min))
1169 (save-buffer)
1170 (message "%d entries extracted and copied to new database"
1171 (length entries))))
1174 ;; arch-tag: d53d0a5a-ab32-4b52-a846-2a7c3527cd89
1175 ;;; reftex-cite.el ends here