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