Add arch taglines
[bpt/emacs.git] / lisp / progmodes / cmacexp.el
CommitLineData
4af1f509 1;;; cmacexp.el --- expand C macros in a region
c0274f38 2
8a30aaa3 3;; Copyright (C) 1992, 1994, 1996, 2000 Free Software Foundation, Inc.
9750e079 4
8a30aaa3 5;; Author: Francesco Potorti` <pot@gnu.org>
4af1f509 6;; Adapted-By: ESR
e5167999
ER
7;; Keywords: c
8
c17d15d0
JB
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
e5167999 13;; the Free Software Foundation; either version 2, or (at your option)
c17d15d0
JB
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
b578f267
EN
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.
c17d15d0 25
e8af40ee
PJ
26;;; Commentary:
27
89fb82d6 28;; USAGE =============================================================
e41b2db1 29
074521be
RS
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.
e41b2db1 33;;
4af1f509 34;; When called with a C-u prefix, c-macro-expand replaces the selected
89fb82d6 35;; region with the expansion. Both the preprocessor name and the
074521be
RS
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.
4af1f509
RS
42
43;; A c-macro-expansion function is provided for non-interactive use.
4af1f509
RS
44
45;; INSTALLATION ======================================================
46
074521be 47;; Put the following in your ~/.emacs file.
4af1f509 48
4af1f509 49;; If you want the *Macroexpansion* window to be not higher than
4ff3fcc7 50;; necessary:
074521be 51;;(setq c-macro-shrink-window-flag t)
e41b2db1 52;;
4af1f509
RS
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;;
89fb82d6
RS
58;; If you often use a particular set of flags:
59;;(setq c-macro-cppflags "-I /usr/include/local -DDEBUG"
4af1f509 60;;
89fb82d6 61;; If you want the "Preprocessor arguments: " prompt:
074521be 62;;(setq c-macro-prompt-flag t)
4af1f509
RS
63
64;; BUG REPORTS =======================================================
65
66;; Please report bugs, suggestions, complaints and so on to
8a30aaa3 67;; pot@gnu.org (Francesco Potorti`).
4af1f509
RS
68
69;; IMPROVEMENTS OVER emacs 18.xx cmacexp.el ==========================
70
3332766c 71;; - A lot of user and programmer visible changes. See above.
4af1f509
RS
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.
4af1f509
RS
77
78;; ACKNOWLEDGEMENTS ==================================================
79
80;; A lot of thanks to Don Maszle who did a great work of testing, bug
074521be
RS
81;; reporting and suggestion of new features. This work has been
82;; partially inspired by Don Maszle and Jonathan Segal's.
4af1f509 83
89fb82d6 84;; BUGS ==============================================================
4af1f509
RS
85
86;; If the start point of the region is inside a macro definition the
87;; macro expansion is often inaccurate.
e41b2db1 88
e8af40ee 89;;; Code:
89fb82d6 90
a9132c1f
RS
91(require 'cc-mode)
92
89fb82d6 93(provide 'cmacexp)
c17d15d0 94
00ed33e7
RS
95(defgroup c-macro nil
96 "Expand C macros in a region."
97 :group 'c)
4af1f509 98
4af1f509 99
00ed33e7
RS
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
883310a7
EZ
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 - -")
b4ec679c
RS
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")
4ff3fcc7 120 ((file-exists-p "/usr/ccs/lib/cpp") "/usr/ccs/lib/cpp -C")
b4ec679c 121 (t "/lib/cpp -C"))
9c32788e 122 "The preprocessor used by the cmacexp package.
4af1f509 123
440c10f8 124If you change this, be sure to preserve the `-C' (don't strip comments)
00ed33e7
RS
125option, or to set an equivalent one."
126 :type 'string
127 :group 'c-macro)
128
129(defcustom c-macro-cppflags ""
130 "*Preprocessor flags used by `c-macro-expand'."
131 :type 'string
132 :group 'c-macro)
4af1f509
RS
133
134(defconst c-macro-buffer-name "*Macroexpansion*")
135
d322f009 136;;;###autoload
9c32788e
RS
137(defun c-macro-expand (start end subst)
138 "Expand C macros in the region, using the C preprocessor.
139Normally display output in temp buffer, but
140prefix arg means replace the region with it.
141
142`c-macro-preprocessor' specifies the preprocessor to use.
143Prompt for arguments to the preprocessor \(e.g. `-DDEBUG -I ./include')
144if the user option `c-macro-prompt-flag' is non-nil.
4af1f509 145
89fb82d6 146Noninteractive args are START, END, SUBST.
9c32788e 147For use inside Lisp programs, see also `c-macro-expansion'."
4af1f509
RS
148
149 (interactive "r\nP")
89fb82d6
RS
150 (let ((inbuf (current-buffer))
151 (displaybuf (if subst
152 (get-buffer c-macro-buffer-name)
153 (get-buffer-create c-macro-buffer-name)))
074521be 154 (expansion ""))
4af1f509 155 ;; Build the command string.
9c32788e 156 (if c-macro-prompt-flag
89fb82d6 157 (setq c-macro-cppflags
4af1f509 158 (read-string "Preprocessor arguments: "
89fb82d6 159 c-macro-cppflags)))
4af1f509
RS
160 ;; Decide where to display output.
161 (if (and subst
6c61e6a9 162 (and buffer-read-only (not inhibit-read-only))
4af1f509
RS
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.
89fb82d6
RS
172 (setq expansion (c-macro-expansion start end
173 (concat c-macro-preprocessor " "
074521be 174 c-macro-cppflags) t))
4af1f509
RS
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)
3332766c 183 (buffer-disable-undo displaybuf)
4af1f509
RS
184 (erase-buffer)
185 (insert expansion)
186 (set-buffer-modified-p nil)
187 (if (string= "" expansion)
188 (message "Null expansion")
89fb82d6 189 (c-macro-display-buffer))
4af1f509 190 (setq buffer-read-only t)
89fb82d6 191 (setq buffer-auto-save-file-name nil)
4af1f509
RS
192 (bury-buffer displaybuf))))
193
194
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
89fb82d6
RS
197;; screen, whichever is smaller. Do not select the new
198;; window.
4af1f509
RS
199;;
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
9c32788e 206;; variable c-macro-shrink-window-flag is nil the window size is *never*
4af1f509 207;; changed.
89fb82d6 208(defun c-macro-display-buffer ()
4af1f509
RS
209 (goto-char (point-min))
210 (c-mode)
4af1f509
RS
211 (let ((oldwinheight (window-height))
212 (alreadythere ;the window was already there
213 (get-buffer-window (current-buffer)))
4ff3fcc7 214 (popped nil)) ;the window popped changing the layout
4af1f509
RS
215 (or alreadythere
216 (progn
217 (display-buffer (current-buffer) t)
218 (setq popped (/= oldwinheight (window-height)))))
9c32788e 219 (if (and c-macro-shrink-window-flag ;user wants fancy shrinking :\)
4af1f509
RS
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))
32cdf3f6 230 (setq maxheight (/ (frame-height) 2))
4af1f509
RS
231 (enlarge-window (- (min maxheight
232 (max minheight
89fb82d6 233 (+ 2 (vertical-motion (point-max)))))
4af1f509
RS
234 (window-height)))
235 (goto-char (point-min))
236 (select-window oldwin))))))
237
238
074521be 239(defun c-macro-expansion (start end cppcommand &optional display)
9c32788e 240 "Run a preprocessor on region and return the output as a string.
89fb82d6
RS
241Expand the region between START and END in the current buffer using
242the shell command CPPCOMMAND (e.g. \"/lib/cpp -C -DDEBUG\").
074521be
RS
243Be sure to use a -C (don't strip comments) or equivalent option.
244Optional arg DISPLAY non-nil means show messages in the echo area."
4af1f509
RS
245
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
4ff3fcc7 256;; buffer.
4af1f509
RS
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)))
074521be
RS
264 (mymsg (format "Invoking %s%s%s on region..."
265 c-macro-preprocessor
266 (if (string= "" c-macro-cppflags) "" " ")
267 c-macro-cppflags))
32cdf3f6 268 (uniquestring "??? !!! ??? start of c-macro expansion ??? !!! ???")
074521be 269 (startlinenum 0)
4af1f509 270 (linenum 0)
074521be 271 (startstat ())
440c10f8 272 (startmarker "")
3332766c 273 (exit-status 0)
767d12f2 274 (tempname (make-temp-file
fc416240 275 (expand-file-name "cmacexp"
77f90711
EZ
276 (or small-temporary-file-directory
277 temporary-file-directory)))))
4af1f509
RS
278 (unwind-protect
279 (save-excursion
280 (save-restriction
281 (widen)
32cdf3f6
KH
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))
4af1f509
RS
287 (insert-buffer-substring inbuf 1 end))
288
289 ;; We have copied inbuf to outbuf. Point is at end of
32cdf3f6
KH
290 ;; outbuf. Inset a newline at the end, so cpp can correctly
291 ;; parse a token ending at END.
292 (insert "\n")
4af1f509 293
074521be
RS
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)))
298
4af1f509 299 ;; Now we insert the #line directives after all #endif or
074521be
RS
300 ;; #else following START going backward, so the lines we
301 ;; insert don't change the line numbers.
4af1f509 302 ;(switch-to-buffer outbuf) (debug) ;debugging instructions
074521be 303 (goto-char (point-max))
4af1f509 304 (while (re-search-backward "\n#\\(endif\\|else\\)\\>" start 'move)
074521be
RS
305 (if (equal (nthcdr 3 (parse-partial-sexp start (point)
306 nil nil startstat))
9c32788e 307 '(nil nil nil 0 nil)) ;neither in string nor in
074521be 308 ;comment nor after quote
4af1f509
RS
309 (progn
310 (goto-char (match-end 0))
074521be
RS
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)))))
315
316 ;; Now we are at START. Insert the first #line directive.
317 ;; This must work even inside a string or comment, or after a
4af1f509 318 ;; quote.
074521be
RS
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 (""))
074521be 328 (setq startmarker
521fffcd 329 (concat "\n" uniquestring
074521be
RS
330 (cond (startinstring
331 (char-to-string startinstring))
332 (startincomment "/*")
333 (startinbcomment "//"))
521fffcd
FP
334 (if startafterquote "\\")))
335 (format "\n#line %d \"%s\"\n" startlinenum filename)))
4af1f509
RS
336
337 ;; Call the preprocessor.
074521be 338 (if display (message mymsg))
440c10f8 339 (setq exit-status
68dff3ca
RS
340 (call-process-region 1 (point-max)
341 shell-file-name
342 t (list t tempname) nil "-c"
343 cppcommand))
074521be 344 (if display (message (concat mymsg "done")))
eb426f3a
RS
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)))
074521be
RS
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))))
4af1f509 360
440c10f8 361 ;; If CPP got errors, show them at the beginning.
68dff3ca
RS
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))))
440c10f8
RS
371 (progn
372 (goto-char (point-min))
68dff3ca
RS
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")))
440c10f8
RS
381 (delete-file tempname)
382
4af1f509
RS
383 ;; Compute the return value, keeping in account the space
384 ;; inserted at the end of the buffer.
074521be 385 (buffer-substring 1 (max 1 (- (point-max) 1))))
4af1f509
RS
386
387 ;; Cleanup.
388 (kill-buffer outbuf))))
389
ab5796a9 390;;; arch-tag: 4f20253c-71ef-4e6d-a774-19087060910e
89fb82d6 391;;; cmacexp.el ends here