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