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