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