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