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