Simplify Emacs 19 compatibility.
[emacs.git] / lisp / progmodes / cmacexp.el
bloba42df869dfdebc1c3fa5ac0d3abe1573b247d3a2
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>
6 ;; Adapted-By: ESR
7 ;; Keywords: c
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)
14 ;; any later version.
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 ;;; Commentary:
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
41 ;; c-macro-cppflags.
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
50 ;; necessary:
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.
89 ;;; Code:
91 (require 'cc-mode)
93 (provide 'cmacexp)
95 (defgroup c-macro nil
96 "Expand C macros in a region."
97 :group 'c)
100 (defcustom c-macro-shrink-window-flag nil
101 "*Non-nil means shrink the *Macroexpansion* window to fit its contents."
102 :type 'boolean
103 :group 'c-macro)
105 (defcustom c-macro-prompt-flag nil
106 "*Non-nil makes `c-macro-expand' prompt for preprocessor arguments."
107 :type 'boolean
108 :group 'c-macro)
110 (defcustom c-macro-preprocessor
111 ;; Cannot rely on standard directory on MS-DOS to find CPP. In
112 ;; fact, cannot rely on having cpp.exe, either, in latest GCC
113 ;; versions.
114 (cond ((eq system-type 'ms-dos) "gcc -E -C -o - -")
115 ;; Solaris has it in an unusual place.
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")
120 ((file-exists-p "/usr/ccs/lib/cpp") "/usr/ccs/lib/cpp -C")
121 (t "/lib/cpp -C"))
122 "The preprocessor used by the cmacexp package.
124 If you change this, be sure to preserve the `-C' (don't strip comments)
125 option, or to set an equivalent one."
126 :type 'string
127 :group 'c-macro)
129 (defcustom c-macro-cppflags ""
130 "*Preprocessor flags used by `c-macro-expand'."
131 :type 'string
132 :group 'c-macro)
134 (defconst c-macro-buffer-name "*Macroexpansion*")
136 ;;;###autoload
137 (defun c-macro-expand (start end subst)
138 "Expand C macros in the region, using the C preprocessor.
139 Normally display output in temp buffer, but
140 prefix arg means replace the region with it.
142 `c-macro-preprocessor' specifies the preprocessor to use.
143 Prompt for arguments to the preprocessor \(e.g. `-DDEBUG -I ./include')
144 if the user option `c-macro-prompt-flag' is non-nil.
146 Noninteractive args are START, END, SUBST.
147 For use inside Lisp programs, see also `c-macro-expansion'."
149 (interactive "r\nP")
150 (let ((inbuf (current-buffer))
151 (displaybuf (if subst
152 (get-buffer c-macro-buffer-name)
153 (get-buffer-create c-macro-buffer-name)))
154 (expansion ""))
155 ;; Build the command string.
156 (if c-macro-prompt-flag
157 (setq c-macro-cppflags
158 (read-string "Preprocessor arguments: "
159 c-macro-cppflags)))
160 ;; Decide where to display output.
161 (if (and subst
162 (and buffer-read-only (not inhibit-read-only))
163 (not (eq inbuf displaybuf)))
164 (progn
165 (message
166 "Buffer is read only: displaying expansion in alternate window")
167 (sit-for 2)
168 (setq subst nil)
169 (or displaybuf
170 (setq displaybuf (get-buffer-create c-macro-buffer-name)))))
171 ;; Expand the macro and output it.
172 (setq expansion (c-macro-expansion start end
173 (concat c-macro-preprocessor " "
174 c-macro-cppflags) t))
175 (if subst
176 (let ((exchange (= (point) start)))
177 (delete-region start end)
178 (insert expansion)
179 (if exchange
180 (exchange-point-and-mark)))
181 (set-buffer displaybuf)
182 (setq buffer-read-only nil)
183 (buffer-disable-undo displaybuf)
184 (erase-buffer)
185 (insert expansion)
186 (set-buffer-modified-p nil)
187 (if (string= "" expansion)
188 (message "Null expansion")
189 (c-macro-display-buffer))
190 (setq buffer-read-only t)
191 (setq buffer-auto-save-file-name nil)
192 (bury-buffer displaybuf))))
195 ;; Display the current buffer in a window which is either just large
196 ;; enough to contain the entire buffer, or half the size of the
197 ;; screen, whichever is smaller. Do not select the new
198 ;; window.
200 ;; Several factors influence window resizing so that the window is
201 ;; sized optimally if it is created anew, and so that it is messed
202 ;; with minimally if it has been created by the user. If the window
203 ;; chosen for display exists already but contains something else, the
204 ;; window is not re-sized. If the window already contains the current
205 ;; buffer, it is never shrunk, but possibly expanded. Finally, if the
206 ;; variable c-macro-shrink-window-flag is nil the window size is *never*
207 ;; changed.
208 (defun c-macro-display-buffer ()
209 (goto-char (point-min))
210 (c-mode)
211 (let ((oldwinheight (window-height))
212 (alreadythere ;the window was already there
213 (get-buffer-window (current-buffer)))
214 (popped nil)) ;the window popped changing the layout
215 (or alreadythere
216 (progn
217 (display-buffer (current-buffer) t)
218 (setq popped (/= oldwinheight (window-height)))))
219 (if (and c-macro-shrink-window-flag ;user wants fancy shrinking :\)
220 (or alreadythere popped))
221 ;; Enlarge up to half screen, or shrink properly.
222 (let ((oldwin (selected-window))
223 (minheight 0)
224 (maxheight 0))
225 (save-excursion
226 (select-window (get-buffer-window (current-buffer)))
227 (setq minheight (if alreadythere
228 (window-height)
229 window-min-height))
230 (setq maxheight (/ (frame-height) 2))
231 (enlarge-window (- (min maxheight
232 (max minheight
233 (+ 2 (vertical-motion (point-max)))))
234 (window-height)))
235 (goto-char (point-min))
236 (select-window oldwin))))))
239 (defun c-macro-expansion (start end cppcommand &optional display)
240 "Run a preprocessor on region and return the output as a string.
241 Expand the region between START and END in the current buffer using
242 the shell command CPPCOMMAND (e.g. \"/lib/cpp -C -DDEBUG\").
243 Be sure to use a -C (don't strip comments) or equivalent option.
244 Optional arg DISPLAY non-nil means show messages in the echo area."
246 ;; Copy the current buffer's contents to a temporary hidden buffer.
247 ;; Delete from END to end of buffer. Insert a preprocessor #line
248 ;; directive at START and after each #endif following START that are
249 ;; not inside a comment or a string. Put all the strings thus
250 ;; inserted (without the "line" substring) in a list named linelist.
251 ;; If START is inside a comment, prepend "*/" and append "/*" to the
252 ;; #line directive. If inside a string, prepend and append "\"".
253 ;; Preprocess the buffer contents, then look for all the lines stored
254 ;; in linelist starting from end of buffer. The last line so found is
255 ;; where START was, so return the substring from point to end of
256 ;; buffer.
257 (let ((inbuf (current-buffer))
258 (outbuf (get-buffer-create " *C Macro Expansion*"))
259 (filename (if (and buffer-file-name
260 (string-match (regexp-quote default-directory)
261 buffer-file-name))
262 (substring buffer-file-name (match-end 0))
263 (buffer-name)))
264 (mymsg (format "Invoking %s%s%s on region..."
265 c-macro-preprocessor
266 (if (string= "" c-macro-cppflags) "" " ")
267 c-macro-cppflags))
268 (uniquestring "??? !!! ??? start of c-macro expansion ??? !!! ???")
269 (startlinenum 0)
270 (linenum 0)
271 (startstat ())
272 (startmarker "")
273 (exit-status 0)
274 (tempname (make-temp-file
275 (expand-file-name "cmacexp"
276 (or small-temporary-file-directory
277 temporary-file-directory)))))
278 (unwind-protect
279 (save-excursion
280 (save-restriction
281 (widen)
282 (let ((in-syntax-table (syntax-table)))
283 (set-buffer outbuf)
284 (setq buffer-read-only nil)
285 (erase-buffer)
286 (set-syntax-table in-syntax-table))
287 (insert-buffer-substring inbuf 1 end))
289 ;; We have copied inbuf to outbuf. Point is at end of
290 ;; outbuf. Inset a newline at the end, so cpp can correctly
291 ;; parse a token ending at END.
292 (insert "\n")
294 ;; Save sexp status and line number at START.
295 (setq startstat (parse-partial-sexp 1 start))
296 (setq startlinenum (+ (count-lines 1 (point))
297 (if (bolp) 1 0)))
299 ;; Now we insert the #line directives after all #endif or
300 ;; #else following START going backward, so the lines we
301 ;; insert don't change the line numbers.
302 ;(switch-to-buffer outbuf) (debug) ;debugging instructions
303 (goto-char (point-max))
304 (while (re-search-backward "\n#\\(endif\\|else\\)\\>" start 'move)
305 (if (equal (nthcdr 3 (parse-partial-sexp start (point)
306 nil nil startstat))
307 '(nil nil nil 0 nil)) ;neither in string nor in
308 ;comment nor after quote
309 (progn
310 (goto-char (match-end 0))
311 (setq linenum (+ startlinenum
312 (count-lines start (point))))
313 (insert (format "\n#line %d \"%s\"\n" linenum filename))
314 (goto-char (match-beginning 0)))))
316 ;; Now we are at START. Insert the first #line directive.
317 ;; This must work even inside a string or comment, or after a
318 ;; quote.
319 (let* ((startinstring (nth 3 startstat))
320 (startincomment (nth 4 startstat))
321 (startafterquote (nth 5 startstat))
322 (startinbcomment (nth 7 startstat)))
323 (insert (if startafterquote " " "")
324 (cond (startinstring
325 (char-to-string startinstring))
326 (startincomment "*/")
327 (""))
328 (setq startmarker
329 (concat "\n" uniquestring
330 (cond (startinstring
331 (char-to-string startinstring))
332 (startincomment "/*")
333 (startinbcomment "//"))
334 (if startafterquote "\\")))
335 (format "\n#line %d \"%s\"\n" startlinenum filename)))
337 ;; Call the preprocessor.
338 (if display (message mymsg))
339 (setq exit-status
340 (call-process-region 1 (point-max)
341 shell-file-name
342 t (list t tempname) nil "-c"
343 cppcommand))
344 (if display (message (concat mymsg "done")))
345 (if (= (buffer-size) 0)
346 ;; Empty output is normal after a fatal error.
347 (insert "\nPreprocessor produced no output\n")
348 ;; Find and delete the mark of the start of the expansion.
349 ;; Look for `# nn "file.c"' lines and delete them.
350 (goto-char (point-min))
351 (search-forward startmarker)
352 (delete-region 1 (point)))
353 (while (re-search-forward (concat "^# [0-9]+ \""
354 (regexp-quote filename)
355 "\"") nil t)
356 (beginning-of-line)
357 (let ((beg (point)))
358 (forward-line 1)
359 (delete-region beg (point))))
361 ;; If CPP got errors, show them at the beginning.
362 ;; MS-DOS shells don't return the exit code of their children.
363 ;; Look at the size of the error message file instead, but
364 ;; don't punish those MS-DOS users who have a shell that does
365 ;; return an error code.
366 (or (and (or (not (boundp 'msdos-shells))
367 (not (member (file-name-nondirectory shell-file-name)
368 msdos-shells)))
369 (eq exit-status 0))
370 (zerop (nth 7 (file-attributes (expand-file-name tempname))))
371 (progn
372 (goto-char (point-min))
373 ;; Put the messages inside a comment, so they won't get in
374 ;; the way of font-lock, highlighting etc.
375 (insert
376 (format "/* Preprocessor terminated with status %s\n\n Messages from `%s\':\n\n"
377 exit-status cppcommand))
378 (goto-char (+ (point)
379 (nth 1 (insert-file-contents tempname))))
380 (insert "\n\n*/\n")))
381 (delete-file tempname)
383 ;; Compute the return value, keeping in account the space
384 ;; inserted at the end of the buffer.
385 (buffer-substring 1 (max 1 (- (point-max) 1))))
387 ;; Cleanup.
388 (kill-buffer outbuf))))
390 ;;; cmacexp.el ends here