; * doc/misc/calc.texi (Date Arithmetic): Fix order in @menu.
[emacs.git] / lisp / autoinsert.el
blob0392903c33258dfab62270411eeb0795f72cfe38
1 ;;; autoinsert.el --- automatic mode-dependent insertion of text into new files -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1994-1995, 1998, 2000-2021 Free Software
4 ;; Foundation, Inc.
6 ;; Author: Charlie Martin <crm@cs.duke.edu>
7 ;; Adapted-By: Daniel Pfeiffer <occitan@esperanto.org>
8 ;; Keywords: convenience
9 ;; Maintainer: emacs-devel@gnu.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; The following defines an association list for text to be
29 ;; automatically inserted when a new file is created, and a function
30 ;; which automatically inserts these files; the idea is to insert
31 ;; default text much as the mode is automatically set using
32 ;; auto-mode-alist.
34 ;; To use:
35 ;; (auto-insert-mode t)
36 ;; setq auto-insert-directory to an appropriate slash-terminated value
38 ;; You can also customize the variable `auto-insert-mode' to load the
39 ;; package. Alternatively, add the following to your init file:
40 ;; (auto-insert-mode 1)
42 ;; Author: Charlie Martin
43 ;; Department of Computer Science and
44 ;; National Biomedical Simulation Resource
45 ;; Box 3709
46 ;; Duke University Medical Center
47 ;; Durham, NC 27710
48 ;; (crm@cs.duke.edu,mcnc!duke!crm)
50 ;;; Code:
52 (require 'seq)
54 (defgroup auto-insert nil
55 "Automatic mode-dependent insertion of text into new files."
56 :prefix "auto-insert-"
57 :group 'files
58 :group 'convenience
59 :link '(custom-manual "(autotype) Autoinserting"))
62 (defcustom auto-insert 'not-modified
63 "Controls automatic insertion into newly found empty files.
64 Possible values:
65 nil do nothing
66 t insert if possible
67 other insert if possible, but mark as unmodified.
68 Insertion is possible when something appropriate is found in
69 `auto-insert-alist'. When the insertion is marked as unmodified, you can
70 save it with \\[write-file] RET.
71 This variable is used when the function `auto-insert' is called, e.g.
72 when you do (add-hook \\='find-file-hook \\='auto-insert).
73 With \\[auto-insert], this is always treated as if it were t."
74 :type '(choice (const :tag "Insert if possible" t)
75 (const :tag "Do nothing" nil)
76 (other :tag "insert if possible, mark as unmodified."
77 not-modified)))
79 (defcustom auto-insert-query 'function
80 "Non-nil means ask user before auto-inserting.
81 When this is `function', only ask when called non-interactively."
82 :type '(choice (const :tag "Don't ask" nil)
83 (const :tag "Ask if called non-interactively" function)
84 (other :tag "Ask" t)))
86 (defcustom auto-insert-prompt "Perform %s auto-insertion? "
87 "Prompt to use when querying whether to auto-insert.
88 If this contains a %s, that will be replaced by the matching rule."
89 :type 'string)
92 (defcustom auto-insert-alist
93 '((("\\.\\([Hh]\\|hh\\|hpp\\|hxx\\|h\\+\\+\\)\\'" . "C / C++ header")
94 (replace-regexp-in-string
95 "[^A-Z0-9]" "_"
96 (replace-regexp-in-string
97 "\\+" "P"
98 (upcase (file-name-nondirectory buffer-file-name))))
99 "#ifndef " str \n
100 "#define " str "\n\n"
101 _ "\n\n#endif")
103 (("\\.\\([Cc]\\|cc\\|cpp\\|cxx\\|c\\+\\+\\)\\'" . "C / C++ program")
105 "#include \""
106 (let ((stem (file-name-sans-extension buffer-file-name))
107 ret)
108 (dolist (ext '("H" "h" "hh" "hpp" "hxx" "h++") ret)
109 (when (file-exists-p (concat stem "." ext))
110 (setq ret (file-name-nondirectory (concat stem "." ext))))))
111 & ?\" | -10)
113 (("[Mm]akefile\\'" . "Makefile") . "makefile.inc")
115 (html-mode . (lambda () (sgml-tag "html")))
117 (plain-tex-mode . "tex-insert.tex")
118 (bibtex-mode . "tex-insert.tex")
119 (latex-mode
120 ;; should try to offer completing read for these
121 "options, RET: "
122 "\\documentclass[" str & ?\] | -1
123 ?{ (read-string "class: ") "}\n"
124 ("package, %s: "
125 "\\usepackage[" (read-string "options, RET: ") & ?\] | -1 ?{ str "}\n")
126 _ "\n\\begin{document}\n" _
127 "\n\\end{document}")
129 (("/bin/.*[^/]\\'" . "Shell-Script mode magic number") .
130 (lambda ()
131 (if (eq major-mode (default-value 'major-mode))
132 (sh-mode))))
134 (ada-mode . ada-header)
136 (("\\.[1-9]\\'" . "Man page skeleton")
137 "Short description: "
138 ".\\\" Copyright (C), " (format-time-string "%Y") " "
139 (getenv "ORGANIZATION") | (progn user-full-name)
141 .\\\" You may distribute this file under the terms of the GNU Free
142 .\\\" Documentation License.
143 .TH " (file-name-base (buffer-file-name))
144 " " (file-name-extension (buffer-file-name))
145 " " (format-time-string "%Y-%m-%d ")
146 "\n.SH NAME\n"
147 (file-name-base (buffer-file-name))
148 " \\- " str
149 "\n.SH SYNOPSIS
150 .B " (file-name-base (buffer-file-name))
151 "\n"
154 .SH DESCRIPTION
155 .SH OPTIONS
156 .SH FILES
157 .SH \"SEE ALSO\"
158 .SH BUGS
159 .SH AUTHOR
160 " (user-full-name)
161 '(if (search-backward "&" (line-beginning-position) t)
162 (replace-match (capitalize (user-login-name)) t t))
163 '(end-of-line 1) " <" (progn user-mail-address) ">\n")
165 (".dir-locals.el"
167 ";;; Directory Local Variables\n"
168 ";;; For more information see (info \"(emacs) Directory Variables\")\n\n"
169 "(("
170 '(setq v1 (let (modes)
171 (mapatoms (lambda (mode)
172 (let ((name (symbol-name mode)))
173 (when (string-match "-mode$" name)
174 (push name modes)))))
175 (sort modes 'string<)))
176 (completing-read "Local variables for mode: " v1 nil t)
177 " . (("
178 (let ((all-variables
179 (apropos-internal ".*"
180 (lambda (symbol)
181 (and (boundp symbol)
182 (get symbol 'variable-documentation))))))
183 (completing-read "Variable to set: " all-variables))
184 " . "
185 (completing-read "Value to set it to: " nil)
186 "))))\n")
188 (("\\.el\\'" . "Emacs Lisp header")
189 "Short description: "
190 ";;; " (file-name-nondirectory (buffer-file-name)) " --- " str
191 (make-string (max 2 (- 80 (current-column) 27)) ?\s)
192 "-*- lexical-binding: t; -*-" '(setq lexical-binding t)
195 ;; Copyright (C) " (format-time-string "%Y") " "
196 (getenv "ORGANIZATION") | (progn user-full-name) "
198 ;; Author: " (user-full-name)
199 '(if (search-backward "&" (line-beginning-position) t)
200 (replace-match (capitalize (user-login-name)) t t))
201 '(end-of-line 1) " <" (progn user-mail-address) ">
202 ;; Keywords: "
203 '(require 'finder)
204 ;;'(setq v1 (apply 'vector (mapcar 'car finder-known-keywords)))
205 '(setq v1 (mapcar (lambda (x) (list (symbol-name (car x))))
206 finder-known-keywords)
207 v2 (mapconcat (lambda (x) (format "%12s: %s" (car x) (cdr x)))
208 finder-known-keywords
209 "\n"))
210 ((let ((minibuffer-help-form v2))
211 (completing-read "Keyword, C-h: " v1 nil t))
212 str ", ") & -2 "
214 \;; This program is free software; you can redistribute it and/or modify
215 \;; it under the terms of the GNU General Public License as published by
216 \;; the Free Software Foundation, either version 3 of the License, or
217 \;; (at your option) any later version.
219 \;; This program is distributed in the hope that it will be useful,
220 \;; but WITHOUT ANY WARRANTY; without even the implied warranty of
221 \;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
222 \;; GNU General Public License for more details.
224 \;; You should have received a copy of the GNU General Public License
225 \;; along with this program. If not, see <https://www.gnu.org/licenses/>.
227 \;;; Commentary:
229 \;; " _ "
231 \;;; Code:
235 \(provide '"
236 (file-name-base (buffer-file-name))
238 \;;; " (file-name-nondirectory (buffer-file-name)) " ends here\n")
239 (("\\.texi\\(nfo\\)?\\'" . "Texinfo file skeleton")
240 "Title: "
241 "\\input texinfo @c -*-texinfo-*-
242 @c %**start of header
243 @setfilename "
244 (file-name-base (buffer-file-name)) ".info\n"
245 "@settitle " str "
246 @c %**end of header
247 @copying\n"
248 (setq short-description (read-string "Short description: "))
249 ".\n\n"
250 "Copyright @copyright{} " (format-time-string "%Y") " "
251 (getenv "ORGANIZATION") | (progn user-full-name) "
253 @quotation
254 Permission is granted to copy, distribute and/or modify this document
255 under the terms of the GNU Free Documentation License, Version 1.3
256 or any later version published by the Free Software Foundation;
257 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
258 A copy of the license is included in the section entitled ``GNU
259 Free Documentation License''.
261 A copy of the license is also available from the Free Software
262 Foundation Web site at @url{https://www.gnu.org/licenses/fdl.html}.
264 @end quotation
266 The document was typeset with
267 @uref{https://www.gnu.org/software/texinfo/, GNU Texinfo}.
269 @end copying
271 @titlepage
272 @title " str "
273 @subtitle " short-description "
274 @author " (getenv "ORGANIZATION") | (progn user-full-name)
275 " <" (progn user-mail-address) ">
276 @page
277 @vskip 0pt plus 1filll
278 @insertcopying
279 @end titlepage
281 @c Output the table of the contents at the beginning.
282 @contents
284 @ifnottex
285 @node Top
286 @top " str "
288 @insertcopying
289 @end ifnottex
291 @c Generate the nodes for this menu with `C-c C-u C-m'.
292 @menu
293 @end menu
295 @c Update all node entries with `C-c C-u C-n'.
296 @c Insert new nodes with `C-c C-c n'.
297 @node Chapter One
298 @chapter Chapter One
300 " _ "
302 @node Copying This Manual
303 @appendix Copying This Manual
305 @menu
306 * GNU Free Documentation License:: License for copying this manual.
307 @end menu
309 @c Get fdl.texi from https://www.gnu.org/licenses/fdl.html
310 @include fdl.texi
312 @node Index
313 @unnumbered Index
315 @printindex cp
317 @bye
319 "A list specifying text to insert by default into a new file.
320 Elements look like (CONDITION . ACTION) or ((CONDITION . DESCRIPTION) . ACTION).
321 CONDITION may be a regexp that must match the new file's name, or it may be
322 a symbol that must match the major mode for this element to apply.
323 Only the first matching element is effective.
324 Optional DESCRIPTION is a string for filling `auto-insert-prompt'.
325 ACTION may be a skeleton to insert (see `skeleton-insert'), an absolute
326 file-name or one relative to `auto-insert-directory' or a function to call.
327 ACTION may also be a vector containing several successive single actions as
328 described above, e.g. [\"header.insert\" date-and-author-update]."
329 :type '(alist :key-type
330 (choice (regexp :tag "Regexp matching file name")
331 (symbol :tag "Major mode")
332 (cons :tag "Condition and description"
333 (choice :tag "Condition"
334 (regexp :tag "Regexp matching file name")
335 (symbol :tag "Major mode"))
336 (string :tag "Description")))
337 ;; There's no custom equivalent of "repeat" for vectors.
338 :value-type (choice file function
339 (sexp :tag "Skeleton or vector")))
340 :version "27.1")
343 ;; Establish a default value for auto-insert-directory
344 (defcustom auto-insert-directory "~/insert/"
345 "Directory from which auto-inserted files are taken.
346 The value must be an absolute directory name;
347 thus, on a GNU or Unix system, it must end in a slash."
348 :type 'directory)
351 ;;;###autoload
352 (defun auto-insert ()
353 "Insert default contents into new files if variable `auto-insert' is non-nil.
354 Matches the visited file name against the elements of `auto-insert-alist'."
355 (interactive)
356 (and (not buffer-read-only)
357 (or (eq this-command 'auto-insert)
358 (and auto-insert
359 (bobp) (eobp)))
360 (let* ((case-fold-search nil)
361 (desc nil)
362 ;; Find first matching alist entry.
363 (action
364 (seq-some
365 (pcase-lambda (`(,cond . ,action))
366 (if (atom cond)
367 (setq desc cond)
368 (setq desc (cdr cond)
369 cond (car cond)))
370 (when (if (symbolp cond)
371 (derived-mode-p cond)
372 (and buffer-file-name
373 (string-match cond buffer-file-name)))
374 action))
375 auto-insert-alist)))
376 (goto-char 1)
377 ;; Now, if we found something, do it
378 (and action
379 (or (not (stringp action))
380 (file-readable-p (expand-file-name
381 action auto-insert-directory)))
382 (or (not auto-insert-query)
383 (if (eq auto-insert-query 'function)
384 (eq this-command 'auto-insert))
385 (y-or-n-p (format auto-insert-prompt desc)))
386 (mapc
387 (lambda (action)
388 (if (stringp action)
389 (if (file-readable-p
390 (setq action (expand-file-name
391 action auto-insert-directory)))
392 (insert-file-contents action))
393 (save-window-excursion
394 ;; make buffer visible before skeleton or function
395 ;; which might ask the user for something
396 (switch-to-buffer (current-buffer))
397 (if (and (consp action)
398 (not (functionp action)))
399 (skeleton-insert action)
400 (funcall action)))))
401 (if (vectorp action)
402 action
403 (vector action))))
404 (and (buffer-modified-p)
405 (not (eq this-command 'auto-insert))
406 (set-buffer-modified-p (eq auto-insert t)))))
407 ;; Return nil so that it could be used in
408 ;; `find-file-not-found-functions', though that's probably inadvisable.
409 nil)
412 ;;;###autoload
413 (defun define-auto-insert (condition action &optional after)
414 "Associate CONDITION with (additional) ACTION in `auto-insert-alist'.
415 Optional AFTER means to insert action after all existing actions for CONDITION,
416 or if CONDITION had no actions, after all other CONDITIONs."
417 (let ((elt (assoc condition auto-insert-alist)))
418 (if elt
419 (setcdr elt
420 (if (vectorp (cdr elt))
421 (vconcat (if after (cdr elt))
422 (if (vectorp action) action (vector action))
423 (if after () (cdr elt)))
424 (if after
425 (vector (cdr elt) action)
426 (vector action (cdr elt)))))
427 (if after
428 (nconc auto-insert-alist (list (cons condition action)))
429 (push (cons condition action) auto-insert-alist)))))
431 ;;;###autoload
432 (define-minor-mode auto-insert-mode
433 "Toggle Auto-insert mode, a global minor mode.
435 When Auto-insert mode is enabled, when new files are created you can
436 insert a template for the file depending on the mode of the buffer."
437 :global t :group 'auto-insert
438 (if auto-insert-mode
439 (add-hook 'find-file-hook 'auto-insert)
440 (remove-hook 'find-file-hook 'auto-insert)))
442 (provide 'autoinsert)
444 ;;; autoinsert.el ends here