(sh-indent-line): Use indent-line-to.
[bpt/emacs.git] / lisp / progmodes / sh-script.el
1 ;;; sh-script.el --- shell-script editing commands for Emacs
2
3 ;; Copyright (C) 1993, 94, 95, 96, 97, 1999, 2001, 2003
4 ;; Free Software Foundation, Inc.
5
6 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
7 ;; Version: 2.0f
8 ;; Maintainer: FSF
9 ;; Keywords: languages, unix
10
11 ;; This file is part of GNU Emacs.
12
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 2, or (at your option)
16 ;; any later version.
17
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.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 ;;; Commentary:
29
30 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
31 ;; as various derivatives are supported and easily derived from. Structured
32 ;; statements can be inserted with one command or abbrev. Completion is
33 ;; available for filenames, variables known from the script, the shell and
34 ;; the environment as well as commands.
35
36 ;;; Known Bugs:
37
38 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
39 ;; - Variables in `"' strings aren't fontified because there's no way of
40 ;; syntactically distinguishing those from `'' strings.
41
42 ;; Indentation
43 ;; ===========
44 ;; Indentation for rc and es modes is very limited, but for Bourne shells
45 ;; and its derivatives it is quite customizable.
46 ;;
47 ;; The following description applies to sh and derived shells (bash,
48 ;; zsh, ...).
49 ;;
50 ;; There are various customization variables which allow tailoring to
51 ;; a wide variety of styles. Most of these variables are named
52 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
53 ;; sh-indent-after-if controls the indenting of a line following
54 ;; an if statement, and sh-indent-for-fi controls the indentation
55 ;; of the line containing the fi.
56 ;;
57 ;; You can set each to a numeric value, but it is often more convenient
58 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
59 ;; By changing this one variable you can increase or decrease how much
60 ;; indentation there is. Valid symbols:
61 ;;
62 ;; + Indent right by sh-basic-offset
63 ;; - Indent left by sh-basic-offset
64 ;; ++ Indent right twice sh-basic-offset
65 ;; -- Indent left twice sh-basic-offset
66 ;; * Indent right half sh-basic-offset
67 ;; / Indent left half sh-basic-offset.
68 ;;
69 ;; There are 4 commands to help set the indentation variables:
70 ;;
71 ;; `sh-show-indent'
72 ;; This shows what variable controls the indentation of the current
73 ;; line and its value.
74 ;;
75 ;; `sh-set-indent'
76 ;; This allows you to set the value of the variable controlling the
77 ;; current line's indentation. You can enter a number or one of a
78 ;; number of special symbols to denote the value of sh-basic-offset,
79 ;; or its negative, or half it, or twice it, etc. If you've used
80 ;; cc-mode this should be familiar. If you forget which symbols are
81 ;; valid simply press C-h at the prompt.
82 ;;
83 ;; `sh-learn-line-indent'
84 ;; Simply make the line look the way you want it, then invoke this
85 ;; command. It will set the variable to the value that makes the line
86 ;; indent like that. If called with a prefix argument then it will set
87 ;; the value to one of the symbols if applicable.
88 ;;
89 ;; `sh-learn-buffer-indent'
90 ;; This is the deluxe function! It "learns" the whole buffer (use
91 ;; narrowing if you want it to process only part). It outputs to a
92 ;; buffer *indent* any conflicts it finds, and all the variables it has
93 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
94 ;; easily find where something was set. It is popped to automatically
95 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
96 ;; non-nil.
97 ;; `sh-indent-comment' will be set if all comments follow the same
98 ;; pattern; if they don't it will be set to nil.
99 ;; Whether `sh-basic-offset' is set is determined by variable
100 ;; `sh-learn-basic-offset'.
101 ;;
102 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
103 ;; (e.g. if there are large case statements). Perhaps it does not make
104 ;; sense to run it on large buffers: if lots of lines have different
105 ;; indentation styles it will produce a lot of diagnostics in the
106 ;; *indent* buffer; if there is a consistent style then running
107 ;; `sh-learn-buffer-indent' on a small region of the buffer should
108 ;; suffice.
109 ;;
110 ;; Saving indentation values
111 ;; -------------------------
112 ;; After you've learned the values in a buffer, how to you remember
113 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
114 ;; would make this unnecessary; simply learn the values when you visit
115 ;; the buffer.
116 ;; You can do this automatically like this:
117 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
118 ;;
119 ;; However... `sh-learn-buffer-indent' is extremely slow,
120 ;; especially on large-ish buffer. Also, if there are conflicts the
121 ;; "last one wins" which may not produce the desired setting.
122 ;;
123 ;; So...There is a minimal way of being able to save indentation values and
124 ;; to reload them in another buffer or at another point in time.
125 ;;
126 ;; Use `sh-name-style' to give a name to the indentation settings of
127 ;; the current buffer.
128 ;; Use `sh-load-style' to load indentation settings for the current
129 ;; buffer from a specific style.
130 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
131 ;; in lisp code. You can then store it in a file and later use
132 ;; `load-file' to load it.
133 ;;
134 ;; Indentation variables - buffer local or global?
135 ;; ----------------------------------------------
136 ;; I think that often having them buffer-local makes sense,
137 ;; especially if one is using `sh-learn-buffer-indent'. However, if
138 ;; a user sets values using customization, these changes won't appear
139 ;; to work if the variables are already local!
140 ;;
141 ;; To get round this, there is a variable `sh-make-vars-local' and 2
142 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
143 ;;
144 ;; If `sh-make-vars-local' is non-nil, then these variables become
145 ;; buffer local when the mode is established.
146 ;; If this is nil, then the variables are global. At any time you
147 ;; can make them local with the command `sh-make-vars-local'.
148 ;; Conversely, to update with the global values you can use the
149 ;; command `sh-reset-indent-vars-to-global-values'.
150 ;;
151 ;; This may be awkward, but the intent is to cover all cases.
152 ;;
153 ;; Awkward things, pitfalls
154 ;; ------------------------
155 ;; Indentation for a sh script is complicated for a number of reasons:
156 ;;
157 ;; 1. You can't format by simply looking at symbols, you need to look
158 ;; at keywords. [This is not the case for rc and es shells.]
159 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
160 ;; as a stand-alone symbol (in a case alternative). This makes
161 ;; things quite tricky!
162 ;; 3. Here-documents in a script should be treated "as is", and when
163 ;; they terminate we want to revert to the indentation of the line
164 ;; containing the "<<" symbol.
165 ;; 4. A line may be continued using the "\".
166 ;; 5. The character "#" (outside a string) normally starts a comment,
167 ;; but it doesn't in the sequence "$#"!
168 ;;
169 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
170 ;; uses, that of a text's syntax property. This, however, has 2
171 ;; disadvantages:
172 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
173 ;; case alternative, to find any here documents, and handle "$#".
174 ;; 2. Setting the text property makes the buffer modified. If the
175 ;; buffer is read-only buffer we have to cheat and bypass the read-only
176 ;; status. This is for cases where the buffer started read-only buffer
177 ;; but the user issued `toggle-read-only'.
178 ;;
179 ;; Bugs
180 ;; ----
181 ;; - Indenting many lines is slow. It currently does each line
182 ;; independently, rather than saving state information.
183 ;;
184 ;; - `sh-learn-buffer-indent' is extremely slow.
185 ;;
186 ;; Richard Sharman <rsharman@pobox.com> June 1999.
187
188 ;;; Code:
189
190 ;; page 1: variables and settings
191 ;; page 2: indentation stuff
192 ;; page 3: mode-command and utility functions
193 ;; page 4: statement syntax-commands for various shells
194 ;; page 5: various other commands
195
196 (eval-when-compile
197 (require 'skeleton)
198 (require 'cl)
199 (require 'comint))
200 (require 'executable)
201
202
203
204 (defgroup sh nil
205 "Shell programming utilities"
206 :group 'unix
207 :group 'languages)
208
209 (defgroup sh-script nil
210 "Shell script mode"
211 :group 'sh
212 :prefix "sh-")
213
214
215 (defcustom sh-ancestor-alist
216 '((ash . sh)
217 (bash . jsh)
218 (bash2 . jsh)
219 (dtksh . ksh)
220 (es . rc)
221 (itcsh . tcsh)
222 (jcsh . csh)
223 (jsh . sh)
224 (ksh . ksh88)
225 (ksh88 . jsh)
226 (oash . sh)
227 (pdksh . ksh88)
228 (posix . sh)
229 (tcsh . csh)
230 (wksh . ksh88)
231 (wsh . sh)
232 (zsh . ksh88)
233 (rpm . sh))
234 "*Alist showing the direct ancestor of various shells.
235 This is the basis for `sh-feature'. See also `sh-alias-alist'.
236 By default we have the following three hierarchies:
237
238 csh C Shell
239 jcsh C Shell with Job Control
240 tcsh Turbo C Shell
241 itcsh ? Turbo C Shell
242 rc Plan 9 Shell
243 es Extensible Shell
244 sh Bourne Shell
245 ash ? Shell
246 jsh Bourne Shell with Job Control
247 bash GNU Bourne Again Shell
248 ksh88 Korn Shell '88
249 ksh Korn Shell '93
250 dtksh CDE Desktop Korn Shell
251 pdksh Public Domain Korn Shell
252 wksh Window Korn Shell
253 zsh Z Shell
254 oash SCO OA (curses) Shell
255 posix IEEE 1003.2 Shell Standard
256 wsh ? Shell"
257 :type '(repeat (cons symbol symbol))
258 :group 'sh-script)
259
260
261 (defcustom sh-alias-alist
262 (append (if (eq system-type 'gnu/linux)
263 '((csh . tcsh)
264 (ksh . pdksh)))
265 ;; for the time being
266 '((ksh . ksh88)
267 (bash2 . bash)
268 (sh5 . sh)))
269 "*Alist for transforming shell names to what they really are.
270 Use this where the name of the executable doesn't correspond to the type of
271 shell it really is."
272 :type '(repeat (cons symbol symbol))
273 :group 'sh-script)
274
275
276 (defcustom sh-shell-file
277 (or
278 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
279 ;; the executable extension, so comparisons with the list of
280 ;; known shells work.
281 (and (memq system-type '(ms-dos windows-nt))
282 (let* ((shell (getenv "SHELL"))
283 (shell-base
284 (and shell (file-name-nondirectory shell))))
285 ;; shell-script mode doesn't support DOS/Windows shells,
286 ;; so use the default instead.
287 (if (or (null shell)
288 (member (downcase shell-base)
289 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
290 "cmdproxy.exe")))
291 "/bin/sh"
292 (file-name-sans-extension (downcase shell)))))
293 (getenv "SHELL")
294 "/bin/sh")
295 "*The executable file name for the shell being programmed."
296 :type 'string
297 :group 'sh-script)
298
299
300 (defcustom sh-shell-arg
301 ;; bash does not need any options when run in a shell script,
302 '((bash)
303 (csh . "-f")
304 (pdksh)
305 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
306 (ksh88)
307 ;; -p means don't initialize functions from the environment.
308 (rc . "-p")
309 ;; Someone proposed -motif, but we don't want to encourage
310 ;; use of a non-free widget set.
311 (wksh)
312 ;; -f means don't run .zshrc.
313 (zsh . "-f"))
314 "*Single argument string for the magic number. See `sh-feature'."
315 :type '(repeat (cons (symbol :tag "Shell")
316 (choice (const :tag "No Arguments" nil)
317 (string :tag "Arguments")
318 (cons :format "Evaluate: %v"
319 (const :format "" eval)
320 sexp))))
321 :group 'sh-script)
322
323 (defcustom sh-imenu-generic-expression
324 `((sh
325 . ((nil "^\\s-*\\(function\\s-+\\)?\\([A-Za-z_][A-Za-z_0-9]+\\)\\s-*()" 2))))
326 "*Alist of regular expressions for recognizing shell function definitions.
327 See `sh-feature' and `imenu-generic-expression'."
328 :type '(alist :key-type (symbol :tag "Shell")
329 :value-type (alist :key-type (choice :tag "Title"
330 string
331 (const :tag "None" nil))
332 :value-type
333 (repeat :tag "Regexp, index..." sexp)))
334 :group 'sh-script
335 :version "20.4")
336
337 (defvar sh-shell-variables nil
338 "Alist of shell variable names that should be included in completion.
339 These are used for completion in addition to all the variables named
340 in `process-environment'. Each element looks like (VAR . VAR), where
341 the car and cdr are the same symbol.")
342
343 (defvar sh-shell-variables-initialized nil
344 "Non-nil if `sh-shell-variables' is initialized.")
345
346 (defun sh-canonicalize-shell (shell)
347 "Convert a shell name SHELL to the one we should handle it as."
348 (if (string-match "\\.exe\\'" shell)
349 (setq shell (substring shell 0 (match-beginning 0))))
350 (or (symbolp shell)
351 (setq shell (intern shell)))
352 (or (cdr (assq shell sh-alias-alist))
353 shell))
354
355 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
356 "The shell being programmed. This is set by \\[sh-set-shell].")
357
358 ;; I turned off this feature because it doesn't permit typing commands
359 ;; in the usual way without help.
360 ;;(defvar sh-abbrevs
361 ;; '((csh eval sh-abbrevs shell
362 ;; "switch" 'sh-case
363 ;; "getopts" 'sh-while-getopts)
364
365 ;; (es eval sh-abbrevs shell
366 ;; "function" 'sh-function)
367
368 ;; (ksh88 eval sh-abbrevs sh
369 ;; "select" 'sh-select)
370
371 ;; (rc eval sh-abbrevs shell
372 ;; "case" 'sh-case
373 ;; "function" 'sh-function)
374
375 ;; (sh eval sh-abbrevs shell
376 ;; "case" 'sh-case
377 ;; "function" 'sh-function
378 ;; "until" 'sh-until
379 ;; "getopts" 'sh-while-getopts)
380
381 ;; ;; The next entry is only used for defining the others
382 ;; (shell "for" sh-for
383 ;; "loop" sh-indexed-loop
384 ;; "if" sh-if
385 ;; "tmpfile" sh-tmp-file
386 ;; "while" sh-while)
387
388 ;; (zsh eval sh-abbrevs ksh88
389 ;; "repeat" 'sh-repeat))
390 ;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
391 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
392 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
393
394
395
396 (defvar sh-mode-syntax-table
397 '((sh eval sh-mode-syntax-table ()
398 ?\# "<"
399 ?\n ">#"
400 ?\" "\"\""
401 ?\' "\"'"
402 ?\` "\"`"
403 ?! "_"
404 ?% "_"
405 ?: "_"
406 ?. "_"
407 ?^ "_"
408 ?~ "_"
409 ?< "."
410 ?> ".")
411 (csh eval identity sh)
412 (rc eval identity sh))
413
414 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
415
416 (defvar sh-mode-map
417 (let ((map (make-sparse-keymap))
418 (menu-map (make-sparse-keymap "Insert")))
419 (define-key map "\C-c(" 'sh-function)
420 (define-key map "\C-c\C-w" 'sh-while)
421 (define-key map "\C-c\C-u" 'sh-until)
422 (define-key map "\C-c\C-t" 'sh-tmp-file)
423 (define-key map "\C-c\C-s" 'sh-select)
424 (define-key map "\C-c\C-r" 'sh-repeat)
425 (define-key map "\C-c\C-o" 'sh-while-getopts)
426 (define-key map "\C-c\C-l" 'sh-indexed-loop)
427 (define-key map "\C-c\C-i" 'sh-if)
428 (define-key map "\C-c\C-f" 'sh-for)
429 (define-key map "\C-c\C-c" 'sh-case)
430 (define-key map "\C-c?" 'sh-show-indent)
431 (define-key map "\C-c=" 'sh-set-indent)
432 (define-key map "\C-c<" 'sh-learn-line-indent)
433 (define-key map "\C-c>" 'sh-learn-buffer-indent)
434
435 (define-key map "=" 'sh-assignment)
436 (define-key map "\C-c+" 'sh-add)
437 (define-key map "\C-\M-x" 'sh-execute-region)
438 (define-key map "\C-c\C-x" 'executable-interpret)
439 (define-key map "<" 'sh-maybe-here-document)
440 (define-key map "(" 'skeleton-pair-insert-maybe)
441 (define-key map "{" 'skeleton-pair-insert-maybe)
442 (define-key map "[" 'skeleton-pair-insert-maybe)
443 (define-key map "'" 'skeleton-pair-insert-maybe)
444 (define-key map "`" 'skeleton-pair-insert-maybe)
445 (define-key map "\"" 'skeleton-pair-insert-maybe)
446
447 (define-key map [remap complete-tag] 'comint-dynamic-complete)
448 (define-key map [remap newline-and-indent] 'sh-newline-and-indent)
449 (define-key map [remap delete-backward-char]
450 'backward-delete-char-untabify)
451 (define-key map "\C-c:" 'sh-set-shell)
452 (define-key map [remap beginning-of-defun]
453 'sh-beginning-of-compound-command)
454 (define-key map [remap backward-sentence] 'sh-beginning-of-command)
455 (define-key map [remap forward-sentence] 'sh-end-of-command)
456 (define-key map [menu-bar insert] (cons "Insert" menu-map))
457 (define-key menu-map [sh-while] '("While Loop" . sh-while))
458 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
459 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
460 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
461 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
462 (define-key menu-map [sh-getopts] '("Options Loop" . sh-while-getopts))
463 (define-key menu-map [sh-indexed-loop] '("Indexed Loop" . sh-indexed-loop))
464 (define-key menu-map [sh-if] '("If Statement" . sh-if))
465 (define-key menu-map [sh-for] '("For Loop" . sh-for))
466 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
467 map)
468 "Keymap used in Shell-Script mode.")
469
470
471
472 (defcustom sh-dynamic-complete-functions
473 '(shell-dynamic-complete-environment-variable
474 shell-dynamic-complete-command
475 comint-dynamic-complete-filename)
476 "*Functions for doing TAB dynamic completion."
477 :type '(repeat function)
478 :group 'sh-script)
479
480
481 (defcustom sh-require-final-newline
482 '((csh . t)
483 (pdksh . t)
484 (rc eval . require-final-newline)
485 (sh eval . require-final-newline))
486 "*Value of `require-final-newline' in Shell-Script mode buffers.
487 See `sh-feature'."
488 :type '(repeat (cons (symbol :tag "Shell")
489 (choice (const :tag "require" t)
490 (cons :format "Evaluate: %v"
491 (const :format "" eval)
492 sexp))))
493 :group 'sh-script)
494
495
496 (defcustom sh-assignment-regexp
497 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
498 ;; actually spaces are only supported in let/(( ... ))
499 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
500 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
501 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
502 "*Regexp for the variable name and what may follow in an assignment.
503 First grouping matches the variable name. This is upto and including the `='
504 sign. See `sh-feature'."
505 :type '(repeat (cons (symbol :tag "Shell")
506 (choice regexp
507 (cons :format "Evaluate: %v"
508 (const :format "" eval)
509 sexp))))
510 :group 'sh-script)
511
512
513 (defcustom sh-indentation 4
514 "The width for further indentation in Shell-Script mode."
515 :type 'integer
516 :group 'sh-script)
517
518
519 (defcustom sh-remember-variable-min 3
520 "*Don't remember variables less than this length for completing reads."
521 :type 'integer
522 :group 'sh-script)
523
524
525 (defvar sh-header-marker nil
526 "When non-nil is the end of header for prepending by \\[sh-execute-region].
527 That command is also used for setting this variable.")
528
529
530 (defcustom sh-beginning-of-command
531 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
532 "*Regexp to determine the beginning of a shell command.
533 The actual command starts at the beginning of the second \\(grouping\\)."
534 :type 'regexp
535 :group 'sh-script)
536
537
538 (defcustom sh-end-of-command
539 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
540 "*Regexp to determine the end of a shell command.
541 The actual command ends at the end of the first \\(grouping\\)."
542 :type 'regexp
543 :group 'sh-script)
544
545
546
547 (defvar sh-here-document-word "EOF"
548 "Word to delimit here documents.")
549
550 (defvar sh-test
551 '((sh "[ ]" . 3)
552 (ksh88 "[[ ]]" . 4))
553 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
554
555
556 ;; customized this out of sheer bravado. not for the faint of heart.
557 ;; but it *did* have an asterisk in the docstring!
558 (defcustom sh-builtins
559 '((bash eval sh-append posix
560 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
561 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
562 "suspend" "typeset" "unalias")
563
564 ;; The next entry is only used for defining the others
565 (bourne eval sh-append shell
566 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
567 "times" "ulimit")
568
569 (csh eval sh-append shell
570 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
571 "setenv" "source" "time" "unalias" "unhash")
572
573 (dtksh eval identity wksh)
574
575 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
576 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
577
578 (jsh eval sh-append sh
579 "bg" "fg" "jobs" "kill" "stop" "suspend")
580
581 (jcsh eval sh-append csh
582 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
583
584 (ksh88 eval sh-append bourne
585 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
586 "typeset" "unalias" "whence")
587
588 (oash eval sh-append sh
589 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
590 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
591 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
592 "wmtitle" "wrefresh")
593
594 (pdksh eval sh-append ksh88
595 "bind")
596
597 (posix eval sh-append sh
598 "command")
599
600 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
601 "whatis")
602
603 (sh eval sh-append bourne
604 "hash" "test" "type")
605
606 ;; The next entry is only used for defining the others
607 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
608
609 (wksh eval sh-append ksh88
610 "Xt[A-Z][A-Za-z]*")
611
612 (zsh eval sh-append ksh88
613 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
614 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
615 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
616 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
617 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
618 "which"))
619 "*List of all shell builtins for completing read and fontification.
620 Note that on some systems not all builtins are available or some are
621 implemented as aliases. See `sh-feature'."
622 :type '(repeat (cons (symbol :tag "Shell")
623 (choice (repeat string)
624 (cons :format "Evaluate: %v"
625 (const :format "" eval)
626 sexp))))
627 :group 'sh-script)
628
629
630
631 (defcustom sh-leading-keywords
632 '((csh "else")
633
634 (es "true" "unwind-protect" "whatis")
635
636 (rc "else")
637
638 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
639 "*List of keywords that may be immediately followed by a builtin or keyword.
640 Given some confusion between keywords and builtins depending on shell and
641 system, the distinction here has been based on whether they influence the
642 flow of control or syntax. See `sh-feature'."
643 :type '(repeat (cons (symbol :tag "Shell")
644 (choice (repeat string)
645 (cons :format "Evaluate: %v"
646 (const :format "" eval)
647 sexp))))
648 :group 'sh-script)
649
650
651 (defcustom sh-other-keywords
652 '((bash eval sh-append bourne
653 "bye" "logout")
654
655 ;; The next entry is only used for defining the others
656 (bourne eval sh-append sh
657 "function")
658
659 (csh eval sh-append shell
660 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
661 "if" "logout" "onintr" "repeat" "switch" "then" "while")
662
663 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
664 "return" "throw" "while")
665
666 (ksh88 eval sh-append bourne
667 "select")
668
669 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
670 "while")
671
672 (sh eval sh-append shell
673 "done" "esac" "fi" "for" "in" "return")
674
675 ;; The next entry is only used for defining the others
676 (shell "break" "case" "continue" "exec" "exit")
677
678 (zsh eval sh-append bash
679 "select"))
680 "*List of keywords not in `sh-leading-keywords'.
681 See `sh-feature'."
682 :type '(repeat (cons (symbol :tag "Shell")
683 (choice (repeat string)
684 (cons :format "Evaluate: %v"
685 (const :format "" eval)
686 sexp))))
687 :group 'sh-script)
688
689
690
691 (defvar sh-variables
692 '((bash eval sh-append sh
693 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
694 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
695 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
696 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
697 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
698 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
699 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
700 "SECONDS" "SHLVL" "TMOUT" "UID")
701
702 (csh eval sh-append shell
703 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
704 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
705 "shell" "status" "time" "verbose")
706
707 (es eval sh-append shell
708 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
709 "pid" "prompt" "signals")
710
711 (jcsh eval sh-append csh
712 "notify")
713
714 (ksh88 eval sh-append sh
715 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
716 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
717 "TMOUT")
718
719 (oash eval sh-append sh
720 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
721
722 (rc eval sh-append shell
723 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
724 "prompt" "status")
725
726 (sh eval sh-append shell
727 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
728
729 ;; The next entry is only used for defining the others
730 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
731 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
732 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
733 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
734
735 (tcsh eval sh-append csh
736 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
737 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
738 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
739 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
740 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
741 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
742 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
743 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
744 "wordchars")
745
746 (zsh eval sh-append ksh88
747 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
748 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
749 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
750 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
751 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
752 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
753 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
754 "List of all shell variables available for completing read.
755 See `sh-feature'.")
756
757 \f
758 ;; Font-Lock support
759
760 (defface sh-heredoc-face
761 '((((class color)
762 (background dark))
763 (:foreground "yellow" :weight bold))
764 (((class color)
765 (background light))
766 (:foreground "tan" ))
767 (t
768 (:weight bold)))
769 "Face to show a here-document"
770 :group 'sh-indentation)
771 (defvar sh-heredoc-face 'sh-heredoc-face)
772
773
774 (defvar sh-font-lock-keywords
775 '((csh eval sh-append shell
776 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
777 font-lock-variable-name-face))
778
779 (es eval sh-append executable-font-lock-keywords
780 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
781 font-lock-variable-name-face))
782
783 (rc eval identity es)
784
785 (sh eval sh-append shell
786 ;; Variable names.
787 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
788 font-lock-variable-name-face)
789 ;; Function names.
790 '("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
791 '("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
792 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t)))
793
794 ;; The next entry is only used for defining the others
795 (shell eval sh-append executable-font-lock-keywords
796 '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face)
797 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
798 font-lock-variable-name-face))
799 (rpm eval sh-append rpm2
800 '("%{?\\(\\sw+\\)" 1 font-lock-keyword-face))
801 (rpm2 eval sh-append shell
802 '("^\\(\\sw+\\):" 1 font-lock-variable-name-face)))
803 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
804
805 (defvar sh-font-lock-keywords-1
806 '((sh "[ \t]in\\>"))
807 "Subdued level highlighting for Shell Script modes.")
808
809 (defvar sh-font-lock-keywords-2 ()
810 "Gaudy level highlighting for Shell Script modes.")
811
812 ;; These are used for the syntax table stuff (derived from cperl-mode).
813 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
814 (defconst sh-st-punc (string-to-syntax "."))
815 (defconst sh-st-symbol (string-to-syntax "_"))
816 (defconst sh-here-doc-syntax (string-to-syntax "|")) ;; generic string
817
818 (defconst sh-here-doc-open-re "<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\|\\s_\\)+\\).*\\(\n\\)")
819
820 (defvar sh-here-doc-markers nil)
821 (make-variable-buffer-local 'sh-here-doc-markers)
822 (defvar sh-here-doc-re sh-here-doc-open-re)
823 (make-variable-buffer-local 'sh-here-doc-re)
824
825 (defun sh-font-lock-close-heredoc (bol eof indented)
826 "Determine the syntax of the \\n after an EOF.
827 If non-nil INDENTED indicates that the EOF was indented."
828 (let* ((eof-re (if eof (regexp-quote eof) ""))
829 ;; A rough regexp that should find the opening <<EOF back.
830 (sre (concat "<<\\(-?\\)\\s-*['\"\\]?"
831 ;; Use \s| to cheaply check it's an open-heredoc.
832 eof-re "['\"]?\\([ \t|;&)<>].*\\)?\\s|"))
833 ;; A regexp that will find other EOFs.
834 (ere (concat "^" (if indented "[ \t]*") eof-re "\n"))
835 (start (save-excursion
836 (goto-char bol)
837 (re-search-backward (concat sre "\\|" ere) nil t))))
838 ;; If subgroup 1 matched, we found an open-heredoc, otherwise we first
839 ;; found a close-heredoc which makes the current close-heredoc inoperant.
840 (cond
841 ((when (and start (match-end 1)
842 (not (and indented (= (match-beginning 1) (match-end 1))))
843 (not (sh-in-comment-or-string (match-beginning 0))))
844 ;; Make sure our `<<' is not the EOF1 of a `cat <<EOF1 <<EOF2'.
845 (save-excursion
846 (goto-char start)
847 (setq start (line-beginning-position 2))
848 (while
849 (progn
850 (re-search-forward "<<") ; Skip ourselves.
851 (and (re-search-forward sh-here-doc-open-re start 'move)
852 (goto-char (match-beginning 0))
853 (sh-in-comment-or-string (point)))))
854 ;; No <<EOF2 found after our <<.
855 (= (point) start)))
856 sh-here-doc-syntax)
857 ((not (or start (save-excursion (re-search-forward sre nil t))))
858 ;; There's no <<EOF either before or after us,
859 ;; so we should remove ourselves from font-lock's keywords.
860 (setq sh-here-doc-markers (delete eof sh-here-doc-markers))
861 (setq sh-here-doc-re
862 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
863 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))
864 nil))))
865
866 (defun sh-font-lock-open-heredoc (start string)
867 "Determine the syntax of the \\n after a <<EOF.
868 START is the position of <<.
869 STRING is the actual word used as delimiter (f.ex. \"EOF\").
870 INDENTED is non-nil if the here document's content (and the EOF mark) can
871 be indented (i.e. a <<- was used rather than just <<)."
872 (unless (or (memq (char-before start) '(?< ?>))
873 (sh-in-comment-or-string start))
874 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
875 ;; font-lock keywords to detect the end of this here document.
876 (let ((str (replace-regexp-in-string "['\"]" "" string)))
877 (unless (member str sh-here-doc-markers)
878 (push str sh-here-doc-markers)
879 (setq sh-here-doc-re
880 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
881 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))))
882 sh-here-doc-syntax))
883
884 (defun sh-font-lock-here-doc (limit)
885 "Search for a heredoc marker."
886 ;; This looks silly, but it's because `sh-here-doc-re' keeps changing.
887 (re-search-forward sh-here-doc-re limit t))
888
889 (defun sh-font-lock-paren (start)
890 (save-excursion
891 (goto-char start)
892 ;; Skip through all patterns
893 (while
894 (progn
895 (forward-comment (- (point-max)))
896 ;; Skip through one pattern
897 (while
898 (or (/= 0 (skip-syntax-backward "w_"))
899 (/= 0 (skip-chars-backward "?*/"))
900 (when (memq (char-before) '(?\" ?\'))
901 (condition-case nil (progn (backward-sexp 1) t)
902 (error nil)))))
903 (forward-comment (- (point-max)))
904 (when (eq (char-before) ?|)
905 (backward-char 1) t)))
906 (when (save-excursion (backward-char 2) (looking-at ";;\\|in"))
907 sh-st-punc)))
908
909 (defconst sh-font-lock-syntactic-keywords
910 ;; A `#' begins a comment when it is unquoted and at the beginning of a
911 ;; word. In the shell, words are separated by metacharacters.
912 ;; The list of special chars is taken from the single-unix spec
913 ;; of the shell command language (under `quoting') but with `$' removed.
914 `(("[^|&;<>()`\\\"' \t\n]\\(#+\\)" 1 ,sh-st-symbol)
915 ;; Find HEREDOC starters and add a corresponding rule for the ender.
916 (sh-font-lock-here-doc
917 (2 (sh-font-lock-open-heredoc
918 (match-beginning 0) (match-string 1)) nil t)
919 (5 (sh-font-lock-close-heredoc
920 (match-beginning 0) (match-string 4)
921 (and (match-beginning 3) (/= (match-beginning 3) (match-end 3))))
922 nil t))
923 ;; Distinguish the special close-paren in `case'.
924 (")" 0 (sh-font-lock-paren (match-beginning 0)))))
925
926 (defun sh-font-lock-syntactic-face-function (state)
927 (if (nth 3 state)
928 (if (char-valid-p (nth 3 state))
929 font-lock-string-face
930 sh-heredoc-face)
931 font-lock-comment-face))
932
933 (defgroup sh-indentation nil
934 "Variables controlling indentation in shell scripts.
935
936 Note: customizing these variables will not affect existing buffers if
937 `sh-make-vars-local' is no-nil. See the documentation for
938 variable `sh-make-vars-local', command `sh-make-vars-local'
939 and command `sh-reset-indent-vars-to-global-values'."
940 :group 'sh-script)
941
942
943 (defcustom sh-set-shell-hook nil
944 "*Hook run by `sh-set-shell'."
945 :type 'hook
946 :group 'sh-script)
947
948 (defcustom sh-mode-hook nil
949 "*Hook run by `sh-mode'."
950 :type 'hook
951 :group 'sh-script)
952
953 (defcustom sh-learn-basic-offset nil
954 "*When `sh-guess-basic-offset' should learn `sh-basic-offset'.
955
956 nil mean: never.
957 t means: only if there seems to be an obvious value.
958 Anything else means: whenever we have a \"good guess\" as to the value."
959 :type '(choice
960 (const :tag "Never" nil)
961 (const :tag "Only if sure" t)
962 (const :tag "If have a good guess" usually))
963 :group 'sh-indentation)
964
965 (defcustom sh-popup-occur-buffer nil
966 "*Controls when `sh-learn-buffer-indent' pops the *indent* buffer.
967 If t it is always shown. If nil, it is shown only when there
968 are conflicts."
969 :type '(choice
970 (const :tag "Only when there are conflicts." nil)
971 (const :tag "Always" t))
972 :group 'sh-indentation)
973
974 (defcustom sh-blink t
975 "*If non-nil, `sh-show-indent' shows the line indentation is relative to.
976 The position on the line is not necessarily meaningful.
977 In some cases the line will be the matching keyword, but this is not
978 always the case."
979 :type 'boolean
980 :group 'sh-indentation)
981
982 (defcustom sh-first-lines-indent 0
983 "*The indentation of the first non-blank non-comment line.
984 Usually 0 meaning first column.
985 Can be set to a number, or to nil which means leave it as is."
986 :type '(choice
987 (const :tag "Leave as is" nil)
988 (integer :tag "Column number"
989 :menu-tag "Indent to this col (0 means first col)" ))
990 :group 'sh-indentation)
991
992
993 (defcustom sh-basic-offset 4
994 "*The default indentation increment.
995 This value is used for the + and - symbols in an indentation variable."
996 :type 'integer
997 :group 'sh-indentation)
998
999 (defcustom sh-indent-comment nil
1000 "*How a comment line is to be indented.
1001 nil means leave it as it is;
1002 t means indent it as a normal line, aligning it to previous non-blank
1003 non-comment line;
1004 a number means align to that column, e.g. 0 means fist column."
1005 :type '(choice
1006 (const :tag "Leave as is." nil)
1007 (const :tag "Indent as a normal line." t)
1008 (integer :menu-tag "Indent to this col (0 means first col)."
1009 :tag "Indent to column number.") )
1010 :group 'sh-indentation)
1011
1012
1013 (defvar sh-debug nil
1014 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1015
1016
1017 ;; Uncomment this defun and comment the defmacro for debugging.
1018 ;; (defun sh-debug (&rest args)
1019 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1020 ;; (if sh-debug
1021 ;; (apply 'message args)))
1022 (defmacro sh-debug (&rest args))
1023
1024 (defconst sh-symbol-list
1025 '((const :tag "+ " :value +
1026 :menu-tag "+ Indent right by sh-basic-offset")
1027 (const :tag "- " :value -
1028 :menu-tag "- Indent left by sh-basic-offset")
1029 (const :tag "++" :value ++
1030 :menu-tag "++ Indent right twice sh-basic-offset")
1031 (const :tag "--" :value --
1032 :menu-tag "-- Indent left twice sh-basic-offset")
1033 (const :tag "* " :value *
1034 :menu-tag "* Indent right half sh-basic-offset")
1035 (const :tag "/ " :value /
1036 :menu-tag "/ Indent left half sh-basic-offset")))
1037
1038 (defcustom sh-indent-for-else 0
1039 "*How much to indent an else relative to an if. Usually 0."
1040 :type `(choice
1041 (integer :menu-tag "A number (positive=>indent right)"
1042 :tag "A number")
1043 (const :tag "--") ;; separator!
1044 ,@ sh-symbol-list
1045 )
1046 :group 'sh-indentation)
1047
1048 (defconst sh-number-or-symbol-list
1049 (append '((integer :menu-tag "A number (positive=>indent right)"
1050 :tag "A number")
1051 (const :tag "--")) ; separator
1052 sh-symbol-list))
1053
1054 (defcustom sh-indent-for-fi 0
1055 "*How much to indent a fi relative to an if. Usually 0."
1056 :type `(choice ,@ sh-number-or-symbol-list )
1057 :group 'sh-indentation)
1058
1059 (defcustom sh-indent-for-done '0
1060 "*How much to indent a done relative to its matching stmt. Usually 0."
1061 :type `(choice ,@ sh-number-or-symbol-list )
1062 :group 'sh-indentation)
1063
1064 (defcustom sh-indent-after-else '+
1065 "*How much to indent a statement after an else statement."
1066 :type `(choice ,@ sh-number-or-symbol-list )
1067 :group 'sh-indentation)
1068
1069 (defcustom sh-indent-after-if '+
1070 "*How much to indent a statement after an if statement.
1071 This includes lines after else and elif statements, too, but
1072 does not affect then else elif or fi statements themselves."
1073 :type `(choice ,@ sh-number-or-symbol-list )
1074 :group 'sh-indentation)
1075
1076 (defcustom sh-indent-for-then '+
1077 "*How much to indent a then relative to an if."
1078 :type `(choice ,@ sh-number-or-symbol-list )
1079 :group 'sh-indentation)
1080
1081 (defcustom sh-indent-for-do '*
1082 "*How much to indent a do statement.
1083 This is relative to the statement before the do, i.e. the
1084 while until or for statement."
1085 :type `(choice ,@ sh-number-or-symbol-list)
1086 :group 'sh-indentation)
1087
1088 (defcustom sh-indent-after-do '*
1089 "*How much to indent a line after a do statement.
1090 This is used when the do is the first word of the line.
1091 This is relative to the statement before the do, e.g. a
1092 while for repeat or select statement."
1093 :type `(choice ,@ sh-number-or-symbol-list)
1094 :group 'sh-indentation)
1095
1096 (defcustom sh-indent-after-loop-construct '+
1097 "*How much to indent a statement after a loop construct.
1098
1099 This variable is used when the keyword \"do\" is on the same line as the
1100 loop statement (e.g. \"until\", \"while\" or \"for\").
1101 If the do is on a line by itself, then `sh-indent-after-do' is used instead."
1102 :type `(choice ,@ sh-number-or-symbol-list)
1103 :group 'sh-indentation)
1104
1105
1106 (defcustom sh-indent-after-done 0
1107 "*How much to indent a statement after a \"done\" keyword.
1108 Normally this is 0, which aligns the \"done\" to the matching
1109 looping construct line.
1110 Setting it non-zero allows you to have the \"do\" statement on a line
1111 by itself and align the done under to do."
1112 :type `(choice ,@ sh-number-or-symbol-list)
1113 :group 'sh-indentation)
1114
1115 (defcustom sh-indent-for-case-label '+
1116 "*How much to indent a case label statement.
1117 This is relative to the line containing the case statement."
1118 :type `(choice ,@ sh-number-or-symbol-list)
1119 :group 'sh-indentation)
1120
1121 (defcustom sh-indent-for-case-alt '++
1122 "*How much to indent statements after the case label.
1123 This is relative to the line containing the case statement."
1124 :type `(choice ,@ sh-number-or-symbol-list)
1125 :group 'sh-indentation)
1126
1127
1128 (defcustom sh-indent-for-continuation '+
1129 "*How much to indent for a continuation statement."
1130 :type `(choice ,@ sh-number-or-symbol-list)
1131 :group 'sh-indentation)
1132
1133 (defcustom sh-indent-after-open '+
1134 "*How much to indent after a line with an opening parenthesis or brace.
1135 For an open paren after a function `sh-indent-after-function' is used."
1136 :type `(choice ,@ sh-number-or-symbol-list)
1137 :group 'sh-indentation)
1138
1139 (defcustom sh-indent-after-function '+
1140 "*How much to indent after a function line."
1141 :type `(choice ,@ sh-number-or-symbol-list)
1142 :group 'sh-indentation)
1143
1144 ;; These 2 are for the rc shell:
1145
1146 (defcustom sh-indent-after-switch '+
1147 "*How much to indent a case statement relative to the switch statement.
1148 This is for the rc shell."
1149 :type `(choice ,@ sh-number-or-symbol-list)
1150 :group 'sh-indentation)
1151
1152 (defcustom sh-indent-after-case '+
1153 "*How much to indent a statement relative to the case statement.
1154 This is for the rc shell."
1155 :type `(choice ,@ sh-number-or-symbol-list)
1156 :group 'sh-indentation)
1157
1158 ;; Internal use - not designed to be changed by the user:
1159
1160 (defun sh-mkword-regexpr (word)
1161 "Make a regexp which matches WORD as a word.
1162 This specifically excludes an occurrence of WORD followed by
1163 punctuation characters like '-'."
1164 (concat word "\\([^-a-z0-9_]\\|$\\)"))
1165
1166 (defconst sh-re-done (sh-mkword-regexpr "done"))
1167
1168
1169 (defconst sh-kws-for-done
1170 '((sh . ( "while" "until" "for" ) )
1171 (bash . ( "while" "until" "for" "select" ) )
1172 (ksh88 . ( "while" "until" "for" "select" ) )
1173 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1174 "Which keywords can match the word `done' in this shell.")
1175
1176
1177 (defconst sh-indent-supported
1178 '((sh . t)
1179 (csh . nil)
1180 (rc . t))
1181 "Shell types that shell indenting can do something with.")
1182
1183 (defvar sh-indent-supported-here nil
1184 "Non-nil if we support indentation for the current buffer's shell type.")
1185
1186 (defconst sh-var-list
1187 '(
1188 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1189 sh-indent-after-do sh-indent-after-done
1190 sh-indent-after-else
1191 sh-indent-after-if
1192 sh-indent-after-loop-construct
1193 sh-indent-after-open
1194 sh-indent-comment
1195 sh-indent-for-case-alt
1196 sh-indent-for-case-label
1197 sh-indent-for-continuation
1198 sh-indent-for-do
1199 sh-indent-for-done
1200 sh-indent-for-else
1201 sh-indent-for-fi
1202 sh-indent-for-then
1203 )
1204 "A list of variables used by script mode to control indentation.
1205 This list is used when switching between buffer-local and global
1206 values of variables, and for the commands using indentation styles.")
1207
1208 (defvar sh-make-vars-local t
1209 "*Controls whether indentation variables are local to the buffer.
1210 If non-nil, indentation variables are made local initially.
1211 If nil, you can later make the variables local by invoking
1212 command `sh-make-vars-local'.
1213 The default is t because I assume that in one Emacs session one is
1214 frequently editing existing scripts with different styles.")
1215
1216 \f
1217 ;; mode-command and utility functions
1218
1219 ;;;###autoload
1220 (put 'sh-mode 'mode-class 'special)
1221
1222 ;;;###autoload
1223 (defun sh-mode ()
1224 "Major mode for editing shell scripts.
1225 This mode works for many shells, since they all have roughly the same syntax,
1226 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1227 Unless the file's magic number indicates the shell, your usual shell is
1228 assumed. Since filenames rarely give a clue, they are not further analyzed.
1229
1230 This mode adapts to the variations between shells (see `sh-set-shell') by
1231 means of an inheritance based feature lookup (see `sh-feature'). This
1232 mechanism applies to all variables (including skeletons) that pertain to
1233 shell-specific features.
1234
1235 The default style of this mode is that of Rosenblatt's Korn shell book.
1236 The syntax of the statements varies with the shell being used. The
1237 following commands are available, based on the current shell's syntax:
1238
1239 \\[sh-case] case statement
1240 \\[sh-for] for loop
1241 \\[sh-function] function definition
1242 \\[sh-if] if statement
1243 \\[sh-indexed-loop] indexed loop from 1 to n
1244 \\[sh-while-getopts] while getopts loop
1245 \\[sh-repeat] repeat loop
1246 \\[sh-select] select loop
1247 \\[sh-until] until loop
1248 \\[sh-while] while loop
1249
1250 For sh and rc shells indentation commands are:
1251 \\[sh-show-indent] Show the variable controlling this line's indentation.
1252 \\[sh-set-indent] Set then variable controlling this line's indentation.
1253 \\[sh-learn-line-indent] Change the indentation variable so this line
1254 would indent to the way it currently is.
1255 \\[sh-learn-buffer-indent] Set the indentation variables so the
1256 buffer indents as it currently is indented.
1257
1258
1259 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1260 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
1261 \\[sh-end-of-command] Go to end of successive commands.
1262 \\[sh-beginning-of-command] Go to beginning of successive commands.
1263 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1264 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1265
1266 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
1267 \{, (, [, ', \", `
1268 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1269
1270 If you generally program a shell different from your login shell you can
1271 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1272 indicate what shell it is use `sh-alias-alist' to translate.
1273
1274 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1275 with your script for an edit-interpret-debug cycle."
1276 (interactive)
1277 (kill-all-local-variables)
1278 (setq major-mode 'sh-mode
1279 mode-name "Shell-script")
1280 (use-local-map sh-mode-map)
1281 (make-local-variable 'skeleton-end-hook)
1282 (make-local-variable 'paragraph-start)
1283 (make-local-variable 'paragraph-separate)
1284 (make-local-variable 'comment-start)
1285 (make-local-variable 'comment-start-skip)
1286 (make-local-variable 'require-final-newline)
1287 (make-local-variable 'sh-header-marker)
1288 (make-local-variable 'sh-shell-file)
1289 (make-local-variable 'sh-shell)
1290 (make-local-variable 'skeleton-pair-alist)
1291 (make-local-variable 'skeleton-pair-filter)
1292 (make-local-variable 'comint-dynamic-complete-functions)
1293 (make-local-variable 'comint-prompt-regexp)
1294 (make-local-variable 'font-lock-defaults)
1295 (make-local-variable 'skeleton-filter)
1296 (make-local-variable 'skeleton-newline-indent-rigidly)
1297 (make-local-variable 'sh-shell-variables)
1298 (make-local-variable 'sh-shell-variables-initialized)
1299 (make-local-variable 'imenu-generic-expression)
1300 (make-local-variable 'sh-indent-supported-here)
1301 (setq skeleton-end-hook (lambda ()
1302 (or (eolp) (newline) (indent-relative)))
1303 paragraph-start (concat page-delimiter "\\|$")
1304 paragraph-separate paragraph-start
1305 comment-start "# "
1306 comint-dynamic-complete-functions sh-dynamic-complete-functions
1307 ;; we can't look if previous line ended with `\'
1308 comint-prompt-regexp "^[ \t]*"
1309 font-lock-defaults
1310 `((sh-font-lock-keywords
1311 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1312 nil nil
1313 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1314 (font-lock-syntactic-keywords . sh-font-lock-syntactic-keywords)
1315 (font-lock-syntactic-face-function
1316 . sh-font-lock-syntactic-face-function))
1317 skeleton-pair-alist '((?` _ ?`))
1318 skeleton-pair-filter 'sh-quoted-p
1319 skeleton-further-elements '((< '(- (min sh-indentation
1320 (current-column)))))
1321 skeleton-filter 'sh-feature
1322 skeleton-newline-indent-rigidly t
1323 sh-indent-supported-here nil)
1324 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1325 ;; Parse or insert magic number for exec, and set all variables depending
1326 ;; on the shell thus determined.
1327 (let ((interpreter
1328 (save-excursion
1329 (goto-char (point-min))
1330 (cond ((looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1331 (match-string 2))
1332 ((and buffer-file-name
1333 (string-match "\\.m?spec$" buffer-file-name))
1334 "rpm")))))
1335 (sh-set-shell (or interpreter sh-shell-file) nil nil))
1336 (run-hooks 'sh-mode-hook))
1337
1338 ;;;###autoload
1339 (defalias 'shell-script-mode 'sh-mode)
1340
1341
1342 (defun sh-font-lock-keywords (&optional keywords)
1343 "Function to get simple fontification based on `sh-font-lock-keywords'.
1344 This adds rules for comments and assignments."
1345 (sh-feature sh-font-lock-keywords
1346 (when (stringp (sh-feature sh-assignment-regexp))
1347 (lambda (list)
1348 `((,(sh-feature sh-assignment-regexp)
1349 1 font-lock-variable-name-face)
1350 ,@keywords
1351 ,@list)))))
1352
1353 (defun sh-font-lock-keywords-1 (&optional builtins)
1354 "Function to get better fontification including keywords."
1355 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1356 (regexp-opt (sh-feature sh-leading-keywords) t)
1357 "[ \t]+\\)?"
1358 (regexp-opt (append (sh-feature sh-leading-keywords)
1359 (sh-feature sh-other-keywords))
1360 t))))
1361 (sh-font-lock-keywords
1362 `(,@(if builtins
1363 `((,(concat keywords "[ \t]+\\)?"
1364 (regexp-opt (sh-feature sh-builtins) t)
1365 "\\>")
1366 (2 font-lock-keyword-face nil t)
1367 (6 font-lock-builtin-face))
1368 ,@(sh-feature sh-font-lock-keywords-2)))
1369 (,(concat keywords "\\)\\>")
1370 2 font-lock-keyword-face)
1371 ,@(sh-feature sh-font-lock-keywords-1)))))
1372
1373 (defun sh-font-lock-keywords-2 ()
1374 "Function to get better fontification including keywords and builtins."
1375 (sh-font-lock-keywords-1 t))
1376
1377
1378 (defvar sh-regexp-for-done nil
1379 "A buffer-local regexp to match opening keyword for done.")
1380
1381 (defvar sh-kw-alist nil
1382 "A buffer-local, since it is shell-type dependent, list of keywords.")
1383
1384 ;; ( key-word first-on-this on-prev-line )
1385 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1386 ;; having 3 elements:
1387 ;; a keyword
1388 ;; a rule to check when the keyword appears on "this" line
1389 ;; a rule to check when the keyword appears on "the previous" line
1390 ;; The keyword is usually a string and is the first word on a line.
1391 ;; If this keyword appears on the line whose indentation is to be
1392 ;; calculated, the rule in element 2 is called. If this returns
1393 ;; non-zero, the resulting point (which may be changed by the rule)
1394 ;; is used as the default indentation.
1395 ;; If it returned false or the keyword was not found in the table,
1396 ;; then the keyword from the previous line is looked up and the rule
1397 ;; in element 3 is called. In this case, however,
1398 ;; `sh-get-indent-info' does not stop but may keep going and test
1399 ;; other keywords against rules in element 3. This is because the
1400 ;; preceding line could have, for example, an opening "if" and an
1401 ;; opening "while" keyword and we need to add the indentation offsets
1402 ;; for both.
1403 ;;
1404 (defconst sh-kw
1405 '((sh
1406 ("if" nil sh-handle-prev-if)
1407 ("elif" sh-handle-this-else sh-handle-prev-else)
1408 ("else" sh-handle-this-else sh-handle-prev-else)
1409 ("fi" sh-handle-this-fi sh-handle-prev-fi)
1410 ("then" sh-handle-this-then sh-handle-prev-then)
1411 ("(" nil sh-handle-prev-open)
1412 ("{" nil sh-handle-prev-open)
1413 ("[" nil sh-handle-prev-open)
1414 ("}" sh-handle-this-close nil)
1415 (")" sh-handle-this-close nil)
1416 ("]" sh-handle-this-close nil)
1417 ("case" nil sh-handle-prev-case)
1418 ("esac" sh-handle-this-esac sh-handle-prev-esac)
1419 (case-label nil sh-handle-after-case-label) ;; ???
1420 (";;" nil sh-handle-prev-case-alt-end) ;; ???
1421 ("done" sh-handle-this-done sh-handle-prev-done)
1422 ("do" sh-handle-this-do sh-handle-prev-do))
1423
1424 ;; Note: we don't need specific stuff for bash and zsh shells;
1425 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1426 ;; these shells use.
1427 (rc
1428 ("{" nil sh-handle-prev-open)
1429 ("}" sh-handle-this-close nil)
1430 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
1431
1432
1433 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
1434 "Set this buffer's shell to SHELL (a string).
1435 When used interactively, insert the proper starting #!-line,
1436 and make the visited file executable via `executable-set-magic',
1437 perhaps querying depending on the value of `executable-query'.
1438
1439 When this function is called noninteractively, INSERT-FLAG (the third
1440 argument) controls whether to insert a #!-line and think about making
1441 the visited file executable, and NO-QUERY-FLAG (the second argument)
1442 controls whether to query about making the visited file executable.
1443
1444 Calls the value of `sh-set-shell-hook' if set."
1445 (interactive (list (completing-read (format "Shell \(default %s\): "
1446 sh-shell-file)
1447 interpreter-mode-alist
1448 (lambda (x) (eq (cdr x) 'sh-mode))
1449 nil nil nil sh-shell-file)
1450 (eq executable-query 'function)
1451 t))
1452 (if (string-match "\\.exe\\'" shell)
1453 (setq shell (substring shell 0 (match-beginning 0))))
1454 (setq sh-shell (intern (file-name-nondirectory shell))
1455 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
1456 sh-shell))
1457 (if insert-flag
1458 (setq sh-shell-file
1459 (executable-set-magic shell (sh-feature sh-shell-arg)
1460 no-query-flag insert-flag)))
1461 (setq require-final-newline (sh-feature sh-require-final-newline)
1462 ;;; local-abbrev-table (sh-feature sh-abbrevs)
1463 comment-start-skip "#+[\t ]*"
1464 mode-line-process (format "[%s]" sh-shell)
1465 sh-shell-variables nil
1466 sh-shell-variables-initialized nil
1467 imenu-generic-expression (sh-feature sh-imenu-generic-expression)
1468 imenu-case-fold-search nil)
1469 (set-syntax-table (or (sh-feature sh-mode-syntax-table)
1470 (standard-syntax-table)))
1471 (dolist (var (sh-feature sh-variables))
1472 (sh-remember-variable var))
1473 (make-local-variable 'indent-line-function)
1474 (if (setq sh-indent-supported-here (sh-feature sh-indent-supported))
1475 (progn
1476 (message "Setting up indent for shell type %s" sh-shell)
1477 (set (make-local-variable 'parse-sexp-lookup-properties) t)
1478 (set (make-local-variable 'sh-kw-alist) (sh-feature sh-kw))
1479 (let ((regexp (sh-feature sh-kws-for-done)))
1480 (if regexp
1481 (set (make-local-variable 'sh-regexp-for-done)
1482 (sh-mkword-regexpr (regexp-opt regexp t)))))
1483 (message "setting up indent stuff")
1484 ;; sh-mode has already made indent-line-function local
1485 ;; but do it in case this is called before that.
1486 (setq indent-line-function 'sh-indent-line)
1487 (if sh-make-vars-local
1488 (sh-make-vars-local))
1489 (message "Indentation setup for shell type %s" sh-shell))
1490 (message "No indentation for this shell type.")
1491 (setq indent-line-function 'sh-basic-indent-line))
1492 (run-hooks 'sh-set-shell-hook))
1493
1494
1495
1496 (defun sh-feature (list &optional function)
1497 "Index ALIST by the current shell.
1498 If ALIST isn't a list where every element is a cons, it is returned as is.
1499 Else indexing follows an inheritance logic which works in two ways:
1500
1501 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1502 the alist contains no value for the current shell.
1503 The ultimate default is always `sh'.
1504
1505 - If the value thus looked up is a list starting with `eval' its `cdr' is
1506 first evaluated. If that is also a list and the first argument is a
1507 symbol in ALIST it is not evaluated, but rather recursively looked up in
1508 ALIST to allow the function called to define the value for one shell to be
1509 derived from another shell. While calling the function, is the car of the
1510 alist element is the current shell.
1511 The value thus determined is physically replaced into the alist.
1512
1513 Optional FUNCTION is applied to the determined value and the result is cached
1514 in ALIST."
1515 (or (if (consp list)
1516 (let ((l list))
1517 (while (and l (consp (car l)))
1518 (setq l (cdr l)))
1519 (if l list)))
1520 (if function
1521 (cdr (assoc (setq function (cons sh-shell function)) list)))
1522 (let ((sh-shell sh-shell)
1523 elt val)
1524 (while (and sh-shell
1525 (not (setq elt (assq sh-shell list))))
1526 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
1527 ;; If the shell is not known, treat it as sh.
1528 (unless elt
1529 (setq elt (assq 'sh list)))
1530 (if (and (consp (setq val (cdr elt)))
1531 (eq (car val) 'eval))
1532 (setcdr elt
1533 (setq val
1534 (eval (if (consp (setq val (cdr val)))
1535 (let ((sh-shell (car (cdr val)))
1536 function)
1537 (if (assq sh-shell list)
1538 (setcar (cdr val)
1539 (list 'quote
1540 (sh-feature list))))
1541 val)
1542 val)))))
1543 (if function
1544 (nconc list
1545 (list (cons function
1546 (setq sh-shell (car function)
1547 val (funcall (cdr function) val))))))
1548 val)))
1549
1550
1551
1552 ;; I commented this out because nobody calls it -- rms.
1553 ;;(defun sh-abbrevs (ancestor &rest list)
1554 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
1555 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1556 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1557 ;;according to the remaining arguments NAMEi EXPANSIONi ...
1558 ;;EXPANSION may be either a string or a skeleton command."
1559 ;; (or (if (boundp sh-shell)
1560 ;; (symbol-value sh-shell))
1561 ;; (progn
1562 ;; (if (listp ancestor)
1563 ;; (nconc list ancestor))
1564 ;; (define-abbrev-table sh-shell ())
1565 ;; (if (vectorp ancestor)
1566 ;; (mapatoms (lambda (atom)
1567 ;; (or (eq atom 0)
1568 ;; (define-abbrev (symbol-value sh-shell)
1569 ;; (symbol-name atom)
1570 ;; (symbol-value atom)
1571 ;; (symbol-function atom))))
1572 ;; ancestor))
1573 ;; (while list
1574 ;; (define-abbrev (symbol-value sh-shell)
1575 ;; (car list)
1576 ;; (if (stringp (car (cdr list)))
1577 ;; (car (cdr list))
1578 ;; "")
1579 ;; (if (symbolp (car (cdr list)))
1580 ;; (car (cdr list))))
1581 ;; (setq list (cdr (cdr list)))))
1582 ;; (symbol-value sh-shell)))
1583
1584
1585 (defun sh-mode-syntax-table (table &rest list)
1586 "Copy TABLE and set syntax for successive CHARs according to strings S."
1587 (setq table (copy-syntax-table table))
1588 (while list
1589 (modify-syntax-entry (pop list) (pop list) table))
1590 table)
1591
1592 (defun sh-append (ancestor &rest list)
1593 "Return list composed of first argument (a list) physically appended to rest."
1594 (nconc list ancestor))
1595
1596
1597 (defun sh-modify (skeleton &rest list)
1598 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1599 (setq skeleton (copy-sequence skeleton))
1600 (while list
1601 (setcar (or (nthcdr (car list) skeleton)
1602 (error "Index %d out of bounds" (car list)))
1603 (car (cdr list)))
1604 (setq list (nthcdr 2 list)))
1605 skeleton)
1606
1607
1608 (defun sh-basic-indent-line ()
1609 "Indent a line for Sh mode (shell script mode).
1610 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1611 Lines containing only comments are considered empty."
1612 (interactive)
1613 (let ((previous (save-excursion
1614 (while (and (progn (beginning-of-line)
1615 (not (bobp)))
1616 (progn
1617 (forward-line -1)
1618 (back-to-indentation)
1619 (or (eolp)
1620 (eq (following-char) ?#)))))
1621 (current-column)))
1622 current)
1623 (save-excursion
1624 (indent-to (if (eq this-command 'newline-and-indent)
1625 previous
1626 (if (< (current-column)
1627 (setq current (progn (back-to-indentation)
1628 (current-column))))
1629 (if (eolp) previous 0)
1630 (delete-region (point)
1631 (progn (beginning-of-line) (point)))
1632 (if (eolp)
1633 (max previous (* (1+ (/ current sh-indentation))
1634 sh-indentation))
1635 (* (1+ (/ current sh-indentation)) sh-indentation))))))
1636 (if (< (current-column) (current-indentation))
1637 (skip-chars-forward " \t"))))
1638
1639
1640 (defun sh-execute-region (start end &optional flag)
1641 "Pass optional header and region to a subshell for noninteractive execution.
1642 The working directory is that of the buffer, and only environment variables
1643 are already set which is why you can mark a header within the script.
1644
1645 With a positive prefix ARG, instead of sending region, define header from
1646 beginning of buffer to point. With a negative prefix ARG, instead of sending
1647 region, clear header."
1648 (interactive "r\nP")
1649 (if flag
1650 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
1651 (point-marker)))
1652 (if sh-header-marker
1653 (save-excursion
1654 (let (buffer-undo-list)
1655 (goto-char sh-header-marker)
1656 (append-to-buffer (current-buffer) start end)
1657 (shell-command-on-region (point-min)
1658 (setq end (+ sh-header-marker
1659 (- end start)))
1660 sh-shell-file)
1661 (delete-region sh-header-marker end)))
1662 (shell-command-on-region start end (concat sh-shell-file " -")))))
1663
1664
1665 (defun sh-remember-variable (var)
1666 "Make VARIABLE available for future completing reads in this buffer."
1667 (or (< (length var) sh-remember-variable-min)
1668 (getenv var)
1669 (assoc var sh-shell-variables)
1670 (push (cons var var) sh-shell-variables))
1671 var)
1672
1673
1674
1675 (defun sh-quoted-p ()
1676 "Is point preceded by an odd number of backslashes?"
1677 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
1678 \f
1679 ;; Indentation stuff.
1680 (defun sh-must-support-indent ()
1681 "*Signal an error if the shell type for this buffer is not supported.
1682 Also, the buffer must be in Shell-script mode."
1683 (unless sh-indent-supported-here
1684 (error "This buffer's shell does not support indentation through Emacs")))
1685
1686 (defun sh-make-vars-local ()
1687 "Make the indentation variables local to this buffer.
1688 Normally they already are local. This command is provided in case
1689 variable `sh-make-vars-local' has been set to nil.
1690
1691 To revert all these variables to the global values, use
1692 command `sh-reset-indent-vars-to-global-values'."
1693 (interactive)
1694 (mapcar 'make-local-variable sh-var-list)
1695 (message "Indentation variable are now local."))
1696
1697 (defun sh-reset-indent-vars-to-global-values ()
1698 "Reset local indentation variables to the global values.
1699 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1700 (interactive)
1701 (mapcar 'kill-local-variable sh-var-list)
1702 (if sh-make-vars-local
1703 (mapcar 'make-local-variable sh-var-list)))
1704
1705
1706 ;; Theoretically these are only needed in shell and derived modes.
1707 ;; However, the routines which use them are only called in those modes.
1708 (defconst sh-special-keywords "then\\|do")
1709
1710 (defun sh-help-string-for-variable (var)
1711 "Construct a string for `sh-read-variable' when changing variable VAR ."
1712 (let ((msg (documentation-property var 'variable-documentation))
1713 (msg2 ""))
1714 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
1715 (setq msg2
1716 (format "\n
1717 You can enter a number (positive to increase indentation,
1718 negative to decrease indentation, zero for no change to indentation).
1719
1720 Or, you can enter one of the following symbols which are relative to
1721 the value of variable `sh-basic-offset'
1722 which in this buffer is currently %s.
1723
1724 \t%s."
1725 sh-basic-offset
1726 (mapconcat (lambda (x)
1727 (nth (1- (length x)) x))
1728 sh-symbol-list "\n\t"))))
1729 (concat
1730 ;; The following shows the global not the local value!
1731 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1732 msg msg2)))
1733
1734 (defun sh-read-variable (var)
1735 "Read a new value for indentation variable VAR."
1736 (interactive "*variable? ") ;; to test
1737 (let ((minibuffer-help-form `(sh-help-string-for-variable
1738 (quote ,var)))
1739 val)
1740 (setq val (read-from-minibuffer
1741 (format "New value for %s (press %s for help): "
1742 var (single-key-description help-char))
1743 (format "%s" (symbol-value var))
1744 nil t))
1745 val))
1746
1747
1748
1749 (defun sh-in-comment-or-string (start)
1750 "Return non-nil if START is in a comment or string."
1751 (save-excursion
1752 (let ((state (syntax-ppss start)))
1753 (or (nth 3 state) (nth 4 state)))))
1754
1755 (defun sh-goto-matching-if ()
1756 "Go to the matching if for a fi.
1757 This handles nested if..fi pairs."
1758 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1759 (if found
1760 (goto-char found))))
1761
1762
1763 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1764 ;; line whose indentation is being handled contain XXX;
1765 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
1766
1767 (defun sh-handle-prev-if ()
1768 (list '(+ sh-indent-after-if)))
1769
1770 (defun sh-handle-this-else ()
1771 (if (sh-goto-matching-if)
1772 ;; (list "aligned to if")
1773 (list "aligned to if" '(+ sh-indent-for-else))
1774 nil
1775 ))
1776
1777 (defun sh-handle-prev-else ()
1778 (if (sh-goto-matching-if)
1779 (list '(+ sh-indent-after-if))
1780 ))
1781
1782 (defun sh-handle-this-fi ()
1783 (if (sh-goto-matching-if)
1784 (list "aligned to if" '(+ sh-indent-for-fi))
1785 nil
1786 ))
1787
1788 (defun sh-handle-prev-fi ()
1789 ;; Why do we have this rule? Because we must go back to the if
1790 ;; to get its indent. We may continue back from there.
1791 ;; We return nil because we don't have anything to add to result,
1792 ;; the side affect of setting align-point is all that matters.
1793 ;; we could return a comment (a string) but I can't think of a good one...
1794 (sh-goto-matching-if)
1795 nil)
1796
1797 (defun sh-handle-this-then ()
1798 (let ((p (sh-goto-matching-if)))
1799 (if p
1800 (list '(+ sh-indent-for-then))
1801 )))
1802
1803 (defun sh-handle-prev-then ()
1804 (let ((p (sh-goto-matching-if)))
1805 (if p
1806 (list '(+ sh-indent-after-if))
1807 )))
1808
1809 (defun sh-handle-prev-open ()
1810 (save-excursion
1811 (let ((x (sh-prev-stmt)))
1812 (if (and x
1813 (progn
1814 (goto-char x)
1815 (or
1816 (looking-at "function\\b")
1817 (looking-at "\\s-*\\S-+\\s-*()")
1818 )))
1819 (list '(+ sh-indent-after-function))
1820 (list '(+ sh-indent-after-open)))
1821 )))
1822
1823 (defun sh-handle-this-close ()
1824 (forward-char 1) ;; move over ")"
1825 (if (sh-safe-forward-sexp -1)
1826 (list "aligned to opening paren")))
1827
1828 (defun sh-goto-matching-case ()
1829 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
1830 (if found (goto-char found))))
1831
1832 (defun sh-handle-prev-case ()
1833 ;; This is typically called when point is on same line as a case
1834 ;; we shouldn't -- and can't find prev-case
1835 (if (looking-at ".*\\<case\\>")
1836 (list '(+ sh-indent-for-case-label))
1837 (error "We don't seem to be on a line with a case"))) ;; debug
1838
1839 (defun sh-handle-this-esac ()
1840 (if (sh-goto-matching-case)
1841 (list "aligned to matching case")))
1842
1843 (defun sh-handle-prev-esac ()
1844 (if (sh-goto-matching-case)
1845 (list "matching case")))
1846
1847 (defun sh-handle-after-case-label ()
1848 (if (sh-goto-matching-case)
1849 (list '(+ sh-indent-for-case-alt))))
1850
1851 (defun sh-handle-prev-case-alt-end ()
1852 (if (sh-goto-matching-case)
1853 (list '(+ sh-indent-for-case-label))))
1854
1855 (defun sh-safe-forward-sexp (&optional arg)
1856 "Try and do a `forward-sexp', but do not error.
1857 Return new point if successful, nil if an error occurred."
1858 (condition-case nil
1859 (progn
1860 (forward-sexp (or arg 1))
1861 (point)) ;; return point if successful
1862 (error
1863 (sh-debug "oops!(1) %d" (point))
1864 nil))) ;; return nil if fail
1865
1866 (defun sh-goto-match-for-done ()
1867 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
1868 (if found
1869 (goto-char found))))
1870
1871 (defun sh-handle-this-done ()
1872 (if (sh-goto-match-for-done)
1873 (list "aligned to do stmt" '(+ sh-indent-for-done))))
1874
1875 (defun sh-handle-prev-done ()
1876 (if (sh-goto-match-for-done)
1877 (list "previous done")))
1878
1879 (defun sh-handle-this-do ()
1880 (if (sh-goto-match-for-done)
1881 (list '(+ sh-indent-for-do))))
1882
1883 (defun sh-handle-prev-do ()
1884 (cond
1885 ((save-restriction
1886 (narrow-to-region
1887 (point)
1888 (save-excursion
1889 (beginning-of-line)
1890 (point)))
1891 (sh-goto-match-for-done))
1892 (sh-debug "match for done found on THIS line")
1893 (list '(+ sh-indent-after-loop-construct)))
1894 ((sh-goto-match-for-done)
1895 (sh-debug "match for done found on PREV line")
1896 (list '(+ sh-indent-after-do)))
1897 (t
1898 (message "match for done NOT found")
1899 nil)))
1900
1901 ;; for rc:
1902 (defun sh-find-prev-switch ()
1903 "Find the line for the switch keyword matching this line's case keyword."
1904 (re-search-backward "\\<switch\\>" nil t))
1905
1906 (defun sh-handle-this-rc-case ()
1907 (if (sh-find-prev-switch)
1908 (list '(+ sh-indent-after-switch))
1909 ;; (list '(+ sh-indent-for-case-label))
1910 nil))
1911
1912 (defun sh-handle-prev-rc-case ()
1913 (list '(+ sh-indent-after-case)))
1914
1915 (defun sh-check-rule (n thing)
1916 (let ((rule (nth n (assoc thing sh-kw-alist)))
1917 (val nil))
1918 (if rule
1919 (progn
1920 (setq val (funcall rule))
1921 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
1922 n thing (point) rule val)))
1923 val))
1924
1925
1926 (defun sh-get-indent-info ()
1927 "Return indent-info for this line.
1928 This is a list. nil means the line is to be left as is.
1929 Otherwise it contains one or more of the following sublists:
1930 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
1931 relative to. If present, this is always the first of the
1932 sublists. The indentation of the line in question is
1933 derived from the indentation of this point, possibly
1934 modified by subsequent sublists.
1935 \(+ VAR\)
1936 \(- VAR\) Get the value of variable VAR and add to or subtract from
1937 the indentation calculated so far.
1938 \(= VAR\) Get the value of variable VAR and *replace* the
1939 indentation with its value. This only occurs for
1940 special variables such as `sh-indent-comment'.
1941 STRING This is ignored for the purposes of calculating
1942 indentation, it is printed in certain cases to help show
1943 what the indentation is based on."
1944 ;; See comments before `sh-kw'.
1945 (save-excursion
1946 (let ((prev-kw nil)
1947 (prev-stmt nil)
1948 (have-result nil)
1949 depth-bol depth-eol
1950 this-kw
1951 (state nil)
1952 state-bol
1953 (depth-prev-bol nil)
1954 start
1955 func val
1956 (result nil)
1957 prev-lines-indent
1958 (prev-list nil)
1959 (this-list nil)
1960 (align-point nil)
1961 prev-line-end x)
1962 (beginning-of-line)
1963 ;; Note: setting result to t means we are done and will return nil.
1964 ;;(This function never returns just t.)
1965 (cond
1966 ((or (and (boundp 'font-lock-string-face)
1967 (eq (get-text-property (point) 'face) font-lock-string-face))
1968 (eq (get-text-property (point) 'face) sh-heredoc-face))
1969 (setq result t)
1970 (setq have-result t))
1971 ((looking-at "\\s-*#") ; was (equal this-kw "#")
1972 (if (bobp)
1973 (setq result t) ;; return nil if 1st line!
1974 (setq result (list '(= sh-indent-comment)))
1975 ;; we still need to get previous line in case
1976 ;; sh-indent-comment is t (indent as normal)
1977 (setq align-point (sh-prev-line nil))
1978 (setq have-result nil)
1979 ))
1980 ) ;; cond
1981
1982 (unless have-result
1983 ;; Continuation lines are handled specially
1984 (if (sh-this-is-a-continuation)
1985 (progn
1986 ;; We assume the line being continued is already
1987 ;; properly indented...
1988 ;; (setq prev-line-end (sh-prev-line))
1989 (setq align-point (sh-prev-line nil))
1990 (setq result (list '(+ sh-indent-for-continuation)))
1991 (setq have-result t))
1992 (beginning-of-line)
1993 (skip-chars-forward " \t")
1994 (setq this-kw (sh-get-kw)))
1995
1996 ;; Handle "this" keyword: first word on the line we're
1997 ;; calculating indentation info for.
1998 (if this-kw
1999 (if (setq val (sh-check-rule 1 this-kw))
2000 (progn
2001 (setq align-point (point))
2002 (sh-debug
2003 "this - setting align-point to %d" align-point)
2004 (setq result (append result val))
2005 (setq have-result t)
2006 ;; set prev-line to continue processing remainder
2007 ;; of this line as a previous line
2008 (setq prev-line-end (point))
2009 ))))
2010
2011 (unless have-result
2012 (setq prev-line-end (sh-prev-line 'end)))
2013
2014 (if prev-line-end
2015 (save-excursion
2016 ;; We start off at beginning of this line.
2017 ;; Scan previous statements while this is <=
2018 ;; start of previous line.
2019 (setq start (point)) ;; for debug only
2020 (goto-char prev-line-end)
2021 (setq x t)
2022 (while (and x (setq x (sh-prev-thing)))
2023 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2024 (cond
2025 ((and (equal x ")")
2026 (equal (get-text-property (1- (point)) 'syntax-table)
2027 sh-st-punc))
2028 (sh-debug "Case label) here")
2029 (setq x 'case-label)
2030 (if (setq val (sh-check-rule 2 x))
2031 (progn
2032 (setq result (append result val))
2033 (setq align-point (point))))
2034 (forward-char -1)
2035 (skip-chars-forward "[a-z0-9]*?")
2036 )
2037 ((string-match "[])}]" x)
2038 (setq x (sh-safe-forward-sexp -1))
2039 (if x
2040 (progn
2041 (setq align-point (point))
2042 (setq result (append result
2043 (list "aligned to opening paren")))
2044 )))
2045 ((string-match "[[({]" x)
2046 (sh-debug "Checking special thing: %s" x)
2047 (if (setq val (sh-check-rule 2 x))
2048 (setq result (append result val)))
2049 (forward-char -1)
2050 (setq align-point (point)))
2051 ((string-match "[\"'`]" x)
2052 (sh-debug "Skipping back for %s" x)
2053 ;; this was oops-2
2054 (setq x (sh-safe-forward-sexp -1)))
2055 ((stringp x)
2056 (sh-debug "Checking string %s at %s" x (point))
2057 (if (setq val (sh-check-rule 2 x))
2058 ;; (or (eq t (car val))
2059 ;; (eq t (car (car val))))
2060 (setq result (append result val)))
2061 ;; not sure about this test Wed Jan 27 23:48:35 1999
2062 (setq align-point (point))
2063 (unless (bolp)
2064 (forward-char -1)))
2065 (t
2066 (error "Don't know what to do with %s" x))
2067 )
2068 ) ;; while
2069 (sh-debug "result is %s" result)
2070 )
2071 (sh-debug "No prev line!")
2072 (sh-debug "result: %s align-point: %s" result align-point)
2073 )
2074
2075 (if align-point
2076 ;; was: (setq result (append result (list (list t align-point))))
2077 (setq result (append (list (list t align-point)) result))
2078 )
2079 (sh-debug "result is now: %s" result)
2080
2081 (or result
2082 (if prev-line-end
2083 (setq result (list (list t prev-line-end)))
2084 (setq result (list (list '= 'sh-first-lines-indent)))
2085 ))
2086
2087 (if (eq result t)
2088 (setq result nil))
2089 (sh-debug "result is: %s" result)
2090 result
2091 ) ;; let
2092 ))
2093
2094
2095 (defun sh-get-indent-var-for-line (&optional info)
2096 "Return the variable controlling indentation for this line.
2097 If there is not [just] one such variable, return a string
2098 indicating the problem.
2099 If INFO is supplied it is used, else it is calculated."
2100 (let ((var nil)
2101 (result nil)
2102 (reason nil)
2103 sym elt)
2104 (or info
2105 (setq info (sh-get-indent-info)))
2106 (if (null info)
2107 (setq result "this line to be left as is")
2108 (while (and info (null result))
2109 (setq elt (car info))
2110 (cond
2111 ((stringp elt)
2112 (setq reason elt)
2113 )
2114 ((not (listp elt))
2115 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2116 ;; so it is a list
2117 ((eq t (car elt))
2118 ) ;; nothing
2119 ((symbolp (setq sym (nth 1 elt)))
2120 ;; A bit of a kludge - when we see the sh-indent-comment
2121 ;; ignore other variables. Otherwise it is tricky to
2122 ;; "learn" the comment indentation.
2123 (if (eq var 'sh-indent-comment)
2124 (setq result var)
2125 (if var
2126 (setq result
2127 "this line is controlled by more than 1 variable.")
2128 (setq var sym))))
2129 (t
2130 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2131 (setq info (cdr info))
2132 ))
2133 (or result
2134 (setq result var))
2135 (or result
2136 (setq result reason))
2137 (if (null result)
2138 ;; e.g. just had (t POS)
2139 (setq result "line has default indentation"))
2140 result))
2141
2142
2143
2144 ;; Finding the previous line isn't trivial.
2145 ;; We must *always* go back one more and see if that is a continuation
2146 ;; line -- it is the PREVIOUS line which is continued, not the one
2147 ;; we are going to!
2148 ;; Also, we want to treat a whole "here document" as one big line,
2149 ;; because we may want to a align to the beginning of it.
2150 ;;
2151 ;; What we do:
2152 ;; - go back to previous non-empty line
2153 ;; - if this is in a here-document, go to the beginning of it
2154 ;; - while previous line is continued, go back one line
2155 (defun sh-prev-line (&optional end)
2156 "Back to end of previous non-comment non-empty line.
2157 Go to beginning of logical line unless END is non-nil, in which case
2158 we go to the end of the previous line and do not check for continuations."
2159 (save-excursion
2160 (beginning-of-line)
2161 (forward-comment (- (point-max)))
2162 (unless end (beginning-of-line))
2163 (when (and (not (bobp))
2164 (equal (get-text-property (1- (point)) 'face)
2165 sh-heredoc-face))
2166 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
2167 (when p1
2168 (goto-char p1)
2169 (if end
2170 (end-of-line)
2171 (beginning-of-line)))))
2172 (unless end
2173 ;; we must check previous lines to see if they are continuation lines
2174 ;; if so, we must return position of first of them
2175 (while (and (sh-this-is-a-continuation)
2176 (>= 0 (forward-line -1))))
2177 (beginning-of-line)
2178 (skip-chars-forward " \t"))
2179 (point)))
2180
2181
2182 (defun sh-prev-stmt ()
2183 "Return the address of the previous stmt or nil."
2184 ;; This is used when we are trying to find a matching keyword.
2185 ;; Searching backward for the keyword would certainly be quicker, but
2186 ;; it is hard to remove "false matches" -- such as if the keyword
2187 ;; appears in a string or quote. This way is slower, but (I think) safer.
2188 (interactive)
2189 (save-excursion
2190 (let ((going t)
2191 (start (point))
2192 (found nil)
2193 (prev nil))
2194 (skip-chars-backward " \t;|&({[")
2195 (while (and (not found)
2196 (not (bobp))
2197 going)
2198 ;; Do a backward-sexp if possible, else backup bit by bit...
2199 (if (sh-safe-forward-sexp -1)
2200 (progn
2201 (if (looking-at sh-special-keywords)
2202 (progn
2203 (setq found prev))
2204 (setq prev (point))
2205 ))
2206 ;; backward-sexp failed
2207 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2208 (forward-char -1))
2209 (if (bolp)
2210 (let ((back (sh-prev-line nil)))
2211 (if back
2212 (goto-char back)
2213 (setq going nil)))))
2214 (unless found
2215 (skip-chars-backward " \t")
2216 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2217 (eq (char-before) ?\;)
2218 (looking-at "\\s-*[|&]"))
2219 (setq found (point)))))
2220 (if found
2221 (goto-char found))
2222 (if found
2223 (progn
2224 (skip-chars-forward " \t|&({[")
2225 (setq found (point))))
2226 (if (>= (point) start)
2227 (progn
2228 (debug "We didn't move!")
2229 (setq found nil))
2230 (or found
2231 (sh-debug "Did not find prev stmt.")))
2232 found)))
2233
2234
2235 (defun sh-get-word ()
2236 "Get a shell word skipping whitespace from point."
2237 (interactive)
2238 (skip-chars-forward "\t ")
2239 (let ((start (point)))
2240 (while
2241 (if (looking-at "[\"'`]")
2242 (sh-safe-forward-sexp)
2243 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2244 (> (skip-chars-forward "-_a-zA-Z\$0-9") 0)
2245 ))
2246 (buffer-substring start (point))
2247 ))
2248
2249 (defun sh-prev-thing ()
2250 "Return the previous thing this logical line."
2251 ;; This is called when `sh-get-indent-info' is working backwards on
2252 ;; the previous line(s) finding what keywords may be relevant for
2253 ;; indenting. It moves over sexps if possible, and will stop
2254 ;; on a ; and at the beginning of a line if it is not a continuation
2255 ;; line.
2256 ;;
2257 ;; Added a kludge for ";;"
2258 ;; Possible return values:
2259 ;; nil - nothing
2260 ;; a string - possibly a keyword
2261 ;;
2262 (if (bolp)
2263 nil
2264 (let ((going t)
2265 c n
2266 min-point
2267 (start (point))
2268 (found nil))
2269 (save-restriction
2270 (narrow-to-region
2271 (if (sh-this-is-a-continuation)
2272 (setq min-point (sh-prev-line nil))
2273 (save-excursion
2274 (beginning-of-line)
2275 (setq min-point (point))))
2276 (point))
2277 (skip-chars-backward " \t;")
2278 (unless (looking-at "\\s-*;;")
2279 (skip-chars-backward "^)}];\"'`({[")
2280 (setq c (char-before))))
2281 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2282 (point) c start min-point)
2283 (if (< (point) min-point)
2284 (error "point %d < min-point %d" (point) min-point))
2285 (cond
2286 ((looking-at "\\s-*;;")
2287 ;; (message "Found ;; !")
2288 ";;")
2289 ((or (eq c ?\n)
2290 (eq c nil)
2291 (eq c ?\;))
2292 (save-excursion
2293 ;; skip forward over white space newline and \ at eol
2294 (skip-chars-forward " \t\n\\\\")
2295 (sh-debug "Now at %d start=%d" (point) start)
2296 (if (>= (point) start)
2297 (progn
2298 (sh-debug "point: %d >= start: %d" (point) start)
2299 nil)
2300 (sh-get-word))
2301 ))
2302 (t
2303 ;; c -- return a string
2304 (char-to-string c)
2305 ))
2306 )))
2307
2308
2309 (defun sh-this-is-a-continuation ()
2310 "Return non-nil if current line is a continuation of previous line."
2311 (save-excursion
2312 (and (zerop (forward-line -1))
2313 (looking-at ".*\\\\$")
2314 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2315 nil nil nil t))))))
2316
2317 (defun sh-get-kw (&optional where and-move)
2318 "Return first word of line from WHERE.
2319 If AND-MOVE is non-nil then move to end of word."
2320 (let ((start (point)))
2321 (if where
2322 (goto-char where))
2323 (prog1
2324 (buffer-substring (point)
2325 (progn (skip-chars-forward "^ \t\n;")(point)))
2326 (unless and-move
2327 (goto-char start)))))
2328
2329 (defun sh-find-prev-matching (open close &optional depth)
2330 "Find a matching token for a set of opening and closing keywords.
2331 This takes into account that there may be nested open..close pairings.
2332 OPEN and CLOSE are regexps denoting the tokens to be matched.
2333 Optional parameter DEPTH (usually 1) says how many to look for."
2334 (let ((parse-sexp-ignore-comments t)
2335 prev)
2336 (setq depth (or depth 1))
2337 (save-excursion
2338 (condition-case nil
2339 (while (and
2340 (/= 0 depth)
2341 (not (bobp))
2342 (setq prev (sh-prev-stmt)))
2343 (goto-char prev)
2344 (save-excursion
2345 (if (looking-at "\\\\\n")
2346 (progn
2347 (forward-char 2)
2348 (skip-chars-forward " \t")))
2349 (cond
2350 ((looking-at open)
2351 (setq depth (1- depth))
2352 (sh-debug "found open at %d - depth = %d" (point) depth))
2353 ((looking-at close)
2354 (setq depth (1+ depth))
2355 (sh-debug "found close - depth = %d" depth))
2356 (t
2357 ))))
2358 (error nil))
2359 (if (eq depth 0)
2360 prev ;; (point)
2361 nil)
2362 )))
2363
2364
2365 (defun sh-var-value (var &optional ignore-error)
2366 "Return the value of variable VAR, interpreting symbols.
2367 It can also return t or nil.
2368 If an illegal value is found, throw an error unless Optional argument
2369 IGNORE-ERROR is non-nil."
2370 (let ((val (symbol-value var)))
2371 (cond
2372 ((numberp val)
2373 val)
2374 ((eq val t)
2375 val)
2376 ((null val)
2377 val)
2378 ((eq val '+)
2379 sh-basic-offset)
2380 ((eq val '-)
2381 (- sh-basic-offset))
2382 ((eq val '++)
2383 (* 2 sh-basic-offset))
2384 ((eq val '--)
2385 (* 2 (- sh-basic-offset)))
2386 ((eq val '*)
2387 (/ sh-basic-offset 2))
2388 ((eq val '/)
2389 (/ (- sh-basic-offset) 2))
2390 (t
2391 (if ignore-error
2392 (progn
2393 (message "Don't know how to handle %s's value of %s" var val)
2394 0)
2395 (error "Don't know how to handle %s's value of %s" var val))
2396 ))))
2397
2398 (defun sh-set-var-value (var value &optional no-symbol)
2399 "Set variable VAR to VALUE.
2400 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2401 can be represented by a symbol then do so."
2402 (cond
2403 (no-symbol
2404 (set var value))
2405 ((= value sh-basic-offset)
2406 (set var '+))
2407 ((= value (- sh-basic-offset))
2408 (set var '-))
2409 ((eq value (* 2 sh-basic-offset))
2410 (set var '++))
2411 ((eq value (* 2 (- sh-basic-offset)))
2412 (set var '--))
2413 ((eq value (/ sh-basic-offset 2))
2414 (set var '*))
2415 ((eq value (/ (- sh-basic-offset) 2))
2416 (set var '/))
2417 (t
2418 (set var value)))
2419 )
2420
2421
2422 (defun sh-calculate-indent (&optional info)
2423 "Return the indentation for the current line.
2424 If INFO is supplied it is used, else it is calculated from current line."
2425 (let ((ofs 0)
2426 (base-value 0)
2427 elt a b var val)
2428 (or info
2429 (setq info (sh-get-indent-info)))
2430 (when info
2431 (while info
2432 (sh-debug "info: %s ofs=%s" info ofs)
2433 (setq elt (car info))
2434 (cond
2435 ((stringp elt)) ;; do nothing?
2436 ((listp elt)
2437 (setq a (car (car info)))
2438 (setq b (nth 1 (car info)))
2439 (cond
2440 ((eq a t)
2441 (save-excursion
2442 (goto-char b)
2443 (setq val (current-indentation)))
2444 (setq base-value val))
2445 ((symbolp b)
2446 (setq val (sh-var-value b))
2447 (cond
2448 ((eq a '=)
2449 (cond
2450 ((null val)
2451 ;; no indentation
2452 ;; set info to nil so we stop immediately
2453 (setq base-value nil ofs nil info nil))
2454 ((eq val t) (setq ofs 0)) ;; indent as normal line
2455 (t
2456 ;; The following assume the (t POS) come first!
2457 (setq ofs val base-value 0)
2458 (setq info nil)))) ;; ? stop now
2459 ((eq a '+) (setq ofs (+ ofs val)))
2460 ((eq a '-) (setq ofs (- ofs val)))
2461 (t
2462 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
2463 (t
2464 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
2465 (t
2466 (error "sh-calculate-indent invalid elt %s" elt)))
2467 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2468 a b val base-value ofs)
2469 (setq info (cdr info)))
2470 ;; return value:
2471 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
2472
2473 (cond
2474 ((or (null base-value)(null ofs))
2475 nil)
2476 ((and (numberp base-value)(numberp ofs))
2477 (sh-debug "base (%d) + ofs (%d) = %d"
2478 base-value ofs (+ base-value ofs))
2479 (+ base-value ofs)) ;; return value
2480 (t
2481 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2482 base-value ofs)
2483 nil)))))
2484
2485
2486 (defun sh-indent-line ()
2487 "Indent the current line."
2488 (interactive)
2489 (let ((indent (sh-calculate-indent))
2490 (pos (- (point-max) (point))))
2491 (when indent
2492 (beginning-of-line)
2493 (skip-chars-forward " \t")
2494 (indent-line-to indent)
2495 ;; If initial point was within line's indentation,
2496 ;; position after the indentation. Else stay at same point in text.
2497 (if (> (- (point-max) pos) (point))
2498 (goto-char (- (point-max) pos))))))
2499
2500
2501 (defun sh-blink (blinkpos &optional msg)
2502 "Move cursor momentarily to BLINKPOS and display MSG."
2503 ;; We can get here without it being a number on first line
2504 (if (numberp blinkpos)
2505 (save-excursion
2506 (goto-char blinkpos)
2507 (message msg)
2508 (sit-for blink-matching-delay))
2509 (message msg)))
2510
2511 (defun sh-show-indent (arg)
2512 "Show the how the currently line would be indented.
2513 This tells you which variable, if any, controls the indentation of
2514 this line.
2515 If optional arg ARG is non-null (called interactively with a prefix),
2516 a pop up window describes this variable.
2517 If variable `sh-blink' is non-nil then momentarily go to the line
2518 we are indenting relative to, if applicable."
2519 (interactive "P")
2520 (sh-must-support-indent)
2521 (let* ((info (sh-get-indent-info))
2522 (var (sh-get-indent-var-for-line info))
2523 (curr-indent (current-indentation))
2524 val msg)
2525 (if (stringp var)
2526 (message (setq msg var))
2527 (setq val (sh-calculate-indent info))
2528
2529 (if (eq curr-indent val)
2530 (setq msg (format "%s is %s" var (symbol-value var)))
2531 (setq msg
2532 (if val
2533 (format "%s (%s) would change indent from %d to: %d"
2534 var (symbol-value var) curr-indent val)
2535 (format "%s (%s) would leave line as is"
2536 var (symbol-value var)))
2537 ))
2538 (if (and arg var)
2539 (describe-variable var)))
2540 (if sh-blink
2541 (let ((info (sh-get-indent-info)))
2542 (if (and info (listp (car info))
2543 (eq (car (car info)) t))
2544 (sh-blink (nth 1 (car info)) msg)
2545 (message msg)))
2546 (message msg))
2547 ))
2548
2549 (defun sh-set-indent ()
2550 "Set the indentation for the current line.
2551 If the current line is controlled by an indentation variable, prompt
2552 for a new value for it."
2553 (interactive)
2554 (sh-must-support-indent)
2555 (let* ((info (sh-get-indent-info))
2556 (var (sh-get-indent-var-for-line info))
2557 val val0 new-val old-val indent-val)
2558 (if (stringp var)
2559 (message (format "Cannot set indent - %s" var))
2560 (setq old-val (symbol-value var))
2561 (setq val (sh-read-variable var))
2562 (condition-case nil
2563 (progn
2564 (set var val)
2565 (setq indent-val (sh-calculate-indent info))
2566 (if indent-val
2567 (message "Variable: %s Value: %s would indent to: %d"
2568 var (symbol-value var) indent-val)
2569 (message "Variable: %s Value: %s would leave line as is."
2570 var (symbol-value var)))
2571 ;; I'm not sure about this, indenting it now?
2572 ;; No. Because it would give the impression that an undo would
2573 ;; restore thing, but the value has been altered.
2574 ;; (sh-indent-line)
2575 )
2576 (error
2577 (set var old-val)
2578 (message "Bad value for %s, restoring to previous value %s"
2579 var old-val)
2580 (sit-for 1)
2581 nil))
2582 )))
2583
2584
2585 (defun sh-learn-line-indent (arg)
2586 "Learn how to indent a line as it currently is indented.
2587
2588 If there is an indentation variable which controls this line's indentation,
2589 then set it to a value which would indent the line the way it
2590 presently is.
2591
2592 If the value can be represented by one of the symbols then do so
2593 unless optional argument ARG (the prefix when interactive) is non-nil."
2594 (interactive "*P")
2595 (sh-must-support-indent)
2596 ;; I'm not sure if we show allow learning on an empty line.
2597 ;; Though it might occasionally be useful I think it usually
2598 ;; would just be confusing.
2599 (if (save-excursion
2600 (beginning-of-line)
2601 (looking-at "\\s-*$"))
2602 (message "sh-learn-line-indent ignores empty lines.")
2603 (let* ((info (sh-get-indent-info))
2604 (var (sh-get-indent-var-for-line info))
2605 ival sval diff new-val
2606 (no-symbol arg)
2607 (curr-indent (current-indentation)))
2608 (cond
2609 ((stringp var)
2610 (message (format "Cannot learn line - %s" var)))
2611 ((eq var 'sh-indent-comment)
2612 ;; This is arbitrary...
2613 ;; - if curr-indent is 0, set to curr-indent
2614 ;; - else if it has the indentation of a "normal" line,
2615 ;; then set to t
2616 ;; - else set to curr-indent.
2617 (setq sh-indent-comment
2618 (if (= curr-indent 0)
2619 0
2620 (let* ((sh-indent-comment t)
2621 (val2 (sh-calculate-indent info)))
2622 (if (= val2 curr-indent)
2623 t
2624 curr-indent))))
2625 (message "%s set to %s" var (symbol-value var))
2626 )
2627 ((numberp (setq sval (sh-var-value var)))
2628 (setq ival (sh-calculate-indent info))
2629 (setq diff (- curr-indent ival))
2630
2631 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2632 curr-indent ival diff var sval)
2633 (setq new-val (+ sval diff))
2634 ;;; I commented out this because someone might want to replace
2635 ;;; a value of `+' with the current value of sh-basic-offset
2636 ;;; or vice-versa.
2637 ;;; (if (= 0 diff)
2638 ;;; (message "No change needed!")
2639 (sh-set-var-value var new-val no-symbol)
2640 (message "%s set to %s" var (symbol-value var))
2641 )
2642 (t
2643 (debug)
2644 (message "Cannot change %s" var))))))
2645
2646
2647
2648 (defun sh-mark-init (buffer)
2649 "Initialize a BUFFER to be used by `sh-mark-line'."
2650 (save-excursion
2651 (set-buffer (get-buffer-create buffer))
2652 (erase-buffer)
2653 (occur-mode)
2654 ))
2655
2656
2657 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
2658 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2659 Buffer BUFFER is in `occur-mode'.
2660 If ADD-LINENUM is non-nil the message is preceded by the line number.
2661 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2662 so that `occur-next' and `occur-prev' will work."
2663 (let ((m1 (make-marker))
2664 start
2665 (line ""))
2666 (when point
2667 (set-marker m1 point (current-buffer))
2668 (if add-linenum
2669 (setq line (format "%d: " (1+ (count-lines 1 point))))))
2670 (save-excursion
2671 (if (get-buffer buffer)
2672 (set-buffer (get-buffer buffer))
2673 (set-buffer (get-buffer-create buffer))
2674 (occur-mode)
2675 )
2676 (goto-char (point-max))
2677 (setq start (point))
2678 (insert line)
2679 (if occur-point
2680 (setq occur-point (point)))
2681 (insert message)
2682 (if point
2683 (add-text-properties
2684 start (point)
2685 '(mouse-face highlight
2686 help-echo "mouse-2: go to the line where I learned this")))
2687 (insert "\n")
2688 (if point
2689 (progn
2690 (put-text-property start (point) 'occur-target m1)
2691 (if occur-point
2692 (put-text-property start occur-point
2693 'occur-match t))
2694 ))
2695 )))
2696
2697
2698
2699 ;; Is this really worth having?
2700 (defvar sh-learned-buffer-hook nil
2701 "*An abnormal hook, called with an alist of learned variables.")
2702 ;; Example of how to use sh-learned-buffer-hook
2703 ;;
2704 ;; (defun what-i-learned (list)
2705 ;; (let ((p list))
2706 ;; (save-excursion
2707 ;; (set-buffer "*scratch*")
2708 ;; (goto-char (point-max))
2709 ;; (insert "(setq\n")
2710 ;; (while p
2711 ;; (insert (format " %s %s \n"
2712 ;; (nth 0 (car p)) (nth 1 (car p))))
2713 ;; (setq p (cdr p)))
2714 ;; (insert ")\n")
2715 ;; )))
2716 ;;
2717 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2718
2719
2720 ;; Originally this was sh-learn-region-indent (beg end)
2721 ;; However, in practice this was awkward so I changed it to
2722 ;; use the whole buffer. Use narrowing if needbe.
2723 (defun sh-learn-buffer-indent (&optional arg)
2724 "Learn how to indent the buffer the way it currently is.
2725
2726 Output in buffer \"*indent*\" shows any lines which have conflicting
2727 values of a variable, and the final value of all variables learned.
2728 This buffer is popped to automatically if there are any discrepancies.
2729
2730 If no prefix ARG is given, then variables are set to numbers.
2731 If a prefix arg is given, then variables are set to symbols when
2732 applicable -- e.g. to symbol `+' if the value is that of the
2733 basic indent.
2734 If a positive numerical prefix is given, then `sh-basic-offset'
2735 is set to the prefix's numerical value.
2736 Otherwise, sh-basic-offset may or may not be changed, according
2737 to the value of variable `sh-learn-basic-offset'.
2738
2739 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2740 function completes. The function is abnormal because it is called
2741 with an alist of variables learned. This feature may be changed or
2742 removed in the future.
2743
2744 This command can often take a long time to run."
2745 (interactive "P")
2746 (sh-must-support-indent)
2747 (save-excursion
2748 (goto-char (point-min))
2749 (let ((learned-var-list nil)
2750 (out-buffer "*indent*")
2751 (num-diffs 0)
2752 last-pos
2753 previous-set-info
2754 (max 17)
2755 vec
2756 msg
2757 (comment-col nil) ;; number if all same, t if seen diff values
2758 (comments-always-default t) ;; nil if we see one not default
2759 initial-msg
2760 (specified-basic-offset (and arg (numberp arg)
2761 (> arg 0)))
2762 (linenum 0)
2763 suggested)
2764 (setq vec (make-vector max 0))
2765 (sh-mark-init out-buffer)
2766
2767 (if specified-basic-offset
2768 (progn
2769 (setq sh-basic-offset arg)
2770 (setq initial-msg
2771 (format "Using specified sh-basic-offset of %d"
2772 sh-basic-offset)))
2773 (setq initial-msg
2774 (format "Initial value of sh-basic-offset: %s"
2775 sh-basic-offset)))
2776
2777 (while (< (point) (point-max))
2778 (setq linenum (1+ linenum))
2779 ;; (if (zerop (% linenum 10))
2780 (message "line %d" linenum)
2781 ;; )
2782 (unless (looking-at "\\s-*$") ;; ignore empty lines!
2783 (let* ((sh-indent-comment t) ;; info must return default indent
2784 (info (sh-get-indent-info))
2785 (var (sh-get-indent-var-for-line info))
2786 sval ival diff new-val
2787 (curr-indent (current-indentation)))
2788 (cond
2789 ((null var)
2790 nil)
2791 ((stringp var)
2792 nil)
2793 ((numberp (setq sval (sh-var-value var 'no-error)))
2794 ;; the numberp excludes comments since sval will be t.
2795 (setq ival (sh-calculate-indent))
2796 (setq diff (- curr-indent ival))
2797 (setq new-val (+ sval diff))
2798 (sh-set-var-value var new-val 'no-symbol)
2799 (unless (looking-at "\\s-*#") ;; don't learn from comments
2800 (if (setq previous-set-info (assoc var learned-var-list))
2801 (progn
2802 ;; it was already there, is it same value ?
2803 (unless (eq (symbol-value var)
2804 (nth 1 previous-set-info))
2805 (sh-mark-line
2806 (format "Variable %s was set to %s"
2807 var (symbol-value var))
2808 (point) out-buffer t t)
2809 (sh-mark-line
2810 (format " but was previously set to %s"
2811 (nth 1 previous-set-info))
2812 (nth 2 previous-set-info) out-buffer t)
2813 (setq num-diffs (1+ num-diffs))
2814 ;; (delete previous-set-info learned-var-list)
2815 (setcdr previous-set-info
2816 (list (symbol-value var) (point)))
2817 )
2818 )
2819 (setq learned-var-list
2820 (append (list (list var (symbol-value var)
2821 (point)))
2822 learned-var-list)))
2823 (if (numberp new-val)
2824 (progn
2825 (sh-debug
2826 "This line's indent value: %d" new-val)
2827 (if (< new-val 0)
2828 (setq new-val (- new-val)))
2829 (if (< new-val max)
2830 (aset vec new-val (1+ (aref vec new-val))))))
2831 ))
2832 ((eq var 'sh-indent-comment)
2833 (unless (= curr-indent (sh-calculate-indent info))
2834 ;; this is not the default indentation
2835 (setq comments-always-default nil)
2836 (if comment-col ;; then we have see one before
2837 (or (eq comment-col curr-indent)
2838 (setq comment-col t)) ;; seen a different one
2839 (setq comment-col curr-indent))
2840 ))
2841 (t
2842 (sh-debug "Cannot learn this line!!!")
2843 ))
2844 (sh-debug
2845 "at %s learned-var-list is %s" (point) learned-var-list)
2846 ))
2847 (forward-line 1)
2848 ) ;; while
2849 (if sh-debug
2850 (progn
2851 (setq msg (format
2852 "comment-col = %s comments-always-default = %s"
2853 comment-col comments-always-default))
2854 ;; (message msg)
2855 (sh-mark-line msg nil out-buffer)))
2856 (cond
2857 ((eq comment-col 0)
2858 (setq msg "\nComments are all in 1st column.\n"))
2859 (comments-always-default
2860 (setq msg "\nComments follow default indentation.\n")
2861 (setq comment-col t))
2862 ((numberp comment-col)
2863 (setq msg (format "\nComments are in col %d." comment-col)))
2864 (t
2865 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
2866 (setq comment-col nil)
2867 ))
2868 (sh-debug msg)
2869 (sh-mark-line msg nil out-buffer)
2870
2871 (sh-mark-line initial-msg nil out-buffer t t)
2872
2873 (setq suggested (sh-guess-basic-offset vec))
2874
2875 (if (and suggested (not specified-basic-offset))
2876 (let ((new-value
2877 (cond
2878 ;; t => set it if we have a single value as a number
2879 ((and (eq sh-learn-basic-offset t) (numberp suggested))
2880 suggested)
2881 ;; other non-nil => set it if only one value was found
2882 (sh-learn-basic-offset
2883 (if (numberp suggested)
2884 suggested
2885 (if (= (length suggested) 1)
2886 (car suggested))))
2887 (t
2888 nil))))
2889 (if new-value
2890 (progn
2891 (setq learned-var-list
2892 (append (list (list 'sh-basic-offset
2893 (setq sh-basic-offset new-value)
2894 (point-max)))
2895 learned-var-list))
2896 ;; Not sure if we need to put this line in, since
2897 ;; it will appear in the "Learned variable settings".
2898 (sh-mark-line
2899 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
2900 nil out-buffer))
2901 (sh-mark-line
2902 (if (listp suggested)
2903 (format "Possible value(s) for sh-basic-offset: %s"
2904 (mapconcat 'int-to-string suggested " "))
2905 (format "Suggested sh-basic-offset: %d" suggested))
2906 nil out-buffer))))
2907
2908
2909 (setq learned-var-list
2910 (append (list (list 'sh-indent-comment comment-col (point-max)))
2911 learned-var-list))
2912 (setq sh-indent-comment comment-col)
2913 (let ((name (buffer-name))
2914 (lines (if (and (eq (point-min) 1)
2915 (eq (point-max) (1+ (buffer-size))))
2916 ""
2917 (format "lines %d to %d of "
2918 (1+ (count-lines 1 (point-min)))
2919 (1+ (count-lines 1 (point-max))))))
2920 )
2921 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
2922 (if arg
2923 ;; Set learned variables to symbolic rather than numeric
2924 ;; values where possible.
2925 (dolist (learned-var (reverse learned-var-list))
2926 (let ((var (car learned-var))
2927 (val (nth 1 learned-var)))
2928 (when (and (not (eq var 'sh-basic-offset))
2929 (numberp val))
2930 (sh-set-var-value var val)))))
2931 (dolist (learned-var (reverse learned-var-list))
2932 (let ((var (car learned-var)))
2933 (sh-mark-line (format " %s %s" var (symbol-value var))
2934 (nth 2 learned-var) out-buffer)))
2935 (save-excursion
2936 (set-buffer out-buffer)
2937 (goto-char (point-min))
2938 (insert
2939 (format "Indentation values for buffer %s.\n" name)
2940 (format "%d indentation variable%s different values%s\n\n"
2941 num-diffs
2942 (if (= num-diffs 1)
2943 " has" "s have")
2944 (if (zerop num-diffs)
2945 "." ":"))
2946 )))
2947 ;; Are abnormal hooks considered bad form?
2948 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
2949 (if (or sh-popup-occur-buffer (> num-diffs 0))
2950 (pop-to-buffer out-buffer))
2951 )))
2952
2953 (defun sh-guess-basic-offset (vec)
2954 "See if we can determine a reasonable value for `sh-basic-offset'.
2955 This is experimental, heuristic and arbitrary!
2956 Argument VEC is a vector of information collected by
2957 `sh-learn-buffer-indent'.
2958 Return values:
2959 number - there appears to be a good single value
2960 list of numbers - no obvious one, here is a list of one or more
2961 reasonable choices
2962 nil - we couldn't find a reasonable one."
2963 (let* ((max (1- (length vec)))
2964 (i 1)
2965 (totals (make-vector max 0))
2966 (return nil)
2967 j)
2968 (while (< i max)
2969 (aset totals i (+ (aref totals i) (* 4 (aref vec i))))
2970 (setq j (/ i 2))
2971 (if (zerop (% i 2))
2972 (aset totals i (+ (aref totals i) (aref vec (/ i 2)))))
2973 (if (< (* i 2) max)
2974 (aset totals i (+ (aref totals i) (aref vec (* i 2)))))
2975 (setq i (1+ i)))
2976
2977 (let ((x nil)
2978 (result nil)
2979 tot sum p)
2980 (setq i 1)
2981 (while (< i max)
2982 (if (/= (aref totals i) 0)
2983 (setq x (append x (list (cons i (aref totals i))))))
2984 (setq i (1+ i)))
2985
2986 (setq x (sort x (lambda (a b) (> (cdr a) (cdr b)))))
2987 (setq tot (apply '+ (append totals nil)))
2988 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
2989 vec totals tot))
2990 (cond
2991 ((zerop (length x))
2992 (message "no values!")) ;; we return nil
2993 ((= (length x) 1)
2994 (message "only value is %d" (car (car x)))
2995 (setq result (car (car x)))) ;; return single value
2996 ((> (cdr (car x)) (/ tot 2))
2997 ;; 1st is > 50%
2998 (message "basic-offset is probably %d" (car (car x)))
2999 (setq result (car (car x)))) ;; again, return a single value
3000 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3001 ;; 1st is >= 2 * 2nd
3002 (message "basic-offset could be %d" (car (car x)))
3003 (setq result (car (car x))))
3004 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3005 ;; 1st & 2nd together >= 50% - return a list
3006 (setq p x sum 0 result nil)
3007 (while (and p
3008 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3009 (setq result (append result (list (car (car p)))))
3010 (setq p (cdr p)))
3011 (message "Possible choices for sh-basic-offset: %s"
3012 (mapconcat 'int-to-string result " ")))
3013 (t
3014 (message "No obvious value for sh-basic-offset. Perhaps %d"
3015 (car (car x)))
3016 ;; result is nil here
3017 ))
3018 result)))
3019
3020 ;; ========================================================================
3021
3022 ;; Styles -- a quick and dirty way of saving the indentation settings.
3023
3024 (defvar sh-styles-alist nil
3025 "A list of all known shell indentation styles.")
3026
3027 (defun sh-name-style (name &optional confirm-overwrite)
3028 "Name the current indentation settings as a style called NAME.
3029 If this name exists, the command will prompt whether it should be
3030 overwritten if
3031 - - it was called interactively with a prefix argument, or
3032 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3033 ;; (interactive "sName for this style: ")
3034 (interactive
3035 (list
3036 (read-from-minibuffer "Name for this style? " )
3037 (not current-prefix-arg)))
3038 (let ((slist (cons name
3039 (mapcar (lambda (var) (cons var (symbol-value var)))
3040 sh-var-list)))
3041 (style (assoc name sh-styles-alist)))
3042 (if style
3043 (if (and confirm-overwrite
3044 (not (y-or-n-p "This style exists. Overwrite it? ")))
3045 (message "Not changing style %s" name)
3046 (message "Updating style %s" name)
3047 (setcdr style (cdr slist)))
3048 (message "Creating new style %s" name)
3049 (push slist sh-styles-alist))))
3050
3051 (defun sh-load-style (name)
3052 "Set shell indentation values for this buffer from those in style NAME."
3053 (interactive (list (completing-read
3054 "Which style to use for this buffer? "
3055 sh-styles-alist nil t)))
3056 (let ((sl (assoc name sh-styles-alist)))
3057 (if (null sl)
3058 (error "sh-load-style - style %s not known" name)
3059 (dolist (var (cdr sl))
3060 (set (car var) (cdr var))))))
3061
3062 (defun sh-save-styles-to-buffer (buff)
3063 "Save all current styles in elisp to buffer BUFF.
3064 This is always added to the end of the buffer."
3065 (interactive (list
3066 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3067 (with-current-buffer (get-buffer-create buff)
3068 (goto-char (point-max))
3069 (insert "\n")
3070 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3071
3072
3073 \f
3074 ;; statement syntax-commands for various shells
3075
3076 ;; You are welcome to add the syntax or even completely new statements as
3077 ;; appropriate for your favorite shell.
3078
3079 (defconst sh-non-closing-paren
3080 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3081 ;; that inherits this property, which then confuses the indentation.
3082 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3083
3084 (define-skeleton sh-case
3085 "Insert a case/switch statement. See `sh-feature'."
3086 (csh "expression: "
3087 "switch( " str " )" \n
3088 > "case " (read-string "pattern: ") ?: \n
3089 > _ \n
3090 "breaksw" \n
3091 ( "other pattern, %s: "
3092 < "case " str ?: \n
3093 > _ \n
3094 "breaksw" \n)
3095 < "default:" \n
3096 > _ \n
3097 resume:
3098 < < "endsw" \n)
3099 (es)
3100 (rc "expression: "
3101 > "switch( " str " ) {" \n
3102 > "case " (read-string "pattern: ") \n
3103 > _ \n
3104 ( "other pattern, %s: "
3105 "case " str > \n
3106 > _ \n)
3107 "case *" > \n
3108 > _ \n
3109 resume:
3110 ?\} > \n)
3111 (sh "expression: "
3112 > "case " str " in" \n
3113 ( "pattern, %s: "
3114 > str sh-non-closing-paren \n
3115 > _ \n
3116 ";;" \n)
3117 > "*" sh-non-closing-paren \n
3118 > _ \n
3119 resume:
3120 "esac" > \n))
3121
3122 (define-skeleton sh-for
3123 "Insert a for loop. See `sh-feature'."
3124 (csh eval sh-modify sh
3125 1 ""
3126 2 "foreach "
3127 4 " ( "
3128 6 " )"
3129 15 '<
3130 16 "end")
3131 (es eval sh-modify rc
3132 4 " = ")
3133 (rc eval sh-modify sh
3134 2 "for( "
3135 6 " ) {"
3136 15 ?\} )
3137 (sh "Index variable: "
3138 > "for " str " in " _ "; do" \n
3139 > _ | ?$ & (sh-remember-variable str) \n
3140 "done" > \n))
3141
3142
3143
3144 (define-skeleton sh-indexed-loop
3145 "Insert an indexed loop from 1 to n. See `sh-feature'."
3146 (bash eval identity posix)
3147 (csh "Index variable: "
3148 "@ " str " = 1" \n
3149 "while( $" str " <= " (read-string "upper limit: ") " )" \n
3150 > _ ?$ str \n
3151 "@ " str "++" \n
3152 < "end" \n)
3153 (es eval sh-modify rc
3154 4 " =")
3155 (ksh88 "Index variable: "
3156 > "integer " str "=0" \n
3157 > "while (( ( " str " += 1 ) <= "
3158 (read-string "upper limit: ")
3159 " )); do" \n
3160 > _ ?$ (sh-remember-variable str) > \n
3161 "done" > \n)
3162 (posix "Index variable: "
3163 > str "=1" \n
3164 "while [ $" str " -le "
3165 (read-string "upper limit: ")
3166 " ]; do" \n
3167 > _ ?$ str \n
3168 str ?= (sh-add (sh-remember-variable str) 1) \n
3169 "done" > \n)
3170 (rc "Index variable: "
3171 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
3172 (read-string "upper limit: ")
3173 "; i++ ) print i }'`}) {" \n
3174 > _ ?$ (sh-remember-variable str) \n
3175 ?\} > \n)
3176 (sh "Index variable: "
3177 > "for " str " in `awk 'BEGIN { for( i=1; i<="
3178 (read-string "upper limit: ")
3179 "; i++ ) print i }'`; do" \n
3180 > _ ?$ (sh-remember-variable str) \n
3181 "done" > \n))
3182
3183
3184 (defun sh-shell-initialize-variables ()
3185 "Scan the buffer for variable assignments.
3186 Add these variables to `sh-shell-variables'."
3187 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3188 (save-excursion
3189 (goto-char (point-min))
3190 (setq sh-shell-variables-initialized t)
3191 (while (search-forward "=" nil t)
3192 (sh-assignment 0)))
3193 (message "Scanning buffer `%s' for variable assignments...done"
3194 (buffer-name)))
3195
3196 (defvar sh-add-buffer)
3197
3198 (defun sh-add-completer (string predicate code)
3199 "Do completion using `sh-shell-variables', but initialize it first.
3200 This function is designed for use as the \"completion table\",
3201 so it takes three arguments:
3202 STRING, the current buffer contents;
3203 PREDICATE, the predicate for filtering possible matches;
3204 CODE, which says what kind of things to do.
3205 CODE can be nil, t or `lambda'.
3206 nil means to return the best completion of STRING, or nil if there is none.
3207 t means to return a list of all possible completions of STRING.
3208 `lambda' means to return t if STRING is a valid completion as it stands."
3209 (let ((sh-shell-variables
3210 (save-excursion
3211 (set-buffer sh-add-buffer)
3212 (or sh-shell-variables-initialized
3213 (sh-shell-initialize-variables))
3214 (nconc (mapcar (lambda (var)
3215 (let ((name
3216 (substring var 0 (string-match "=" var))))
3217 (cons name name)))
3218 process-environment)
3219 sh-shell-variables))))
3220 (case code
3221 (nil (try-completion string sh-shell-variables predicate))
3222 (lambda (test-completion string sh-shell-variables predicate))
3223 (t (all-completions string sh-shell-variables predicate)))))
3224
3225 (defun sh-add (var delta)
3226 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3227 (interactive
3228 (let ((sh-add-buffer (current-buffer)))
3229 (list (completing-read "Variable: " 'sh-add-completer)
3230 (prefix-numeric-value current-prefix-arg))))
3231 (insert (sh-feature '((bash . "$[ ")
3232 (ksh88 . "$(( ")
3233 (posix . "$(( ")
3234 (rc . "`{expr $")
3235 (sh . "`expr $")
3236 (zsh . "$[ ")))
3237 (sh-remember-variable var)
3238 (if (< delta 0) " - " " + ")
3239 (number-to-string (abs delta))
3240 (sh-feature '((bash . " ]")
3241 (ksh88 . " ))")
3242 (posix . " ))")
3243 (rc . "}")
3244 (sh . "`")
3245 (zsh . " ]")))))
3246
3247
3248
3249 (define-skeleton sh-function
3250 "Insert a function definition. See `sh-feature'."
3251 (bash eval sh-modify ksh88
3252 3 "() {")
3253 (ksh88 "name: "
3254 "function " str " {" \n
3255 > _ \n
3256 < "}" \n)
3257 (rc eval sh-modify ksh88
3258 1 "fn ")
3259 (sh ()
3260 "() {" \n
3261 > _ \n
3262 < "}" \n))
3263
3264
3265
3266 (define-skeleton sh-if
3267 "Insert an if statement. See `sh-feature'."
3268 (csh "condition: "
3269 "if( " str " ) then" \n
3270 > _ \n
3271 ( "other condition, %s: "
3272 < "else if( " str " ) then" \n
3273 > _ \n)
3274 < "else" \n
3275 > _ \n
3276 resume:
3277 < "endif" \n)
3278 (es "condition: "
3279 > "if { " str " } {" \n
3280 > _ \n
3281 ( "other condition, %s: "
3282 "} { " str " } {" > \n
3283 > _ \n)
3284 "} {" > \n
3285 > _ \n
3286 resume:
3287 ?\} > \n)
3288 (rc "condition: "
3289 > "if( " str " ) {" \n
3290 > _ \n
3291 ( "other condition, %s: "
3292 "} else if( " str " ) {" > \n
3293 > _ \n)
3294 "} else {" > \n
3295 > _ \n
3296 resume:
3297 ?\} > \n)
3298 (sh "condition: "
3299 '(setq input (sh-feature sh-test))
3300 > "if " str "; then" \n
3301 > _ \n
3302 ( "other condition, %s: "
3303 > "elif " str "; then" > \n
3304 > \n)
3305 "else" > \n
3306 > \n
3307 resume:
3308 "fi" > \n))
3309
3310
3311
3312 (define-skeleton sh-repeat
3313 "Insert a repeat loop definition. See `sh-feature'."
3314 (es nil
3315 > "forever {" \n
3316 > _ \n
3317 ?\} > \n)
3318 (zsh "factor: "
3319 > "repeat " str "; do" > \n
3320 > \n
3321 "done" > \n))
3322
3323 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3324
3325
3326
3327 (define-skeleton sh-select
3328 "Insert a select statement. See `sh-feature'."
3329 (ksh88 "Index variable: "
3330 > "select " str " in " _ "; do" \n
3331 > ?$ str \n
3332 "done" > \n)
3333 (bash eval sh-append ksh88))
3334 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3335
3336
3337
3338 (define-skeleton sh-tmp-file
3339 "Insert code to setup temporary file handling. See `sh-feature'."
3340 (bash eval identity ksh88)
3341 (csh (file-name-nondirectory (buffer-file-name))
3342 "set tmp = /tmp/" str ".$$" \n
3343 "onintr exit" \n _
3344 (and (goto-char (point-max))
3345 (not (bolp))
3346 ?\n)
3347 "exit:\n"
3348 "rm $tmp* >&/dev/null" > \n)
3349 (es (file-name-nondirectory (buffer-file-name))
3350 > "local( signals = $signals sighup sigint; tmp = /tmp/" str
3351 ".$pid ) {" \n
3352 > "catch @ e {" \n
3353 > "rm $tmp^* >[2]/dev/null" \n
3354 "throw $e" \n
3355 "} {" > \n
3356 _ \n
3357 ?\} > \n
3358 ?\} > \n)
3359 (ksh88 eval sh-modify sh
3360 7 "EXIT")
3361 (rc (file-name-nondirectory (buffer-file-name))
3362 > "tmp = /tmp/" str ".$pid" \n
3363 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
3364 (sh (file-name-nondirectory (buffer-file-name))
3365 > "TMP=${TMPDIR:-/tmp}/" str ".$$" \n
3366 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
3367
3368
3369
3370 (define-skeleton sh-until
3371 "Insert an until loop. See `sh-feature'."
3372 (sh "condition: "
3373 '(setq input (sh-feature sh-test))
3374 > "until " str "; do" \n
3375 > _ \n
3376 "done" > \n))
3377 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3378
3379
3380
3381 (define-skeleton sh-while
3382 "Insert a while loop. See `sh-feature'."
3383 (csh eval sh-modify sh
3384 2 ""
3385 3 "while( "
3386 5 " )"
3387 10 '<
3388 11 "end")
3389 (es eval sh-modify sh
3390 3 "while { "
3391 5 " } {"
3392 10 ?\} )
3393 (rc eval sh-modify sh
3394 3 "while( "
3395 5 " ) {"
3396 10 ?\} )
3397 (sh "condition: "
3398 '(setq input (sh-feature sh-test))
3399 > "while " str "; do" \n
3400 > _ \n
3401 "done" > \n))
3402
3403
3404
3405 (define-skeleton sh-while-getopts
3406 "Insert a while getopts loop. See `sh-feature'.
3407 Prompts for an options string which consists of letters for each recognized
3408 option followed by a colon `:' if the option accepts an argument."
3409 (bash eval sh-modify sh
3410 18 "${0##*/}")
3411 (csh nil
3412 "while( 1 )" \n
3413 > "switch( \"$1\" )" \n
3414 '(setq input '("- x" . 2))
3415 > >
3416 ( "option, %s: "
3417 < "case " '(eval str)
3418 '(if (string-match " +" str)
3419 (setq v1 (substring str (match-end 0))
3420 str (substring str 0 (match-beginning 0)))
3421 (setq v1 nil))
3422 str ?: \n
3423 > "set " v1 & " = $2" | -4 & _ \n
3424 (if v1 "shift") & \n
3425 "breaksw" \n)
3426 < "case --:" \n
3427 > "shift" \n
3428 < "default:" \n
3429 > "break" \n
3430 resume:
3431 < < "endsw" \n
3432 "shift" \n
3433 < "end" \n)
3434 (ksh88 eval sh-modify sh
3435 16 "print"
3436 18 "${0##*/}"
3437 36 "OPTIND-1")
3438 (posix eval sh-modify sh
3439 18 "$(basename $0)")
3440 (sh "optstring: "
3441 > "while getopts :" str " OPT; do" \n
3442 > "case $OPT in" \n
3443 '(setq v1 (append (vconcat str) nil))
3444 ( (prog1 (if v1 (char-to-string (car v1)))
3445 (if (eq (nth 1 v1) ?:)
3446 (setq v1 (nthcdr 2 v1)
3447 v2 "\"$OPTARG\"")
3448 (setq v1 (cdr v1)
3449 v2 nil)))
3450 > str "|+" str sh-non-closing-paren \n
3451 > _ v2 \n
3452 > ";;" \n)
3453 > "*" sh-non-closing-paren \n
3454 > "echo" " \"usage: " "`basename $0`"
3455 " [+-" '(setq v1 (point)) str
3456 '(save-excursion
3457 (while (search-backward ":" v1 t)
3458 (replace-match " ARG] [+-" t t)))
3459 (if (eq (preceding-char) ?-) -5)
3460 (if (and (sequencep v1) (length v1)) "] " "} ")
3461 "[--] ARGS...\"" \n
3462 "exit 2" > \n
3463 "esac" >
3464 \n "done"
3465 > \n
3466 "shift " (sh-add "OPTIND" -1) \n))
3467
3468
3469
3470 (defun sh-assignment (arg)
3471 "Remember preceding identifier for future completion and do self-insert."
3472 (interactive "p")
3473 (self-insert-command arg)
3474 (if (<= arg 1)
3475 (sh-remember-variable
3476 (save-excursion
3477 (if (re-search-forward (sh-feature sh-assignment-regexp)
3478 (prog1 (point)
3479 (beginning-of-line 1))
3480 t)
3481 (match-string 1))))))
3482
3483
3484
3485 (defun sh-maybe-here-document (arg)
3486 "Insert self. Without prefix, following unquoted `<' inserts here document.
3487 The document is bounded by `sh-here-document-word'."
3488 (interactive "*P")
3489 (self-insert-command (prefix-numeric-value arg))
3490 (or arg
3491 (not (eq (char-after (- (point) 2)) last-command-char))
3492 (save-excursion
3493 (backward-char 2)
3494 (sh-quoted-p))
3495 (progn
3496 (insert sh-here-document-word)
3497 (or (eolp) (looking-at "[ \t]") (insert ? ))
3498 (end-of-line 1)
3499 (while
3500 (sh-quoted-p)
3501 (end-of-line 2))
3502 (newline)
3503 (save-excursion (insert ?\n sh-here-document-word)))))
3504
3505 \f
3506 ;; various other commands
3507
3508 (autoload 'comint-dynamic-complete "comint"
3509 "Dynamically perform completion at point." t)
3510
3511 (autoload 'shell-dynamic-complete-command "shell"
3512 "Dynamically complete the command at point." t)
3513
3514 (autoload 'comint-dynamic-complete-filename "comint"
3515 "Dynamically complete the filename at point." t)
3516
3517 (autoload 'shell-dynamic-complete-environment-variable "shell"
3518 "Dynamically complete the environment variable at point." t)
3519
3520
3521
3522 (defun sh-newline-and-indent ()
3523 "Strip unquoted whitespace, insert newline, and indent like current line."
3524 (interactive "*")
3525 (indent-to (prog1 (current-indentation)
3526 (delete-region (point)
3527 (progn
3528 (or (zerop (skip-chars-backward " \t"))
3529 (if (sh-quoted-p)
3530 (forward-char)))
3531 (point)))
3532 (newline))))
3533
3534 (defun sh-beginning-of-command ()
3535 "Move point to successive beginnings of commands."
3536 (interactive)
3537 (if (re-search-backward sh-beginning-of-command nil t)
3538 (goto-char (match-beginning 2))))
3539
3540 (defun sh-end-of-command ()
3541 "Move point to successive ends of commands."
3542 (interactive)
3543 (if (re-search-forward sh-end-of-command nil t)
3544 (goto-char (match-end 1))))
3545
3546 (provide 'sh-script)
3547
3548 ;;; sh-script.el ends here