Replace "Maintainer: FSF" with the emacs-devel mailing address
[emacs.git] / lisp / progmodes / hideif.el
blob9a811481f49559f0730c1f90cff9d1bf835245bd
1 ;;; hideif.el --- hides selected code within ifdef
3 ;; Copyright (C) 1988, 1994, 2001-2014 Free Software Foundation, Inc.
5 ;; Author: Brian Marick
6 ;; Daniel LaLiberte <liberte@holonexus.org>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: c, outlines
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; To initialize, toggle the hide-ifdef minor mode with
29 ;; M-x hide-ifdef-mode
31 ;; This will set up key bindings and call hide-ifdef-mode-hook if it
32 ;; has a value. To explicitly hide ifdefs using a buffer-local
33 ;; define list (default empty), type
35 ;; M-x hide-ifdefs or C-c @ h
37 ;; Hide-ifdef suppresses the display of code that the preprocessor wouldn't
38 ;; pass through. Support complete C/C++ expression and precedence.
40 ;; The hidden code is marked by ellipses (...). Be
41 ;; cautious when editing near ellipses, since the hidden text is
42 ;; still in the buffer, and you can move the point into it and modify
43 ;; text unawares.
44 ;; You can make your buffer read-only while hide-ifdef-hiding by setting
45 ;; hide-ifdef-read-only to a non-nil value. You can toggle this
46 ;; variable with hide-ifdef-toggle-read-only (C-c @ C-q).
48 ;; You can undo the effect of hide-ifdefs by typing
50 ;; M-x show-ifdefs or C-c @ s
52 ;; Use M-x hide-ifdef-define (C-c @ d) to define a symbol.
53 ;; Use M-x hide-ifdef-undef (C-c @ u) to undefine a symbol.
55 ;; If you define or undefine a symbol while hide-ifdef-mode is in effect,
56 ;; the display will be updated. Only the define list for the current
57 ;; buffer will be affected. You can save changes to the local define
58 ;; list with hide-ifdef-set-define-alist. This adds entries
59 ;; to hide-ifdef-define-alist.
61 ;; If you have defined a hide-ifdef-mode-hook, you can set
62 ;; up a list of symbols that may be used by hide-ifdefs as in the
63 ;; following example:
65 ;; (add-hook 'hide-ifdef-mode-hook
66 ;; (lambda ()
67 ;; (unless hide-ifdef-define-alist
68 ;; (setq hide-ifdef-define-alist
69 ;; '((list1 ONE TWO)
70 ;; (list2 TWO THREE))))
71 ;; (hide-ifdef-use-define-alist 'list2))) ; use list2 by default
73 ;; You can call hide-ifdef-use-define-alist (C-c @ U) at any time to specify
74 ;; another list to use.
76 ;; To cause ifdefs to be hidden as soon as hide-ifdef-mode is called,
77 ;; set hide-ifdef-initially to non-nil.
79 ;; If you set hide-ifdef-lines to t, hide-ifdefs hides all the #ifdef lines.
80 ;; In the absence of highlighting, that might be a bad idea. If you set
81 ;; hide-ifdef-lines to nil (the default), the surrounding preprocessor
82 ;; lines will be displayed. That can be confusing in its own
83 ;; right. Other variations on display are possible, but not much
84 ;; better.
86 ;; You can explicitly hide or show individual ifdef blocks irrespective
87 ;; of the define list by using hide-ifdef-block and show-ifdef-block.
89 ;; You can move the point between ifdefs with forward-ifdef, backward-ifdef,
90 ;; up-ifdef, down-ifdef, next-ifdef, and previous-ifdef.
92 ;; If you have minor-mode-alist in your mode line (the default) two labels
93 ;; may appear. "Ifdef" will appear when hide-ifdef-mode is active. "Hiding"
94 ;; will appear when text may be hidden ("hide-ifdef-hiding" is non-nil).
96 ;; Written by Brian Marick, at Gould, Computer Systems Division, Urbana IL.
97 ;; Extensively modified by Daniel LaLiberte (while at Gould).
99 ;; Extensively modified by Luke Lee in 2013 to support complete C expression
100 ;; evaluation.
102 ;;; Code:
104 (require 'cc-mode)
106 (defgroup hide-ifdef nil
107 "Hide selected code within `ifdef'."
108 :group 'c)
110 (defcustom hide-ifdef-initially nil
111 "Non-nil means call `hide-ifdefs' when Hide-Ifdef mode is first activated."
112 :type 'boolean
113 :group 'hide-ifdef)
115 (defcustom hide-ifdef-read-only nil
116 "Set to non-nil if you want buffer to be read-only while hiding text."
117 :type 'boolean
118 :group 'hide-ifdef)
120 (defcustom hide-ifdef-lines nil
121 "Non-nil means hide the #ifX, #else, and #endif lines."
122 :type 'boolean
123 :group 'hide-ifdef)
125 (defcustom hide-ifdef-shadow nil
126 "Non-nil means shadow text instead of hiding it."
127 :type 'boolean
128 :group 'hide-ifdef
129 :version "23.1")
131 (defface hide-ifdef-shadow '((t (:inherit shadow)))
132 "Face for shadowing ifdef blocks."
133 :group 'hide-ifdef
134 :version "23.1")
137 (defvar hide-ifdef-mode-submap
138 ;; Set up the submap that goes after the prefix key.
139 (let ((map (make-sparse-keymap)))
140 (define-key map "d" 'hide-ifdef-define)
141 (define-key map "u" 'hide-ifdef-undef)
142 (define-key map "D" 'hide-ifdef-set-define-alist)
143 (define-key map "U" 'hide-ifdef-use-define-alist)
145 (define-key map "h" 'hide-ifdefs)
146 (define-key map "s" 'show-ifdefs)
147 (define-key map "\C-d" 'hide-ifdef-block)
148 (define-key map "\C-s" 'show-ifdef-block)
150 (define-key map "\C-q" 'hide-ifdef-toggle-read-only)
151 (define-key map "\C-w" 'hide-ifdef-toggle-shadowing)
152 (substitute-key-definition
153 'toggle-read-only 'hide-ifdef-toggle-outside-read-only map)
154 map)
155 "Keymap used by `hide-ifdef-mode' under `hide-ifdef-mode-prefix-key'.")
157 (defconst hide-ifdef-mode-prefix-key "\C-c@"
158 "Prefix key for all Hide-Ifdef mode commands.")
160 (defvar hide-ifdef-mode-map
161 ;; Set up the mode's main map, which leads via the prefix key to the submap.
162 (let ((map (make-sparse-keymap)))
163 (define-key map hide-ifdef-mode-prefix-key hide-ifdef-mode-submap)
164 map)
165 "Keymap used with `hide-ifdef-mode'.")
167 (easy-menu-define hide-ifdef-mode-menu hide-ifdef-mode-map
168 "Menu for `hide-ifdef-mode'."
169 '("Hide-Ifdef"
170 ["Hide some ifdefs" hide-ifdefs
171 :help "Hide the contents of some #ifdefs"]
172 ["Show all ifdefs" show-ifdefs
173 :help "Cancel the effects of `hide-ifdef': show the contents of all #ifdefs"]
174 ["Hide ifdef block" hide-ifdef-block
175 :help "Hide the ifdef block (true or false part) enclosing or before the cursor"]
176 ["Show ifdef block" show-ifdef-block
177 :help "Show the ifdef block (true or false part) enclosing or before the cursor"]
178 ["Define a variable..." hide-ifdef-define
179 :help "Define a VAR so that #ifdef VAR would be included"]
180 ["Undefine a variable..." hide-ifdef-undef
181 :help "Undefine a VAR so that #ifdef VAR would not be included"]
182 ["Define an alist..." hide-ifdef-set-define-alist
183 :help "Set the association for NAME to `hide-ifdef-env'"]
184 ["Use an alist..." hide-ifdef-use-define-alist
185 :help "Set `hide-ifdef-env' to the define list specified by NAME"]
186 ["Toggle read only" hide-ifdef-toggle-read-only
187 :style toggle :selected hide-ifdef-read-only
188 :help "Buffer should be read-only while hiding text"]
189 ["Toggle shadowing" hide-ifdef-toggle-shadowing
190 :style toggle :selected hide-ifdef-shadow
191 :help "Text should be shadowed instead of hidden"]))
193 (defvar hide-ifdef-hiding nil
194 "Non-nil when text may be hidden.")
196 (or (assq 'hide-ifdef-hiding minor-mode-alist)
197 (setq minor-mode-alist
198 (cons '(hide-ifdef-hiding " Hiding")
199 minor-mode-alist)))
201 ;; fix c-mode syntax table so we can recognize whole symbols.
202 (defvar hide-ifdef-syntax-table
203 (let ((st (copy-syntax-table c-mode-syntax-table)))
204 (modify-syntax-entry ?_ "w" st)
205 (modify-syntax-entry ?& "." st)
206 (modify-syntax-entry ?\| "." st)
208 "Syntax table used for tokenizing #if expressions.")
210 (defvar hide-ifdef-env nil
211 "An alist of defined symbols and their values.")
213 (defvar hif-outside-read-only nil
214 "Internal variable. Saves the value of `buffer-read-only' while hiding.")
216 ;;;###autoload
217 (define-minor-mode hide-ifdef-mode
218 "Toggle features to hide/show #ifdef blocks (Hide-Ifdef mode).
219 With a prefix argument ARG, enable Hide-Ifdef mode if ARG is
220 positive, and disable it otherwise. If called from Lisp, enable
221 the mode if ARG is omitted or nil.
223 Hide-Ifdef mode is a buffer-local minor mode for use with C and
224 C-like major modes. When enabled, code within #ifdef constructs
225 that the C preprocessor would eliminate may be hidden from view.
226 Several variables affect how the hiding is done:
228 `hide-ifdef-env'
229 An association list of defined and undefined symbols for the
230 current buffer. Initially, the global value of `hide-ifdef-env'
231 is used.
233 `hide-ifdef-define-alist'
234 An association list of defined symbol lists.
235 Use `hide-ifdef-set-define-alist' to save the current `hide-ifdef-env'
236 and `hide-ifdef-use-define-alist' to set the current `hide-ifdef-env'
237 from one of the lists in `hide-ifdef-define-alist'.
239 `hide-ifdef-lines'
240 Set to non-nil to not show #if, #ifdef, #ifndef, #else, and
241 #endif lines when hiding.
243 `hide-ifdef-initially'
244 Indicates whether `hide-ifdefs' should be called when Hide-Ifdef mode
245 is activated.
247 `hide-ifdef-read-only'
248 Set to non-nil if you want to make buffers read only while hiding.
249 After `show-ifdefs', read-only status is restored to previous value.
251 \\{hide-ifdef-mode-map}"
252 :group 'hide-ifdef :lighter " Ifdef"
253 (if hide-ifdef-mode
254 (progn
255 ;; inherit global values
256 (set (make-local-variable 'hide-ifdef-env)
257 (default-value 'hide-ifdef-env))
258 (set (make-local-variable 'hide-ifdef-hiding)
259 (default-value 'hide-ifdef-hiding))
260 (set (make-local-variable 'hif-outside-read-only) buffer-read-only)
261 (set (make-local-variable 'line-move-ignore-invisible) t)
262 (add-hook 'change-major-mode-hook
263 (lambda () (hide-ifdef-mode -1)) nil t)
265 (add-to-invisibility-spec '(hide-ifdef . t))
267 (if hide-ifdef-initially
268 (hide-ifdefs)
269 (show-ifdefs)))
270 ;; else end hide-ifdef-mode
271 (kill-local-variable 'line-move-ignore-invisible)
272 (remove-from-invisibility-spec '(hide-ifdef . t))
273 (when hide-ifdef-hiding
274 (show-ifdefs))))
277 (defun hif-show-all ()
278 "Show all of the text in the current buffer."
279 (interactive)
280 (hif-show-ifdef-region (point-min) (point-max)))
282 ;; By putting this on after-revert-hook, we arrange that it only
283 ;; does anything when revert-buffer avoids turning off the mode.
284 ;; (That can happen in VC.)
285 (defun hif-after-revert-function ()
286 (and hide-ifdef-mode hide-ifdef-hiding
287 (hide-ifdefs t)))
288 (add-hook 'after-revert-hook 'hif-after-revert-function)
290 (defun hif-end-of-line ()
291 (end-of-line)
292 (while (= (logand 1 (skip-chars-backward "\\\\")) 1)
293 (end-of-line 2)))
295 (defun hide-ifdef-region-internal (start end)
296 (remove-overlays start end 'hide-ifdef t)
297 (let ((o (make-overlay start end)))
298 (overlay-put o 'hide-ifdef t)
299 (if hide-ifdef-shadow
300 (overlay-put o 'face 'hide-ifdef-shadow)
301 (overlay-put o 'invisible 'hide-ifdef))))
303 (defun hide-ifdef-region (start end)
304 "START is the start of a #if or #else form. END is the ending part.
305 Everything including these lines is made invisible."
306 (save-excursion
307 (goto-char start) (hif-end-of-line) (setq start (point))
308 (goto-char end) (hif-end-of-line) (setq end (point))
309 (hide-ifdef-region-internal start end)))
311 (defun hif-show-ifdef-region (start end)
312 "Everything between START and END is made visible."
313 (remove-overlays start end 'hide-ifdef t))
316 ;;===%%SF%% evaluation (Start) ===
318 ;; It is not useful to set this to anything but `eval'.
319 ;; In fact, the variable might as well be eliminated.
320 (defvar hide-ifdef-evaluator 'eval
321 "The function to use to evaluate a form.
322 The evaluator is given a canonical form and returns t if text under
323 that form should be displayed.")
325 (defvar hif-undefined-symbol nil
326 "...is by default considered to be false.")
329 (defun hif-set-var (var value)
330 "Prepend (var value) pair to hide-ifdef-env."
331 (setq hide-ifdef-env (cons (cons var value) hide-ifdef-env)))
333 (declare-function semantic-c-hideif-lookup "semantic/bovine/c" (var))
334 (declare-function semantic-c-hideif-defined "semantic/bovine/c" (var))
336 (defun hif-lookup (var)
337 (or (when (bound-and-true-p semantic-c-takeover-hideif)
338 (semantic-c-hideif-lookup var))
339 (let ((val (assoc var hide-ifdef-env)))
340 (if val
341 (cdr val)
342 hif-undefined-symbol))))
344 (defun hif-defined (var)
345 (cond
346 ((bound-and-true-p semantic-c-takeover-hideif)
347 (semantic-c-hideif-defined var))
348 ((assoc var hide-ifdef-env) 1)
349 (t 0)))
351 ;;===%%SF%% evaluation (End) ===
355 ;;===%%SF%% parsing (Start) ===
356 ;;; The code that understands what ifs and ifdef in files look like.
358 (defconst hif-cpp-prefix "\\(^\\|\r\\)[ \t]*#[ \t]*")
359 (defconst hif-ifndef-regexp (concat hif-cpp-prefix "ifndef"))
360 (defconst hif-ifx-regexp (concat hif-cpp-prefix "if\\(n?def\\)?[ \t]+"))
361 (defconst hif-else-regexp (concat hif-cpp-prefix "else"))
362 (defconst hif-endif-regexp (concat hif-cpp-prefix "endif"))
363 (defconst hif-ifx-else-endif-regexp
364 (concat hif-ifx-regexp "\\|" hif-else-regexp "\\|" hif-endif-regexp))
366 ;; Used to store the current token and the whole token list during parsing.
367 ;; Only bound dynamically.
368 (defvar hif-token)
369 (defvar hif-token-list)
371 (defconst hif-token-alist
372 '(("||" . hif-or)
373 ("&&" . hif-and)
374 ("|" . hif-logior)
375 ("^" . hif-logxor)
376 ("&" . hif-logand)
377 ("<<" . hif-shiftleft)
378 (">>" . hif-shiftright)
379 ("==" . hif-equal)
380 ;; Note: we include tokens like `=' which aren't supported by CPP's
381 ;; expression syntax, because they are still relevant for the tokenizer,
382 ;; especially in conjunction with ##.
383 ("=" . hif-assign)
384 ("!=" . hif-notequal)
385 ("##" . hif-token-concat)
386 ("!" . hif-not)
387 ("~" . hif-lognot)
388 ("(" . hif-lparen)
389 (")" . hif-rparen)
390 (">" . hif-greater)
391 ("<" . hif-less)
392 (">=" . hif-greater-equal)
393 ("<=" . hif-less-equal)
394 ("+" . hif-plus)
395 ("-" . hif-minus)
396 ("*" . hif-multiply)
397 ("/" . hif-divide)
398 ("%" . hif-modulo)
399 ("?" . hif-conditional)
400 (":" . hif-colon)))
402 (defconst hif-token-regexp
403 (concat (regexp-opt (mapcar 'car hif-token-alist))
404 "\\|0x[0-9a-fA-F]+\\.?[0-9a-fA-F]*"
405 "\\|[0-9]+\\.?[0-9]*" ;; decimal/octal
406 "\\|\\w+"))
408 (defconst hif-string-literal-regexp "\\(\"\\(?:[^\"\\]\\|\\\\.\\)*\"\\)")
411 (defun hif-tokenize (start end)
412 "Separate string between START and END into a list of tokens."
413 (let ((token-list nil))
414 (with-syntax-table hide-ifdef-syntax-table
415 (save-excursion
416 (goto-char start)
417 (while (progn (forward-comment (point-max)) (< (point) end))
418 ;; (message "expr-start = %d" expr-start) (sit-for 1)
419 (cond
420 ((looking-at "\\\\\n")
421 (forward-char 2))
423 ((looking-at hif-string-literal-regexp)
424 (push (substring-no-properties (match-string 1)) token-list)
425 (goto-char (match-end 0)))
426 ((looking-at hif-token-regexp)
427 (let ((token (buffer-substring (point) (match-end 0))))
428 (goto-char (match-end 0))
429 ;; (message "token: %s" token) (sit-for 1)
430 (push
431 (or (cdr (assoc token hif-token-alist))
432 (if (string-equal token "defined") 'hif-defined)
433 ;; TODO:
434 ;; 1. postfix 'l', 'll', 'ul' and 'ull'
435 ;; 2. floating number formats
436 ;; 3. hexadecimal/octal floats
437 ;; 4. 098 is interpreted as octal conversion error
438 ;; FIXME: string-to-number does not convert hex floats
439 (if (string-match "0x\\([0-9a-fA-F]+\\.?[0-9a-fA-F]*\\)"
440 token)
441 (string-to-number (match-string 1 token) 16)) ;; hex
442 ;; FIXME: string-to-number does not convert octal floats
443 (if (string-match "\\`0[0-9]+\\(\\.[0-9]+\\)?\\'" token)
444 (string-to-number token 8)) ;; octal
445 (if (string-match "\\`[1-9][0-9]*\\(\\.[0-9]+\\)?\\'"
446 token)
447 (string-to-number token)) ;; decimal
448 (intern token))
449 token-list)))
450 (t (error "Bad #if expression: %s" (buffer-string)))))))
451 (nreverse token-list)))
453 ;;------------------------------------------------------------------------
454 ;; Translate C preprocessor #if expressions using recursive descent.
455 ;; This parser was limited to the operators &&, ||, !, and "defined".
456 ;; Added ==, !=, +, and -. Gary Oberbrunner, garyo@avs.com, 8/9/94
458 ;; Implement the C language operator precedence table. Add all those
459 ;; missing operators that could be used in macros. Luke Lee 2013-09-04
461 ;; | Operator Type | Operator | Associativity |
462 ;; +----------------------+-----------------------------+---------------+
463 ;; | Primary Expression | () [] . -> expr++ expr-- | left-to-right |
464 ;; | Unary Operators | * & + - ! ~ ++expr --expr | right-to-left |
465 ;; | | (typecast) sizeof | |
466 ;; | Binary Operators | * / % | left-to-right |
467 ;; | | + - | |
468 ;; | | >> << | |
469 ;; | | < > <= >= | |
470 ;; | | == != | |
471 ;; | | & | |
472 ;; | | ^ | |
473 ;; | | | | |
474 ;; | | && | |
475 ;; | | || | |
476 ;; | Ternary Operator | ?: | right-to-left |
477 ;; x| Assignment Operators | = += -= *= /= %= >>= <<= &= | right-to-left |
478 ;; | | ^= = | |
479 ;; | Comma | , | left-to-right |
481 (defsubst hif-nexttoken ()
482 "Pop the next token from token-list into the let variable \"hif-token\"."
483 (setq hif-token (pop hif-token-list)))
485 (defun hif-parse-if-exp (token-list)
486 "Parse the TOKEN-LIST. Return translated list in prefix form."
487 (let ((hif-token-list token-list))
488 (hif-nexttoken)
489 (prog1
490 (and hif-token
491 (hif-exprlist))
492 (if hif-token ; is there still a token?
493 (error "Error: unexpected token: %s" hif-token)))))
495 (defun hif-exprlist ()
496 "Parse an exprlist: expr { ',' expr}"
497 (let ((result (hif-expr)))
498 (if (eq hif-token 'hif-comma)
499 (let ((temp (list result)))
500 (while
501 (progn
502 (hif-nexttoken)
503 (push (hif-expr) temp)
504 (eq hif-token 'hif-comma)))
505 (cons 'hif-comma (nreverse temp)))
506 result)))
508 (defun hif-expr ()
509 "Parse an expression as found in #if.
510 expr : or-expr | or-expr '?' expr ':' expr."
511 (let ((result (hif-or-expr))
512 middle)
513 (while (eq hif-token 'hif-conditional)
514 (hif-nexttoken)
515 (setq middle (hif-expr))
516 (if (eq hif-token 'hif-colon)
517 (progn
518 (hif-nexttoken)
519 (setq result (list 'hif-conditional result middle (hif-expr))))
520 (error "Error: unexpected token: %s" hif-token)))
521 result))
523 (defun hif-or-expr ()
524 "Parse an or-expr : and-expr | or-expr '||' and-expr."
525 (let ((result (hif-and-expr)))
526 (while (eq hif-token 'hif-or)
527 (hif-nexttoken)
528 (setq result (list 'hif-or result (hif-and-expr))))
529 result))
531 (defun hif-and-expr ()
532 "Parse an and-expr : logior-expr | and-expr '&&' logior-expr."
533 (let ((result (hif-logior-expr)))
534 (while (eq hif-token 'hif-and)
535 (hif-nexttoken)
536 (setq result (list 'hif-and result (hif-logior-expr))))
537 result))
539 (defun hif-logior-expr ()
540 "Parse a logor-expr : logxor-expr | logor-expr '|' logxor-expr."
541 (let ((result (hif-logxor-expr)))
542 (while (eq hif-token 'hif-logior)
543 (hif-nexttoken)
544 (setq result (list 'hif-logior result (hif-logxor-expr))))
545 result))
547 (defun hif-logxor-expr ()
548 "Parse a logxor-expr : logand-expr | logxor-expr '^' logand-expr."
549 (let ((result (hif-logand-expr)))
550 (while (eq hif-token 'hif-logxor)
551 (hif-nexttoken)
552 (setq result (list 'hif-logxor result (hif-logand-expr))))
553 result))
555 (defun hif-logand-expr ()
556 "Parse a logand-expr : eq-expr | logand-expr '&' eq-expr."
557 (let ((result (hif-eq-expr)))
558 (while (eq hif-token 'hif-logand)
559 (hif-nexttoken)
560 (setq result (list 'hif-logand result (hif-eq-expr))))
561 result))
563 (defun hif-eq-expr ()
564 "Parse an eq-expr : comp | eq-expr `=='|`!=' comp."
565 (let ((result (hif-comp-expr))
566 (eq-token nil))
567 (while (memq hif-token '(hif-equal hif-notequal))
568 (setq eq-token hif-token)
569 (hif-nexttoken)
570 (setq result (list eq-token result (hif-comp-expr))))
571 result))
573 (defun hif-comp-expr ()
574 "Parse a comp-expr : logshift | comp-expr `<'|`>'|`>='|`<=' logshift."
575 (let ((result (hif-logshift-expr))
576 (comp-token nil))
577 (while (memq hif-token '(hif-greater hif-less hif-greater-equal hif-less-equal))
578 (setq comp-token hif-token)
579 (hif-nexttoken)
580 (setq result (list comp-token result (hif-logshift-expr))))
581 result))
583 (defun hif-logshift-expr ()
584 "Parse a logshift : math | logshift `<<'|`>>' math."
585 (let ((result (hif-math))
586 (shift-token nil))
587 (while (memq hif-token '(hif-shiftleft hif-shiftright))
588 (setq shift-token hif-token)
589 (hif-nexttoken)
590 (setq result (list shift-token result (hif-math))))
591 result))
593 (defun hif-math ()
594 "Parse an expression with + or -.
595 math : muldiv | math '+|-' muldiv."
596 (let ((result (hif-muldiv-expr))
597 (math-op nil))
598 (while (memq hif-token '(hif-plus hif-minus))
599 (setq math-op hif-token)
600 (hif-nexttoken)
601 (setq result (list math-op result (hif-muldiv-expr))))
602 result))
604 (defun hif-muldiv-expr ()
605 "Parse an expression with *,/,%.
606 muldiv : factor | muldiv '*|/|%' factor."
607 (let ((result (hif-factor))
608 (math-op nil))
609 (while (memq hif-token '(hif-multiply hif-divide hif-modulo))
610 (setq math-op hif-token)
611 (hif-nexttoken)
612 (setq result (list math-op result (hif-factor))))
613 result))
615 (defun hif-factor ()
616 "Parse a factor: '!' factor | '~' factor | '(' expr ')' | 'defined(' id ')' | 'id(parmlist)' | strings | id."
617 (cond
618 ((eq hif-token 'hif-not)
619 (hif-nexttoken)
620 (list 'hif-not (hif-factor)))
622 ((eq hif-token 'hif-lognot)
623 (hif-nexttoken)
624 (list 'hif-lognot (hif-factor)))
626 ((eq hif-token 'hif-lparen)
627 (hif-nexttoken)
628 (let ((result (hif-exprlist)))
629 (if (not (eq hif-token 'hif-rparen))
630 (error "Bad token in parenthesized expression: %s" hif-token)
631 (hif-nexttoken)
632 result)))
634 ((eq hif-token 'hif-defined)
635 (hif-nexttoken)
636 (let ((paren (when (eq hif-token 'hif-lparen) (hif-nexttoken) t))
637 (ident hif-token))
638 (if (memq hif-token '(or and not hif-defined hif-lparen hif-rparen))
639 (error "Error: unexpected token: %s" hif-token))
640 (when paren
641 (hif-nexttoken)
642 (unless (eq hif-token 'hif-rparen)
643 (error "Error: expected \")\" after identifier")))
644 (hif-nexttoken)
645 `(hif-defined (quote ,ident))))
647 ((numberp hif-token)
648 (prog1 hif-token (hif-nexttoken)))
650 ;; Unary plus/minus.
651 ((memq hif-token '(hif-minus hif-plus))
652 (list (prog1 hif-token (hif-nexttoken)) 0 (hif-factor)))
654 (t ; identifier
655 (let ((ident hif-token))
656 (if (memq ident '(or and))
657 (error "Error: missing identifier"))
658 (hif-nexttoken)
659 `(hif-lookup (quote ,ident))))))
661 (defun hif-mathify (val)
662 "Treat VAL as a number: if it's t or nil, use 1 or 0."
663 (cond ((eq val t) 1)
664 ((null val) 0)
665 (t val)))
667 (defun hif-conditional (a b c)
668 (if (not (zerop (hif-mathify a))) (hif-mathify b) (hif-mathify c)))
669 (defun hif-and (a b)
670 (and (not (zerop (hif-mathify a))) (not (zerop (hif-mathify b)))))
671 (defun hif-or (a b)
672 (or (not (zerop (hif-mathify a))) (not (zerop (hif-mathify b)))))
673 (defun hif-not (a)
674 (zerop (hif-mathify a)))
675 (defun hif-lognot (a)
676 (lognot (hif-mathify a)))
678 (defmacro hif-mathify-binop (fun)
679 `(lambda (a b)
680 ,(format "Like `%s' but treat t and nil as 1 and 0." fun)
681 (,fun (hif-mathify a) (hif-mathify b))))
683 (defun hif-shiftleft (a b)
684 (setq a (hif-mathify a))
685 (setq b (hif-mathify b))
686 (if (< a 0)
687 (ash a b)
688 (lsh a b)))
690 (defun hif-shiftright (a b)
691 (setq a (hif-mathify a))
692 (setq b (hif-mathify b))
693 (if (< a 0)
694 (ash a (- b))
695 (lsh a (- b))))
698 (defalias 'hif-multiply (hif-mathify-binop *))
699 (defalias 'hif-divide (hif-mathify-binop /))
700 (defalias 'hif-modulo (hif-mathify-binop %))
701 (defalias 'hif-plus (hif-mathify-binop +))
702 (defalias 'hif-minus (hif-mathify-binop -))
703 (defalias 'hif-equal (hif-mathify-binop =))
704 (defalias 'hif-notequal (hif-mathify-binop /=))
705 (defalias 'hif-greater (hif-mathify-binop >))
706 (defalias 'hif-less (hif-mathify-binop <))
707 (defalias 'hif-greater-equal (hif-mathify-binop >=))
708 (defalias 'hif-less-equal (hif-mathify-binop <=))
709 (defalias 'hif-logior (hif-mathify-binop logior))
710 (defalias 'hif-logxor (hif-mathify-binop logxor))
711 (defalias 'hif-logand (hif-mathify-binop logand))
714 (defun hif-comma (&rest expr)
715 "Evaluate a list of expr, return the result of the last item"
716 (let ((result nil))
717 (dolist (e expr)
718 (ignore-errors
719 (setq result (funcall hide-ifdef-evaluator e))))
720 result))
723 ;;;----------- end of parser -----------------------
726 (defun hif-canonicalize ()
727 "When at beginning of #ifX, return a Lisp expression for its condition."
728 (save-excursion
729 (let ((negate (looking-at hif-ifndef-regexp)))
730 (re-search-forward hif-ifx-regexp)
731 (let* ((tokens (hif-tokenize (point)
732 (progn (hif-end-of-line) (point))))
733 (expr (hif-parse-if-exp tokens)))
734 ;; (message "hif-canonicalized: %s" expr)
735 (if negate
736 (list 'hif-not expr)
737 expr)))))
740 (defun hif-find-any-ifX ()
741 "Move to next #if..., or #ifndef, at point or after."
742 ;; (message "find ifX at %d" (point))
743 (prog1
744 (re-search-forward hif-ifx-regexp (point-max) t)
745 (beginning-of-line)))
748 (defun hif-find-next-relevant ()
749 "Move to next #if..., #else, or #endif, after the current line."
750 ;; (message "hif-find-next-relevant at %d" (point))
751 (end-of-line)
752 ;; avoid infinite recursion by only going to beginning of line if match found
753 (if (re-search-forward hif-ifx-else-endif-regexp (point-max) t)
754 (beginning-of-line)))
756 (defun hif-find-previous-relevant ()
757 "Move to previous #if..., #else, or #endif, before the current line."
758 ;; (message "hif-find-previous-relevant at %d" (point))
759 (beginning-of-line)
760 ;; avoid infinite recursion by only going to beginning of line if match found
761 (if (re-search-backward hif-ifx-else-endif-regexp (point-min) t)
762 (beginning-of-line)))
765 (defun hif-looking-at-ifX () ;; Should eventually see #if
766 (looking-at hif-ifx-regexp))
767 (defun hif-looking-at-endif ()
768 (looking-at hif-endif-regexp))
769 (defun hif-looking-at-else ()
770 (looking-at hif-else-regexp))
774 (defun hif-ifdef-to-endif ()
775 "If positioned at #ifX or #else form, skip to corresponding #endif."
776 ;; (message "hif-ifdef-to-endif at %d" (point)) (sit-for 1)
777 (hif-find-next-relevant)
778 (cond ((hif-looking-at-ifX)
779 (hif-ifdef-to-endif) ; find endif of nested if
780 (hif-ifdef-to-endif)) ; find outer endif or else
781 ((hif-looking-at-else)
782 (hif-ifdef-to-endif)) ; find endif following else
783 ((hif-looking-at-endif)
784 'done)
786 (error "Mismatched #ifdef #endif pair"))))
789 (defun hif-endif-to-ifdef ()
790 "If positioned at #endif form, skip backward to corresponding #ifX."
791 ;; (message "hif-endif-to-ifdef at %d" (point))
792 (let ((start (point)))
793 (hif-find-previous-relevant)
794 (if (= start (point))
795 (error "Mismatched #ifdef #endif pair")))
796 (cond ((hif-looking-at-endif)
797 (hif-endif-to-ifdef) ; find beginning of nested if
798 (hif-endif-to-ifdef)) ; find beginning of outer if or else
799 ((hif-looking-at-else)
800 (hif-endif-to-ifdef))
801 ((hif-looking-at-ifX)
802 'done)
803 (t))) ; never gets here
806 (defun forward-ifdef (&optional arg)
807 "Move point to beginning of line of the next ifdef-endif.
808 With argument, do this that many times."
809 (interactive "p")
810 (or arg (setq arg 1))
811 (if (< arg 0) (backward-ifdef (- arg))
812 (while (< 0 arg)
813 (setq arg (- arg))
814 (let ((start (point)))
815 (unless (hif-looking-at-ifX)
816 (hif-find-next-relevant))
817 (if (hif-looking-at-ifX)
818 (hif-ifdef-to-endif)
819 (goto-char start)
820 (error "No following #ifdef"))))))
823 (defun backward-ifdef (&optional arg)
824 "Move point to beginning of the previous ifdef-endif.
825 With argument, do this that many times."
826 (interactive "p")
827 (or arg (setq arg 1))
828 (if (< arg 0) (forward-ifdef (- arg))
829 (while (< 0 arg)
830 (setq arg (1- arg))
831 (beginning-of-line)
832 (let ((start (point)))
833 (unless (hif-looking-at-endif)
834 (hif-find-previous-relevant))
835 (if (hif-looking-at-endif)
836 (hif-endif-to-ifdef)
837 (goto-char start)
838 (error "No previous #ifdef"))))))
841 (defun down-ifdef ()
842 "Move point to beginning of nested ifdef or else-part."
843 (interactive)
844 (let ((start (point)))
845 (hif-find-next-relevant)
846 (if (or (hif-looking-at-ifX) (hif-looking-at-else))
848 (goto-char start)
849 (error "No following #ifdef"))))
852 (defun up-ifdef ()
853 "Move point to beginning of enclosing ifdef or else-part."
854 (interactive)
855 (beginning-of-line)
856 (let ((start (point)))
857 (unless (hif-looking-at-endif)
858 (hif-find-previous-relevant))
859 (if (hif-looking-at-endif)
860 (hif-endif-to-ifdef))
861 (if (= start (point))
862 (error "No previous #ifdef"))))
864 (defun next-ifdef (&optional arg)
865 "Move to the beginning of the next #ifX, #else, or #endif.
866 With argument, do this that many times."
867 (interactive "p")
868 (or arg (setq arg 1))
869 (if (< arg 0) (previous-ifdef (- arg))
870 (while (< 0 arg)
871 (setq arg (1- arg))
872 (hif-find-next-relevant)
873 (when (eolp)
874 (beginning-of-line)
875 (error "No following #ifdefs, #elses, or #endifs")))))
877 (defun previous-ifdef (&optional arg)
878 "Move to the beginning of the previous #ifX, #else, or #endif.
879 With argument, do this that many times."
880 (interactive "p")
881 (or arg (setq arg 1))
882 (if (< arg 0) (next-ifdef (- arg))
883 (while (< 0 arg)
884 (setq arg (1- arg))
885 (let ((start (point)))
886 (hif-find-previous-relevant)
887 (if (= start (point))
888 (error "No previous #ifdefs, #elses, or #endifs"))))))
891 ;;===%%SF%% parsing (End) ===
894 ;;===%%SF%% hide-ifdef-hiding (Start) ===
897 ;;; A range is a structure with four components:
898 ;;; ELSE-P True if there was an else clause for the ifdef.
899 ;;; START The start of the range. (beginning of line)
900 ;;; ELSE The else marker (beginning of line)
901 ;;; Only valid if ELSE-P is true.
902 ;;; END The end of the range. (beginning of line)
904 (defsubst hif-make-range (start end &optional else)
905 (list start else end))
907 (defsubst hif-range-start (range) (elt range 0))
908 (defsubst hif-range-else (range) (elt range 1))
909 (defsubst hif-range-end (range) (elt range 2))
913 ;;; Find-Range
914 ;;; The workhorse, it delimits the #if region. Reasonably simple:
915 ;;; Skip until an #else or #endif is found, remembering positions. If
916 ;;; an #else was found, skip some more, looking for the true #endif.
918 (defun hif-find-range ()
919 "Return a Range structure describing the current #if region.
920 Point is left unchanged."
921 ;; (message "hif-find-range at %d" (point))
922 (save-excursion
923 (beginning-of-line)
924 (let ((start (point))
925 (else nil)
926 (end nil))
927 ;; Part one. Look for either #endif or #else.
928 ;; This loop-and-a-half dedicated to E. Dijkstra.
929 (while (progn
930 (hif-find-next-relevant)
931 (hif-looking-at-ifX)) ; Skip nested ifdef
932 (hif-ifdef-to-endif))
933 ;; Found either a #else or an #endif.
934 (cond ((hif-looking-at-else)
935 (setq else (point)))
937 (setq end (point)))) ; (line-end-position)
938 ;; If found #else, look for #endif.
939 (when else
940 (while (progn
941 (hif-find-next-relevant)
942 (hif-looking-at-ifX)) ; Skip nested ifdef
943 (hif-ifdef-to-endif))
944 (if (hif-looking-at-else)
945 (error "Found two elses in a row? Broken!"))
946 (setq end (point))) ; (line-end-position)
947 (hif-make-range start end else))))
950 ;;; A bit slimy.
952 (defun hif-hide-line (point)
953 "Hide the line containing point. Does nothing if `hide-ifdef-lines' is nil."
954 (when hide-ifdef-lines
955 (save-excursion
956 (goto-char point)
957 (hide-ifdef-region-internal
958 (line-beginning-position) (progn (hif-end-of-line) (point))))))
961 ;;; Hif-Possibly-Hide
962 ;;; There are four cases. The #ifX expression is "taken" if it
963 ;;; the hide-ifdef-evaluator returns T. Presumably, this means the code
964 ;;; inside the #ifdef would be included when the program was
965 ;;; compiled.
967 ;;; Case 1: #ifX taken, and there's an #else.
968 ;;; The #else part must be hidden. The #if (then) part must be
969 ;;; processed for nested #ifX's.
970 ;;; Case 2: #ifX taken, and there's no #else.
971 ;;; The #if part must be processed for nested #ifX's.
972 ;;; Case 3: #ifX not taken, and there's an #else.
973 ;;; The #if part must be hidden. The #else part must be processed
974 ;;; for nested #ifs.
975 ;;; Case 4: #ifX not taken, and there's no #else.
976 ;;; The #ifX part must be hidden.
978 ;;; Further processing is done by narrowing to the relevant region
979 ;;; and just recursively calling hide-ifdef-guts.
981 ;;; When hif-possibly-hide returns, point is at the end of the
982 ;;; possibly-hidden range.
984 (defun hif-recurse-on (start end)
985 "Call `hide-ifdef-guts' after narrowing to end of START line and END line."
986 (save-excursion
987 (save-restriction
988 (goto-char start)
989 (end-of-line)
990 (narrow-to-region (point) end)
991 (hide-ifdef-guts))))
993 (defun hif-possibly-hide ()
994 "Called at #ifX expression, this hides those parts that should be hidden.
995 It uses the judgment of `hide-ifdef-evaluator'."
996 ;; (message "hif-possibly-hide") (sit-for 1)
997 (let ((test (hif-canonicalize))
998 (range (hif-find-range)))
999 ;; (message "test = %s" test) (sit-for 1)
1001 (hif-hide-line (hif-range-end range))
1002 (if (not (hif-not (funcall hide-ifdef-evaluator test)))
1003 (cond ((hif-range-else range) ; case 1
1004 (hif-hide-line (hif-range-else range))
1005 (hide-ifdef-region (hif-range-else range)
1006 (1- (hif-range-end range)))
1007 (hif-recurse-on (hif-range-start range)
1008 (hif-range-else range)))
1009 (t ; case 2
1010 (hif-recurse-on (hif-range-start range)
1011 (hif-range-end range))))
1012 (cond ((hif-range-else range) ; case 3
1013 (hif-hide-line (hif-range-else range))
1014 (hide-ifdef-region (hif-range-start range)
1015 (1- (hif-range-else range)))
1016 (hif-recurse-on (hif-range-else range)
1017 (hif-range-end range)))
1018 (t ; case 4
1019 (hide-ifdef-region (point)
1020 (1- (hif-range-end range))))))
1021 (hif-hide-line (hif-range-start range)) ; Always hide start.
1022 (goto-char (hif-range-end range))
1023 (end-of-line)))
1027 (defun hide-ifdef-guts ()
1028 "Does most of the work of `hide-ifdefs'.
1029 It does not do the work that's pointless to redo on a recursive entry."
1030 ;; (message "hide-ifdef-guts")
1031 (save-excursion
1032 (goto-char (point-min))
1033 (while (hif-find-any-ifX)
1034 (hif-possibly-hide))))
1036 ;;===%%SF%% hide-ifdef-hiding (End) ===
1039 ;;===%%SF%% exports (Start) ===
1041 (defun hide-ifdef-toggle-read-only ()
1042 "Toggle `hide-ifdef-read-only'."
1043 (interactive)
1044 (setq hide-ifdef-read-only (not hide-ifdef-read-only))
1045 (message "Hide-Read-Only %s"
1046 (if hide-ifdef-read-only "ON" "OFF"))
1047 (if hide-ifdef-hiding
1048 (setq buffer-read-only (or hide-ifdef-read-only hif-outside-read-only)))
1049 (force-mode-line-update))
1051 (defun hide-ifdef-toggle-outside-read-only ()
1052 "Replacement for `toggle-read-only' within Hide-Ifdef mode."
1053 (interactive)
1054 (setq hif-outside-read-only (not hif-outside-read-only))
1055 (message "Read only %s"
1056 (if hif-outside-read-only "ON" "OFF"))
1057 (setq buffer-read-only
1058 (or (and hide-ifdef-hiding hide-ifdef-read-only)
1059 hif-outside-read-only))
1060 (force-mode-line-update))
1062 (defun hide-ifdef-toggle-shadowing ()
1063 "Toggle shadowing."
1064 (interactive)
1065 (set (make-local-variable 'hide-ifdef-shadow) (not hide-ifdef-shadow))
1066 (message "Shadowing %s" (if hide-ifdef-shadow "ON" "OFF"))
1067 (save-restriction
1068 (widen)
1069 (dolist (overlay (overlays-in (point-min) (point-max)))
1070 (when (overlay-get overlay 'hide-ifdef)
1071 (if hide-ifdef-shadow
1072 (progn
1073 (overlay-put overlay 'invisible nil)
1074 (overlay-put overlay 'face 'hide-ifdef-shadow))
1075 (overlay-put overlay 'face nil)
1076 (overlay-put overlay 'invisible 'hide-ifdef))))))
1078 (defun hide-ifdef-define (var)
1079 "Define a VAR so that #ifdef VAR would be included."
1080 (interactive "SDefine what? ")
1081 (hif-set-var var 1)
1082 (if hide-ifdef-hiding (hide-ifdefs)))
1084 (defun hide-ifdef-undef (var)
1085 "Undefine a VAR so that #ifdef VAR would not be included."
1086 (interactive "SUndefine what? ")
1087 (hif-set-var var nil)
1088 (if hide-ifdef-hiding (hide-ifdefs)))
1091 (defun hide-ifdefs (&optional nomsg)
1092 "Hide the contents of some #ifdefs.
1093 Assume that defined symbols have been added to `hide-ifdef-env'.
1094 The text hidden is the text that would not be included by the C
1095 preprocessor if it were given the file with those symbols defined.
1097 Turn off hiding by calling `show-ifdefs'."
1099 (interactive)
1100 (message "Hiding...")
1101 (setq hif-outside-read-only buffer-read-only)
1102 (unless hide-ifdef-mode (hide-ifdef-mode 1)) ; turn on hide-ifdef-mode
1103 (if hide-ifdef-hiding
1104 (show-ifdefs)) ; Otherwise, deep confusion.
1105 (setq hide-ifdef-hiding t)
1106 (hide-ifdef-guts)
1107 (setq buffer-read-only (or hide-ifdef-read-only hif-outside-read-only))
1108 (or nomsg
1109 (message "Hiding done")))
1112 (defun show-ifdefs ()
1113 "Cancel the effects of `hide-ifdef': show the contents of all #ifdefs."
1114 (interactive)
1115 (setq buffer-read-only hif-outside-read-only)
1116 (hif-show-all)
1117 (setq hide-ifdef-hiding nil))
1120 (defun hif-find-ifdef-block ()
1121 "Utility for hide and show `ifdef-block'.
1122 Return as (TOP . BOTTOM) the extent of ifdef block."
1123 (let (max-bottom)
1124 (cons (save-excursion
1125 (beginning-of-line)
1126 (unless (or (hif-looking-at-else) (hif-looking-at-ifX))
1127 (up-ifdef))
1128 (prog1 (point)
1129 (hif-ifdef-to-endif)
1130 (setq max-bottom (1- (point)))))
1131 (save-excursion
1132 (beginning-of-line)
1133 (unless (hif-looking-at-endif)
1134 (hif-find-next-relevant))
1135 (while (hif-looking-at-ifX)
1136 (hif-ifdef-to-endif)
1137 (hif-find-next-relevant))
1138 (min max-bottom (1- (point)))))))
1141 (defun hide-ifdef-block ()
1142 "Hide the ifdef block (true or false part) enclosing or before the cursor."
1143 (interactive)
1144 (unless hide-ifdef-mode (hide-ifdef-mode 1))
1145 (let ((top-bottom (hif-find-ifdef-block)))
1146 (hide-ifdef-region (car top-bottom) (cdr top-bottom))
1147 (when hide-ifdef-lines
1148 (hif-hide-line (car top-bottom))
1149 (hif-hide-line (1+ (cdr top-bottom))))
1150 (setq hide-ifdef-hiding t))
1151 (setq buffer-read-only (or hide-ifdef-read-only hif-outside-read-only)))
1153 (defun show-ifdef-block ()
1154 "Show the ifdef block (true or false part) enclosing or before the cursor."
1155 (interactive)
1156 (let ((top-bottom (hif-find-ifdef-block)))
1157 (if hide-ifdef-lines
1158 (hif-show-ifdef-region
1159 (save-excursion
1160 (goto-char (car top-bottom)) (line-beginning-position))
1161 (save-excursion
1162 (goto-char (1+ (cdr top-bottom)))
1163 (hif-end-of-line) (point)))
1164 (hif-show-ifdef-region (1- (car top-bottom)) (cdr top-bottom)))))
1167 ;;; definition alist support
1169 (defvar hide-ifdef-define-alist nil
1170 "A global assoc list of pre-defined symbol lists.")
1172 (defun hif-compress-define-list (env)
1173 "Compress the define list ENV into a list of defined symbols only."
1174 (let ((new-defs nil))
1175 (dolist (def env new-defs)
1176 (if (hif-lookup (car def)) (push (car def) new-defs)))))
1178 (defun hide-ifdef-set-define-alist (name)
1179 "Set the association for NAME to `hide-ifdef-env'."
1180 (interactive "SSet define list: ")
1181 (push (cons name (hif-compress-define-list hide-ifdef-env))
1182 hide-ifdef-define-alist))
1184 (defun hide-ifdef-use-define-alist (name)
1185 "Set `hide-ifdef-env' to the define list specified by NAME."
1186 (interactive
1187 (list (completing-read "Use define list: "
1188 (mapcar (lambda (x) (symbol-name (car x)))
1189 hide-ifdef-define-alist)
1190 nil t)))
1191 (if (stringp name) (setq name (intern name)))
1192 (let ((define-list (assoc name hide-ifdef-define-alist)))
1193 (if define-list
1194 (setq hide-ifdef-env
1195 (mapcar (lambda (arg) (cons arg t))
1196 (cdr define-list)))
1197 (error "No define list for %s" name))
1198 (if hide-ifdef-hiding (hide-ifdefs))))
1200 (provide 'hideif)
1202 ;;; hideif.el ends here