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