1 ;;; reftex-cite.el --- creating citations with RefTeX
3 ;; Copyright (C) 1997-2012 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <dominik@science.uva.nl>
6 ;; Maintainer: auctex-devel@gnu.org
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
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.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 (eval-when-compile (require 'cl))
28 (provide 'reftex-cite)
32 ;; Variables and constants
34 ;; The history list of regular expressions used for citations
35 (defvar reftex-cite-regexp-hist nil)
37 ;; Prompt and help string for citation selection
38 (defconst reftex-citation-prompt
39 "Select: [n]ext [p]revious [r]estrict [ ]full_entry [q]uit RET [?]Help+more")
41 (defconst reftex-citation-help
42 " n / p Go to next/previous entry (Cursor motion works as well).
43 g / r Start over with new regexp / Refine with additional regexp.
44 SPC Show full database entry in other window.
45 f Toggle follow mode: Other window will follow with full db entry.
46 . Show insertion point.
47 q Quit without inserting \\cite macro into buffer.
48 TAB Enter citation key with completion.
49 RET Accept current entry (also on mouse-2) and create \\cite macro.
50 m / u Mark/Unmark the entry.
51 e / E Create BibTeX file with all (marked/unmarked) entries
52 a / A Put all (marked) entries into one/many \\cite commands.")
56 (defmacro reftex-with-special-syntax-for-bib (&rest body)
57 `(let ((saved-syntax (syntax-table)))
60 (set-syntax-table reftex-syntax-table-for-bib)
62 (set-syntax-table saved-syntax))))
64 (defun reftex-default-bibliography ()
65 ;; Return the expanded value of `reftex-default-bibliography'.
66 ;; The expanded value is cached.
67 (unless (eq (get 'reftex-default-bibliography :reftex-raw)
68 reftex-default-bibliography)
69 (put 'reftex-default-bibliography :reftex-expanded
70 (reftex-locate-bibliography-files
71 default-directory reftex-default-bibliography))
72 (put 'reftex-default-bibliography :reftex-raw
73 reftex-default-bibliography))
74 (get 'reftex-default-bibliography :reftex-expanded))
76 (defun reftex-bib-or-thebib ()
77 ;; Tests if BibTeX or \begin{thebibliography} should be used for the
79 ;; Find the bof of the current file
80 (let* ((docstruct (symbol-value reftex-docstruct-symbol))
81 (rest (or (member (list 'bof (buffer-file-name)) docstruct)
83 (bib (assq 'bib rest))
84 (thebib (assq 'thebib rest))
85 (bibmem (memq bib rest))
86 (thebibmem (memq thebib rest)))
87 (when (not (or thebib bib))
88 (setq bib (assq 'bib docstruct)
89 thebib (assq 'thebib docstruct)
90 bibmem (memq bib docstruct)
91 thebibmem (memq thebib docstruct)))
92 (if (> (length bibmem) (length thebibmem))
94 (if thebib 'thebib nil))))
96 (defun reftex-get-bibfile-list ()
97 ;; Return list of bibfiles for current document.
98 ;; When using the chapterbib or bibunits package you should either
99 ;; use the same database files everywhere, or separate parts using
100 ;; different databases into different files (included into the mater file).
101 ;; Then this function will return the applicable database files.
103 ;; Ensure access to scanning info
104 (reftex-access-scan-info)
106 ;; Try inside this file (and its includes)
107 (cdr (reftex-last-assoc-before-elt
108 'bib (list 'eof (buffer-file-name))
109 (member (list 'bof (buffer-file-name))
110 (symbol-value reftex-docstruct-symbol))))
111 ;; Try after the beginning of this file
112 (cdr (assq 'bib (member (list 'bof (buffer-file-name))
113 (symbol-value reftex-docstruct-symbol))))
114 ;; Anywhere in the entire document
115 (cdr (assq 'bib (symbol-value reftex-docstruct-symbol)))
116 (error "\\bibliography statement missing or .bib files not found")))
118 ;; Find a certain reference in any of the BibTeX files.
120 (defun reftex-pop-to-bibtex-entry (key file-list &optional mark-to-kill
121 highlight item return)
122 ;; Find BibTeX KEY in any file in FILE-LIST in another window.
123 ;; If MARK-TO-KILL is non-nil, mark new buffer to kill.
124 ;; If HIGHLIGHT is non-nil, highlight the match.
125 ;; If ITEM in non-nil, search for bibitem instead of database entry.
126 ;; If RETURN is non-nil, just return the entry and restore point.
130 (concat "\\\\bibitem[ \t]*\\(\\[[^]]*\\]\\)?[ \t]*{"
131 (regexp-quote key) "}")
132 (concat "@\\(?:\\w\\|\\s_\\)+[ \t\n\r]*[{(][ \t\n\r]*"
133 (regexp-quote key) "[, \t\r\n}]")))
134 (buffer-conf (current-buffer))
139 (setq file (car file-list)
140 file-list (cdr file-list))
141 (unless (setq buf (reftex-get-file-buffer-force file mark-to-kill))
142 (error "No such file %s" file))
144 (setq oldpos (point))
146 (goto-char (point-min))
147 (if (not (re-search-forward re nil t))
148 (goto-char oldpos) ;; restore previous position of point
149 (goto-char (match-beginning 0))
152 ;; Just return the relevant entry
153 (if item (goto-char (match-end 0)))
154 (setq return (buffer-substring
155 (point) (reftex-end-of-bib-entry item)))
156 (goto-char oldpos) ;; restore point.
157 (set-buffer buffer-conf)
158 (throw 'exit return))
159 (switch-to-buffer-other-window buf)
163 (reftex-highlight 0 (match-beginning 0) (match-end 0)))
164 (throw 'exit (selected-window))))
165 (set-buffer buffer-conf)
167 (error "No \\bibitem with citation key %s" key)
168 (error "No BibTeX entry with citation key %s" key)))))
170 (defun reftex-end-of-bib-entry (item)
176 "\\\\bibitem\\|\\end{thebibliography}")
177 (1- (match-beginning 0)))
178 (progn (forward-list 1) (point)))
179 (error (min (point-max) (+ 300 (point)))))))
181 ;; Parse bibtex buffers
183 (defun reftex-extract-bib-entries (buffers)
184 ;; Extract bib entries which match regexps from BUFFERS.
185 ;; BUFFERS is a list of buffers or file names.
186 ;; Return list with entries."
187 (let* (re-list first-re rest-re
188 (buffer-list (if (listp buffers) buffers (list buffers)))
189 found-list entry buffer1 buffer alist
190 key-point start-point end-point default)
192 ;; Read a regexp, completing on known citation keys.
193 (setq default (regexp-quote (reftex-get-bibkey-default)))
198 "Regex { && Regex...}: "
201 (if (fboundp 'LaTeX-bibitem-list)
203 (cdr (assoc 'bibview-cache
204 (symbol-value reftex-docstruct-symbol))))
206 nil nil nil 'reftex-cite-regexp-hist)
209 (if (or (null re-list ) (equal re-list '("")))
210 (setq re-list (list default)))
212 (setq first-re (car re-list) ; We'll use the first re to find things,
213 rest-re (cdr re-list)) ; the others to narrow down.
214 (if (string-match "\\`[ \t]*\\'" (or first-re ""))
215 (error "Empty regular expression"))
218 (save-window-excursion
220 ;; Walk through all bibtex files
222 (setq buffer (car buffer-list)
223 buffer-list (cdr buffer-list))
224 (if (and (bufferp buffer)
225 (buffer-live-p buffer))
226 (setq buffer1 buffer)
227 (setq buffer1 (reftex-get-file-buffer-force
228 buffer (not reftex-keep-temporary-buffers))))
230 (message "No such BibTeX file %s (ignored)" buffer)
231 (message "Scanning bibliography database %s" buffer1)
232 (unless (verify-visited-file-modtime buffer1)
234 (format "File %s changed on disk. Reread from disk? "
235 (file-name-nondirectory
236 (buffer-file-name buffer1))))
237 (with-current-buffer buffer1 (revert-buffer t t)))))
240 (reftex-with-special-syntax-for-bib
242 (goto-char (point-min))
243 (while (re-search-forward first-re nil t)
245 (setq key-point (point))
246 (unless (re-search-backward "\\(\\`\\|[\n\r]\\)[ \t]*\
247 @\\(\\(?:\\w\\|\\s_\\)+\\)[ \t\n\r]*[{(]" nil t)
248 (throw 'search-again nil))
249 (setq start-point (point))
250 (goto-char (match-end 0))
253 (error (goto-char key-point)
254 (throw 'search-again nil)))
255 (setq end-point (point))
257 ;; Ignore @string, @comment and @c entries or things
259 (when (or (string= (downcase (match-string 2)) "string")
260 (string= (downcase (match-string 2)) "comment")
261 (string= (downcase (match-string 2)) "c")
262 (< (point) key-point)) ; this means match not in {}
263 (goto-char key-point)
264 (throw 'search-again nil))
266 ;; Well, we have got a match
267 ;;(setq entry (concat
268 ;; (buffer-substring start-point (point)) "\n"))
269 (setq entry (buffer-substring start-point (point)))
271 ;; Check if other regexp match as well
272 (setq re-list rest-re)
274 (unless (string-match (car re-list) entry)
276 (throw 'search-again nil))
279 (setq alist (reftex-parse-bibtex-entry
280 nil start-point end-point))
281 (push (cons "&entry" entry) alist)
283 ;; check for crossref entries
284 (if (assoc "crossref" alist)
287 alist (reftex-get-crossref-alist alist))))
290 (push (cons "&formatted" (reftex-format-bib-entry alist))
293 ;; make key the first element
294 (push (reftex-get-bib-field "&key" alist) alist)
296 ;; add it to the list
297 (push alist found-list)))))
298 (reftex-kill-temporary-buffers))))
299 (setq found-list (nreverse found-list))
303 ((eq 'author reftex-sort-bibtex-matches)
304 (sort found-list 'reftex-bib-sort-author))
305 ((eq 'year reftex-sort-bibtex-matches)
306 (sort found-list 'reftex-bib-sort-year))
307 ((eq 'reverse-year reftex-sort-bibtex-matches)
308 (sort found-list 'reftex-bib-sort-year-reverse))
311 (defun reftex-bib-sort-author (e1 e2)
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)))
317 (if (and (stringp (car al1))
319 (string< (car al1) (car al2))
320 (not (stringp (car al1))))))
322 (defun reftex-bib-sort-year (e1 e2)
323 (< (string-to-number (or (cdr (assoc "year" e1)) "0"))
324 (string-to-number (or (cdr (assoc "year" e2)) "0"))))
326 (defun reftex-bib-sort-year-reverse (e1 e2)
327 (> (string-to-number (or (cdr (assoc "year" e1)) "0"))
328 (string-to-number (or (cdr (assoc "year" e2)) "0"))))
330 (defun reftex-get-crossref-alist (entry)
331 ;; return the alist from a crossref entry
332 (let ((crkey (cdr (assoc "crossref" entry)))
337 (if (re-search-forward
338 (concat "@\\w+[{(][ \t\n\r]*" (regexp-quote crkey)
339 "[ \t\n\r]*,") nil t)
341 (setq start (match-beginning 0))
345 (reftex-parse-bibtex-entry nil start (point)))
348 ;; Parse the bibliography environment
349 (defun reftex-extract-bib-entries-from-thebibliography (files)
350 ;; Extract bib-entries from the \begin{thebibliography} environment.
351 ;; Parsing is not as good as for the BibTeX database stuff.
352 ;; The environment should be located in file FILE.
354 (let* (start end buf entries re re-list file default)
356 (error "Need file name to find thebibliography environment"))
357 (while (setq file (pop files))
358 (setq buf (reftex-get-file-buffer-force
359 file (not reftex-keep-temporary-buffers)))
361 (error "No such file %s" file))
362 (message "Scanning thebibliography environment in %s" file)
364 (with-current-buffer buf
368 (goto-char (point-min))
369 (while (re-search-forward
370 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
371 (beginning-of-line 2)
373 (if (re-search-forward
374 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\end{thebibliography}" nil t)
376 (beginning-of-line 1)
378 (when (and start end)
381 (mapcar 'reftex-parse-bibitem
384 (buffer-substring-no-properties
386 "[ \t\n\r]*\\\\bibitem[ \t]*\
387 \\(\\[[^]]*]\\)*\[ \t]*"))))))
390 (error "No bibitems found"))
392 ;; Read a regexp, completing on known citation keys.
393 (setq default (regexp-quote (reftex-get-bibkey-default)))
398 "Regex { && Regex...}: "
401 (if (fboundp 'LaTeX-bibitem-list)
403 (cdr (assoc 'bibview-cache
404 (symbol-value reftex-docstruct-symbol))))
406 nil nil nil 'reftex-cite-regexp-hist)
409 (if (or (null re-list ) (equal re-list '("")))
410 (setq re-list (list default)))
412 (if (string-match "\\`[ \t]*\\'" (car re-list))
413 (error "Empty regular expression"))
415 (while (and (setq re (pop re-list)) entries)
419 (if (string-match re (cdr (assoc "&entry" x)))
425 (push (cons "&formatted" (reftex-format-bibitem x)) x)
426 (push (reftex-get-bib-field "&key" x) x)
432 (defun reftex-get-bibkey-default ()
433 ;; Return the word before the cursor. If the cursor is in a
434 ;; citation macro, return the word before the macro.
435 (let* ((macro (reftex-what-macro 1)))
437 (if (and macro (string-match "cite" (car macro)))
438 (goto-char (cdr macro)))
439 (skip-chars-backward "^a-zA-Z0-9")
440 (reftex-this-word))))
442 ;; Parse and format individual entries
444 (defun reftex-get-bib-names (field entry)
445 ;; Return a list with the author or editor names in ENTRY
446 (let ((names (reftex-get-bib-field field entry)))
448 (setq names (reftex-get-bib-field "editor" entry)))
449 (while (string-match "\\band\\b[ \t]*" names)
450 (setq names (replace-match "\n" nil t names)))
451 (while (string-match "[\\.a-zA-Z\\-]+\\.[ \t]*\\|,.*\\|[{}]+" names)
452 (setq names (replace-match "" nil t names)))
453 (while (string-match "^[ \t]+\\|[ \t]+$" names)
454 (setq names (replace-match "" nil t names)))
455 (while (string-match "[ \t][ \t]+" names)
456 (setq names (replace-match " " nil t names)))
457 (split-string names "\n")))
459 (defun reftex-parse-bibtex-entry (entry &optional from to raw)
460 ; if RAW is non-nil, keep double quotes/curly braces delimiting fields
461 (let (alist key start field)
466 (set-buffer (get-buffer-create " *RefTeX-scratch*"))
468 (set-syntax-table reftex-syntax-table-for-bib)
472 (if (and from to) (narrow-to-region from to)))
473 (goto-char (point-min))
475 (if (re-search-forward "@\\(\\(?:\\w\\|\\s_\\)+\\)[ \t\n\r]*\
476 \[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
479 (cons "&type" (downcase (reftex-match-string 1)))
480 (cons "&key" (reftex-match-string 2)))))
481 (while (re-search-forward "\\(\\(?:\\w\\|-\\)+\\)[ \t\n\r]*=[ \t\n\r]*"
483 (setq key (downcase (reftex-match-string 1)))
485 ((= (following-char) ?{)
496 ((= (following-char) ?\")
503 (setq start (point))))
504 (while (and (search-forward "\"" nil t)
505 (= ?\\ (char-after (- (point) 2))))))
508 (re-search-forward "[ \t]*[\n\r,}]" nil 1)))
509 ;; extract field value, ignore trailing comma if in RAW mode
510 (let ((stop (if (and raw (not (= (char-after (1- (point))) ?,)))
513 (setq field (buffer-substring-no-properties start stop)))
514 ;; remove extra whitespace
515 (while (string-match "[\n\t\r]\\|[ \t][ \t]+" field)
516 (setq field (replace-match " " nil t field)))
517 ;; remove leading garbage
518 (if (string-match (if raw "^[ \t]+" "^[ \t{]+") field)
519 (setq field (replace-match "" nil t field)))
520 ;; remove trailing garbage
521 (if (string-match (if raw "[ \t]+$" "[ \t}]+$") field)
522 (setq field (replace-match "" nil t field)))
523 (push (cons key field) alist))))
526 (defun reftex-get-bib-field (fieldname entry &optional format)
527 ;; Extract the field FIELDNAME from an ENTRY
528 (let ((cell (assoc fieldname entry)))
531 (format format (cdr cell))
535 (defun reftex-format-bib-entry (entry)
536 ;; Format a BibTeX ENTRY so that it is nice to look at
538 ((auth-list (reftex-get-bib-names "author" entry))
539 (authors (mapconcat 'identity auth-list ", "))
540 (year (reftex-get-bib-field "year" entry))
541 (title (reftex-get-bib-field "title" entry))
542 (type (reftex-get-bib-field "&type" entry))
543 (key (reftex-get-bib-field "&key" entry))
546 ((equal type "article")
547 (concat (reftex-get-bib-field "journal" entry) " "
548 (reftex-get-bib-field "volume" entry) ", "
549 (reftex-get-bib-field "pages" entry)))
551 (concat "book (" (reftex-get-bib-field "publisher" entry) ")"))
552 ((equal type "phdthesis")
553 (concat "PhD: " (reftex-get-bib-field "school" entry)))
554 ((equal type "mastersthesis")
555 (concat "Master: " (reftex-get-bib-field "school" entry)))
556 ((equal type "inbook")
557 (concat "Chap: " (reftex-get-bib-field "chapter" entry)
558 ", pp. " (reftex-get-bib-field "pages" entry)))
559 ((or (equal type "conference")
560 (equal type "incollection")
561 (equal type "inproceedings"))
562 (reftex-get-bib-field "booktitle" entry "in: %s"))
564 (setq authors (reftex-truncate authors 30 t t))
565 (when (reftex-use-fonts)
566 (put-text-property 0 (length key) 'face reftex-label-face
568 (put-text-property 0 (length authors) 'face reftex-bib-author-face
570 (put-text-property 0 (length year) 'face reftex-bib-year-face
572 (put-text-property 0 (length title) 'face reftex-bib-title-face
574 (put-text-property 0 (length extra) 'face reftex-bib-extra-face
576 (concat key "\n " authors " " year " " extra "\n " title "\n\n")))
578 (defun reftex-parse-bibitem (item)
579 ;; Parse a \bibitem entry
580 (let ((key "") (text ""))
581 (when (string-match "\\`{\\([^}]+\\)}\\([^\000]*\\)" item)
582 (setq key (match-string 1 item)
583 text (match-string 2 item)))
584 ;; Clean up the text a little bit
585 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
586 (setq text (replace-match " " nil t text)))
587 (if (string-match "\\`[ \t]+" text)
588 (setq text (replace-match "" nil t text)))
592 (cons "&entry" (concat key " " text)))))
594 (defun reftex-format-bibitem (item)
595 ;; Format a \bibitem entry so that it is (relatively) nice to look at.
596 (let ((text (reftex-get-bib-field "&text" item))
597 (key (reftex-get-bib-field "&key" item))
600 ;; Wrap the text into several lines.
601 (while (and (> (length text) 70)
602 (string-match " " (substring text 60)))
603 (push (substring text 0 (+ 60 (match-beginning 0))) lines)
604 (setq text (substring text (+ 61 (match-beginning 0)))))
606 (setq text (mapconcat 'identity (nreverse lines) "\n "))
608 (when (reftex-use-fonts)
609 (put-text-property 0 (length text) 'face reftex-bib-author-face text))
610 (concat key "\n " text "\n\n")))
615 (defun reftex-citation (&optional no-insert format-key)
616 "Make a citation using BibTeX database files.
617 After prompting for a regular expression, scans the buffers with
618 bibtex entries (taken from the \\bibliography command) and offers the
619 matching entries for selection. The selected entry is formatted according
620 to `reftex-cite-format' and inserted into the buffer.
622 If NO-INSERT is non-nil, nothing is inserted, only the selected key returned.
624 FORMAT-KEY can be used to pre-select a citation format.
626 When called with a `C-u' prefix, prompt for optional arguments in
627 cite macros. When called with a numeric prefix, make that many
628 citations. When called with point inside the braces of a `\\cite'
629 command, it will add another key, ignoring the value of
630 `reftex-cite-format'.
632 The regular expression uses an expanded syntax: && is interpreted as `and'.
633 Thus, `aaaa&&bbb' matches entries which contain both `aaaa' and `bbb'.
634 While entering the regexp, completion on knows citation keys is possible.
635 `=' is a good regular expression to match all entries in all files."
639 ;; check for recursive edit
640 (reftex-check-recursive-edit)
642 ;; This function may also be called outside reftex-mode.
643 ;; Thus look for the scanning info only if in reftex-mode.
646 (reftex-access-scan-info nil))
648 ;; Call reftex-do-citation, but protected
650 (reftex-do-citation current-prefix-arg no-insert format-key)
651 (reftex-kill-temporary-buffers)))
653 (defun reftex-do-citation (&optional arg no-insert format-key)
654 ;; This really does the work of reftex-citation.
656 (let* ((format (reftex-figure-out-cite-format arg no-insert format-key))
657 (docstruct-symbol reftex-docstruct-symbol)
658 (selected-entries (reftex-offer-bib-menu))
659 (insert-entries selected-entries)
660 entry string cite-view)
662 (unless selected-entries (error "Quit"))
664 (if (stringp selected-entries)
666 (setq insert-entries (list (list selected-entries
667 (cons "&key" selected-entries)))
668 selected-entries nil)
669 ;; It makes sense to compute the cite-view strings.
672 (when (eq (car selected-entries) 'concat)
673 ;; All keys go into a single command - we need to trick a little
674 ;; FIXME: Unfortunately, this means that commenting does not work right.
675 (pop selected-entries)
676 (let ((concat-keys (mapconcat 'car selected-entries
677 reftex-cite-key-separator)))
679 (list (list concat-keys (cons "&key" concat-keys))))))
683 ;; We shall insert this into the buffer...
684 (message "Formatting...")
686 (while (setq entry (pop insert-entries))
687 ;; Format the citation and insert it
688 (setq string (if reftex-format-cite-function
689 (funcall reftex-format-cite-function
690 (reftex-get-bib-field "&key" entry)
692 (reftex-format-citation entry format)))
693 (when (or (eq reftex-cite-prompt-optional-args t)
694 (and reftex-cite-prompt-optional-args
696 (let ((start 0) (nth 0) value)
697 (while (setq start (string-match "\\[\\]" string start))
698 (setq value (save-match-data
699 (read-string (format "Optional argument %d: "
700 (setq nth (1+ nth))))))
701 (setq string (replace-match (concat "[" value "]") t t string))
702 (setq start (1+ start)))))
703 ;; Should we cleanup empty optional arguments?
704 ;; if the first is empty, it can be removed. If the second is empty,
705 ;; it has to go. If there is only a single arg and empty, it can go
707 (when reftex-cite-cleanup-optional-args
709 ((string-match "\\([a-zA-Z0-9]\\)\\[\\]{" string)
710 (setq string (replace-match "\\1{" nil nil string)))
711 ((string-match "\\[\\]\\(\\[[a-zA-Z0-9., ]+\\]\\)" string)
712 (setq string (replace-match "\\1" nil nil string)))
713 ((string-match "\\[\\]\\[\\]" string)
714 (setq string (replace-match "" t t string)))))
717 ;; Reposition cursor?
718 (when (string-match "\\?" string)
719 (search-backward "?")
723 (when (and reftex-mode
724 (fboundp 'LaTeX-add-bibitems)
725 reftex-plug-into-AUCTeX)
726 (apply 'LaTeX-add-bibitems (mapcar 'car selected-entries)))
728 ;; Produce the cite-view strings
729 (when (and reftex-mode reftex-cache-cite-echo cite-view)
730 (mapc (lambda (entry)
731 (reftex-make-cite-echo-string entry docstruct-symbol))
736 (set-marker reftex-select-return-marker nil)
737 (reftex-kill-buffer "*RefTeX Select*")
739 ;; Check if the prefix arg was numeric, and call recursively
743 (skip-chars-backward "}")
745 (reftex-do-citation arg))
748 ;; Return the citation key
749 (mapcar 'car selected-entries)))
751 (defun reftex-figure-out-cite-format (arg &optional no-insert format-key)
752 ;; Check if there is already a cite command at point and change cite format
753 ;; in order to only add another reference in the same cite command.
754 (let ((macro (car (reftex-what-macro 1)))
755 (cite-format-value (reftex-get-cite-format))
759 ;; Format does not really matter because nothing will be inserted.
762 ((and (stringp macro)
763 (string-match "\\`\\\\cite\\|cite\\'" macro))
764 ;; We are already inside a cite macro
765 (if (or (not arg) (not (listp arg)))
768 (if (member (preceding-char) '(?\{ ?,))
770 reftex-cite-key-separator)
772 (if (member (following-char) '(?\} ?,))
774 reftex-cite-key-separator)))
777 ;; Figure out the correct format
779 (if (and (symbolp cite-format-value)
780 (assq cite-format-value reftex-cite-format-builtin))
781 (nth 2 (assq cite-format-value reftex-cite-format-builtin))
786 (reftex-select-with-char
787 "" (concat "SELECT A CITATION FORMAT\n\n"
790 (format "[%c] %s %s" (car x)
791 (if (> (car x) 31) " " "")
794 (if (assq key format)
795 (setq format (cdr (assq key format)))
796 (error "No citation format associated with key `%c'" key)))))
799 (defun reftex-citep ()
800 "Call `reftex-citation' with a format selector `?p'."
802 (reftex-citation nil ?p))
804 (defun reftex-citet ()
805 "Call `reftex-citation' with a format selector `?t'."
807 (reftex-citation nil ?t))
809 (defvar reftex-select-bib-map)
810 (defun reftex-offer-bib-menu ()
811 ;; Offer bib menu and return list of selected items
813 (let ((bibtype (reftex-bib-or-thebib))
814 found-list rtn key data selected-entries)
822 ; ((assq 'bib (symbol-value reftex-docstruct-symbol))
823 ;; using BibTeX database files.
824 (reftex-extract-bib-entries (reftex-get-bibfile-list)))
825 ((eq bibtype 'thebib)
826 ; ((assq 'thebib (symbol-value reftex-docstruct-symbol))
827 ;; using thebibliography environment.
828 (reftex-extract-bib-entries-from-thebibliography
832 'thebib (symbol-value reftex-docstruct-symbol))))))
833 (reftex-default-bibliography
834 (message "Using default bibliography")
835 (reftex-extract-bib-entries (reftex-default-bibliography)))
836 (t (error "No valid bibliography in this document, and no default available"))))
839 (error "Sorry, no matches found"))
841 ;; Remember where we came from
842 (setq reftex-call-back-to-this-buffer (current-buffer))
843 (set-marker reftex-select-return-marker (point))
846 (save-window-excursion
847 (delete-other-windows)
848 (reftex-kill-buffer "*RefTeX Select*")
849 (switch-to-buffer-other-window "*RefTeX Select*")
850 (unless (eq major-mode 'reftex-select-bib-mode)
851 (reftex-select-bib-mode))
852 (let ((buffer-read-only nil))
854 (reftex-insert-bib-matches found-list))
855 (setq buffer-read-only t)
856 (if (= 0 (buffer-size))
857 (error "No matches found"))
858 (setq truncate-lines t)
863 reftex-citation-prompt
865 reftex-select-bib-map
867 'reftex-bibtex-selection-callback nil))
870 (unless key (throw 'done t))
876 ;; Restrict with new regular expression
877 (setq found-list (reftex-restrict-bib-matches found-list))
878 (let ((buffer-read-only nil))
880 (reftex-insert-bib-matches found-list))
884 (setq selected-entries
885 (if reftex-select-marked
886 (mapcar 'car (nreverse reftex-select-marked))
890 ;; Take all (marked), and push the symbol 'concat
891 (setq selected-entries
893 (if reftex-select-marked
894 (mapcar 'car (nreverse reftex-select-marked))
898 ;; Take all (marked), and push the symbol 'concat
899 (reftex-extract-bib-file found-list reftex-select-marked)
900 (setq selected-entries "BibTeX database file created")
903 ;; Take all (marked), and push the symbol 'concat
904 (reftex-extract-bib-file found-list reftex-select-marked
906 (setq selected-entries "BibTeX database file created")
911 (setq selected-entries
912 (if reftex-select-marked
914 (mapcar 'car (nreverse reftex-select-marked)))
915 (if data (list data) nil)))
918 ;; Got this one with completion
919 (setq selected-entries key)
925 (defun reftex-restrict-bib-matches (found-list)
926 ;; Limit FOUND-LIST with more regular expressions
927 (let ((re-list (split-string (read-string
928 "RegExp [ && RegExp...]: "
929 nil 'reftex-cite-regexp-hist)
931 (found-list-r found-list)
933 (while (setq re (pop re-list))
939 re (cdr (assoc "&entry" x)))
948 (defun reftex-extract-bib-file (all &optional marked complement)
949 ;; Limit FOUND-LIST with more regular expressions
950 (let ((file (read-file-name "File to create: ")))
951 (find-file-other-window file)
952 (if (> (buffer-size) 0)
954 (format "Overwrite non-empty file %s? " file))
961 (if (or (and (assoc x marked) (not complement))
962 (and (not (assoc x marked)) complement))
963 (cdr (assoc "&entry" x))
965 (cdr (assoc "&entry" x))))
967 (insert (mapconcat 'identity all "\n\n"))
969 (goto-char (point-min))))
971 (defun reftex-insert-bib-matches (list)
972 ;; Insert the bib matches and number them correctly
974 (if (memq reftex-highlight-selection '(mouse both))
975 reftex-mouse-selected-face
980 (setq tmp (cdr (assoc "&formatted" x))
982 (put-text-property 0 len :data x tmp)
983 (put-text-property 0 (1- len) 'mouse-face mouse-face tmp)
986 (run-hooks 'reftex-display-copied-context-hook))
988 (defun reftex-format-names (namelist n)
989 (let (last (len (length namelist)))
990 (if (= n 0) (setq n len))
993 ((= 1 len) (car namelist))
994 ((> len n) (concat (car namelist) (nth 2 reftex-cite-punctuation)))
997 last (nth (1- n) namelist))
998 (setcdr (nthcdr (- n 2) namelist) nil)
1000 (mapconcat 'identity namelist (nth 0 reftex-cite-punctuation))
1001 (nth 1 reftex-cite-punctuation)
1004 (defun reftex-format-citation (entry format)
1005 ;; Format a citation from the info in the BibTeX ENTRY
1007 (unless (stringp format) (setq format "\\cite{%l}"))
1009 (if (and reftex-comment-citations
1010 (string-match "%l" reftex-cite-comment-format))
1011 (error "reftex-cite-comment-format contains invalid %%l"))
1013 (while (string-match
1014 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
1016 (let ((n (string-to-number (match-string 4 format)))
1017 (l (string-to-char (match-string 5 format)))
1023 (reftex-get-bib-field "&key" entry)
1024 (if reftex-comment-citations
1025 reftex-cite-comment-format
1027 ((= l ?a) (reftex-format-names
1028 (reftex-get-bib-names "author" entry)
1030 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
1031 ((= l ?b) (reftex-get-bib-field "booktitle" entry "in: %s"))
1032 ((= l ?B) (reftex-abbreviate-title
1033 (reftex-get-bib-field "booktitle" entry "in: %s")))
1034 ((= l ?c) (reftex-get-bib-field "chapter" entry))
1035 ((= l ?d) (reftex-get-bib-field "edition" entry))
1036 ((= l ?e) (reftex-format-names
1037 (reftex-get-bib-names "editor" entry)
1039 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
1040 ((= l ?h) (reftex-get-bib-field "howpublished" entry))
1041 ((= l ?i) (reftex-get-bib-field "institution" entry))
1042 ((= l ?j) (reftex-get-bib-field "journal" entry))
1043 ((= l ?k) (reftex-get-bib-field "key" entry))
1044 ((= l ?m) (reftex-get-bib-field "month" entry))
1045 ((= l ?n) (reftex-get-bib-field "number" entry))
1046 ((= l ?o) (reftex-get-bib-field "organization" entry))
1047 ((= l ?p) (reftex-get-bib-field "pages" entry))
1048 ((= l ?P) (car (split-string
1049 (reftex-get-bib-field "pages" entry)
1051 ((= l ?s) (reftex-get-bib-field "school" entry))
1052 ((= l ?u) (reftex-get-bib-field "publisher" entry))
1053 ((= l ?r) (reftex-get-bib-field "address" entry))
1054 ((= l ?t) (reftex-get-bib-field "title" entry))
1055 ((= l ?T) (reftex-abbreviate-title
1056 (reftex-get-bib-field "title" entry)))
1057 ((= l ?v) (reftex-get-bib-field "volume" entry))
1058 ((= l ?y) (reftex-get-bib-field "year" entry)))))
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)))
1070 (defun reftex-make-cite-echo-string (entry docstruct-symbol)
1071 ;; Format a bibtex entry for the echo area and cache the result.
1072 (let* ((key (reftex-get-bib-field "&key" entry))
1074 (let* ((reftex-cite-punctuation '(" " " & " " etal.")))
1075 (reftex-format-citation entry reftex-cite-view-format)))
1076 (cache (assq 'bibview-cache (symbol-value docstruct-symbol)))
1077 (cache-entry (assoc key (cdr cache))))
1079 ;; This docstruct has no cache - make one.
1080 (set docstruct-symbol (cons (cons 'bibview-cache nil)
1081 (symbol-value docstruct-symbol))))
1082 (when reftex-cache-cite-echo
1083 (setq key (copy-sequence key))
1084 (set-text-properties 0 (length key) nil key)
1085 (set-text-properties 0 (length string) nil string)
1087 (unless (string= (cdr cache-entry) string)
1088 (setcdr cache-entry string)
1089 (put reftex-docstruct-symbol 'modified t))
1090 (push (cons key string) (cdr cache))
1091 (put reftex-docstruct-symbol 'modified t)))
1094 (defun reftex-bibtex-selection-callback (data ignore no-revisit)
1095 ;; Callback function to be called from the BibTeX selection, in
1096 ;; order to display context. This function is relatively slow and not
1097 ;; recommended for follow mode. It works OK for individual lookups.
1098 (let ((win (selected-window))
1099 (key (reftex-get-bib-field "&key" data))
1100 bibfile-list item bibtype)
1103 (with-current-buffer reftex-call-back-to-this-buffer
1104 (setq bibtype (reftex-bib-or-thebib))
1107 ; ((assq 'bib (symbol-value reftex-docstruct-symbol))
1108 (setq bibfile-list (reftex-get-bibfile-list)))
1109 ((eq bibtype 'thebib)
1110 ; ((assq 'thebib (symbol-value reftex-docstruct-symbol))
1115 'thebib (symbol-value reftex-docstruct-symbol))))
1117 (reftex-default-bibliography
1118 (setq bibfile-list (reftex-default-bibliography)))
1119 (t (ding) (throw 'exit nil))))
1122 (setq bibfile-list (reftex-visited-files bibfile-list)))
1125 (reftex-pop-to-bibtex-entry
1126 key bibfile-list (not reftex-keep-temporary-buffers) t item)
1129 (select-window win)))
1131 ;;; Global BibTeX file
1132 (defun reftex-all-used-citation-keys ()
1133 (reftex-access-scan-info)
1134 (let ((files (reftex-all-document-files)) file keys kk k)
1135 (save-current-buffer
1136 (while (setq file (pop files))
1137 (set-buffer (reftex-get-file-buffer-force file 'mark))
1141 (goto-char (point-min))
1142 (while (re-search-forward "\\(?:^\\|\\=\\)[^%\n\r]*?\\\\\\(bibentry\\|[a-zA-Z]*cite[a-zA-Z]*\\)\\(\\[[^\\]]*\\]\\)?{\\([^}]+\\)}" nil t)
1143 (setq kk (match-string-no-properties 3))
1144 (while (string-match "%.*\n?" kk)
1145 (setq kk (replace-match "" t t kk)))
1146 (setq kk (split-string kk "[, \t\r\n]+"))
1147 (while (setq k (pop kk))
1149 (setq keys (cons k keys)))))))))
1150 (reftex-kill-temporary-buffers)
1153 (defun reftex-get-string-refs (alist)
1154 "Return a list of BibTeX @string references that appear as values in ALIST."
1155 (reftex-remove-if (lambda (x) (string-match "^\\([\"{]\\|[0-9]+$\\)" x))
1156 ;; get list of values, discard keys
1158 ;; remove &key and &type entries
1159 (reftex-remove-if (lambda (pair)
1160 (string-match "^&" (car pair)))
1163 (defun reftex-create-bibtex-file (bibfile)
1164 "Create a new BibTeX database file with all entries referenced in document.
1165 The command prompts for a filename and writes the collected
1166 entries to that file. Only entries referenced in the current
1167 document with any \\cite-like macros are used. The sequence in
1168 the new file is the same as it was in the old database.
1170 Entries referenced from other entries must appear after all
1171 referencing entries.
1173 You can define strings to be used as header or footer for the
1174 created files in the variables `reftex-create-bibtex-header' or
1175 `reftex-create-bibtex-footer' respectively."
1176 (interactive "FNew BibTeX file: ")
1177 (let ((keys (reftex-all-used-citation-keys))
1178 (files (reftex-get-bibfile-list))
1179 file key entries beg end entry string-keys string-entries)
1180 (save-current-buffer
1181 (dolist (file files)
1182 (set-buffer (reftex-get-file-buffer-force file 'mark))
1183 (reftex-with-special-syntax-for-bib
1187 (goto-char (point-min))
1188 (while (re-search-forward "^[ \t]*@\\(?:\\w\\|\\s_\\)+[ \t\n\r]*\
1189 \[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
1190 (setq key (match-string 1)
1191 beg (match-beginning 0)
1193 (goto-char (match-beginning 1))
1196 (error (goto-char (match-end 0))))
1198 (when (member key keys)
1199 (setq entry (buffer-substring beg end)
1200 entries (cons entry entries)
1201 keys (delete key keys))
1203 ;; check for crossref entries
1204 (let* ((attr-list (reftex-parse-bibtex-entry nil beg end))
1205 (xref-key (cdr (assoc "crossref" attr-list))))
1206 (if xref-key (pushnew xref-key keys)))
1207 ;; check for string references
1208 (let* ((raw-fields (reftex-parse-bibtex-entry nil beg end t))
1209 (string-fields (reftex-get-string-refs raw-fields)))
1210 (dolist (skey string-fields)
1211 (unless (member skey string-keys)
1212 (push skey string-keys)))))))))))
1213 ;; second pass: grab @string references
1215 (save-current-buffer
1216 (dolist (file files)
1217 (set-buffer (reftex-get-file-buffer-force file 'mark))
1218 (reftex-with-special-syntax-for-bib
1222 (goto-char (point-min))
1223 (while (re-search-forward
1224 "^[ \t]*@[Ss][Tt][Rr][Ii][Nn][Gg][ \t]*{[ \t]*\\([^ \t\r\n]+\\)"
1226 (setq key (match-string 1)
1227 beg (match-beginning 0)
1229 (goto-char (match-beginning 1))
1232 (error (goto-char (match-end 0))))
1234 (when (member key string-keys)
1235 (setq entry (buffer-substring beg end)
1236 string-entries (cons entry string-entries)
1237 string-keys (delete key string-keys))))))))))
1238 (find-file-other-window bibfile)
1239 (if (> (buffer-size) 0)
1240 (unless (yes-or-no-p
1241 (format "Overwrite non-empty file %s? " bibfile))
1244 (if reftex-create-bibtex-header (insert reftex-create-bibtex-header "\n\n"))
1245 (insert (mapconcat 'identity (reverse string-entries) "\n\n"))
1246 (if string-entries (insert "\n\n\n"))
1247 (insert (mapconcat 'identity (reverse entries) "\n\n"))
1248 (if reftex-create-bibtex-footer (insert "\n\n" reftex-create-bibtex-footer))
1249 (goto-char (point-min))
1251 (message "%d entries extracted and copied to new database"
1255 ;;; reftex-cite.el ends here