cpp.el 28.3 KB
Newer Older
1
;;; cpp.el --- highlight or hide text according to cpp conditionals
Richard M. Stallman's avatar
Richard M. Stallman committed
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1994-1995, 2001-2016 Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4

Per Abrahamsen's avatar
Per Abrahamsen committed
5
;; Author: Per Abrahamsen <abraham@dina.kvl.dk>
Richard M. Stallman's avatar
Richard M. Stallman committed
6 7
;; Keywords: c, faces, tools

8
;; This file is part of GNU Emacs.
Richard M. Stallman's avatar
Richard M. Stallman committed
9

10
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
11
;; it under the terms of the GNU General Public License as published by
12 13
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
14 15

;; GNU Emacs is distributed in the hope that it will be useful,
Richard M. Stallman's avatar
Richard M. Stallman committed
16 17 18
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
19

Richard M. Stallman's avatar
Richard M. Stallman committed
20
;; You should have received a copy of the GNU General Public License
21
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Richard M. Stallman's avatar
Richard M. Stallman committed
22

23
;;; Commentary:
Richard M. Stallman's avatar
Richard M. Stallman committed
24 25 26 27

;; Parse a text for C preprocessor conditionals, and highlight or hide
;; the text inside the conditionals as you wish.

28
;; This package is inspired by Jim Coplien's delta editor for SCCS.
Richard M. Stallman's avatar
Richard M. Stallman committed
29 30 31 32

;;; Todo:

;; Should parse "#if" and "#elif" expressions and merge the faces
33
;; somehow.
Richard M. Stallman's avatar
Richard M. Stallman committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47

;; Somehow it is sometimes possible to make changes near a read only
;; area which you can't undo.  Their are other strange effects in that
;; area.

;; The Edit buffer should -- optionally -- appear in its own frame.

;; Conditionals seem to be rear-sticky.  They shouldn't be.

;; Restore window configurations when exiting CPP Edit buffer.

;;; Code:

;;; Customization:
Richard M. Stallman's avatar
Richard M. Stallman committed
48 49
(defgroup cpp nil
  "Highlight or hide text according to cpp conditionals."
50
  :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
51
  :group 'c
Richard M. Stallman's avatar
Richard M. Stallman committed
52 53 54
  :prefix "cpp-")

(defcustom cpp-config-file (convert-standard-filename ".cpp.el")
55
  "File name to save cpp configuration."
Richard M. Stallman's avatar
Richard M. Stallman committed
56 57 58
  :type 'file
  :group 'cpp)

Juri Linkov's avatar
Juri Linkov committed
59
(define-widget 'cpp-face 'lazy
60
  "Either a face or the special symbol `invisible'."
Juri Linkov's avatar
Juri Linkov committed
61 62
  :type '(choice (const invisible) (face)))

Richard M. Stallman's avatar
Richard M. Stallman committed
63
(defcustom cpp-known-face 'invisible
64
  "Face used for known cpp symbols."
Juri Linkov's avatar
Juri Linkov committed
65
  :type 'cpp-face
Richard M. Stallman's avatar
Richard M. Stallman committed
66 67 68
  :group 'cpp)

(defcustom cpp-unknown-face 'highlight
69
  "Face used for unknown cpp symbols."
Juri Linkov's avatar
Juri Linkov committed
70
  :type 'cpp-face
Richard M. Stallman's avatar
Richard M. Stallman committed
71 72
  :group 'cpp)

73
(defcustom cpp-face-type 'light
74
  "Indicate what background face type you prefer.
Richard M. Stallman's avatar
Richard M. Stallman committed
75
Can be either light or dark for color screens, mono for monochrome
76 77
screens, and none if you don't use a window system and don't have
a color-capable display."
Richard M. Stallman's avatar
Richard M. Stallman committed
78 79 80 81 82
  :options '(light dark mono nil)
  :type 'symbol
  :group 'cpp)

(defcustom cpp-known-writable t
83
  "Non-nil means you are allowed to modify the known conditionals."
Richard M. Stallman's avatar
Richard M. Stallman committed
84 85 86 87
  :type 'boolean
  :group 'cpp)

(defcustom cpp-unknown-writable t
88
  "Non-nil means you are allowed to modify the unknown conditionals."
Richard M. Stallman's avatar
Richard M. Stallman committed
89 90 91 92
  :type 'boolean
  :group 'cpp)

(defcustom cpp-edit-list nil
93 94 95 96 97
  "Alist of cpp macros and information about how they should be displayed.
Each entry is a list with the following elements:
0. The name of the macro (a string).
1. Face used for text that is `ifdef' the macro.
2. Face used for text that is `ifndef' the macro.
98
3. t, nil, or `both' depending on what text may be edited."
Juri Linkov's avatar
Juri Linkov committed
99 100 101 102
  :type '(repeat (list (string :tag "Macro")
		       (cpp-face :tag "True")
		       (cpp-face :tag "False")
		       (choice (const :tag "True branch writable" t)
Chong Yidong's avatar
Chong Yidong committed
103 104
			       (const :tag "False branch writable" nil)
			       (const :tag "Both branches writable" both))))
Richard M. Stallman's avatar
Richard M. Stallman committed
105
  :group 'cpp)
106

107 108 109
(defcustom cpp-message-min-time-interval 1.0
  "Minimum time interval in seconds for `cpp-progress-message' messages.
If nil, `cpp-progress-message' prints no progress messages."
Eli Zaretskii's avatar
Eli Zaretskii committed
110 111
  :type '(choice (const :tag "Disable progress messages" nil)
                 float)
112 113 114
  :group 'cpp
  :version "26.1")

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
(defvar cpp-overlay-list nil)
;; List of cpp overlays active in the current buffer.
(make-variable-buffer-local 'cpp-overlay-list)

(defvar cpp-callback-data)
(defvar cpp-state-stack)

(defconst cpp-face-type-list
  '(("light color background" . light)
    ("dark color background" . dark)
    ("monochrome" . mono)
    ("tty" . none))
  "Alist of strings and names of the defined face collections.")

(defconst cpp-writable-list
  ;; Names used for the writable property.
  '(("writable" . t)
    ("read-only" . nil)))

(defvar cpp-button-event nil)
;; This will be t in the callback for `cpp-make-button'.

(defvar cpp-edit-buffer nil)
;; Real buffer whose cpp display information we are editing.
(make-variable-buffer-local 'cpp-edit-buffer)

(defconst cpp-branch-list
  ;; Alist of branches.
  '(("false" . nil)
    ("true" . t)
    ("both" . both)))

147
;; FIXME Gets clobbered by cpp-choose-face, so why is even it a defcustom?
Richard M. Stallman's avatar
Richard M. Stallman committed
148
(defcustom cpp-face-default-list nil
149 150 151 152 153
  "Alist of faces you can choose from for cpp conditionals.
Each element has the form (STRING . FACE), where STRING
serves as a name (for `cpp-highlight-buffer' only)
and FACE is either a face (a symbol)
or a cons cell (background-color . COLOR)."
154 155 156 157 158
  :type '(alist :key-type (string :tag "Name")
		:value-type (choice face
				    (const invisible)
				    (cons (const background-color)
					  (string :tag "Color"))))
Richard M. Stallman's avatar
Richard M. Stallman committed
159
  :group 'cpp)
160

Richard M. Stallman's avatar
Richard M. Stallman committed
161
(defcustom cpp-face-light-name-list
162 163 164
  '("light gray" "light blue" "light cyan" "light yellow" "light pink"
    "pale green" "beige" "orange" "magenta" "violet" "medium purple"
    "turquoise")
165
  "Background colors useful with dark foreground colors."
Richard M. Stallman's avatar
Richard M. Stallman committed
166 167
  :type '(repeat string)
  :group 'cpp)
168

Richard M. Stallman's avatar
Richard M. Stallman committed
169
(defcustom cpp-face-dark-name-list
170 171 172
  '("dim gray" "blue" "cyan" "yellow" "red"
    "dark green" "brown" "dark orange" "dark khaki" "dark violet" "purple"
    "dark turquoise")
173
  "Background colors useful with light foreground colors."
Richard M. Stallman's avatar
Richard M. Stallman committed
174 175 176 177 178
  :type '(repeat string)
  :group 'cpp)

(defcustom cpp-face-light-list nil
  "Alist of names and faces to be used for light backgrounds."
179 180
  :type '(repeat (cons string (choice face
				      (cons (const background-color) string))))
Richard M. Stallman's avatar
Richard M. Stallman committed
181 182 183 184
  :group 'cpp)

(defcustom cpp-face-dark-list nil
  "Alist of names and faces to be used for dark backgrounds."
185 186
  :type '(repeat (cons string (choice face
				      (cons (const background-color) string))))
Richard M. Stallman's avatar
Richard M. Stallman committed
187 188 189 190 191 192 193 194 195 196 197 198
  :group 'cpp)

(defcustom cpp-face-mono-list
  '(("bold" . bold)
    ("bold-italic" . bold-italic)
    ("italic" . italic)
    ("underline" . underline))
  "Alist of names and faces to be used for monochrome screens."
  :type '(repeat (cons string face))
  :group 'cpp)

(defcustom cpp-face-none-list
199 200
   '(("default" . default)
     ("invisible" . invisible))
Richard M. Stallman's avatar
Richard M. Stallman committed
201
   "Alist of names and faces available even if you don't use a window system."
202
  :type '(repeat (cons string cpp-face))
Richard M. Stallman's avatar
Richard M. Stallman committed
203
  :group 'cpp)
204 205 206 207 208 209

(defvar cpp-face-all-list
  (append cpp-face-light-list
	  cpp-face-dark-list
	  cpp-face-mono-list
	  cpp-face-none-list)
210
  "All faces used for highlighting text inside cpp conditionals.")
211

Richard M. Stallman's avatar
Richard M. Stallman committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225
;;; Parse Buffer:

(defvar cpp-parse-symbols nil
  "List of cpp macros used in the local buffer.")
(make-variable-buffer-local 'cpp-parse-symbols)

(defconst cpp-parse-regexp
  ;; Regexp matching all tokens needed to find conditionals.
  (concat
   "'\\|\"\\|/\\*\\|//\\|"
   "\\(^[ \t]*#[ \t]*\\(ifdef\\|ifndef\\|if\\|"
   "elif\\|else\\|endif\\)\\b\\)"))

;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
226 227 228 229
(defun cpp-highlight-buffer (arg)
  "Highlight C code according to preprocessor conditionals.
This command pops up a buffer which you should edit to specify
what kind of highlighting to use, and the criteria for highlighting.
230
A prefix arg suppresses display of that buffer."
Richard M. Stallman's avatar
Richard M. Stallman committed
231
  (interactive "P")
232 233
  (unless (or (eq t buffer-invisibility-spec)
	      (memq 'cpp buffer-invisibility-spec))
234
    (add-to-invisibility-spec 'cpp))
Richard M. Stallman's avatar
Richard M. Stallman committed
235 236 237 238
  (setq cpp-parse-symbols nil)
  (cpp-parse-reset)
  (if (null cpp-edit-list)
      (cpp-edit-load))
239
  (let (cpp-state-stack)
Richard M. Stallman's avatar
Richard M. Stallman committed
240 241 242 243 244
    (save-excursion
      (goto-char (point-min))
      (cpp-progress-message "Parsing...")
      (while (re-search-forward cpp-parse-regexp nil t)
	(cpp-progress-message "Parsing...%d%%"
245 246
			      (floor (* 100.0 (- (point) (point-min)))
				     (buffer-size)))
Richard M. Stallman's avatar
Richard M. Stallman committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
	(let ((match (buffer-substring (match-beginning 0) (match-end 0))))
	  (cond ((or (string-equal match "'")
		     (string-equal match "\""))
		 (goto-char (match-beginning 0))
		 (condition-case nil
		     (forward-sexp)
		   (error (cpp-parse-error
			   "Unterminated string or character"))))
		((string-equal match "/*")
		 (or (search-forward "*/" nil t)
		     (error "Unterminated comment")))
		((string-equal match "//")
		 (skip-chars-forward "^\n\r"))
		(t
		 (end-of-line 1)
		 (let ((from (match-beginning 1))
		       (to (1+ (point)))
		       (type (buffer-substring (match-beginning 2)
					       (match-end 2)))
		       (expr (buffer-substring (match-end 1) (point))))
		   (cond ((string-equal type "ifdef")
			  (cpp-parse-open t expr from to))
			 ((string-equal type "ifndef")
			  (cpp-parse-open nil expr from to))
			 ((string-equal type "if")
			  (cpp-parse-open t expr from to))
			 ((string-equal type "elif")
			  (let (cpp-known-face cpp-unknown-face)
			    (cpp-parse-close from to))
			  (cpp-parse-open t expr from to))
			 ((string-equal type "else")
278 279 280 281
			  (or cpp-state-stack
			      (cpp-parse-error "Top level #else"))
			  (let ((entry (list (not (nth 0 (car cpp-state-stack)))
					     (nth 1 (car cpp-state-stack))
Richard M. Stallman's avatar
Richard M. Stallman committed
282 283
					     from to)))
			    (cpp-parse-close from to)
284
			    (setq cpp-state-stack (cons entry cpp-state-stack))))
Richard M. Stallman's avatar
Richard M. Stallman committed
285 286 287 288
			 ((string-equal type "endif")
			  (cpp-parse-close from to))
			 (t
			  (cpp-parse-error "Parser error"))))))))
289
      (cpp-progress-message "Parsing...done"))
290
    (if cpp-state-stack
Richard M. Stallman's avatar
Richard M. Stallman committed
291
      (save-excursion
292
	(goto-char (nth 3 (car cpp-state-stack)))
Richard M. Stallman's avatar
Richard M. Stallman committed
293 294 295 296 297 298
	(cpp-parse-error "Unclosed conditional"))))
  (or arg
      (null cpp-parse-symbols)
      (cpp-parse-edit)))

(defun cpp-parse-open (branch expr begin end)
299
  "Push information about conditional-beginning onto `cpp-state-stack'."
300
  ;; Discard comments within this line.
Richard M. Stallman's avatar
Richard M. Stallman committed
301 302 303
  (while (string-match "\\b[ \t]*/\\*.*\\*/[ \t]*\\b" expr)
    (setq expr (concat (substring expr 0 (match-beginning 0))
		       (substring expr (match-end 0)))))
304 305 306 307
  ;; If a comment starts on this line and continues past, discard it.
  (if (string-match "\\b[ \t]*/\\*" expr)
      (setq expr (substring expr 0 (match-beginning 0))))
  ;; Delete any C++ comment from the line.
Richard M. Stallman's avatar
Richard M. Stallman committed
308 309 310 311 312
  (if (string-match "\\b[ \t]*\\(//.*\\)?$" expr)
      (setq expr (substring expr 0 (match-beginning 0))))
  (while (string-match "[ \t]+" expr)
      (setq expr (concat (substring expr 0 (match-beginning 0))
			 (substring expr (match-end 0)))))
313
  (setq cpp-state-stack (cons (list branch expr begin end) cpp-state-stack))
Richard M. Stallman's avatar
Richard M. Stallman committed
314 315 316 317 318 319 320 321
  (or (member expr cpp-parse-symbols)
      (setq cpp-parse-symbols
	    (cons expr cpp-parse-symbols)))
  (if (assoc expr cpp-edit-list)
      (cpp-make-known-overlay begin end)
    (cpp-make-unknown-overlay begin end)))

(defun cpp-parse-close (from to)
322 323 324 325 326
  ;; Pop top of cpp-state-stack and create overlay.
  (let ((entry (assoc (nth 1 (car cpp-state-stack)) cpp-edit-list))
	(branch (nth 0 (car cpp-state-stack)))
	(end (nth 3 (car cpp-state-stack))))
    (setq cpp-state-stack (cdr cpp-state-stack))
Richard M. Stallman's avatar
Richard M. Stallman committed
327 328 329
    (if entry
	(let ((face (nth (if branch 1 2) entry))
	      (read-only (eq (not branch) (nth 3 entry)))
330
	      (priority (length cpp-state-stack))
Richard M. Stallman's avatar
Richard M. Stallman committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
	      (overlay (make-overlay end from)))
	  (cpp-make-known-overlay from to)
	  (setq cpp-overlay-list (cons overlay cpp-overlay-list))
	  (if priority (overlay-put overlay 'priority priority))
	  (cond ((eq face 'invisible)
		 (cpp-make-overlay-hidden overlay))
		((eq face 'default))
		(t
		 (overlay-put overlay 'face face)))
	  (if read-only
	      (cpp-make-overlay-read-only overlay)
	    (cpp-make-overlay-sticky overlay)))
      (cpp-make-unknown-overlay from to))))

(defun cpp-parse-error (error)
  ;; Error message issued by the cpp parser.
347
  (error "%s at line %d" error (count-lines (point-min) (point))))
Richard M. Stallman's avatar
Richard M. Stallman committed
348 349 350 351 352 353 354 355 356 357 358 359 360

(defun cpp-parse-reset ()
  "Reset display of cpp conditionals to normal."
  (interactive)
  (while cpp-overlay-list
    (delete-overlay (car cpp-overlay-list))
    (setq cpp-overlay-list (cdr cpp-overlay-list))))

;;;###autoload
(defun cpp-parse-edit ()
  "Edit display information for cpp conditionals."
  (interactive)
  (or cpp-parse-symbols
361
      (cpp-highlight-buffer t))
Richard M. Stallman's avatar
Richard M. Stallman committed
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
  (let ((buffer (current-buffer)))
    (pop-to-buffer "*CPP Edit*")
    (cpp-edit-mode)
    (setq cpp-edit-buffer buffer)
    (cpp-edit-reset)))

;;; Overlays:

(defun cpp-make-known-overlay (start end)
  ;; Create an overlay for a known cpp command from START to END.
  (let ((overlay (make-overlay start end)))
    (if (eq cpp-known-face 'invisible)
	(cpp-make-overlay-hidden overlay)
      (or (eq cpp-known-face 'default)
	  (overlay-put overlay 'face cpp-known-face))
      (if cpp-known-writable
	  ()
	(overlay-put overlay 'modification-hooks '(cpp-signal-read-only))
	(overlay-put overlay 'insert-in-front-hooks '(cpp-signal-read-only))))
    (setq cpp-overlay-list (cons overlay cpp-overlay-list))))

(defun cpp-make-unknown-overlay (start end)
  ;; Create an overlay for an unknown cpp command from START to END.
  (let ((overlay (make-overlay start end)))
    (cond ((eq cpp-unknown-face 'invisible)
	   (cpp-make-overlay-hidden overlay))
	  ((eq cpp-unknown-face 'default))
389
	  (t
Richard M. Stallman's avatar
Richard M. Stallman committed
390 391 392 393 394 395 396 397 398
	   (overlay-put overlay 'face cpp-unknown-face)))
    (if cpp-unknown-writable
	()
      (overlay-put overlay 'modification-hooks '(cpp-signal-read-only))
      (overlay-put overlay 'insert-in-front-hooks '(cpp-signal-read-only)))
    (setq cpp-overlay-list (cons overlay cpp-overlay-list))))

(defun cpp-make-overlay-hidden (overlay)
  ;; Make overlay hidden and intangible.
399
  (overlay-put overlay 'invisible 'cpp)
400 401
  (overlay-put overlay 'modification-hooks '(cpp-signal-read-only))
  (overlay-put overlay 'insert-in-front-hooks '(cpp-signal-read-only)))
Richard M. Stallman's avatar
Richard M. Stallman committed
402 403 404 405 406 407 408 409 410 411 412 413

(defun cpp-make-overlay-read-only (overlay)
  ;; Make overlay read only.
  (overlay-put overlay 'modification-hooks '(cpp-signal-read-only))
  (overlay-put overlay 'insert-in-front-hooks '(cpp-signal-read-only))
  (overlay-put overlay 'insert-behind-hooks '(cpp-signal-read-only)))

(defun cpp-make-overlay-sticky (overlay)
  ;; Make OVERLAY grow when you insert text at either end.
  (overlay-put overlay 'insert-in-front-hooks '(cpp-grow-overlay))
  (overlay-put overlay 'insert-behind-hooks '(cpp-grow-overlay)))

414
(defun cpp-signal-read-only (overlay after start end &optional _len)
Richard M. Stallman's avatar
Richard M. Stallman committed
415 416
  ;; Only allow deleting the whole overlay.
  ;; Trying to change a read-only overlay.
417 418 419
  (if (and (not after)
	   (or (< (overlay-start overlay) start)
	       (> (overlay-end overlay) end)))
Richard M. Stallman's avatar
Richard M. Stallman committed
420 421
      (error "This text is read only")))

422
(defun cpp-grow-overlay (overlay after start end &optional _len)
Richard M. Stallman's avatar
Richard M. Stallman committed
423
  ;; Make OVERLAY grow to contain range START to END.
424 425 426 427
  (if after
      (move-overlay overlay
		    (min start (overlay-start overlay))
		    (max end (overlay-end overlay)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
428 429 430

;;; Edit Buffer:

431 432 433 434 435
(defvar cpp-edit-mode-map
  (let ((map (make-keymap)))
    (suppress-keymap map)
    (define-key map [ down-mouse-2 ] 'cpp-push-button)
    (define-key map [ mouse-2 ] 'ignore)
436
    (define-key map " " 'scroll-up-command)
437
    (define-key map [?\S-\ ] 'scroll-down-command)
438
    (define-key map "\C-?" 'scroll-down-command)
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
    (define-key map [ delete ] 'scroll-down)
    (define-key map "\C-c\C-c" 'cpp-edit-apply)
    (define-key map "a" 'cpp-edit-apply)
    (define-key map "A" 'cpp-edit-apply)
    (define-key map "r" 'cpp-edit-reset)
    (define-key map "R" 'cpp-edit-reset)
    (define-key map "s" 'cpp-edit-save)
    (define-key map "S" 'cpp-edit-save)
    (define-key map "l" 'cpp-edit-load)
    (define-key map "L" 'cpp-edit-load)
    (define-key map "h" 'cpp-edit-home)
    (define-key map "H" 'cpp-edit-home)
    (define-key map "b" 'cpp-edit-background)
    (define-key map "B" 'cpp-edit-background)
    (define-key map "k" 'cpp-edit-known)
    (define-key map "K" 'cpp-edit-known)
    (define-key map "u" 'cpp-edit-unknown)
    (define-key map "u" 'cpp-edit-unknown)
    (define-key map "t" 'cpp-edit-true)
    (define-key map "T" 'cpp-edit-true)
    (define-key map "f" 'cpp-edit-false)
    (define-key map "F" 'cpp-edit-false)
    (define-key map "w" 'cpp-edit-write)
    (define-key map "W" 'cpp-edit-write)
    (define-key map "X" 'cpp-edit-toggle-known)
    (define-key map "x" 'cpp-edit-toggle-known)
    (define-key map "Y" 'cpp-edit-toggle-unknown)
    (define-key map "y" 'cpp-edit-toggle-unknown)
    (define-key map "q" 'bury-buffer)
    (define-key map "Q" 'bury-buffer)
    map)
  "Keymap for `cpp-edit-mode'.")


Richard M. Stallman's avatar
Richard M. Stallman committed
473 474 475 476 477

(defvar cpp-edit-symbols nil)
;; Symbols defined in the edit buffer.
(make-variable-buffer-local 'cpp-edit-symbols)

478
(define-derived-mode cpp-edit-mode fundamental-mode "CPP Edit"
Richard M. Stallman's avatar
Richard M. Stallman committed
479
  "Major mode for editing the criteria for highlighting cpp conditionals.
480
Click on objects to change them.
Richard M. Stallman's avatar
Richard M. Stallman committed
481 482 483
You can also use the keyboard accelerators indicated like this: [K]ey."
  (buffer-disable-undo)
  (auto-save-mode -1)
484
  (setq buffer-read-only t))
Richard M. Stallman's avatar
Richard M. Stallman committed
485 486 487 488 489

(defun cpp-edit-apply ()
  "Apply edited display information to original buffer."
  (interactive)
  (cpp-edit-home)
490
  (cpp-highlight-buffer t))
Richard M. Stallman's avatar
Richard M. Stallman committed
491 492 493 494 495 496 497 498 499 500 501 502 503 504

(defun cpp-edit-reset ()
  "Reset display information from original buffer."
  (interactive)
  (let ((buffer (current-buffer))
	(buffer-read-only nil)
	(start (window-start))
	(pos (point))
	symbols)
    (set-buffer cpp-edit-buffer)
    (setq symbols cpp-parse-symbols)
    (set-buffer buffer)
    (setq cpp-edit-symbols symbols)
    (erase-buffer)
Paul Eggert's avatar
Paul Eggert committed
505
    (insert (substitute-command-keys "CPP Display Information for `"))
Richard M. Stallman's avatar
Richard M. Stallman committed
506
    (cpp-make-button (buffer-name cpp-edit-buffer) 'cpp-edit-home)
Paul Eggert's avatar
Paul Eggert committed
507 508
    (insert (substitute-command-keys
	     "'\n\nClick mouse-2 on item you want to change or use\n")
509 510 511 512 513 514 515 516 517 518 519
	    "or switch to this buffer and type the keyboard equivalents.\n"
	    "Keyboard equivalents are indicated with brackets like [T]his.\n\n")
    (cpp-make-button "[H]ome (display the C file)" 'cpp-edit-home)
    (insert "  ")
    (cpp-make-button "[A]pply new settings" 'cpp-edit-apply)
    (insert "\n")
    (cpp-make-button "[S]ave settings" 'cpp-edit-save)
    (insert "  ")
    (cpp-make-button "[L]oad settings" 'cpp-edit-load)
    (insert "\n\n")

Richard M. Stallman's avatar
Richard M. Stallman committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
    (insert "[B]ackground: ")
    (cpp-make-button (car (rassq cpp-face-type cpp-face-type-list))
		     'cpp-edit-background)
    (insert "\n[K]nown conditionals: ")
    (cpp-make-button (cpp-face-name cpp-known-face)
		     'cpp-edit-known nil t)
    (insert " [X] ")
    (cpp-make-button (car (rassq cpp-known-writable cpp-writable-list))
		     'cpp-edit-toggle-known)
    (insert "\n[U]nknown conditionals: ")
    (cpp-make-button (cpp-face-name cpp-unknown-face)
		     'cpp-edit-unknown nil t)
    (insert " [Y] ")
    (cpp-make-button (car (rassq cpp-unknown-writable cpp-writable-list))
		     'cpp-edit-toggle-unknown)
    (insert (format "\n\n\n%39s: %14s %14s %7s\n\n" "Expression"
		    "[T]rue Face" "[F]alse Face" "[W]rite"))
537 538

    (setq symbols (reverse symbols))
Richard M. Stallman's avatar
Richard M. Stallman committed
539 540 541 542 543 544 545 546 547 548 549 550 551 552
    (while symbols
      (let*  ((symbol (car symbols))
	      (entry (assoc symbol cpp-edit-list))
	      (true (nth 1 entry))
	      (false (nth 2 entry))
	      (write (if entry (nth 3 entry) 'both)))
	(setq symbols (cdr symbols))

	(if (and entry			; Make default entries unknown.
		 (or (null true) (eq true 'default))
		 (or (null false) (eq false 'default))
		 (eq write 'both))
	    (setq cpp-edit-list (delq entry cpp-edit-list)
		  entry nil))
553

554
	(if (> (length symbol) 39)
Richard M. Stallman's avatar
Richard M. Stallman committed
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
	    (insert (substring symbol 0 39) ": ")
	  (insert (format "%39s: " symbol)))

	(cpp-make-button (cpp-face-name true)
			 'cpp-edit-true symbol t 14)
	(insert " ")
	(cpp-make-button (cpp-face-name false)
			 'cpp-edit-false symbol t 14)
	(insert " ")
	(cpp-make-button (car (rassq write cpp-branch-list))
			 'cpp-edit-write symbol nil 6)
	(insert "\n")))
    (insert "\n\n")
    (set-window-start nil start)
    (goto-char pos)))

(defun cpp-edit-load ()
  "Load cpp configuration."
  (interactive)
574 575 576 577
  (cond ((null init-file-user)
	 ;; If -q was specified, don't load any init files.
	 nil)
	((file-readable-p cpp-config-file)
578 579 580
	 (load-file cpp-config-file))
	((file-readable-p (concat "~/" cpp-config-file))
	 (load-file cpp-config-file)))
581
  (if (derived-mode-p 'cpp-edit-mode)
582
      (cpp-edit-reset)))
Richard M. Stallman's avatar
Richard M. Stallman committed
583 584

(defun cpp-edit-save ()
585
  "Save the current cpp configuration in a file."
Richard M. Stallman's avatar
Richard M. Stallman committed
586 587
  (interactive)
  (require 'pp)
588
  (with-current-buffer cpp-edit-buffer
589
    (let ((buffer (find-file-noselect cpp-config-file)))
Richard M. Stallman's avatar
Richard M. Stallman committed
590 591 592 593 594 595 596 597 598 599 600 601 602 603
      (set-buffer buffer)
      (erase-buffer)
      (pp (list 'setq 'cpp-known-face
		(list 'quote cpp-known-face)) buffer)
      (pp (list 'setq 'cpp-unknown-face
		(list 'quote cpp-unknown-face)) buffer)
      (pp (list 'setq 'cpp-face-type
		(list 'quote cpp-face-type)) buffer)
      (pp (list 'setq 'cpp-known-writable
		(list 'quote cpp-known-writable)) buffer)
      (pp (list 'setq 'cpp-unknown-writable
		(list 'quote cpp-unknown-writable)) buffer)
      (pp (list 'setq 'cpp-edit-list
		(list 'quote cpp-edit-list)) buffer)
604
      (write-file cpp-config-file))))
Richard M. Stallman's avatar
Richard M. Stallman committed
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632

(defun cpp-edit-home ()
  "Switch back to original buffer."
  (interactive)
  (if cpp-button-event
      (read-event))
  (pop-to-buffer cpp-edit-buffer))

(defun cpp-edit-background ()
  "Change default face collection."
  (interactive)
  (call-interactively 'cpp-choose-default-face)
  (cpp-edit-reset))

(defun cpp-edit-known ()
  "Select default for known conditionals."
  (interactive)
  (setq cpp-known-face (cpp-choose-face "Known face" cpp-known-face))
  (cpp-edit-reset))

(defun cpp-edit-unknown ()
  "Select default for unknown conditionals."
  (interactive)
  (setq cpp-unknown-face (cpp-choose-face "Unknown face" cpp-unknown-face))
  (cpp-edit-reset))

(defun cpp-edit-toggle-known (arg)
  "Toggle writable status for known conditionals.
633 634
With optional argument ARG, make them writable if ARG is positive,
otherwise make them unwritable."
Richard M. Stallman's avatar
Richard M. Stallman committed
635 636 637 638 639 640 641 642 643
  (interactive "@P")
  (if (or (and (null arg) cpp-known-writable)
	  (<= (prefix-numeric-value arg) 0))
      (setq cpp-known-writable nil)
    (setq cpp-known-writable t))
  (cpp-edit-reset))

(defun cpp-edit-toggle-unknown (arg)
  "Toggle writable status for unknown conditionals.
644 645
With optional argument ARG, make them writable if ARG is positive,
otherwise make them unwritable."
Richard M. Stallman's avatar
Richard M. Stallman committed
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
  (interactive "@P")
  (if (or (and (null arg) cpp-unknown-writable)
	  (<= (prefix-numeric-value arg) 0))
      (setq cpp-unknown-writable nil)
    (setq cpp-unknown-writable t))
  (cpp-edit-reset))

(defun cpp-edit-true (symbol face)
  "Select SYMBOL's true FACE used for highlighting taken conditionals."
  (interactive
   (let ((symbol (cpp-choose-symbol)))
     (list symbol
	   (cpp-choose-face "True face"
			    (nth 1 (assoc symbol cpp-edit-list))))))
  (setcar (nthcdr 1 (cpp-edit-list-entry-get-or-create symbol)) face)
  (cpp-edit-reset))

(defun cpp-edit-false (symbol face)
  "Select SYMBOL's false FACE used for highlighting untaken conditionals."
  (interactive
   (let ((symbol (cpp-choose-symbol)))
     (list symbol
668
	   (cpp-choose-face "False face"
Richard M. Stallman's avatar
Richard M. Stallman committed
669 670 671 672 673 674
			    (nth 2 (assoc symbol cpp-edit-list))))))
  (setcar (nthcdr 2 (cpp-edit-list-entry-get-or-create symbol)) face)
  (cpp-edit-reset))

(defun cpp-edit-write (symbol branch)
  "Set which branches of SYMBOL should be writable to BRANCH.
675
BRANCH should be either nil (false branch), t (true branch) or `both'."
Richard M. Stallman's avatar
Richard M. Stallman committed
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
  (interactive (list (cpp-choose-symbol) (cpp-choose-branch)))
  (setcar (nthcdr 3 (cpp-edit-list-entry-get-or-create symbol)) branch)
  (cpp-edit-reset))

(defun cpp-edit-list-entry-get-or-create (symbol)
  ;; Return the entry for SYMBOL in `cpp-edit-list'.
  ;; If it does not exist, create it.
  (let ((entry (assoc symbol cpp-edit-list)))
    (or entry
	(setq entry (list symbol nil nil 'both nil)
	      cpp-edit-list (cons entry cpp-edit-list)))
    entry))

;;; Prompts:

(defun cpp-choose-symbol ()
  ;; Choose a symbol if called from keyboard, otherwise use the one clicked on.
  (if cpp-button-event
694
      cpp-callback-data
695
    (completing-read "Symbol: " cpp-edit-symbols nil t)))
Richard M. Stallman's avatar
Richard M. Stallman committed
696 697 698 699 700 701 702 703 704 705

(defun cpp-choose-branch ()
  ;; Choose a branch, either nil, t, or both.
  (if cpp-button-event
      (x-popup-menu cpp-button-event
		    (list "Branch" (cons "Branch" cpp-branch-list)))
    (cdr (assoc	(completing-read "Branch: " cpp-branch-list nil t)
		cpp-branch-list))))

(defun cpp-choose-face (prompt default)
Pavel Janík's avatar
Pavel Janík committed
706
  ;; Choose a face from cpp-face-default-list.
Richard M. Stallman's avatar
Richard M. Stallman committed
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
  ;; PROMPT is what to say to the user.
  ;; DEFAULT is the default face.
  (or (if cpp-button-event
	  (x-popup-menu cpp-button-event
			(list prompt (cons prompt cpp-face-default-list)))
	(let ((name (car (rassq default cpp-face-default-list))))
	  (cdr (assoc (completing-read (if name
					   (concat prompt
						   " (default " name "): ")
					 (concat prompt ": "))
				       cpp-face-default-list nil t)
		      cpp-face-all-list))))
      default))

(defun cpp-choose-default-face (type)
  ;; Choose default face list for screen of TYPE.
  ;; Type must be one of the types defined in `cpp-face-type-list'.
  (interactive (list (if cpp-button-event
			 (x-popup-menu cpp-button-event
				       (list "Screen type"
					     (cons "Screen type"
						   cpp-face-type-list)))
		       (cdr (assoc (completing-read "Screen type: "
						    cpp-face-type-list
						    nil t)
				   cpp-face-type-list)))))
  (cond ((null type))
	((eq type 'light)
	 (if cpp-face-light-list
	     ()
	   (setq cpp-face-light-list
		 (mapcar 'cpp-create-bg-face cpp-face-light-name-list))
	   (setq cpp-face-all-list
		 (append cpp-face-all-list cpp-face-light-list)))
	 (setq cpp-face-type 'light)
	 (setq cpp-face-default-list
	       (append cpp-face-light-list cpp-face-none-list)))
	((eq type 'dark)
	 (if cpp-face-dark-list
	     ()
	   (setq cpp-face-dark-list
		 (mapcar 'cpp-create-bg-face cpp-face-dark-name-list))
	   (setq cpp-face-all-list
		 (append cpp-face-all-list cpp-face-dark-list)))
	 (setq cpp-face-type 'dark)
	 (setq cpp-face-default-list
	       (append cpp-face-dark-list cpp-face-none-list)))
	((eq type 'mono)
	 (setq cpp-face-type 'mono)
	 (setq cpp-face-default-list
	       (append cpp-face-mono-list cpp-face-none-list)))
	(t
	 (setq cpp-face-type 'none)
	 (setq cpp-face-default-list cpp-face-none-list))))

;;; Buttons:

(defun cpp-make-button (name callback &optional data face padding)
  ;; Create a button at point.
  ;; NAME is the name of the button.
  ;; CALLBACK is the function to call when the button is pushed.
768 769
  ;; DATA will be made available to CALLBACK
  ;;in the free variable cpp-callback-data.
Richard M. Stallman's avatar
Richard M. Stallman committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
  ;; FACE means that NAME is the name of a face in `cpp-face-all-list'.
  ;; PADDING means NAME will be right justified at that length.
  (let ((name (format "%s" name))
	from to)
    (cond ((null padding)
	   (setq from (point))
	   (insert name))
	  ((> (length name) padding)
	   (setq from (point))
	   (insert (substring name 0 padding)))
	  (t
	   (insert (make-string (- padding (length name)) ? ))
	   (setq from (point))
	   (insert name)))
    (setq to (point))
    (setq face
	  (if face
	      (let ((check (cdr (assoc name cpp-face-all-list))))
		(if (memq check '(default invisible))
		    'bold
		  check))
	    'bold))
    (add-text-properties from to
			 (append (list 'face face)
				 '(mouse-face highlight)
795
				 '(help-echo "mouse-2: change/use this item")
Richard M. Stallman's avatar
Richard M. Stallman committed
796 797 798 799 800 801 802 803
				 (list 'cpp-callback callback)
				 (if data (list 'cpp-data data))))))

(defun cpp-push-button (event)
  ;; Pushed a CPP button.
  (interactive "@e")
  (set-buffer (window-buffer (posn-window (event-start event))))
  (let ((pos (posn-point (event-start event))))
804
    (let ((cpp-callback-data (get-text-property pos 'cpp-data))
Richard M. Stallman's avatar
Richard M. Stallman committed
805 806 807 808 809 810 811 812 813 814 815
	  (fun (get-text-property pos 'cpp-callback))
	  (cpp-button-event event))
      (cond (fun
	     (call-interactively (get-text-property pos 'cpp-callback)))
	    ((lookup-key global-map [ down-mouse-2])
	     (call-interactively (lookup-key global-map [ down-mouse-2])))))))

;;; Faces:

(defun cpp-create-bg-face (color)
  ;; Create entry for face with background COLOR.
816
  (cons color (cons 'background-color color)))
Richard M. Stallman's avatar
Richard M. Stallman committed
817

818 819
(cpp-choose-default-face
 (if (or window-system (display-color-p)) cpp-face-type 'none))
Richard M. Stallman's avatar
Richard M. Stallman committed
820 821 822 823 824 825 826 827 828 829

(defun cpp-face-name (face)
  ;; Return the name of FACE from `cpp-face-all-list'.
  (let ((entry (rassq (if face face 'default) cpp-face-all-list)))
    (if entry
	(car entry)
      (format "<%s>" face))))

;;; Utilities:

830 831
(defvar cpp-progress-time 0
  "Last time `cpp-progress-message' issued a progress message.")
Richard M. Stallman's avatar
Richard M. Stallman committed
832 833

(defun cpp-progress-message (&rest args)
834 835 836 837 838 839 840 841 842 843 844
  "Report progress by printing messages used by \"cpp-\" functions.

Print messages at most once every `cpp-message-min-time-interval' seconds.
If that option is nil, don't prints messages.
ARGS are the same as for `message'."
  (when cpp-message-min-time-interval
    (let ((time (current-time)))
      (when (>= (float-time (time-subtract time cpp-progress-time))
                cpp-message-min-time-interval)
        (setq cpp-progress-time time)
        (apply 'message args)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
845 846 847 848

(provide 'cpp)

;;; cpp.el ends here