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