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