Derive from prog-mode, use derived-mode-p, and fix up various
[bpt/emacs.git] / lisp / progmodes / sh-script.el
CommitLineData
ac59aed8 1;;; sh-script.el --- shell-script editing commands for Emacs
b578f267 2
c4f6e489 3;; Copyright (C) 1993, 1994, 1995, 1996, 1997, 1999, 2001, 2002, 2003,
9b026d9f
GM
4;; 2004, 2005, 2006, 2007, 2008, 2009, 2010
5;; Free Software Foundation, Inc.
ac59aed8 6
3e910376 7;; Author: Daniel Pfeiffer <occitan@esperanto.org>
f964dfcb 8;; Version: 2.0f
ac59aed8 9;; Maintainer: FSF
133693bc 10;; Keywords: languages, unix
ac59aed8
RS
11
12;; This file is part of GNU Emacs.
13
b1fc2b50 14;; GNU Emacs is free software: you can redistribute it and/or modify
ac59aed8 15;; it under the terms of the GNU General Public License as published by
b1fc2b50
GM
16;; the Free Software Foundation, either version 3 of the License, or
17;; (at your option) any later version.
ac59aed8
RS
18
19;; GNU Emacs is distributed in the hope that it will be useful,
20;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22;; GNU General Public License for more details.
23
24;; You should have received a copy of the GNU General Public License
b1fc2b50 25;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
ac59aed8
RS
26
27;;; Commentary:
28
133693bc
KH
29;; Major mode for editing shell scripts. Bourne, C and rc shells as well
30;; as various derivatives are supported and easily derived from. Structured
31;; statements can be inserted with one command or abbrev. Completion is
32;; available for filenames, variables known from the script, the shell and
33;; the environment as well as commands.
ac59aed8 34
133693bc
KH
35;;; Known Bugs:
36
bfc8e97b 37;; - In Bourne the keyword `in' is not anchored to case, for, select ...
133693bc
KH
38;; - Variables in `"' strings aren't fontified because there's no way of
39;; syntactically distinguishing those from `'' strings.
e932f2d2 40
f964dfcb
GM
41;; Indentation
42;; ===========
43;; Indentation for rc and es modes is very limited, but for Bourne shells
44;; and its derivatives it is quite customizable.
035107fa 45;;
f964dfcb
GM
46;; The following description applies to sh and derived shells (bash,
47;; zsh, ...).
035107fa 48;;
f964dfcb
GM
49;; There are various customization variables which allow tailoring to
50;; a wide variety of styles. Most of these variables are named
51;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
52;; sh-indent-after-if controls the indenting of a line following
8db2b9fb 53;; an if statement, and sh-indent-for-fi controls the indentation
f964dfcb 54;; of the line containing the fi.
035107fa 55;;
f964dfcb
GM
56;; You can set each to a numeric value, but it is often more convenient
57;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
58;; By changing this one variable you can increase or decrease how much
59;; indentation there is. Valid symbols:
035107fa 60;;
f964dfcb
GM
61;; + Indent right by sh-basic-offset
62;; - Indent left by sh-basic-offset
63;; ++ Indent right twice sh-basic-offset
64;; -- Indent left twice sh-basic-offset
65;; * Indent right half sh-basic-offset
66;; / Indent left half sh-basic-offset.
035107fa 67;;
f964dfcb 68;; There are 4 commands to help set the indentation variables:
035107fa 69;;
f964dfcb
GM
70;; `sh-show-indent'
71;; This shows what variable controls the indentation of the current
72;; line and its value.
035107fa 73;;
f964dfcb
GM
74;; `sh-set-indent'
75;; This allows you to set the value of the variable controlling the
76;; current line's indentation. You can enter a number or one of a
77;; number of special symbols to denote the value of sh-basic-offset,
78;; or its negative, or half it, or twice it, etc. If you've used
79;; cc-mode this should be familiar. If you forget which symbols are
80;; valid simply press C-h at the prompt.
035107fa 81;;
f964dfcb
GM
82;; `sh-learn-line-indent'
83;; Simply make the line look the way you want it, then invoke this
84;; command. It will set the variable to the value that makes the line
85;; indent like that. If called with a prefix argument then it will set
86;; the value to one of the symbols if applicable.
035107fa 87;;
f964dfcb
GM
88;; `sh-learn-buffer-indent'
89;; This is the deluxe function! It "learns" the whole buffer (use
90;; narrowing if you want it to process only part). It outputs to a
91;; buffer *indent* any conflicts it finds, and all the variables it has
92;; learned. This buffer is a sort of Occur mode buffer, allowing you to
93;; easily find where something was set. It is popped to automatically
94;; if there are any conflicts found or if `sh-popup-occur-buffer' is
95;; non-nil.
96;; `sh-indent-comment' will be set if all comments follow the same
97;; pattern; if they don't it will be set to nil.
98;; Whether `sh-basic-offset' is set is determined by variable
99;; `sh-learn-basic-offset'.
035107fa 100;;
f964dfcb
GM
101;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
102;; (e.g. if there are large case statements). Perhaps it does not make
103;; sense to run it on large buffers: if lots of lines have different
104;; indentation styles it will produce a lot of diagnostics in the
105;; *indent* buffer; if there is a consistent style then running
106;; `sh-learn-buffer-indent' on a small region of the buffer should
107;; suffice.
035107fa 108;;
f964dfcb
GM
109;; Saving indentation values
110;; -------------------------
111;; After you've learned the values in a buffer, how to you remember
112;; them? Originally I had hoped that `sh-learn-buffer-indent'
113;; would make this unnecessary; simply learn the values when you visit
114;; the buffer.
115;; You can do this automatically like this:
6c5bcbc1 116;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
035107fa 117;;
4a9592f6 118;; However... `sh-learn-buffer-indent' is extremely slow,
8db2b9fb 119;; especially on large-ish buffer. Also, if there are conflicts the
f964dfcb 120;; "last one wins" which may not produce the desired setting.
035107fa 121;;
f964dfcb
GM
122;; So...There is a minimal way of being able to save indentation values and
123;; to reload them in another buffer or at another point in time.
035107fa 124;;
f964dfcb
GM
125;; Use `sh-name-style' to give a name to the indentation settings of
126;; the current buffer.
127;; Use `sh-load-style' to load indentation settings for the current
128;; buffer from a specific style.
129;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
130;; in lisp code. You can then store it in a file and later use
131;; `load-file' to load it.
035107fa 132;;
f964dfcb
GM
133;; Indentation variables - buffer local or global?
134;; ----------------------------------------------
135;; I think that often having them buffer-local makes sense,
136;; especially if one is using `sh-learn-buffer-indent'. However, if
8db2b9fb 137;; a user sets values using customization, these changes won't appear
f964dfcb 138;; to work if the variables are already local!
035107fa 139;;
8db2b9fb 140;; To get round this, there is a variable `sh-make-vars-local' and 2
f964dfcb 141;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
035107fa 142;;
8db2b9fb 143;; If `sh-make-vars-local' is non-nil, then these variables become
f964dfcb 144;; buffer local when the mode is established.
8db2b9fb 145;; If this is nil, then the variables are global. At any time you
f964dfcb 146;; can make them local with the command `sh-make-vars-local'.
8db2b9fb 147;; Conversely, to update with the global values you can use the
f964dfcb 148;; command `sh-reset-indent-vars-to-global-values'.
035107fa 149;;
8db2b9fb 150;; This may be awkward, but the intent is to cover all cases.
035107fa 151;;
f964dfcb
GM
152;; Awkward things, pitfalls
153;; ------------------------
154;; Indentation for a sh script is complicated for a number of reasons:
035107fa 155;;
8db2b9fb 156;; 1. You can't format by simply looking at symbols, you need to look
f964dfcb
GM
157;; at keywords. [This is not the case for rc and es shells.]
158;; 2. The character ")" is used both as a matched pair "(" ... ")" and
159;; as a stand-alone symbol (in a case alternative). This makes
160;; things quite tricky!
8db2b9fb 161;; 3. Here-documents in a script should be treated "as is", and when
f964dfcb
GM
162;; they terminate we want to revert to the indentation of the line
163;; containing the "<<" symbol.
164;; 4. A line may be continued using the "\".
165;; 5. The character "#" (outside a string) normally starts a comment,
166;; but it doesn't in the sequence "$#"!
035107fa 167;;
f964dfcb 168;; To try and address points 2 3 and 5 I used a feature that cperl mode
8db2b9fb 169;; uses, that of a text's syntax property. This, however, has 2
f964dfcb
GM
170;; disadvantages:
171;; 1. We need to scan the buffer to find which ")" symbols belong to a
172;; case alternative, to find any here documents, and handle "$#".
035107fa 173;;
f964dfcb
GM
174;; Bugs
175;; ----
f964dfcb
GM
176;; - Indenting many lines is slow. It currently does each line
177;; independently, rather than saving state information.
035107fa 178;;
f964dfcb 179;; - `sh-learn-buffer-indent' is extremely slow.
035107fa 180;;
74ab576e
SM
181;; - "case $x in y) echo ;; esac)" the last ) is mis-identified as being
182;; part of a case-pattern. You need to add a semi-colon after "esac" to
183;; coerce sh-script into doing the right thing.
184;;
185;; - "echo $z in ps | head)" the last ) is mis-identified as being part of
186;; a case-pattern. You need to put the "in" between quotes to coerce
187;; sh-script into doing the right thing.
188;;
189;; - A line starting with "}>foo" is not indented like "} >foo".
190;;
f964dfcb
GM
191;; Richard Sharman <rsharman@pobox.com> June 1999.
192
ac59aed8
RS
193;;; Code:
194
195;; page 1: variables and settings
f964dfcb
GM
196;; page 2: indentation stuff
197;; page 3: mode-command and utility functions
198;; page 4: statement syntax-commands for various shells
199;; page 5: various other commands
ac59aed8 200
d2d00127
DL
201(eval-when-compile
202 (require 'skeleton)
017708e9 203 (require 'cl)
d2d00127 204 (require 'comint))
133693bc
KH
205(require 'executable)
206
482db54b
JB
207(defvar font-lock-comment-face)
208(defvar font-lock-set-defaults)
209(defvar font-lock-string-face)
2bffb7c4 210
2bffb7c4 211
cd482e05 212(defgroup sh nil
1689f309 213 "Shell programming utilities."
cd482e05
RS
214 :group 'languages)
215
216(defgroup sh-script nil
1689f309 217 "Shell script mode."
8ec3bce0 218 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
cd482e05
RS
219 :group 'sh
220 :prefix "sh-")
221
222
223(defcustom sh-ancestor-alist
133693bc
KH
224 '((ash . sh)
225 (bash . jsh)
457316e9 226 (bash2 . jsh)
133693bc
KH
227 (dtksh . ksh)
228 (es . rc)
229 (itcsh . tcsh)
230 (jcsh . csh)
231 (jsh . sh)
232 (ksh . ksh88)
233 (ksh88 . jsh)
234 (oash . sh)
235 (pdksh . ksh88)
236 (posix . sh)
237 (tcsh . csh)
238 (wksh . ksh88)
239 (wsh . sh)
547745f5
RS
240 (zsh . ksh88)
241 (rpm . sh))
4f3a3368 242 "Alist showing the direct ancestor of various shells.
133693bc
KH
243This is the basis for `sh-feature'. See also `sh-alias-alist'.
244By default we have the following three hierarchies:
245
246csh C Shell
247 jcsh C Shell with Job Control
c0a4da52
CY
248 tcsh TENEX C Shell
249 itcsh Ian's TENEX C Shell
133693bc
KH
250rc Plan 9 Shell
251 es Extensible Shell
252sh Bourne Shell
309c7698 253 ash Almquist Shell
133693bc
KH
254 jsh Bourne Shell with Job Control
255 bash GNU Bourne Again Shell
256 ksh88 Korn Shell '88
257 ksh Korn Shell '93
258 dtksh CDE Desktop Korn Shell
259 pdksh Public Domain Korn Shell
260 wksh Window Korn Shell
261 zsh Z Shell
262 oash SCO OA (curses) Shell
263 posix IEEE 1003.2 Shell Standard
cd482e05
RS
264 wsh ? Shell"
265 :type '(repeat (cons symbol symbol))
266 :group 'sh-script)
133693bc
KH
267
268
cd482e05 269(defcustom sh-alias-alist
3ee5ce58 270 (append (if (eq system-type 'gnu/linux)
133693bc 271 '((csh . tcsh)
aafd074a 272 (ksh . pdksh)))
133693bc
KH
273 ;; for the time being
274 '((ksh . ksh88)
457316e9 275 (bash2 . bash)
133693bc 276 (sh5 . sh)))
4f3a3368 277 "Alist for transforming shell names to what they really are.
133693bc 278Use this where the name of the executable doesn't correspond to the type of
cd482e05
RS
279shell it really is."
280 :type '(repeat (cons symbol symbol))
281 :group 'sh-script)
133693bc
KH
282
283
cd482e05 284(defcustom sh-shell-file
d9de8c04 285 (or
5c449169
RS
286 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
287 ;; the executable extension, so comparisons with the list of
d9de8c04 288 ;; known shells work.
5c449169 289 (and (memq system-type '(ms-dos windows-nt))
eee86eff
EZ
290 (let* ((shell (getenv "SHELL"))
291 (shell-base
292 (and shell (file-name-nondirectory shell))))
293 ;; shell-script mode doesn't support DOS/Windows shells,
294 ;; so use the default instead.
295 (if (or (null shell)
296 (member (downcase shell-base)
ced7b4a4
RS
297 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
298 "cmdproxy.exe")))
eee86eff
EZ
299 "/bin/sh"
300 (file-name-sans-extension (downcase shell)))))
d9de8c04
RS
301 (getenv "SHELL")
302 "/bin/sh")
4f3a3368 303 "The executable file name for the shell being programmed."
cd482e05
RS
304 :type 'string
305 :group 'sh-script)
133693bc
KH
306
307
cd482e05 308(defcustom sh-shell-arg
8d31ff15 309 ;; bash does not need any options when run in a shell script,
8e46e267 310 '((bash)
133693bc 311 (csh . "-f")
133693bc 312 (pdksh)
8d31ff15 313 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
8e46e267 314 (ksh88)
8d31ff15 315 ;; -p means don't initialize functions from the environment.
133693bc 316 (rc . "-p")
8d31ff15
RS
317 ;; Someone proposed -motif, but we don't want to encourage
318 ;; use of a non-free widget set.
319 (wksh)
320 ;; -f means don't run .zshrc.
133693bc 321 (zsh . "-f"))
4f3a3368 322 "Single argument string for the magic number. See `sh-feature'."
cd482e05
RS
323 :type '(repeat (cons (symbol :tag "Shell")
324 (choice (const :tag "No Arguments" nil)
325 (string :tag "Arguments")
6b61353c 326 (sexp :format "Evaluate: %v"))))
cd482e05 327 :group 'sh-script)
133693bc 328
aa2c2426 329(defcustom sh-imenu-generic-expression
6c5bcbc1 330 `((sh
4f3a3368
SM
331 . ((nil "^\\s-*\\(function\\s-+\\)?\\([[:alpha:]_][[:alnum:]_]+\\)\\s-*()" 2))))
332 "Alist of regular expressions for recognizing shell function definitions.
83c5d68f
DL
333See `sh-feature' and `imenu-generic-expression'."
334 :type '(alist :key-type (symbol :tag "Shell")
335 :value-type (alist :key-type (choice :tag "Title"
336 string
337 (const :tag "None" nil))
338 :value-type
339 (repeat :tag "Regexp, index..." sexp)))
cd32a7ba 340 :group 'sh-script
f964dfcb 341 :version "20.4")
aa2c2426 342
5a989d6e
RS
343(defvar sh-shell-variables nil
344 "Alist of shell variable names that should be included in completion.
345These are used for completion in addition to all the variables named
346in `process-environment'. Each element looks like (VAR . VAR), where
347the car and cdr are the same symbol.")
133693bc 348
5d73ac66
RS
349(defvar sh-shell-variables-initialized nil
350 "Non-nil if `sh-shell-variables' is initialized.")
351
aafd074a
KH
352(defun sh-canonicalize-shell (shell)
353 "Convert a shell name SHELL to the one we should handle it as."
842cc0e6 354 (if (string-match "\\.exe\\'" shell)
c8b88e9f 355 (setq shell (substring shell 0 (match-beginning 0))))
aafd074a
KH
356 (or (symbolp shell)
357 (setq shell (intern shell)))
358 (or (cdr (assq shell sh-alias-alist))
359 shell))
133693bc 360
aafd074a
KH
361(defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
362 "The shell being programmed. This is set by \\[sh-set-shell].")
7fe9a6e3 363;;;###autoload(put 'sh-shell 'safe-local-variable 'symbolp)
133693bc 364
8a0d0722
RS
365(define-abbrev-table 'sh-mode-abbrev-table ())
366
367
3e2dd647
SM
368;; I turned off this feature because it doesn't permit typing commands
369;; in the usual way without help.
370;;(defvar sh-abbrevs
6b61353c 371;; '((csh sh-abbrevs shell
3e2dd647
SM
372;; "switch" 'sh-case
373;; "getopts" 'sh-while-getopts)
374
6b61353c 375;; (es sh-abbrevs shell
3e2dd647
SM
376;; "function" 'sh-function)
377
6b61353c 378;; (ksh88 sh-abbrevs sh
3e2dd647
SM
379;; "select" 'sh-select)
380
6b61353c 381;; (rc sh-abbrevs shell
3e2dd647
SM
382;; "case" 'sh-case
383;; "function" 'sh-function)
384
6b61353c 385;; (sh sh-abbrevs shell
3e2dd647
SM
386;; "case" 'sh-case
387;; "function" 'sh-function
388;; "until" 'sh-until
389;; "getopts" 'sh-while-getopts)
390
391;; ;; The next entry is only used for defining the others
392;; (shell "for" sh-for
393;; "loop" sh-indexed-loop
394;; "if" sh-if
395;; "tmpfile" sh-tmp-file
396;; "while" sh-while)
397
6b61353c 398;; (zsh sh-abbrevs ksh88
3e2dd647
SM
399;; "repeat" 'sh-repeat))
400;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
aafd074a
KH
401;;;Due to the internal workings of abbrev tables, the shell name symbol is
402;;;actually defined as the table for the like of \\[edit-abbrevs].")
ac59aed8 403
ac59aed8
RS
404
405
6b61353c
KH
406(defun sh-mode-syntax-table (table &rest list)
407 "Copy TABLE and set syntax for successive CHARs according to strings S."
408 (setq table (copy-syntax-table table))
409 (while list
410 (modify-syntax-entry (pop list) (pop list) table))
411 table)
412
5ccaa359 413(defvar sh-mode-syntax-table
6b61353c 414 (sh-mode-syntax-table ()
b1e851bb 415 ?\# "<"
b1e851bb
RS
416 ?\n ">#"
417 ?\" "\"\""
418 ?\' "\"'"
419 ?\` "\"`"
8cec35c4
DN
420 ;; ?$ might also have a ". p" syntax. Both "'" and ". p" seem
421 ;; to work fine. This is needed so that dabbrev-expand
422 ;; $VARNAME works.
423 ?$ "'"
b1e851bb
RS
424 ?! "_"
425 ?% "_"
426 ?: "_"
427 ?. "_"
428 ?^ "_"
429 ?~ "_"
29653ebc 430 ?, "_"
56858354 431 ?= "."
b1e851bb
RS
432 ?< "."
433 ?> ".")
5ccaa359
SM
434 "The syntax table to use for Shell-Script mode.
435This is buffer-local in every such buffer.")
b1e851bb 436
6b61353c
KH
437(defvar sh-mode-syntax-table-input
438 '((sh . nil))
b1e851bb 439 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
ac59aed8
RS
440
441(defvar sh-mode-map
bfc8e97b 442 (let ((map (make-sparse-keymap))
f03562ec 443 (menu-map (make-sparse-keymap)))
ac59aed8
RS
444 (define-key map "\C-c(" 'sh-function)
445 (define-key map "\C-c\C-w" 'sh-while)
446 (define-key map "\C-c\C-u" 'sh-until)
133693bc 447 (define-key map "\C-c\C-t" 'sh-tmp-file)
ac59aed8 448 (define-key map "\C-c\C-s" 'sh-select)
133693bc
KH
449 (define-key map "\C-c\C-r" 'sh-repeat)
450 (define-key map "\C-c\C-o" 'sh-while-getopts)
ac59aed8
RS
451 (define-key map "\C-c\C-l" 'sh-indexed-loop)
452 (define-key map "\C-c\C-i" 'sh-if)
453 (define-key map "\C-c\C-f" 'sh-for)
454 (define-key map "\C-c\C-c" 'sh-case)
f964dfcb
GM
455 (define-key map "\C-c?" 'sh-show-indent)
456 (define-key map "\C-c=" 'sh-set-indent)
457 (define-key map "\C-c<" 'sh-learn-line-indent)
458 (define-key map "\C-c>" 'sh-learn-buffer-indent)
bdd5fa99 459 (define-key map "\C-c\C-\\" 'sh-backslash-region)
133693bc 460
ac59aed8
RS
461 (define-key map "=" 'sh-assignment)
462 (define-key map "\C-c+" 'sh-add)
fd4ea9a2
RS
463 (define-key map "\C-\M-x" 'sh-execute-region)
464 (define-key map "\C-c\C-x" 'executable-interpret)
133693bc 465 (define-key map "<" 'sh-maybe-here-document)
81ed2d75
KH
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)
470 (define-key map "`" 'skeleton-pair-insert-maybe)
471 (define-key map "\"" 'skeleton-pair-insert-maybe)
ac59aed8 472
5d1825c6 473 (define-key map [remap complete-tag] 'comint-dynamic-complete)
5d1825c6
AS
474 (define-key map [remap delete-backward-char]
475 'backward-delete-char-untabify)
ac59aed8 476 (define-key map "\C-c:" 'sh-set-shell)
5d1825c6
AS
477 (define-key map [remap backward-sentence] 'sh-beginning-of-command)
478 (define-key map [remap forward-sentence] 'sh-end-of-command)
f03562ec
DN
479 (define-key map [menu-bar sh-script] (cons "Sh-Script" menu-map))
480 (define-key menu-map [sh-learn-buffer-indent]
481 '(menu-item "Learn buffer indentation" sh-learn-buffer-indent
482 :help "Learn how to indent the buffer the way it currently is."))
483 (define-key menu-map [sh-learn-line-indent]
484 '(menu-item "Learn line indentation" sh-learn-line-indent
485 :help "Learn how to indent a line as it currently is indented"))
486 (define-key menu-map [sh-show-indent]
487 '(menu-item "Show indentation" sh-show-indent
63616f52 488 :help "Show the how the current line would be indented"))
f03562ec
DN
489 (define-key menu-map [sh-set-indent]
490 '(menu-item "Set indentation" sh-set-indent
491 :help "Set the indentation for the current line"))
492
63616f52 493 (define-key menu-map [sh-pair]
e4bf03f6
CY
494 '(menu-item "Insert braces and quotes in pairs"
495 (lambda ()
496 (interactive)
497 (require 'skeleton)
498 (setq skeleton-pair (not skeleton-pair)))
499 :button (:toggle . (and (boundp 'skeleton-pair)
500 skeleton-pair))
63616f52
DN
501 :help "Inserting a brace or quote automatically inserts the matching pair"))
502
f03562ec
DN
503 (define-key menu-map [sh-s0] '("--"))
504 ;; Insert
505 (define-key menu-map [sh-function]
506 '(menu-item "Function..." sh-function
507 :help "Insert a function definition"))
508 (define-key menu-map [sh-add]
509 '(menu-item "Addition..." sh-add
510 :help "Insert an addition of VAR and prefix DELTA for Bourne (type) shell"))
511 (define-key menu-map [sh-until]
512 '(menu-item "Until Loop" sh-until
513 :help "Insert an until loop"))
514 (define-key menu-map [sh-repeat]
515 '(menu-item "Repeat Loop" sh-repeat
516 :help "Insert a repeat loop definition"))
517 (define-key menu-map [sh-while]
518 '(menu-item "While Loop" sh-while
519 :help "Insert a while loop"))
520 (define-key menu-map [sh-getopts]
521 '(menu-item "Options Loop" sh-while-getopts
522 :help "Insert a while getopts loop."))
523 (define-key menu-map [sh-indexed-loop]
524 '(menu-item "Indexed Loop" sh-indexed-loop
525 :help "Insert an indexed loop from 1 to n."))
526 (define-key menu-map [sh-select]
527 '(menu-item "Select Statement" sh-select
528 :help "Insert a select statement "))
529 (define-key menu-map [sh-if]
530 '(menu-item "If Statement" sh-if
531 :help "Insert an if statement"))
532 (define-key menu-map [sh-for]
533 '(menu-item "For Loop" sh-for
534 :help "Insert a for loop"))
535 (define-key menu-map [sh-case]
536 '(menu-item "Case Statement" sh-case
537 :help "Insert a case/switch statement"))
538 (define-key menu-map [sh-s1] '("--"))
539 (define-key menu-map [sh-exec]
540 '(menu-item "Execute region" sh-execute-region
541 :help "Pass optional header and region to a subshell for noninteractive execution"))
542 (define-key menu-map [sh-exec-interpret]
543 '(menu-item "Execute script..." executable-interpret
544 :help "Run script with user-specified args, and collect output in a buffer"))
545 (define-key menu-map [sh-set-shell]
546 '(menu-item "Set shell type..." sh-set-shell
547 :help "Set this buffer's shell to SHELL (a string)"))
548 (define-key menu-map [sh-backslash-region]
549 '(menu-item "Backslash region" sh-backslash-region
550 :help "Insert, align, or delete end-of-line backslashes on the lines in the region."))
ac59aed8
RS
551 map)
552 "Keymap used in Shell-Script mode.")
553
0404a075
RS
554(defvar sh-skeleton-pair-default-alist '((?( _ ?)) (?\))
555 (?[ ?\s _ ?\s ?]) (?\])
556 (?{ _ ?}) (?\}))
557 "Value to use for `skeleton-pair-default-alist' in Shell-Script mode.")
ac59aed8 558
cd482e05 559(defcustom sh-dynamic-complete-functions
133693bc
KH
560 '(shell-dynamic-complete-environment-variable
561 shell-dynamic-complete-command
562 comint-dynamic-complete-filename)
4f3a3368 563 "Functions for doing TAB dynamic completion."
cd482e05
RS
564 :type '(repeat function)
565 :group 'sh-script)
ac59aed8 566
c410bd65 567(defcustom sh-assignment-regexp
4f3a3368 568 '((csh . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
133693bc 569 ;; actually spaces are only supported in let/(( ... ))
4f3a3368
SM
570 (ksh88 . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
571 (rc . "\\<\\([[:alnum:]_*]+\\)[ \t]*=")
572 (sh . "\\<\\([[:alnum:]_]+\\)="))
573 "Regexp for the variable name and what may follow in an assignment.
133693bc 574First grouping matches the variable name. This is upto and including the `='
cd482e05
RS
575sign. See `sh-feature'."
576 :type '(repeat (cons (symbol :tag "Shell")
577 (choice regexp
6b61353c 578 (sexp :format "Evaluate: %v"))))
cd482e05 579 :group 'sh-script)
ac59aed8 580
ac59aed8 581
cd482e05
RS
582(defcustom sh-indentation 4
583 "The width for further indentation in Shell-Script mode."
584 :type 'integer
585 :group 'sh-script)
218da0e9 586(put 'sh-indentation 'safe-local-variable 'integerp)
ac59aed8 587
cd482e05 588(defcustom sh-remember-variable-min 3
4f3a3368 589 "Don't remember variables less than this length for completing reads."
cd482e05
RS
590 :type 'integer
591 :group 'sh-script)
ac59aed8
RS
592
593
133693bc 594(defvar sh-header-marker nil
f964dfcb 595 "When non-nil is the end of header for prepending by \\[sh-execute-region].
133693bc 596That command is also used for setting this variable.")
5ccaa359 597(make-variable-buffer-local 'sh-header-marker)
133693bc 598
cd482e05 599(defcustom sh-beginning-of-command
4f3a3368
SM
600 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~[:alnum:]:]\\)"
601 "Regexp to determine the beginning of a shell command.
cd482e05
RS
602The actual command starts at the beginning of the second \\(grouping\\)."
603 :type 'regexp
604 :group 'sh-script)
ac59aed8 605
133693bc 606
cd482e05 607(defcustom sh-end-of-command
4f3a3368
SM
608 "\\([/~[:alnum:]:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
609 "Regexp to determine the end of a shell command.
cd482e05
RS
610The actual command ends at the end of the first \\(grouping\\)."
611 :type 'regexp
612 :group 'sh-script)
ac59aed8
RS
613
614
615
546e2f6f 616(defcustom sh-here-document-word "EOF"
18368c4a 617 "Word to delimit here documents.
546e2f6f
GM
618If the first character of this string is \"-\", this is taken as
619part of the redirection operator, rather than part of the
620word (that is, \"<<-\" instead of \"<<\"). This is a feature
621used by some shells (for example Bash) to indicate that leading
622tabs inside the here document should be ignored. In this case,
623Emacs indents the initial body and end of the here document with
624tabs, to the same level as the start (note that apart from this
625there is no support for indentation of here documents). This
626will only work correctly if `sh-basic-offset' is a multiple of
627`tab-width'.
628
629Any quote characters or leading whitespace in the word are
630removed when closing the here document."
631 :type 'string
632 :group 'sh-script)
633
ac59aed8 634
225f6185
KH
635(defvar sh-test
636 '((sh "[ ]" . 3)
637 (ksh88 "[[ ]]" . 4))
638 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
639
ac59aed8 640
cd482e05
RS
641;; customized this out of sheer bravado. not for the faint of heart.
642;; but it *did* have an asterisk in the docstring!
643(defcustom sh-builtins
6b61353c 644 '((bash sh-append posix
450a39ff 645 "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
6b61353c
KH
646 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
647 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
648 "source" "suspend" "typeset" "unalias")
ac59aed8 649
133693bc 650 ;; The next entry is only used for defining the others
6b61353c 651 (bourne sh-append shell
84bfbb44
KH
652 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
653 "times" "ulimit")
ac59aed8 654
6b61353c 655 (csh sh-append shell
84bfbb44
KH
656 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
657 "setenv" "source" "time" "unalias" "unhash")
658
6b61353c 659 (dtksh sh-append wksh)
ac59aed8 660
84bfbb44
KH
661 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
662 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
ac59aed8 663
6b61353c 664 (jsh sh-append sh
133693bc 665 "bg" "fg" "jobs" "kill" "stop" "suspend")
ac59aed8 666
6b61353c 667 (jcsh sh-append csh
6c5bcbc1 668 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
133693bc 669
6b61353c 670 (ksh88 sh-append bourne
84bfbb44
KH
671 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
672 "typeset" "unalias" "whence")
133693bc 673
6b61353c 674 (oash sh-append sh
133693bc
KH
675 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
676 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
677 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
678 "wmtitle" "wrefresh")
679
6b61353c 680 (pdksh sh-append ksh88
133693bc
KH
681 "bind")
682
6b61353c 683 (posix sh-append sh
133693bc
KH
684 "command")
685
84bfbb44
KH
686 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
687 "whatis")
133693bc 688
6b61353c 689 (sh sh-append bourne
133693bc
KH
690 "hash" "test" "type")
691
692 ;; The next entry is only used for defining the others
84bfbb44
KH
693 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
694
6b61353c 695 (wksh sh-append ksh88
4f3a3368 696 ;; FIXME: This looks too much like a regexp. --Stef
84bfbb44 697 "Xt[A-Z][A-Za-z]*")
133693bc 698
6b61353c 699 (zsh sh-append ksh88
84bfbb44
KH
700 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
701 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
702 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
703 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
704 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
705 "which"))
4f3a3368 706 "List of all shell builtins for completing read and fontification.
133693bc 707Note that on some systems not all builtins are available or some are
cd482e05
RS
708implemented as aliases. See `sh-feature'."
709 :type '(repeat (cons (symbol :tag "Shell")
710 (choice (repeat string)
6b61353c 711 (sexp :format "Evaluate: %v"))))
cd482e05 712 :group 'sh-script)
133693bc
KH
713
714
84bfbb44 715
cd482e05 716(defcustom sh-leading-keywords
6b61353c
KH
717 '((bash sh-append sh
718 "time")
719
720 (csh "else")
84bfbb44
KH
721
722 (es "true" "unwind-protect" "whatis")
723
724 (rc "else")
725
14116f3c 726 (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
4f3a3368 727 "List of keywords that may be immediately followed by a builtin or keyword.
84bfbb44
KH
728Given some confusion between keywords and builtins depending on shell and
729system, the distinction here has been based on whether they influence the
cd482e05
RS
730flow of control or syntax. See `sh-feature'."
731 :type '(repeat (cons (symbol :tag "Shell")
732 (choice (repeat string)
6b61353c 733 (sexp :format "Evaluate: %v"))))
cd482e05 734 :group 'sh-script)
84bfbb44
KH
735
736
cd482e05 737(defcustom sh-other-keywords
6b61353c 738 '((bash sh-append bourne
bc387269 739 "bye" "logout" "select")
133693bc
KH
740
741 ;; The next entry is only used for defining the others
6b61353c 742 (bourne sh-append sh
d9de8c04 743 "function")
133693bc 744
6b61353c 745 (csh sh-append shell
84bfbb44
KH
746 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
747 "if" "logout" "onintr" "repeat" "switch" "then" "while")
133693bc 748
84bfbb44
KH
749 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
750 "return" "throw" "while")
133693bc 751
6b61353c 752 (ksh88 sh-append bourne
84bfbb44 753 "select")
133693bc 754
84bfbb44
KH
755 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
756 "while")
133693bc 757
6b61353c 758 (sh sh-append shell
d9de8c04
RS
759 "done" "esac" "fi" "for" "in" "return")
760
84bfbb44
KH
761 ;; The next entry is only used for defining the others
762 (shell "break" "case" "continue" "exec" "exit")
133693bc 763
6b61353c 764 (zsh sh-append bash
84bfbb44 765 "select"))
4f3a3368 766 "List of keywords not in `sh-leading-keywords'.
cd482e05
RS
767See `sh-feature'."
768 :type '(repeat (cons (symbol :tag "Shell")
769 (choice (repeat string)
6b61353c 770 (sexp :format "Evaluate: %v"))))
cd482e05 771 :group 'sh-script)
133693bc
KH
772
773
774
775(defvar sh-variables
6b61353c
KH
776 '((bash sh-append sh
777 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
778 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
779 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
780 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
781 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
782 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
783 "HISTIGNORE" "history_control" "HISTSIZE"
784 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
785 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
786 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
787 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
788 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
789 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
790 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
791
792 (csh sh-append shell
133693bc
KH
793 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
794 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
795 "shell" "status" "time" "verbose")
796
6b61353c 797 (es sh-append shell
133693bc
KH
798 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
799 "pid" "prompt" "signals")
800
6b61353c 801 (jcsh sh-append csh
6c5bcbc1 802 "notify")
133693bc 803
6b61353c 804 (ksh88 sh-append sh
133693bc
KH
805 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
806 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
807 "TMOUT")
808
6b61353c 809 (oash sh-append sh
133693bc
KH
810 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
811
6b61353c 812 (rc sh-append shell
133693bc
KH
813 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
814 "prompt" "status")
815
6b61353c 816 (sh sh-append shell
133693bc
KH
817 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
818
819 ;; The next entry is only used for defining the others
820 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
821 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
822 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
823 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
824
6b61353c 825 (tcsh sh-append csh
133693bc
KH
826 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
827 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
828 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
829 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
830 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
831 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
832 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
833 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
834 "wordchars")
835
6b61353c 836 (zsh sh-append ksh88
133693bc
KH
837 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
838 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
839 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
840 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
841 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
842 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
843 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
844 "List of all shell variables available for completing read.
845See `sh-feature'.")
846
aace6150 847\f
3e2dd647 848;; Font-Lock support
aace6150 849
33595ec6 850(defface sh-heredoc
ea81d57e
DN
851 '((((min-colors 88) (class color)
852 (background dark))
853 (:foreground "yellow1" :weight bold))
854 (((class color)
aace6150 855 (background dark))
1fd714a4 856 (:foreground "yellow" :weight bold))
aace6150
SM
857 (((class color)
858 (background light))
f03562ec 859 (:foreground "tan1" ))
aace6150 860 (t
1fd714a4 861 (:weight bold)))
aace6150
SM
862 "Face to show a here-document"
863 :group 'sh-indentation)
6d39902f 864
6772c8e1 865;; These colors are probably icky. It's just a placeholder though.
6d39902f
EZ
866(defface sh-quoted-exec
867 '((((class color) (background dark))
868 (:foreground "salmon"))
869 (((class color) (background light))
870 (:foreground "magenta"))
871 (t
872 (:weight bold)))
873 "Face to show quoted execs like ``"
874 :group 'sh-indentation)
c4f6e489 875(define-obsolete-face-alias 'sh-heredoc-face 'sh-heredoc "22.1")
33595ec6 876(defvar sh-heredoc-face 'sh-heredoc)
133693bc 877
450a39ff
GM
878(defface sh-escaped-newline '((t :inherit font-lock-string-face))
879 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
880 :group 'sh-script
881 :version "22.1")
133693bc 882
5789bd83 883(defvar sh-font-lock-keywords-var
6b61353c 884 '((csh sh-append shell
4f3a3368 885 ("\\${?[#?]?\\([[:alpha:]_][[:alnum:]_]*\\|0\\)" 1
6b61353c 886 font-lock-variable-name-face))
133693bc 887
6b61353c 888 (es sh-append executable-font-lock-keywords
4f3a3368 889 ("\\$#?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\)" 1
6b61353c 890 font-lock-variable-name-face))
133693bc 891
6b61353c 892 (rc sh-append es)
6d39902f 893 (bash sh-append shell ("\\$(\\(\\sw+\\)" (1 'sh-quoted-exec t) ))
6b61353c 894 (sh sh-append shell
4d7ce99c 895 ;; Variable names.
4f3a3368 896 ("\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?@!]\\)" 2
4d7ce99c
RS
897 font-lock-variable-name-face)
898 ;; Function names.
6b61353c
KH
899 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
900 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
d5f2a899
DP
901 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
902 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
903 1 font-lock-negation-char-face))
133693bc
KH
904
905 ;; The next entry is only used for defining the others
5789bd83 906 (shell
6b61353c 907 ;; Using font-lock-string-face here confuses sh-get-indent-info.
450a39ff 908 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline)
4f3a3368
SM
909 ("\\\\[^[:alnum:]]" 0 font-lock-string-face)
910 ("\\${?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\|[$*_]\\)" 1
547745f5 911 font-lock-variable-name-face))
6b61353c
KH
912 (rpm sh-append rpm2
913 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face))
914 (rpm2 sh-append shell
915 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face)))
38c979d3 916 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
133693bc 917
5789bd83 918(defvar sh-font-lock-keywords-var-1
bfc8e97b 919 '((sh "[ \t]in\\>"))
38c979d3 920 "Subdued level highlighting for Shell Script modes.")
84bfbb44 921
5789bd83 922(defvar sh-font-lock-keywords-var-2 ()
38c979d3 923 "Gaudy level highlighting for Shell Script modes.")
84bfbb44 924
34939e2c
SM
925;; These are used for the syntax table stuff (derived from cperl-mode).
926;; Note: parse-sexp-lookup-properties must be set to t for it to work.
927(defconst sh-st-punc (string-to-syntax "."))
928(defconst sh-here-doc-syntax (string-to-syntax "|")) ;; generic string
929
9d37a5c0 930(defconst sh-escaped-line-re
935e6b79 931 ;; Should match until the real end-of-continued-line, but if that is not
9d37a5c0
SM
932 ;; possible (because we bump into EOB or the search bound), then we should
933 ;; match until the search bound.
934 "\\(?:\\(?:.*[^\\\n]\\)?\\(?:\\\\\\\\\\)*\\\\\n\\)*.*")
935
936(defconst sh-here-doc-open-re
937 (concat "<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\)+\\)"
938 sh-escaped-line-re "\\(\n\\)"))
3e2dd647
SM
939
940(defvar sh-here-doc-markers nil)
941(make-variable-buffer-local 'sh-here-doc-markers)
942(defvar sh-here-doc-re sh-here-doc-open-re)
943(make-variable-buffer-local 'sh-here-doc-re)
944
cf38dd42 945(defun sh-font-lock-close-heredoc (bol eof indented eol)
3e2dd647
SM
946 "Determine the syntax of the \\n after an EOF.
947If non-nil INDENTED indicates that the EOF was indented."
187cd25b 948 (let* ((eof-re (if eof (regexp-quote eof) ""))
035107fa 949 ;; A rough regexp that should find the opening <<EOF back.
3e2dd647
SM
950 (sre (concat "<<\\(-?\\)\\s-*['\"\\]?"
951 ;; Use \s| to cheaply check it's an open-heredoc.
9d37a5c0
SM
952 eof-re "['\"]?\\([ \t|;&)<>]"
953 sh-escaped-line-re
954 "\\)?\\s|"))
3e2dd647 955 ;; A regexp that will find other EOFs.
035107fa 956 (ere (concat "^" (if indented "[ \t]*") eof-re "\n"))
3e2dd647
SM
957 (start (save-excursion
958 (goto-char bol)
cf38dd42
SM
959 ;; FIXME: will incorrectly find a <<EOF embedded inside
960 ;; the heredoc.
3e2dd647
SM
961 (re-search-backward (concat sre "\\|" ere) nil t))))
962 ;; If subgroup 1 matched, we found an open-heredoc, otherwise we first
963 ;; found a close-heredoc which makes the current close-heredoc inoperant.
964 (cond
965 ((when (and start (match-end 1)
966 (not (and indented (= (match-beginning 1) (match-end 1))))
967 (not (sh-in-comment-or-string (match-beginning 0))))
968 ;; Make sure our `<<' is not the EOF1 of a `cat <<EOF1 <<EOF2'.
969 (save-excursion
970 (goto-char start)
971 (setq start (line-beginning-position 2))
972 (while
973 (progn
974 (re-search-forward "<<") ; Skip ourselves.
975 (and (re-search-forward sh-here-doc-open-re start 'move)
976 (goto-char (match-beginning 0))
977 (sh-in-comment-or-string (point)))))
978 ;; No <<EOF2 found after our <<.
979 (= (point) start)))
cf38dd42 980 (put-text-property eol (1+ eol) 'syntax-table sh-here-doc-syntax))
3e2dd647
SM
981 ((not (or start (save-excursion (re-search-forward sre nil t))))
982 ;; There's no <<EOF either before or after us,
983 ;; so we should remove ourselves from font-lock's keywords.
984 (setq sh-here-doc-markers (delete eof sh-here-doc-markers))
985 (setq sh-here-doc-re
986 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
987 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))
988 nil))))
989
cf38dd42 990(defun sh-font-lock-open-heredoc (start string eol)
3e2dd647
SM
991 "Determine the syntax of the \\n after a <<EOF.
992START is the position of <<.
df321f09 993STRING is the actual word used as delimiter (e.g. \"EOF\").
3e2dd647 994INDENTED is non-nil if the here document's content (and the EOF mark) can
9d37a5c0
SM
995be indented (i.e. a <<- was used rather than just <<).
996Point is at the beginning of the next line."
3e2dd647
SM
997 (unless (or (memq (char-before start) '(?< ?>))
998 (sh-in-comment-or-string start))
34939e2c
SM
999 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
1000 ;; font-lock keywords to detect the end of this here document.
3e2dd647
SM
1001 (let ((str (replace-regexp-in-string "['\"]" "" string)))
1002 (unless (member str sh-here-doc-markers)
1003 (push str sh-here-doc-markers)
1004 (setq sh-here-doc-re
1005 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
1006 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))))
9d37a5c0
SM
1007 (let ((ppss (save-excursion (syntax-ppss (1- (point))))))
1008 (if (nth 4 ppss)
1009 ;; The \n not only starts the heredoc but also closes a comment.
1010 ;; Let's close the comment just before the \n.
1011 (put-text-property (1- (point)) (point) 'syntax-table '(12))) ;">"
1012 (if (or (nth 5 ppss) (> (count-lines start (point)) 1))
1013 ;; If the sh-escaped-line-re part of sh-here-doc-re has matched
1014 ;; several lines, make sure we refontify them together.
1015 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
1016 ;; escaped), it means the right \n is actually further down.
1017 ;; Don't bother fixing it now, but place a multiline property so
1018 ;; that when jit-lock-context-* refontifies the rest of the
1019 ;; buffer, it also refontifies the current line with it.
cf38dd42
SM
1020 (put-text-property start (point) 'syntax-multiline t)))
1021 (put-text-property eol (1+ eol) 'syntax-table sh-here-doc-syntax)))
3e2dd647 1022
e58914d0 1023(defun sh-font-lock-quoted-subshell (limit)
3a723c3a
SM
1024 "Search for a subshell embedded in a string.
1025Find all the unescaped \" characters within said subshell, remembering that
1026subshells can nest."
69c6ad83
SM
1027 ;; FIXME: This can (and often does) match multiple lines, yet it makes no
1028 ;; effort to handle multiline cases correctly, so it ends up being
1029 ;; rather flakey.
cf38dd42 1030 (when (eq ?\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
3a723c3a
SM
1031 ;; bingo we have a $( or a ` inside a ""
1032 (let ((char (char-after (point)))
4f3a3368
SM
1033 ;; `state' can be: double-quote, backquote, code.
1034 (state (if (eq (char-before) ?`) 'backquote 'code))
1035 ;; Stacked states in the context.
1036 (states '(double-quote)))
23ae1f25 1037 (while (and state (progn (skip-chars-forward "^'\\\\\"`$()" limit)
4f3a3368
SM
1038 (< (point) limit)))
1039 ;; unescape " inside a $( ... ) construct.
1040 (case (char-after)
c9176b9f
SM
1041 (?\' (case state
1042 (double-quote nil)
1043 (t (forward-char 1) (skip-chars-forward "^'" limit))))
4f3a3368
SM
1044 (?\\ (forward-char 1))
1045 (?\" (case state
1046 (double-quote (setq state (pop states)))
1047 (t (push state states) (setq state 'double-quote)))
1048 (if state (put-text-property (point) (1+ (point))
1049 'syntax-table '(1))))
1050 (?\` (case state
1051 (backquote (setq state (pop states)))
1052 (t (push state states) (setq state 'backquote))))
1053 (?\$ (if (not (eq (char-after (1+ (point))) ?\())
1054 nil
e58914d0 1055 (forward-char 1)
4f3a3368
SM
1056 (case state
1057 (t (push state states) (setq state 'code)))))
1058 (?\( (case state
1059 (double-quote nil)
1060 (t (push state states) (setq state 'code))))
1061 (?\) (case state
1062 (double-quote nil)
1063 (t (setq state (pop states)))))
e58914d0 1064 (t (error "Internal error in sh-font-lock-quoted-subshell")))
cf38dd42 1065 (forward-char 1)))))
f24a26a5 1066
6d39902f 1067
485219e0
SM
1068(defun sh-is-quoted-p (pos)
1069 (and (eq (char-before pos) ?\\)
1070 (not (sh-is-quoted-p (1- pos)))))
1071
34939e2c
SM
1072(defun sh-font-lock-paren (start)
1073 (save-excursion
1074 (goto-char start)
1075 ;; Skip through all patterns
1076 (while
1077 (progn
1078 (forward-comment (- (point-max)))
1079 ;; Skip through one pattern
1080 (while
1081 (or (/= 0 (skip-syntax-backward "w_"))
6b61353c 1082 (/= 0 (skip-chars-backward "?[]*@/\\"))
485219e0
SM
1083 (and (sh-is-quoted-p (1- (point)))
1084 (goto-char (- (point) 2)))
34939e2c
SM
1085 (when (memq (char-before) '(?\" ?\'))
1086 (condition-case nil (progn (backward-sexp 1) t)
1087 (error nil)))))
3e8ae8a6 1088 ;; Patterns can be preceded by an open-paren (Bug#1320).
6f750f0d 1089 (if (eq (char-before (point)) ?\()
3e8ae8a6 1090 (backward-char 1))
bd24684b
SM
1091 (while (progn
1092 (forward-comment (- (point-max)))
1093 ;; Maybe we've bumped into an escaped newline.
1094 (sh-is-quoted-p (point)))
1095 (backward-char 1))
34939e2c
SM
1096 (when (eq (char-before) ?|)
1097 (backward-char 1) t)))
74ab576e
SM
1098 ;; FIXME: ";; esac )" is a case that looks like a case-pattern but it's
1099 ;; really just a close paren after a case statement. I.e. if we skipped
1100 ;; over `esac' just now, we're not looking at a case-pattern.
1101 (when (progn (backward-char 2)
1102 (if (> start (line-end-position))
1103 (put-text-property (point) (1+ start)
cf38dd42 1104 'syntax-multiline t))
74ab576e
SM
1105 ;; FIXME: The `in' may just be a random argument to
1106 ;; a normal command rather than the real `in' keyword.
1107 ;; I.e. we should look back to try and find the
1108 ;; corresponding `case'.
1109 (looking-at ";;\\|in"))
34939e2c
SM
1110 sh-st-punc)))
1111
935e6b79
SM
1112(defun sh-font-lock-backslash-quote ()
1113 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?\')
1114 ;; In a '...' the backslash is not escaping.
1115 sh-st-punc
1116 nil))
1117
cf38dd42
SM
1118(defun sh-syntax-propertize-function (start end)
1119 (goto-char start)
1120 (while (prog1
1121 (re-search-forward sh-here-doc-re end 'move)
1122 (save-excursion
1123 (save-match-data
1124 (funcall
1125 (syntax-propertize-rules
1126 ;; A `#' begins a comment when it is unquoted and at the
1127 ;; beginning of a word. In the shell, words are separated by
1128 ;; metacharacters. The list of special chars is taken from
1129 ;; the single-unix spec of the shell command language (under
1130 ;; `quoting') but with `$' removed.
1131 ("[^|&;<>()`\\\"' \t\n]\\(#+\\)" (1 "_"))
1132 ;; In a '...' the backslash is not escaping.
1133 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1134 ;; Make sure $@ and $? are correctly recognized as sexps.
1135 ("\\$\\([?@]\\)" (1 "_"))
1136 ;; Distinguish the special close-paren in `case'.
1137 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1138 ;; Highlight (possibly nested) subshells inside "" quoted
1139 ;; regions correctly.
1140 ("\"\\(?:\\(?:.\\|\n\\)*?[^\\]\\(?:\\\\\\\\\\)*\\)??\\(\\$(\\|`\\)"
1141 (1 (ignore
1142 ;; Save excursion because we want to also apply other
1143 ;; syntax-propertize rules within the affected region.
1144 (save-excursion
1145 (sh-font-lock-quoted-subshell end))))))
1146 (prog1 start (setq start (point))) (point)))))
1147 (if (match-beginning 2)
1148 ;; FIXME: actually, once we see an heredoc opener, we should just
1149 ;; search for its ender without propertizing anything in it.
1150 (sh-font-lock-open-heredoc
1151 (match-beginning 0) (match-string 1) (match-beginning 2))
1152 (sh-font-lock-close-heredoc
1153 (match-beginning 0) (match-string 4)
1154 (and (match-beginning 3) (/= (match-beginning 3) (match-end 3)))
1155 (match-beginning 5)))))
f964dfcb 1156
aace6150 1157(defun sh-font-lock-syntactic-face-function (state)
6d39902f
EZ
1158 (let ((q (nth 3 state)))
1159 (if q
b883cdb2 1160 (if (characterp q)
6d39902f
EZ
1161 (if (eq q ?\`) 'sh-quoted-exec font-lock-string-face)
1162 sh-heredoc-face)
1163 font-lock-comment-face)))
aace6150 1164
f964dfcb
GM
1165(defgroup sh-indentation nil
1166 "Variables controlling indentation in shell scripts.
1167
1168Note: customizing these variables will not affect existing buffers if
449d63fd 1169`sh-make-vars-local' is non-nil. See the documentation for
f964dfcb
GM
1170variable `sh-make-vars-local', command `sh-make-vars-local'
1171and command `sh-reset-indent-vars-to-global-values'."
1172 :group 'sh-script)
1173
1174
1175(defcustom sh-set-shell-hook nil
4f3a3368 1176 "Hook run by `sh-set-shell'."
6c5bcbc1 1177 :type 'hook
f964dfcb
GM
1178 :group 'sh-script)
1179
1180(defcustom sh-mode-hook nil
4f3a3368 1181 "Hook run by `sh-mode'."
6c5bcbc1 1182 :type 'hook
f964dfcb
GM
1183 :group 'sh-script)
1184
1185(defcustom sh-learn-basic-offset nil
4f3a3368 1186 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
f964dfcb
GM
1187
1188nil mean: never.
1189t means: only if there seems to be an obvious value.
1190Anything else means: whenever we have a \"good guess\" as to the value."
1191 :type '(choice
1192 (const :tag "Never" nil)
1193 (const :tag "Only if sure" t)
8db2b9fb 1194 (const :tag "If have a good guess" usually))
f964dfcb
GM
1195 :group 'sh-indentation)
1196
1197(defcustom sh-popup-occur-buffer nil
4f3a3368 1198 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
8db2b9fb 1199If t it is always shown. If nil, it is shown only when there
f964dfcb
GM
1200are conflicts."
1201 :type '(choice
1202 (const :tag "Only when there are conflicts." nil)
8db2b9fb 1203 (const :tag "Always" t))
f964dfcb
GM
1204 :group 'sh-indentation)
1205
1206(defcustom sh-blink t
4f3a3368 1207 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
f964dfcb
GM
1208The position on the line is not necessarily meaningful.
1209In some cases the line will be the matching keyword, but this is not
1210always the case."
1211 :type 'boolean
1212 :group 'sh-indentation)
1213
1214(defcustom sh-first-lines-indent 0
4f3a3368 1215 "The indentation of the first non-blank non-comment line.
f964dfcb 1216Usually 0 meaning first column.
8db2b9fb 1217Can be set to a number, or to nil which means leave it as is."
f964dfcb
GM
1218 :type '(choice
1219 (const :tag "Leave as is" nil)
1220 (integer :tag "Column number"
8db2b9fb 1221 :menu-tag "Indent to this col (0 means first col)" ))
f964dfcb
GM
1222 :group 'sh-indentation)
1223
1224
1225(defcustom sh-basic-offset 4
4f3a3368 1226 "The default indentation increment.
dd77d6f4 1227This value is used for the `+' and `-' symbols in an indentation variable."
f964dfcb
GM
1228 :type 'integer
1229 :group 'sh-indentation)
fc9a9287 1230(put 'sh-basic-offset 'safe-local-variable 'integerp)
f964dfcb
GM
1231
1232(defcustom sh-indent-comment nil
4f3a3368 1233 "How a comment line is to be indented.
f964dfcb 1234nil means leave it as it is;
8db2b9fb 1235t means indent it as a normal line, aligning it to previous non-blank
f964dfcb 1236 non-comment line;
7d86c380 1237a number means align to that column, e.g. 0 means first column."
f964dfcb
GM
1238 :type '(choice
1239 (const :tag "Leave as is." nil)
1240 (const :tag "Indent as a normal line." t)
1241 (integer :menu-tag "Indent to this col (0 means first col)."
6c5bcbc1 1242 :tag "Indent to column number.") )
f964dfcb
GM
1243 :group 'sh-indentation)
1244
1245
1246(defvar sh-debug nil
1247 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1248
1249
1250;; Uncomment this defun and comment the defmacro for debugging.
1251;; (defun sh-debug (&rest args)
1252;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1253;; (if sh-debug
1254;; (apply 'message args)))
1255(defmacro sh-debug (&rest args))
1256
d92474ed
SM
1257(defconst sh-symbol-list
1258 '((const :tag "+ " :value +
1259 :menu-tag "+ Indent right by sh-basic-offset")
1260 (const :tag "- " :value -
1261 :menu-tag "- Indent left by sh-basic-offset")
1262 (const :tag "++" :value ++
1263 :menu-tag "++ Indent right twice sh-basic-offset")
1264 (const :tag "--" :value --
1265 :menu-tag "-- Indent left twice sh-basic-offset")
1266 (const :tag "* " :value *
1267 :menu-tag "* Indent right half sh-basic-offset")
1268 (const :tag "/ " :value /
1269 :menu-tag "/ Indent left half sh-basic-offset")))
f964dfcb
GM
1270
1271(defcustom sh-indent-for-else 0
4f3a3368 1272 "How much to indent an `else' relative to its `if'. Usually 0."
f964dfcb
GM
1273 :type `(choice
1274 (integer :menu-tag "A number (positive=>indent right)"
1275 :tag "A number")
1276 (const :tag "--") ;; separator!
1277 ,@ sh-symbol-list
1278 )
1279 :group 'sh-indentation)
1280
d92474ed 1281(defconst sh-number-or-symbol-list
6c5bcbc1
SM
1282 (append '((integer :menu-tag "A number (positive=>indent right)"
1283 :tag "A number")
1284 (const :tag "--")) ; separator
d92474ed 1285 sh-symbol-list))
f964dfcb
GM
1286
1287(defcustom sh-indent-for-fi 0
4f3a3368 1288 "How much to indent a `fi' relative to its `if'. Usually 0."
f964dfcb
GM
1289 :type `(choice ,@ sh-number-or-symbol-list )
1290 :group 'sh-indentation)
1291
dd77d6f4 1292(defcustom sh-indent-for-done 0
4f3a3368 1293 "How much to indent a `done' relative to its matching stmt. Usually 0."
f964dfcb
GM
1294 :type `(choice ,@ sh-number-or-symbol-list )
1295 :group 'sh-indentation)
1296
1297(defcustom sh-indent-after-else '+
4f3a3368 1298 "How much to indent a statement after an `else' statement."
f964dfcb
GM
1299 :type `(choice ,@ sh-number-or-symbol-list )
1300 :group 'sh-indentation)
1301
1302(defcustom sh-indent-after-if '+
4f3a3368 1303 "How much to indent a statement after an `if' statement.
dd77d6f4
RS
1304This includes lines after `else' and `elif' statements, too, but
1305does not affect the `else', `elif' or `fi' statements themselves."
f964dfcb
GM
1306 :type `(choice ,@ sh-number-or-symbol-list )
1307 :group 'sh-indentation)
1308
bae7df15 1309(defcustom sh-indent-for-then 0
4f3a3368 1310 "How much to indent a `then' relative to its `if'."
f964dfcb
GM
1311 :type `(choice ,@ sh-number-or-symbol-list )
1312 :group 'sh-indentation)
1313
3f0f48c0 1314(defcustom sh-indent-for-do 0
4f3a3368 1315 "How much to indent a `do' statement.
32518913
RS
1316This is relative to the statement before the `do', typically a
1317`while', `until', `for', `repeat' or `select' statement."
f964dfcb
GM
1318 :type `(choice ,@ sh-number-or-symbol-list)
1319 :group 'sh-indentation)
1320
dd77d6f4 1321(defcustom sh-indent-after-do '+
4f3a3368 1322 "How much to indent a line after a `do' statement.
dd77d6f4 1323This is used when the `do' is the first word of the line.
32518913
RS
1324This is relative to the statement before the `do', typically a
1325`while', `until', `for', `repeat' or `select' statement."
f964dfcb
GM
1326 :type `(choice ,@ sh-number-or-symbol-list)
1327 :group 'sh-indentation)
1328
1329(defcustom sh-indent-after-loop-construct '+
4f3a3368 1330 "How much to indent a statement after a loop construct.
f964dfcb 1331
dd77d6f4
RS
1332This variable is used when the keyword `do' is on the same line as the
1333loop statement (e.g., `until', `while' or `for').
1334If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
f964dfcb
GM
1335 :type `(choice ,@ sh-number-or-symbol-list)
1336 :group 'sh-indentation)
1337
1338
1339(defcustom sh-indent-after-done 0
4f3a3368 1340 "How much to indent a statement after a `done' keyword.
dd77d6f4 1341Normally this is 0, which aligns the `done' to the matching
f964dfcb 1342looping construct line.
dd77d6f4 1343Setting it non-zero allows you to have the `do' statement on a line
f964dfcb
GM
1344by itself and align the done under to do."
1345 :type `(choice ,@ sh-number-or-symbol-list)
1346 :group 'sh-indentation)
1347
1348(defcustom sh-indent-for-case-label '+
4f3a3368 1349 "How much to indent a case label statement.
dd77d6f4 1350This is relative to the line containing the `case' statement."
f964dfcb
GM
1351 :type `(choice ,@ sh-number-or-symbol-list)
1352 :group 'sh-indentation)
1353
1354(defcustom sh-indent-for-case-alt '++
4f3a3368 1355 "How much to indent statements after the case label.
dd77d6f4 1356This is relative to the line containing the `case' statement."
f964dfcb
GM
1357 :type `(choice ,@ sh-number-or-symbol-list)
1358 :group 'sh-indentation)
1359
1360
1361(defcustom sh-indent-for-continuation '+
4f3a3368 1362 "How much to indent for a continuation statement."
f964dfcb
GM
1363 :type `(choice ,@ sh-number-or-symbol-list)
1364 :group 'sh-indentation)
1365
1366(defcustom sh-indent-after-open '+
4f3a3368 1367 "How much to indent after a line with an opening parenthesis or brace.
dd77d6f4 1368For an open paren after a function, `sh-indent-after-function' is used."
f964dfcb
GM
1369 :type `(choice ,@ sh-number-or-symbol-list)
1370 :group 'sh-indentation)
1371
1372(defcustom sh-indent-after-function '+
4f3a3368 1373 "How much to indent after a function line."
f964dfcb
GM
1374 :type `(choice ,@ sh-number-or-symbol-list)
1375 :group 'sh-indentation)
1376
1377;; These 2 are for the rc shell:
1378
1379(defcustom sh-indent-after-switch '+
4f3a3368 1380 "How much to indent a `case' statement relative to the `switch' statement.
f964dfcb
GM
1381This is for the rc shell."
1382 :type `(choice ,@ sh-number-or-symbol-list)
1383 :group 'sh-indentation)
1384
1385(defcustom sh-indent-after-case '+
4f3a3368 1386 "How much to indent a statement relative to the `case' statement.
f964dfcb
GM
1387This is for the rc shell."
1388 :type `(choice ,@ sh-number-or-symbol-list)
1389 :group 'sh-indentation)
1390
bdd5fa99 1391(defcustom sh-backslash-column 48
4f3a3368 1392 "Column in which `sh-backslash-region' inserts backslashes."
bdd5fa99
RS
1393 :type 'integer
1394 :group 'sh)
1395
1396(defcustom sh-backslash-align t
4f3a3368 1397 "If non-nil, `sh-backslash-region' will align backslashes."
bdd5fa99
RS
1398 :type 'boolean
1399 :group 'sh)
1400
f964dfcb
GM
1401;; Internal use - not designed to be changed by the user:
1402
f964dfcb
GM
1403(defun sh-mkword-regexpr (word)
1404 "Make a regexp which matches WORD as a word.
8db2b9fb 1405This specifically excludes an occurrence of WORD followed by
f964dfcb 1406punctuation characters like '-'."
4f3a3368 1407 (concat word "\\([^-[:alnum:]_]\\|$\\)"))
f964dfcb 1408
d92474ed 1409(defconst sh-re-done (sh-mkword-regexpr "done"))
f964dfcb
GM
1410
1411
1412(defconst sh-kws-for-done
d92474ed 1413 '((sh . ( "while" "until" "for" ) )
f964dfcb
GM
1414 (bash . ( "while" "until" "for" "select" ) )
1415 (ksh88 . ( "while" "until" "for" "select" ) )
d92474ed
SM
1416 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1417 "Which keywords can match the word `done' in this shell.")
f964dfcb
GM
1418
1419
1420(defconst sh-indent-supported
d92474ed 1421 '((sh . t)
f964dfcb 1422 (csh . nil)
d92474ed
SM
1423 (rc . t))
1424 "Shell types that shell indenting can do something with.")
1425
1426(defvar sh-indent-supported-here nil
1427 "Non-nil if we support indentation for the current buffer's shell type.")
f964dfcb 1428
f964dfcb
GM
1429(defconst sh-var-list
1430 '(
1431 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1432 sh-indent-after-do sh-indent-after-done
1433 sh-indent-after-else
1434 sh-indent-after-if
1435 sh-indent-after-loop-construct
1436 sh-indent-after-open
1437 sh-indent-comment
1438 sh-indent-for-case-alt
1439 sh-indent-for-case-label
1440 sh-indent-for-continuation
1441 sh-indent-for-do
1442 sh-indent-for-done
1443 sh-indent-for-else
1444 sh-indent-for-fi
1445 sh-indent-for-then
1446 )
1447 "A list of variables used by script mode to control indentation.
1448This list is used when switching between buffer-local and global
8db2b9fb 1449values of variables, and for the commands using indentation styles.")
f964dfcb
GM
1450
1451(defvar sh-make-vars-local t
1452 "*Controls whether indentation variables are local to the buffer.
8db2b9fb
SM
1453If non-nil, indentation variables are made local initially.
1454If nil, you can later make the variables local by invoking
f964dfcb
GM
1455command `sh-make-vars-local'.
1456The default is t because I assume that in one Emacs session one is
1457frequently editing existing scripts with different styles.")
1458
133693bc
KH
1459\f
1460;; mode-command and utility functions
1461
fc8318f6 1462;;;###autoload
791ffe1c 1463(define-derived-mode sh-mode prog-mode "Shell-script"
ac59aed8
RS
1464 "Major mode for editing shell scripts.
1465This mode works for many shells, since they all have roughly the same syntax,
1466as far as commands, arguments, variables, pipes, comments etc. are concerned.
1467Unless the file's magic number indicates the shell, your usual shell is
1468assumed. Since filenames rarely give a clue, they are not further analyzed.
1469
133693bc
KH
1470This mode adapts to the variations between shells (see `sh-set-shell') by
1471means of an inheritance based feature lookup (see `sh-feature'). This
1472mechanism applies to all variables (including skeletons) that pertain to
1473shell-specific features.
ac59aed8 1474
133693bc
KH
1475The default style of this mode is that of Rosenblatt's Korn shell book.
1476The syntax of the statements varies with the shell being used. The
1477following commands are available, based on the current shell's syntax:
917e8d0b 1478\\<sh-mode-map>
ac59aed8
RS
1479\\[sh-case] case statement
1480\\[sh-for] for loop
1481\\[sh-function] function definition
1482\\[sh-if] if statement
1483\\[sh-indexed-loop] indexed loop from 1 to n
133693bc
KH
1484\\[sh-while-getopts] while getopts loop
1485\\[sh-repeat] repeat loop
1486\\[sh-select] select loop
ac59aed8
RS
1487\\[sh-until] until loop
1488\\[sh-while] while loop
1489
f964dfcb
GM
1490For sh and rc shells indentation commands are:
1491\\[sh-show-indent] Show the variable controlling this line's indentation.
1492\\[sh-set-indent] Set then variable controlling this line's indentation.
1493\\[sh-learn-line-indent] Change the indentation variable so this line
1494would indent to the way it currently is.
1495\\[sh-learn-buffer-indent] Set the indentation variables so the
8db2b9fb 1496buffer indents as it currently is indented.
f964dfcb
GM
1497
1498
ac59aed8 1499\\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
2ae8360b 1500\\[newline-and-indent] Delete unquoted space and indent new line same as this one.
ac59aed8
RS
1501\\[sh-end-of-command] Go to end of successive commands.
1502\\[sh-beginning-of-command] Go to beginning of successive commands.
1503\\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
133693bc 1504\\[sh-execute-region] Have optional header and region be executed in a subshell.
ac59aed8 1505
ac59aed8 1506\\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
b52b132f 1507\{, (, [, ', \", `
133693bc
KH
1508 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1509
1510If you generally program a shell different from your login shell you can
aafd074a 1511set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
133693bc
KH
1512indicate what shell it is use `sh-alias-alist' to translate.
1513
1514If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1515with your script for an edit-interpret-debug cycle."
aafd074a 1516 (make-local-variable 'sh-shell-file)
ac59aed8 1517 (make-local-variable 'sh-shell)
5ccaa359
SM
1518
1519 (set (make-local-variable 'skeleton-pair-default-alist)
1520 sh-skeleton-pair-default-alist)
1521 (set (make-local-variable 'skeleton-end-hook)
1522 (lambda () (or (eolp) (newline) (indent-relative))))
1523
1524 (set (make-local-variable 'paragraph-start) (concat page-delimiter "\\|$"))
1525 (set (make-local-variable 'paragraph-separate) paragraph-start)
1526 (set (make-local-variable 'comment-start) "# ")
1527 (set (make-local-variable 'comment-start-skip) "#+[\t ]*")
1528 (set (make-local-variable 'local-abbrev-table) sh-mode-abbrev-table)
1529 (set (make-local-variable 'comint-dynamic-complete-functions)
1530 sh-dynamic-complete-functions)
1531 ;; we can't look if previous line ended with `\'
1532 (set (make-local-variable 'comint-prompt-regexp) "^[ \t]*")
1533 (set (make-local-variable 'imenu-case-fold-search) nil)
1534 (set (make-local-variable 'font-lock-defaults)
1535 `((sh-font-lock-keywords
1536 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1537 nil nil
1538 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
5ccaa359
SM
1539 (font-lock-syntactic-face-function
1540 . sh-font-lock-syntactic-face-function)))
cf38dd42
SM
1541 (set (make-local-variable 'syntax-propertize-function)
1542 #'sh-syntax-propertize-function)
1543 (add-hook 'syntax-propertize-extend-region-functions
1544 #'syntax-propertize-multiline 'append 'local)
5ccaa359
SM
1545 (set (make-local-variable 'skeleton-pair-alist) '((?` _ ?`)))
1546 (set (make-local-variable 'skeleton-pair-filter-function) 'sh-quoted-p)
1547 (set (make-local-variable 'skeleton-further-elements)
1548 '((< '(- (min sh-indentation (current-column))))))
1549 (set (make-local-variable 'skeleton-filter-function) 'sh-feature)
1550 (set (make-local-variable 'skeleton-newline-indent-rigidly) t)
1551 (set (make-local-variable 'sh-indent-supported-here) nil)
b6ddf8d7
SM
1552 (set (make-local-variable 'defun-prompt-regexp)
1553 (concat "^\\(function[ \t]\\|[[:alnum:]]+[ \t]+()[ \t]+\\)"))
e3dce9ba
RS
1554 ;; Parse or insert magic number for exec, and set all variables depending
1555 ;; on the shell thus determined.
19cd88cc
TTN
1556 (sh-set-shell
1557 (cond ((save-excursion
1558 (goto-char (point-min))
1559 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1560 (match-string 2))
1561 ((not buffer-file-name)
1562 sh-shell-file)
1563 ;; Checks that use `buffer-file-name' follow.
1564 ((string-match "\\.m?spec\\'" buffer-file-name)
1565 "rpm")
1566 ((string-match "[.]sh\\>" buffer-file-name)
1567 "sh")
1568 ((string-match "[.]bash\\>" buffer-file-name)
1569 "bash")
1570 ((string-match "[.]ksh\\>" buffer-file-name)
1571 "ksh")
1572 ((string-match "[.]csh\\>" buffer-file-name)
1573 "csh")
68c2f86d
RS
1574 ((equal (file-name-nondirectory buffer-file-name) ".profile")
1575 "sh")
19cd88cc
TTN
1576 (t
1577 sh-shell-file))
791ffe1c 1578 nil nil))
aace6150 1579
133693bc 1580;;;###autoload
ac59aed8
RS
1581(defalias 'shell-script-mode 'sh-mode)
1582
1583
84bfbb44
KH
1584(defun sh-font-lock-keywords (&optional keywords)
1585 "Function to get simple fontification based on `sh-font-lock-keywords'.
1586This adds rules for comments and assignments."
5789bd83 1587 (sh-feature sh-font-lock-keywords-var
b946fbad
RS
1588 (when (stringp (sh-feature sh-assignment-regexp))
1589 (lambda (list)
1590 `((,(sh-feature sh-assignment-regexp)
1591 1 font-lock-variable-name-face)
1592 ,@keywords
5789bd83
RS
1593 ,@list
1594 ,@executable-font-lock-keywords)))))
84bfbb44
KH
1595
1596(defun sh-font-lock-keywords-1 (&optional builtins)
1597 "Function to get better fontification including keywords."
3e2dd647
SM
1598 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1599 (regexp-opt (sh-feature sh-leading-keywords) t)
1600 "[ \t]+\\)?"
1601 (regexp-opt (append (sh-feature sh-leading-keywords)
1602 (sh-feature sh-other-keywords))
1603 t))))
84bfbb44
KH
1604 (sh-font-lock-keywords
1605 `(,@(if builtins
3e2dd647
SM
1606 `((,(concat keywords "[ \t]+\\)?"
1607 (regexp-opt (sh-feature sh-builtins) t)
1608 "\\>")
84bfbb44 1609 (2 font-lock-keyword-face nil t)
f802bd02 1610 (6 font-lock-builtin-face))
5789bd83 1611 ,@(sh-feature sh-font-lock-keywords-var-2)))
84bfbb44
KH
1612 (,(concat keywords "\\)\\>")
1613 2 font-lock-keyword-face)
5789bd83 1614 ,@(sh-feature sh-font-lock-keywords-var-1)))))
84bfbb44
KH
1615
1616(defun sh-font-lock-keywords-2 ()
1617 "Function to get better fontification including keywords and builtins."
1618 (sh-font-lock-keywords-1 t))
1619
ac59aed8 1620
d92474ed
SM
1621(defvar sh-regexp-for-done nil
1622 "A buffer-local regexp to match opening keyword for done.")
1623
1624(defvar sh-kw-alist nil
1625 "A buffer-local, since it is shell-type dependent, list of keywords.")
1626
1627;; ( key-word first-on-this on-prev-line )
1628;; This is used to set `sh-kw-alist' which is a list of sublists each
1629;; having 3 elements:
1630;; a keyword
8db2b9fb
SM
1631;; a rule to check when the keyword appears on "this" line
1632;; a rule to check when the keyword appears on "the previous" line
d92474ed 1633;; The keyword is usually a string and is the first word on a line.
8db2b9fb
SM
1634;; If this keyword appears on the line whose indentation is to be
1635;; calculated, the rule in element 2 is called. If this returns
1636;; non-zero, the resulting point (which may be changed by the rule)
d92474ed
SM
1637;; is used as the default indentation.
1638;; If it returned false or the keyword was not found in the table,
1639;; then the keyword from the previous line is looked up and the rule
1640;; in element 3 is called. In this case, however,
8db2b9fb 1641;; `sh-get-indent-info' does not stop but may keep going and test
d92474ed 1642;; other keywords against rules in element 3. This is because the
8db2b9fb 1643;; preceding line could have, for example, an opening "if" and an
d92474ed
SM
1644;; opening "while" keyword and we need to add the indentation offsets
1645;; for both.
1646;;
1647(defconst sh-kw
6c5bcbc1
SM
1648 '((sh
1649 ("if" nil sh-handle-prev-if)
1650 ("elif" sh-handle-this-else sh-handle-prev-else)
1651 ("else" sh-handle-this-else sh-handle-prev-else)
1652 ("fi" sh-handle-this-fi sh-handle-prev-fi)
1653 ("then" sh-handle-this-then sh-handle-prev-then)
1654 ("(" nil sh-handle-prev-open)
1655 ("{" nil sh-handle-prev-open)
1656 ("[" nil sh-handle-prev-open)
1657 ("}" sh-handle-this-close nil)
1658 (")" sh-handle-this-close nil)
1659 ("]" sh-handle-this-close nil)
1660 ("case" nil sh-handle-prev-case)
1661 ("esac" sh-handle-this-esac sh-handle-prev-esac)
1662 (case-label nil sh-handle-after-case-label) ;; ???
1663 (";;" nil sh-handle-prev-case-alt-end) ;; ???
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)
2501 (if (looking-at "\\s-*;;")
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