(sh-mode): Remove ! in column 1.
[bpt/emacs.git] / lisp / progmodes / cmacexp.el
CommitLineData
4af1f509 1;;; cmacexp.el --- expand C macros in a region
c0274f38 2
d733c5ec 3;; Copyright (C) 1992, 1994 Free Software Foundation, Inc.
9750e079 4
4af1f509 5;; Author: Francesco Potorti` <pot@cnuce.cnr.it>
a9132c1f 6;; Version: $Id: cmacexp.el,v 1.19 1995/03/07 15:24:44 pot Exp rms $
4af1f509 7;; Adapted-By: ESR
e5167999
ER
8;; Keywords: c
9
c17d15d0
JB
10;; This file is part of GNU Emacs.
11
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
e5167999 14;; the Free Software Foundation; either version 2, or (at your option)
c17d15d0
JB
15;; any later version.
16
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.
21
22;; You should have received a copy of the GNU General Public License
23;; along with GNU Emacs; see the file COPYING. If not, write to
24;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25
89fb82d6 26;; USAGE =============================================================
e41b2db1 27
074521be
RS
28;; In C mode C-C C-e is bound to c-macro-expand. The result of the
29;; expansion is put in a separate buffer. A user option allows the
30;; window displaying the buffer to be optimally sized.
e41b2db1 31;;
4af1f509 32;; When called with a C-u prefix, c-macro-expand replaces the selected
89fb82d6 33;; region with the expansion. Both the preprocessor name and the
074521be
RS
34;; initial flag can be set by the user. If c-macro-prompt-flag is set
35;; to a non-nil value the user is offered to change the options to the
36;; preprocessor each time c-macro-expand is invoked. Preprocessor
37;; arguments default to the last ones entered. If c-macro-prompt-flag
38;; is nil, one must use M-x set-variable to set a different value for
39;; c-macro-cppflags.
4af1f509
RS
40
41;; A c-macro-expansion function is provided for non-interactive use.
4af1f509
RS
42
43;; INSTALLATION ======================================================
44
074521be 45;; Put the following in your ~/.emacs file.
4af1f509 46
4af1f509
RS
47;; If you want the *Macroexpansion* window to be not higher than
48;; necessary:
074521be 49;;(setq c-macro-shrink-window-flag t)
e41b2db1 50;;
4af1f509
RS
51;; If you use a preprocessor other than /lib/cpp (be careful to set a
52;; -C option or equivalent in order to make the preprocessor not to
53;; strip the comments):
54;;(setq c-macro-preprocessor "gpp -C")
55;;
89fb82d6
RS
56;; If you often use a particular set of flags:
57;;(setq c-macro-cppflags "-I /usr/include/local -DDEBUG"
4af1f509 58;;
89fb82d6 59;; If you want the "Preprocessor arguments: " prompt:
074521be 60;;(setq c-macro-prompt-flag t)
4af1f509
RS
61
62;; BUG REPORTS =======================================================
63
64;; Please report bugs, suggestions, complaints and so on to
65;; pot@cnuce.cnr.it (Francesco Potorti`).
66
67;; IMPROVEMENTS OVER emacs 18.xx cmacexp.el ==========================
68
3332766c 69;; - A lot of user and programmer visible changes. See above.
4af1f509
RS
70;; - #line directives are inserted, so __LINE__ and __FILE__ are
71;; correctly expanded. Works even with START inside a string, a
72;; comment or a region #ifdef'd away by cpp. cpp is invoked with -C,
73;; making comments visible in the expansion.
74;; - All work is done in core memory, no need for temporary files.
4af1f509
RS
75
76;; ACKNOWLEDGEMENTS ==================================================
77
78;; A lot of thanks to Don Maszle who did a great work of testing, bug
074521be
RS
79;; reporting and suggestion of new features. This work has been
80;; partially inspired by Don Maszle and Jonathan Segal's.
4af1f509 81
89fb82d6 82;; BUGS ==============================================================
4af1f509
RS
83
84;; If the start point of the region is inside a macro definition the
85;; macro expansion is often inaccurate.
e41b2db1 86
89fb82d6 87
a9132c1f
RS
88(require 'cc-mode)
89
89fb82d6 90(provide 'cmacexp)
c17d15d0 91
9c32788e 92(defvar c-macro-shrink-window-flag nil
4af1f509
RS
93 "*Non-nil means shrink the *Macroexpansion* window to fit its contents.")
94
43427c5b 95(defvar c-macro-prompt-flag nil
9c32788e 96 "*Non-nil makes `c-macro-expand' prompt for preprocessor arguments.")
4af1f509 97
9c32788e
RS
98(defvar c-macro-preprocessor "/lib/cpp -C"
99 "The preprocessor used by the cmacexp package.
4af1f509 100
440c10f8 101If you change this, be sure to preserve the `-C' (don't strip comments)
4af1f509
RS
102option, or to set an equivalent one.")
103
89fb82d6 104(defvar c-macro-cppflags ""
440c10f8 105 "*Preprocessor flags used by `c-macro-expand'.")
4af1f509
RS
106
107(defconst c-macro-buffer-name "*Macroexpansion*")
108
9c32788e
RS
109(defun c-macro-expand (start end subst)
110 "Expand C macros in the region, using the C preprocessor.
111Normally display output in temp buffer, but
112prefix arg means replace the region with it.
113
114`c-macro-preprocessor' specifies the preprocessor to use.
115Prompt for arguments to the preprocessor \(e.g. `-DDEBUG -I ./include')
116if the user option `c-macro-prompt-flag' is non-nil.
4af1f509 117
89fb82d6 118Noninteractive args are START, END, SUBST.
9c32788e 119For use inside Lisp programs, see also `c-macro-expansion'."
4af1f509
RS
120
121 (interactive "r\nP")
89fb82d6
RS
122 (let ((inbuf (current-buffer))
123 (displaybuf (if subst
124 (get-buffer c-macro-buffer-name)
125 (get-buffer-create c-macro-buffer-name)))
074521be 126 (expansion ""))
4af1f509 127 ;; Build the command string.
9c32788e 128 (if c-macro-prompt-flag
89fb82d6 129 (setq c-macro-cppflags
4af1f509 130 (read-string "Preprocessor arguments: "
89fb82d6 131 c-macro-cppflags)))
4af1f509
RS
132 ;; Decide where to display output.
133 (if (and subst
6c61e6a9 134 (and buffer-read-only (not inhibit-read-only))
4af1f509
RS
135 (not (eq inbuf displaybuf)))
136 (progn
137 (message
138 "Buffer is read only: displaying expansion in alternate window")
139 (sit-for 2)
140 (setq subst nil)
141 (or displaybuf
142 (setq displaybuf (get-buffer-create c-macro-buffer-name)))))
143 ;; Expand the macro and output it.
89fb82d6
RS
144 (setq expansion (c-macro-expansion start end
145 (concat c-macro-preprocessor " "
074521be 146 c-macro-cppflags) t))
4af1f509
RS
147 (if subst
148 (let ((exchange (= (point) start)))
149 (delete-region start end)
150 (insert expansion)
151 (if exchange
152 (exchange-point-and-mark)))
153 (set-buffer displaybuf)
154 (setq buffer-read-only nil)
3332766c 155 (buffer-disable-undo displaybuf)
4af1f509
RS
156 (erase-buffer)
157 (insert expansion)
158 (set-buffer-modified-p nil)
159 (if (string= "" expansion)
160 (message "Null expansion")
89fb82d6 161 (c-macro-display-buffer))
4af1f509 162 (setq buffer-read-only t)
89fb82d6 163 (setq buffer-auto-save-file-name nil)
4af1f509
RS
164 (bury-buffer displaybuf))))
165
166
167;; Display the current buffer in a window which is either just large
168;; enough to contain the entire buffer, or half the size of the
89fb82d6
RS
169;; screen, whichever is smaller. Do not select the new
170;; window.
4af1f509
RS
171;;
172;; Several factors influence window resizing so that the window is
173;; sized optimally if it is created anew, and so that it is messed
174;; with minimally if it has been created by the user. If the window
175;; chosen for display exists already but contains something else, the
176;; window is not re-sized. If the window already contains the current
177;; buffer, it is never shrunk, but possibly expanded. Finally, if the
9c32788e 178;; variable c-macro-shrink-window-flag is nil the window size is *never*
4af1f509 179;; changed.
89fb82d6 180(defun c-macro-display-buffer ()
4af1f509
RS
181 (goto-char (point-min))
182 (c-mode)
4af1f509
RS
183 (let ((oldwinheight (window-height))
184 (alreadythere ;the window was already there
185 (get-buffer-window (current-buffer)))
1dc5112c 186 (popped nil)) ;the window popped changing the layout
4af1f509
RS
187 (or alreadythere
188 (progn
189 (display-buffer (current-buffer) t)
190 (setq popped (/= oldwinheight (window-height)))))
9c32788e 191 (if (and c-macro-shrink-window-flag ;user wants fancy shrinking :\)
4af1f509
RS
192 (or alreadythere popped))
193 ;; Enlarge up to half screen, or shrink properly.
194 (let ((oldwin (selected-window))
195 (minheight 0)
196 (maxheight 0))
197 (save-excursion
198 (select-window (get-buffer-window (current-buffer)))
199 (setq minheight (if alreadythere
200 (window-height)
201 window-min-height))
202 (setq maxheight (/ (screen-height) 2))
203 (enlarge-window (- (min maxheight
204 (max minheight
89fb82d6 205 (+ 2 (vertical-motion (point-max)))))
4af1f509
RS
206 (window-height)))
207 (goto-char (point-min))
208 (select-window oldwin))))))
209
210
074521be 211(defun c-macro-expansion (start end cppcommand &optional display)
9c32788e 212 "Run a preprocessor on region and return the output as a string.
89fb82d6
RS
213Expand the region between START and END in the current buffer using
214the shell command CPPCOMMAND (e.g. \"/lib/cpp -C -DDEBUG\").
074521be
RS
215Be sure to use a -C (don't strip comments) or equivalent option.
216Optional arg DISPLAY non-nil means show messages in the echo area."
4af1f509
RS
217
218;; Copy the current buffer's contents to a temporary hidden buffer.
219;; Delete from END to end of buffer. Insert a preprocessor #line
220;; directive at START and after each #endif following START that are
221;; not inside a comment or a string. Put all the strings thus
222;; inserted (without the "line" substring) in a list named linelist.
223;; If START is inside a comment, prepend "*/" and append "/*" to the
224;; #line directive. If inside a string, prepend and append "\"".
225;; Preprocess the buffer contents, then look for all the lines stored
226;; in linelist starting from end of buffer. The last line so found is
227;; where START was, so return the substring from point to end of
228;; buffer.
229 (let ((inbuf (current-buffer))
230 (outbuf (get-buffer-create " *C Macro Expansion*"))
231 (filename (if (and buffer-file-name
232 (string-match (regexp-quote default-directory)
233 buffer-file-name))
234 (substring buffer-file-name (match-end 0))
235 (buffer-name)))
074521be
RS
236 (mymsg (format "Invoking %s%s%s on region..."
237 c-macro-preprocessor
238 (if (string= "" c-macro-cppflags) "" " ")
239 c-macro-cppflags))
240 (uniquestring "???!!!???!!! start of c-macro expansion ???!!!???!!!")
241 (startlinenum 0)
4af1f509 242 (linenum 0)
074521be 243 (startstat ())
440c10f8 244 (startmarker "")
3332766c 245 (exit-status 0)
440c10f8 246 (tempname (make-temp-name "/tmp/")))
4af1f509
RS
247 (unwind-protect
248 (save-excursion
249 (save-restriction
250 (widen)
251 (set-buffer outbuf)
252 (setq buffer-read-only nil)
253 (erase-buffer)
254 (set-syntax-table c-mode-syntax-table)
255 (insert-buffer-substring inbuf 1 end))
256
257 ;; We have copied inbuf to outbuf. Point is at end of
258 ;; outbuf. Insert a space at the end, so cpp can correctly
259 ;; parse a token ending at END.
4af1f509
RS
260 (insert " ")
261
074521be
RS
262 ;; Save sexp status and line number at START.
263 (setq startstat (parse-partial-sexp 1 start))
264 (setq startlinenum (+ (count-lines 1 (point))
265 (if (bolp) 1 0)))
266
4af1f509 267 ;; Now we insert the #line directives after all #endif or
074521be
RS
268 ;; #else following START going backward, so the lines we
269 ;; insert don't change the line numbers.
4af1f509 270 ;(switch-to-buffer outbuf) (debug) ;debugging instructions
074521be 271 (goto-char (point-max))
4af1f509 272 (while (re-search-backward "\n#\\(endif\\|else\\)\\>" start 'move)
074521be
RS
273 (if (equal (nthcdr 3 (parse-partial-sexp start (point)
274 nil nil startstat))
9c32788e 275 '(nil nil nil 0 nil)) ;neither in string nor in
074521be 276 ;comment nor after quote
4af1f509
RS
277 (progn
278 (goto-char (match-end 0))
074521be
RS
279 (setq linenum (+ startlinenum
280 (count-lines start (point))))
281 (insert (format "\n#line %d \"%s\"\n" linenum filename))
282 (goto-char (match-beginning 0)))))
283
284 ;; Now we are at START. Insert the first #line directive.
285 ;; This must work even inside a string or comment, or after a
4af1f509 286 ;; quote.
074521be
RS
287 (let* ((startinstring (nth 3 startstat))
288 (startincomment (nth 4 startstat))
289 (startafterquote (nth 5 startstat))
290 (startinbcomment (nth 7 startstat)))
291 (insert (if startafterquote " " "")
292 (cond (startinstring
293 (char-to-string startinstring))
294 (startincomment "*/")
295 (""))
074521be 296 (setq startmarker
521fffcd 297 (concat "\n" uniquestring
074521be
RS
298 (cond (startinstring
299 (char-to-string startinstring))
300 (startincomment "/*")
301 (startinbcomment "//"))
521fffcd
FP
302 (if startafterquote "\\")))
303 (format "\n#line %d \"%s\"\n" startlinenum filename)))
4af1f509
RS
304
305 ;; Call the preprocessor.
074521be 306 (if display (message mymsg))
440c10f8
RS
307 (setq exit-status
308 (call-process-region 1 (point-max) "sh" t t nil "-c"
309 (concat cppcommand " 2>" tempname)))
074521be 310 (if display (message (concat mymsg "done")))
eb426f3a
RS
311 (if (= (buffer-size) 0)
312 ;; Empty output is normal after a fatal error.
313 (insert "\nPreprocessor produced no output\n")
314 ;; Find and delete the mark of the start of the expansion.
315 ;; Look for `# nn "file.c"' lines and delete them.
316 (goto-char (point-min))
317 (search-forward startmarker)
318 (delete-region 1 (point)))
074521be
RS
319 (while (re-search-forward (concat "^# [0-9]+ \""
320 (regexp-quote filename)
321 "\"") nil t)
322 (beginning-of-line)
323 (let ((beg (point)))
324 (forward-line 1)
325 (delete-region beg (point))))
4af1f509 326
440c10f8
RS
327 ;; If CPP got errors, show them at the beginning.
328 (or (eq exit-status 0)
329 (progn
330 (goto-char (point-min))
331 (insert (format "Preprocessor terminated with status %s\n"
332 exit-status))
333 (insert-file-contents tempname)
334 (insert "\n")))
335 (delete-file tempname)
336
4af1f509
RS
337 ;; Compute the return value, keeping in account the space
338 ;; inserted at the end of the buffer.
074521be 339 (buffer-substring 1 (max 1 (- (point-max) 1))))
4af1f509
RS
340
341 ;; Cleanup.
342 (kill-buffer outbuf))))
343
89fb82d6 344;;; cmacexp.el ends here