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