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