1 ;;; cmacexp.el --- expand C macros in a region
3 ;; Copyright (C) 1992, 1994, 1996 Free Software Foundation, Inc.
5 ;; Author: Francesco Potorti` <pot@cnuce.cnr.it>
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.
26 ;; USAGE =============================================================
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.
32 ;; When called with a C-u prefix, c-macro-expand replaces the selected
33 ;; region with the expansion. Both the preprocessor name and the
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
41 ;; A c-macro-expansion function is provided for non-interactive use.
43 ;; INSTALLATION ======================================================
45 ;; Put the following in your ~/.emacs file.
47 ;; If you want the *Macroexpansion* window to be not higher than
49 ;;(setq c-macro-shrink-window-flag t)
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")
56 ;; If you often use a particular set of flags:
57 ;;(setq c-macro-cppflags "-I /usr/include/local -DDEBUG"
59 ;; If you want the "Preprocessor arguments: " prompt:
60 ;;(setq c-macro-prompt-flag t)
62 ;; BUG REPORTS =======================================================
64 ;; Please report bugs, suggestions, complaints and so on to
65 ;; pot@cnuce.cnr.it (Francesco Potorti`).
67 ;; IMPROVEMENTS OVER emacs 18.xx cmacexp.el ==========================
69 ;; - A lot of user and programmer visible changes. See above.
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.
76 ;; ACKNOWLEDGEMENTS ==================================================
78 ;; A lot of thanks to Don Maszle who did a great work of testing, bug
79 ;; reporting and suggestion of new features. This work has been
80 ;; partially inspired by Don Maszle and Jonathan Segal's.
82 ;; BUGS ==============================================================
84 ;; If the start point of the region is inside a macro definition the
85 ;; macro expansion is often inaccurate.
93 "Expand C macros in a region."
97 (defcustom c-macro-shrink-window-flag nil
98 "*Non-nil means shrink the *Macroexpansion* window to fit its contents."
102 (defcustom c-macro-prompt-flag nil
103 "*Non-nil makes `c-macro-expand' prompt for preprocessor arguments."
107 (defcustom c-macro-preprocessor
108 ;; Cannot rely on standard directory on MS-DOS to find CPP.
109 (cond ((eq system-type
'ms-dos
) "cpp -C")
110 ;; Solaris has it in an unusual place.
111 ((and (string-match "^[^-]*-[^-]*-\\(solaris\\|sunos5\\)"
112 system-configuration
)
113 (file-exists-p "/opt/SUNWspro/SC3.0.1/bin/acomp"))
114 "/opt/SUNWspro/SC3.0.1/bin/acomp -C -E")
115 ((file-exists-p "/usr/ccs/lib/cpp") "/usr/ccs/lib/cpp -C")
117 "The preprocessor used by the cmacexp package.
119 If you change this, be sure to preserve the `-C' (don't strip comments)
120 option, or to set an equivalent one."
124 (defcustom c-macro-cppflags
""
125 "*Preprocessor flags used by `c-macro-expand'."
129 (defconst c-macro-buffer-name
"*Macroexpansion*")
132 (defun c-macro-expand (start end subst
)
133 "Expand C macros in the region, using the C preprocessor.
134 Normally display output in temp buffer, but
135 prefix arg means replace the region with it.
137 `c-macro-preprocessor' specifies the preprocessor to use.
138 Prompt for arguments to the preprocessor \(e.g. `-DDEBUG -I ./include')
139 if the user option `c-macro-prompt-flag' is non-nil.
141 Noninteractive args are START, END, SUBST.
142 For use inside Lisp programs, see also `c-macro-expansion'."
145 (let ((inbuf (current-buffer))
146 (displaybuf (if subst
147 (get-buffer c-macro-buffer-name
)
148 (get-buffer-create c-macro-buffer-name
)))
150 ;; Build the command string.
151 (if c-macro-prompt-flag
152 (setq c-macro-cppflags
153 (read-string "Preprocessor arguments: "
155 ;; Decide where to display output.
157 (and buffer-read-only
(not inhibit-read-only
))
158 (not (eq inbuf displaybuf
)))
161 "Buffer is read only: displaying expansion in alternate window")
165 (setq displaybuf
(get-buffer-create c-macro-buffer-name
)))))
166 ;; Expand the macro and output it.
167 (setq expansion
(c-macro-expansion start end
168 (concat c-macro-preprocessor
" "
169 c-macro-cppflags
) t
))
171 (let ((exchange (= (point) start
)))
172 (delete-region start end
)
175 (exchange-point-and-mark)))
176 (set-buffer displaybuf
)
177 (setq buffer-read-only nil
)
178 (buffer-disable-undo displaybuf
)
181 (set-buffer-modified-p nil
)
182 (if (string= "" expansion
)
183 (message "Null expansion")
184 (c-macro-display-buffer))
185 (setq buffer-read-only t
)
186 (setq buffer-auto-save-file-name nil
)
187 (bury-buffer displaybuf
))))
190 ;; Display the current buffer in a window which is either just large
191 ;; enough to contain the entire buffer, or half the size of the
192 ;; screen, whichever is smaller. Do not select the new
195 ;; Several factors influence window resizing so that the window is
196 ;; sized optimally if it is created anew, and so that it is messed
197 ;; with minimally if it has been created by the user. If the window
198 ;; chosen for display exists already but contains something else, the
199 ;; window is not re-sized. If the window already contains the current
200 ;; buffer, it is never shrunk, but possibly expanded. Finally, if the
201 ;; variable c-macro-shrink-window-flag is nil the window size is *never*
203 (defun c-macro-display-buffer ()
204 (goto-char (point-min))
206 (let ((oldwinheight (window-height))
207 (alreadythere ;the window was already there
208 (get-buffer-window (current-buffer)))
209 (popped nil
)) ;the window popped changing the layout
212 (display-buffer (current-buffer) t
)
213 (setq popped
(/= oldwinheight
(window-height)))))
214 (if (and c-macro-shrink-window-flag
;user wants fancy shrinking :\)
215 (or alreadythere popped
))
216 ;; Enlarge up to half screen, or shrink properly.
217 (let ((oldwin (selected-window))
221 (select-window (get-buffer-window (current-buffer)))
222 (setq minheight
(if alreadythere
225 (setq maxheight
(/ (frame-height) 2))
226 (enlarge-window (- (min maxheight
228 (+ 2 (vertical-motion (point-max)))))
230 (goto-char (point-min))
231 (select-window oldwin
))))))
234 (defun c-macro-expansion (start end cppcommand
&optional display
)
235 "Run a preprocessor on region and return the output as a string.
236 Expand the region between START and END in the current buffer using
237 the shell command CPPCOMMAND (e.g. \"/lib/cpp -C -DDEBUG\").
238 Be sure to use a -C (don't strip comments) or equivalent option.
239 Optional arg DISPLAY non-nil means show messages in the echo area."
241 ;; Copy the current buffer's contents to a temporary hidden buffer.
242 ;; Delete from END to end of buffer. Insert a preprocessor #line
243 ;; directive at START and after each #endif following START that are
244 ;; not inside a comment or a string. Put all the strings thus
245 ;; inserted (without the "line" substring) in a list named linelist.
246 ;; If START is inside a comment, prepend "*/" and append "/*" to the
247 ;; #line directive. If inside a string, prepend and append "\"".
248 ;; Preprocess the buffer contents, then look for all the lines stored
249 ;; in linelist starting from end of buffer. The last line so found is
250 ;; where START was, so return the substring from point to end of
252 (let ((inbuf (current-buffer))
253 (outbuf (get-buffer-create " *C Macro Expansion*"))
254 (filename (if (and buffer-file-name
255 (string-match (regexp-quote default-directory
)
257 (substring buffer-file-name
(match-end 0))
259 (mymsg (format "Invoking %s%s%s on region..."
261 (if (string= "" c-macro-cppflags
) "" " ")
263 (uniquestring "??? !!! ??? start of c-macro expansion ??? !!! ???")
269 (tempname (make-temp-file
270 (expand-file-name "cmacexp"
271 (or small-temporary-file-directory
272 temporary-file-directory
)))))
277 (let ((in-syntax-table (syntax-table)))
279 (setq buffer-read-only nil
)
281 (set-syntax-table in-syntax-table
))
282 (insert-buffer-substring inbuf
1 end
))
284 ;; We have copied inbuf to outbuf. Point is at end of
285 ;; outbuf. Inset a newline at the end, so cpp can correctly
286 ;; parse a token ending at END.
289 ;; Save sexp status and line number at START.
290 (setq startstat
(parse-partial-sexp 1 start
))
291 (setq startlinenum
(+ (count-lines 1 (point))
294 ;; Now we insert the #line directives after all #endif or
295 ;; #else following START going backward, so the lines we
296 ;; insert don't change the line numbers.
297 ;(switch-to-buffer outbuf) (debug) ;debugging instructions
298 (goto-char (point-max))
299 (while (re-search-backward "\n#\\(endif\\|else\\)\\>" start
'move
)
300 (if (equal (nthcdr 3 (parse-partial-sexp start
(point)
302 '(nil nil nil
0 nil
)) ;neither in string nor in
303 ;comment nor after quote
305 (goto-char (match-end 0))
306 (setq linenum
(+ startlinenum
307 (count-lines start
(point))))
308 (insert (format "\n#line %d \"%s\"\n" linenum filename
))
309 (goto-char (match-beginning 0)))))
311 ;; Now we are at START. Insert the first #line directive.
312 ;; This must work even inside a string or comment, or after a
314 (let* ((startinstring (nth 3 startstat
))
315 (startincomment (nth 4 startstat
))
316 (startafterquote (nth 5 startstat
))
317 (startinbcomment (nth 7 startstat
)))
318 (insert (if startafterquote
" " "")
320 (char-to-string startinstring
))
321 (startincomment "*/")
324 (concat "\n" uniquestring
326 (char-to-string startinstring
))
327 (startincomment "/*")
328 (startinbcomment "//"))
329 (if startafterquote
"\\")))
330 (format "\n#line %d \"%s\"\n" startlinenum filename
)))
332 ;; Call the preprocessor.
333 (if display
(message mymsg
))
335 (call-process-region 1 (point-max)
337 t
(list t tempname
) nil
"-c"
339 (if display
(message (concat mymsg
"done")))
340 (if (= (buffer-size) 0)
341 ;; Empty output is normal after a fatal error.
342 (insert "\nPreprocessor produced no output\n")
343 ;; Find and delete the mark of the start of the expansion.
344 ;; Look for `# nn "file.c"' lines and delete them.
345 (goto-char (point-min))
346 (search-forward startmarker
)
347 (delete-region 1 (point)))
348 (while (re-search-forward (concat "^# [0-9]+ \""
349 (regexp-quote filename
)
354 (delete-region beg
(point))))
356 ;; If CPP got errors, show them at the beginning.
357 ;; MS-DOS shells don't return the exit code of their children.
358 ;; Look at the size of the error message file instead, but
359 ;; don't punish those MS-DOS users who have a shell that does
360 ;; return an error code.
361 (or (and (or (not (boundp 'msdos-shells
))
362 (not (member (file-name-nondirectory shell-file-name
)
365 (zerop (nth 7 (file-attributes (expand-file-name tempname
))))
367 (goto-char (point-min))
368 ;; Put the messages inside a comment, so they won't get in
369 ;; the way of font-lock, highlighting etc.
371 (format "/* Preprocessor terminated with status %s\n\n Messages from `%s\':\n\n"
372 exit-status cppcommand
))
373 (goto-char (+ (point)
374 (nth 1 (insert-file-contents tempname
))))
375 (insert "\n\n*/\n")))
376 (delete-file tempname
)
378 ;; Compute the return value, keeping in account the space
379 ;; inserted at the end of the buffer.
380 (buffer-substring 1 (max 1 (- (point-max) 1))))
383 (kill-buffer outbuf
))))
385 ;;; cmacexp.el ends here