Add "Package:" file headers to denote built-in packages.
[bpt/emacs.git] / lisp / textmodes / reftex-index.el
1 ;;; reftex-index.el --- index support with RefTeX
2
3 ;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4 ;; 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 ;; Author: Carsten Dominik <dominik@science.uva.nl>
7 ;; Maintainer: auctex-devel@gnu.org
8 ;; Version: 4.31
9 ;; Package: reftex
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;;; Code:
29
30 (eval-when-compile (require 'cl))
31 (provide 'reftex-index)
32 (require 'reftex)
33 ;;;
34
35 ;; START remove for XEmacs release
36 (defvar mark-active)
37 (defvar transient-mark-mode)
38 (defvar TeX-master)
39 ;; END remove for XEmacs release
40
41 (declare-function texmathp "ext:texmathp" ())
42
43 (defun reftex-index-selection-or-word (&optional arg phrase)
44 "Put selection or the word near point into the default index macro.
45 This uses the information in `reftex-index-default-macro' to make an index
46 entry. The phrase indexed is the current selection or the word near point.
47 When called with one `C-u' prefix, let the user have a chance to edit the
48 index entry. When called with 2 `C-u' as prefix, also ask for the index
49 macro and other stuff.
50 When called inside TeX math mode as determined by the `texmathp.el' library
51 which is part of AUCTeX, the string is first processed with the
52 `reftex-index-math-format', which see."
53 (interactive "P")
54 (let* ((use-default (not (equal arg '(16)))) ; check for double prefix
55 ;; check if we have an active selection
56 (active (if (featurep 'xemacs)
57 (and zmacs-regions (region-exists-p)) ; XEmacs
58 (and transient-mark-mode mark-active))) ; Emacs
59 (beg (if active
60 (region-beginning)
61 (save-excursion
62 (skip-syntax-backward "w\\") (point))))
63 (end (if active
64 (region-end)
65 (save-excursion
66 (skip-syntax-forward "w\\") (point))))
67 (sel (buffer-substring beg end))
68 (mathp (condition-case nil (texmathp) (error nil)))
69 (current-prefix-arg nil) ; we want to call reftex-index without prefix.
70 key def-char def-tag full-entry)
71
72 (if phrase
73 (progn
74 (reftex-index-visit-phrases-buffer)
75 (reftex-index-new-phrase sel))
76
77 (if (equal sel "")
78 ;; Nothing selected, no word, so use full reftex-index command
79 (reftex-index)
80 ;; OK, we have something to index here.
81 ;; Add the dollars when necessary
82 (setq key (if mathp
83 (format reftex-index-math-format sel)
84 sel))
85 ;; Get info from `reftex-index-default-macro'
86 (setq def-char (if use-default (car reftex-index-default-macro)))
87 (setq def-tag (if use-default (nth 1 reftex-index-default-macro)))
88 ;; Does the user want to edit the entry?
89 (setq full-entry (if arg
90 (reftex-index-complete-key
91 def-tag nil (cons key 0))
92 key))
93 ;; Delete what is in the buffer and make the index entry
94 (delete-region beg end)
95 (reftex-index def-char full-entry def-tag sel)))))
96
97 (defun reftex-index (&optional char key tag sel no-insert)
98 "Query for an index macro and insert it along with its arguments.
99 The index macros available are those defined in `reftex-index-macro' or
100 by a call to `reftex-add-index-macros', typically from an AUCTeX style file.
101 RefteX provides completion for the index tag and the index key, and
102 will prompt for other arguments."
103
104 (interactive)
105
106 ;; Ensure access to scanning info
107 (reftex-ensure-index-support t)
108 (reftex-access-scan-info current-prefix-arg)
109
110 ;; Find out which macro we are going to use
111 (let* ((char (or char
112 (reftex-select-with-char reftex-query-index-macro-prompt
113 reftex-query-index-macro-help)))
114 (macro (nth 1 (assoc char reftex-key-to-index-macro-alist)))
115 (entry (or (assoc macro reftex-index-macro-alist)
116 (error "No index macro associated with %c" char)))
117 (ntag (nth 1 entry))
118 (tag (or tag (nth 1 entry)))
119 (nargs (nth 4 entry))
120 (nindex (nth 5 entry))
121 (opt-args (nth 6 entry))
122 (repeat (nth 7 entry))
123 opt tag1 value)
124
125 ;; Get the supported arguments
126 (if (stringp tag)
127 (setq tag1 tag)
128 (setq tag1 (or (reftex-index-complete-tag tag opt-args) "")))
129 (setq key (or key
130 (reftex-index-complete-key
131 (if (string= tag1 "") "idx" tag1)
132 (member nindex opt-args))))
133
134 ;; Insert the macro and ask for any additional args
135 (insert macro)
136 (loop for i from 1 to nargs do
137 (setq opt (member i opt-args)
138 value (cond ((= nindex i) key)
139 ((equal ntag i) tag1)
140 (t (read-string (concat "Macro arg nr. "
141 (int-to-string i)
142 (if opt " (optional)" "")
143 ": ")))))
144 (unless (and opt (string= value ""))
145 (insert (if opt "[" "{") value (if opt "]" "}"))))
146 (and repeat (stringp sel) (insert sel))
147 (and key reftex-plug-into-AUCTeX (fboundp 'LaTeX-add-index-entries)
148 (LaTeX-add-index-entries key))
149 (reftex-index-update-taglist tag1)
150 (reftex-notice-new)))
151
152 (defun reftex-default-index ()
153 (cond ((null reftex-index-default-tag) nil)
154 ((stringp reftex-index-default-tag) reftex-index-default-tag)
155 (t (or (get reftex-docstruct-symbol 'default-index-tag)
156 "idx"))))
157
158 (defun reftex-update-default-index (tag &optional tag-list)
159 (if (and (not (equal tag ""))
160 (stringp tag)
161 (eq reftex-index-default-tag 'last)
162 (or (null tag-list)
163 (member tag tag-list)))
164 (put reftex-docstruct-symbol 'default-index-tag tag)))
165
166 (defun reftex-index-complete-tag (&optional itag opt-args)
167 ;; Ask the user for a tag, completing on known tags.
168 ;; ITAG is the argument number which contains the tag.
169 ;; OPT-ARGS is a list of optional argument indices, as given by
170 ;; `reftex-parse-args'.
171 (let* ((opt (and (integerp itag) (member itag opt-args)))
172 (index-tags (cdr (assq 'index-tags
173 (symbol-value reftex-docstruct-symbol))))
174 (default (reftex-default-index))
175 (prompt (concat "Index tag"
176 (if (or opt default)
177 (format " (%s): "
178 (concat
179 (if opt "optional" "")
180 (if default
181 (concat (if opt ", " "")
182 (format "default %s" default))
183 "")))
184 ": ")))
185 (tag (completing-read prompt (mapcar 'list index-tags))))
186 (if (and default (equal tag "")) (setq tag default))
187 (reftex-update-default-index tag)
188 tag))
189
190 (defun reftex-index-select-tag ()
191 ;; Have the user select an index tag.
192 ;; FIXME: should we cache tag-alist, prompt and help?
193 (let* ((index-tags (cdr (assoc 'index-tags
194 (symbol-value reftex-docstruct-symbol))))
195 (default (reftex-default-index)))
196 (cond
197 ((null index-tags)
198 (error "No index tags available"))
199
200 ((= (length index-tags) 1)
201 ;; Just one index, use it
202 (car index-tags))
203
204 ((> (length index-tags) 1)
205 ;; Several indices, ask.
206 (let* ((tags (copy-sequence index-tags))
207 (cnt 0)
208 tag-alist i val len tag prompt help rpl)
209 ;; Move idx and glo up in the list to ensure ?i and ?g shortcuts
210 (if (member "glo" tags)
211 (setq tags (cons "glo" (delete "glo" tags))))
212 (if (member "idx" tags)
213 (setq tags (cons "idx" (delete "idx" tags))))
214 ;; Find unique shortcuts for each index.
215 (while (setq tag (pop tags))
216 (setq len (length tag)
217 i -1
218 val nil)
219 (catch 'exit
220 (while (and (< (incf i) len) (null val))
221 (unless (assq (aref tag i) tag-alist)
222 (push (list (aref tag i)
223 tag
224 (concat (substring tag 0 i)
225 "[" (substring tag i (incf i)) "]"
226 (substring tag i)))
227 tag-alist)
228 (throw 'exit t)))
229 (push (list (+ ?0 (incf cnt)) tag
230 (concat "[" (int-to-string cnt) "]:" tag))
231 tag-alist)))
232 (setq tag-alist (nreverse tag-alist))
233 ;; Compute Prompt and Help strings
234 (setq prompt
235 (concat
236 (format "Select Index%s: "
237 (if default (format " (Default <%s>)" default) ""))
238 (mapconcat (lambda(x) (nth 2 x)) tag-alist " ")))
239 (setq help
240 (concat "Select an Index\n===============\n"
241 (if default
242 (format "[^M] %s (the default)\n" default)
243 "")
244 (mapconcat (lambda(x)
245 (apply 'format "[%c] %s" x))
246 tag-alist "\n")))
247 ;; Query the user for an index-tag
248 (setq rpl (reftex-select-with-char prompt help 3 t))
249 (message "")
250 (if (and default (equal rpl ?\C-m))
251 default
252 (if (assq rpl tag-alist)
253 (progn
254 (reftex-update-default-index (nth 1 (assq rpl tag-alist)))
255 (nth 1 (assq rpl tag-alist)))
256 (error "No index tag associated with %c" rpl)))))
257 (t (error "This should not happen (reftex-index-select-tag)")))))
258
259 (defun reftex-index-complete-key (&optional tag optional initial)
260 ;; Read an index key, with completion.
261 ;; Restrict completion table on index tag TAG.
262 ;; OPTIONAL indicates if the arg is optional.
263 (let* ((table (reftex-sublist-nth
264 (symbol-value reftex-docstruct-symbol) 6
265 (lambda(x) (and (eq (car x) 'index)
266 (string= (nth 1 x) (or tag ""))))
267 t))
268 (prompt (concat "Index key" (if optional " (optional)" "") ": "))
269 (key (completing-read prompt table nil nil initial)))
270 key))
271
272 (defun reftex-index-update-taglist (newtag)
273 ;; add NEWTAG to the list of available index tags.
274 (let ((cell (assoc 'index-tags (symbol-value reftex-docstruct-symbol))))
275 (and newtag (cdr cell) (not (member newtag (cdr cell)))
276 (push newtag (cdr cell)))))
277
278 (defvar reftex-index-map (make-sparse-keymap)
279 "Keymap used for *Index* buffers.")
280
281 (defvar reftex-index-menu)
282
283 (defvar reftex-last-index-file nil
284 "Stores the file name from which `reftex-display-index' was called.")
285 (defvar reftex-index-tag nil
286 "Stores the tag of the index in an index buffer.")
287
288 (defvar reftex-index-return-marker (make-marker)
289 "Marker which makes it possible to return from index to old position.")
290
291 (defvar reftex-index-restriction-indicator nil)
292 (defvar reftex-index-restriction-data nil)
293
294 (defun reftex-index-mode ()
295 "Major mode for managing Index buffers for LaTeX files.
296 This buffer was created with RefTeX.
297 Press `?' for a summary of important key bindings, or check the menu.
298
299 Here are all local bindings.
300
301 \\{reftex-index-map}"
302 (interactive)
303 (kill-all-local-variables)
304 (setq major-mode 'reftex-index-mode
305 mode-name "RefTeX Index")
306 (use-local-map reftex-index-map)
307 (set (make-local-variable 'revert-buffer-function) 'reftex-index-revert)
308 (set (make-local-variable 'reftex-index-restriction-data) nil)
309 (set (make-local-variable 'reftex-index-restriction-indicator) nil)
310 (setq mode-line-format
311 (list "---- " 'mode-line-buffer-identification
312 " " 'global-mode-string
313 " R<" 'reftex-index-restriction-indicator ">"
314 " -%-"))
315 (setq truncate-lines t)
316 (when (featurep 'xemacs)
317 ;; XEmacs needs the call to make-local-hook
318 (make-local-hook 'post-command-hook)
319 (make-local-hook 'pre-command-hook))
320 (make-local-variable 'reftex-last-follow-point)
321 (easy-menu-add reftex-index-menu reftex-index-map)
322 (add-hook 'post-command-hook 'reftex-index-post-command-hook nil t)
323 (add-hook 'pre-command-hook 'reftex-index-pre-command-hook nil t)
324 (run-hooks 'reftex-index-mode-hook))
325
326 (defconst reftex-index-help
327 " AVAILABLE KEYS IN INDEX BUFFER
328 ==============================
329 ! A..Z Goto the section of entries starting with this letter.
330 n / p next-entry / previous-entry
331 SPC / TAB Show/Goto the corresponding entry in the LaTeX document.
332 RET Goto the entry and hide the *Index* window (also on mouse-2).
333 q / k Hide/Kill *Index* buffer.
334 C-c = Switch to the TOC buffer.
335 f / c Toggle follow mode / Toggle display of [c]ontext.
336 g Refresh *Index* buffer.
337 r / C-u r Reparse the LaTeX document / Reparse entire LaTeX document.
338 s Switch to a different index (for documents with multiple indices).
339 e / C-k Edit/Kill the entry.
340 * | @ Edit specific part of entry: [*]key [|]attribute [@]visual
341 With prefix: kill that part.
342 \( ) Toggle entry's beginning/end of page range property.
343 _ ^ Add/Remove parent key (to make this item a subitem).
344 } / { Restrict Index to a single document section / Widen.
345 < / > When restricted, move restriction to previous/next section.")
346
347 (defun reftex-index-show-entry (data &optional no-revisit)
348 ;; Find an index entry associated with DATA and display it highlighted
349 ;; in another window. NO-REVISIT means we are not allowed to visit
350 ;; files for this.
351 ;; Note: This function just looks for the nearest match of the
352 ;; context string and may fail if the entry moved and an identical
353 ;; entry is close to the old position. Frequent rescans make this
354 ;; safer.
355 (let* ((file (nth 3 data))
356 (literal (nth 2 data))
357 (pos (nth 4 data))
358 (re (regexp-quote literal))
359 (match
360 (cond
361 ((or (not no-revisit)
362 (reftex-get-buffer-visiting file))
363 (switch-to-buffer-other-window
364 (reftex-get-file-buffer-force file nil))
365 (goto-char (or pos (point-min)))
366 (or (looking-at re)
367 (reftex-nearest-match re (length literal))))
368 (t (message "%s" reftex-no-follow-message) nil))))
369 (when match
370 (goto-char (match-beginning 0))
371 (recenter '(4))
372 (reftex-highlight 0 (match-beginning 0) (match-end 0) (current-buffer)))
373 match))
374
375 (defun reftex-display-index (&optional tag overriding-restriction redo
376 &rest locations)
377 "Display a buffer with an index compiled from the current document.
378 When the document has multiple indices, first prompts for the correct one.
379 When index support is turned off, offer to turn it on.
380 With one or two `C-u' prefixes, rescan document first.
381 With prefix 2, restrict index to current document section.
382 With prefix 3, restrict index to region."
383
384 (interactive)
385
386 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4).
387 (let ((current-prefix-arg current-prefix-arg))
388 (reftex-ensure-index-support t)
389 (reftex-access-scan-info current-prefix-arg))
390
391 (set-marker reftex-index-return-marker (point))
392 (setq reftex-last-follow-point 1)
393
394 ;; Determine the correct index to process
395 (let* ((docstruct (symbol-value reftex-docstruct-symbol))
396 (docstruct-symbol reftex-docstruct-symbol)
397 (index-tag (or tag (reftex-index-select-tag)))
398 (master (reftex-TeX-master-file))
399 (calling-file (buffer-file-name))
400 (restriction
401 (or overriding-restriction
402 (and (not redo)
403 (reftex-get-restriction current-prefix-arg docstruct))))
404 (locations
405 ;; See if we are on an index macro as initial position
406 (or locations
407 (let* ((what-macro (reftex-what-macro-safe 1))
408 (macro (car what-macro))
409 (here-I-am (when (member macro reftex-macros-with-index)
410 (save-excursion
411 (goto-char (+ (cdr what-macro)
412 (length macro)))
413 (reftex-move-over-touching-args)
414 (reftex-where-am-I)))))
415 (if (eq (car (car here-I-am)) 'index)
416 (list (car here-I-am))))))
417 buffer-name)
418
419 (setq buffer-name (reftex-make-index-buffer-name index-tag))
420
421 ;; Goto the buffer and put it into the correct mode
422
423 (when (or restriction current-prefix-arg)
424 (reftex-kill-buffer buffer-name))
425
426 (if (get-buffer-window buffer-name)
427 (select-window (get-buffer-window buffer-name))
428 (switch-to-buffer buffer-name))
429
430 (or (eq major-mode 'reftex-index-mode) (reftex-index-mode))
431
432 ;; If the buffer is currently restricted, empty it to force update.
433 (when reftex-index-restriction-data
434 (reftex-erase-buffer))
435 (set (make-local-variable 'reftex-last-index-file) calling-file)
436 (set (make-local-variable 'reftex-index-tag) index-tag)
437 (set (make-local-variable 'reftex-docstruct-symbol) docstruct-symbol)
438 (if restriction
439 (setq reftex-index-restriction-indicator (car restriction)
440 reftex-index-restriction-data (cdr restriction))
441 (if (not redo)
442 (setq reftex-index-restriction-indicator nil
443 reftex-index-restriction-data nil)))
444 (when (= (buffer-size) 0)
445 ;; buffer is empty - fill it
446 (message "Building %s buffer..." buffer-name)
447
448 (setq buffer-read-only nil)
449 (insert (format
450 "INDEX <%s> on %s
451 Restriction: <%s>
452 SPC=view TAB=goto RET=goto+hide [e]dit [q]uit [r]escan [f]ollow [?]Help
453 ------------------------------------------------------------------------------
454 " index-tag (abbreviate-file-name master)
455 (if (eq (car (car reftex-index-restriction-data)) 'toc)
456 (nth 2 (car reftex-index-restriction-data))
457 reftex-index-restriction-indicator)))
458
459 (if (reftex-use-fonts)
460 (put-text-property 1 (point) 'face reftex-index-header-face))
461 (put-text-property 1 (point) 'intangible t)
462
463 (reftex-insert-index docstruct index-tag)
464 (goto-char (point-min))
465 (run-hooks 'reftex-display-copied-context-hook)
466 (message "Building %s buffer...done." buffer-name)
467 (setq buffer-read-only t))
468 (and locations (apply 'reftex-find-start-point (point) locations))
469 (if reftex-index-restriction-indicator
470 (message "Index restricted: <%s>" reftex-index-restriction-indicator))))
471
472 (defun reftex-insert-index (docstruct tag &optional update-one remark)
473 ;; Insert an index into the current buffer. Entries are from the
474 ;; DOCSTRUCT.
475 ;; TAG is the subindex to process.
476 ;; UPDATE-ONE: When non-nil, delete the entry at point and replace
477 ;; it with whatever the DOCSTRUCT contains.
478 ;; REMARK can be a note to add to the entry.
479 (let* ((all docstruct)
480 (indent " ")
481 (context reftex-index-include-context)
482 (context-indent (concat indent " "))
483 (section-chars (mapcar 'identity reftex-index-section-letters))
484 (this-section-char 0)
485 (font (reftex-use-fonts))
486 (bor (car reftex-index-restriction-data))
487 (eor (nth 1 reftex-index-restriction-data))
488 (mouse-face
489 (if (memq reftex-highlight-selection '(mouse both))
490 reftex-mouse-selected-face
491 nil))
492 (index-face (reftex-verified-face reftex-label-face
493 'font-lock-constant-face
494 'font-lock-reference-face))
495 sublist cell from to first-char)
496
497 ;; Make the sublist and sort it
498 (when bor
499 (setq all (or (memq bor all) all)))
500
501 (while (setq cell (pop all))
502 (if (eq cell eor)
503 (setq all nil)
504 (and (eq (car cell) 'index)
505 (equal (nth 1 cell) tag)
506 (push cell sublist))))
507 (setq sublist (sort (nreverse sublist)
508 (lambda (a b) (string< (nth 8 a) (nth 8 b)))))
509
510 (when update-one
511 ;; Delete the entry at place
512 (and (bolp) (forward-char 1))
513 (delete-region (previous-single-property-change (1+ (point)) :data)
514 (or (next-single-property-change (point) :data)
515 (point-max))))
516
517 ;; Walk through the list and insert all entries
518 (while (setq cell (pop sublist))
519 (unless update-one
520 (setq first-char (upcase (string-to-char (nth 6 cell))))
521 (when (and (not (equal first-char this-section-char))
522 (member first-char section-chars))
523 ;; There is a new initial letter, so start a new section
524 (reftex-index-insert-new-letter first-char font)
525 (setq section-chars (delete first-char section-chars)
526 this-section-char first-char))
527 (when (= this-section-char 0)
528 (setq this-section-char ?!)
529 (reftex-index-insert-new-letter this-section-char font)))
530
531 (setq from (point))
532 (insert indent (nth 7 cell))
533 (when font
534 (setq to (point))
535 (put-text-property
536 (- (point) (length (nth 7 cell))) to
537 'face index-face)
538 (goto-char to))
539
540 (when (or remark (nth 9 cell))
541 (and (< (current-column) 40)
542 ;; FIXME: maybe this is too slow?
543 (insert (make-string (max (- 40 (current-column)) 0) ?\ )))
544 (and (nth 9 cell) (insert " " (substring (nth 5 cell) (nth 9 cell))))
545 (and remark (insert " " remark)))
546
547 (insert "\n")
548 (setq to (point))
549
550 (when context
551 (insert context-indent (nth 2 cell) "\n")
552 (setq to (point)))
553 (put-text-property from to :data cell)
554 (when mouse-face
555 (put-text-property from (1- to)
556 'mouse-face mouse-face))
557 (goto-char to))))
558
559
560 (defun reftex-index-insert-new-letter (letter &optional font)
561 ;; Start a new section in the index
562 (let ((from (point)))
563 (insert "\n" letter letter letter
564 "-----------------------------------------------------------------")
565 (when font
566 (put-text-property from (point) 'face reftex-index-section-face))
567 (insert "\n")))
568
569 (defun reftex-get-restriction (arg docstruct)
570 ;; Interprete the prefix ARG and derive index restriction specs.
571 (let* ((beg (min (point) (or (condition-case nil (mark) (error nil))
572 (point-max))))
573 (end (max (point) (or (condition-case nil (mark) (error nil))
574 (point-min))))
575 bor eor label here-I-am)
576 (cond
577 ((eq arg 2)
578 (setq here-I-am (car (reftex-where-am-I))
579 bor (if (eq (car here-I-am) 'toc)
580 here-I-am
581 (reftex-last-assoc-before-elt
582 'toc here-I-am docstruct))
583 eor (car (memq (assq 'toc (cdr (memq bor docstruct))) docstruct))
584 label (nth 6 bor)))
585 ((eq arg 3)
586 (save-excursion
587 (setq label "region")
588 (goto-char beg)
589 (setq bor (car (reftex-where-am-I)))
590 (setq bor (nth 1 (memq bor docstruct)))
591 (goto-char end)
592 (setq eor (nth 1 (memq (car (reftex-where-am-I)) docstruct)))))
593 (t nil))
594 (if (and label (or bor eor))
595 (list label bor eor)
596 nil)))
597
598 (defun reftex-index-pre-command-hook ()
599 ;; Used as pre command hook in *Index* buffer
600 (reftex-unhighlight 0)
601 (reftex-unhighlight 1))
602
603 (defun reftex-index-post-command-hook ()
604 ;; Used in the post-command-hook for the *Index* buffer
605 (when (get-text-property (point) :data)
606 (and (> (point) 1)
607 (not (get-text-property (point) 'intangible))
608 (memq reftex-highlight-selection '(cursor both))
609 (reftex-highlight 1
610 (or (previous-single-property-change (1+ (point)) :data)
611 (point-min))
612 (or (next-single-property-change (point) :data)
613 (point-max)))))
614 (if (integerp reftex-index-follow-mode)
615 ;; Remove delayed action
616 (setq reftex-index-follow-mode t)
617 (and reftex-index-follow-mode
618 (not (equal reftex-last-follow-point (point)))
619 ;; Show context in other window
620 (setq reftex-last-follow-point (point))
621 (condition-case nil
622 (reftex-index-visit-location nil (not reftex-revisit-to-follow))
623 (error t)))))
624
625 (defun reftex-index-show-help ()
626 "Show a summary of special key bindings."
627 (interactive)
628 (with-output-to-temp-buffer "*RefTeX Help*"
629 (princ reftex-index-help))
630 (reftex-enlarge-to-fit "*RefTeX Help*" t)
631 ;; If follow mode is active, arrange to delay it one command
632 (if reftex-index-follow-mode
633 (setq reftex-index-follow-mode 1)))
634
635 (defun reftex-index-next (&optional arg)
636 "Move to next selectable item."
637 (interactive "p")
638 (setq reftex-callback-fwd t)
639 (or (eobp) (forward-char 1))
640 (goto-char (or (next-single-property-change (point) :data)
641 (point)))
642 (unless (get-text-property (point) :data)
643 (goto-char (or (next-single-property-change (point) :data)
644 (point)))))
645 (defun reftex-index-previous (&optional arg)
646 "Move to previous selectable item."
647 (interactive "p")
648 (setq reftex-callback-fwd nil)
649 (goto-char (or (previous-single-property-change (point) :data)
650 (point)))
651 (unless (get-text-property (point) :data)
652 (goto-char (or (previous-single-property-change (point) :data)
653 (point)))))
654 (defun reftex-index-toggle-follow ()
655 "Toggle follow (other window follows with context)."
656 (interactive)
657 (setq reftex-last-follow-point -1)
658 (setq reftex-index-follow-mode (not reftex-index-follow-mode)))
659 (defun reftex-index-toggle-context ()
660 "Toggle inclusion of label context in *Index* buffer.
661 Label context is only displayed when the labels are there as well."
662 (interactive)
663 (setq reftex-index-include-context (not reftex-index-include-context))
664 (reftex-index-revert))
665 (defun reftex-index-view-entry ()
666 "View document location in other window."
667 (interactive)
668 (reftex-index-visit-location))
669 (defun reftex-index-goto-entry-and-hide ()
670 "Go to document location in other window. Hide the *Index* window."
671 (interactive)
672 (reftex-index-visit-location 'hide))
673 (defun reftex-index-goto-entry ()
674 "Go to document location in other window. *Index* window stays."
675 (interactive)
676 (reftex-index-visit-location t))
677 (defun reftex-index-mouse-goto-line-and-hide (ev)
678 "Go to document location in other window. Hide the *Index* window."
679 (interactive "e")
680 (mouse-set-point ev)
681 (reftex-index-visit-location 'hide))
682 (defun reftex-index-quit ()
683 "Hide the *Index* window and do not move point."
684 (interactive)
685 (or (one-window-p) (delete-window))
686 (switch-to-buffer (marker-buffer reftex-index-return-marker))
687 (goto-char (or (marker-position reftex-index-return-marker) (point))))
688 (defun reftex-index-quit-and-kill ()
689 "Kill the *Index* buffer."
690 (interactive)
691 (kill-buffer (current-buffer))
692 (or (one-window-p) (delete-window))
693 (switch-to-buffer (marker-buffer reftex-index-return-marker))
694 (goto-char (or (marker-position reftex-index-return-marker) (point))))
695 (defun reftex-index-goto-toc (&rest ignore)
696 "Switch to the table of contents of the current document.
697 The function will go to the section where the entry at point was defined."
698 (interactive)
699 (if (get-text-property (point) :data)
700 (reftex-index-goto-entry)
701 (switch-to-buffer (marker-buffer reftex-index-return-marker)))
702 (delete-other-windows)
703 (reftex-toc))
704 (defun reftex-index-rescan (&rest ignore)
705 "Regenerate the *Index* buffer after reparsing file of section at point."
706 (interactive)
707 (let ((index-tag reftex-index-tag))
708 (if (and reftex-enable-partial-scans
709 (null current-prefix-arg))
710 (let* ((data (get-text-property (point) :data))
711 (file (nth 3 data))
712 (line (+ (count-lines (point-min) (point)) (if (bolp) 1 0))))
713 (if (not file)
714 (error "Don't know which file to rescan. Try `C-u r'")
715 (switch-to-buffer (reftex-get-file-buffer-force file))
716 (setq current-prefix-arg '(4))
717 (reftex-display-index index-tag nil 'redo line)))
718 (reftex-index-Rescan))
719 (reftex-kill-temporary-buffers)))
720 (defun reftex-index-Rescan (&rest ignore)
721 "Regenerate the *Index* buffer after reparsing the entire document."
722 (interactive)
723 (let ((index-tag reftex-index-tag)
724 (line (+ (count-lines (point-min) (point)) (if (bolp) 1 0))))
725 (switch-to-buffer
726 (reftex-get-file-buffer-force reftex-last-index-file))
727 (setq current-prefix-arg '(16))
728 (reftex-display-index index-tag nil 'redo line)))
729 (defun reftex-index-revert (&rest ignore)
730 "Regenerate the *Index* from the internal lists. No reparsing os done."
731 (interactive)
732 (let ((buf (current-buffer))
733 (index-tag reftex-index-tag)
734 (data (get-text-property (point) :data))
735 (line (+ (count-lines (point-min) (point)) (if (bolp) 1 0))))
736 (switch-to-buffer
737 (reftex-get-file-buffer-force reftex-last-index-file))
738 (reftex-erase-buffer buf)
739 (setq current-prefix-arg nil
740 reftex-last-follow-point 1)
741 (reftex-display-index index-tag nil 'redo data line)))
742 (defun reftex-index-switch-index-tag (&rest ignore)
743 "Switch to a different index of the same document."
744 (interactive)
745 (switch-to-buffer
746 (reftex-get-file-buffer-force reftex-last-index-file))
747 (setq current-prefix-arg nil)
748 (reftex-display-index nil nil 'redo))
749
750 (defun reftex-index-restrict-to-section (&optional force)
751 "Restrict index to entries defined in same document sect. as entry at point."
752 ;; Optional FORCE means, even if point is not on an index entry.
753 (interactive)
754 (let* ((data (get-text-property (point) :data))
755 (docstruct (symbol-value reftex-docstruct-symbol))
756 bor eor)
757 (if (and (not data) force)
758 (setq data (assq 'toc docstruct)))
759 (when data
760 (setq bor (reftex-last-assoc-before-elt 'toc data docstruct)
761 eor (car (memq (assq 'toc (cdr (memq bor docstruct)))
762 docstruct))
763 reftex-index-restriction-data (list bor eor)
764 reftex-index-restriction-indicator (nth 6 bor) )))
765 (reftex-index-revert))
766
767 (defun reftex-index-widen (&rest ignore)
768 "Show the unrestricted index (all entries)."
769 (interactive)
770 (setq reftex-index-restriction-indicator nil
771 reftex-index-restriction-data nil)
772 (reftex-index-revert)
773 (message "Index widened"))
774 (defun reftex-index-restriction-forward (&rest ignore)
775 "Restrict to previous section.
776 When index is currently unrestricted, restrict it to a section.
777 When index is restricted, select the next section as restriction criterion."
778 (interactive)
779 (let* ((docstruct (symbol-value reftex-docstruct-symbol))
780 (bor (nth 1 reftex-index-restriction-data)))
781 (if (or (not bor)
782 (not (eq (car bor) 'toc)))
783 (reftex-index-restrict-to-section t)
784 (setq reftex-index-restriction-indicator (nth 6 bor)
785 reftex-index-restriction-data
786 (list bor
787 (car (memq (assq 'toc (cdr (memq bor docstruct)))
788 docstruct))))
789 (reftex-index-revert))))
790 (defun reftex-index-restriction-backward (&rest ignore)
791 "Restrict to next section.
792 When index is currently unrestricted, restrict it to a section.
793 When index is restricted, select the previous section as restriction criterion."
794 (interactive)
795 (let* ((docstruct (symbol-value reftex-docstruct-symbol))
796 (eor (car reftex-index-restriction-data))
797 (bor (reftex-last-assoc-before-elt 'toc eor docstruct t)))
798 (if (or (not bor)
799 (not (eq (car bor) 'toc)))
800 (reftex-index-restrict-to-section t)
801 (setq reftex-index-restriction-indicator (nth 6 bor)
802 reftex-index-restriction-data
803 (list bor eor))
804 (reftex-index-revert))))
805
806 (defun reftex-index-visit-location (&optional final no-revisit)
807 ;; Visit the tex file corresponding to the index entry on the current line.
808 ;; If FINAL is t, stay there
809 ;; If FINAL is 'hide, hide the *Index* window.
810 ;; Otherwise, move cursor back into *Index* window.
811 ;; NO-REVISIT means don't visit files, just use live biffers.
812
813 (let* ((data (get-text-property (point) :data))
814 (index-window (selected-window))
815 show-window show-buffer match)
816
817 (unless data (error "Don't know which index entry to visit"))
818
819 (if (eq (car data) 'index)
820 (setq match (reftex-index-show-entry data no-revisit)))
821
822 (setq show-window (selected-window)
823 show-buffer (current-buffer))
824
825 (unless match
826 (select-window index-window)
827 (error "Cannot find location"))
828
829 (select-window index-window)
830
831 ;; Use the `final' parameter to decide what to do next
832 (cond
833 ((eq final t)
834 (reftex-unhighlight 0)
835 (select-window show-window))
836 ((eq final 'hide)
837 (reftex-unhighlight 0)
838 (or (one-window-p) (delete-window))
839 (switch-to-buffer show-buffer))
840 (t nil))))
841
842 (defun reftex-index-analyze-entry (data)
843 ;; This splits the index context so that key, attribute and visual
844 ;; values are accessible individually.
845 (interactive)
846 (let* ((arg (nth 5 data))
847 (context (nth 2 data))
848 (sc reftex-index-special-chars)
849 (boa (if (string-match (regexp-quote (concat "{" arg "}")) context)
850 (1+ (match-beginning 0))
851 (error "Something is wrong here")))
852 (eoa (1- (match-end 0)))
853 (boactual (if (string-match (concat "[^" (nth 3 sc) "]" (nth 2 sc))
854 context boa)
855 (1+ (match-beginning 0))
856 eoa))
857 (boattr (if (string-match (concat "[^" (nth 3 sc) "]" (nth 1 sc))
858 context boa)
859 (1+ (match-beginning 0))
860 boactual))
861 (pre (substring context 0 boa))
862 (key (substring context boa boattr))
863 (attr (substring context boattr boactual))
864 (actual (substring context boactual eoa))
865 (post (substring context eoa)))
866 (list pre key attr actual post)))
867
868 (defun reftex-index-edit ()
869 "Edit the index entry at point."
870 (interactive)
871 (let* ((data (get-text-property (point) :data))
872 old new)
873 (unless data (error "Don't know which index entry to edit"))
874 (reftex-index-view-entry)
875 (setq old (nth 2 data) new (read-string "Edit: " old))
876 (reftex-index-change-entry new)))
877
878 (defun reftex-index-toggle-range-beginning ()
879 "Toggle the page range start attribute `|('."
880 (interactive)
881 (let* ((data (get-text-property (point) :data))
882 (bor (concat (nth 1 reftex-index-special-chars) "("))
883 new analyze attr)
884 (unless data (error "Don't know which index entry to edit"))
885 (setq analyze (reftex-index-analyze-entry data)
886 attr (nth 2 analyze))
887 (setf (nth 2 analyze) (if (string= attr bor) "" bor))
888 (setq new (apply 'concat analyze))
889 (reftex-index-change-entry
890 new (if (string= (nth 2 analyze) bor)
891 "Entry is now START-OF-PAGE-RANGE"
892 "START-OF-PAGE-RANGE canceled"))))
893
894 (defun reftex-index-toggle-range-end ()
895 "Toggle the page-range-end attribute `|)'."
896 (interactive)
897 (let* ((data (get-text-property (point) :data))
898 (eor (concat (nth 1 reftex-index-special-chars) ")"))
899 new analyze attr)
900 (unless data (error "Don't know which index entry to edit"))
901 (setq analyze (reftex-index-analyze-entry data)
902 attr (nth 2 analyze))
903 (setf (nth 2 analyze) (if (string= attr eor) "" eor))
904 (setq new (apply 'concat analyze))
905 (reftex-index-change-entry
906 new (if (string= (nth 2 analyze) eor)
907 "Entry is now END-OF-PAGE-RANGE"
908 "END-OF-PAGE-RANGE canceled"))))
909
910 (defun reftex-index-edit-key ()
911 "Edit the KEY part of the index entry."
912 (interactive)
913 (reftex-index-edit-part nil 1 "" "Key: " t))
914
915 (defun reftex-index-edit-attribute (&optional arg)
916 "EDIT the ATTRIBUTE part of the entry. With arg: remove entire ATTRIBUTE."
917 (interactive "P")
918 (reftex-index-edit-part arg 2 (nth 1 reftex-index-special-chars)
919 "Attribute: "))
920
921 (defun reftex-index-edit-visual (&optional arg)
922 "EDIT the VISUAL part of the entry. With arg: remove entire VISUAL string."
923 (interactive "P")
924 (reftex-index-edit-part arg 3 (nth 2 reftex-index-special-chars) "Visual: "))
925
926 (defun reftex-index-edit-part (arg n initial prompt &optional dont-allow-empty)
927 ;; This function does the work for all partial editing commands
928 (let* ((data (get-text-property (point) :data))
929 new analyze opart npart)
930 (unless data (error "Don't know which index entry to edit"))
931 ;; Analyze the whole context string
932 (setq analyze (reftex-index-analyze-entry data)
933 opart (nth n analyze))
934 (and (> (length opart) 0) (setq opart (substring opart 1)))
935 ;; Have the user editing the part
936 (setq npart (if arg "" (read-string (concat prompt initial) opart)))
937 ;; Tests:
938 (cond ((string= npart opart)
939 (error "Not changed"))
940 ((string= npart "")
941 (if dont-allow-empty
942 (error "Invalid value")
943 (setf (nth n analyze) npart)))
944 (t (setf (nth n analyze) (concat initial npart))))
945 (setq new (apply 'concat analyze))
946 ;; Change the entry and insert the changed version into the index.
947 (reftex-index-change-entry
948 new (if (string= npart "")
949 (format "Deleted: %s" opart)
950 (format "New value is: %s" npart)))))
951
952 (defun reftex-index-level-down ()
953 "Make index entry a subitem of another entry."
954 (interactive)
955 (let* ((data (get-text-property (point) :data))
956 (docstruct (symbol-value reftex-docstruct-symbol))
957 old new prefix key)
958 (unless data (error "Don't know which index entry to change"))
959 (setq old (nth 2 data)
960 key (nth 6 data)
961 prefix (completing-read
962 "Prefix: "
963 (reftex-sublist-nth
964 docstruct 6
965 (lambda (x)
966 (and (eq (car x) 'index)
967 (string= (nth 1 x) reftex-index-tag))) t)))
968 (unless (string-match
969 (concat (regexp-quote (car reftex-index-special-chars)) "\\'")
970 prefix)
971 (setq prefix (concat prefix (car reftex-index-special-chars))))
972 (if (string-match (regexp-quote key) old)
973 (setq new (replace-match (concat prefix key) t t old))
974 (error "Cannot construct new index key"))
975 (reftex-index-change-entry new (format "Added prefix: %s" prefix))))
976
977 (defun reftex-index-level-up ()
978 "Remove the highest level of a hierarchical index entry."
979 (interactive)
980 (let* ((data (get-text-property (point) :data))
981 old new prefix)
982 (unless data (error "Don't know which entry to change"))
983 (setq old (nth 2 data))
984 (if (string-match (concat "{\\([^" (nth 0 reftex-index-special-chars) "]*"
985 "[^" (nth 3 reftex-index-special-chars) "]"
986 (regexp-quote (nth 0 reftex-index-special-chars))
987 "\\)")
988 old)
989 (setq prefix (substring old (match-beginning 1) (match-end 1))
990 new (concat (substring old 0 (match-beginning 1))
991 (substring old (match-end 1))))
992 (error "Entry is not a subitem"))
993 (reftex-index-change-entry new (format "Removed prefix: %s" prefix))))
994
995 (defun reftex-index-kill ()
996 "FIXME: Not yet implemented"
997 (interactive)
998 (error "This function is currently not implemented"))
999
1000 (defun reftex-index-undo ()
1001 "FIXME: Not yet implemented"
1002 (interactive)
1003 (error "This function is currently not implemented"))
1004
1005 (defun reftex-index-change-entry (new &optional message)
1006 ;; Change the full context string of the index entry at point to
1007 ;; NEW. This actually edits the buffer where the entry is defined.
1008
1009 (let* ((data (get-text-property (point) :data))
1010 old beg end info)
1011 (unless data (error "Cannot change entry"))
1012 (reftex-index-view-entry)
1013 (setq beg (match-beginning 0) end (match-end 0))
1014 (setq old (nth 2 data))
1015 (and (equal old new) (error "Entry unchanged"))
1016 (with-current-buffer (get-file-buffer (nth 3 data))
1017 (goto-char beg)
1018 (unless (looking-at (regexp-quote old))
1019 (error "This should not happen (reftex-index-change-entry)"))
1020 (delete-region beg end)
1021 (insert new)
1022 (goto-char (1- beg))
1023 (when (and (re-search-forward (reftex-everything-regexp) nil t)
1024 (match-end 10)
1025 (< (abs (- (match-beginning 10) beg)) (length new))
1026 (setq info (reftex-index-info-safe buffer-file-name)))
1027 (setcdr data (cdr info))))
1028 (let ((buffer-read-only nil))
1029 (save-excursion
1030 (reftex-insert-index (list data) reftex-index-tag t
1031 "EDITED")))
1032 (setq reftex-last-follow-point 1)
1033 (and message (message "%s" message))))
1034
1035 ;; Index map
1036 (define-key reftex-index-map (if (featurep 'xemacs) [(button2)] [(mouse-2)])
1037 'reftex-index-mouse-goto-line-and-hide)
1038 (define-key reftex-index-map [follow-link] 'mouse-face)
1039
1040 (substitute-key-definition
1041 'next-line 'reftex-index-next reftex-index-map global-map)
1042 (substitute-key-definition
1043 'previous-line 'reftex-index-previous reftex-index-map global-map)
1044
1045 (loop for x in
1046 '(("n" . reftex-index-next)
1047 ("p" . reftex-index-previous)
1048 ("?" . reftex-index-show-help)
1049 (" " . reftex-index-view-entry)
1050 ("\C-m" . reftex-index-goto-entry-and-hide)
1051 ("\C-i" . reftex-index-goto-entry)
1052 ("\C-k" . reftex-index-kill)
1053 ("r" . reftex-index-rescan)
1054 ("R" . reftex-index-Rescan)
1055 ("g" . revert-buffer)
1056 ("q" . reftex-index-quit)
1057 ("k" . reftex-index-quit-and-kill)
1058 ("f" . reftex-index-toggle-follow)
1059 ("s" . reftex-index-switch-index-tag)
1060 ("e" . reftex-index-edit)
1061 ("^" . reftex-index-level-up)
1062 ("_" . reftex-index-level-down)
1063 ("}" . reftex-index-restrict-to-section)
1064 ("{" . reftex-index-widen)
1065 (">" . reftex-index-restriction-forward)
1066 ("<" . reftex-index-restriction-backward)
1067 ("(" . reftex-index-toggle-range-beginning)
1068 (")" . reftex-index-toggle-range-end)
1069 ("|" . reftex-index-edit-attribute)
1070 ("@" . reftex-index-edit-visual)
1071 ("*" . reftex-index-edit-key)
1072 ("\C-c=". reftex-index-goto-toc)
1073 ("c" . reftex-index-toggle-context))
1074 do (define-key reftex-index-map (car x) (cdr x)))
1075
1076 (loop for key across "0123456789" do
1077 (define-key reftex-index-map (vector (list key)) 'digit-argument))
1078 (define-key reftex-index-map "-" 'negative-argument)
1079
1080 ;; The capital letters and the exclamation mark
1081 (loop for key across (concat "!" reftex-index-section-letters) do
1082 (define-key reftex-index-map (vector (list key))
1083 (list 'lambda '() '(interactive)
1084 (list 'reftex-index-goto-letter key))))
1085
1086 (defun reftex-index-goto-letter (char)
1087 "Go to the CHAR section in the index."
1088 (let ((pos (point))
1089 (case-fold-search nil))
1090 (goto-char (point-min))
1091 (forward-line 2)
1092 (if (re-search-forward (concat "^" (char-to-string char)) nil t)
1093 (progn
1094 (beginning-of-line)
1095 (recenter 0)
1096 (reftex-index-next))
1097 (goto-char pos)
1098 (if (eq char ?!)
1099 (error "This <%s> index does not contain entries sorted before the letters"
1100 reftex-index-tag)
1101 (error "This <%s> index does not contain entries starting with `%c'"
1102 reftex-index-tag char)))))
1103
1104 (easy-menu-define
1105 reftex-index-menu reftex-index-map
1106 "Menu for Index buffer"
1107 `("Index"
1108 ["Goto section A-Z"
1109 (message "To go to a section, just press any of: !%s"
1110 reftex-index-section-letters) t]
1111 ["Show Entry" reftex-index-view-entry t]
1112 ["Go To Entry" reftex-index-goto-entry t]
1113 ["Exit & Go To Entry" reftex-index-goto-entry-and-hide t]
1114 ["Table of Contents" reftex-index-goto-toc t]
1115 ["Quit" reftex-index-quit t]
1116 "--"
1117 ("Update"
1118 ["Rebuilt *Index* Buffer" revert-buffer t]
1119 "--"
1120 ["Rescan One File" reftex-index-rescan reftex-enable-partial-scans]
1121 ["Rescan Entire Document" reftex-index-Rescan t])
1122 ("Restrict"
1123 ["Restrict to section" reftex-index-restrict-to-section t]
1124 ["Widen" reftex-index-widen reftex-index-restriction-indicator]
1125 ["Next Section" reftex-index-restriction-forward
1126 reftex-index-restriction-indicator]
1127 ["Previous Section" reftex-index-restriction-backward
1128 reftex-index-restriction-indicator])
1129 ("Edit"
1130 ["Edit Entry" reftex-index-edit t]
1131 ["Edit Key" reftex-index-edit-key t]
1132 ["Edit Attribute" reftex-index-edit-attribute t]
1133 ["Edit Visual" reftex-index-edit-visual t]
1134 "--"
1135 ["Add Parentkey" reftex-index-level-down t]
1136 ["Remove Parentkey " reftex-index-level-up t]
1137 "--"
1138 ["Make Start-of-Range" reftex-index-toggle-range-beginning t]
1139 ["Make End-of-Range" reftex-index-toggle-range-end t]
1140 "--"
1141 ["Kill Entry" reftex-index-kill nil]
1142 "--"
1143 ["Undo" reftex-index-undo nil])
1144 ("Options"
1145 ["Context" reftex-index-toggle-context :style toggle
1146 :selected reftex-index-include-context]
1147 "--"
1148 ["Follow Mode" reftex-index-toggle-follow :style toggle
1149 :selected reftex-index-follow-mode])
1150 "--"
1151 ["Help" reftex-index-show-help t]))
1152
1153
1154 ;;----------------------------------------------------------------------
1155 ;; The Index Phrases File
1156
1157 ;; Some constants and variables
1158 (defconst reftex-index-phrases-comment-regexp "^[ \t]*%.*"
1159 "Regular expression to match comment lines in phrases buffer")
1160 (defconst reftex-index-phrases-macrodef-regexp
1161 "^\\(>>>INDEX_MACRO_DEFINITION:\\)[ \t]+\\(\\S-\\)\\( *\t[ \t]*\\)\\([^\t]*[^ \t]\\)\\( *\t[ \t]*\\)\\(\\S-+\\)"
1162 "Regular expression to match macro definition lines the phrases buffer.")
1163 ;(defconst reftex-index-phrases-macrodef-regexp
1164 ; "^\\(>>>INDEX_MACRO_DEFINITION:\\)[ \t]+\\(\\S-\\)\\([ \t]*\\)\\([^\t]*[^ \t]\\)\\([ \t]*\\)\\(nil\\|t\\)[ \t]*$"
1165 ; "Regular expression to match macro definition lines the phrases buffer.
1166 ;This version would allow just spaces as separators.")
1167 (defconst reftex-index-phrases-phrase-regexp1
1168 "^\\(\\S-?\\)\\(\t\\)\\([^\t\n]*\\S-\\)\\([ \t]*\\)$"
1169 "Regular expression matching phrases which have no separate index key.")
1170 (defconst reftex-index-phrases-phrase-regexp2
1171 "^\\(\\S-?\\)\\(\t\\)\\([^\t]*\\S-\\)\\(\t[ \t]*\\)\\([^\n\t]*\\S-\\)[ \t]*$"
1172 "Regular expression matching phrases which have a separate index key.")
1173 (defconst reftex-index-phrases-phrase-regexp12
1174 "^\\(\\S-?\\)\\(\t\\)\\([^\n\t]*\\S-\\)\\(\\(\t[ \t]*\\)\\([^\n\t]*\\S-\\)\\)?[ \t]*$"
1175 "Regular expression matching all types of phrase lines.")
1176 (defvar reftex-index-phrases-macro-data nil
1177 "Alist containing the information taken from the macro definition lines.
1178 This gets refreshed in every phrases command.")
1179 (defvar reftex-index-phrases-files nil
1180 "List of document files relevant for the phrases file.")
1181
1182 (defvar reftex-index-phrases-font-lock-keywords nil
1183 "Font lock keywords for reftex-index-phrases-mode.")
1184 (defvar reftex-index-phrases-font-lock-defaults nil
1185 "Font lock defaults for reftex-index-phrases-mode.")
1186 (defvar reftex-index-phrases-map (make-sparse-keymap)
1187 "Keymap used for *toc* buffer.")
1188
1189
1190 (defun reftex-index-phrase-selection-or-word (arg)
1191 "Add current selection or word at point to the phrases buffer.
1192 When you are in transient-mark-mode and the region is active, the
1193 selection will be used - otherwise the word at point.
1194 You get a chance to edit the entry in the phrases buffer - finish with
1195 `C-c C-c'."
1196 (interactive "P")
1197 (set-marker reftex-index-return-marker (point))
1198 (reftex-index-selection-or-word arg 'phrase)
1199 (if (eq major-mode 'reftex-index-phrases-mode)
1200 (message "%s"
1201 (substitute-command-keys
1202 "Return to LaTeX with \\[reftex-index-phrases-save-and-return]"))))
1203
1204 (defun reftex-index-visit-phrases-buffer ()
1205 "Switch to the phrases buffer, initialize if empty."
1206 (interactive)
1207 (reftex-access-scan-info)
1208 (let* ((master (reftex-TeX-master-file))
1209 (name (concat (file-name-sans-extension master)
1210 reftex-index-phrase-file-extension)))
1211 (find-file name)
1212 (unless (eq major-mode 'reftex-index-phrases-mode)
1213 (reftex-index-phrases-mode))
1214 (if (= (buffer-size) 0)
1215 (reftex-index-initialize-phrases-buffer master))))
1216
1217 (defun reftex-index-initialize-phrases-buffer (&optional master)
1218 "Initialize the phrases buffer by creating the header.
1219 If the buffer is non-empty, delete the old header first."
1220 (interactive)
1221 (let* ((case-fold-search t)
1222 (default-key (car reftex-index-default-macro))
1223 (default-macro (nth 1 (assoc default-key
1224 reftex-key-to-index-macro-alist)))
1225 (macro-alist
1226 (sort (copy-sequence reftex-index-macro-alist)
1227 (lambda (a b) (equal (car a) default-macro))))
1228 macro entry key repeat)
1229
1230 (if master (set (make-local-variable 'TeX-master)
1231 (file-name-nondirectory master)))
1232
1233 (when (> (buffer-size) 0)
1234 (goto-char 1)
1235 (set-mark (point))
1236 (while (re-search-forward reftex-index-phrases-macrodef-regexp nil t)
1237 (end-of-line))
1238 (beginning-of-line 2)
1239 (if (looking-at reftex-index-phrases-comment-regexp)
1240 (beginning-of-line 2))
1241 (while (looking-at "^[ \t]*$")
1242 (beginning-of-line 2))
1243 (if (featurep 'xemacs)
1244 (zmacs-activate-region)
1245 (setq mark-active t))
1246 (if (yes-or-no-p "Delete and rebuild header? ")
1247 (delete-region (point-min) (point))))
1248
1249 ;; Insert the mode line
1250 (insert
1251 (format "%% -*- mode: reftex-index-phrases; TeX-master: \"%s\" -*-\n"
1252 (file-name-nondirectory (reftex-index-phrase-tex-master))))
1253 ;; Insert the macro definitions
1254 (insert "% Key Macro Format Repeat\n")
1255 (insert "%---------------------------------------------------------------------\n")
1256 (while (setq entry (pop macro-alist))
1257 (setq macro (car entry)
1258 repeat (nth 7 entry)
1259 key (car (delq nil (mapcar (lambda (x) (if (equal (nth 1 x) macro)
1260 (car x)
1261 nil))
1262 reftex-key-to-index-macro-alist))))
1263 (insert (format ">>>INDEX_MACRO_DEFINITION:\t%s\t%-20s\t%s\n"
1264 (char-to-string key) (concat macro "{%s}")
1265 (if repeat "t" "nil"))))
1266 (insert "%---------------------------------------------------------------------\n\n\n")))
1267
1268 (defvar TeX-master)
1269 (defun reftex-index-phrase-tex-master (&optional dir)
1270 "Return the name of the master file associated with a phrase buffer."
1271 (if (and (boundp 'TeX-master)
1272 (local-variable-p 'TeX-master (current-buffer))
1273 (stringp TeX-master))
1274 ;; We have a local variable which tells us which file to use
1275 (expand-file-name TeX-master dir)
1276 ;; have to guess
1277 (concat (file-name-sans-extension (buffer-file-name)) ".tex")))
1278
1279 (defun reftex-index-phrases-save-and-return ()
1280 "Return to where the `reftex-index-phrase-selection-or-word' was called."
1281 (interactive)
1282 (save-buffer)
1283 (switch-to-buffer (marker-buffer reftex-index-return-marker))
1284 (goto-char (or (marker-position reftex-index-return-marker) (point))))
1285
1286
1287 (defvar reftex-index-phrases-menu)
1288 (defvar reftex-index-phrases-marker)
1289 (defvar reftex-index-phrases-restrict-file nil)
1290 ;;;###autoload
1291 (defun reftex-index-phrases-mode ()
1292 "Major mode for managing the Index phrases of a LaTeX document.
1293 This buffer was created with RefTeX.
1294
1295 To insert new phrases, use
1296 - `C-c \\' in the LaTeX document to copy selection or word
1297 - `\\[reftex-index-new-phrase]' in the phrases buffer.
1298
1299 To index phrases use one of:
1300
1301 \\[reftex-index-this-phrase] index current phrase
1302 \\[reftex-index-next-phrase] index next phrase (or N with prefix arg)
1303 \\[reftex-index-all-phrases] index all phrases
1304 \\[reftex-index-remaining-phrases] index current and following phrases
1305 \\[reftex-index-region-phrases] index the phrases in the region
1306
1307 You can sort the phrases in this buffer with \\[reftex-index-sort-phrases].
1308 To display information about the phrase at point, use \\[reftex-index-phrases-info].
1309
1310 For more information see the RefTeX User Manual.
1311
1312 Here are all local bindings.
1313
1314 \\{reftex-index-phrases-map}"
1315 (interactive)
1316 (kill-all-local-variables)
1317 (setq major-mode 'reftex-index-phrases-mode
1318 mode-name "Phrases")
1319 (use-local-map reftex-index-phrases-map)
1320 (set (make-local-variable 'font-lock-defaults)
1321 reftex-index-phrases-font-lock-defaults)
1322 (easy-menu-add reftex-index-phrases-menu reftex-index-phrases-map)
1323 (set (make-local-variable 'reftex-index-phrases-marker) (make-marker))
1324 (run-hooks 'reftex-index-phrases-mode-hook))
1325 (add-hook 'reftex-index-phrases-mode-hook 'turn-on-font-lock)
1326
1327 ;; Font Locking stuff
1328 (let ((ss (if (featurep 'xemacs) 'secondary-selection ''secondary-selection)))
1329 (setq reftex-index-phrases-font-lock-keywords
1330 (list
1331 (cons reftex-index-phrases-comment-regexp 'font-lock-comment-face)
1332 (list reftex-index-phrases-macrodef-regexp
1333 '(1 font-lock-type-face)
1334 '(2 font-lock-keyword-face)
1335 (list 3 ss)
1336 '(4 font-lock-function-name-face)
1337 (list 5 ss)
1338 '(6 font-lock-string-face))
1339 (list reftex-index-phrases-phrase-regexp1
1340 '(1 font-lock-keyword-face)
1341 (list 2 ss)
1342 '(3 font-lock-string-face)
1343 (list 4 ss))
1344 (list reftex-index-phrases-phrase-regexp2
1345 '(1 font-lock-keyword-face)
1346 (list 2 ss)
1347 '(3 font-lock-string-face)
1348 (list 4 ss)
1349 '(5 font-lock-function-name-face))
1350 (cons "^\t$" ss)))
1351 (setq reftex-index-phrases-font-lock-defaults
1352 '((reftex-index-phrases-font-lock-keywords)
1353 nil t nil beginning-of-line))
1354 (put 'reftex-index-phrases-mode 'font-lock-defaults
1355 reftex-index-phrases-font-lock-defaults) ; XEmacs
1356 )
1357
1358 (defun reftex-index-next-phrase (&optional arg)
1359 "Index the next ARG phrases in the phrases buffer."
1360 (interactive "p")
1361 (reftex-index-phrases-parse-header t)
1362 (while (> arg 0)
1363 (decf arg)
1364 (end-of-line)
1365 (if (re-search-forward reftex-index-phrases-phrase-regexp12 nil t)
1366 (progn
1367 (goto-char (match-beginning 0))
1368 (reftex-index-this-phrase 'slave))
1369 (error "No more phrase lines after point"))))
1370
1371 (defun reftex-index-this-phrase (&optional slave)
1372 "Index the phrase in the current line.
1373 Does a global search and replace in the entire document. At each
1374 match, the user will be asked to confirm the replacement."
1375 (interactive)
1376 (if (not slave) (reftex-index-phrases-parse-header t))
1377 (save-excursion
1378 (beginning-of-line)
1379 (cond ((looking-at reftex-index-phrases-comment-regexp)
1380 (if (not slave) (error "Comment line")))
1381 ((looking-at "^[ \t]*$")
1382 (if (not slave) (error "Empty line")))
1383 ((looking-at reftex-index-phrases-macrodef-regexp)
1384 (if (not slave) (error "Macro definition line")))
1385 ((looking-at reftex-index-phrases-phrase-regexp12)
1386 ;; This is a phrase
1387 (let* ((char (if (not (equal (match-string 1) ""))
1388 (string-to-char (match-string 1))))
1389 (phrase (match-string 3))
1390 (index-key (match-string 6))
1391 (macro-data (cdr (if (null char)
1392 (car reftex-index-phrases-macro-data)
1393 (assoc char reftex-index-phrases-macro-data))))
1394 (macro-fmt (car macro-data))
1395 (repeat (nth 1 macro-data))
1396 (files
1397 (cond ((and (stringp reftex-index-phrases-restrict-file)
1398 (file-regular-p reftex-index-phrases-restrict-file))
1399 (list reftex-index-phrases-restrict-file))
1400 ((stringp reftex-index-phrases-restrict-file)
1401 (error "Invalid restriction file %s"
1402 reftex-index-phrases-restrict-file))
1403 (t reftex-index-phrases-files)))
1404 (as-words reftex-index-phrases-search-whole-words))
1405 (unless macro-data
1406 (error "No macro associated with key %c" char))
1407 (unwind-protect
1408 (let ((overlay-arrow-string "=>")
1409 (overlay-arrow-position
1410 reftex-index-phrases-marker)
1411 (replace-count 0))
1412 ;; Show the overlay arrow
1413 (move-marker reftex-index-phrases-marker
1414 (match-beginning 0) (current-buffer))
1415 ;; Start the query-replace
1416 (reftex-query-index-phrase-globally
1417 files phrase macro-fmt
1418 index-key repeat as-words)
1419 (message "%s replaced"
1420 (reftex-number replace-count "occurrence"))))))
1421 (t (error "Cannot parse this line")))))
1422
1423 (defun reftex-index-all-phrases ()
1424 "Index all phrases in the phrases buffer.
1425 Calls `reftex-index-this-phrase' on each line in the buffer."
1426 (interactive)
1427 (reftex-index-region-phrases (point-min) (point-max)))
1428
1429 (defun reftex-index-remaining-phrases ()
1430 "Index all phrases in the phrases buffer.
1431 Calls `reftex-index-this-phrase' on each line ay and below point in
1432 the buffer."
1433 (interactive)
1434 (beginning-of-line)
1435 (reftex-index-region-phrases (point) (point-max)))
1436
1437 (defun reftex-index-region-phrases (beg end)
1438 "Index all phrases in the phrases buffer.
1439 Calls `reftex-index-this-phrase' on each line in the region."
1440 (interactive "r")
1441 (reftex-index-phrases-parse-header t)
1442 (goto-char beg)
1443 (while (not (or (eobp)
1444 (>= (point) end)))
1445 (save-excursion (reftex-index-this-phrase 'slave))
1446 (beginning-of-line 2)))
1447
1448 (defun reftex-index-phrases-parse-header (&optional get-files)
1449 "Parse the header of a phrases file to extract the macro definitions.
1450 The definitions get stored in `reftex-index-phrases-macro-data'.
1451 Also switches to the LaTeX document to find out which files belong to
1452 the document and stores the list in `reftex-index-phrases-files'."
1453 (let* ((master (reftex-index-phrase-tex-master))
1454 buf)
1455 (if get-files
1456 ;; Get the file list
1457 (save-excursion
1458 (setq buf (reftex-get-file-buffer-force master))
1459 (unless buf (error "Master file %s not found" master))
1460 (set-buffer buf)
1461 (reftex-access-scan-info)
1462 (setq reftex-index-phrases-files
1463 (reftex-all-document-files))))
1464 ;; Parse the files header for macro definitions
1465 (setq reftex-index-phrases-macro-data nil)
1466 (save-excursion
1467 (goto-char (point-min))
1468 (while (re-search-forward reftex-index-phrases-macrodef-regexp nil t)
1469 (push (list
1470 (string-to-char (match-string 2))
1471 (match-string 4)
1472 (equal (match-string 6) "t"))
1473 reftex-index-phrases-macro-data))
1474 ;; Reverse the list, so that the first macro is first
1475 (if (null reftex-index-phrases-macro-data)
1476 (error "No valid MACRO DEFINITION line in %s file (make sure to use TAB separators)" reftex-index-phrase-file-extension))
1477 (setq reftex-index-phrases-macro-data
1478 (nreverse reftex-index-phrases-macro-data))
1479 (goto-char (point-min)))))
1480
1481 (defun reftex-index-phrases-apply-to-region (beg end)
1482 "Index all index phrases in the current region.
1483 This works exactly like global indexing from the index phrases buffer,
1484 but operation is restricted to the current region. This is useful if
1485 you need to add/change text in an already indexed document and want to
1486 index the new part without having to go over the unchanged parts again."
1487 (interactive "r")
1488 (let ((win-conf (current-window-configuration))
1489 (reftex-index-phrases-restrict-file (buffer-file-name)))
1490 (save-excursion
1491 (save-restriction
1492 (narrow-to-region beg end)
1493 (unwind-protect
1494 (progn
1495 ;; Hide the region highlighting
1496 (if (featurep 'xemacs)
1497 (zmacs-deactivate-region)
1498 (deactivate-mark))
1499 (delete-other-windows)
1500 (reftex-index-visit-phrases-buffer)
1501 (reftex-index-all-phrases))
1502 (set-window-configuration win-conf))))))
1503
1504 (defun reftex-index-new-phrase (&optional text)
1505 "Open a new line in the phrases buffer, insert TEXT."
1506 (interactive)
1507 (if (and text (stringp text))
1508 (progn
1509 ;; Check if the phrase is already in the buffer
1510 (setq text (reftex-index-simplify-phrase text))
1511 (goto-char (point-min))
1512 (if (re-search-forward
1513 (concat "^\\(\\S-*\\)\t\\(" (regexp-quote text)
1514 "\\) *[\t\n]") nil t)
1515 (progn
1516 (goto-char (match-end 2))
1517 (error "Phrase is already in phrases buffer")))))
1518 ;; Add the new phrase line after the last in the buffer
1519 (goto-char (point-max))
1520 (if (re-search-backward reftex-index-phrases-phrase-regexp12 nil t)
1521 (end-of-line))
1522 (if (not (bolp))
1523 (insert "\n"))
1524 (insert "\t")
1525 (if (and text (stringp text))
1526 (insert text)))
1527
1528 (defun reftex-index-find-next-conflict-phrase (&optional arg)
1529 "Find the next a phrase which is has conflicts in the phrase buffer.
1530 The command helps to find possible conflicts in the phrase indexing process.
1531 It searches downward from point for a phrase which is repeated elsewhere
1532 in the buffer, or which is a subphrase of another phrase. If such a
1533 phrase is found, the phrase info is displayed.
1534 To check the whole buffer, start at the beginning and continue by calling
1535 this function repeatedly."
1536 (interactive "P")
1537 (if (catch 'exit
1538 (while (re-search-forward reftex-index-phrases-phrase-regexp12 nil t)
1539 (goto-char (match-beginning 3))
1540 (let* ((phrase (match-string 3))
1541 (case-fold-search reftex-index-phrases-case-fold-search)
1542 (re (reftex-index-phrases-find-dup-re phrase t)))
1543 (if (save-excursion
1544 (goto-char (point-min))
1545 (and (re-search-forward re nil t)
1546 (re-search-forward re nil t)))
1547 (throw 'exit t)))))
1548 (progn
1549 (reftex-index-phrases-info)
1550 (message "Phrase with match conflict discovered"))
1551 (goto-char (point-max))
1552 (error "No further problematic phrases found")))
1553
1554 (defun reftex-index-phrases-info ()
1555 "Display information about the phrase at point."
1556 (interactive)
1557 (save-excursion
1558 (beginning-of-line)
1559 (unless (looking-at reftex-index-phrases-phrase-regexp12)
1560 (error "Not a phrase line"))
1561 (save-match-data (reftex-index-phrases-parse-header t))
1562 (let* ((char (if (not (equal (match-string 1) ""))
1563 (string-to-char (match-string 1))))
1564 (phrase (match-string 3))
1565 (index-key (match-string 6))
1566 (index-keys (split-string
1567 (or index-key phrase)
1568 reftex-index-phrases-logical-or-regexp))
1569 (macro-data (cdr (if (null char)
1570 (car reftex-index-phrases-macro-data)
1571 (assoc char reftex-index-phrases-macro-data))))
1572 (macro-fmt (car macro-data))
1573 (repeat (nth 1 macro-data))
1574 (as-words reftex-index-phrases-search-whole-words)
1575 (example (reftex-index-make-replace-string
1576 macro-fmt (downcase phrase) (car index-keys) repeat))
1577 (re (reftex-index-make-phrase-regexp phrase as-words t))
1578 (re1 (reftex-index-phrases-find-dup-re phrase))
1579 (re2 (reftex-index-phrases-find-dup-re phrase 'sub))
1580 superphrases
1581 (nmatches 0)
1582 (ntimes1 0)
1583 (ntimes2 0)
1584 (case-fold-search reftex-index-phrases-case-fold-search)
1585 file files buf)
1586 (setq files reftex-index-phrases-files)
1587 (save-excursion
1588 (save-restriction
1589 (widen)
1590 (goto-char (point-min))
1591 (while (re-search-forward re1 nil t)
1592 (incf ntimes1))
1593 (goto-char (point-min))
1594 (while (re-search-forward re2 nil t)
1595 (push (cons (count-lines 1 (point)) (match-string 1)) superphrases)
1596 (incf ntimes2))))
1597 (save-current-buffer
1598 (while (setq file (pop files))
1599 (setq buf (reftex-get-file-buffer-force file))
1600 (when buf
1601 (set-buffer buf)
1602 (save-excursion
1603 (save-restriction
1604 (widen)
1605 (goto-char (point-min))
1606 (let ((case-fold-search reftex-index-phrases-case-fold-search))
1607 (while (re-search-forward re nil t)
1608 (or (reftex-in-comment)
1609 (incf nmatches)))))))))
1610 (with-output-to-temp-buffer "*Help*"
1611 (princ (format " Phrase: %s\n" phrase))
1612 (princ (format " Macro key: %s\n" char))
1613 (princ (format " Macro format: %s\n" macro-fmt))
1614 (princ (format " Repeat: %s\n" repeat))
1615 (cond
1616 (index-key
1617 (let ((iks index-keys) (cnt 0) ik)
1618 (while (setq ik (pop iks))
1619 (princ (format "Index entry %d: %s\n" (incf cnt) ik)))))
1620 (repeat
1621 (princ (format " Index entry: %s\n" phrase)))
1622 (t
1623 (princ (format " Index key: <<Given by the match>>\n"))))
1624 (princ (format " Example: %s\n" example))
1625 (terpri)
1626 (princ (format "Total matches: %s in %s\n"
1627 (reftex-number nmatches "match" "es")
1628 (reftex-number (length reftex-index-phrases-files)
1629 "LaTeX file")))
1630 (princ (format " Uniqueness: Phrase occurs %s in phrase buffer\n"
1631 (reftex-number ntimes1 "time")))
1632 (if (> ntimes2 1)
1633 (progn
1634 (princ (format " Superphrases: Phrase matches the following %s in the phrase buffer:\n"
1635 (reftex-number ntimes2 "line")))
1636 (mapcar (lambda(x)
1637 (princ (format " Line %4d: %s\n" (car x) (cdr x))))
1638 (nreverse superphrases))))))))
1639
1640 (defun reftex-index-phrases-set-macro-key ()
1641 "Change the macro key for the current line.
1642 Prompts for a macro key and insert is at the beginning of the line.
1643 If you reply with SPACE, the macro keyn will be removed, so that the
1644 default macro will be used. If you reply with `RET', just prints
1645 information about the currently selected macro."
1646 (interactive)
1647 (reftex-index-phrases-parse-header)
1648 (save-excursion
1649 (beginning-of-line)
1650 (unless (or (looking-at reftex-index-phrases-phrase-regexp12)
1651 (looking-at "\t"))
1652 (error "This is not a phrase line"))
1653 (let* ((nc (reftex-index-select-phrases-macro 0))
1654 (macro-data (assoc nc reftex-index-phrases-macro-data))
1655 macro-fmt repeat)
1656 (cond (macro-data)
1657 ((equal nc ?\ )
1658 (setq nc ""
1659 macro-data (car reftex-index-phrases-macro-data)))
1660 ((equal nc ?\C-m)
1661 (setq nc (char-after (point)))
1662 (if (equal nc ?\t)
1663 (setq nc ""
1664 macro-data (car reftex-index-phrases-macro-data))
1665 (setq macro-data (assoc nc reftex-index-phrases-macro-data))))
1666 (t (error "No macro associated with %c" nc)))
1667
1668 (setq macro-fmt (nth 1 macro-data)
1669 repeat (nth 2 macro-data))
1670 (if macro-data
1671 (progn
1672 (if (looking-at "[^\t]") (delete-char 1))
1673 (insert nc)
1674 (message "Line will use %s %s repeat" macro-fmt
1675 (if repeat "with" "without")))
1676 (error "Abort")))))
1677
1678 (defun reftex-index-sort-phrases (&optional chars-first)
1679 "Sort the phrases lines in the buffer alphabetically.
1680 Normally, this looks only at the phrases. With a prefix arg CHARS-FIRST,
1681 it first compares the macro identifying chars and then the phrases."
1682 (interactive "P")
1683 ;; Remember the current line, so that we can return
1684 (let ((line (buffer-substring (progn (beginning-of-line) (point))
1685 (progn (end-of-line) (point))))
1686 beg end)
1687 (goto-char (point-min))
1688 ;; Find first and last phrase line in buffer
1689 (setq beg
1690 (and (re-search-forward reftex-index-phrases-phrase-regexp12 nil t)
1691 (match-beginning 0)))
1692 (goto-char (point-max))
1693 (setq end (re-search-backward reftex-index-phrases-phrase-regexp12 nil t))
1694 (if end (setq end (progn (goto-char end) (end-of-line) (point))))
1695 ;; Take the lines, sort them and re-insert.
1696 (if (and beg end)
1697 (progn
1698 (message "Sorting lines...")
1699 (let* ((lines (split-string (buffer-substring beg end) "\n"))
1700 (lines1 (sort lines 'reftex-compare-phrase-lines)))
1701 (message "Sorting lines...done")
1702 (let ((inhibit-quit t)) ;; make sure we do not loose lines
1703 (delete-region beg end)
1704 (insert (mapconcat 'identity lines1 "\n"))))
1705 (goto-char (point-max))
1706 (re-search-backward (concat "^" (regexp-quote line) "$") nil t))
1707 (error "Cannot find phrases lines to sort"))))
1708
1709 (defvar chars-first)
1710 (defun reftex-compare-phrase-lines (a b)
1711 "The comparison function used for sorting."
1712 (let (ca cb pa pb c-p p-p)
1713 (if (string-match reftex-index-phrases-phrase-regexp12 a)
1714 (progn
1715 ;; Extract macro char and phrase-or-key for a
1716 (setq ca (match-string 1 a)
1717 pa (downcase
1718 (or (and reftex-index-phrases-sort-prefers-entry
1719 (match-string 6 a))
1720 (match-string 3 a))))
1721 (if (string-match reftex-index-phrases-phrase-regexp12 b)
1722 (progn
1723 ;; Extract macro char and phrase-or-key for b
1724 (setq cb (match-string 1 b)
1725 pb (downcase
1726 (or (and reftex-index-phrases-sort-prefers-entry
1727 (match-string 6 b))
1728 (match-string 3 b))))
1729 (setq c-p (string< ca cb)
1730 p-p (string< pa pb))
1731 ;; Do the right comparison, based on the value of `chars-first'
1732 ;; `chars-first' is bound locally in the calling function
1733 (if chars-first
1734 (if (string= ca cb) p-p c-p)
1735 (if (string= pa pb) c-p p-p)))))
1736 ;; If line a does not match, the answer we return determines
1737 ;; if non-matching lines are collected at the beginning.
1738 ;; When we return t here, non-matching lines form
1739 ;; block separators for searches.
1740 (not reftex-index-phrases-sort-in-blocks))))
1741
1742 (defvar reftex-index-phrases-menu)
1743 (defun reftex-index-make-phrase-regexp (phrase &optional
1744 as-words allow-newline)
1745 "Return a regexp matching PHRASE, even if distributed over lines.
1746 With optional arg AS-WORDS, require word boundary at beginning and end.
1747 With optional arg ALLOW-NEWLINE, allow single newline between words."
1748 (let* ((words (split-string phrase))
1749 (space-re (if allow-newline
1750 "\\([ \t]*\\(\n[ \t]*\\)?\\|[ \t]\\)"
1751 "\\([ \t]+\\)")))
1752 (concat (if (and as-words (string-match "\\`\\w" (car words)))
1753 "\\(\\<\\|[`']\\)" "")
1754 (mapconcat (lambda (w) (regexp-quote
1755 (if reftex-index-phrases-case-fold-search
1756 (downcase w)
1757 w)))
1758 words space-re)
1759 (if (and as-words
1760 (string-match "\\w\\'" (nth (1- (length words)) words)))
1761 "\\(\\>\\|'\\)" ""))))
1762
1763 (defun reftex-index-simplify-phrase (phrase)
1764 "Make phrase single spaces and single line."
1765 (mapconcat 'identity (split-string phrase) " "))
1766
1767 (defun reftex-index-phrases-find-dup-re (phrase &optional sub)
1768 "Return a regexp which matches variations of PHRASE (with additional space).
1769 When SUB ins non-nil, the regexp will also match when PHRASE is a subphrase
1770 of another phrase. The regexp works lonly in the phrase buffer."
1771 (concat (if sub "^\\S-?\t\\([^\t\n]*" "^\\S-?\t")
1772 (mapconcat 'regexp-quote (split-string phrase) " +")
1773 (if sub "[^\t\n]*\\)\\([\t\n]\\|$\\)" " *\\([\t\n]\\|$\\)")))
1774
1775 (defun reftex-index-make-replace-string (macro-fmt match index-key
1776 &optional repeat mathp)
1777 "Return the string which can be used as replacement.
1778 Treats the logical `and' for index phrases."
1779 (let ((index-keys (split-string (or index-key match)
1780 reftex-index-phrases-logical-and-regexp)))
1781 (concat
1782 (mapconcat (lambda (x)
1783 (format macro-fmt
1784 (format (if mathp reftex-index-math-format "%s") x)))
1785 index-keys "")
1786 (if repeat (reftex-index-simplify-phrase match) ""))))
1787
1788 (defun reftex-query-index-phrase-globally (files &rest args)
1789 "Call `reftex-query-index-phrase' for all files in FILES."
1790 (let ((win-conf (current-window-configuration))
1791 (file))
1792 (unless files (error "No files"))
1793 (unwind-protect
1794 (progn
1795 (switch-to-buffer-other-window (reftex-get-file-buffer-force
1796 (car files)))
1797 (catch 'no-more-files
1798 (while (setq file (pop files))
1799 (switch-to-buffer (reftex-get-file-buffer-force file))
1800 (save-excursion
1801 (save-restriction
1802 (unless (stringp reftex-index-phrases-restrict-file)
1803 (widen))
1804 (goto-char (point-min))
1805 (apply 'reftex-query-index-phrase args))))))
1806 (reftex-unhighlight 0)
1807 (set-window-configuration win-conf))))
1808
1809 (defconst reftex-index-phrases-help
1810 " Keys for query-index search
1811 ===========================
1812 y Replace this match
1813 n Skip this match
1814 ! Replace this and all further matches in this file
1815 q / Q Skip match, start next file / start next phrase
1816 o Use a different indexing macro for this match
1817 1 - 9 Select one of the multiple phrases
1818 e Edit the replacement text
1819 C-r Recursive edit.
1820 s / S Save this buffer / Save all document buffers
1821 C-g Abort"
1822 "The help string for indexing phrases.")
1823
1824 (defvar replace-count)
1825 (defun reftex-query-index-phrase (phrase macro-fmt &optional
1826 index-key repeat as-words)
1827 "Search through buffer for PHRASE, and offer to replace it with an indexed
1828 version. The index version is derived by applying `format' with MACRO-FMT
1829 to INDEX-KEY or PHRASE. When REPEAT is non-nil, the PHRASE is inserted
1830 again after the macro.
1831 AS-WORDS means, the search for PHRASE should require word boundaries at
1832 both ends."
1833 (let* ((re (reftex-index-make-phrase-regexp phrase as-words 'allow-newline))
1834 (case-fold-search reftex-index-phrases-case-fold-search)
1835 (index-keys (split-string
1836 (or index-key phrase)
1837 reftex-index-phrases-logical-or-regexp))
1838 (nkeys (length index-keys))
1839 (ckey (nth 0 index-keys))
1840 (all-yes nil)
1841 match rpl char (beg (make-marker)) (end (make-marker)) mathp)
1842 (move-marker beg 1)
1843 (move-marker end 1)
1844 (unwind-protect
1845 (while (re-search-forward re nil t)
1846 (catch 'next-match
1847 (if (reftex-in-comment)
1848 (throw 'next-match nil))
1849 (if (and (fboundp reftex-index-verify-function)
1850 (not (funcall reftex-index-verify-function)))
1851 (throw 'next-match nil))
1852 (setq match (match-string 0))
1853 (setq mathp
1854 (save-match-data
1855 (condition-case nil (texmathp) (error nil))))
1856 (setq beg (move-marker beg (match-beginning 0))
1857 end (move-marker end (match-end 0)))
1858 (if (and reftex-index-phrases-skip-indexed-matches
1859 (save-match-data
1860 (reftex-index-phrase-match-is-indexed beg
1861 end)))
1862 (throw 'next-match nil))
1863 (reftex-highlight 0 (match-beginning 0) (match-end 0))
1864 (setq rpl
1865 (save-match-data
1866 (reftex-index-make-replace-string
1867 macro-fmt (match-string 0) ckey repeat mathp)))
1868 (while
1869 (not
1870 (catch 'loop
1871 (message "REPLACE: %s? (yn!qoe%s?)"
1872 rpl
1873 (if (> nkeys 1)
1874 (concat "1-" (int-to-string nkeys))
1875 ""))
1876 (setq char (if all-yes ?y (read-char-exclusive)))
1877 (cond ((member char '(?y ?Y ?\ ))
1878 ;; Yes!
1879 (replace-match rpl t t)
1880 (incf replace-count)
1881 ;; See if we should insert newlines to shorten lines
1882 (and reftex-index-phrases-wrap-long-lines
1883 (reftex-index-phrases-fixup-line beg end))
1884 (throw 'loop t))
1885 ((member char '(?n ?N ?\C-h ?\C-?));; FIXME: DEL
1886 ;; No
1887 (throw 'loop t))
1888 ((equal char ?!)
1889 ;; Yes for all in this buffer
1890 (setq all-yes t))
1891 ((equal char ?q)
1892 ;; Stop this one in this file
1893 (goto-char (point-max))
1894 (throw 'loop t))
1895 ((equal char ?Q)
1896 ;; Stop this one
1897 (throw 'no-more-files t))
1898 ((equal char ?s)
1899 (save-buffer))
1900 ((equal char ?S)
1901 (reftex-save-all-document-buffers))
1902 ((equal char ?\C-g)
1903 (keyboard-quit))
1904 ((member char '(?o ?O))
1905 ;; Select a differnt macro
1906 (let* ((nc (reftex-index-select-phrases-macro 2))
1907 (macro-data
1908 (cdr (assoc nc reftex-index-phrases-macro-data)))
1909 (macro-fmt (car macro-data))
1910 (repeat (nth 1 macro-data)))
1911 (if macro-data
1912 (setq rpl (save-match-data
1913 (reftex-index-make-replace-string
1914 macro-fmt match
1915 ckey repeat mathp)))
1916 (ding))))
1917 ((equal char ?\?)
1918 ;; Help
1919 (with-output-to-temp-buffer "*Help*"
1920 (princ reftex-index-phrases-help)))
1921 ((equal char ?\C-r)
1922 ;; Recursive edit
1923 (save-match-data
1924 (save-excursion
1925 (message "%s"
1926 (substitute-command-keys
1927 "Recursive edit. Resume with \\[exit-recursive-edit]"))
1928 (recursive-edit))))
1929 ((equal char ?e)
1930 (setq rpl (read-string "Edit: " rpl)))
1931 ((equal char ?0)
1932 (setq ckey (or index-key phrase)
1933 rpl (save-match-data
1934 (reftex-index-make-replace-string
1935 macro-fmt match ckey repeat mathp))))
1936 ((and (> char ?0)
1937 (<= char (+ ?0 nkeys)))
1938 (setq ckey (nth (1- (- char ?0)) index-keys)
1939 rpl (save-match-data
1940 (reftex-index-make-replace-string
1941 macro-fmt match ckey repeat mathp))))
1942 (t (ding)))
1943 nil)))))
1944 (message "")
1945 (move-marker beg nil)
1946 (move-marker end nil)
1947 (setq all-yes nil)
1948 (reftex-unhighlight 0))))
1949
1950 (defun reftex-index-phrase-match-is-indexed (beg end)
1951 ;; Check if match is in an argument of an index macro, or if an
1952 ;; index macro is directly attached to the match.
1953 (save-excursion
1954 (goto-char end)
1955 (let* ((all-macros (reftex-what-macro t))
1956 ; (this-macro (car (car all-macros)))
1957 (before-macro
1958 (and (> beg 2)
1959 (goto-char (1- beg))
1960 (memq (char-after (point)) '(?\] ?\}))
1961 (car (reftex-what-macro 1))))
1962 (after-macro
1963 (and (goto-char end)
1964 (looking-at "\\(\\\\[a-zA-Z]+\\*?\\)[[{]")
1965 (match-string 1)))
1966 macro)
1967 (or (catch 'matched
1968 (while (setq macro (pop all-macros))
1969 (if (member (car macro) reftex-macros-with-index)
1970 (throw 'matched t)))
1971 nil)
1972 (and before-macro
1973 (member before-macro reftex-macros-with-index))
1974 (and after-macro
1975 (member after-macro reftex-macros-with-index))))))
1976
1977 (defun reftex-index-phrases-fixup-line (beg end)
1978 "Insert newlines before BEG and/or after END to shorten line."
1979 (let (bol eol space1 space2)
1980 (save-excursion
1981 ;; Find line boundaries and possible line breaks near BEG and END
1982 (beginning-of-line)
1983 (setq bol (point))
1984 (end-of-line)
1985 (setq eol (point))
1986 (goto-char beg)
1987 (skip-chars-backward "^ \n")
1988 (if (and (equal (preceding-char) ?\ )
1989 (string-match "\\S-" (buffer-substring bol (point))))
1990 (setq space1 (1- (point))))
1991 (goto-char end)
1992 (skip-chars-forward "^ \n")
1993 (if (and (equal (following-char) ?\ )
1994 (string-match "\\S-" (buffer-substring (point) eol)))
1995 (setq space2 (point)))
1996 ;; Now check what we have and insert the newlines
1997 (if (<= (- eol bol) fill-column)
1998 ;; Line is already short
1999 nil
2000 (cond
2001 ((and (not space1) (not space2))) ; No spaces available
2002 ((not space2) ; Do space1
2003 (reftex-index-phrases-replace-space space1))
2004 ((not space1) ; Do space2
2005 (reftex-index-phrases-replace-space space2))
2006 (t ; We have both spaces
2007 (let ((l1 (- space1 bol))
2008 (l2 (- space2 space1))
2009 (l3 (- eol space2)))
2010 (if (> l2 fill-column)
2011 ;; The central part alone is more than one line
2012 (progn
2013 (reftex-index-phrases-replace-space space1)
2014 (reftex-index-phrases-replace-space space2))
2015 (if (> (+ l1 l2) fill-column)
2016 ;; Need to split beginning
2017 (reftex-index-phrases-replace-space space1))
2018 (if (> (+ l2 l3) fill-column)
2019 ;; Need to split end
2020 (reftex-index-phrases-replace-space space2))))))))))
2021
2022 (defun reftex-index-phrases-replace-space (pos)
2023 "If there is a space at POS, replace it with a newline char.
2024 Does not do a save-excursion."
2025 (when (equal (char-after pos) ?\ )
2026 (goto-char pos)
2027 (delete-char 1)
2028 (insert "\n")))
2029
2030 (defun reftex-index-select-phrases-macro (&optional delay)
2031 "Offer a list of possible index macros and have the user select one."
2032 (let* ((prompt (concat "Select macro: ["
2033 (mapconcat (lambda (x) (char-to-string (car x)))
2034 reftex-index-phrases-macro-data "")
2035 "] "))
2036 (help (concat "Select an indexing macro\n========================\n"
2037 (mapconcat (lambda (x)
2038 (format " [%c] %s"
2039 (car x) (nth 1 x)))
2040 reftex-index-phrases-macro-data "\n"))))
2041 (reftex-select-with-char prompt help delay)))
2042
2043 ;; Keybindings and Menu for phrases buffer
2044
2045 (loop for x in
2046 '(("\C-c\C-c" . reftex-index-phrases-save-and-return)
2047 ("\C-c\C-x" . reftex-index-this-phrase)
2048 ("\C-c\C-f" . reftex-index-next-phrase)
2049 ("\C-c\C-r" . reftex-index-region-phrases)
2050 ("\C-c\C-a" . reftex-index-all-phrases)
2051 ("\C-c\C-d" . reftex-index-remaining-phrases)
2052 ("\C-c\C-s" . reftex-index-sort-phrases)
2053 ("\C-c\C-n" . reftex-index-new-phrase)
2054 ("\C-c\C-m" . reftex-index-phrases-set-macro-key)
2055 ("\C-c\C-i" . reftex-index-phrases-info)
2056 ("\C-c\C-t" . reftex-index-find-next-conflict-phrase)
2057 ("\C-i" . self-insert-command))
2058 do (define-key reftex-index-phrases-map (car x) (cdr x)))
2059
2060 (easy-menu-define
2061 reftex-index-phrases-menu reftex-index-phrases-map
2062 "Menu for Phrases buffer"
2063 '("Phrases"
2064 ["New Phrase" reftex-index-new-phrase t]
2065 ["Set Phrase Macro" reftex-index-phrases-set-macro-key t]
2066 ["Recreate File Header" reftex-index-initialize-phrases-buffer t]
2067 "--"
2068 ("Sort Phrases"
2069 ["Sort" reftex-index-sort-phrases t]
2070 "--"
2071 "Sort Options"
2072 ["by Search Phrase" (setq reftex-index-phrases-sort-prefers-entry nil)
2073 :style radio :selected (not reftex-index-phrases-sort-prefers-entry)]
2074 ["by Index Entry" (setq reftex-index-phrases-sort-prefers-entry t)
2075 :style radio :selected reftex-index-phrases-sort-prefers-entry]
2076 ["in Blocks" (setq reftex-index-phrases-sort-in-blocks
2077 (not reftex-index-phrases-sort-in-blocks))
2078 :style toggle :selected reftex-index-phrases-sort-in-blocks])
2079 ["Describe Phrase" reftex-index-phrases-info t]
2080 ["Next Phrase Conflict" reftex-index-find-next-conflict-phrase t]
2081 "--"
2082 ("Find and Index in Document"
2083 ["Current Phrase" reftex-index-this-phrase t]
2084 ["Next Phrase" reftex-index-next-phrase t]
2085 ["Current and Following" reftex-index-remaining-phrases t]
2086 ["Region Phrases" reftex-index-region-phrases t]
2087 ["All Phrases" reftex-index-all-phrases t]
2088 "--"
2089 "Options"
2090 ["Match Whole Words" (setq reftex-index-phrases-search-whole-words
2091 (not reftex-index-phrases-search-whole-words))
2092 :style toggle :selected reftex-index-phrases-search-whole-words]
2093 ["Case Sensitive Search" (setq reftex-index-phrases-case-fold-search
2094 (not reftex-index-phrases-case-fold-search))
2095 :style toggle :selected (not
2096 reftex-index-phrases-case-fold-search)]
2097 ["Wrap Long Lines" (setq reftex-index-phrases-wrap-long-lines
2098 (not reftex-index-phrases-wrap-long-lines))
2099 :style toggle :selected reftex-index-phrases-wrap-long-lines]
2100 ["Skip Indexed Matches" (setq reftex-index-phrases-skip-indexed-matches
2101 (not reftex-index-phrases-skip-indexed-matches))
2102 :style toggle :selected reftex-index-phrases-skip-indexed-matches])
2103 "--"
2104 ["Save and Return" reftex-index-phrases-save-and-return t]))
2105
2106
2107 ;; arch-tag: 4b2362af-c156-42c1-8932-ea2823e205c1
2108 ;;; reftex-index.el ends here