]> git.eshelyaron.com Git - emacs.git/commitdiff
Add RefTeX support for non-file buffers
authorPaul Nelson <ultrono@gmail.com>
Wed, 2 Apr 2025 19:38:48 +0000 (21:38 +0200)
committerEshel Yaron <me@eshelyaron.com>
Tue, 8 Apr 2025 05:40:45 +0000 (07:40 +0200)
* lisp/textmodes/reftex.el (reftex--get-buffer-identifier)
(reftex--get-directory, reftex--abbreviate-name)
(reftex--get-basename, reftex--get-truename): New helper
functions that handle both files and buffer objects.
(reftex--remove-buffer-from-master-index): New helper function.
(reftex-tie-multifile-symbols): Support non-file buffers, using
the above.
(reftex-TeX-master-file): Return current buffer when no file.
(reftex-access-scan-info): Remove check requiring file buffers.
(reftex-access-parse-file, reftex-check-parse-consistency): Skip
for non-file buffers.
(reftex-select-external-document): Use new helper function.
(reftex-locate-file): Return buffer objects directly.
(reftex-get-file-buffer-force): Handle buffer objects and
special 'buffer:' strings.
* lisp/textmodes/reftex-global.el (reftex-create-tags-file): Add
error handling for non-file buffers.  Leave TAGS unsupported in
non-file buffers.
(reftex-find-duplicate-labels)
(reftex-isearch-switch-to-next-file): Use new helper functions
that handle both files and buffer objects.
(reftex-isearch-switch-to-next-file): Use equal rather than
string= to compare strings/buffers.
* lisp/textmodes/reftex-index.el (reftex-display-index)
(reftex-index-change-entry): Use new helper functions.
(reftex-index-visit-phrases-buffer): Add error handling for
non-file buffers.  Leave phrases unsupported in non-file
buffers.
* lisp/textmodes/reftex-parse.el (reftex-do-parse)
(reftex-parse-from-file): Add support for non-file buffers.
(reftex-all-document-files, reftex-where-am-I)
(reftex-notice-new): Use new helper functions.
* lisp/textmodes/reftex-ref.el (reftex-label-info-update):
Support non-file buffers.
(reftex-label-info, reftex-replace-prefix-escapes, reftex-label)
(reftex-replace-prefix-escapes, reftex-offer-label-menu): Use
new helper functions.
* lisp/textmodes/reftex-sel.el (reftex-insert-docstruct): Use
new helper function.
* lisp/textmodes/reftex-toc.el (reftex-toc)
(reftex-recenter-toc-when-idle): Support non-file buffers.
* lisp/textmodes/reftex-cite.el (reftex-bib-or-thebib)
(reftex-get-bibfile-list): Use new helper functions.
* lisp/textmodes/reftex-global.el
(reftex-save-all-document-buffers, reftex-ensure-write-access):
Ignore non-file buffers.
* lisp/textmodes/reftex-parse.el (reftex-all-document-files):
For non-file objects, do not apply relative path transformation.
* test/lisp/textmodes/reftex-tests.el
(reftex-all-used-citation-keys-buffer)
(reftex-renumber-simple-labels-buffer): New tests for operations
on non-file buffers.

RefTeX historically assumed that the buffers it operates on
visit files.  To handle non-file buffers:

Modify reftex-TeX-master-file so that it returns the buffer
object itself (as suggested by Stefan Monnier).  Modify each
caller to handle buffer objects, aided by some helper functions
added to reftex.el.  Replace 'string=' by 'equal' in places.

Use buffer-base-buffer, where appropriate, to handle indirect
buffers (file and non-file).

TAGS files and phrases buffers remain unsupported for non-file
buffers.

(cherry picked from commit 03fc0e0fd51990570759601fa7e64f1cc5b76932)

lisp/textmodes/reftex-cite.el
lisp/textmodes/reftex-global.el
lisp/textmodes/reftex-index.el
lisp/textmodes/reftex-parse.el
lisp/textmodes/reftex-ref.el
lisp/textmodes/reftex-sel.el
lisp/textmodes/reftex-toc.el
lisp/textmodes/reftex.el
test/lisp/textmodes/reftex-tests.el

index fe6751a13f6179711dc82b23bcff6fdf08642bdc..8830f188c93519b65180daea1782b79d7cc66995 100644 (file)
@@ -76,7 +76,8 @@ The expanded value is cached."
   "Test if BibTeX or \\begin{thebibliography} should be used for the citation.
 Find the bof of the current file."
   (let* ((docstruct (symbol-value reftex-docstruct-symbol))
-         (rest (or (member (list 'bof (buffer-file-name)) docstruct)
+         (rest (or (member (list 'bof (reftex--get-buffer-identifier))
+                           docstruct)
                    docstruct))
          (bib (assq 'bib rest))
          (thebib (assq 'thebib rest))
@@ -104,11 +105,11 @@ Then this function will return the applicable database files."
   (or
    ;; Try inside this file (and its includes)
    (cdr (reftex-last-assoc-before-elt
-         'bib (list 'eof (buffer-file-name))
-         (member (list 'bof (buffer-file-name))
+         'bib (list 'eof (reftex--get-buffer-identifier))
+         (member (list 'bof (reftex--get-buffer-identifier))
                  (symbol-value reftex-docstruct-symbol))))
    ;; Try after the beginning of this file
-   (cdr (assq 'bib (member (list 'bof (buffer-file-name))
+   (cdr (assq 'bib (member (list 'bof (reftex--get-buffer-identifier))
                            (symbol-value reftex-docstruct-symbol))))
    ;; Anywhere in the entire document
    (cdr (assq 'bib (symbol-value reftex-docstruct-symbol)))
index 20abd36192d832166ee05f84df5f436d9d628781..bd330d3a4188fe6a88cce91dfa2a2fbfb0b91c0c 100644 (file)
 The TAGS file is also immediately visited with `visit-tags-table'."
   (interactive)
   (reftex-access-scan-info current-prefix-arg)
-  (let* ((master (reftex-TeX-master-file))
-         (files  (reftex-all-document-files))
-         (cmd    (format "%s %s"
-                         etags-program-name
-                         (mapconcat #'shell-quote-argument
-                                   files " "))))
-    (with-current-buffer (reftex-get-file-buffer-force master)
-      (message "Running etags to create TAGS file...")
-      (shell-command cmd)
-      (visit-tags-table "TAGS"))))
+  (let ((master (reftex-TeX-master-file)))
+    (if (bufferp master)
+        (user-error "Cannot create TAGS file for non-file buffers")
+      (let* ((files  (reftex-all-document-files))
+             (cmd (format "%s %s"
+                          etags-program-name
+                          (mapconcat #'shell-quote-argument
+                                     files " "))))
+        (with-current-buffer (reftex-get-file-buffer-force master)
+          (message "Running etags to create TAGS file...")
+          (shell-command cmd)
+          (visit-tags-table "TAGS"))))))
 
 ;; History of grep commands.
 (defvar reftex-grep-history nil)
@@ -144,7 +146,7 @@ No active TAGS table is required."
                 (if (< 1 (length x1))
                     (append (list (car x))
                             (mapcar (lambda(x)
-                                      (abbreviate-file-name (nth 3 x)))
+                                      (reftex--abbreviate-name (nth 3 x)))
                                     x1))
                   (list nil))))))
           (reftex-uniquify-by-car (symbol-value reftex-docstruct-symbol)))))
@@ -369,31 +371,33 @@ labels."
         file buffer)
     (save-current-buffer
       (while (setq file (pop files))
-        (setq buffer (find-buffer-visiting file))
-        (when buffer
-          (set-buffer buffer)
-          (save-buffer))))))
+        (when (stringp file) ; Ignore non-file buffers.
+          (setq buffer (find-buffer-visiting file))
+          (when buffer
+            (set-buffer buffer)
+            (save-buffer)))))))
 
 (defun reftex-ensure-write-access (files)
   "Make sure we have write access to all files in FILES.
 Also checks if buffers visiting the files are in read-only mode."
   (let (file buf)
-    (while (setq file (pop files))
-      (unless (file-exists-p file)
-        (ding)
-        (or (y-or-n-p (format "No such file %s. Continue?" file))
-            (error "Abort")))
-      (unless (file-writable-p file)
-        (ding)
-        (or (y-or-n-p (format "No write access to %s. Continue?" file))
-            (error "Abort")))
-      (when (and (setq buf (find-buffer-visiting file))
-                 (with-current-buffer buf
-                   buffer-read-only))
-        (ding)
-        (or (y-or-n-p (format "Buffer %s is read-only.  Continue?"
-                              (buffer-name buf)))
-            (error "Abort"))))))
+    (while (setq file (pop files)) ; Ignore non-file buffers.
+      (when (stringp file)
+        (unless (file-exists-p file)
+          (ding)
+          (or (y-or-n-p (format "No such file %s. Continue?" file))
+              (error "Abort")))
+        (unless (file-writable-p file)
+          (ding)
+          (or (y-or-n-p (format "No write access to %s. Continue?" file))
+              (error "Abort")))
+        (when (and (setq buf (find-buffer-visiting file))
+                   (with-current-buffer buf
+                     buffer-read-only))
+          (ding)
+          (or (y-or-n-p (format "Buffer %s is read-only.  Continue?"
+                                (buffer-name buf)))
+              (error "Abort")))))))
 
 ;;; Multi-file RefTeX Isearch
 
@@ -456,7 +460,7 @@ Also checks if buffers visiting the files are in read-only mode."
 ;; beginning/end of the file list, depending of the search direction.
 (defun reftex-isearch-switch-to-next-file (crt-buf &optional wrapp)
   (reftex-access-scan-info)
-  (let ((cb (buffer-file-name crt-buf))
+  (let ((cb (reftex--get-buffer-identifier crt-buf))
        (flist (reftex-all-document-files)))
     (when flist
       (if wrapp
@@ -464,7 +468,7 @@ Also checks if buffers visiting the files are in read-only mode."
            (setq flist (last flist)))
        (unless isearch-forward
          (setq flist (reverse flist)))
-       (while (not (string= (car flist) cb))
+       (while (not (equal (car flist) cb))
          (setq flist (cdr flist)))
        (setq flist (cdr flist)))
       (when flist
index bd6a5e111472a790f2c2cb46430d64a4fc564640..8eb2ba70a236da3719aee2740c99c73dc30bbdf8 100644 (file)
@@ -475,7 +475,7 @@ With prefix 3, restrict index to region."
          (docstruct-symbol reftex-docstruct-symbol)
          (index-tag (or tag (reftex-index-select-tag)))
          (master (reftex-TeX-master-file))
-         (calling-file (buffer-file-name))
+         (calling-file (reftex--get-buffer-identifier))
          (restriction
           (or overriding-restriction
               (and (not redo)
@@ -531,7 +531,7 @@ Restriction: <%s>
 SPC=view TAB=goto RET=goto+hide [e]dit [q]uit [r]escan [f]ollow [?]Help
 ------------------------------------------------------------------------------
 "
-               index-tag (abbreviate-file-name master)
+               index-tag (reftex--abbreviate-name master)
                (if (eq (car (car reftex-index-restriction-data)) 'toc)
                    (nth 2 (car reftex-index-restriction-data))
                  reftex-index-restriction-indicator)))
@@ -1107,7 +1107,8 @@ values are accessible individually."
       (when (and (re-search-forward (reftex-everything-regexp) nil t)
                  (match-end 10)
                  (< (abs (- (match-beginning 10) beg)) (length new))
-                 (setq info (reftex-index-info-safe buffer-file-name)))
+                 (setq info (reftex-index-info-safe
+                             (reftex--get-buffer-identifier))))
         (setcdr data (cdr info))))
     (let ((buffer-read-only nil))
       (save-excursion
@@ -1281,14 +1282,16 @@ You get a chance to edit the entry in the phrases buffer - finish with
   (interactive)
   (reftex-access-scan-info)
   (set-marker reftex-index-return-marker (point))
-  (let* ((master (reftex-TeX-master-file))
-         (name (concat (file-name-sans-extension master)
-                       reftex-index-phrase-file-extension)))
-    (find-file name)
-    (unless (eq major-mode 'reftex-index-phrases-mode)
-      (reftex-index-phrases-mode))
-    (if (= (buffer-size) 0)
-        (reftex-index-initialize-phrases-buffer master))))
+  (let ((master (reftex-TeX-master-file)))
+    (when (bufferp master)
+      (user-error "RefTeX phrases buffer requires a file buffer"))
+    (let ((name (concat (file-name-sans-extension master)
+                        reftex-index-phrase-file-extension)))
+      (find-file name)
+      (unless (eq major-mode 'reftex-index-phrases-mode)
+        (reftex-index-phrases-mode))
+      (if (= (buffer-size) 0)
+          (reftex-index-initialize-phrases-buffer master)))))
 
 (defun reftex-index-initialize-phrases-buffer (&optional master)
   "Initialize the phrases buffer by creating the header.
index 7795c58307656c074555473a83626138fe26e07d..cd8b33785583cfc7edbc7afcebb01aeacfca5dce 100644 (file)
@@ -74,10 +74,10 @@ When allowed, do only a partial scan from FILE."
 
   (let* ((old-list (symbol-value reftex-docstruct-symbol))
          (master (reftex-TeX-master-file))
-         (true-master (file-truename master))
-         (master-dir (file-name-as-directory (file-name-directory master)))
-         (file (or file (buffer-file-name)))
-         (true-file (file-truename file))
+         (true-master (reftex--get-truename master))
+         (master-dir (file-name-as-directory (reftex--get-directory master)))
+         (file (or file (reftex--get-buffer-identifier)))
+         (true-file (reftex--get-truename file))
          (bibview-cache (assq 'bibview-cache old-list))
          (reftex--index-tags (cdr (assq 'index-tags old-list)))
          from-file appendix docstruct tmp)
@@ -88,7 +88,7 @@ When allowed, do only a partial scan from FILE."
                          (member (list 'eof file) old-list))))
       ;; Scan whole document because no such file section exists
       (setq rescan 1))
-    (when (string= true-file true-master)
+    (when (equal true-file true-master)
       ;; Scan whole document because this file is the master
       (setq rescan 1))
 
@@ -186,13 +186,14 @@ When allowed, do only a partial scan from FILE."
 When RELATIVE is non-nil, give file names relative to directory
 of master file."
   (let* ((all (symbol-value reftex-docstruct-symbol))
-         (master-dir (file-name-directory (reftex-TeX-master-file)))
+         (master-dir (reftex--get-directory (reftex-TeX-master-file)))
          (re (concat "\\`" (regexp-quote master-dir)))
         file-list tmp file)
     (while (setq tmp (assoc 'bof all))
       (setq file (nth 1 tmp)
             all (cdr (memq tmp all)))
       (and relative
+           (stringp file) ; Ignore non-file buffers.
            (string-match re file)
            (setq file (substring file (match-end 0))))
       (push file file-list))
@@ -228,7 +229,7 @@ of master file."
                 (not (eq t reftex-keep-temporary-buffers)))))
 
         ;; Begin of file mark
-        (setq file (buffer-file-name))
+        (setq file (reftex--get-buffer-identifier))
         (push (list 'bof file) docstruct)
 
         (reftex-with-special-syntax
@@ -275,7 +276,8 @@ of master file."
                  (when (and toc-entry
                             (eq ;; Either both are t or both are nil.
                              (= (char-after bound) ?%)
-                             (string-suffix-p ".dtx" file)))
+                             (and (stringp file)
+                                  (string-suffix-p ".dtx" file))))
                    ;; It can happen that section info returns nil
                    (setq level (nth 5 toc-entry))
                    (setq highest-level (min highest-level level))
@@ -638,7 +640,8 @@ if the information is exact (t) or approximate (nil)."
                ((not found)
                 ;; no match
                 (or
-                 (car (member (list 'bof (buffer-file-name)) docstruct))
+                 (car (member (list 'bof (reftex--get-buffer-identifier))
+                              docstruct))
                  (not (setq cnt 2))
                  (assq 'bof docstruct)  ;; for safety reasons
                  'corrupted))
@@ -649,15 +652,16 @@ if the information is exact (t) or approximate (nil)."
                ((match-end 3)
                 ;; Section
                 (goto-char (1- (match-beginning 3)))
-                (let* ((list (member (list 'bof (buffer-file-name))
+                (let* ((buffile (reftex--get-buffer-identifier))
+                       (list (member (list 'bof buffile)
                                      docstruct))
-                       (endelt (car (member (list 'eof (buffer-file-name))
+                       (endelt (car (member (list 'eof buffile)
                                             list)))
                        rtn1)
                   (while (and list (not (eq endelt (car list))))
                     (if (and (eq (car (car list)) 'toc)
-                             (string= (buffer-file-name)
-                                      (nth 3 (car list))))
+                             (equal buffile
+                                    (nth 3 (car list))))
                         (cond
                          ((equal (point)
                                  (or (and (markerp (nth 4 (car list)))
@@ -685,10 +689,13 @@ if the information is exact (t) or approximate (nil)."
                 (when reftex-support-index
                   (let* ((index-info (save-excursion
                                        (reftex-index-info-safe nil)))
-                         (list (member (list 'bof (buffer-file-name))
-                                       docstruct))
-                         (endelt (car (member (list 'eof (buffer-file-name))
-                                              list)))
+                         (list (member
+                                (list 'bof (reftex--get-buffer-identifier))
+                                docstruct))
+                         (endelt
+                          (car (member
+                                (list 'eof (reftex--get-buffer-identifier))
+                                list)))
                          dist last-dist last (n 0))
                     ;; Check all index entries with equal text
                     (while (and list (not (eq endelt (car list))))
@@ -758,12 +765,13 @@ if the information is exact (t) or approximate (nil)."
          (when (re-search-forward (reftex-everything-regexp) nil t)
            (cond
             ((match-end 1)
-             (push (reftex-label-info (reftex-match-string 1) buffer-file-name)
+             (push (reftex-label-info (reftex-match-string 1)
+                                  (reftex--get-buffer-identifier))
                    (cdr tail)))
 
             ((match-end 3)
              (setq star (= ?* (char-after (match-end 3)))
-                   entry (reftex-section-info (buffer-file-name))
+                   entry (reftex-section-info (reftex--get-buffer-identifier))
                    level (nth 5 entry))
              ;; Insert the section info
              (push entry (cdr tail))
@@ -795,7 +803,8 @@ if the information is exact (t) or approximate (nil)."
             ((match-end 10)
              ;; Index entry
              (and reftex-support-index
-                  (setq entry (reftex-index-info-safe buffer-file-name))
+                  (setq entry (reftex-index-info-safe
+                               (reftex--get-buffer-identifier)))
                   ;; FIXME: (add-to-list 'reftex--index-tags (nth 1 index-entry))
                   (push entry (cdr tail))))))))))
 
index d7022cf4a3b178e0f1c4108f756ad7d666469a89..fa0ee4de04deb55b1e123402faf9fc21ec76e43b 100644 (file)
@@ -73,8 +73,10 @@ If optional BOUND is an integer, limit backward searches to that point."
          (file    (nth 3 cell))
          (comment (nth 4 cell))
          (note    (nth 5 cell))
-         (buf (reftex-get-file-buffer-force
-               file (not (eq t reftex-keep-temporary-buffers)))))
+         (buf (if (bufferp file)
+                  file
+                (reftex-get-file-buffer-force
+                 file (not (eq t reftex-keep-temporary-buffers))))))
     (if (not buf)
         (list label typekey "" file comment "LOST LABEL.  RESCAN TO FIX.")
       (with-current-buffer buf
@@ -102,7 +104,7 @@ If optional BOUND is an integer, limit backward searches to that point."
   (let* ((prefix (if (string-match "^[a-zA-Z0-9]+:" label)
                      (match-string 0 label)))
          (typekey (cdr (assoc prefix reftex-prefix-to-typekey-alist)))
-         (file (or file (buffer-file-name)))
+         (file (or file (reftex--get-buffer-identifier)))
          (trust reftex-trust-label-prefix)
          (in-comment (reftex-in-comment)))
     (if (and typekey
@@ -249,7 +251,7 @@ This function is controlled by the settings of reftex-insert-label-flags."
              (note (if (cdr here-I-am-info)
                        ""
                      "POSITION UNCERTAIN.  RESCAN TO FIX."))
-             (file (buffer-file-name))
+             (file (reftex--get-buffer-identifier))
              ;; (text nil)
              (tail (memq here-I-am (symbol-value reftex-docstruct-symbol))))
 
@@ -314,19 +316,21 @@ also applies `reftex-translate-to-ascii-function' to the string."
               (save-match-data
                 (cond
                  ((equal letter "f")
-                  (file-name-base (buffer-file-name)))
+                  (file-name-base (reftex--get-buffer-identifier)))
                  ((equal letter "F")
-                  (let ((masterdir (file-name-directory (reftex-TeX-master-file)))
-                        (file (file-name-sans-extension (buffer-file-name))))
+                  (let ((masterdir (reftex--get-directory
+                                    (reftex-TeX-master-file)))
+                        (file (file-name-sans-extension
+                               (reftex--get-buffer-identifier))))
                     (if (string-match (concat "\\`" (regexp-quote masterdir))
                                       file)
                         (substring file (length masterdir))
                       file)))
                  ((equal letter "m")
-                  (file-name-base (reftex-TeX-master-file)))
+                  (reftex--get-basename (reftex-TeX-master-file)))
                  ((equal letter "M")
                   (file-name-nondirectory
-                   (substring (file-name-directory (reftex-TeX-master-file))
+                   (substring (reftex--get-directory (reftex-TeX-master-file))
                               0 -1)))
                  ((equal letter "u")
                   (or (user-login-name) ""))
@@ -536,7 +540,8 @@ When called with 2 \\[universal-argument] prefix args, disable magic word recogn
   ;; Offer a menu with the appropriate labels.
   (let* ((buf (current-buffer))
          (xr-data (assq 'xr (symbol-value reftex-docstruct-symbol)))
-         (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
+         (xr-alist (cons (cons "" (reftex--get-buffer-identifier))
+                         (nth 1 xr-data)))
          (xr-index 0)
          (here-I-am (car (reftex-where-am-I)))
          (here-I-am1 here-I-am)
index 1f1c74550a5bfa7122e72f3364ac6c69bde9e08e..6e65ad4786cb9460e3cc109722f1798da53e1add 100644 (file)
@@ -234,7 +234,7 @@ During a selection process, these are the local bindings.
             reftex-active-toc nil
             master-dir-re
             (concat "\\`" (regexp-quote
-                           (file-name-directory (reftex-TeX-master-file))))))
+                           (reftex--get-directory (reftex-TeX-master-file))))))
 
     (setq-local reftex-docstruct-symbol docstruct-symbol)
     (setq-local reftex-prefix
index d8d09da5ed0fef3e7a9e91dbdc100efca2aab81d..2e3be51c87c15571eb4b7ac8ecc0e898b7f9d187 100644 (file)
@@ -184,14 +184,14 @@ When called with a raw \\[universal-argument] prefix, rescan the document first.
 
   (interactive)
 
-  (if (or (not (string= reftex-last-toc-master (reftex-TeX-master-file)))
+  (if (or (not (equal reftex-last-toc-master (reftex-TeX-master-file)))
           ;; FIXME: use (interactive "P") to receive current-prefix-arg as
           ;; an argument instead of using the var here, which forces us to set
           ;; current-prefix-arg in the callers.
           current-prefix-arg)
       (reftex-erase-buffer "*toc*"))
 
-  (setq reftex-last-toc-file   (buffer-file-name))
+  (setq reftex-last-toc-file   (reftex--get-buffer-identifier))
   (setq reftex-last-toc-master (reftex-TeX-master-file))
 
   (set-marker reftex-toc-return-marker (point))
@@ -211,7 +211,8 @@ When called with a raw \\[universal-argument] prefix, rescan the document first.
   (let* ((this-buf (current-buffer))
          (docstruct-symbol reftex-docstruct-symbol)
          (xr-data (assq 'xr (symbol-value reftex-docstruct-symbol)))
-         (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
+         (xr-alist (cons (cons "" (reftex--get-buffer-identifier))
+                         (nth 1 xr-data)))
          (here-I-am (if reftex--rebuilding-toc
                         (get 'reftex-toc :reftex-data)
                       (car (reftex-where-am-I))))
@@ -261,7 +262,7 @@ When called with a raw \\[universal-argument] prefix, rescan the document first.
 "TABLE-OF-CONTENTS on %s
 SPC=view TAB=goto RET=goto+hide [q]uit [r]escan [l]abels [f]ollow [x]r [?]Help
 ------------------------------------------------------------------------------
-" (abbreviate-file-name reftex-last-toc-master)))
+" (reftex--abbreviate-name reftex-last-toc-master)))
 
       (if reftex-use-fonts
           (put-text-property (point-min) (point) 'font-lock-face reftex-toc-header-face))
@@ -997,7 +998,7 @@ label prefix determines the wording of a reference."
        (not (active-minibuffer-window))
        (fboundp 'reftex-toc-mode)
        (get-buffer-window "*toc*" 'visible)
-       (string= reftex-last-toc-master (reftex-TeX-master-file))
+       (equal reftex-last-toc-master (reftex-TeX-master-file))
        (let (current-prefix-arg)
          (reftex-toc-recenter))))
 
index be532afb78cde0417e40fcab098e41045ef42736..a4eeec83f2853e470ece559c8e4df9fc3da536fe 100644 (file)
     (setq reftex-tables-dirty t)
     (set symbol value)))
 
-(defvar reftex--suppress-nonfile-error nil
-  "When non-nil, don't signal error in non-file buffer.
-
-Note that this is just a quick and dirty hack and is _not_ reliable at
-all.  It only circumvents disastrous error in `reftex-TeX-master-file',
-in case that the user turns on RefTeX in latex mode hook.")
 
 ;; Configuration variables
 (require 'reftex-vars)
@@ -257,6 +251,52 @@ on the menu bar.
 (defvar tex-main-file)
 (defvar outline-minor-mode)
 
+;;; =========================================================================
+;;;
+;;; Helper functions for handling both file names and buffer objects.
+;;;
+
+(defun reftex--get-buffer-identifier (&optional buffer)
+  "Return the base buffer's file name or buffer identifier.
+For file buffers, returns the file name of the base buffer.
+For non-file buffers, return the base buffer object itself.
+When BUFFER is nil, use the current buffer."
+  (let* ((buffer (or (buffer-base-buffer buffer) buffer (current-buffer))))
+    (or (buffer-local-value 'buffer-file-name buffer)
+        buffer)))
+
+(defun reftex--get-directory (file-or-buffer)
+  "Get the directory associated with FILE-OR-BUFFER.
+FILE-OR-BUFFER can be a file name or a buffer object."
+  (if (bufferp file-or-buffer)
+      (buffer-local-value 'default-directory file-or-buffer)
+    (file-name-directory file-or-buffer)))
+
+(defun reftex--abbreviate-name (file-or-buffer)
+  "Get a nice display name for FILE-OR-BUFFER.
+For files, returns the abbreviated file name.
+For buffers, returns the buffer name."
+  (if (bufferp file-or-buffer)
+      (prin1-to-string file-or-buffer)
+    (abbreviate-file-name file-or-buffer)))
+
+(defun reftex--get-basename (file-or-buffer)
+  "Get the base name (without extension) for FILE-OR-BUFFER.
+For file names, returns the file name without directory and extension.
+For buffer objects, returns a sanitized version of the buffer name
+suitable for use in LaTeX labels."
+  (if (bufferp file-or-buffer)
+      (file-name-base (buffer-name file-or-buffer))
+    (file-name-base file-or-buffer)))
+
+(defun reftex--get-truename (file-or-buffer)
+  "Get the canonical form of FILE-OR-BUFFER's identity.
+For files, returns the result of file-truename.
+For buffer objects, returns the buffer object itself."
+  (if (bufferp file-or-buffer)
+      file-or-buffer
+    (file-truename file-or-buffer)))
+
 ;;; =========================================================================
 ;;;
 ;;; Multibuffer Variables
@@ -285,10 +325,16 @@ on the menu bar.
   ;; Return the next free index for multifile symbols.
   (incf reftex-multifile-index))
 
+(defun reftex--remove-buffer-from-master-index ()
+  "Remove current buffer from `reftex-master-index-list'."
+  (setq reftex-master-index-list
+        (assq-delete-all (current-buffer) reftex-master-index-list)))
+
 (defun reftex-tie-multifile-symbols ()
   "Tie the buffer-local symbols to globals connected with the master file.
 If the symbols for the current master file do not exist, they are created."
-  (let* ((master (file-truename (reftex-TeX-master-file)))
+  (let* ((master (reftex-TeX-master-file))
+         (master (reftex--get-truename master))
          (index (assoc master reftex-master-index-list))
          (symlist reftex-multifile-symbols)
          symbol symname newflag)
@@ -299,7 +345,11 @@ If the symbols for the current master file do not exist, they are created."
       ;; Get a new index and add info to the alist.
       (setq index (reftex-next-multifile-index)
             newflag t)
-      (push (cons master index) reftex-master-index-list))
+      (push (cons master index) reftex-master-index-list)
+      (when (bufferp master)
+        (with-current-buffer master
+          (add-hook 'kill-buffer-hook
+                    #'reftex--remove-buffer-from-master-index nil t))))
 
     ;; Get/create symbols and tie them.
     (while symlist
@@ -332,74 +382,76 @@ If the symbols for the current master file do not exist, they are created."
   ;; When AUCTeX is loaded, we will use it's more sophisticated method.
   ;; We also support the default TeX and LaTeX modes by checking for a
   ;; variable tex-main-file.
-  (let
-      ((master
-        (cond
-        ;; Test if we're in a subfile using the subfiles document
-        ;; class, e.g., \documentclass[main.tex]{subfiles}.  It's
-        ;; argument is the main file, however it's not really the
-        ;; master file in `TeX-master-file' or `tex-main-file's
-        ;; sense.  It should be used for references but not for
-        ;; compilation, thus subfiles use a setting of
-        ;; `TeX-master'/`tex-main-file' being themselves.
-        ((save-excursion
-            (goto-char (point-min))
-            (re-search-forward
-             "^[[:space:]]*\\\\documentclass\\[\\([^]]+\\)\\]{subfiles}"
-             nil t))
-          (match-string-no-properties 1))
-         ;; AUCTeX is loaded.  Use its mechanism.
-         ((fboundp 'TeX-master-file)
-          (condition-case nil
-              (TeX-master-file t)
-            (error (buffer-file-name))))
-         ;; Emacs LaTeX mode
-         ((fboundp 'tex-main-file) (tex-main-file))
-         ;; Check the `TeX-master' variable.
-         ((boundp 'TeX-master)
+  (with-current-buffer (or (buffer-base-buffer) (current-buffer))
+    (let
+        ;; Set master to a file name (possibly non-existent), or nil:
+        ((master
           (cond
-           ((eq TeX-master t)
-            (buffer-file-name))
-           ((eq TeX-master 'shared)
-            (setq TeX-master (read-file-name "Master file: "
-                                             nil nil t nil)))
-           (TeX-master)
+          ;; Test if we're in a subfile using the subfiles document
+          ;; class, e.g., \documentclass[main.tex]{subfiles}.  It's
+          ;; argument is the main file, however it's not really the
+          ;; master file in `TeX-master-file' or `tex-main-file's
+          ;; sense.  It should be used for references but not for
+          ;; compilation, thus subfiles use a setting of
+          ;; `TeX-master'/`tex-main-file' being themselves.
+          ((save-excursion
+              (goto-char (point-min))
+              (re-search-forward
+               "^[[:space:]]*\\\\documentclass\\[\\([^]]+\\)\\]{subfiles}"
+               nil t))
+            (match-string-no-properties 1))
+           ;; AUCTeX is loaded.  Use its mechanism.
+           ((fboundp 'TeX-master-file)
+            (condition-case nil
+                (TeX-master-file t)
+              (error (buffer-file-name))))
+           ;; Emacs LaTeX mode
+           ((fboundp 'tex-main-file)
+            (condition-case nil
+                (tex-main-file)
+              (error (buffer-file-name))))
+           ;; Check the `TeX-master' variable.
+           ((boundp 'TeX-master)
+            (cond
+             ((eq TeX-master t)
+              (buffer-file-name))
+             ((eq TeX-master 'shared)
+              (setq TeX-master (read-file-name "Master file: "
+                                               nil nil t nil)))
+             (TeX-master)
+             (t
+              (setq TeX-master (read-file-name "Master file: "
+                                               nil nil t nil)))))
+           ;; Check the `tex-main-file' variable.
+           ((boundp 'tex-main-file)
+            ;; This is the variable from the default TeX modes.
+            (cond
+             ((stringp tex-main-file)
+              ;; ok, this must be it
+              tex-main-file)
+             (t
+              ;; In this case, the buffer is its own master.
+              (buffer-file-name))))
+           ;; We know nothing about master file.  Assume this is a
+           ;; master file.
            (t
-            (setq TeX-master (read-file-name "Master file: "
-                                             nil nil t nil)))))
-         ;; Check the `tex-main-file' variable.
-         ((boundp 'tex-main-file)
-          ;; This is the variable from the default TeX modes.
-          (cond
-           ((stringp tex-main-file)
-            ;; ok, this must be it
-            tex-main-file)
-           (t
-            ;; In this case, the buffer is its own master.
-            (buffer-file-name))))
-         ;; We know nothing about master file.  Assume this is a
-         ;; master file.
-         (t
-          (buffer-file-name)))))
-    (cond
-     ((null master)
-      (or reftex--suppress-nonfile-error
-          (error "Need a filename for this buffer, please save it first")))
-     ((or (file-exists-p (concat master ".tex"))
-          (find-buffer-visiting (concat master ".tex")))
-      ;; Ahh, an extra .tex was missing...
-      (setq master (concat master ".tex")))
-     ((or (file-exists-p master)
-          (find-buffer-visiting master))
-      ;; We either see the file, or have a buffer on it.  OK.
-      )
-     (t
-      ;; Use buffer file name.
-      (setq master (buffer-file-name))))
-    (if (and (not master)
-             reftex--suppress-nonfile-error)
-        "<none>.tex"
-      (expand-file-name master))))
+            (buffer-file-name)))))
+      (cond
+       ((null master))
+       ((or (file-exists-p (concat master ".tex"))
+            (find-buffer-visiting (concat master ".tex")))
+        ;; Ahh, an extra .tex was missing...
+        (setq master (concat master ".tex")))
+       ((or (file-exists-p master)
+            (find-buffer-visiting master))
+        ;; We either see the file, or have a buffer on it.  OK.
+        )
+       (t
+        ;; Use buffer file name.
+        (setq master (buffer-file-name))))
+      (if master
+          (expand-file-name master)
+        (current-buffer)))))
 
 (defun reftex-is-multi ()
   ;; Tell if this is a multifile document.  When not sure, say yes.
@@ -722,7 +774,7 @@ on next use."
 (defun reftex-reset-scanning-information ()
   "Reset the symbols containing information from buffer scanning.
 This enforces rescanning the buffer on next use."
-  (if (string= reftex-last-toc-master (reftex-TeX-master-file))
+  (if (equal reftex-last-toc-master (reftex-TeX-master-file))
       (reftex-erase-buffer "*toc*"))
   (let ((symlist reftex-multifile-symbols)
         symbol)
@@ -1115,11 +1167,6 @@ This enforces rescanning the buffer on next use."
   ;; But, when RESCAN is -1, don't rescan even if docstruct is empty.
   ;; When FILE is non-nil, parse only from that file.
 
-  ;; Error out in a buffer without a file.
-  (if (and reftex-mode
-          (not (buffer-file-name)))
-      (error "RefTeX works only in buffers visiting a file"))
-
   ;; Make sure we have the symbols tied
   (if (eq reftex-docstruct-symbol nil)
       ;; Symbols are not yet tied: Tie them.
@@ -1167,16 +1214,26 @@ This enforces rescanning the buffer on next use."
 
 (defun reftex-access-parse-file (action)
   "Perform ACTION on the parse file (the .rel file).
-Valid actions are: readable, restore, read, kill, write."
+Valid actions are: readable, restore, read, kill, write.
+For non-file buffers, persistence operations are skipped."
   (let* ((list (symbol-value reftex-docstruct-symbol))
          (docstruct-symbol reftex-docstruct-symbol)
          (master (reftex-TeX-master-file))
          (enable-local-variables nil)
-         (file (if (string-match "\\.[a-zA-Z]+\\'" master)
-                   (concat (substring master 0 (match-beginning 0))
-                           reftex-parse-file-extension)
-                 (concat master reftex-parse-file-extension))))
+         (non-file (bufferp master))
+         (file (if non-file
+                   nil
+                 (if (string-match "\\.[a-zA-Z]+\\'" master)
+                     (concat (substring master 0 (match-beginning 0))
+                             reftex-parse-file-extension)
+                   (concat master reftex-parse-file-extension)))))
     (cond
+     ;; For non-file buffers, skip file operations but allow initialization.
+     (non-file (cond ((eq action 'readable) nil)
+                     ((eq action 'read) nil)
+                     ((eq action 'kill) t)
+                     ((eq action 'restore)
+                      (error "Cannot restore for non-file buffer"))))
      ((eq action 'readable)
       (file-readable-p file))
      ((eq action 'restore)
@@ -1250,7 +1307,9 @@ Valid actions are: readable, restore, read, kill, write."
   (let* ((real-master (reftex-TeX-master-file))
          (parsed-master
           (nth 1 (assq 'bof (symbol-value reftex-docstruct-symbol)))))
-    (unless (string= (file-truename real-master) (file-truename parsed-master))
+    ;; Skip this check for buffer objects.
+    (unless (equal (reftex--get-truename real-master)
+                   (reftex--get-truename parsed-master))
       (message "Master file name in load file is different: %s versus %s"
                parsed-master real-master)
       (error "Master file name error")))
@@ -1291,7 +1350,7 @@ Valid actions are: readable, restore, read, kill, write."
                   (mapconcat
                    (lambda (x)
                      (format fmt (incf n) (or (car x) "")
-                             (abbreviate-file-name (cdr x))))
+                             (reftex--abbreviate-name (cdr x))))
                    xr-alist ""))
                  nil t))
           (cond
@@ -1309,8 +1368,11 @@ Valid actions are: readable, restore, read, kill, write."
   "Find FILE of type TYPE in MASTER-DIR or on the path associated with TYPE.
 If the file does not have any of the valid extensions for TYPE,
 try first the default extension and only then the naked file name.
-When DIE is non-nil, throw an error if file not found."
-  (let* ((rec-values (if reftex-search-unrecursed-path-first '(nil t) '(t)))
+When DIE is non-nil, throw an error if file not found.
+When FILE is a buffer object, return that buffer."
+  (if (bufferp file)
+      file
+    (let* ((rec-values (if reftex-search-unrecursed-path-first '(nil t) '(t)))
          (extensions (cdr (assoc type reftex-file-extensions)))
          (def-ext (car extensions))
          (ext-re (concat "\\("
@@ -1345,7 +1407,7 @@ When DIE is non-nil, throw an error if file not found."
            (setq file1 (reftex-find-file-on-path f path master-dir)))))))
     (cond (file1 file1)
           (die (error "No such file: %s" file))
-          (t (message "No such file: %s (ignored)" file) nil))))
+          (t (message "No such file: %s (ignored)" file) nil)))))
 
 (defun reftex-find-file-externally (file type &optional master-dir)
   ;; Use external program to find FILE.
@@ -1752,7 +1814,9 @@ When DIE is non-nil, throw an error if file not found."
   ;; initializations according to `reftex-initialize-temporary-buffers',
   ;; and mark the buffer to be killed after use.
 
-  (let ((buf (find-buffer-visiting file)))
+  (let ((buf (if (bufferp file)
+                 file
+               (find-buffer-visiting file))))
 
     (cond (buf
            ;; We have it already as a buffer - just return it
index 4e5053065cdc5f46379e18cfaa1a28a3763b4a32..3a4d9b1f2e5d4cc9996b1d9ecb7209c696484a73 100644 (file)
@@ -548,6 +548,329 @@ This is with listings package:
 \\end{document}"))
       (kill-buffer (file-name-nondirectory tex-file)))))
 
+;;; non-file buffers
+
+(ert-deftest reftex-all-used-citation-keys-buffer ()
+  "Test `reftex-all-used-citation-keys' on a buffer without a file."
+  (with-temp-buffer
+    (insert "\
+\\documentclass{article}
+\\usepackage{biblatex}
+\\begin{document}
+
+Standard commands:
+\\cite[pre][pos]{cite:2022}
+\\Cite[pos]{Cite:2022}
+\\parencite{parencite:2022}
+\\Parencite[pre][]{Parencite:2022}
+\\footcite[][]{footcite:2022}
+\\footcitetext[pre][pos]{footcitetext:2022}
+
+Style specific commands:
+\\textcite{textcite:2022}
+\\Textcite[pos]{Textcite:2022}
+\\smartcite[pre][pos]{smartcite:2022}
+\\Smartcite[pre][]{Smartcite:2022}
+\\cite*[pre][pos]{cite*:2022}
+\\parencite*[][]{parencite*:2022}
+
+Style independent commands:
+\\autocite[pre][pos]{autocite:2022}
+\\autocite*[pos]{autocite*:2022}
+\\Autocite[pre][]{Autocite:2022}
+\\Autocite*{Autocite*:2022}
+
+Text commands:
+\\citeauthor[pre][pos]{citeauthor:2022}
+\\citeauthor*[pre][]{citeauthor*:2022}
+\\Citeauthor[pos]{Citeauthor:2022}
+\\Citeauthor*{Citeauthor*:2022}
+\\citetitle[][]{citetitle:2022}
+\\citetitle*[pre][pos]{citetitle*:2022}
+\\citeyear[pre][pos]{citeyear:2022}
+\\citeyear*[pre][pos]{citeyear*:2022}
+\\citedate[pre][pos]{citedate:2022}
+\\citedate*[pre][pos]{citedate*:2022}
+\\citeurl[pre][pos]{citeurl:2022}
+
+Special commands:
+\\nocite{nocite:2022}
+\\fullcite[pos]{fullcite:2022}
+\\footfullcite[][]{fullfootcite:2022}
+``volcite'' macros have different number of args.
+\\volcite{2}{volcite:2022}
+\\Volcite[pre]{1}{Volcite:2022}
+\\pvolcite{1}[pg]{pvolcite:2022}
+\\Pvolcite[pre]{2}[pg]{Pvolcite:2022}
+\\fvolcite[pre]{3}[pg]{fvolcite:2022}
+\\ftvolcite[pre]{3}[pg]{ftvolcite:2022}
+\\svolcite[pre]{2}[pg]{svolcite:2022}
+\\Svolcite[pre]{4}[pg]{Svolcite:2022}
+\\tvolcite[pre]{5}[pg]{tvolcite:2022}
+\\Tvolcite[pre]{2}[pg]{Tvolcite:2022}
+\\avolcite[pre]{3}[pg]{avolcite:2022}
+\\Avolcite[pre]{1}[pg]{Avolcite:2022}
+\\Notecite[pre]{Notecite:2022}
+\\pnotecite[pre]{pnotecite:2022}
+\\Pnotecite[pre]{Pnotecite:2022}
+\\fnotecite[pre]{fnotecite:2022}
+
+Natbib compatibility commands:
+\\citet{citet:2022}
+\\citet*[pre][pos]{citet*:2022}
+\\citep[pre][pos]{citep:2022}
+\\citep*[pos]{citep*:2022}
+\\citealt[pre][]{citealt:2022}
+\\citealt*[][]{citealt*:2022}
+\\citealp[pre][pos]{citealp:2022}
+\\citealp*{citealp*:2022}
+\\Citet[pre][pos]{Citet:2022}
+\\Citet*[pre][pos]{Citet*:2022}
+\\Citep[pre][pos]{Citep:2022}
+\\Citep*[pre][pos]{Citep*:2022}
+
+Qualified Citation Lists:
+\\cites(Global Prenote)(Global Postnote)[pre][post]{cites:1}[pre][post]{cites:2}
+\\Cites(Global Prenote)(Global Postnote)[pre][post]{Cites:1}[pre][post]{Cites:2}
+\\parencites(Global Prenote)(Global Postnote)[pre][post]{parencites:1}
+  [pre][post]{parencites:2}
+\\Parencites(Global Prenote)(Global Postnote)[pre][post]{Parencites:1}{Parencites:2}
+\\footcites[pre][post]{footcites:1}[pre][post]{footcites:2}
+\\footcitetexts{footcitetexts:1}{footcitetexts:2}
+\\smartcites{smartcites:1}
+% This is comment about \\smartcites{smartcites:2}
+[pre][post]{smartcites:2}
+% And this should be ignored \\smartcites{smartcites:3}{smartcites:4}
+
+
+Test for bug#56655:
+There was a few \\% of increase in budget \\Citep*{bug:56655}.
+
+And this should be % \\cite{ignored}.
+\\end{document}")
+    (tex-mode)
+    (let ((keys (reftex-all-used-citation-keys)))
+      (should (equal (sort keys #'string<)
+                     (sort (list
+                           ;; Standard commands:
+                           "cite:2022"      "Cite:2022"
+                           "parencite:2022" "Parencite:2022"
+                           "footcite:2022"  "footcitetext:2022"
+                           ;; Style specific commands:
+                           "textcite:2022"  "Textcite:2022"
+                           "smartcite:2022" "Smartcite:2022"
+                           "cite*:2022" "parencite*:2022"
+                           ;; Style independent commands:
+                           "autocite:2022"  "autocite*:2022"
+                           "Autocite:2022"  "Autocite*:2022"
+                           ;; Text commands
+                           "citeauthor:2022" "citeauthor*:2022"
+                           "Citeauthor:2022" "Citeauthor*:2022"
+                           "citetitle:2022"  "citetitle*:2022"
+                           "citeyear:2022"   "citeyear*:2022"
+                           "citedate:2022"   "citedate*:2022"
+                           "citeurl:2022"
+                           ;; Special commands:
+                           "nocite:2022"     "fullcite:2022"
+                           "fullfootcite:2022"
+                           "volcite:2022"   "Volcite:2022"
+                           "pvolcite:2022"  "Pvolcite:2022"
+                           "fvolcite:2022"  "ftvolcite:2022"
+                           "svolcite:2022"  "Svolcite:2022"
+                           "tvolcite:2022"  "Tvolcite:2022"
+                           "avolcite:2022"  "Avolcite:2022"
+                           "Notecite:2022"  "pnotecite:2022"
+                           "Pnotecite:2022" "fnotecite:2022"
+                           ;; Natbib compatibility commands:
+                           "citet:2022"   "citet*:2022"
+                           "citep:2022"   "citep*:2022"
+                           "citealt:2022" "citealt*:2022"
+                           "citealp:2022" "citealp*:2022"
+                           "Citet:2022"   "Citet*:2022"
+                           "Citep:2022"   "Citep*:2022"
+                           ;; Qualified Citation Lists
+                           "cites:1"         "cites:2"
+                           "Cites:1"         "Cites:2"
+                           "parencites:1"    "parencites:2"
+                           "Parencites:1"    "Parencites:2"
+                           "footcites:1"     "footcites:2"
+                           "footcitetexts:1" "footcitetexts:2"
+                           "smartcites:1"    "smartcites:2"
+                           "bug:56655")
+                         #'string<))))))
+
+(ert-deftest reftex-renumber-simple-labels-buffer ()
+  "Test `reftex-renumber-simple-labels' on a buffer without a file."
+  (let ((temp-buffer (generate-new-buffer " *temp*")))
+    (unwind-protect
+        (with-current-buffer temp-buffer
+          (insert "\
+\\documentclass{article}
+\\usepackage{tcolorbox}
+\\tcbuselibrary{theorems}
+\\usepackage{fancyvrb}
+\\usepackage{listings}
+
+\\begin{document}
+
+This is with tcolorbox package:
+\\begin{problem}[%
+    colback                = white          ,
+    colframe               = red!50!black   ,
+    fonttitle              = \\bfseries      ,
+    description delimiters = {\\flqq}{\\frqq} ,
+    label                  = {problem:2}]{Prove RH2}{}
+  Problem
+\\end{problem}
+
+This is with vanilla \\LaTeX:
+\\begin{equation}
+  \\label{eq:2}
+  2
+\\end{equation}
+By \\eqref{eq:2} and \\ref{problem:2}
+
+This is with tcolorbox package:
+\\begin{problem}[%
+    colback=white,
+    colframe=red!50!black,
+    fonttitle=\\bfseries,
+    theorem label supplement={hypertarget={XYZ-##1}},
+    theorem full label supplement={code={\\marginnote{##1}}},
+    label={problem:1}]{Prove RH1}{}
+  Problem
+\\end{problem}
+
+This is with vanilla \\LaTeX:
+\\begin{equation}
+  \\label{eq:1}
+  1
+\\end{equation}
+
+\\Cref{problem:1} and \\pageref{eq:1}.
+
+\\begin{problem}[label={problem:6}]{Some Problem}{}
+  Problem
+\\end{problem}
+
+\\Ref{problem:6}.
+
+This is with fancyvrb package:
+\\begin{Verbatim}[reflabel={lst:6}]
+Some Verb Content
+\\end{Verbatim}
+
+\\pageref{lst:6}
+
+This is with listings package:
+\\begin{lstlisting}[language=elisp,caption=Some Caption,label={lst:3}]
+(car (cons 1 '(2)))
+\\end{lstlisting}
+
+\\ref{lst:3}
+
+\\end{document}")
+
+          ;; The label prefix must be known to RefTeX:
+          (add-to-list 'reftex-label-alist
+                       '("problem" ?p "problem:" "~\\ref{%s}"
+                         nil nil nil)
+                       t)
+          (add-to-list 'reftex-label-alist
+                       '("Verbatim" ?l "lst:" "~\\ref{%s}"
+                         nil nil nil)
+                       t)
+          ;; The environments must be known to RefTeX otherwise the labels
+          ;; aren't parsed correctly:
+          (add-to-list 'reftex-label-regexps
+                       (concat "\\\\begin{\\(?:problem\\|Verbatim\\)}"
+                               "\\[[^][]*"
+                               "\\(?:{[^}{]*"
+                               "\\(?:{[^}{]*"
+                               "\\(?:{[^}{]*}[^}{]*\\)*"
+                               "}[^}{]*\\)*"
+                               "}[^][]*\\)*"
+                               "\\<\\(?:ref\\)?label[[:space:]]*=[[:space:]]*"
+                               "{?\\(?1:[^] ,}\r\n\t%]+\\)"
+                               "[^]]*\\]")
+                       t)
+          ;; Always run this after changing `reftex-label-regexps':
+          (reftex-compile-variables)
+
+          ;; Silence the user query:
+          (cl-letf (((symbol-function 'yes-or-no-p) #'always))
+            (reftex-renumber-simple-labels))
+
+          (should (string= (buffer-string)
+                           "\
+\\documentclass{article}
+\\usepackage{tcolorbox}
+\\tcbuselibrary{theorems}
+\\usepackage{fancyvrb}
+\\usepackage{listings}
+
+\\begin{document}
+
+This is with tcolorbox package:
+\\begin{problem}[%
+    colback                = white          ,
+    colframe               = red!50!black   ,
+    fonttitle              = \\bfseries      ,
+    description delimiters = {\\flqq}{\\frqq} ,
+    label                  = {problem:1}]{Prove RH2}{}
+  Problem
+\\end{problem}
+
+This is with vanilla \\LaTeX:
+\\begin{equation}
+  \\label{eq:1}
+  2
+\\end{equation}
+By \\eqref{eq:1} and \\ref{problem:1}
+
+This is with tcolorbox package:
+\\begin{problem}[%
+    colback=white,
+    colframe=red!50!black,
+    fonttitle=\\bfseries,
+    theorem label supplement={hypertarget={XYZ-##1}},
+    theorem full label supplement={code={\\marginnote{##1}}},
+    label={problem:2}]{Prove RH1}{}
+  Problem
+\\end{problem}
+
+This is with vanilla \\LaTeX:
+\\begin{equation}
+  \\label{eq:2}
+  1
+\\end{equation}
+
+\\Cref{problem:2} and \\pageref{eq:2}.
+
+\\begin{problem}[label={problem:3}]{Some Problem}{}
+  Problem
+\\end{problem}
+
+\\Ref{problem:3}.
+
+This is with fancyvrb package:
+\\begin{Verbatim}[reflabel={lst:1}]
+Some Verb Content
+\\end{Verbatim}
+
+\\pageref{lst:1}
+
+This is with listings package:
+\\begin{lstlisting}[language=elisp,caption=Some Caption,label={lst:2}]
+(car (cons 1 '(2)))
+\\end{lstlisting}
+
+\\ref{lst:2}
+
+\\end{document}")))
+      (kill-buffer temp-buffer))))
+
+
 ;;; Autoload tests
 
 ;; Test to check whether reftex autoloading mechanisms are working