Initial Commit
[packages] / xemacs-packages / c-support / hideif.el
1 ;;; hide-ifdef-mode.el --- hides selected code within ifdef.
2
3 ;; Copyright (C) 1988, 1994 Free Software Foundation, Inc.
4
5 ;; Author: Dan LaLiberte <liberte@a.cs.uiuc.edu>
6 ;; Maintainer: FSF
7 ;; Keywords: c, outlines
8
9 ;; This file is part of XEmacs.
10
11 ;; XEmacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; XEmacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with XEmacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330, 
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Synched up with: FSF 20.4.
27
28 ;;; Commentary:
29
30 ;; To initialize, toggle the hide-ifdef minor mode with
31 ;;
32 ;; M-x hide-ifdef-mode
33 ;;
34 ;; This will set up key bindings and call hide-ifdef-mode-hook if it
35 ;; has a value.  To explicitly hide ifdefs using a buffer-local
36 ;; define list (default empty), type
37 ;;
38 ;; M-x hide-ifdefs  or C-c @ h
39 ;;
40 ;; Hide-ifdef suppresses the display of code that the preprocessor wouldn't
41 ;; pass through.  The support of constant expressions in #if lines is 
42 ;; limited to identifiers, parens, and the operators: &&, ||, !, and
43 ;; "defined".  Please extend this.
44 ;;
45 ;; The hidden code is marked by ellipses (...).  Be
46 ;; cautious when editing near ellipses, since the hidden text is
47 ;; still in the buffer, and you can move the point into it and modify
48 ;; text unawares.  If you don't want to see the ellipses, set 
49 ;; selective-display-ellipses to nil.  But this can be dangerous.
50 ;; You can make your buffer read-only while hide-ifdef-hiding by setting
51 ;; hide-ifdef-read-only to a non-nil value.  You can toggle this 
52 ;; variable with hide-ifdef-toggle-read-only (C-c @ C-q).
53 ;;
54 ;; You can undo the effect of hide-ifdefs by typing
55 ;;
56 ;; M-x show-ifdefs  or C-c @ s
57 ;;
58 ;; Use M-x hide-ifdef-define (C-c @ d) to define a symbol.
59 ;; Use M-x hide-ifdef-undef (C-c @ u) to undefine a symbol.
60 ;;
61 ;; If you define or undefine a symbol while hide-ifdef-mode is in effect,
62 ;; the display will be updated.  Only the define list for the current
63 ;; buffer will be affected.  You can save changes to the local define
64 ;; list with hide-ifdef-set-define-alist.  This adds entries 
65 ;; to hide-ifdef-define-alist.
66 ;;
67 ;; If you have defined a hide-ifdef-mode-hook, you can set
68 ;; up a list of symbols that may be used by hide-ifdefs as in the
69 ;; following example:
70 ;;
71 ;; (setq hide-ifdef-mode-hook
72 ;;      '(lambda ()
73 ;;       (if (not hide-ifdef-define-alist)
74 ;;           (setq hide-ifdef-define-alist
75 ;;                '((list1 ONE TWO)
76 ;;                  (list2 TWO THREE)
77 ;;                  )))
78 ;;       (hide-ifdef-use-define-alist 'list2) ; use list2 by default
79 ;;       ))
80 ;;
81 ;; You can call hide-ifdef-use-define-alist (C-c @ u) at any time to specify
82 ;; another list to use.
83 ;;
84 ;; To cause ifdefs to be hidden as soon as hide-ifdef-mode is called,
85 ;; set hide-ifdef-initially to non-nil.
86 ;;
87 ;; If you set hide-ifdef-lines to t, hide-ifdefs hides all the #ifdef lines.
88 ;; In the absence of highlighting, that might be a bad idea.  If you set
89 ;; hide-ifdef-lines to nil (the default), the surrounding preprocessor
90 ;; lines will be displayed.  That can be confusing in its own
91 ;; right.  Other variations on display are possible, but not much
92 ;; better.
93 ;;
94 ;; You can explicitly hide or show individual ifdef blocks irrespective
95 ;; of the define list by using hide-ifdef-block and show-ifdef-block.
96 ;;
97 ;; You can move the point between ifdefs with forward-ifdef, backward-ifdef,
98 ;; up-ifdef, down-ifdef, next-ifdef, and previous-ifdef.
99 ;;
100 ;; If you have minor-mode-alist in your mode line (the default) two labels
101 ;; may appear.  "Ifdef" will appear when hide-ifdef-mode is active.  "Hiding"
102 ;; will appear when text may be hidden ("hide-ifdef-hiding" is non-nil).
103 ;;
104 ;; Written by Brian Marick, at Gould, Computer Systems Division, Urbana IL.
105 ;; Extensively modified by Daniel LaLiberte (while at Gould).
106 ;;
107 ;; You may freely modify and distribute this, but keep a record
108 ;; of modifications and send comments to:
109 ;;       liberte@a.cs.uiuc.edu  or  ihnp4!uiucdcs!liberte
110 ;; I will continue to upgrade hide-ifdef-mode
111 ;; with your contributions.
112
113 ;;; Code:
114
115 (require 'cc-mode)
116
117 (defgroup hide-ifdef nil
118   "Hide selected code within `ifdef'."
119   :group 'c)
120
121 (defvar hide-ifdef-mode-submap nil
122   "Keymap used with Hide-Ifdef mode.")
123
124 ;;;###autoload
125 (defvar hide-ifdef-mode-map nil
126   "Keymap used with Hide-Ifdef mode.")
127
128 ;; XEmacs Change: Use vector notation. 
129 (defconst hide-ifdef-mode-prefix-key [(control c) @]
130   "Prefix key for all Hide-Ifdef mode commands.")
131
132 ;; Set up the submap that goes after the prefix key.
133 (if hide-ifdef-mode-submap
134     ()                          ; Don't redefine it.
135   (setq hide-ifdef-mode-submap (make-sparse-keymap))
136   (define-key hide-ifdef-mode-submap "d" 'hide-ifdef-define)
137   (define-key hide-ifdef-mode-submap "u" 'hide-ifdef-undef)
138   (define-key hide-ifdef-mode-submap "D" 'hide-ifdef-set-define-alist)
139   (define-key hide-ifdef-mode-submap "U" 'hide-ifdef-use-define-alist)
140
141   (define-key hide-ifdef-mode-submap "h" 'hide-ifdefs)
142   (define-key hide-ifdef-mode-submap "s" 'show-ifdefs)
143   (define-key hide-ifdef-mode-submap "\C-d" 'hide-ifdef-block)
144   (define-key hide-ifdef-mode-submap "\C-s" 'show-ifdef-block)
145
146   (define-key hide-ifdef-mode-submap "\C-q" 'hide-ifdef-toggle-read-only)
147 ;;(let ((where (where-is-internal 'toggle-read-only '(keymap) t)))
148 ;; XEmacs change 
149   (let ((where (where-is-internal 'toggle-read-only nil  t)))
150     (if where
151         (define-key hide-ifdef-mode-submap
152           where
153           'hide-ifdef-toggle-outside-read-only)))
154   )
155
156 ;; Set up the mode's main map, which leads via the prefix key to the submap.
157 (if hide-ifdef-mode-map
158     ()
159   (setq hide-ifdef-mode-map (make-sparse-keymap))
160   (define-key hide-ifdef-mode-map hide-ifdef-mode-prefix-key
161     hide-ifdef-mode-submap))
162
163 (defvar hide-ifdef-mode nil
164   "Non-nil when hide-ifdef-mode is activated.")
165
166 (defvar hide-ifdef-hiding nil
167   "Non-nil when text may be hidden.")
168
169 (or (assq 'hide-ifdef-hiding minor-mode-alist)
170     (setq minor-mode-alist
171           (cons '(hide-ifdef-hiding " Hiding")
172                 minor-mode-alist)))
173
174 ;(or (assq 'hide-ifdef-mode minor-mode-alist)
175 ;    (setq minor-mode-alist
176 ;          (cons '(hide-ifdef-mode " Ifdef")
177 ;                minor-mode-alist)))
178 ;; XEmacs: do it right.
179 ;;;###autoload
180 (add-minor-mode 'hide-ifdef-mode " Ifdef" hide-ifdef-mode-map)
181
182 ;; fix c-mode syntax table so we can recognize whole symbols.
183 (defvar hide-ifdef-syntax-table
184   (copy-syntax-table c-mode-syntax-table)
185   "Syntax table used for tokenizing #if expressions.")
186
187 (modify-syntax-entry ?_ "w" hide-ifdef-syntax-table)
188 (modify-syntax-entry ?& "." hide-ifdef-syntax-table)
189 (modify-syntax-entry ?\| "." hide-ifdef-syntax-table)
190
191 (defvar hide-ifdef-env nil
192   "An alist of defined symbols and their values.")
193
194 (defvar hif-outside-read-only nil
195   "Internal variable.  Saves the value of `buffer-read-only' while hiding.")
196
197 ;;;###autoload
198 (defun hide-ifdef-mode (arg)
199   "Toggle Hide-Ifdef mode.  This is a minor mode, albeit a large one.
200 With ARG, turn Hide-Ifdef mode on if arg is positive, off otherwise.
201 In Hide-Ifdef mode, code within #ifdef constructs that the C preprocessor
202 would eliminate may be hidden from view.  Several variables affect
203 how the hiding is done:
204
205 hide-ifdef-env
206         An association list of defined and undefined symbols for the
207         current buffer.  Initially, the global value of `hide-ifdef-env'
208         is used.
209
210 hide-ifdef-define-alist
211         An association list of defined symbol lists.  
212         Use `hide-ifdef-set-define-alist' to save the current `hide-ifdef-env'
213         and `hide-ifdef-use-define-alist' to set the current `hide-ifdef-env'
214         from one of the lists in `hide-ifdef-define-alist'.
215
216 hide-ifdef-lines
217         Set to non-nil to not show #if, #ifdef, #ifndef, #else, and
218         #endif lines when hiding.
219
220 hide-ifdef-initially
221         Indicates whether `hide-ifdefs' should be called when Hide-Ifdef mode
222         is activated.
223
224 hide-ifdef-read-only
225         Set to non-nil if you want to make buffers read only while hiding.
226         After `show-ifdefs', read-only status is restored to previous value.
227
228 \\{hide-ifdef-mode-map}"
229
230   (interactive "P")
231   (make-local-variable 'hide-ifdef-mode)
232   (setq hide-ifdef-mode
233         (if (null arg)
234             (not hide-ifdef-mode)
235           (> (prefix-numeric-value arg) 0)))
236
237   ;; XEmacs change
238   (redraw-modeline)
239
240   (if hide-ifdef-mode
241       (progn
242         ; inherit global values
243         (make-local-variable 'hide-ifdef-env)
244         (setq hide-ifdef-env (default-value 'hide-ifdef-env))
245
246         (make-local-variable 'hide-ifdef-hiding)
247         (setq hide-ifdef-hiding (default-value 'hide-ifdef-hiding))
248
249         (make-local-variable 'hif-outside-read-only)
250         (setq hif-outside-read-only buffer-read-only)
251
252         (run-hooks 'hide-ifdef-mode-hook)
253
254         (if hide-ifdef-initially
255             (hide-ifdefs)
256           (show-ifdefs))
257         (message "Enter Hide-Ifdef mode")
258         )
259      ; else end hide-ifdef-mode
260     (if hide-ifdef-hiding
261         (show-ifdefs))
262     (message "Exit Hide-Ifdef mode")
263     ))
264   
265
266 ;; from outline.el with docstring fixed.
267 (defun hif-outline-flag-region (from to flag)
268   "Hides or shows lines from FROM to TO, according to FLAG.
269 If FLAG is \\n (newline character) then text is shown, while if FLAG is \\^M
270 \(control-M) the text is hidden."
271   (let ((modp (buffer-modified-p)))
272     (unwind-protect (progn
273                       (subst-char-in-region from to
274                               (if (= flag ?\n) ?\^M ?\n)
275                               flag t) )
276       (set-buffer-modified-p modp))
277     ))
278
279 (defun hif-show-all ()
280   "Show all of the text in the current buffer."
281   (interactive)
282   (hif-outline-flag-region (point-min) (point-max) ?\n))
283
284 ;; By putting this on after-revert-hook, we arrange that it only
285 ;; does anything when revert-buffer avoids turning off the mode.
286 ;; (That can happen in VC.)
287 (defun hif-before-revert-function ()
288   (and hide-ifdef-mode hide-ifdef-hiding
289        (hide-ifdefs t)))
290 (add-hook 'after-revert-hook 'hif-before-revert-function)
291
292 (defun hide-ifdef-region (start end)
293   "START is the start of a #if or #else form.  END is the ending part.
294 Everything including these lines is made invisible."
295   (hif-outline-flag-region start end ?\^M)
296   )
297
298 (defun hif-show-ifdef-region (start end)
299   "Everything between START and END is made visible."
300   (hif-outline-flag-region start end ?\n)
301   )
302
303
304
305 ;===%%SF%% evaluation (Start)  ===
306
307 ;; It is not useful to set this to anything but `eval'.
308 ;; In fact, the variable might as well be eliminated.
309 (defvar hide-ifdef-evaluator 'eval
310   "The function to use to evaluate a form.
311 The evaluator is given a canonical form and returns t if text under
312 that form should be displayed.")
313
314 (defvar hif-undefined-symbol nil
315   "...is by default considered to be false.")
316
317
318 (defun hif-set-var (var value)
319   "Prepend (var value) pair to hide-ifdef-env."
320   (setq hide-ifdef-env (cons (cons var value) hide-ifdef-env)))
321
322
323 (defun hif-lookup (var)
324 ;  (message "hif-lookup %s" var)
325   (let ((val (assoc var hide-ifdef-env)))
326     (if val
327         (cdr val)
328       hif-undefined-symbol)))
329
330 (defun hif-defined (var)
331   (hif-lookup var)
332   ; when #if expressions are fully supported, defined result should be 1
333   ;  (if (assoc var  hide-ifdef-env)
334   ;      1
335   ;    nil)
336 )
337
338
339 ;===%%SF%% evaluation (End)  ===
340
341
342
343 ;===%%SF%% parsing (Start)  ===
344 ;;;  The code that understands what ifs and ifdef in files look like.
345
346 (defconst hif-cpp-prefix "\\(^\\|\r\\)[ \t]*#[ \t]*")
347 (defconst hif-ifndef-regexp (concat hif-cpp-prefix "ifndef"))
348 (defconst hif-ifx-regexp (concat hif-cpp-prefix "if\\(n?def\\)?[ \t]+"))
349 (defconst hif-else-regexp (concat hif-cpp-prefix "else"))
350 (defconst hif-endif-regexp (concat hif-cpp-prefix "endif"))
351 (defconst hif-ifx-else-endif-regexp
352   (concat hif-ifx-regexp "\\|" hif-else-regexp "\\|" hif-endif-regexp))
353
354 ; Used to store the current token and the whole token list during parsing.
355 ; Only bound dynamically.
356 (defvar hif-token)
357 (defvar hif-token-list)
358
359 (defun hif-infix-to-prefix (token-list)
360   "Convert list of tokens in infix into prefix list"
361 ;  (message "hif-infix-to-prefix: %s" token-list)
362   (if (= 1 (length token-list))
363       (` (hif-lookup (quote (, (car token-list)))))
364     (hif-parse-if-exp token-list))
365   )
366
367 ; pattern to match initial identifier, !, &&, ||, (, or ).
368 ; Added ==, + and -: garyo@avs.com 8/9/94
369 (defconst hif-token-regexp "^\\(&&\\|||\\|[!=]=\\|!\\|[()+-]\\|[<>]=?\\|\\w+\\)")
370 (defconst hif-end-of-comment "\\*/")
371
372
373 (defun hif-tokenize (expr-string)
374   "Separate string into a list of tokens"
375   (let ((token-list nil)
376         (expr-start 0)
377         (expr-length (length expr-string))
378         (current-syntax-table (syntax-table)))
379     (unwind-protect
380         (progn
381           (set-syntax-table hide-ifdef-syntax-table)
382           (while (< expr-start expr-length) 
383 ;           (message "expr-start = %d" expr-start) (sit-for 1)
384             (cond
385              ((string-match "^[ \t]+" expr-string expr-start)
386               ;; skip whitespace
387               (setq expr-start (match-end 0))
388               ;; stick newline in string so ^ matches on the next string-match
389               (aset expr-string (1- expr-start) ?\n))
390
391              ((string-match "^/\\*" expr-string expr-start)
392               (setq expr-start (match-end 0))
393               (aset expr-string (1- expr-start) ?\n)
394               (or
395                (string-match hif-end-of-comment
396                              expr-string expr-start) ; eat comment
397                (string-match "$" expr-string expr-start)) ; multi-line comment
398               (setq expr-start (match-end 0))
399               (aset expr-string (1- expr-start) ?\n))
400
401              ((string-match "^//" expr-string expr-start)
402               (string-match "$" expr-string expr-start)
403               (setq expr-start (match-end 0)))
404
405              ((string-match hif-token-regexp expr-string expr-start)
406               (let ((token (substring expr-string expr-start (match-end 0))))
407                 (setq expr-start (match-end 0))
408                 (aset expr-string (1- expr-start) ?\n)
409 ;               (message "token: %s" token) (sit-for 1)
410                 (setq token-list
411                       (cons
412                        (cond
413                         ((string-equal token "||") 'or)
414                         ((string-equal token "&&") 'and)
415                         ((string-equal token "==") 'equal)
416                         ((string-equal token "!=") 'hif-notequal)
417                         ((string-equal token "!")  'not)
418                         ((string-equal token "defined") 'hif-defined)
419                         ((string-equal token "(") 'lparen)
420                         ((string-equal token ")") 'rparen)
421                         ((string-equal token ">") 'hif-greater)
422                         ((string-equal token "<") 'hif-less)
423                         ((string-equal token ">=") 'hif-greater-equal)
424                         ((string-equal token "<=") 'hif-less-equal)
425                         ((string-equal token "+") 'hif-plus)
426                         ((string-equal token "-") 'hif-minus)
427                         (t (intern token)))
428                        token-list))))
429              (t (error "Bad #if expression: %s" expr-string)))))
430       (set-syntax-table current-syntax-table))
431     (nreverse token-list)))
432
433 ;;;-----------------------------------------------------------------
434 ;;; Translate C preprocessor #if expressions using recursive descent.
435 ;;; This parser is limited to the operators &&, ||, !, and "defined".
436 ;;; Added ==, !=, +, and -.  Gary Oberbrunner, garyo@avs.com, 8/9/94
437
438 (defun hif-parse-if-exp (hif-token-list)
439   "Parse the TOKEN-LIST.  Return translated list in prefix form."
440   (hif-nexttoken)
441   (prog1
442       (hif-expr)
443     (if hif-token ; is there still a token?
444         (error "Error: unexpected token: %s" hif-token))))
445
446 (defun hif-nexttoken ()
447   "Pop the next token from token-list into the let variable \"hif-token\"."
448   (setq hif-token (car hif-token-list))
449   (setq hif-token-list (cdr hif-token-list))
450   hif-token)
451
452 (defun hif-expr ()
453   "Parse an expression as found in #if.
454        expr : term | expr '||' term."
455   (let ((result (hif-term)))
456     (while (eq  hif-token 'or)
457       (hif-nexttoken)
458       (setq result (list 'or result (hif-term))))
459   result))
460
461 (defun hif-term ()
462   "Parse a term : eq-expr | term '&&' eq-expr."
463   (let ((result (hif-eq-expr)))
464     (while (eq hif-token 'and)
465       (hif-nexttoken)
466       (setq result (list 'and result (hif-eq-expr))))
467     result))
468
469 (defun hif-eq-expr ()
470   "Parse an eq-expr : math | eq-expr `=='|`!='|`<'|`>'|`>='|`<=' math."
471   (let ((result (hif-math))
472         (eq-token nil))
473     (while (memq hif-token '(equal hif-notequal hif-greater hif-less
474                                    hif-greater-equal hif-less-equal))
475       (setq eq-token hif-token)
476       (hif-nexttoken)
477       (setq result (list eq-token result (hif-math))))
478     result))
479
480 (defun hif-math ()
481   "Parse an expression with + or - and simpler things.
482        math : factor | math '+|-' factor."
483   (let ((result (hif-factor))
484         (math-op nil))
485     (while (or (eq  hif-token 'hif-plus) (eq hif-token 'hif-minus))
486       (setq math-op hif-token)
487       (hif-nexttoken)
488       (setq result (list math-op result (hif-factor))))
489   result))
490
491 (defun hif-factor ()
492   "Parse a factor: '!' factor | '(' expr ')' | 'defined(' id ')' | id."
493   (cond
494     ((eq hif-token 'not)
495      (hif-nexttoken)
496      (list 'not (hif-factor)))
497
498     ((eq hif-token 'lparen)
499      (hif-nexttoken)
500      (let ((result (hif-expr)))
501        (if (not (eq hif-token 'rparen))
502            (error "Bad token in parenthesized expression: %s" hif-token)
503          (hif-nexttoken)
504          result)))
505
506     ((eq hif-token 'hif-defined)
507      (hif-nexttoken)
508      (if (not (eq hif-token 'lparen))
509          (error "Error: expected \"(\" after \"defined\""))
510      (hif-nexttoken)
511      (let ((ident hif-token))
512        (if (memq hif-token '(or and not hif-defined lparen rparen))
513            (error "Error: unexpected token: %s" hif-token))
514        (hif-nexttoken)
515        (if (not (eq hif-token 'rparen))
516            (error "Error: expected \")\" after identifier"))
517        (hif-nexttoken)
518        (` (hif-defined (quote (, ident))))
519        ))
520
521     (t ; identifier
522       (let ((ident hif-token))
523         (if (memq ident '(or and))
524             (error "Error: missing identifier"))
525         (hif-nexttoken)
526         (` (hif-lookup (quote (, ident))))
527         ))
528     ))
529
530 (defun hif-mathify (val)
531   "Treat VAL as a number: if it's t or nil, use 1 or 0."
532   (cond ((eq val t)
533          1)
534         ((null val)
535          0)
536         (t val)))
537
538 (defun hif-plus (a b)
539   "Like ordinary plus but treat t and nil as 1 and 0."
540   (+ (hif-mathify a) (hif-mathify b)))
541 (defun hif-minus (a b)
542   "Like ordinary minus but treat t and nil as 1 and 0."
543   (- (hif-mathify a) (hif-mathify b)))
544 (defun hif-notequal (a b)
545   "Like (not (equal A B)) but as one symbol."
546   (not (equal a b)))
547 (defun hif-greater (a b)
548   "Simple comparison."
549   (> (hif-mathify a) (hif-mathify b)))
550 (defun hif-less (a b)
551   "Simple comparison."
552   (< (hif-mathify a) (hif-mathify b)))
553 (defun hif-greater-equal (a b)
554   "Simple comparison."
555   (>= (hif-mathify a) (hif-mathify b)))
556 (defun hif-less-equal (a b)
557   "Simple comparison."
558   (<= (hif-mathify a) (hif-mathify b)))
559 ;;;----------- end of parser -----------------------
560
561
562 (defun hif-canonicalize ()
563   "When at beginning of #ifX, returns a Lisp expression for its condition."
564   (save-excursion
565     (let ((negate (looking-at hif-ifndef-regexp)))
566       (re-search-forward hif-ifx-regexp)
567       (let* ((expr-string
568               (buffer-substring (point)
569                                 (progn (skip-chars-forward "^\n\r") (point))))
570              (expr (hif-infix-to-prefix (hif-tokenize expr-string))))
571 ;       (message "hif-canonicalized: %s" expr)
572         (if negate
573             (list 'not expr)
574           expr)))))
575
576
577 (defun hif-find-any-ifX ()
578   "Move to next #if..., or #ifndef, at point or after."
579 ;  (message "find ifX at %d" (point))
580   (prog1
581       (re-search-forward hif-ifx-regexp (point-max) t)
582     (beginning-of-line)))
583
584
585 (defun hif-find-next-relevant ()
586   "Move to next #if..., #else, or #endif, after the current line."
587 ;  (message "hif-find-next-relevant at %d" (point))
588   (end-of-line)
589   ; avoid infinite recursion by only going to beginning of line if match found
590   (if (re-search-forward hif-ifx-else-endif-regexp (point-max) t)
591       (beginning-of-line)))
592
593 (defun hif-find-previous-relevant ()
594   "Move to previous #if..., #else, or #endif, before the current line."
595 ;  (message "hif-find-previous-relevant at %d" (point))
596   (beginning-of-line)
597   ; avoid infinite recursion by only going to beginning of line if match found
598   (if (re-search-backward hif-ifx-else-endif-regexp (point-min) t)
599      (beginning-of-line)))
600
601
602 (defun hif-looking-at-ifX ()            ;; Should eventually see #if
603   (looking-at hif-ifx-regexp))
604 (defun hif-looking-at-endif ()
605   (looking-at hif-endif-regexp))
606 (defun hif-looking-at-else ()
607   (looking-at hif-else-regexp))
608
609
610
611 (defun hif-ifdef-to-endif ()
612   "If positioned at #ifX or #else form, skip to corresponding #endif."
613 ;  (message "hif-ifdef-to-endif at %d" (point)) (sit-for 1)
614   (hif-find-next-relevant)
615   (cond ((hif-looking-at-ifX)
616          (hif-ifdef-to-endif) ; find endif of nested if
617          (hif-ifdef-to-endif)) ; find outer endif or else
618         ((hif-looking-at-else)
619          (hif-ifdef-to-endif)) ; find endif following else
620         ((hif-looking-at-endif)
621          'done)
622         (t
623          (error "Mismatched #ifdef #endif pair"))))
624
625
626 (defun hif-endif-to-ifdef ()
627   "If positioned at #endif form, skip backward to corresponding #ifX."
628 ;  (message "hif-endif-to-ifdef at %d" (point))
629   (let ((start (point)))
630     (hif-find-previous-relevant)
631     (if (= start (point))
632         (error "Mismatched #ifdef #endif pair")))
633   (cond ((hif-looking-at-endif)
634          (hif-endif-to-ifdef) ; find beginning of nested if
635          (hif-endif-to-ifdef)) ; find beginning of outer if or else
636         ((hif-looking-at-else)
637          (hif-endif-to-ifdef))
638         ((hif-looking-at-ifX)
639          'done)
640         (t)))                   ; never gets here
641
642
643 (defun forward-ifdef (&optional arg)
644   "Move point to beginning of line of the next ifdef-endif.
645 With argument, do this that many times."
646   (interactive "p")
647   (or arg (setq arg 1))
648   (if (< arg 0)
649       (backward-ifdef (- arg)))
650   (while (< 0 arg)
651     (setq arg (- arg))
652     (let ((start (point)))
653       (if (not (hif-looking-at-ifX))
654           (hif-find-next-relevant))
655       (if (hif-looking-at-ifX)
656           (hif-ifdef-to-endif)
657         (goto-char start)
658         (error "No following #ifdef")
659         ))))
660
661
662 (defun backward-ifdef (&optional arg)
663   "Move point to beginning of the previous ifdef-endif.
664 With argument, do this that many times."
665   (interactive "p")
666   (or arg (setq arg 1))
667   (if (< arg 0)
668       (forward-ifdef (- arg)))
669   (while (< 0 arg)
670     (setq arg (1- arg))
671     (beginning-of-line)
672     (let ((start (point)))
673       (if (not (hif-looking-at-endif))
674           (hif-find-previous-relevant))
675       (if (hif-looking-at-endif)
676           (hif-endif-to-ifdef)
677         (goto-char start)
678         (error "No previous #ifdef")))))
679
680
681 (defun down-ifdef ()
682   "Move point to beginning of nested ifdef or else-part."
683     (interactive)
684     (let ((start (point)))
685       (hif-find-next-relevant)
686       (if (or (hif-looking-at-ifX) (hif-looking-at-else))
687           ()
688         (goto-char start)
689         (error "No following #ifdef"))))
690
691
692 (defun up-ifdef ()
693   "Move point to beginning of enclosing ifdef or else-part."
694   (interactive)
695   (beginning-of-line)
696   (let ((start (point)))
697     (if (not (hif-looking-at-endif))
698         (hif-find-previous-relevant))
699     (if (hif-looking-at-endif)
700         (hif-endif-to-ifdef))
701       (if (= start (point))
702           (error "No previous #ifdef"))))
703
704 (defun next-ifdef (&optional arg)
705   "Move to the beginning of the next #ifX, #else, or #endif.
706 With argument, do this that many times."
707   (interactive "p")
708   (or arg (setq arg 1))
709   (if (< arg 0)
710       (previous-ifdef (- arg)))
711   (while (< 0 arg)
712     (setq arg (1- arg))
713     (hif-find-next-relevant)
714     (if (eolp)
715         (progn
716           (beginning-of-line)
717           (error "No following #ifdefs, #elses, or #endifs")))))
718
719 (defun previous-ifdef (&optional arg)
720   "Move to the beginning of the previous #ifX, #else, or #endif.
721 With argument, do this that many times."
722   (interactive "p")
723   (or arg (setq arg 1))
724   (if (< arg 0)
725       (next-ifdef (- arg)))
726   (while (< 0 arg)
727     (setq arg (1- arg))
728     (let ((start (point)))
729       (hif-find-previous-relevant)
730       (if (= start (point))
731           (error "No previous #ifdefs, #elses, or #endifs")
732         ))))
733
734
735 ;===%%SF%% parsing (End)  ===
736
737
738 ;===%%SF%% hide-ifdef-hiding (Start)  ===
739
740
741 ;;; A range is a structure with four components:
742 ;;; ELSE-P      True if there was an else clause for the ifdef.
743 ;;; START       The start of the range. (beginning of line)
744 ;;; ELSE        The else marker (beginning of line)
745 ;;;                     Only valid if ELSE-P is true.
746 ;;; END         The end of the range.  (beginning of line)
747
748 (defun hif-make-range (else-p start end &optional else)
749   (list else-p start else end))
750
751 (defun hif-range-else-p (range)  (elt range 0))
752 (defun hif-range-start (range) (elt range 1))
753 (defun hif-range-else (range) (elt range 2))
754 (defun hif-range-end (range) (elt range 3))
755
756
757
758 ;;; Find-Range
759 ;;; The workhorse, it delimits the #if region.  Reasonably simple:
760 ;;; Skip until an #else or #endif is found, remembering positions.  If
761 ;;; an #else was found, skip some more, looking for the true #endif.
762
763 (defun hif-find-range ()
764   "Returns a Range structure describing the current #if region.
765 Point is left unchanged."
766 ;  (message "hif-find-range at %d" (point))
767   (save-excursion
768     (beginning-of-line)
769     (let ((start (point))
770           (else-p nil)
771           (else nil)
772           (end nil))
773       ;; Part one.  Look for either #endif or #else.
774       ;; This loop-and-a-half dedicated to E. Dijkstra.
775       (hif-find-next-relevant)
776       (while (hif-looking-at-ifX)               ; Skip nested ifdef
777         (hif-ifdef-to-endif)
778         (hif-find-next-relevant))
779       ;; Found either a #else or an #endif.
780       (cond ((hif-looking-at-else)
781              (setq else-p t)
782              (setq else (point)))
783             (t
784              (setq end (point)) ; (save-excursion (end-of-line) (point))
785              ))
786       ;; If found #else, look for #endif.
787       (if else-p
788           (progn
789             (hif-find-next-relevant)
790             (while (hif-looking-at-ifX) ; Skip nested ifdef
791               (hif-ifdef-to-endif)
792               (hif-find-next-relevant))
793             (if (hif-looking-at-else)
794                 (error "Found two elses in a row?  Broken!"))
795             (setq end (point))  ; (save-excursion (end-of-line) (point))
796             ))
797       (hif-make-range else-p start end else))))
798
799           
800 ;;; A bit slimy.
801 ;;; NOTE:  If there's an #ifdef at the beginning of the file, we can't
802 ;;; hide it.  There's no previous newline to replace.  If we added
803 ;;; one, we'd throw off all the counts.  Feh.
804
805 (defun hif-hide-line (point)
806   "Hide the line containing point.  Does nothing if `hide-ifdef-lines' is nil."
807   (if hide-ifdef-lines
808       (save-excursion
809         (goto-char point)
810         (let ((modp (buffer-modified-p)))
811           (unwind-protect
812               (progn
813                 (beginning-of-line)
814                 (if (not (= (point) 1))
815                     (hide-ifdef-region (1- (point)) (point))))
816             (set-buffer-modified-p modp))
817           ))
818     ))
819                   
820
821 ;;;  Hif-Possibly-Hide
822 ;;;  There are four cases.  The #ifX expression is "taken" if it
823 ;;;  the hide-ifdef-evaluator returns T.  Presumably, this means the code
824 ;;;  inside the #ifdef would be included when the program was
825 ;;;  compiled.  
826 ;;;
827 ;;;  Case 1:  #ifX taken, and there's an #else.
828 ;;;     The #else part must be hidden.  The #if (then) part must be
829 ;;;     processed for nested #ifX's.
830 ;;;  Case 2:  #ifX taken, and there's no #else.
831 ;;;     The #if part must be processed for nested #ifX's.
832 ;;;  Case 3:  #ifX not taken, and there's an #else.
833 ;;;     The #if part must be hidden.  The #else part must be processed
834 ;;;     for nested #ifs.
835 ;;;  Case 4:  #ifX not taken, and there's no #else.
836 ;;;     The #ifX part must be hidden.
837 ;;;
838 ;;;  Further processing is done by narrowing to the relevant region
839 ;;;  and just recursively calling hide-ifdef-guts.
840 ;;;
841 ;;;  When hif-possibly-hide returns, point is at the end of the
842 ;;;  possibly-hidden range.
843
844 (defun hif-recurse-on (start end)
845   "Call `hide-ifdef-guts' after narrowing to end of START line and END line."
846   (save-excursion
847     (save-restriction
848       (goto-char start)
849       (end-of-line)
850       (narrow-to-region (point) end)
851       (hide-ifdef-guts))))
852
853 (defun hif-possibly-hide ()
854   "Called at #ifX expression, this hides those parts that should be hidden.
855 It uses the judgment of `hide-ifdef-evaluator'."
856 ;  (message "hif-possibly-hide") (sit-for 1)
857     (let ((test (hif-canonicalize))
858           (range (hif-find-range)))
859 ;      (message "test = %s" test) (sit-for 1)
860       
861       (hif-hide-line (hif-range-end range))
862       (if (funcall hide-ifdef-evaluator test)
863           (cond ((hif-range-else-p range) ; case 1
864                  (hif-hide-line (hif-range-else range))
865                  (hide-ifdef-region (hif-range-else range) 
866                                     (1- (hif-range-end range)))
867                  (hif-recurse-on (hif-range-start range)
868                                  (hif-range-else range)))
869                 (t ; case 2
870                  (hif-recurse-on (hif-range-start range)
871                                  (hif-range-end range))))
872         (cond ((hif-range-else-p range) ; case 3
873                (hif-hide-line (hif-range-else range))
874                (hide-ifdef-region (hif-range-start range)
875                                   (1- (hif-range-else range)))
876                (hif-recurse-on (hif-range-else range)
877                                (hif-range-end range)))
878               (t ; case 4
879                (hide-ifdef-region (point)
880                                   (1- (hif-range-end range))))
881               ))
882       (hif-hide-line (hif-range-start range))   ; Always hide start.
883       (goto-char (hif-range-end range))
884       (end-of-line)
885       ))
886
887
888
889 (defun hide-ifdef-guts ()
890   "Does most of the work of `hide-ifdefs'.
891 It does not do the work that's pointless to redo on a recursive entry."
892 ;  (message "hide-ifdef-guts")
893   (save-excursion
894     (goto-char (point-min))
895     (while (hif-find-any-ifX)
896       (hif-possibly-hide))))
897
898 ;===%%SF%% hide-ifdef-hiding (End)  ===
899
900
901 ;===%%SF%% exports (Start)  ===
902
903 ;;;###autoload
904 (defcustom hide-ifdef-initially nil
905   "*Non-nil means call `hide-ifdefs' when Hide-Ifdef mode is first activated."
906   :type 'boolean
907   :group 'hide-ifdef)
908
909 ;;;###autoload
910 (defcustom hide-ifdef-read-only nil
911   "*Set to non-nil if you want buffer to be read-only while hiding text."
912   :type 'boolean
913   :group 'hide-ifdef)
914
915 ;;;###autoload
916 (defcustom hide-ifdef-lines nil
917   "*Non-nil means hide the #ifX, #else, and #endif lines."
918   :type 'boolean
919   :group 'hide-ifdef)
920
921 (defun hide-ifdef-toggle-read-only ()
922   "Toggle hide-ifdef-read-only."
923   (interactive)
924   (setq hide-ifdef-read-only (not hide-ifdef-read-only))
925   (message "Hide-Read-Only %s"
926            (if hide-ifdef-read-only "ON" "OFF"))
927   (if hide-ifdef-hiding
928       (setq buffer-read-only (or hide-ifdef-read-only hif-outside-read-only)))
929   ;; XEmacs change
930   (redraw-modeline))
931
932 (defun hide-ifdef-toggle-outside-read-only ()
933   "Replacement for `toggle-read-only' within Hide-Ifdef mode."
934   (interactive)
935   (setq hif-outside-read-only (not hif-outside-read-only))
936   (message "Read only %s"
937            (if hif-outside-read-only "ON" "OFF"))
938   (setq buffer-read-only
939         (or (and hide-ifdef-hiding hide-ifdef-read-only)
940             hif-outside-read-only)
941         )
942   ;; XEmacs change
943   (redraw-modeline))
944
945       
946 (defun hide-ifdef-define (var)
947   "Define a VAR so that #ifdef VAR would be included."
948   (interactive "SDefine what? ")
949   (hif-set-var var 1)
950   (if hide-ifdef-hiding (hide-ifdefs)))
951
952 (defun hide-ifdef-undef (var)
953   "Undefine a VAR so that #ifdef VAR would not be included."
954   (interactive "SUndefine what? ")
955   (hif-set-var var nil)
956   (if hide-ifdef-hiding (hide-ifdefs)))
957
958
959 (defun hide-ifdefs (&optional nomsg)
960   "Hide the contents of some #ifdefs.  
961 Assume that defined symbols have been added to `hide-ifdef-env'.  
962 The text hidden is the text that would not be included by the C
963 preprocessor if it were given the file with those symbols defined.
964
965 Turn off hiding by calling `show-ifdefs'."
966
967   (interactive)
968   (message "Hiding...")
969   (setq hif-outside-read-only buffer-read-only)
970   (if (not hide-ifdef-mode)
971       (hide-ifdef-mode 1)) ; turn on hide-ifdef-mode
972   (if hide-ifdef-hiding
973       (show-ifdefs))                    ; Otherwise, deep confusion.
974   (let ((inhibit-read-only t))
975     (setq selective-display t)
976     (setq hide-ifdef-hiding t)
977     (hide-ifdef-guts))
978   (setq buffer-read-only (or hide-ifdef-read-only hif-outside-read-only))
979   (or nomsg
980       (message "Hiding done")))
981
982
983 (defun show-ifdefs ()
984   "Cancel the effects of `hide-ifdef': show the contents of all #ifdefs."
985   (interactive)
986   (setq buffer-read-only hif-outside-read-only)
987   (setq selective-display nil)  ; defaults
988   (let ((inhibit-read-only t))
989     (hif-show-all))
990   (setq hide-ifdef-hiding nil))
991
992
993 (defun hif-find-ifdef-block ()
994   "Utility for hide and show `ifdef-block'.
995 Return as (TOP . BOTTOM) the extent of ifdef block."
996   (let (max-bottom)
997     (cons (save-excursion
998             (beginning-of-line)
999             (if (not (or (hif-looking-at-else) (hif-looking-at-ifX)))
1000                 (up-ifdef))
1001             (prog1 (point)
1002               (hif-ifdef-to-endif)
1003               (setq max-bottom (1- (point)))))
1004           (save-excursion
1005             (beginning-of-line)
1006             (if (not (hif-looking-at-endif))
1007                 (hif-find-next-relevant))
1008             (while (hif-looking-at-ifX)
1009               (hif-ifdef-to-endif)
1010               (hif-find-next-relevant))
1011             (min max-bottom (1- (point)))))))
1012
1013
1014 (defun hide-ifdef-block ()
1015   "Hide the ifdef block (true or false part) enclosing or before the cursor."
1016   (interactive)
1017   (if (not hide-ifdef-mode)
1018       (hide-ifdef-mode 1))
1019   (setq selective-display t)
1020   (let ((top-bottom  (hif-find-ifdef-block))
1021         (inhibit-read-only t))
1022     (hide-ifdef-region (car top-bottom) (cdr top-bottom))
1023     (if hide-ifdef-lines
1024         (progn
1025           (hif-hide-line (car top-bottom))
1026           (hif-hide-line (1+ (cdr top-bottom)))))
1027     (setq hide-ifdef-hiding t))
1028   (setq buffer-read-only (or hide-ifdef-read-only hif-outside-read-only)))
1029
1030
1031 (defun show-ifdef-block ()
1032   "Show the ifdef block (true or false part) enclosing or before the cursor."
1033   (interactive)
1034   (let ((inhibit-read-only t))
1035     (if hide-ifdef-lines
1036         (save-excursion
1037           (beginning-of-line)
1038           (hif-show-ifdef-region (1- (point)) (progn (end-of-line) (point))))
1039
1040       (let ((top-bottom (hif-find-ifdef-block)))
1041       (hif-show-ifdef-region (1- (car top-bottom)) (cdr top-bottom))))))
1042
1043
1044 ;;;  definition alist support
1045
1046 (defvar hide-ifdef-define-alist nil
1047   "A global assoc list of pre-defined symbol lists")
1048
1049 (defun hif-compress-define-list (env)
1050   "Compress the define list ENV into a list of defined symbols only."
1051   (let ((defs (mapcar '(lambda (arg)
1052                          (if (hif-lookup (car arg)) (car arg)))
1053                       env))
1054         (new-defs nil))
1055     (while defs
1056       (if (car defs)
1057           (setq new-defs (cons (car defs) new-defs)))
1058       (setq defs (cdr defs)))
1059     new-defs))
1060
1061 (defun hide-ifdef-set-define-alist (name)
1062   "Set the association for NAME to `hide-ifdef-env'."
1063   (interactive "SSet define list: ")
1064   (setq hide-ifdef-define-alist
1065         (cons (cons name (hif-compress-define-list hide-ifdef-env))
1066               hide-ifdef-define-alist)))
1067
1068 (defun hide-ifdef-use-define-alist (name)
1069   "Set `hide-ifdef-env' to the define list specified by NAME."
1070   (interactive "SUse define list: ")
1071   (let ((define-list (assoc name hide-ifdef-define-alist)))
1072     (if define-list
1073         (setq hide-ifdef-env
1074               (mapcar '(lambda (arg) (cons arg t))
1075                       (cdr define-list)))
1076       (error "No define list for %s" name))
1077     (if hide-ifdef-hiding (hide-ifdefs))))
1078
1079 (provide 'hideif)
1080
1081 ;;; hideif.el ends here