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