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