Fix up comment convention on the arch-tag lines.
[bpt/emacs.git] / lisp / progmodes / cmacexp.el
CommitLineData
4af1f509 1;;; cmacexp.el --- expand C macros in a region
c0274f38 2
4e643dd2 3;; Copyright (C) 1992, 1994, 1996, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
034babe1 4;; Free Software Foundation, Inc.
9750e079 5
8a30aaa3 6;; Author: Francesco Potorti` <pot@gnu.org>
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
1a484753 14;; the Free Software Foundation; either version 3, 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
b578f267 23;; along with GNU Emacs; see the file COPYING. If not, write to the
3a35cf56
LK
24;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25;; Boston, MA 02110-1301, USA.
c17d15d0 26
e8af40ee
PJ
27;;; Commentary:
28
89fb82d6 29;; USAGE =============================================================
e41b2db1 30
074521be
RS
31;; In C mode C-C C-e is bound to c-macro-expand. The result of the
32;; expansion is put in a separate buffer. A user option allows the
33;; window displaying the buffer to be optimally sized.
e41b2db1 34;;
4af1f509 35;; When called with a C-u prefix, c-macro-expand replaces the selected
89fb82d6 36;; region with the expansion. Both the preprocessor name and the
074521be
RS
37;; initial flag can be set by the user. If c-macro-prompt-flag is set
38;; to a non-nil value the user is offered to change the options to the
39;; preprocessor each time c-macro-expand is invoked. Preprocessor
40;; arguments default to the last ones entered. If c-macro-prompt-flag
41;; is nil, one must use M-x set-variable to set a different value for
42;; c-macro-cppflags.
4af1f509
RS
43
44;; A c-macro-expansion function is provided for non-interactive use.
4af1f509
RS
45
46;; INSTALLATION ======================================================
47
074521be 48;; Put the following in your ~/.emacs file.
4af1f509 49
4af1f509 50;; If you want the *Macroexpansion* window to be not higher than
4ff3fcc7 51;; necessary:
074521be 52;;(setq c-macro-shrink-window-flag t)
e41b2db1 53;;
4af1f509
RS
54;; If you use a preprocessor other than /lib/cpp (be careful to set a
55;; -C option or equivalent in order to make the preprocessor not to
56;; strip the comments):
57;;(setq c-macro-preprocessor "gpp -C")
58;;
89fb82d6
RS
59;; If you often use a particular set of flags:
60;;(setq c-macro-cppflags "-I /usr/include/local -DDEBUG"
4af1f509 61;;
89fb82d6 62;; If you want the "Preprocessor arguments: " prompt:
074521be 63;;(setq c-macro-prompt-flag t)
4af1f509
RS
64
65;; BUG REPORTS =======================================================
66
67;; Please report bugs, suggestions, complaints and so on to
8a30aaa3 68;; pot@gnu.org (Francesco Potorti`).
4af1f509
RS
69
70;; IMPROVEMENTS OVER emacs 18.xx cmacexp.el ==========================
71
3332766c 72;; - A lot of user and programmer visible changes. See above.
4af1f509
RS
73;; - #line directives are inserted, so __LINE__ and __FILE__ are
74;; correctly expanded. Works even with START inside a string, a
75;; comment or a region #ifdef'd away by cpp. cpp is invoked with -C,
76;; making comments visible in the expansion.
77;; - All work is done in core memory, no need for temporary files.
4af1f509
RS
78
79;; ACKNOWLEDGEMENTS ==================================================
80
81;; A lot of thanks to Don Maszle who did a great work of testing, bug
074521be
RS
82;; reporting and suggestion of new features. This work has been
83;; partially inspired by Don Maszle and Jonathan Segal's.
4af1f509 84
89fb82d6 85;; BUGS ==============================================================
4af1f509
RS
86
87;; If the start point of the region is inside a macro definition the
88;; macro expansion is often inaccurate.
e41b2db1 89
e8af40ee 90;;; Code:
89fb82d6 91
a9132c1f
RS
92(require 'cc-mode)
93
89fb82d6 94(provide 'cmacexp)
c17d15d0 95
80d0edae
JB
96(defvar msdos-shells)
97
98
00ed33e7
RS
99(defgroup c-macro nil
100 "Expand C macros in a region."
101 :group 'c)
4af1f509 102
4af1f509 103
00ed33e7
RS
104(defcustom c-macro-shrink-window-flag nil
105 "*Non-nil means shrink the *Macroexpansion* window to fit its contents."
106 :type 'boolean
107 :group 'c-macro)
108
109(defcustom c-macro-prompt-flag nil
110 "*Non-nil makes `c-macro-expand' prompt for preprocessor arguments."
111 :type 'boolean
112 :group 'c-macro)
113
114(defcustom c-macro-preprocessor
ab3290cb 115 (cond ;; Solaris has it in an unusual place.
b4ec679c
RS
116 ((and (string-match "^[^-]*-[^-]*-\\(solaris\\|sunos5\\)"
117 system-configuration)
118 (file-exists-p "/opt/SUNWspro/SC3.0.1/bin/acomp"))
119 "/opt/SUNWspro/SC3.0.1/bin/acomp -C -E")
ab3290cb
EZ
120 ((locate-file "/usr/ccs/lib/cpp"
121 '("/") exec-suffixes 'file-executable-p)
122 "/usr/ccs/lib/cpp -C")
123 ((locate-file "/lib/cpp"
124 '("/") exec-suffixes 'file-executable-p)
125 "/lib/cpp -C")
126 ;; On some systems, we cannot rely on standard directories to
127 ;; find CPP. In fact, we cannot rely on having cpp, either,
128 ;; in some GCC versions.
129 ((locate-file "cpp" exec-path exec-suffixes 'file-executable-p)
130 "cpp -C")
131 (t "gcc -E -C -o - -"))
9c32788e 132 "The preprocessor used by the cmacexp package.
4af1f509 133
440c10f8 134If you change this, be sure to preserve the `-C' (don't strip comments)
00ed33e7
RS
135option, or to set an equivalent one."
136 :type 'string
137 :group 'c-macro)
138
139(defcustom c-macro-cppflags ""
140 "*Preprocessor flags used by `c-macro-expand'."
141 :type 'string
142 :group 'c-macro)
4af1f509
RS
143
144(defconst c-macro-buffer-name "*Macroexpansion*")
145
d322f009 146;;;###autoload
9c32788e
RS
147(defun c-macro-expand (start end subst)
148 "Expand C macros in the region, using the C preprocessor.
149Normally display output in temp buffer, but
150prefix arg means replace the region with it.
151
152`c-macro-preprocessor' specifies the preprocessor to use.
034babe1
NR
153Tf the user option `c-macro-prompt-flag' is non-nil
154prompt for arguments to the preprocessor \(e.g. `-DDEBUG -I ./include'),
155otherwise use `c-macro-cppflags'.
4af1f509 156
89fb82d6 157Noninteractive args are START, END, SUBST.
9c32788e 158For use inside Lisp programs, see also `c-macro-expansion'."
4af1f509
RS
159
160 (interactive "r\nP")
89fb82d6
RS
161 (let ((inbuf (current-buffer))
162 (displaybuf (if subst
163 (get-buffer c-macro-buffer-name)
164 (get-buffer-create c-macro-buffer-name)))
074521be 165 (expansion ""))
4af1f509 166 ;; Build the command string.
9c32788e 167 (if c-macro-prompt-flag
89fb82d6 168 (setq c-macro-cppflags
4af1f509 169 (read-string "Preprocessor arguments: "
89fb82d6 170 c-macro-cppflags)))
4af1f509
RS
171 ;; Decide where to display output.
172 (if (and subst
6c61e6a9 173 (and buffer-read-only (not inhibit-read-only))
4af1f509
RS
174 (not (eq inbuf displaybuf)))
175 (progn
176 (message
177 "Buffer is read only: displaying expansion in alternate window")
178 (sit-for 2)
179 (setq subst nil)
180 (or displaybuf
181 (setq displaybuf (get-buffer-create c-macro-buffer-name)))))
182 ;; Expand the macro and output it.
89fb82d6
RS
183 (setq expansion (c-macro-expansion start end
184 (concat c-macro-preprocessor " "
074521be 185 c-macro-cppflags) t))
4af1f509
RS
186 (if subst
187 (let ((exchange (= (point) start)))
188 (delete-region start end)
189 (insert expansion)
190 (if exchange
191 (exchange-point-and-mark)))
192 (set-buffer displaybuf)
193 (setq buffer-read-only nil)
3332766c 194 (buffer-disable-undo displaybuf)
4af1f509
RS
195 (erase-buffer)
196 (insert expansion)
197 (set-buffer-modified-p nil)
198 (if (string= "" expansion)
199 (message "Null expansion")
89fb82d6 200 (c-macro-display-buffer))
4af1f509 201 (setq buffer-read-only t)
89fb82d6 202 (setq buffer-auto-save-file-name nil)
4af1f509
RS
203 (bury-buffer displaybuf))))
204
205
206;; Display the current buffer in a window which is either just large
207;; enough to contain the entire buffer, or half the size of the
89fb82d6
RS
208;; screen, whichever is smaller. Do not select the new
209;; window.
4af1f509
RS
210;;
211;; Several factors influence window resizing so that the window is
212;; sized optimally if it is created anew, and so that it is messed
213;; with minimally if it has been created by the user. If the window
214;; chosen for display exists already but contains something else, the
215;; window is not re-sized. If the window already contains the current
216;; buffer, it is never shrunk, but possibly expanded. Finally, if the
9c32788e 217;; variable c-macro-shrink-window-flag is nil the window size is *never*
4af1f509 218;; changed.
89fb82d6 219(defun c-macro-display-buffer ()
4af1f509
RS
220 (goto-char (point-min))
221 (c-mode)
4af1f509
RS
222 (let ((oldwinheight (window-height))
223 (alreadythere ;the window was already there
224 (get-buffer-window (current-buffer)))
4ff3fcc7 225 (popped nil)) ;the window popped changing the layout
4af1f509
RS
226 (or alreadythere
227 (progn
228 (display-buffer (current-buffer) t)
229 (setq popped (/= oldwinheight (window-height)))))
9c32788e 230 (if (and c-macro-shrink-window-flag ;user wants fancy shrinking :\)
4af1f509
RS
231 (or alreadythere popped))
232 ;; Enlarge up to half screen, or shrink properly.
233 (let ((oldwin (selected-window))
234 (minheight 0)
235 (maxheight 0))
236 (save-excursion
237 (select-window (get-buffer-window (current-buffer)))
238 (setq minheight (if alreadythere
239 (window-height)
240 window-min-height))
32cdf3f6 241 (setq maxheight (/ (frame-height) 2))
4af1f509
RS
242 (enlarge-window (- (min maxheight
243 (max minheight
89fb82d6 244 (+ 2 (vertical-motion (point-max)))))
4af1f509
RS
245 (window-height)))
246 (goto-char (point-min))
247 (select-window oldwin))))))
248
249
074521be 250(defun c-macro-expansion (start end cppcommand &optional display)
9c32788e 251 "Run a preprocessor on region and return the output as a string.
89fb82d6
RS
252Expand the region between START and END in the current buffer using
253the shell command CPPCOMMAND (e.g. \"/lib/cpp -C -DDEBUG\").
074521be
RS
254Be sure to use a -C (don't strip comments) or equivalent option.
255Optional arg DISPLAY non-nil means show messages in the echo area."
4af1f509
RS
256
257;; Copy the current buffer's contents to a temporary hidden buffer.
258;; Delete from END to end of buffer. Insert a preprocessor #line
259;; directive at START and after each #endif following START that are
260;; not inside a comment or a string. Put all the strings thus
261;; inserted (without the "line" substring) in a list named linelist.
262;; If START is inside a comment, prepend "*/" and append "/*" to the
263;; #line directive. If inside a string, prepend and append "\"".
264;; Preprocess the buffer contents, then look for all the lines stored
265;; in linelist starting from end of buffer. The last line so found is
266;; where START was, so return the substring from point to end of
4ff3fcc7 267;; buffer.
4af1f509
RS
268 (let ((inbuf (current-buffer))
269 (outbuf (get-buffer-create " *C Macro Expansion*"))
270 (filename (if (and buffer-file-name
271 (string-match (regexp-quote default-directory)
272 buffer-file-name))
273 (substring buffer-file-name (match-end 0))
274 (buffer-name)))
074521be
RS
275 (mymsg (format "Invoking %s%s%s on region..."
276 c-macro-preprocessor
277 (if (string= "" c-macro-cppflags) "" " ")
278 c-macro-cppflags))
32cdf3f6 279 (uniquestring "??? !!! ??? start of c-macro expansion ??? !!! ???")
074521be 280 (startlinenum 0)
4af1f509 281 (linenum 0)
074521be 282 (startstat ())
440c10f8 283 (startmarker "")
3332766c 284 (exit-status 0)
767d12f2 285 (tempname (make-temp-file
fc416240 286 (expand-file-name "cmacexp"
77f90711
EZ
287 (or small-temporary-file-directory
288 temporary-file-directory)))))
4af1f509
RS
289 (unwind-protect
290 (save-excursion
291 (save-restriction
292 (widen)
32cdf3f6
KH
293 (let ((in-syntax-table (syntax-table)))
294 (set-buffer outbuf)
295 (setq buffer-read-only nil)
296 (erase-buffer)
297 (set-syntax-table in-syntax-table))
4af1f509
RS
298 (insert-buffer-substring inbuf 1 end))
299
300 ;; We have copied inbuf to outbuf. Point is at end of
32cdf3f6
KH
301 ;; outbuf. Inset a newline at the end, so cpp can correctly
302 ;; parse a token ending at END.
303 (insert "\n")
4af1f509 304
074521be
RS
305 ;; Save sexp status and line number at START.
306 (setq startstat (parse-partial-sexp 1 start))
307 (setq startlinenum (+ (count-lines 1 (point))
308 (if (bolp) 1 0)))
309
4af1f509 310 ;; Now we insert the #line directives after all #endif or
074521be
RS
311 ;; #else following START going backward, so the lines we
312 ;; insert don't change the line numbers.
4af1f509 313 ;(switch-to-buffer outbuf) (debug) ;debugging instructions
074521be 314 (goto-char (point-max))
4af1f509 315 (while (re-search-backward "\n#\\(endif\\|else\\)\\>" start 'move)
074521be
RS
316 (if (equal (nthcdr 3 (parse-partial-sexp start (point)
317 nil nil startstat))
9c32788e 318 '(nil nil nil 0 nil)) ;neither in string nor in
074521be 319 ;comment nor after quote
4af1f509
RS
320 (progn
321 (goto-char (match-end 0))
074521be
RS
322 (setq linenum (+ startlinenum
323 (count-lines start (point))))
324 (insert (format "\n#line %d \"%s\"\n" linenum filename))
325 (goto-char (match-beginning 0)))))
326
327 ;; Now we are at START. Insert the first #line directive.
328 ;; This must work even inside a string or comment, or after a
4af1f509 329 ;; quote.
074521be
RS
330 (let* ((startinstring (nth 3 startstat))
331 (startincomment (nth 4 startstat))
332 (startafterquote (nth 5 startstat))
333 (startinbcomment (nth 7 startstat)))
334 (insert (if startafterquote " " "")
335 (cond (startinstring
336 (char-to-string startinstring))
337 (startincomment "*/")
338 (""))
074521be 339 (setq startmarker
521fffcd 340 (concat "\n" uniquestring
074521be
RS
341 (cond (startinstring
342 (char-to-string startinstring))
343 (startincomment "/*")
344 (startinbcomment "//"))
521fffcd
FP
345 (if startafterquote "\\")))
346 (format "\n#line %d \"%s\"\n" startlinenum filename)))
4af1f509
RS
347
348 ;; Call the preprocessor.
29a4e67d 349 (if display (message "%s" mymsg))
440c10f8 350 (setq exit-status
68dff3ca
RS
351 (call-process-region 1 (point-max)
352 shell-file-name
353 t (list t tempname) nil "-c"
354 cppcommand))
29a4e67d 355 (if display (message "%s" (concat mymsg "done")))
eb426f3a
RS
356 (if (= (buffer-size) 0)
357 ;; Empty output is normal after a fatal error.
358 (insert "\nPreprocessor produced no output\n")
359 ;; Find and delete the mark of the start of the expansion.
360 ;; Look for `# nn "file.c"' lines and delete them.
361 (goto-char (point-min))
362 (search-forward startmarker)
363 (delete-region 1 (point)))
074521be
RS
364 (while (re-search-forward (concat "^# [0-9]+ \""
365 (regexp-quote filename)
366 "\"") nil t)
367 (beginning-of-line)
368 (let ((beg (point)))
369 (forward-line 1)
370 (delete-region beg (point))))
4af1f509 371
440c10f8 372 ;; If CPP got errors, show them at the beginning.
68dff3ca
RS
373 ;; MS-DOS shells don't return the exit code of their children.
374 ;; Look at the size of the error message file instead, but
375 ;; don't punish those MS-DOS users who have a shell that does
376 ;; return an error code.
377 (or (and (or (not (boundp 'msdos-shells))
378 (not (member (file-name-nondirectory shell-file-name)
379 msdos-shells)))
380 (eq exit-status 0))
381 (zerop (nth 7 (file-attributes (expand-file-name tempname))))
440c10f8
RS
382 (progn
383 (goto-char (point-min))
68dff3ca
RS
384 ;; Put the messages inside a comment, so they won't get in
385 ;; the way of font-lock, highlighting etc.
386 (insert
387 (format "/* Preprocessor terminated with status %s\n\n Messages from `%s\':\n\n"
388 exit-status cppcommand))
389 (goto-char (+ (point)
390 (nth 1 (insert-file-contents tempname))))
391 (insert "\n\n*/\n")))
440c10f8
RS
392 (delete-file tempname)
393
4af1f509
RS
394 ;; Compute the return value, keeping in account the space
395 ;; inserted at the end of the buffer.
074521be 396 (buffer-substring 1 (max 1 (- (point-max) 1))))
4af1f509
RS
397
398 ;; Cleanup.
399 (kill-buffer outbuf))))
400
cbee283d 401;; arch-tag: 4f20253c-71ef-4e6d-a774-19087060910e
89fb82d6 402;;; cmacexp.el ends here