1 ;;; reftex-cite.el --- creating citations with RefTeX
3 ;; Copyright (C) 1997-2013 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 (push (cons key field
) alist
))))
520 (defun reftex-get-bib-field (fieldname entry
&optional format
)
521 ;; Extract the field FIELDNAME from an ENTRY
522 (let ((cell (assoc fieldname entry
)))
525 (format format
(cdr cell
))
529 (defun reftex-format-bib-entry (entry)
530 ;; Format a BibTeX ENTRY so that it is nice to look at
532 ((auth-list (reftex-get-bib-names "author" entry
))
533 (authors (mapconcat 'identity auth-list
", "))
534 (year (reftex-get-bib-field "year" entry
))
535 (title (reftex-get-bib-field "title" entry
))
536 (type (reftex-get-bib-field "&type" entry
))
537 (key (reftex-get-bib-field "&key" entry
))
540 ((equal type
"article")
541 (concat (reftex-get-bib-field "journal" entry
) " "
542 (reftex-get-bib-field "volume" entry
) ", "
543 (reftex-get-bib-field "pages" entry
)))
545 (concat "book (" (reftex-get-bib-field "publisher" entry
) ")"))
546 ((equal type
"phdthesis")
547 (concat "PhD: " (reftex-get-bib-field "school" entry
)))
548 ((equal type
"mastersthesis")
549 (concat "Master: " (reftex-get-bib-field "school" entry
)))
550 ((equal type
"inbook")
551 (concat "Chap: " (reftex-get-bib-field "chapter" entry
)
552 ", pp. " (reftex-get-bib-field "pages" entry
)))
553 ((or (equal type
"conference")
554 (equal type
"incollection")
555 (equal type
"inproceedings"))
556 (reftex-get-bib-field "booktitle" entry
"in: %s"))
558 (setq authors
(reftex-truncate authors
30 t t
))
559 (when (reftex-use-fonts)
560 (put-text-property 0 (length key
) 'face reftex-label-face
562 (put-text-property 0 (length authors
) 'face reftex-bib-author-face
564 (put-text-property 0 (length year
) 'face reftex-bib-year-face
566 (put-text-property 0 (length title
) 'face reftex-bib-title-face
568 (put-text-property 0 (length extra
) 'face reftex-bib-extra-face
570 (concat key
"\n " authors
" " year
" " extra
"\n " title
"\n\n")))
572 (defun reftex-parse-bibitem (item)
573 ;; Parse a \bibitem entry
574 (let ((key "") (text ""))
575 (when (string-match "\\`{\\([^}]+\\)}\\([^\000]*\\)" item
)
576 (setq key
(match-string 1 item
)
577 text
(match-string 2 item
)))
578 ;; Clean up the text a little bit
579 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text
)
580 (setq text
(replace-match " " nil t text
)))
581 (if (string-match "\\`[ \t]+" text
)
582 (setq text
(replace-match "" nil t text
)))
586 (cons "&entry" (concat key
" " text
)))))
588 (defun reftex-format-bibitem (item)
589 ;; Format a \bibitem entry so that it is (relatively) nice to look at.
590 (let ((text (reftex-get-bib-field "&text" item
))
591 (key (reftex-get-bib-field "&key" item
))
594 ;; Wrap the text into several lines.
595 (while (and (> (length text
) 70)
596 (string-match " " (substring text
60)))
597 (push (substring text
0 (+ 60 (match-beginning 0))) lines
)
598 (setq text
(substring text
(+ 61 (match-beginning 0)))))
600 (setq text
(mapconcat 'identity
(nreverse lines
) "\n "))
602 (when (reftex-use-fonts)
603 (put-text-property 0 (length text
) 'face reftex-bib-author-face text
))
604 (concat key
"\n " text
"\n\n")))
609 (defun reftex-citation (&optional no-insert format-key
)
610 "Make a citation using BibTeX database files.
611 After prompting for a regular expression, scans the buffers with
612 bibtex entries (taken from the \\bibliography command) and offers the
613 matching entries for selection. The selected entry is formatted according
614 to `reftex-cite-format' and inserted into the buffer.
616 If NO-INSERT is non-nil, nothing is inserted, only the selected key returned.
618 FORMAT-KEY can be used to pre-select a citation format.
620 When called with a `C-u' prefix, prompt for optional arguments in
621 cite macros. When called with a numeric prefix, make that many
622 citations. When called with point inside the braces of a `\\cite'
623 command, it will add another key, ignoring the value of
624 `reftex-cite-format'.
626 The regular expression uses an expanded syntax: && is interpreted as `and'.
627 Thus, `aaaa&&bbb' matches entries which contain both `aaaa' and `bbb'.
628 While entering the regexp, completion on knows citation keys is possible.
629 `=' is a good regular expression to match all entries in all files."
633 ;; check for recursive edit
634 (reftex-check-recursive-edit)
636 ;; This function may also be called outside reftex-mode.
637 ;; Thus look for the scanning info only if in reftex-mode.
640 (reftex-access-scan-info nil
))
642 ;; Call reftex-do-citation, but protected
644 (reftex-do-citation current-prefix-arg no-insert format-key
)
645 (reftex-kill-temporary-buffers)))
647 (defun reftex-do-citation (&optional arg no-insert format-key
)
648 ;; This really does the work of reftex-citation.
650 (let* ((format (reftex-figure-out-cite-format arg no-insert format-key
))
651 (docstruct-symbol reftex-docstruct-symbol
)
652 (selected-entries (reftex-offer-bib-menu))
653 (insert-entries selected-entries
)
654 entry string cite-view
)
656 (unless selected-entries
(error "Quit"))
658 (if (stringp selected-entries
)
660 (setq insert-entries
(list (list selected-entries
661 (cons "&key" selected-entries
)))
662 selected-entries nil
)
663 ;; It makes sense to compute the cite-view strings.
666 (when (eq (car selected-entries
) 'concat
)
667 ;; All keys go into a single command - we need to trick a little
668 ;; FIXME: Unfortunately, this means that commenting does not work right.
669 (pop selected-entries
)
670 (let ((concat-keys (mapconcat 'car selected-entries
671 reftex-cite-key-separator
)))
673 (list (list concat-keys
(cons "&key" concat-keys
))))))
677 ;; We shall insert this into the buffer...
678 (message "Formatting...")
680 (while (setq entry
(pop insert-entries
))
681 ;; Format the citation and insert it
682 (setq string
(if reftex-format-cite-function
683 (funcall reftex-format-cite-function
684 (reftex-get-bib-field "&key" entry
)
686 (reftex-format-citation entry format
)))
687 (when (or (eq reftex-cite-prompt-optional-args t
)
688 (and reftex-cite-prompt-optional-args
690 (let ((start 0) (nth 0) value
)
691 (while (setq start
(string-match "\\[\\]" string start
))
692 (setq value
(save-match-data
693 (read-string (format "Optional argument %d: "
694 (setq nth
(1+ nth
))))))
695 (setq string
(replace-match (concat "[" value
"]") t t string
))
696 (setq start
(1+ start
)))))
697 ;; Should we cleanup empty optional arguments?
698 ;; if the first is empty, it can be removed. If the second is empty,
699 ;; it has to go. If there is only a single arg and empty, it can go
701 (when reftex-cite-cleanup-optional-args
703 ((string-match "\\([a-zA-Z0-9]\\)\\[\\]{" string
)
704 (setq string
(replace-match "\\1{" nil nil string
)))
705 ((string-match "\\[\\]\\(\\[[a-zA-Z0-9., ]+\\]\\)" string
)
706 (setq string
(replace-match "\\1" nil nil string
)))
707 ((string-match "\\[\\]\\[\\]" string
)
708 (setq string
(replace-match "" t t string
)))))
711 ;; Reposition cursor?
712 (when (string-match "\\?" string
)
713 (search-backward "?")
717 (when (and reftex-mode
718 (fboundp 'LaTeX-add-bibitems
)
719 reftex-plug-into-AUCTeX
)
720 (apply 'LaTeX-add-bibitems
(mapcar 'car selected-entries
)))
722 ;; Produce the cite-view strings
723 (when (and reftex-mode reftex-cache-cite-echo cite-view
)
724 (mapc (lambda (entry)
725 (reftex-make-cite-echo-string entry docstruct-symbol
))
730 (set-marker reftex-select-return-marker nil
)
731 (reftex-kill-buffer "*RefTeX Select*")
733 ;; Check if the prefix arg was numeric, and call recursively
737 (skip-chars-backward "}")
739 (reftex-do-citation arg
))
742 ;; Return the citation key
743 (mapcar 'car selected-entries
)))
745 (defun reftex-figure-out-cite-format (arg &optional no-insert format-key
)
746 ;; Check if there is already a cite command at point and change cite format
747 ;; in order to only add another reference in the same cite command.
748 (let ((macro (car (reftex-what-macro 1)))
749 (cite-format-value (reftex-get-cite-format))
753 ;; Format does not really matter because nothing will be inserted.
756 ((and (stringp macro
)
757 (string-match "\\`\\\\cite\\|cite\\'" macro
))
758 ;; We are already inside a cite macro
759 (if (or (not arg
) (not (listp arg
)))
762 (if (member (preceding-char) '(?\
{ ?
,))
764 reftex-cite-key-separator
)
766 (if (member (following-char) '(?\
} ?
,))
768 reftex-cite-key-separator
)))
771 ;; Figure out the correct format
773 (if (and (symbolp cite-format-value
)
774 (assq cite-format-value reftex-cite-format-builtin
))
775 (nth 2 (assq cite-format-value reftex-cite-format-builtin
))
780 (reftex-select-with-char
781 "" (concat "SELECT A CITATION FORMAT\n\n"
784 (format "[%c] %s %s" (car x
)
785 (if (> (car x
) 31) " " "")
788 (if (assq key format
)
789 (setq format
(cdr (assq key format
)))
790 (error "No citation format associated with key `%c'" key
)))))
793 (defun reftex-citep ()
794 "Call `reftex-citation' with a format selector `?p'."
796 (reftex-citation nil ?p
))
798 (defun reftex-citet ()
799 "Call `reftex-citation' with a format selector `?t'."
801 (reftex-citation nil ?t
))
803 (defvar reftex-select-bib-map
)
804 (defun reftex-offer-bib-menu ()
805 ;; Offer bib menu and return list of selected items
807 (let ((bibtype (reftex-bib-or-thebib))
808 found-list rtn key data selected-entries
)
816 ; ((assq 'bib (symbol-value reftex-docstruct-symbol))
817 ;; using BibTeX database files.
818 (reftex-extract-bib-entries (reftex-get-bibfile-list)))
819 ((eq bibtype
'thebib
)
820 ; ((assq 'thebib (symbol-value reftex-docstruct-symbol))
821 ;; using thebibliography environment.
822 (reftex-extract-bib-entries-from-thebibliography
826 'thebib
(symbol-value reftex-docstruct-symbol
))))))
827 (reftex-default-bibliography
828 (message "Using default bibliography")
829 (reftex-extract-bib-entries (reftex-default-bibliography)))
830 (t (error "No valid bibliography in this document, and no default available"))))
833 (error "Sorry, no matches found"))
835 ;; Remember where we came from
836 (setq reftex-call-back-to-this-buffer
(current-buffer))
837 (set-marker reftex-select-return-marker
(point))
840 (save-window-excursion
841 (delete-other-windows)
842 (reftex-kill-buffer "*RefTeX Select*")
843 (switch-to-buffer-other-window "*RefTeX Select*")
844 (unless (eq major-mode
'reftex-select-bib-mode
)
845 (reftex-select-bib-mode))
846 (let ((buffer-read-only nil
))
848 (reftex-insert-bib-matches found-list
))
849 (setq buffer-read-only t
)
850 (if (= 0 (buffer-size))
851 (error "No matches found"))
852 (setq truncate-lines t
)
857 reftex-citation-prompt
859 reftex-select-bib-map
861 'reftex-bibtex-selection-callback nil
))
864 (unless key
(throw 'done t
))
870 ;; Restrict with new regular expression
871 (setq found-list
(reftex-restrict-bib-matches found-list
))
872 (let ((buffer-read-only nil
))
874 (reftex-insert-bib-matches found-list
))
878 (setq selected-entries
879 (if reftex-select-marked
880 (mapcar 'car
(nreverse reftex-select-marked
))
884 ;; Take all (marked), and push the symbol 'concat
885 (setq selected-entries
887 (if reftex-select-marked
888 (mapcar 'car
(nreverse reftex-select-marked
))
892 ;; Take all (marked), and push the symbol 'concat
893 (reftex-extract-bib-file found-list reftex-select-marked
)
894 (setq selected-entries
"BibTeX database file created")
897 ;; Take all (marked), and push the symbol 'concat
898 (reftex-extract-bib-file found-list reftex-select-marked
900 (setq selected-entries
"BibTeX database file created")
905 (setq selected-entries
906 (if reftex-select-marked
908 (mapcar 'car
(nreverse reftex-select-marked
)))
909 (if data
(list data
) nil
)))
912 ;; Got this one with completion
913 (setq selected-entries key
)
919 (defun reftex-restrict-bib-matches (found-list)
920 ;; Limit FOUND-LIST with more regular expressions
921 (let ((re-list (split-string (read-string
922 "RegExp [ && RegExp...]: "
923 nil
'reftex-cite-regexp-hist
)
925 (found-list-r found-list
)
927 (while (setq re
(pop re-list
))
933 re
(cdr (assoc "&entry" x
)))
942 (defun reftex-extract-bib-file (all &optional marked complement
)
943 ;; Limit FOUND-LIST with more regular expressions
944 (let ((file (read-file-name "File to create: ")))
945 (find-file-other-window file
)
946 (if (> (buffer-size) 0)
948 (format "Overwrite non-empty file %s? " file
))
955 (if (or (and (assoc x marked
) (not complement
))
956 (and (not (assoc x marked
)) complement
))
957 (cdr (assoc "&entry" x
))
959 (cdr (assoc "&entry" x
))))
961 (insert (mapconcat 'identity all
"\n\n"))
963 (goto-char (point-min))))
965 (defun reftex-insert-bib-matches (list)
966 ;; Insert the bib matches and number them correctly
968 (if (memq reftex-highlight-selection
'(mouse both
))
969 reftex-mouse-selected-face
974 (setq tmp
(cdr (assoc "&formatted" x
))
976 (put-text-property 0 len
:data x tmp
)
977 (put-text-property 0 (1- len
) 'mouse-face mouse-face tmp
)
980 (run-hooks 'reftex-display-copied-context-hook
))
982 (defun reftex-format-names (namelist n
)
983 (let (last (len (length namelist
)))
984 (if (= n
0) (setq n len
))
987 ((= 1 len
) (car namelist
))
988 ((> len n
) (concat (car namelist
) (nth 2 reftex-cite-punctuation
)))
991 last
(nth (1- n
) namelist
))
992 (setcdr (nthcdr (- n
2) namelist
) nil
)
994 (mapconcat 'identity namelist
(nth 0 reftex-cite-punctuation
))
995 (nth 1 reftex-cite-punctuation
)
998 (defun reftex-format-citation (entry format
)
999 ;; Format a citation from the info in the BibTeX ENTRY
1001 (unless (stringp format
) (setq format
"\\cite{%l}"))
1003 (if (and reftex-comment-citations
1004 (string-match "%l" reftex-cite-comment-format
))
1005 (error "reftex-cite-comment-format contains invalid %%l"))
1007 (while (string-match
1008 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
1010 (let ((n (string-to-number (match-string 4 format
)))
1011 (l (string-to-char (match-string 5 format
)))
1017 (reftex-get-bib-field "&key" entry
)
1018 (if reftex-comment-citations
1019 reftex-cite-comment-format
1021 ((= l ?a
) (reftex-format-names
1022 (reftex-get-bib-names "author" entry
)
1024 ((= l ?A
) (car (reftex-get-bib-names "author" entry
)))
1025 ((= l ?b
) (reftex-get-bib-field "booktitle" entry
"in: %s"))
1026 ((= l ?B
) (reftex-abbreviate-title
1027 (reftex-get-bib-field "booktitle" entry
"in: %s")))
1028 ((= l ?c
) (reftex-get-bib-field "chapter" entry
))
1029 ((= l ?d
) (reftex-get-bib-field "edition" entry
))
1030 ((= l ?e
) (reftex-format-names
1031 (reftex-get-bib-names "editor" entry
)
1033 ((= l ?E
) (car (reftex-get-bib-names "editor" entry
)))
1034 ((= l ?h
) (reftex-get-bib-field "howpublished" entry
))
1035 ((= l ?i
) (reftex-get-bib-field "institution" entry
))
1036 ((= l ?j
) (reftex-get-bib-field "journal" entry
))
1037 ((= l ?k
) (reftex-get-bib-field "key" entry
))
1038 ((= l ?m
) (reftex-get-bib-field "month" entry
))
1039 ((= l ?n
) (reftex-get-bib-field "number" entry
))
1040 ((= l ?N
) (reftex-get-bib-field "note" entry
))
1041 ((= l ?o
) (reftex-get-bib-field "organization" entry
))
1042 ((= l ?p
) (reftex-get-bib-field "pages" entry
))
1043 ((= l ?P
) (car (split-string
1044 (reftex-get-bib-field "pages" entry
)
1046 ((= l ?s
) (reftex-get-bib-field "school" entry
))
1047 ((= l ?u
) (reftex-get-bib-field "publisher" entry
))
1048 ((= l ?U
) (reftex-get-bib-field "url" entry
))
1049 ((= l ?r
) (reftex-get-bib-field "address" entry
))
1050 ((= l ?t
) (reftex-get-bib-field "title" entry
))
1051 ((= l ?T
) (reftex-abbreviate-title
1052 (reftex-get-bib-field "title" entry
)))
1053 ((= l ?v
) (reftex-get-bib-field "volume" entry
))
1054 ((= l ?y
) (reftex-get-bib-field "year" entry
)))))
1056 (if (string= rpl
"")
1057 (setq b
(match-beginning 2) e
(match-end 2))
1058 (setq b
(match-beginning 3) e
(match-end 3)))
1059 (setq format
(concat (substring format
0 b
) rpl
(substring format e
)))))
1060 (while (string-match "%%" format
)
1061 (setq format
(replace-match "%" t t format
)))
1062 (while (string-match "[ ,.;:]*%<" format
)
1063 (setq format
(replace-match "" t t format
)))
1066 (defun reftex-make-cite-echo-string (entry docstruct-symbol
)
1067 ;; Format a bibtex entry for the echo area and cache the result.
1068 (let* ((key (reftex-get-bib-field "&key" entry
))
1070 (let* ((reftex-cite-punctuation '(" " " & " " etal.")))
1071 (reftex-format-citation entry reftex-cite-view-format
)))
1072 (cache (assq 'bibview-cache
(symbol-value docstruct-symbol
)))
1073 (cache-entry (assoc key
(cdr cache
))))
1075 ;; This docstruct has no cache - make one.
1076 (set docstruct-symbol
(cons (cons 'bibview-cache nil
)
1077 (symbol-value docstruct-symbol
))))
1078 (when reftex-cache-cite-echo
1079 (setq key
(copy-sequence key
))
1080 (set-text-properties 0 (length key
) nil key
)
1081 (set-text-properties 0 (length string
) nil string
)
1083 (unless (string= (cdr cache-entry
) string
)
1084 (setcdr cache-entry string
)
1085 (put reftex-docstruct-symbol
'modified t
))
1086 (push (cons key string
) (cdr cache
))
1087 (put reftex-docstruct-symbol
'modified t
)))
1090 (defun reftex-bibtex-selection-callback (data ignore no-revisit
)
1091 ;; Callback function to be called from the BibTeX selection, in
1092 ;; order to display context. This function is relatively slow and not
1093 ;; recommended for follow mode. It works OK for individual lookups.
1094 (let ((win (selected-window))
1095 (key (reftex-get-bib-field "&key" data
))
1096 bibfile-list item bibtype
)
1099 (with-current-buffer reftex-call-back-to-this-buffer
1100 (setq bibtype
(reftex-bib-or-thebib))
1103 ; ((assq 'bib (symbol-value reftex-docstruct-symbol))
1104 (setq bibfile-list
(reftex-get-bibfile-list)))
1105 ((eq bibtype
'thebib
)
1106 ; ((assq 'thebib (symbol-value reftex-docstruct-symbol))
1111 'thebib
(symbol-value reftex-docstruct-symbol
))))
1113 (reftex-default-bibliography
1114 (setq bibfile-list
(reftex-default-bibliography)))
1115 (t (ding) (throw 'exit nil
))))
1118 (setq bibfile-list
(reftex-visited-files bibfile-list
)))
1121 (reftex-pop-to-bibtex-entry
1122 key bibfile-list
(not reftex-keep-temporary-buffers
) t item
)
1125 (select-window win
)))
1127 ;;; Global BibTeX file
1128 (defun reftex-all-used-citation-keys ()
1129 (reftex-access-scan-info)
1130 (let ((files (reftex-all-document-files)) file keys kk k
)
1131 (save-current-buffer
1132 (while (setq file
(pop files
))
1133 (set-buffer (reftex-get-file-buffer-force file
'mark
))
1137 (goto-char (point-min))
1138 (while (re-search-forward "\\(?:^\\|\\=\\)[^%\n\r]*?\\\\\\(bibentry\\|[a-zA-Z]*cite[a-zA-Z]*\\)\\(\\[[^\\]]*\\]\\)?{\\([^}]+\\)}" nil t
)
1139 (setq kk
(match-string-no-properties 3))
1140 (while (string-match "%.*\n?" kk
)
1141 (setq kk
(replace-match "" t t kk
)))
1142 (setq kk
(split-string kk
"[, \t\r\n]+"))
1143 (while (setq k
(pop kk
))
1145 (setq keys
(cons k keys
)))))))))
1146 (reftex-kill-temporary-buffers)
1149 (defun reftex-get-string-refs (alist)
1150 "Return a list of BibTeX @string references that appear as values in ALIST."
1151 (reftex-remove-if (lambda (x) (string-match "^\\([\"{]\\|[0-9]+$\\)" x
))
1152 ;; get list of values, discard keys
1154 ;; remove &key and &type entries
1155 (reftex-remove-if (lambda (pair)
1156 (string-match "^&" (car pair
)))
1159 (defun reftex-create-bibtex-file (bibfile)
1160 "Create a new BibTeX database file with all entries referenced in document.
1161 The command prompts for a filename and writes the collected
1162 entries to that file. Only entries referenced in the current
1163 document with any \\cite-like macros are used. The sequence in
1164 the new file is the same as it was in the old database.
1166 Entries referenced from other entries must appear after all
1167 referencing entries.
1169 You can define strings to be used as header or footer for the
1170 created files in the variables `reftex-create-bibtex-header' or
1171 `reftex-create-bibtex-footer' respectively."
1172 (interactive "FNew BibTeX file: ")
1173 (let ((keys (reftex-all-used-citation-keys))
1174 (files (reftex-get-bibfile-list))
1175 file key entries beg end entry string-keys string-entries
)
1176 (save-current-buffer
1177 (dolist (file files
)
1178 (set-buffer (reftex-get-file-buffer-force file
'mark
))
1179 (reftex-with-special-syntax-for-bib
1183 (goto-char (point-min))
1184 (while (re-search-forward "^[ \t]*@\\(?:\\w\\|\\s_\\)+[ \t\n\r]*\
1185 \[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t
)
1186 (setq key
(match-string 1)
1187 beg
(match-beginning 0)
1189 (goto-char (match-beginning 1))
1192 (error (goto-char (match-end 0))))
1194 (when (member key keys
)
1195 (setq entry
(buffer-substring beg end
)
1196 entries
(cons entry entries
)
1197 keys
(delete key keys
))
1199 ;; check for crossref entries
1200 (let* ((attr-list (reftex-parse-bibtex-entry nil beg end
))
1201 (xref-key (cdr (assoc "crossref" attr-list
))))
1202 (if xref-key
(pushnew xref-key keys
)))
1203 ;; check for string references
1204 (let* ((raw-fields (reftex-parse-bibtex-entry nil beg end t
))
1205 (string-fields (reftex-get-string-refs raw-fields
)))
1206 (dolist (skey string-fields
)
1207 (unless (member skey string-keys
)
1208 (push skey string-keys
)))))))))))
1209 ;; second pass: grab @string references
1211 (save-current-buffer
1212 (dolist (file files
)
1213 (set-buffer (reftex-get-file-buffer-force file
'mark
))
1214 (reftex-with-special-syntax-for-bib
1218 (goto-char (point-min))
1219 (while (re-search-forward
1220 "^[ \t]*@[Ss][Tt][Rr][Ii][Nn][Gg][ \t]*{[ \t]*\\([^ \t\r\n]+\\)"
1222 (setq key
(match-string 1)
1223 beg
(match-beginning 0)
1225 (goto-char (match-beginning 1))
1228 (error (goto-char (match-end 0))))
1230 (when (member key string-keys
)
1231 (setq entry
(buffer-substring beg end
)
1232 string-entries
(cons entry string-entries
)
1233 string-keys
(delete key string-keys
))))))))))
1234 (find-file-other-window bibfile
)
1235 (if (> (buffer-size) 0)
1236 (unless (yes-or-no-p
1237 (format "Overwrite non-empty file %s? " bibfile
))
1240 (if reftex-create-bibtex-header
(insert reftex-create-bibtex-header
"\n\n"))
1241 (insert (mapconcat 'identity
(reverse string-entries
) "\n\n"))
1242 (if string-entries
(insert "\n\n\n"))
1243 (insert (mapconcat 'identity
(reverse entries
) "\n\n"))
1244 (if reftex-create-bibtex-footer
(insert "\n\n" reftex-create-bibtex-footer
))
1245 (goto-char (point-min))
1247 (message "%d entries extracted and copied to new database"
1251 ;;; reftex-cite.el ends here