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