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