1 ;;; cmacexp.el --- expand C macros in a region
3 ;; Copyright (C) 1992, 1994, 1996, 2000 Free Software Foundation, Inc.
5 ;; Author: Francesco Potorti` <pot@gnu.org>
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
28 ;; USAGE =============================================================
30 ;; In C mode C-C C-e is bound to c-macro-expand. The result of the
31 ;; expansion is put in a separate buffer. A user option allows the
32 ;; window displaying the buffer to be optimally sized.
34 ;; When called with a C-u prefix, c-macro-expand replaces the selected
35 ;; region with the expansion. Both the preprocessor name and the
36 ;; initial flag can be set by the user. If c-macro-prompt-flag is set
37 ;; to a non-nil value the user is offered to change the options to the
38 ;; preprocessor each time c-macro-expand is invoked. Preprocessor
39 ;; arguments default to the last ones entered. If c-macro-prompt-flag
40 ;; is nil, one must use M-x set-variable to set a different value for
43 ;; A c-macro-expansion function is provided for non-interactive use.
45 ;; INSTALLATION ======================================================
47 ;; Put the following in your ~/.emacs file.
49 ;; If you want the *Macroexpansion* window to be not higher than
51 ;;(setq c-macro-shrink-window-flag t)
53 ;; If you use a preprocessor other than /lib/cpp (be careful to set a
54 ;; -C option or equivalent in order to make the preprocessor not to
55 ;; strip the comments):
56 ;;(setq c-macro-preprocessor "gpp -C")
58 ;; If you often use a particular set of flags:
59 ;;(setq c-macro-cppflags "-I /usr/include/local -DDEBUG"
61 ;; If you want the "Preprocessor arguments: " prompt:
62 ;;(setq c-macro-prompt-flag t)
64 ;; BUG REPORTS =======================================================
66 ;; Please report bugs, suggestions, complaints and so on to
67 ;; pot@gnu.org (Francesco Potorti`).
69 ;; IMPROVEMENTS OVER emacs 18.xx cmacexp.el ==========================
71 ;; - A lot of user and programmer visible changes. See above.
72 ;; - #line directives are inserted, so __LINE__ and __FILE__ are
73 ;; correctly expanded. Works even with START inside a string, a
74 ;; comment or a region #ifdef'd away by cpp. cpp is invoked with -C,
75 ;; making comments visible in the expansion.
76 ;; - All work is done in core memory, no need for temporary files.
78 ;; ACKNOWLEDGEMENTS ==================================================
80 ;; A lot of thanks to Don Maszle who did a great work of testing, bug
81 ;; reporting and suggestion of new features. This work has been
82 ;; partially inspired by Don Maszle and Jonathan Segal's.
84 ;; BUGS ==============================================================
86 ;; If the start point of the region is inside a macro definition the
87 ;; macro expansion is often inaccurate.
96 "Expand C macros in a region."
100 (defcustom c-macro-shrink-window-flag nil
101 "*Non-nil means shrink the *Macroexpansion* window to fit its contents."
105 (defcustom c-macro-prompt-flag nil
106 "*Non-nil makes `c-macro-expand' prompt for preprocessor arguments."
110 (defcustom c-macro-preprocessor
111 (cond ;; Solaris has it in an unusual place.
112 ((and (string-match "^[^-]*-[^-]*-\\(solaris\\|sunos5\\)"
113 system-configuration)
114 (file-exists-p "/opt/SUNWspro/SC3.0.1/bin/acomp"))
115 "/opt/SUNWspro/SC3.0.1/bin/acomp -C -E")
116 ((locate-file "/usr/ccs/lib/cpp"
117 '("/") exec-suffixes 'file-executable-p)
118 "/usr/ccs/lib/cpp -C")
119 ((locate-file "/lib/cpp"
120 '("/") exec-suffixes 'file-executable-p)
122 ;; On some systems, we cannot rely on standard directories to
123 ;; find CPP. In fact, we cannot rely on having cpp, either,
124 ;; in some GCC versions.
125 ((locate-file "cpp" exec-path exec-suffixes 'file-executable-p)
127 (t "gcc -E -C -o - -"))
128 "The preprocessor used by the cmacexp package.
130 If you change this, be sure to preserve the `-C' (don't strip comments)
131 option, or to set an equivalent one."
135 (defcustom c-macro-cppflags ""
136 "*Preprocessor flags used by `c-macro-expand'."
140 (defconst c-macro-buffer-name "*Macroexpansion*")
143 (defun c-macro-expand (start end subst)
144 "Expand C macros in the region, using the C preprocessor.
145 Normally display output in temp buffer, but
146 prefix arg means replace the region with it.
148 `c-macro-preprocessor' specifies the preprocessor to use.
149 Prompt for arguments to the preprocessor \(e.g. `-DDEBUG -I ./include')
150 if the user option `c-macro-prompt-flag' is non-nil.
152 Noninteractive args are START, END, SUBST.
153 For use inside Lisp programs, see also `c-macro-expansion'."
156 (let ((inbuf (current-buffer))
157 (displaybuf (if subst
158 (get-buffer c-macro-buffer-name)
159 (get-buffer-create c-macro-buffer-name)))
161 ;; Build the command string.
162 (if c-macro-prompt-flag
163 (setq c-macro-cppflags
164 (read-string "Preprocessor arguments: "
166 ;; Decide where to display output.
168 (and buffer-read-only (not inhibit-read-only))
169 (not (eq inbuf displaybuf)))
172 "Buffer is read only: displaying expansion in alternate window")
176 (setq displaybuf (get-buffer-create c-macro-buffer-name)))))
177 ;; Expand the macro and output it.
178 (setq expansion (c-macro-expansion start end
179 (concat c-macro-preprocessor " "
180 c-macro-cppflags) t))
182 (let ((exchange (= (point) start)))
183 (delete-region start end)
186 (exchange-point-and-mark)))
187 (set-buffer displaybuf)
188 (setq buffer-read-only nil)
189 (buffer-disable-undo displaybuf)
192 (set-buffer-modified-p nil)
193 (if (string= "" expansion)
194 (message "Null expansion")
195 (c-macro-display-buffer))
196 (setq buffer-read-only t)
197 (setq buffer-auto-save-file-name nil)
198 (bury-buffer displaybuf))))
201 ;; Display the current buffer in a window which is either just large
202 ;; enough to contain the entire buffer, or half the size of the
203 ;; screen, whichever is smaller. Do not select the new
206 ;; Several factors influence window resizing so that the window is
207 ;; sized optimally if it is created anew, and so that it is messed
208 ;; with minimally if it has been created by the user. If the window
209 ;; chosen for display exists already but contains something else, the
210 ;; window is not re-sized. If the window already contains the current
211 ;; buffer, it is never shrunk, but possibly expanded. Finally, if the
212 ;; variable c-macro-shrink-window-flag is nil the window size is *never*
214 (defun c-macro-display-buffer ()
215 (goto-char (point-min))
217 (let ((oldwinheight (window-height))
218 (alreadythere ;the window was already there
219 (get-buffer-window (current-buffer)))
220 (popped nil)) ;the window popped changing the layout
223 (display-buffer (current-buffer) t)
224 (setq popped (/= oldwinheight (window-height)))))
225 (if (and c-macro-shrink-window-flag ;user wants fancy shrinking :\)
226 (or alreadythere popped))
227 ;; Enlarge up to half screen, or shrink properly.
228 (let ((oldwin (selected-window))
232 (select-window (get-buffer-window (current-buffer)))
233 (setq minheight (if alreadythere
236 (setq maxheight (/ (frame-height) 2))
237 (enlarge-window (- (min maxheight
239 (+ 2 (vertical-motion (point-max)))))
241 (goto-char (point-min))
242 (select-window oldwin))))))
245 (defun c-macro-expansion (start end cppcommand &optional display)
246 "Run a preprocessor on region and return the output as a string.
247 Expand the region between START and END in the current buffer using
248 the shell command CPPCOMMAND (e.g. \"/lib/cpp -C -DDEBUG\").
249 Be sure to use a -C (don't strip comments) or equivalent option.
250 Optional arg DISPLAY non-nil means show messages in the echo area."
252 ;; Copy the current buffer's contents to a temporary hidden buffer.
253 ;; Delete from END to end of buffer. Insert a preprocessor #line
254 ;; directive at START and after each #endif following START that are
255 ;; not inside a comment or a string. Put all the strings thus
256 ;; inserted (without the "line" substring) in a list named linelist.
257 ;; If START is inside a comment, prepend "*/" and append "/*" to the
258 ;; #line directive. If inside a string, prepend and append "\"".
259 ;; Preprocess the buffer contents, then look for all the lines stored
260 ;; in linelist starting from end of buffer. The last line so found is
261 ;; where START was, so return the substring from point to end of
263 (let ((inbuf (current-buffer))
264 (outbuf (get-buffer-create " *C Macro Expansion*"))
265 (filename (if (and buffer-file-name
266 (string-match (regexp-quote default-directory)
268 (substring buffer-file-name (match-end 0))
270 (mymsg (format "Invoking %s%s%s on region..."
272 (if (string= "" c-macro-cppflags) "" " ")
274 (uniquestring "??? !!! ??? start of c-macro expansion ??? !!! ???")
280 (tempname (make-temp-file
281 (expand-file-name "cmacexp"
282 (or small-temporary-file-directory
283 temporary-file-directory)))))
288 (let ((in-syntax-table (syntax-table)))
290 (setq buffer-read-only nil)
292 (set-syntax-table in-syntax-table))
293 (insert-buffer-substring inbuf 1 end))
295 ;; We have copied inbuf to outbuf. Point is at end of
296 ;; outbuf. Inset a newline at the end, so cpp can correctly
297 ;; parse a token ending at END.
300 ;; Save sexp status and line number at START.
301 (setq startstat (parse-partial-sexp 1 start))
302 (setq startlinenum (+ (count-lines 1 (point))
305 ;; Now we insert the #line directives after all #endif or
306 ;; #else following START going backward, so the lines we
307 ;; insert don't change the line numbers.
308 ;(switch-to-buffer outbuf) (debug) ;debugging instructions
309 (goto-char (point-max))
310 (while (re-search-backward "\n#\\(endif\\|else\\)\\>" start 'move)
311 (if (equal (nthcdr 3 (parse-partial-sexp start (point)
313 '(nil nil nil 0 nil)) ;neither in string nor in
314 ;comment nor after quote
316 (goto-char (match-end 0))
317 (setq linenum (+ startlinenum
318 (count-lines start (point))))
319 (insert (format "\n#line %d \"%s\"\n" linenum filename))
320 (goto-char (match-beginning 0)))))
322 ;; Now we are at START. Insert the first #line directive.
323 ;; This must work even inside a string or comment, or after a
325 (let* ((startinstring (nth 3 startstat))
326 (startincomment (nth 4 startstat))
327 (startafterquote (nth 5 startstat))
328 (startinbcomment (nth 7 startstat)))
329 (insert (if startafterquote " " "")
331 (char-to-string startinstring))
332 (startincomment "*/")
335 (concat "\n" uniquestring
337 (char-to-string startinstring))
338 (startincomment "/*")
339 (startinbcomment "//"))
340 (if startafterquote "\\")))
341 (format "\n#line %d \"%s\"\n" startlinenum filename)))
343 ;; Call the preprocessor.
344 (if display (message mymsg))
346 (call-process-region 1 (point-max)
348 t (list t tempname) nil "-c"
350 (if display (message (concat mymsg "done")))
351 (if (= (buffer-size) 0)
352 ;; Empty output is normal after a fatal error.
353 (insert "\nPreprocessor produced no output\n")
354 ;; Find and delete the mark of the start of the expansion.
355 ;; Look for `# nn "file.c"' lines and delete them.
356 (goto-char (point-min))
357 (search-forward startmarker)
358 (delete-region 1 (point)))
359 (while (re-search-forward (concat "^# [0-9]+ \""
360 (regexp-quote filename)
365 (delete-region beg (point))))
367 ;; If CPP got errors, show them at the beginning.
368 ;; MS-DOS shells don't return the exit code of their children.
369 ;; Look at the size of the error message file instead, but
370 ;; don't punish those MS-DOS users who have a shell that does
371 ;; return an error code.
372 (or (and (or (not (boundp 'msdos-shells))
373 (not (member (file-name-nondirectory shell-file-name)
376 (zerop (nth 7 (file-attributes (expand-file-name tempname))))
378 (goto-char (point-min))
379 ;; Put the messages inside a comment, so they won't get in
380 ;; the way of font-lock, highlighting etc.
382 (format "/* Preprocessor terminated with status %s\n\n Messages from `%s\':\n\n"
383 exit-status cppcommand))
384 (goto-char (+ (point)
385 (nth 1 (insert-file-contents tempname))))
386 (insert "\n\n*/\n")))
387 (delete-file tempname)
389 ;; Compute the return value, keeping in account the space
390 ;; inserted at the end of the buffer.
391 (buffer-substring 1 (max 1 (- (point-max) 1))))
394 (kill-buffer outbuf))))
396 ;;; arch-tag: 4f20253c-71ef-4e6d-a774-19087060910e
397 ;;; cmacexp.el ends here