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