reftex-cite.el 50 KB

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