1 ;;; cmacexp.el --- expand C macros in a region
3 ;; Copyright (C) 1992, 1994, 1996, 2000-2015 Free Software Foundation,
6 ;; Author: Francesco Potortì <pot@gnu.org>
10 ;; Yoni Rabkin <yoni@rabkins.net> contacted the maintainer of this
11 ;; file, and the maintainer agreed that when a bug is filed in the
12 ;; Emacs bug reporting system against this file, a copy of the bug
13 ;; report be sent to the maintainer's email address. However, the
14 ;; maintainer prefers not to be the only person maintaining this file
17 ;; This file is part of GNU Emacs.
19 ;; GNU Emacs is free software: you can redistribute it and/or modify
20 ;; it under the terms of the GNU General Public License as published by
21 ;; the Free Software Foundation, either version 3 of the License, or
22 ;; (at your option) any later version.
24 ;; GNU Emacs is distributed in the hope that it will be useful,
25 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
26 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 ;; GNU General Public License for more details.
29 ;; You should have received a copy of the GNU General Public License
30 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
34 ;; USAGE =============================================================
36 ;; In C mode C-C C-e is bound to c-macro-expand. The result of the
37 ;; expansion is put in a separate buffer. A user option allows the
38 ;; window displaying the buffer to be optimally sized.
40 ;; When called with a C-u prefix, c-macro-expand replaces the selected
41 ;; region with the expansion. Both the preprocessor name and the
42 ;; initial flag can be set by the user. If c-macro-prompt-flag is set
43 ;; to a non-nil value the user is offered to change the options to the
44 ;; preprocessor each time c-macro-expand is invoked. Preprocessor
45 ;; arguments default to the last ones entered. If c-macro-prompt-flag
46 ;; is nil, one must use M-x set-variable to set a different value for
49 ;; A c-macro-expansion function is provided for non-interactive use.
51 ;; INSTALLATION ======================================================
53 ;; Put the following in your init file.
55 ;; If you want the *Macroexpansion* window to be not higher than
57 ;;(setq c-macro-shrink-window-flag t)
59 ;; If you use a preprocessor other than /lib/cpp (be careful to set a
60 ;; -C option or equivalent in order to make the preprocessor not to
61 ;; strip the comments):
62 ;;(setq c-macro-preprocessor "gpp -C")
64 ;; If you often use a particular set of flags:
65 ;;(setq c-macro-cppflags "-I /usr/include/local -DDEBUG"
67 ;; If you want the "Preprocessor arguments: " prompt:
68 ;;(setq c-macro-prompt-flag t)
70 ;; BUG REPORTS =======================================================
72 ;; Please report bugs, suggestions, complaints and so on to
73 ;; bug-gnu-emacs@gnu.org and pot@gnu.org (Francesco Potortì).
75 ;; IMPROVEMENTS OVER emacs 18.xx cmacexp.el ==========================
77 ;; - A lot of user and programmer visible changes. See above.
78 ;; - #line directives are inserted, so __LINE__ and __FILE__ are
79 ;; correctly expanded. Works even with START inside a string, a
80 ;; comment or a region #ifdef'd away by cpp. cpp is invoked with -C,
81 ;; making comments visible in the expansion.
82 ;; - All work is done in core memory, no need for temporary files.
84 ;; ACKNOWLEDGMENTS ===================================================
86 ;; A lot of thanks to Don Maszle who did a great work of testing, bug
87 ;; reporting and suggestion of new features. This work has been
88 ;; partially inspired by Don Maszle and Jonathan Segal's.
90 ;; BUGS ==============================================================
92 ;; If the start point of the region is inside a macro definition the
93 ;; macro expansion is often inaccurate.
101 (defvar msdos-shells
)
104 (defgroup c-macro nil
105 "Expand C macros in a region."
109 (defcustom c-macro-shrink-window-flag nil
110 "Non-nil means shrink the *Macroexpansion* window to fit its contents."
114 (defcustom c-macro-prompt-flag nil
115 "Non-nil makes `c-macro-expand' prompt for preprocessor arguments."
119 (defcustom c-macro-preprocessor
120 (cond ;; Solaris has it in an unusual place.
121 ((and (string-match "^[^-]*-[^-]*-\\(solaris\\|sunos5\\)"
122 system-configuration
)
123 (file-exists-p "/opt/SUNWspro/SC3.0.1/bin/acomp"))
124 "/opt/SUNWspro/SC3.0.1/bin/acomp -C -E")
125 ((locate-file "/usr/ccs/lib/cpp"
126 '("/") exec-suffixes
'file-executable-p
)
127 "/usr/ccs/lib/cpp -C")
128 ((locate-file "/lib/cpp"
129 '("/") exec-suffixes
'file-executable-p
)
131 ;; On some systems, we cannot rely on standard directories to
132 ;; find CPP. In fact, we cannot rely on having cpp, either,
133 ;; in some GCC versions.
134 ((locate-file "cpp" exec-path exec-suffixes
'file-executable-p
)
136 (t "gcc -E -C -o - -"))
137 "The preprocessor used by the cmacexp package.
139 If you change this, be sure to preserve the `-C' (don't strip comments)
140 option, or to set an equivalent one."
144 (defcustom c-macro-cppflags
""
145 "Preprocessor flags used by `c-macro-expand'."
149 (defconst c-macro-buffer-name
"*Macroexpansion*")
152 (defun c-macro-expand (start end subst
)
153 "Expand C macros in the region, using the C preprocessor.
154 Normally display output in temp buffer, but
155 prefix arg means replace the region with it.
157 `c-macro-preprocessor' specifies the preprocessor to use.
158 Tf the user option `c-macro-prompt-flag' is non-nil
159 prompt for arguments to the preprocessor \(e.g. `-DDEBUG -I ./include'),
160 otherwise use `c-macro-cppflags'.
162 Noninteractive args are START, END, SUBST.
163 For use inside Lisp programs, see also `c-macro-expansion'."
166 (let ((inbuf (current-buffer))
167 (displaybuf (if subst
168 (get-buffer c-macro-buffer-name
)
169 (get-buffer-create c-macro-buffer-name
)))
171 ;; Build the command string.
172 (if c-macro-prompt-flag
173 (setq c-macro-cppflags
174 (read-string "Preprocessor arguments: "
176 ;; Decide where to display output.
178 (and buffer-read-only
(not inhibit-read-only
))
179 (not (eq inbuf displaybuf
)))
182 "Buffer is read only: displaying expansion in alternate window")
186 (setq displaybuf
(get-buffer-create c-macro-buffer-name
)))))
187 ;; Expand the macro and output it.
188 (setq expansion
(c-macro-expansion start end
189 (concat c-macro-preprocessor
" "
190 c-macro-cppflags
) t
))
192 (let ((exchange (= (point) start
)))
193 (delete-region start end
)
196 (exchange-point-and-mark)))
197 (set-buffer displaybuf
)
198 (setq buffer-read-only nil
)
199 (buffer-disable-undo displaybuf
)
202 (set-buffer-modified-p nil
)
203 (if (string= "" expansion
)
204 (message "Null expansion")
205 (c-macro-display-buffer))
206 (setq buffer-read-only t
)
207 (setq buffer-auto-save-file-name nil
)
208 (bury-buffer displaybuf
))))
211 ;; Display the current buffer in a window which is either just large
212 ;; enough to contain the entire buffer, or half the size of the
213 ;; screen, whichever is smaller. Do not select the new
216 ;; Several factors influence window resizing so that the window is
217 ;; sized optimally if it is created anew, and so that it is messed
218 ;; with minimally if it has been created by the user. If the window
219 ;; chosen for display exists already but contains something else, the
220 ;; window is not re-sized. If the window already contains the current
221 ;; buffer, it is never shrunk, but possibly expanded. Finally, if the
222 ;; variable c-macro-shrink-window-flag is nil the window size is *never*
224 (defun c-macro-display-buffer ()
225 (goto-char (point-min))
227 (let ((oldwinheight (window-height))
228 (alreadythere ;the window was already there
229 (get-buffer-window (current-buffer)))
230 (popped nil
)) ;the window popped changing the layout
233 (display-buffer (current-buffer) t
)
234 (setq popped
(/= oldwinheight
(window-height)))))
235 (if (and c-macro-shrink-window-flag
;user wants fancy shrinking :\)
236 (or alreadythere popped
))
237 ;; Enlarge up to half screen, or shrink properly.
238 (let ((oldwin (selected-window))
242 (select-window (get-buffer-window (current-buffer)))
243 (setq minheight
(if alreadythere
246 (setq maxheight
(/ (frame-height) 2))
247 (enlarge-window (- (min maxheight
249 (+ 2 (vertical-motion (point-max)))))
251 (goto-char (point-min))
252 (select-window oldwin
))))))
255 (defun c-macro-expansion (start end cppcommand
&optional display
)
256 "Run a preprocessor on region and return the output as a string.
257 Expand the region between START and END in the current buffer using
258 the shell command CPPCOMMAND (e.g. \"/lib/cpp -C -DDEBUG\").
259 Be sure to use a -C (don't strip comments) or equivalent option.
260 Optional arg DISPLAY non-nil means show messages in the echo area."
262 ;; Copy the current buffer's contents to a temporary hidden buffer.
263 ;; Delete from END to end of buffer. Insert a preprocessor #line
264 ;; directive at START and after each #endif following START that are
265 ;; not inside a comment or a string. Put all the strings thus
266 ;; inserted (without the "line" substring) in a list named linelist.
267 ;; If START is inside a comment, prepend "*/" and append "/*" to the
268 ;; #line directive. If inside a string, prepend and append "\"".
269 ;; Preprocess the buffer contents, then look for all the lines stored
270 ;; in linelist starting from end of buffer. The last line so found is
271 ;; where START was, so return the substring from point to end of
273 (let ((inbuf (current-buffer))
274 (outbuf (get-buffer-create " *C Macro Expansion*"))
275 (filename (if (and buffer-file-name
276 (string-match (regexp-quote default-directory
)
278 (substring buffer-file-name
(match-end 0))
280 (mymsg (format "Invoking %s%s%s on region..."
282 (if (string= "" c-macro-cppflags
) "" " ")
284 (uniquestring "??? !!! ??? start of c-macro expansion ??? !!! ???")
290 (tempname (make-temp-file
291 (expand-file-name "cmacexp"
292 (or small-temporary-file-directory
293 temporary-file-directory
)))))
298 (let ((in-syntax-table (syntax-table)))
300 (setq buffer-read-only nil
)
302 (set-syntax-table in-syntax-table
))
303 (insert-buffer-substring inbuf
1 end
))
305 ;; We have copied inbuf to outbuf. Point is at end of
306 ;; outbuf. Inset a newline at the end, so cpp can correctly
307 ;; parse a token ending at END.
310 ;; Save sexp status and line number at START.
311 (setq startstat
(parse-partial-sexp 1 start
))
312 (setq startlinenum
(+ (count-lines 1 (point))
315 ;; Now we insert the #line directives after all #endif or
316 ;; #else following START going backward, so the lines we
317 ;; insert don't change the line numbers.
318 ;(switch-to-buffer outbuf) (debug) ;debugging instructions
319 (goto-char (point-max))
320 (while (re-search-backward "\n#\\(endif\\|else\\)\\>" start
'move
)
321 (if (equal (nthcdr 3 (parse-partial-sexp start
(point)
323 '(nil nil nil
0 nil
)) ;neither in string nor in
324 ;comment nor after quote
326 (goto-char (match-end 0))
327 (setq linenum
(+ startlinenum
328 (count-lines start
(point))))
329 (insert (format "\n#line %d \"%s\"\n" linenum filename
))
330 (goto-char (match-beginning 0)))))
332 ;; Now we are at START. Insert the first #line directive.
333 ;; This must work even inside a string or comment, or after a
335 (let* ((startinstring (nth 3 startstat
))
336 (startincomment (nth 4 startstat
))
337 (startafterquote (nth 5 startstat
))
338 (startinbcomment (nth 7 startstat
)))
339 (insert (if startafterquote
" " "")
341 (char-to-string startinstring
))
342 (startincomment "*/")
345 (concat "\n" uniquestring
347 (char-to-string startinstring
))
348 (startincomment "/*")
349 (startinbcomment "//"))
350 (if startafterquote
"\\")))
351 (format "\n#line %d \"%s\"\n" startlinenum filename
)))
353 ;; Call the preprocessor.
354 (if display
(message "%s" mymsg
))
356 (call-process-region 1 (point-max)
358 t
(list t tempname
) nil
"-c"
360 (if display
(message "%s" (concat mymsg
"done")))
361 (if (= (buffer-size) 0)
362 ;; Empty output is normal after a fatal error.
363 (insert "\nPreprocessor produced no output\n")
364 ;; Find and delete the mark of the start of the expansion.
365 ;; Look for `# nn "file.c"' lines and delete them.
366 (goto-char (point-min))
367 (if (search-forward startmarker nil t
)
368 (delete-region 1 (point))))
369 (while (re-search-forward (concat "^# [0-9]+ \""
370 (regexp-quote filename
)
375 (delete-region beg
(point))))
377 ;; If CPP got errors, show them at the beginning.
378 ;; MS-DOS shells don't return the exit code of their children.
379 ;; Look at the size of the error message file instead, but
380 ;; don't punish those MS-DOS users who have a shell that does
381 ;; return an error code.
382 (or (and (or (not (boundp 'msdos-shells
))
383 (not (member (file-name-nondirectory shell-file-name
)
386 (zerop (nth 7 (file-attributes (expand-file-name tempname
))))
388 (goto-char (point-min))
389 ;; Put the messages inside a comment, so they won't get in
390 ;; the way of font-lock, highlighting etc.
392 (format "/* Preprocessor terminated with status %s\n\n Messages from `%s\':\n\n"
393 exit-status cppcommand
))
394 (goto-char (+ (point)
395 (nth 1 (insert-file-contents tempname
))))
396 (insert "\n\n*/\n")))
397 (delete-file tempname
)
399 ;; Compute the return value, keeping in account the space
400 ;; inserted at the end of the buffer.
401 (buffer-substring 1 (max 1 (- (point-max) 1))))
404 (kill-buffer outbuf
))))
406 ;;; cmacexp.el ends here