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