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