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