Switch to recommended form of GPLv3 permissions notice.
[emacs.git] / lisp / textmodes / reftex-cite.el
blobe16aef91c2070f8c706b56991ee0600706b7905c
1 ;;; reftex-cite.el --- creating citations with RefTeX
3 ;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4 ;; 2006, 2007, 2008 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 (save-excursion
360 (set-buffer buf)
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 start end)
380 "[ \t\n\r]*\\\\bibitem\\(\\[[^]]*]\\)*"))))))
381 (goto-char end)))))
382 (unless entries
383 (error "No bibitems found"))
385 ;; Read a regexp, completing on known citation keys.
386 (setq default (regexp-quote (reftex-get-bibkey-default)))
387 (setq re-list
388 (split-string
389 (completing-read
390 (concat
391 "Regex { && Regex...}: "
392 "[" default "]: ")
393 (if reftex-mode
394 (if (fboundp 'LaTeX-bibitem-list)
395 (LaTeX-bibitem-list)
396 (cdr (assoc 'bibview-cache
397 (symbol-value reftex-docstruct-symbol))))
398 nil)
399 nil nil nil 'reftex-cite-regexp-hist)
400 "[ \t]*&&[ \t]*"))
402 (if (or (null re-list ) (equal re-list '("")))
403 (setq re-list (list default)))
405 (if (string-match "\\`[ \t]*\\'" (car re-list))
406 (error "Empty regular expression"))
408 (while (and (setq re (pop re-list)) entries)
409 (setq entries
410 (delq nil (mapcar
411 (lambda (x)
412 (if (string-match re (cdr (assoc "&entry" x)))
413 x nil))
414 entries))))
415 (setq entries
416 (mapcar
417 (lambda (x)
418 (push (cons "&formatted" (reftex-format-bibitem x)) x)
419 (push (reftex-get-bib-field "&key" x) x)
421 entries))
423 entries))
425 (defun reftex-get-bibkey-default ()
426 ;; Return the word before the cursor. If the cursor is in a
427 ;; citation macro, return the word before the macro.
428 (let* ((macro (reftex-what-macro 1)))
429 (save-excursion
430 (if (and macro (string-match "cite" (car macro)))
431 (goto-char (cdr macro)))
432 (skip-chars-backward "^a-zA-Z0-9")
433 (reftex-this-word))))
435 ;; Parse and format individual entries
437 (defun reftex-get-bib-names (field entry)
438 ;; Return a list with the author or editor names in ENTRY
439 (let ((names (reftex-get-bib-field field entry)))
440 (if (equal "" names)
441 (setq names (reftex-get-bib-field "editor" entry)))
442 (while (string-match "\\band\\b[ \t]*" names)
443 (setq names (replace-match "\n" nil t names)))
444 (while (string-match "[\\.a-zA-Z\\-]+\\.[ \t]*\\|,.*\\|[{}]+" names)
445 (setq names (replace-match "" nil t names)))
446 (while (string-match "^[ \t]+\\|[ \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 (split-string names "\n")))
452 (defun reftex-parse-bibtex-entry (entry &optional from to)
453 (let (alist key start field)
454 (save-excursion
455 (save-restriction
456 (if entry
457 (progn
458 (set-buffer (get-buffer-create " *RefTeX-scratch*"))
459 (fundamental-mode)
460 (set-syntax-table reftex-syntax-table-for-bib)
461 (erase-buffer)
462 (insert entry))
463 (widen)
464 (narrow-to-region from to))
465 (goto-char (point-min))
467 (if (re-search-forward
468 "@\\(\\w+\\)[ \t\n\r]*[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
469 (setq alist
470 (list
471 (cons "&type" (downcase (reftex-match-string 1)))
472 (cons "&key" (reftex-match-string 2)))))
473 (while (re-search-forward "\\(\\w+\\)[ \t\n\r]*=[ \t\n\r]*" nil t)
474 (setq key (downcase (reftex-match-string 1)))
475 (cond
476 ((= (following-char) ?{)
477 (forward-char 1)
478 (setq start (point))
479 (condition-case nil
480 (up-list 1)
481 (error nil)))
482 ((= (following-char) ?\")
483 (forward-char 1)
484 (setq start (point))
485 (while (and (search-forward "\"" nil t)
486 (= ?\\ (char-after (- (point) 2))))))
488 (setq start (point))
489 (re-search-forward "[ \t]*[\n\r,}]" nil 1)))
490 (setq field (buffer-substring-no-properties start (1- (point))))
491 ;; remove extra whitespace
492 (while (string-match "[\n\t\r]\\|[ \t][ \t]+" field)
493 (setq field (replace-match " " nil t field)))
494 ;; remove leading garbage
495 (if (string-match "^[ \t{]+" field)
496 (setq field (replace-match "" nil t field)))
497 ;; remove trailing garbage
498 (if (string-match "[ \t}]+$" field)
499 (setq field (replace-match "" nil t field)))
500 (push (cons key field) alist))))
501 alist))
503 (defun reftex-get-bib-field (fieldname entry &optional format)
504 ;; Extract the field FIELDNAME from an ENTRY
505 (let ((cell (assoc fieldname entry)))
506 (if cell
507 (if format
508 (format format (cdr cell))
509 (cdr cell))
510 "")))
512 (defun reftex-format-bib-entry (entry)
513 ;; Format a BibTeX ENTRY so that it is nice to look at
514 (let*
515 ((auth-list (reftex-get-bib-names "author" entry))
516 (authors (mapconcat 'identity auth-list ", "))
517 (year (reftex-get-bib-field "year" entry))
518 (title (reftex-get-bib-field "title" entry))
519 (type (reftex-get-bib-field "&type" entry))
520 (key (reftex-get-bib-field "&key" entry))
521 (extra
522 (cond
523 ((equal type "article")
524 (concat (reftex-get-bib-field "journal" entry) " "
525 (reftex-get-bib-field "volume" entry) ", "
526 (reftex-get-bib-field "pages" entry)))
527 ((equal type "book")
528 (concat "book (" (reftex-get-bib-field "publisher" entry) ")"))
529 ((equal type "phdthesis")
530 (concat "PhD: " (reftex-get-bib-field "school" entry)))
531 ((equal type "mastersthesis")
532 (concat "Master: " (reftex-get-bib-field "school" entry)))
533 ((equal type "inbook")
534 (concat "Chap: " (reftex-get-bib-field "chapter" entry)
535 ", pp. " (reftex-get-bib-field "pages" entry)))
536 ((or (equal type "conference")
537 (equal type "incollection")
538 (equal type "inproceedings"))
539 (reftex-get-bib-field "booktitle" entry "in: %s"))
540 (t ""))))
541 (setq authors (reftex-truncate authors 30 t t))
542 (when (reftex-use-fonts)
543 (put-text-property 0 (length key) 'face
544 (reftex-verified-face reftex-label-face
545 'font-lock-constant-face
546 'font-lock-reference-face)
547 key)
548 (put-text-property 0 (length authors) 'face reftex-bib-author-face
549 authors)
550 (put-text-property 0 (length year) 'face reftex-bib-year-face
551 year)
552 (put-text-property 0 (length title) 'face reftex-bib-title-face
553 title)
554 (put-text-property 0 (length extra) 'face reftex-bib-extra-face
555 extra))
556 (concat key "\n " authors " " year " " extra "\n " title "\n\n")))
558 (defun reftex-parse-bibitem (item)
559 ;; Parse a \bibitem entry
560 (let ((key "") (text ""))
561 (when (string-match "\\`{\\([^}]+\\)}\\([^\000]*\\)" item)
562 (setq key (match-string 1 item)
563 text (match-string 2 item)))
564 ;; Clean up the text a little bit
565 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
566 (setq text (replace-match " " nil t text)))
567 (if (string-match "\\`[ \t]+" text)
568 (setq text (replace-match "" nil t text)))
569 (list
570 (cons "&key" key)
571 (cons "&text" text)
572 (cons "&entry" (concat key " " text)))))
574 (defun reftex-format-bibitem (item)
575 ;; Format a \bibitem entry so that it is (relatively) nice to look at.
576 (let ((text (reftex-get-bib-field "&text" item))
577 (key (reftex-get-bib-field "&key" item))
578 (lines nil))
580 ;; Wrap the text into several lines.
581 (while (and (> (length text) 70)
582 (string-match " " (substring text 60)))
583 (push (substring text 0 (+ 60 (match-beginning 0))) lines)
584 (setq text (substring text (+ 61 (match-beginning 0)))))
585 (push text lines)
586 (setq text (mapconcat 'identity (nreverse lines) "\n "))
588 (when (reftex-use-fonts)
589 (put-text-property 0 (length text) 'face reftex-bib-author-face text))
590 (concat key "\n " text "\n\n")))
592 ;; Make a citation
594 ;;;###autoload
595 (defun reftex-citation (&optional no-insert format-key)
596 "Make a citation using BibTeX database files.
597 After prompting for a regular expression, scans the buffers with
598 bibtex entries (taken from the \\bibliography command) and offers the
599 matching entries for selection. The selected entry is formatted according
600 to `reftex-cite-format' and inserted into the buffer.
602 If NO-INSERT is non-nil, nothing is inserted, only the selected key returned.
604 FORMAT-KEY can be used to pre-select a citation format.
606 When called with a `C-u' prefix, prompt for optional arguments in
607 cite macros. When called with a numeric prefix, make that many
608 citations. When called with point inside the braces of a `\\cite'
609 command, it will add another key, ignoring the value of
610 `reftex-cite-format'.
612 The regular expression uses an expanded syntax: && is interpreted as `and'.
613 Thus, `aaaa&&bbb' matches entries which contain both `aaaa' and `bbb'.
614 While entering the regexp, completion on knows citation keys is possible.
615 `=' is a good regular expression to match all entries in all files."
617 (interactive)
619 ;; check for recursive edit
620 (reftex-check-recursive-edit)
622 ;; This function may also be called outside reftex-mode.
623 ;; Thus look for the scanning info only if in reftex-mode.
625 (when reftex-mode
626 (reftex-access-scan-info nil))
628 ;; Call reftex-do-citation, but protected
629 (unwind-protect
630 (reftex-do-citation current-prefix-arg no-insert format-key)
631 (reftex-kill-temporary-buffers)))
633 (defun reftex-do-citation (&optional arg no-insert format-key)
634 ;; This really does the work of reftex-citation.
636 (let* ((format (reftex-figure-out-cite-format arg no-insert format-key))
637 (docstruct-symbol reftex-docstruct-symbol)
638 (selected-entries (reftex-offer-bib-menu))
639 (insert-entries selected-entries)
640 entry string cite-view)
642 (when (stringp selected-entries)
643 (error selected-entries))
644 (unless selected-entries (error "Quit"))
646 (if (stringp selected-entries)
647 ;; Nonexistent entry
648 (setq selected-entries nil
649 insert-entries (list (list selected-entries
650 (cons "&key" selected-entries))))
651 ;; It makes sense to compute the cite-view strings.
652 (setq cite-view t))
654 (when (eq (car selected-entries) 'concat)
655 ;; All keys go into a single command - we need to trick a little
656 ;; FIXME: Unfortunately, this meens that commenting does not work right.
657 (pop selected-entries)
658 (let ((concat-keys (mapconcat 'car selected-entries ",")))
659 (setq insert-entries
660 (list (list concat-keys (cons "&key" concat-keys))))))
662 (unless no-insert
664 ;; We shall insert this into the buffer...
665 (message "Formatting...")
667 (while (setq entry (pop insert-entries))
668 ;; Format the citation and insert it
669 (setq string (if reftex-format-cite-function
670 (funcall reftex-format-cite-function
671 (reftex-get-bib-field "&key" entry)
672 format)
673 (reftex-format-citation entry format)))
674 (when (or (eq reftex-cite-prompt-optional-args t)
675 (and reftex-cite-prompt-optional-args
676 (equal arg '(4))))
677 (let ((start 0) (nth 0) value)
678 (while (setq start (string-match "\\[\\]" string start))
679 (setq value (read-string (format "Optional argument %d: "
680 (setq nth (1+ nth)))))
681 (setq string (replace-match (concat "[" value "]") t t string))
682 (setq start (1+ start)))))
683 ;; Should we cleanup empty optional arguments?
684 ;; if the first is empty, it can be removed. If the second is empty,
685 ;; it has to go. If there is only a single arg and empty, it can go
686 ;; as well.
687 (when reftex-cite-cleanup-optional-args
688 (cond
689 ((string-match "\\([a-zA-Z0-9]\\)\\[\\]{" string)
690 (setq string (replace-match "\\1{" nil nil string)))
691 ((string-match "\\[\\]\\(\\[[a-zA-Z0-9., ]+\\]\\)" string)
692 (setq string (replace-match "\\1" nil nil string)))
693 ((string-match "\\[\\]\\[\\]" string)
694 (setq string (replace-match "" t t string)))))
695 (insert string))
697 ;; Reposition cursor?
698 (when (string-match "\\?" string)
699 (search-backward "?")
700 (delete-char 1))
702 ;; Tell AUCTeX
703 (when (and reftex-mode
704 (fboundp 'LaTeX-add-bibitems)
705 reftex-plug-into-AUCTeX)
706 (apply 'LaTeX-add-bibitems (mapcar 'car selected-entries)))
708 ;; Produce the cite-view strings
709 (when (and reftex-mode reftex-cache-cite-echo cite-view)
710 (mapc (lambda (entry)
711 (reftex-make-cite-echo-string entry docstruct-symbol))
712 selected-entries))
714 (message ""))
716 (set-marker reftex-select-return-marker nil)
717 (reftex-kill-buffer "*RefTeX Select*")
719 ;; Check if the prefix arg was numeric, and call recursively
720 (when (integerp arg)
721 (if (> arg 1)
722 (progn
723 (skip-chars-backward "}")
724 (decf arg)
725 (reftex-do-citation arg))
726 (forward-char 1)))
728 ;; Return the citation key
729 (car (car selected-entries))))
731 (defun reftex-figure-out-cite-format (arg &optional no-insert format-key)
732 ;; Check if there is already a cite command at point and change cite format
733 ;; in order to only add another reference in the same cite command.
734 (let ((macro (car (reftex-what-macro 1)))
735 (cite-format-value (reftex-get-cite-format))
736 key format)
737 (cond
738 (no-insert
739 ;; Format does not really matter because nothing will be inserted.
740 (setq format "%l"))
742 ((and (stringp macro)
743 (string-match "\\`\\\\cite\\|cite\\'" macro))
744 ;; We are already inside a cite macro
745 (if (or (not arg) (not (listp arg)))
746 (setq format
747 (concat
748 (if (member (preceding-char) '(?\{ ?,)) "" ",")
749 "%l"
750 (if (member (following-char) '(?\} ?,)) "" ",")))
751 (setq format "%l")))
753 ;; Figure out the correct format
754 (setq format
755 (if (and (symbolp cite-format-value)
756 (assq cite-format-value reftex-cite-format-builtin))
757 (nth 2 (assq cite-format-value reftex-cite-format-builtin))
758 cite-format-value))
759 (when (listp format)
760 (setq key
761 (or format-key
762 (reftex-select-with-char
763 "" (concat "SELECT A CITATION FORMAT\n\n"
764 (mapconcat
765 (lambda (x)
766 (format "[%c] %s %s" (car x)
767 (if (> (car x) 31) " " "")
768 (cdr x)))
769 format "\n")))))
770 (if (assq key format)
771 (setq format (cdr (assq key format)))
772 (error "No citation format associated with key `%c'" key)))))
773 format))
775 (defun reftex-citep ()
776 "Call `reftex-citation' with a format selector `?p'."
777 (interactive)
778 (reftex-citation nil ?p))
780 (defun reftex-citet ()
781 "Call `reftex-citation' with a format selector `?t'."
782 (interactive)
783 (reftex-citation nil ?t))
785 (defvar reftex-select-bib-map)
786 (defun reftex-offer-bib-menu ()
787 ;; Offer bib menu and return list of selected items
789 (let ((bibtype (reftex-bib-or-thebib))
790 found-list rtn key data selected-entries)
791 (while
792 (not
793 (catch 'done
794 ;; Scan bibtex files
795 (setq found-list
796 (cond
797 ((eq bibtype 'bib)
798 ; ((assq 'bib (symbol-value reftex-docstruct-symbol))
799 ;; using BibTeX database files.
800 (reftex-extract-bib-entries (reftex-get-bibfile-list)))
801 ((eq bibtype 'thebib)
802 ; ((assq 'thebib (symbol-value reftex-docstruct-symbol))
803 ;; using thebibliography environment.
804 (reftex-extract-bib-entries-from-thebibliography
805 (reftex-uniquify
806 (mapcar 'cdr
807 (reftex-all-assq
808 'thebib (symbol-value reftex-docstruct-symbol))))))
809 (reftex-default-bibliography
810 (message "Using default bibliography")
811 (reftex-extract-bib-entries (reftex-default-bibliography)))
812 (t (error "No valid bibliography in this document, and no default available"))))
814 (unless found-list
815 (error "Sorry, no matches found"))
817 ;; Remember where we came from
818 (setq reftex-call-back-to-this-buffer (current-buffer))
819 (set-marker reftex-select-return-marker (point))
821 ;; Offer selection
822 (save-window-excursion
823 (delete-other-windows)
824 (let ((default-major-mode 'reftex-select-bib-mode))
825 (reftex-kill-buffer "*RefTeX Select*")
826 (switch-to-buffer-other-window "*RefTeX Select*")
827 (unless (eq major-mode 'reftex-select-bib-mode)
828 (reftex-select-bib-mode))
829 (let ((buffer-read-only nil))
830 (erase-buffer)
831 (reftex-insert-bib-matches found-list)))
832 (setq buffer-read-only t)
833 (if (= 0 (buffer-size))
834 (error "No matches found"))
835 (setq truncate-lines t)
836 (goto-char 1)
837 (while t
838 (setq rtn
839 (reftex-select-item
840 reftex-citation-prompt
841 reftex-citation-help
842 reftex-select-bib-map
844 'reftex-bibtex-selection-callback nil))
845 (setq key (car rtn)
846 data (nth 1 rtn))
847 (unless key (throw 'done t))
848 (cond
849 ((eq key ?g)
850 ;; Start over
851 (throw 'done nil))
852 ((eq key ?r)
853 ;; Restrict with new regular expression
854 (setq found-list (reftex-restrict-bib-matches found-list))
855 (let ((buffer-read-only nil))
856 (erase-buffer)
857 (reftex-insert-bib-matches found-list))
858 (goto-char 1))
859 ((eq key ?A)
860 ;; Take all (marked)
861 (setq selected-entries
862 (if reftex-select-marked
863 (mapcar 'car (nreverse reftex-select-marked))
864 found-list))
865 (throw 'done t))
866 ((eq key ?a)
867 ;; Take all (marked), and push the symbol 'concat
868 (setq selected-entries
869 (cons 'concat
870 (if reftex-select-marked
871 (mapcar 'car (nreverse reftex-select-marked))
872 found-list)))
873 (throw 'done t))
874 ((eq key ?e)
875 ;; Take all (marked), and push the symbol 'concat
876 (reftex-extract-bib-file found-list reftex-select-marked)
877 (setq selected-entries "BibTeX database file created")
878 (throw 'done t))
879 ((eq key ?E)
880 ;; Take all (marked), and push the symbol 'concat
881 (reftex-extract-bib-file found-list reftex-select-marked
882 'complement)
883 (setq selected-entries "BibTeX database file created")
884 (throw 'done t))
885 ((or (eq key ?\C-m)
886 (eq key 'return))
887 ;; Take selected
888 (setq selected-entries
889 (if reftex-select-marked
890 (cons 'concat
891 (mapcar 'car (nreverse reftex-select-marked)))
892 (if data (list data) nil)))
893 (throw 'done t))
894 ((stringp key)
895 ;; Got this one with completion
896 (setq selected-entries key)
897 (throw 'done t))
899 (ding))))))))
900 selected-entries))
902 (defun reftex-restrict-bib-matches (found-list)
903 ;; Limit FOUND-LIST with more regular expressions
904 (let ((re-list (split-string (read-string
905 "RegExp [ && RegExp...]: "
906 nil 'reftex-cite-regexp-hist)
907 "[ \t]*&&[ \t]*"))
908 (found-list-r found-list)
910 (while (setq re (pop re-list))
911 (setq found-list-r
912 (delq nil
913 (mapcar
914 (lambda (x)
915 (if (string-match
916 re (cdr (assoc "&entry" x)))
918 nil))
919 found-list-r))))
920 (if found-list-r
921 found-list-r
922 (ding)
923 found-list)))
925 (defun reftex-extract-bib-file (all &optional marked complement)
926 ;; Limit FOUND-LIST with more regular expressions
927 (let ((file (read-file-name "File to create: ")))
928 (find-file-other-window file)
929 (if (> (buffer-size) 0)
930 (unless (yes-or-no-p
931 (format "Overwrite non-empty file %s? " file))
932 (error "Abort")))
933 (erase-buffer)
934 (setq all (delq nil
935 (mapcar
936 (lambda (x)
937 (if marked
938 (if (or (and (assoc x marked) (not complement))
939 (and (not (assoc x marked)) complement))
940 (cdr (assoc "&entry" x))
941 nil)
942 (cdr (assoc "&entry" x))))
943 all)))
944 (insert (mapconcat 'identity all "\n\n"))
945 (save-buffer)
946 (goto-char (point-min))))
948 (defun reftex-insert-bib-matches (list)
949 ;; Insert the bib matches and number them correctly
950 (let ((mouse-face
951 (if (memq reftex-highlight-selection '(mouse both))
952 reftex-mouse-selected-face
953 nil))
954 tmp len)
955 (mapc
956 (lambda (x)
957 (setq tmp (cdr (assoc "&formatted" x))
958 len (length tmp))
959 (put-text-property 0 len :data x tmp)
960 (put-text-property 0 (1- len) 'mouse-face mouse-face tmp)
961 (insert tmp))
962 list))
963 (run-hooks 'reftex-display-copied-context-hook))
965 (defun reftex-format-names (namelist n)
966 (let (last (len (length namelist)))
967 (if (= n 0) (setq n len))
968 (cond
969 ((< len 1) "")
970 ((= 1 len) (car namelist))
971 ((> len n) (concat (car namelist) (nth 2 reftex-cite-punctuation)))
973 (setq n (min len n)
974 last (nth (1- n) namelist))
975 (setcdr (nthcdr (- n 2) namelist) nil)
976 (concat
977 (mapconcat 'identity namelist (nth 0 reftex-cite-punctuation))
978 (nth 1 reftex-cite-punctuation)
979 last)))))
981 (defun reftex-format-citation (entry format)
982 ;; Format a citation from the info in the BibTeX ENTRY
984 (unless (stringp format) (setq format "\\cite{%l}"))
986 (if (and reftex-comment-citations
987 (string-match "%l" reftex-cite-comment-format))
988 (error "reftex-cite-comment-format contains invalid %%l"))
990 (while (string-match
991 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
992 format)
993 (let ((n (string-to-number (match-string 4 format)))
994 (l (string-to-char (match-string 5 format)))
995 rpl b e)
996 (save-match-data
997 (setq rpl
998 (cond
999 ((= l ?l) (concat
1000 (reftex-get-bib-field "&key" entry)
1001 (if reftex-comment-citations
1002 reftex-cite-comment-format
1003 "")))
1004 ((= l ?a) (reftex-format-names
1005 (reftex-get-bib-names "author" entry)
1006 (or n 2)))
1007 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
1008 ((= l ?b) (reftex-get-bib-field "booktitle" entry "in: %s"))
1009 ((= l ?B) (reftex-abbreviate-title
1010 (reftex-get-bib-field "booktitle" entry "in: %s")))
1011 ((= l ?c) (reftex-get-bib-field "chapter" entry))
1012 ((= l ?d) (reftex-get-bib-field "edition" entry))
1013 ((= l ?e) (reftex-format-names
1014 (reftex-get-bib-names "editor" entry)
1015 (or n 2)))
1016 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
1017 ((= l ?h) (reftex-get-bib-field "howpublished" entry))
1018 ((= l ?i) (reftex-get-bib-field "institution" entry))
1019 ((= l ?j) (reftex-get-bib-field "journal" entry))
1020 ((= l ?k) (reftex-get-bib-field "key" entry))
1021 ((= l ?m) (reftex-get-bib-field "month" entry))
1022 ((= l ?n) (reftex-get-bib-field "number" entry))
1023 ((= l ?o) (reftex-get-bib-field "organization" entry))
1024 ((= l ?p) (reftex-get-bib-field "pages" entry))
1025 ((= l ?P) (car (split-string
1026 (reftex-get-bib-field "pages" entry)
1027 "[- .]+")))
1028 ((= l ?s) (reftex-get-bib-field "school" entry))
1029 ((= l ?u) (reftex-get-bib-field "publisher" entry))
1030 ((= l ?r) (reftex-get-bib-field "address" entry))
1031 ((= l ?t) (reftex-get-bib-field "title" entry))
1032 ((= l ?T) (reftex-abbreviate-title
1033 (reftex-get-bib-field "title" entry)))
1034 ((= l ?v) (reftex-get-bib-field "volume" entry))
1035 ((= l ?y) (reftex-get-bib-field "year" entry)))))
1037 (if (string= rpl "")
1038 (setq b (match-beginning 2) e (match-end 2))
1039 (setq b (match-beginning 3) e (match-end 3)))
1040 (setq format (concat (substring format 0 b) rpl (substring format e)))))
1041 (while (string-match "%%" format)
1042 (setq format (replace-match "%" t t format)))
1043 (while (string-match "[ ,.;:]*%<" format)
1044 (setq format (replace-match "" t t format)))
1045 format)
1047 (defun reftex-make-cite-echo-string (entry docstruct-symbol)
1048 ;; Format a bibtex entry for the echo area and cache the result.
1049 (let* ((key (reftex-get-bib-field "&key" entry))
1050 (string
1051 (let* ((reftex-cite-punctuation '(" " " & " " etal.")))
1052 (reftex-format-citation entry reftex-cite-view-format)))
1053 (cache (assq 'bibview-cache (symbol-value docstruct-symbol)))
1054 (cache-entry (assoc key (cdr cache))))
1055 (unless cache
1056 ;; This docstruct has no cache - make one.
1057 (set docstruct-symbol (cons (cons 'bibview-cache nil)
1058 (symbol-value docstruct-symbol))))
1059 (when reftex-cache-cite-echo
1060 (setq key (copy-sequence key))
1061 (set-text-properties 0 (length key) nil key)
1062 (set-text-properties 0 (length string) nil string)
1063 (if cache-entry
1064 (unless (string= (cdr cache-entry) string)
1065 (setcdr cache-entry string)
1066 (put reftex-docstruct-symbol 'modified t))
1067 (push (cons key string) (cdr cache))
1068 (put reftex-docstruct-symbol 'modified t)))
1069 string))
1071 (defun reftex-bibtex-selection-callback (data ignore no-revisit)
1072 ;; Callback function to be called from the BibTeX selection, in
1073 ;; order to display context. This function is relatively slow and not
1074 ;; recommended for follow mode. It works OK for individual lookups.
1075 (let ((win (selected-window))
1076 (key (reftex-get-bib-field "&key" data))
1077 bibfile-list item bibtype)
1079 (catch 'exit
1080 (save-excursion
1081 (set-buffer reftex-call-back-to-this-buffer)
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
1092 (reftex-all-assq
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))))
1099 (when no-revisit
1100 (setq bibfile-list (reftex-visited-files bibfile-list)))
1102 (condition-case nil
1103 (reftex-pop-to-bibtex-entry
1104 key bibfile-list (not reftex-keep-temporary-buffers) t item)
1105 (error (ding))))
1107 (select-window win)))
1109 ;;; Global BibTeX file
1110 (defun reftex-all-used-citation-keys ()
1111 (reftex-access-scan-info)
1112 (let ((files (reftex-all-document-files)) file keys kk k)
1113 (save-excursion
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))
1131 (defun reftex-create-bibtex-file (bibfile)
1132 "Create a new BibTeX database file with all entries referenced in document.
1133 The command prompts for a filename and writes the collected entries to
1134 that file. Only entries referenced in the current document with
1135 any \\cite-like macros are used.
1136 The 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)
1141 (save-excursion
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))
1149 (while (re-search-forward
1150 "^[ \t]*@[a-zA-Z]+[ \t]*{\\([^ \t\r\n]+\\),"
1151 nil t)
1152 (setq key (match-string 1)
1153 beg (match-beginning 0)
1154 end (progn
1155 (goto-char (match-beginning 1))
1156 (condition-case nil
1157 (up-list 1)
1158 (error (goto-char (match-end 0))))
1159 (point)))
1160 (when (member key keys)
1161 (setq entry (buffer-substring beg end)
1162 entries (cons entry entries)
1163 keys (delete key keys)))))))))
1164 (find-file-other-window bibfile)
1165 (if (> (buffer-size) 0)
1166 (unless (yes-or-no-p
1167 (format "Overwrite non-empty file %s? " bibfile))
1168 (error "Abort")))
1169 (erase-buffer)
1170 (insert (mapconcat 'identity (reverse entries) "\n\n"))
1171 (goto-char (point-min))
1172 (save-buffer)
1173 (message "%d entries extracted and copied to new database"
1174 (length entries))))
1177 ;; arch-tag: d53d0a5a-ab32-4b52-a846-2a7c3527cd89
1178 ;;; reftex-cite.el ends here