* lisp/progmodes/sh-script.el (sh-smie-sh-rules): For { after &&, don't
[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 `"(" `"{" `"["))
9e248ebd
SM
1955 (when (smie-rule-hanging-p)
1956 (if (not (smie-rule-prev-p "&&" "||" "|"))
1957 (smie-rule-parent)
1958 (smie-backward-sexp 'halfexp)
1959 `(column . ,(smie-indent-virtual)))))
ff46c759
SM
1960 ;; FIXME: Maybe this handling of ;; should be made into
1961 ;; a smie-rule-terminator function that takes the substitute ";" as arg.
1962 (`(:before . ,(or `";;" `";&" `";;&"))
1963 (if (and (smie-rule-bolp) (looking-at ";;?&?[ \t]*\\(#\\|$\\)"))
1964 (cons 'column (smie-indent-keyword ";"))
1965 (smie-rule-separator kind)))
1966 (`(:after . ,(or `";;" `";&" `";;&"))
1967 (with-demoted-errors
1968 (smie-backward-sexp token)
1969 (cons 'column
1970 (if (or (smie-rule-bolp)
1971 (save-excursion
1972 (and (member (funcall smie-backward-token-function)
1973 '("in" ";;"))
1974 (smie-rule-bolp))))
1975 (current-column)
1976 (smie-indent-calculate)))))
e9638b49 1977 (`(:after . ,(or `"|" `"&&" `"||")) (if (smie-rule-parent-p token) nil 4))
71e3276b
SM
1978 ;; Attempt at backward compatibility with the old config variables.
1979 (`(:before . "fi") (sh-var-value 'sh-indent-for-fi))
1980 (`(:before . "done") (sh-var-value 'sh-indent-for-done))
1981 (`(:after . "else") (sh-var-value 'sh-indent-after-else))
1982 (`(:after . "if") (sh-var-value 'sh-indent-after-if))
1983 (`(:before . "then") (sh-var-value 'sh-indent-for-then))
1984 (`(:before . "do") (sh-var-value 'sh-indent-for-do))
1985 (`(:after . "do")
1986 (sh-var-value (if (smie-rule-hanging-p)
1987 'sh-indent-after-loop-construct 'sh-indent-after-do)))
1988 ;; sh-indent-after-done: aligned completely differently.
1989 (`(:after . "in") (sh-var-value 'sh-indent-for-case-label))
1990 ;; sh-indent-for-continuation: Line continuations are handled differently.
1991 (`(:after . ,(or `"(" `"{" `"[")) (sh-var-value 'sh-indent-after-open))
1992 ;; sh-indent-after-function: we don't handle it differently.
ff46c759
SM
1993 ))
1994
1995;; (defconst sh-smie-csh-grammar
1996;; (smie-prec2->grammar
1997;; (smie-bnf->prec2
c38e0c97 1998;; '((exp) ;A constant, or a $var, or a sequence of them...
ff46c759
SM
1999;; (elseifcmd (cmd)
2000;; (cmd "else" "else-if" exp "then" elseifcmd))
2001;; (cmd ("switch" branches "endsw")
2002;; ("if" exp)
2003;; ("if" exp "then" cmd "endif")
2004;; ("if" exp "then" cmd "else" cmd "endif")
2005;; ("if" exp "then" elseifcmd "endif")
2006;; ;; ("if" exp "then" cmd "else" cmd "endif")
2007;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd "endif")
2008;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2009;; ;; "else" cmd "endif")
2010;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2011;; ;; "else" "if" exp "then" cmd "endif")
2012;; ("while" cmd "end")
2013;; ("foreach" cmd "end")
2014;; (cmd "|" cmd) (cmd "|&" cmd)
2015;; (cmd "&&" cmd) (cmd "||" cmd)
2016;; (cmd ";" cmd) (cmd "&" cmd))
2017;; ;; This is a lie, but (combined with the corresponding disambiguation
2018;; ;; rule) it makes it more clear that `case' and `default' are the key
2019;; ;; separators and the `:' is a secondary tokens.
2020;; (branches (branches "case" branches)
2021;; (branches "default" branches)
2022;; (exp ":" branches)))
2023;; '((assoc "else" "then" "endif"))
2024;; '((assoc "case" "default") (nonassoc ":"))
2025;; '((assoc ";;" ";&" ";;&"))
2026;; '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2027
2028;;;; SMIE support for `rc'.
2029
2030(defconst sh-smie-rc-grammar
2031 (smie-prec2->grammar
2032 (smie-bnf->prec2
2033 '((exp) ;A constant, or a $var, or a sequence of them...
2034 (cmd (cmd "case" cmd)
2035 ("if" exp)
2036 ("switch" exp)
2037 ("for" exp) ("while" exp)
2038 (cmd "|" cmd) (cmd "|&" cmd)
2039 (cmd "&&" cmd) (cmd "||" cmd)
2040 (cmd ";" cmd) (cmd "&" cmd))
2041 (pattern (pattern "|" pattern))
2042 (branches (branches ";;" branches)
2043 (branches ";&" branches) (branches ";;&" branches) ;bash.
2044 (pattern "case-)" cmd)))
2045 '((assoc ";;" ";&" ";;&"))
2046 '((assoc "case") (assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2047
2048(defun sh-smie--rc-after-special-arg-p ()
2049 "Check if we're after the first arg of an if/while/for/... construct.
2050Returns the construct's token and moves point before it, if so."
2051 (forward-comment (- (point)))
2052 (when (looking-back ")\\|\\_<not" (- (point) 3))
2053 (ignore-errors
2054 (let ((forward-sexp-function nil))
2055 (forward-sexp -1)
2056 (car (member (funcall smie-backward-token-function)
2057 '("if" "for" "switch" "while")))))))
2058
2059(defun sh-smie--rc-newline-semi-p ()
2060 "Return non-nil if a newline should be treated as a semi-colon.
2061Point should be before the newline."
2062 (save-excursion
2063 (let ((tok (funcall smie-backward-token-function)))
2064 (if (or (when (equal tok "not") (forward-word 1) t)
2065 (and (zerop (length tok)) (eq (char-before) ?\))))
2066 (not (sh-smie--rc-after-special-arg-p))
2067 (sh-smie--newline-semi-p tok)))))
2068
2069(defun sh-smie-rc-forward-token ()
2070 ;; FIXME: Code duplication with sh-smie-sh-forward-token.
2071 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
2072 (save-excursion
2073 (skip-chars-backward " \t")
2074 (not (bolp))))
2075 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
2076 ;; Right before a here-doc.
2077 (let ((forward-sexp-function nil))
2078 (forward-sexp 1)
2079 ;; Pretend the here-document is a "newline representing a
2080 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2081 ";")
2082 (let ((semi (sh-smie--rc-newline-semi-p)))
2083 (forward-line 1)
e63ace37 2084 (if (or semi (eobp)) ";"
ff46c759
SM
2085 (sh-smie-rc-forward-token))))
2086 (forward-comment (point-max))
2087 (cond
2088 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-rc-forward-token))
2089 ;; ((looking-at sh-smie--rc-operators-re)
2090 ;; (goto-char (match-end 0))
2091 ;; (let ((tok (match-string-no-properties 0)))
2092 ;; (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
2093 ;; (looking-at "[ \t]*\\(?:#\\|$\\)"))
2094 ;; (forward-line 1))
2095 ;; tok))
2096 (t
2097 (let* ((pos (point))
2098 (tok (smie-default-forward-token)))
2099 (cond
2100 ;; ((equal tok ")") "case-)")
2101 ((and tok (string-match "\\`[a-z]" tok)
2102 (assoc tok smie-grammar)
2103 (not
2104 (save-excursion
2105 (goto-char pos)
dd070019 2106 (sh-smie--keyword-p))))
ff46c759
SM
2107 " word ")
2108 (t tok)))))))
2109
2110(defun sh-smie-rc-backward-token ()
2111 ;; FIXME: Code duplication with sh-smie-sh-backward-token.
dd070019 2112 (let ((bol (line-beginning-position)))
ff46c759
SM
2113 (forward-comment (- (point)))
2114 (cond
2115 ((and (bolp) (not (bobp))
2116 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
2117 (not (nth 3 (syntax-ppss))))
2118 ;; Right after a here-document.
2119 (let ((forward-sexp-function nil))
2120 (forward-sexp -1)
2121 ;; Pretend the here-document is a "newline representing a
2122 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2123 ";"))
2124 ((< (point) bol) ;We skipped over a newline.
2125 (cond
2126 ;; A continued line.
2127 ((and (eolp)
2128 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
2129 (line-beginning-position)))
2130 (forward-char -1)
2131 (funcall smie-backward-token-function))
2132 ((sh-smie--rc-newline-semi-p) ";")
2133 (t (funcall smie-backward-token-function))))
2134 ;; ((looking-back sh-smie--sh-operators-back-re
2135 ;; (line-beginning-position) 'greedy)
2136 ;; (goto-char (match-beginning 1))
2137 ;; (match-string-no-properties 1))
2138 (t
2139 (let ((tok (smie-default-backward-token)))
2140 (cond
2141 ;; ((equal tok ")") "case-)")
2142 ((and tok (string-match "\\`[a-z]" tok)
2143 (assoc tok smie-grammar)
dd070019 2144 (not (save-excursion (sh-smie--keyword-p))))
ff46c759
SM
2145 " word ")
2146 (t tok)))))))
2147
2148(defun sh-smie-rc-rules (kind token)
2149 (pcase (cons kind token)
2150 (`(:elem . basic) sh-indentation)
2151 ;; (`(:after . "case") (or sh-indentation smie-indent-basic))
71e3276b
SM
2152 (`(:after . ";")
2153 (if (smie-rule-parent-p "case")
2154 (smie-rule-parent (sh-var-value 'sh-indent-after-case))))
ff46c759
SM
2155 (`(:before . "{")
2156 (save-excursion
2157 (when (sh-smie--rc-after-special-arg-p)
2158 `(column . ,(current-column)))))
2159 (`(:before . ,(or `"(" `"{" `"["))
2160 (if (smie-rule-hanging-p) (smie-rule-parent)))
2161 ;; FIXME: SMIE parses "if (exp) cmd" as "(if ((exp) cmd))" so "cmd" is
2162 ;; treated as an arg to (exp) by default, which indents it all wrong.
2163 ;; To handle it right, we should extend smie-indent-exps so that the
2164 ;; preceding keyword can give special rules. Currently the only special
2165 ;; rule we have is the :list-intro hack, which we use here to align "cmd"
2166 ;; with "(exp)", which is rarely the right thing to do, but is better
2167 ;; than nothing.
2168 (`(:list-intro . ,(or `"for" `"if" `"while")) t)
71e3276b 2169 ;; sh-indent-after-switch: handled implicitly by the default { rule.
ff46c759
SM
2170 ))
2171
2172;;; End of SMIE code.
ac59aed8 2173
d92474ed
SM
2174(defvar sh-regexp-for-done nil
2175 "A buffer-local regexp to match opening keyword for done.")
2176
2177(defvar sh-kw-alist nil
2178 "A buffer-local, since it is shell-type dependent, list of keywords.")
2179
2180;; ( key-word first-on-this on-prev-line )
2181;; This is used to set `sh-kw-alist' which is a list of sublists each
2182;; having 3 elements:
2183;; a keyword
8db2b9fb
SM
2184;; a rule to check when the keyword appears on "this" line
2185;; a rule to check when the keyword appears on "the previous" line
d92474ed 2186;; The keyword is usually a string and is the first word on a line.
8db2b9fb
SM
2187;; If this keyword appears on the line whose indentation is to be
2188;; calculated, the rule in element 2 is called. If this returns
2189;; non-zero, the resulting point (which may be changed by the rule)
d92474ed
SM
2190;; is used as the default indentation.
2191;; If it returned false or the keyword was not found in the table,
2192;; then the keyword from the previous line is looked up and the rule
2193;; in element 3 is called. In this case, however,
8db2b9fb 2194;; `sh-get-indent-info' does not stop but may keep going and test
d92474ed 2195;; other keywords against rules in element 3. This is because the
8db2b9fb 2196;; preceding line could have, for example, an opening "if" and an
d92474ed
SM
2197;; opening "while" keyword and we need to add the indentation offsets
2198;; for both.
2199;;
2200(defconst sh-kw
6c5bcbc1
SM
2201 '((sh
2202 ("if" nil sh-handle-prev-if)
2203 ("elif" sh-handle-this-else sh-handle-prev-else)
2204 ("else" sh-handle-this-else sh-handle-prev-else)
2205 ("fi" sh-handle-this-fi sh-handle-prev-fi)
2206 ("then" sh-handle-this-then sh-handle-prev-then)
2207 ("(" nil sh-handle-prev-open)
2208 ("{" nil sh-handle-prev-open)
2209 ("[" nil sh-handle-prev-open)
2210 ("}" sh-handle-this-close nil)
2211 (")" sh-handle-this-close nil)
2212 ("]" sh-handle-this-close nil)
2213 ("case" nil sh-handle-prev-case)
2214 ("esac" sh-handle-this-esac sh-handle-prev-esac)
2215 (case-label nil sh-handle-after-case-label) ;; ???
2216 (";;" nil sh-handle-prev-case-alt-end) ;; ???
7cb76591
SM
2217 (";;&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
2218 (";&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
6c5bcbc1
SM
2219 ("done" sh-handle-this-done sh-handle-prev-done)
2220 ("do" sh-handle-this-do sh-handle-prev-do))
d92474ed
SM
2221
2222 ;; Note: we don't need specific stuff for bash and zsh shells;
2223 ;; the regexp `sh-regexp-for-done' handles the extra keywords
2224 ;; these shells use.
2225 (rc
6c5bcbc1
SM
2226 ("{" nil sh-handle-prev-open)
2227 ("}" sh-handle-this-close nil)
2228 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
d92474ed
SM
2229
2230
5789bd83 2231
616db04b 2232(defun sh-set-shell (shell &optional no-query-flag insert-flag)
133693bc 2233 "Set this buffer's shell to SHELL (a string).
57270c90
RS
2234When used interactively, insert the proper starting #!-line,
2235and make the visited file executable via `executable-set-magic',
2236perhaps querying depending on the value of `executable-query'.
2237
2238When this function is called noninteractively, INSERT-FLAG (the third
2239argument) controls whether to insert a #!-line and think about making
2240the visited file executable, and NO-QUERY-FLAG (the second argument)
2241controls whether to query about making the visited file executable.
2242
133693bc 2243Calls the value of `sh-set-shell-hook' if set."
1af4c220
GM
2244 (interactive (list (completing-read
2245 (format "Shell \(default %s\): "
2246 sh-shell-file)
2247 ;; This used to use interpreter-mode-alist, but that is
2248 ;; no longer appropriate now that uses regexps.
2249 ;; Maybe there could be a separate variable that lists
2250 ;; the shells, used here and to construct i-mode-alist.
2251 ;; But the following is probably good enough:
2252 (append (mapcar (lambda (e) (symbol-name (car e)))
2253 sh-ancestor-alist)
2254 '("csh" "rc" "sh"))
2255 nil nil nil nil sh-shell-file)
616db04b
RS
2256 (eq executable-query 'function)
2257 t))
842cc0e6 2258 (if (string-match "\\.exe\\'" shell)
c8b88e9f 2259 (setq shell (substring shell 0 (match-beginning 0))))
133693bc
KH
2260 (setq sh-shell (intern (file-name-nondirectory shell))
2261 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
616db04b 2262 sh-shell))
e3dce9ba
RS
2263 (if insert-flag
2264 (setq sh-shell-file
2265 (executable-set-magic shell (sh-feature sh-shell-arg)
2266 no-query-flag insert-flag)))
5ccaa359 2267 (setq mode-line-process (format "[%s]" sh-shell))
92eadba5
CY
2268 (setq-local sh-shell-variables nil)
2269 (setq-local sh-shell-variables-initialized nil)
2270 (setq-local imenu-generic-expression
2271 (sh-feature sh-imenu-generic-expression))
6b61353c 2272 (let ((tem (sh-feature sh-mode-syntax-table-input)))
5ccaa359 2273 (when tem
92eadba5
CY
2274 (setq-local sh-mode-syntax-table
2275 (apply 'sh-mode-syntax-table tem))
5ccaa359 2276 (set-syntax-table sh-mode-syntax-table)))
6c5bcbc1
SM
2277 (dolist (var (sh-feature sh-variables))
2278 (sh-remember-variable var))
92eadba5
CY
2279 (if (setq-local sh-indent-supported-here
2280 (sh-feature sh-indent-supported))
f964dfcb
GM
2281 (progn
2282 (message "Setting up indent for shell type %s" sh-shell)
dd070019
SM
2283 (let ((mksym (lambda (name)
2284 (intern (format "sh-smie-%s-%s"
2285 sh-indent-supported-here name)))))
500dce5f
SM
2286 (add-function :around (local 'smie--hanging-eolp-function)
2287 (lambda (orig)
2288 (if (looking-at "[ \t]*\\\\\n")
2289 (goto-char (match-end 0))
2290 (funcall orig))))
dd070019
SM
2291 (smie-setup (symbol-value (funcall mksym "grammar"))
2292 (funcall mksym "rules")
2293 :forward-token (funcall mksym "forward-token")
2294 :backward-token (funcall mksym "backward-token")))
2295 (unless sh-use-smie
92eadba5
CY
2296 (setq-local parse-sexp-lookup-properties t)
2297 (setq-local sh-kw-alist (sh-feature sh-kw))
ff46c759
SM
2298 (let ((regexp (sh-feature sh-kws-for-done)))
2299 (if regexp
92eadba5
CY
2300 (setq-local sh-regexp-for-done
2301 (sh-mkword-regexpr (regexp-opt regexp t)))))
ff46c759
SM
2302 (message "setting up indent stuff")
2303 ;; sh-mode has already made indent-line-function local
2304 ;; but do it in case this is called before that.
92eadba5 2305 (setq-local indent-line-function 'sh-indent-line))
f964dfcb
GM
2306 (if sh-make-vars-local
2307 (sh-make-vars-local))
2308 (message "Indentation setup for shell type %s" sh-shell))
2309 (message "No indentation for this shell type.")
2310 (setq indent-line-function 'sh-basic-indent-line))
5789bd83
RS
2311 (when font-lock-mode
2312 (setq font-lock-set-defaults nil)
2313 (font-lock-set-defaults)
2314 (font-lock-fontify-buffer))
6e50e983 2315 (setq sh-shell-process nil)
133693bc
KH
2316 (run-hooks 'sh-set-shell-hook))
2317
2318
6b61353c 2319(defun sh-feature (alist &optional function)
133693bc
KH
2320 "Index ALIST by the current shell.
2321If ALIST isn't a list where every element is a cons, it is returned as is.
2322Else indexing follows an inheritance logic which works in two ways:
2323
2324 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
2325 the alist contains no value for the current shell.
1c64011b 2326 The ultimate default is always `sh'.
133693bc 2327
6b61353c
KH
2328 - If the value thus looked up is a list starting with `sh-append',
2329 we call the function `sh-append' with the rest of the list as
2330 arguments, and use the value. However, the next element of the
2331 list is not used as-is; instead, we look it up recursively
2332 in ALIST to allow the function called to define the value for
2333 one shell to be derived from another shell.
133693bc
KH
2334 The value thus determined is physically replaced into the alist.
2335
5789bd83
RS
2336If FUNCTION is non-nil, it is called with one argument,
2337the value thus obtained, and the result is used instead."
6b61353c 2338 (or (if (consp alist)
5789bd83 2339 ;; Check for something that isn't a valid alist.
6b61353c 2340 (let ((l alist))
133693bc
KH
2341 (while (and l (consp (car l)))
2342 (setq l (cdr l)))
6b61353c 2343 (if l alist)))
5789bd83
RS
2344
2345 (let ((orig-sh-shell sh-shell))
2346 (let ((sh-shell sh-shell)
2347 elt val)
2348 (while (and sh-shell
2349 (not (setq elt (assq sh-shell alist))))
2350 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
2351 ;; If the shell is not known, treat it as sh.
2352 (unless elt
2353 (setq elt (assq 'sh alist)))
2354 (setq val (cdr elt))
2355 (if (and (consp val)
2356 (memq (car val) '(sh-append sh-modify)))
2357 (setq val
2358 (apply (car val)
2359 ;; Refer to the value for a different shell,
2360 ;; as a kind of inheritance.
2361 (let ((sh-shell (car (cdr val))))
2362 (sh-feature alist))
2363 (cddr val))))
2364 (if function
2365 (setq sh-shell orig-sh-shell
2366 val (funcall function val)))
2367 val))))
133693bc
KH
2368
2369
2370
3e2dd647
SM
2371;; I commented this out because nobody calls it -- rms.
2372;;(defun sh-abbrevs (ancestor &rest list)
d136f184 2373;; "If it isn't, define the current shell as abbrev table and fill that.
3e2dd647
SM
2374;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
2375;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
2376;;according to the remaining arguments NAMEi EXPANSIONi ...
2377;;EXPANSION may be either a string or a skeleton command."
2378;; (or (if (boundp sh-shell)
2379;; (symbol-value sh-shell))
2380;; (progn
2381;; (if (listp ancestor)
2382;; (nconc list ancestor))
2383;; (define-abbrev-table sh-shell ())
2384;; (if (vectorp ancestor)
2385;; (mapatoms (lambda (atom)
2386;; (or (eq atom 0)
2387;; (define-abbrev (symbol-value sh-shell)
2388;; (symbol-name atom)
2389;; (symbol-value atom)
2390;; (symbol-function atom))))
2391;; ancestor))
2392;; (while list
2393;; (define-abbrev (symbol-value sh-shell)
2394;; (car list)
2395;; (if (stringp (car (cdr list)))
2396;; (car (cdr list))
2397;; "")
2398;; (if (symbolp (car (cdr list)))
2399;; (car (cdr list))))
2400;; (setq list (cdr (cdr list)))))
2401;; (symbol-value sh-shell)))
133693bc
KH
2402
2403
133693bc
KH
2404(defun sh-append (ancestor &rest list)
2405 "Return list composed of first argument (a list) physically appended to rest."
2406 (nconc list ancestor))
2407
2408
2409(defun sh-modify (skeleton &rest list)
2410 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
2411 (setq skeleton (copy-sequence skeleton))
2412 (while list
2413 (setcar (or (nthcdr (car list) skeleton)
2414 (error "Index %d out of bounds" (car list)))
2415 (car (cdr list)))
2416 (setq list (nthcdr 2 list)))
2417 skeleton)
ac59aed8
RS
2418
2419
f964dfcb 2420(defun sh-basic-indent-line ()
54c87e27
RS
2421 "Indent a line for Sh mode (shell script mode).
2422Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
133693bc 2423Lines containing only comments are considered empty."
ac59aed8
RS
2424 (interactive)
2425 (let ((previous (save-excursion
54c87e27
RS
2426 (while (and (progn (beginning-of-line)
2427 (not (bobp)))
b46c06de
RS
2428 (progn
2429 (forward-line -1)
2430 (back-to-indentation)
2431 (or (eolp)
2432 (eq (following-char) ?#)))))
133693bc
KH
2433 (current-column)))
2434 current)
ac59aed8
RS
2435 (save-excursion
2436 (indent-to (if (eq this-command 'newline-and-indent)
2437 previous
2438 (if (< (current-column)
133693bc
KH
2439 (setq current (progn (back-to-indentation)
2440 (current-column))))
ac59aed8 2441 (if (eolp) previous 0)
133693bc
KH
2442 (delete-region (point)
2443 (progn (beginning-of-line) (point)))
ac59aed8 2444 (if (eolp)
133693bc
KH
2445 (max previous (* (1+ (/ current sh-indentation))
2446 sh-indentation))
2447 (* (1+ (/ current sh-indentation)) sh-indentation))))))
2448 (if (< (current-column) (current-indentation))
2449 (skip-chars-forward " \t"))))
2450
2451
2452(defun sh-execute-region (start end &optional flag)
2453 "Pass optional header and region to a subshell for noninteractive execution.
2454The working directory is that of the buffer, and only environment variables
2455are already set which is why you can mark a header within the script.
2456
2457With a positive prefix ARG, instead of sending region, define header from
2458beginning of buffer to point. With a negative prefix ARG, instead of sending
2459region, clear header."
2460 (interactive "r\nP")
2461 (if flag
2462 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
2463 (point-marker)))
2464 (if sh-header-marker
2465 (save-excursion
2466 (let (buffer-undo-list)
2467 (goto-char sh-header-marker)
2468 (append-to-buffer (current-buffer) start end)
2469 (shell-command-on-region (point-min)
2470 (setq end (+ sh-header-marker
2471 (- end start)))
aafd074a 2472 sh-shell-file)
133693bc 2473 (delete-region sh-header-marker end)))
aafd074a 2474 (shell-command-on-region start end (concat sh-shell-file " -")))))
ac59aed8
RS
2475
2476
2477(defun sh-remember-variable (var)
2478 "Make VARIABLE available for future completing reads in this buffer."
2479 (or (< (length var) sh-remember-variable-min)
133693bc 2480 (getenv var)
5a989d6e 2481 (assoc var sh-shell-variables)
6c5bcbc1 2482 (push (cons var var) sh-shell-variables))
ac59aed8
RS
2483 var)
2484
2485
ac59aed8
RS
2486
2487(defun sh-quoted-p ()
2488 "Is point preceded by an odd number of backslashes?"
133693bc 2489 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
ac59aed8 2490\f
f964dfcb 2491;; Indentation stuff.
f964dfcb 2492(defun sh-must-support-indent ()
fb7ada5f 2493 "Signal an error if the shell type for this buffer is not supported.
8db2b9fb 2494Also, the buffer must be in Shell-script mode."
f964dfcb 2495 (unless sh-indent-supported-here
4aa3ba0a 2496 (error "This buffer's shell does not support indentation through Emacs")))
f964dfcb
GM
2497
2498(defun sh-make-vars-local ()
2499 "Make the indentation variables local to this buffer.
2500Normally they already are local. This command is provided in case
2501variable `sh-make-vars-local' has been set to nil.
2502
8db2b9fb 2503To revert all these variables to the global values, use
f964dfcb
GM
2504command `sh-reset-indent-vars-to-global-values'."
2505 (interactive)
f24a26a5 2506 (mapc 'make-local-variable sh-var-list)
3307f085 2507 (message "Indentation variables are now local."))
f964dfcb
GM
2508
2509(defun sh-reset-indent-vars-to-global-values ()
8db2b9fb
SM
2510 "Reset local indentation variables to the global values.
2511Then, if variable `sh-make-vars-local' is non-nil, make them local."
f964dfcb 2512 (interactive)
f24a26a5 2513 (mapc 'kill-local-variable sh-var-list)
f964dfcb
GM
2514 (if sh-make-vars-local
2515 (mapcar 'make-local-variable sh-var-list)))
2516
2517
f964dfcb
GM
2518;; Theoretically these are only needed in shell and derived modes.
2519;; However, the routines which use them are only called in those modes.
2520(defconst sh-special-keywords "then\\|do")
2521
f964dfcb
GM
2522(defun sh-help-string-for-variable (var)
2523 "Construct a string for `sh-read-variable' when changing variable VAR ."
2524 (let ((msg (documentation-property var 'variable-documentation))
2525 (msg2 ""))
6c5bcbc1 2526 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
f964dfcb
GM
2527 (setq msg2
2528 (format "\n
8db2b9fb
SM
2529You can enter a number (positive to increase indentation,
2530negative to decrease indentation, zero for no change to indentation).
f964dfcb 2531
8db2b9fb 2532Or, you can enter one of the following symbols which are relative to
f964dfcb
GM
2533the value of variable `sh-basic-offset'
2534which in this buffer is currently %s.
2535
2536\t%s."
2537 sh-basic-offset
3e2dd647
SM
2538 (mapconcat (lambda (x)
2539 (nth (1- (length x)) x))
2540 sh-symbol-list "\n\t"))))
f964dfcb
GM
2541 (concat
2542 ;; The following shows the global not the local value!
2543 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
2544 msg msg2)))
2545
2546(defun sh-read-variable (var)
2547 "Read a new value for indentation variable VAR."
f964dfcb
GM
2548 (let ((minibuffer-help-form `(sh-help-string-for-variable
2549 (quote ,var)))
2550 val)
2551 (setq val (read-from-minibuffer
6c5bcbc1
SM
2552 (format "New value for %s (press %s for help): "
2553 var (single-key-description help-char))
2554 (format "%s" (symbol-value var))
2555 nil t))
f964dfcb
GM
2556 val))
2557
2558
2559
2560(defun sh-in-comment-or-string (start)
2561 "Return non-nil if START is in a comment or string."
2562 (save-excursion
3e2dd647
SM
2563 (let ((state (syntax-ppss start)))
2564 (or (nth 3 state) (nth 4 state)))))
f964dfcb
GM
2565
2566(defun sh-goto-matching-if ()
2567 "Go to the matching if for a fi.
2568This handles nested if..fi pairs."
2569 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
2570 (if found
2571 (goto-char found))))
2572
2573
2574;; Functions named sh-handle-this-XXX are called when the keyword on the
2575;; line whose indentation is being handled contain XXX;
8db2b9fb 2576;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
f964dfcb
GM
2577
2578(defun sh-handle-prev-if ()
2579 (list '(+ sh-indent-after-if)))
2580
2581(defun sh-handle-this-else ()
2582 (if (sh-goto-matching-if)
2583 ;; (list "aligned to if")
2584 (list "aligned to if" '(+ sh-indent-for-else))
2585 nil
2586 ))
2587
2588(defun sh-handle-prev-else ()
2589 (if (sh-goto-matching-if)
2590 (list '(+ sh-indent-after-if))
2591 ))
2592
2593(defun sh-handle-this-fi ()
2594 (if (sh-goto-matching-if)
2595 (list "aligned to if" '(+ sh-indent-for-fi))
2596 nil
2597 ))
2598
2599(defun sh-handle-prev-fi ()
2600 ;; Why do we have this rule? Because we must go back to the if
2601 ;; to get its indent. We may continue back from there.
2602 ;; We return nil because we don't have anything to add to result,
2603 ;; the side affect of setting align-point is all that matters.
2604 ;; we could return a comment (a string) but I can't think of a good one...
2605 (sh-goto-matching-if)
2606 nil)
2607
2608(defun sh-handle-this-then ()
2609 (let ((p (sh-goto-matching-if)))
2610 (if p
2611 (list '(+ sh-indent-for-then))
2612 )))
2613
2614(defun sh-handle-prev-then ()
2615 (let ((p (sh-goto-matching-if)))
2616 (if p
2617 (list '(+ sh-indent-after-if))
2618 )))
2619
2620(defun sh-handle-prev-open ()
2621 (save-excursion
2622 (let ((x (sh-prev-stmt)))
2623 (if (and x
2624 (progn
2625 (goto-char x)
2626 (or
2627 (looking-at "function\\b")
2628 (looking-at "\\s-*\\S-+\\s-*()")
2629 )))
2630 (list '(+ sh-indent-after-function))
2631 (list '(+ sh-indent-after-open)))
2632 )))
2633
2634(defun sh-handle-this-close ()
2635 (forward-char 1) ;; move over ")"
6c5bcbc1
SM
2636 (if (sh-safe-forward-sexp -1)
2637 (list "aligned to opening paren")))
f964dfcb
GM
2638
2639(defun sh-goto-matching-case ()
2640 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
6c5bcbc1 2641 (if found (goto-char found))))
f964dfcb
GM
2642
2643(defun sh-handle-prev-case ()
2644 ;; This is typically called when point is on same line as a case
2645 ;; we shouldn't -- and can't find prev-case
6c5bcbc1 2646 (if (looking-at ".*\\<case\\>")
f964dfcb 2647 (list '(+ sh-indent-for-case-label))
6c5bcbc1 2648 (error "We don't seem to be on a line with a case"))) ;; debug
f964dfcb
GM
2649
2650(defun sh-handle-this-esac ()
6c5bcbc1
SM
2651 (if (sh-goto-matching-case)
2652 (list "aligned to matching case")))
f964dfcb
GM
2653
2654(defun sh-handle-prev-esac ()
6c5bcbc1
SM
2655 (if (sh-goto-matching-case)
2656 (list "matching case")))
f964dfcb
GM
2657
2658(defun sh-handle-after-case-label ()
6c5bcbc1
SM
2659 (if (sh-goto-matching-case)
2660 (list '(+ sh-indent-for-case-alt))))
f964dfcb
GM
2661
2662(defun sh-handle-prev-case-alt-end ()
6c5bcbc1
SM
2663 (if (sh-goto-matching-case)
2664 (list '(+ sh-indent-for-case-label))))
f964dfcb 2665
6c5bcbc1 2666(defun sh-safe-forward-sexp (&optional arg)
f964dfcb 2667 "Try and do a `forward-sexp', but do not error.
8db2b9fb 2668Return new point if successful, nil if an error occurred."
f964dfcb
GM
2669 (condition-case nil
2670 (progn
6c5bcbc1
SM
2671 (forward-sexp (or arg 1))
2672 (point)) ;; return point if successful
f964dfcb
GM
2673 (error
2674 (sh-debug "oops!(1) %d" (point))
6c5bcbc1 2675 nil))) ;; return nil if fail
f964dfcb
GM
2676
2677(defun sh-goto-match-for-done ()
2678 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2679 (if found
2680 (goto-char found))))
2681
2682(defun sh-handle-this-done ()
2683 (if (sh-goto-match-for-done)
6c5bcbc1 2684 (list "aligned to do stmt" '(+ sh-indent-for-done))))
f964dfcb
GM
2685
2686(defun sh-handle-prev-done ()
2687 (if (sh-goto-match-for-done)
6c5bcbc1 2688 (list "previous done")))
f964dfcb
GM
2689
2690(defun sh-handle-this-do ()
6c5bcbc1
SM
2691 (if (sh-goto-match-for-done)
2692 (list '(+ sh-indent-for-do))))
f964dfcb
GM
2693
2694(defun sh-handle-prev-do ()
6c5bcbc1
SM
2695 (cond
2696 ((save-restriction
9b026d9f 2697 (narrow-to-region (point) (line-beginning-position))
6c5bcbc1
SM
2698 (sh-goto-match-for-done))
2699 (sh-debug "match for done found on THIS line")
2700 (list '(+ sh-indent-after-loop-construct)))
2701 ((sh-goto-match-for-done)
2702 (sh-debug "match for done found on PREV line")
2703 (list '(+ sh-indent-after-do)))
2704 (t
2705 (message "match for done NOT found")
2706 nil)))
f964dfcb
GM
2707
2708;; for rc:
2709(defun sh-find-prev-switch ()
2710 "Find the line for the switch keyword matching this line's case keyword."
8db2b9fb 2711 (re-search-backward "\\<switch\\>" nil t))
f964dfcb
GM
2712
2713(defun sh-handle-this-rc-case ()
2714 (if (sh-find-prev-switch)
2715 (list '(+ sh-indent-after-switch))
6c5bcbc1 2716 ;; (list '(+ sh-indent-for-case-label))
f964dfcb
GM
2717 nil))
2718
2719(defun sh-handle-prev-rc-case ()
2720 (list '(+ sh-indent-after-case)))
2721
2722(defun sh-check-rule (n thing)
2723 (let ((rule (nth n (assoc thing sh-kw-alist)))
2724 (val nil))
2725 (if rule
2726 (progn
2727 (setq val (funcall rule))
2728 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2729 n thing (point) rule val)))
2730 val))
2731
2732
2733(defun sh-get-indent-info ()
2734 "Return indent-info for this line.
2735This is a list. nil means the line is to be left as is.
2736Otherwise it contains one or more of the following sublists:
8db2b9fb 2737\(t NUMBER\) NUMBER is the base location in the buffer that indentation is
f964dfcb
GM
2738 relative to. If present, this is always the first of the
2739 sublists. The indentation of the line in question is
8db2b9fb 2740 derived from the indentation of this point, possibly
f964dfcb
GM
2741 modified by subsequent sublists.
2742\(+ VAR\)
2743\(- VAR\) Get the value of variable VAR and add to or subtract from
2744 the indentation calculated so far.
2745\(= VAR\) Get the value of variable VAR and *replace* the
8db2b9fb 2746 indentation with its value. This only occurs for
f964dfcb
GM
2747 special variables such as `sh-indent-comment'.
2748STRING This is ignored for the purposes of calculating
8db2b9fb 2749 indentation, it is printed in certain cases to help show
f964dfcb
GM
2750 what the indentation is based on."
2751 ;; See comments before `sh-kw'.
2752 (save-excursion
485219e0 2753 (let ((have-result nil)
f964dfcb 2754 this-kw
485219e0 2755 val
f964dfcb 2756 (result nil)
f964dfcb
GM
2757 (align-point nil)
2758 prev-line-end x)
2759 (beginning-of-line)
2760 ;; Note: setting result to t means we are done and will return nil.
6c5bcbc1 2761 ;;(This function never returns just t.)
f964dfcb 2762 (cond
88a36e60 2763 ((or (nth 3 (syntax-ppss (point)))
b36581fb 2764 (eq (get-text-property (point) 'face) sh-heredoc-face))
88a36e60 2765 ;; String continuation -- don't indent
f964dfcb
GM
2766 (setq result t)
2767 (setq have-result t))
2768 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2769 (if (bobp)
6c5bcbc1 2770 (setq result t) ;; return nil if 1st line!
f964dfcb
GM
2771 (setq result (list '(= sh-indent-comment)))
2772 ;; we still need to get previous line in case
8db2b9fb 2773 ;; sh-indent-comment is t (indent as normal)
f964dfcb
GM
2774 (setq align-point (sh-prev-line nil))
2775 (setq have-result nil)
2776 ))
6c5bcbc1 2777 ) ;; cond
035107fa 2778
f964dfcb
GM
2779 (unless have-result
2780 ;; Continuation lines are handled specially
2781 (if (sh-this-is-a-continuation)
2782 (progn
090475f3
SM
2783 (setq result
2784 (if (save-excursion
2785 (beginning-of-line)
2786 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2787 ;; By convention, if the continuation \ is not
2788 ;; preceded by a SPC or a TAB it means that the line
2789 ;; is cut at a place where spaces cannot be freely
2790 ;; added/removed. I.e. do not indent the line.
2791 (list '(= nil))
2792 ;; We assume the line being continued is already
2793 ;; properly indented...
2794 ;; (setq prev-line-end (sh-prev-line))
2795 (setq align-point (sh-prev-line nil))
2796 (list '(+ sh-indent-for-continuation))))
f964dfcb
GM
2797 (setq have-result t))
2798 (beginning-of-line)
2799 (skip-chars-forward " \t")
2800 (setq this-kw (sh-get-kw)))
2801
2802 ;; Handle "this" keyword: first word on the line we're
2803 ;; calculating indentation info for.
2804 (if this-kw
2805 (if (setq val (sh-check-rule 1 this-kw))
2806 (progn
2807 (setq align-point (point))
2808 (sh-debug
2809 "this - setting align-point to %d" align-point)
2810 (setq result (append result val))
2811 (setq have-result t)
2812 ;; set prev-line to continue processing remainder
8db2b9fb 2813 ;; of this line as a previous line
f964dfcb
GM
2814 (setq prev-line-end (point))
2815 ))))
2816
2817 (unless have-result
2818 (setq prev-line-end (sh-prev-line 'end)))
2819
2820 (if prev-line-end
2821 (save-excursion
2822 ;; We start off at beginning of this line.
2823 ;; Scan previous statements while this is <=
2824 ;; start of previous line.
f964dfcb
GM
2825 (goto-char prev-line-end)
2826 (setq x t)
2827 (while (and x (setq x (sh-prev-thing)))
2828 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2829 (cond
2830 ((and (equal x ")")
2831 (equal (get-text-property (1- (point)) 'syntax-table)
34939e2c 2832 sh-st-punc))
f964dfcb
GM
2833 (sh-debug "Case label) here")
2834 (setq x 'case-label)
2835 (if (setq val (sh-check-rule 2 x))
2836 (progn
2837 (setq result (append result val))
2838 (setq align-point (point))))
6b61353c
KH
2839 (or (bobp)
2840 (forward-char -1))
4f3a3368 2841 ;; FIXME: This charset looks too much like a regexp. --Stef
f964dfcb
GM
2842 (skip-chars-forward "[a-z0-9]*?")
2843 )
2844 ((string-match "[])}]" x)
6c5bcbc1 2845 (setq x (sh-safe-forward-sexp -1))
f964dfcb
GM
2846 (if x
2847 (progn
2848 (setq align-point (point))
2849 (setq result (append result
2850 (list "aligned to opening paren")))
2851 )))
2852 ((string-match "[[({]" x)
2853 (sh-debug "Checking special thing: %s" x)
2854 (if (setq val (sh-check-rule 2 x))
2855 (setq result (append result val)))
2856 (forward-char -1)
2857 (setq align-point (point)))
2858 ((string-match "[\"'`]" x)
2859 (sh-debug "Skipping back for %s" x)
2860 ;; this was oops-2
6c5bcbc1 2861 (setq x (sh-safe-forward-sexp -1)))
f964dfcb
GM
2862 ((stringp x)
2863 (sh-debug "Checking string %s at %s" x (point))
2864 (if (setq val (sh-check-rule 2 x))
2865 ;; (or (eq t (car val))
2866 ;; (eq t (car (car val))))
2867 (setq result (append result val)))
2868 ;; not sure about this test Wed Jan 27 23:48:35 1999
2869 (setq align-point (point))
2870 (unless (bolp)
2871 (forward-char -1)))
2872 (t
2873 (error "Don't know what to do with %s" x))
2874 )
6c5bcbc1 2875 ) ;; while
f964dfcb
GM
2876 (sh-debug "result is %s" result)
2877 )
2878 (sh-debug "No prev line!")
2879 (sh-debug "result: %s align-point: %s" result align-point)
2880 )
035107fa 2881
f964dfcb
GM
2882 (if align-point
2883 ;; was: (setq result (append result (list (list t align-point))))
2884 (setq result (append (list (list t align-point)) result))
2885 )
2886 (sh-debug "result is now: %s" result)
035107fa 2887
f964dfcb 2888 (or result
090475f3
SM
2889 (setq result (list (if prev-line-end
2890 (list t prev-line-end)
2891 (list '= 'sh-first-lines-indent)))))
035107fa 2892
f964dfcb
GM
2893 (if (eq result t)
2894 (setq result nil))
2895 (sh-debug "result is: %s" result)
2896 result
6c5bcbc1 2897 ) ;; let
f964dfcb
GM
2898 ))
2899
2900
2901(defun sh-get-indent-var-for-line (&optional info)
2902 "Return the variable controlling indentation for this line.
2903If there is not [just] one such variable, return a string
2904indicating the problem.
2905If INFO is supplied it is used, else it is calculated."
2906 (let ((var nil)
2907 (result nil)
2908 (reason nil)
2909 sym elt)
2910 (or info
2911 (setq info (sh-get-indent-info)))
2912 (if (null info)
2913 (setq result "this line to be left as is")
2914 (while (and info (null result))
2915 (setq elt (car info))
2916 (cond
2917 ((stringp elt)
2918 (setq reason elt)
2919 )
2920 ((not (listp elt))
2921 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2922 ;; so it is a list
2923 ((eq t (car elt))
6c5bcbc1 2924 ) ;; nothing
f964dfcb
GM
2925 ((symbolp (setq sym (nth 1 elt)))
2926 ;; A bit of a kludge - when we see the sh-indent-comment
2927 ;; ignore other variables. Otherwise it is tricky to
2928 ;; "learn" the comment indentation.
2929 (if (eq var 'sh-indent-comment)
2930 (setq result var)
2931 (if var
2932 (setq result
2933 "this line is controlled by more than 1 variable.")
2934 (setq var sym))))
2935 (t
2936 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2937 (setq info (cdr info))
2938 ))
2939 (or result
2940 (setq result var))
2941 (or result
2942 (setq result reason))
2943 (if (null result)
2944 ;; e.g. just had (t POS)
2945 (setq result "line has default indentation"))
2946 result))
2947
2948
2949
2950;; Finding the previous line isn't trivial.
2951;; We must *always* go back one more and see if that is a continuation
8db2b9fb 2952;; line -- it is the PREVIOUS line which is continued, not the one
f964dfcb
GM
2953;; we are going to!
2954;; Also, we want to treat a whole "here document" as one big line,
2955;; because we may want to a align to the beginning of it.
2956;;
2957;; What we do:
6c5bcbc1 2958;; - go back to previous non-empty line
8db2b9fb 2959;; - if this is in a here-document, go to the beginning of it
6c5bcbc1 2960;; - while previous line is continued, go back one line
f964dfcb
GM
2961(defun sh-prev-line (&optional end)
2962 "Back to end of previous non-comment non-empty line.
8db2b9fb 2963Go to beginning of logical line unless END is non-nil, in which case
f964dfcb 2964we go to the end of the previous line and do not check for continuations."
6c5bcbc1
SM
2965 (save-excursion
2966 (beginning-of-line)
2967 (forward-comment (- (point-max)))
2968 (unless end (beginning-of-line))
2969 (when (and (not (bobp))
34939e2c 2970 (equal (get-text-property (1- (point)) 'face)
b36581fb 2971 sh-heredoc-face))
34939e2c 2972 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
6c5bcbc1
SM
2973 (when p1
2974 (goto-char p1)
34939e2c
SM
2975 (if end
2976 (end-of-line)
2977 (beginning-of-line)))))
6c5bcbc1
SM
2978 (unless end
2979 ;; we must check previous lines to see if they are continuation lines
2980 ;; if so, we must return position of first of them
2981 (while (and (sh-this-is-a-continuation)
2982 (>= 0 (forward-line -1))))
f964dfcb 2983 (beginning-of-line)
6c5bcbc1
SM
2984 (skip-chars-forward " \t"))
2985 (point)))
f964dfcb
GM
2986
2987
2988(defun sh-prev-stmt ()
2989 "Return the address of the previous stmt or nil."
2990 ;; This is used when we are trying to find a matching keyword.
8db2b9fb 2991 ;; Searching backward for the keyword would certainly be quicker, but
f964dfcb
GM
2992 ;; it is hard to remove "false matches" -- such as if the keyword
2993 ;; appears in a string or quote. This way is slower, but (I think) safer.
2994 (interactive)
2995 (save-excursion
2996 (let ((going t)
2997 (start (point))
2998 (found nil)
2999 (prev nil))
3000 (skip-chars-backward " \t;|&({[")
3001 (while (and (not found)
3002 (not (bobp))
3003 going)
8db2b9fb 3004 ;; Do a backward-sexp if possible, else backup bit by bit...
6c5bcbc1 3005 (if (sh-safe-forward-sexp -1)
f964dfcb
GM
3006 (progn
3007 (if (looking-at sh-special-keywords)
3008 (progn
3009 (setq found prev))
3010 (setq prev (point))
3011 ))
3012 ;; backward-sexp failed
3013 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
3014 (forward-char -1))
3015 (if (bolp)
3016 (let ((back (sh-prev-line nil)))
3017 (if back
3018 (goto-char back)
3019 (setq going nil)))))
3020 (unless found
3021 (skip-chars-backward " \t")
3022 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
3023 (eq (char-before) ?\;)
3024 (looking-at "\\s-*[|&]"))
3025 (setq found (point)))))
3026 (if found
3027 (goto-char found))
3028 (if found
3029 (progn
3030 (skip-chars-forward " \t|&({[")
3031 (setq found (point))))
3032 (if (>= (point) start)
3033 (progn
3034 (debug "We didn't move!")
3035 (setq found nil))
3036 (or found
3037 (sh-debug "Did not find prev stmt.")))
34939e2c 3038 found)))
f964dfcb
GM
3039
3040
3041(defun sh-get-word ()
3042 "Get a shell word skipping whitespace from point."
3043 (interactive)
3044 (skip-chars-forward "\t ")
3045 (let ((start (point)))
3046 (while
3047 (if (looking-at "[\"'`]")
3048 (sh-safe-forward-sexp)
3049 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
4f3a3368 3050 (> (skip-chars-forward "-_$[:alnum:]") 0)
f964dfcb
GM
3051 ))
3052 (buffer-substring start (point))
3053 ))
3054
3055(defun sh-prev-thing ()
3056 "Return the previous thing this logical line."
3057 ;; This is called when `sh-get-indent-info' is working backwards on
3058 ;; the previous line(s) finding what keywords may be relevant for
8db2b9fb 3059 ;; indenting. It moves over sexps if possible, and will stop
f964dfcb
GM
3060 ;; on a ; and at the beginning of a line if it is not a continuation
3061 ;; line.
3062 ;;
3063 ;; Added a kludge for ";;"
3064 ;; Possible return values:
3065 ;; nil - nothing
3066 ;; a string - possibly a keyword
035107fa 3067 ;;
f964dfcb
GM
3068 (if (bolp)
3069 nil
49c7a608
SM
3070 (let ((start (point))
3071 (min-point (if (sh-this-is-a-continuation)
3072 (sh-prev-line nil)
3073 (line-beginning-position))))
3074 (skip-chars-backward " \t;" min-point)
7cb76591 3075 (if (looking-at "\\s-*;[;&]")
49c7a608
SM
3076 ;; (message "Found ;; !")
3077 ";;"
3078 (skip-chars-backward "^)}];\"'`({[" min-point)
3079 (let ((c (if (> (point) min-point) (char-before))))
3080 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
3081 (point) c start min-point)
3082 (if (not (memq c '(?\n nil ?\;)))
3083 ;; c -- return a string
3084 (char-to-string c)
3085 ;; Return the leading keyword of the "command" we supposedly
3086 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
3087 ;; `then' that precedes the actual command), so check whether
3088 ;; we're looking at such a keyword and if so, move back forward.
3089 (let ((boundary (point))
3090 kwd next)
3091 (while
3092 (progn
3093 ;; Skip forward over white space newline and \ at eol.
3094 (skip-chars-forward " \t\n\\\\" start)
3095 (if (>= (point) start)
3096 (progn
3097 (sh-debug "point: %d >= start: %d" (point) start)
3098 nil)
3099 (if next (setq boundary next))
3100 (sh-debug "Now at %d start=%d" (point) start)
3101 (setq kwd (sh-get-word))
49c7a608
SM
3102 (if (member kwd (sh-feature sh-leading-keywords))
3103 (progn
3104 (setq next (point))
3105 t)
3106 nil))))
3107 (goto-char boundary)
3108 kwd)))))))
f964dfcb
GM
3109
3110
3111(defun sh-this-is-a-continuation ()
3112 "Return non-nil if current line is a continuation of previous line."
6c5bcbc1
SM
3113 (save-excursion
3114 (and (zerop (forward-line -1))
3115 (looking-at ".*\\\\$")
3116 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
3117 nil nil nil t))))))
f964dfcb
GM
3118
3119(defun sh-get-kw (&optional where and-move)
3120 "Return first word of line from WHERE.
3121If AND-MOVE is non-nil then move to end of word."
3122 (let ((start (point)))
3123 (if where
3124 (goto-char where))
3125 (prog1
3126 (buffer-substring (point)
2ca2ebe6 3127 (progn (skip-chars-forward "^ \t\n;&|")(point)))
f964dfcb 3128 (unless and-move
34939e2c 3129 (goto-char start)))))
f964dfcb
GM
3130
3131(defun sh-find-prev-matching (open close &optional depth)
3132 "Find a matching token for a set of opening and closing keywords.
3133This takes into account that there may be nested open..close pairings.
3134OPEN and CLOSE are regexps denoting the tokens to be matched.
3135Optional parameter DEPTH (usually 1) says how many to look for."
3136 (let ((parse-sexp-ignore-comments t)
85527ff3 3137 (forward-sexp-function nil)
f964dfcb
GM
3138 prev)
3139 (setq depth (or depth 1))
3140 (save-excursion
3141 (condition-case nil
3142 (while (and
3143 (/= 0 depth)
3144 (not (bobp))
3145 (setq prev (sh-prev-stmt)))
3146 (goto-char prev)
3147 (save-excursion
3148 (if (looking-at "\\\\\n")
3149 (progn
3150 (forward-char 2)
3151 (skip-chars-forward " \t")))
3152 (cond
3153 ((looking-at open)
3154 (setq depth (1- depth))
3155 (sh-debug "found open at %d - depth = %d" (point) depth))
3156 ((looking-at close)
3157 (setq depth (1+ depth))
3158 (sh-debug "found close - depth = %d" depth))
3159 (t
3160 ))))
6c5bcbc1 3161 (error nil))
f964dfcb
GM
3162 (if (eq depth 0)
3163 prev ;; (point)
3164 nil)
3165 )))
3166
3167
3168(defun sh-var-value (var &optional ignore-error)
3169 "Return the value of variable VAR, interpreting symbols.
3170It can also return t or nil.
eac9c0ef 3171If an invalid value is found, throw an error unless Optional argument
f964dfcb
GM
3172IGNORE-ERROR is non-nil."
3173 (let ((val (symbol-value var)))
3174 (cond
3175 ((numberp val)
3176 val)
3177 ((eq val t)
3178 val)
3179 ((null val)
3180 val)
3181 ((eq val '+)
3182 sh-basic-offset)
3183 ((eq val '-)
3184 (- sh-basic-offset))
3185 ((eq val '++)
3186 (* 2 sh-basic-offset))
3187 ((eq val '--)
3188 (* 2 (- sh-basic-offset)))
3189 ((eq val '*)
3190 (/ sh-basic-offset 2))
3191 ((eq val '/)
3192 (/ (- sh-basic-offset) 2))
3193 (t
71e3276b
SM
3194 (funcall (if ignore-error #'message #'error)
3195 "Don't know how to handle %s's value of %s" var val)
3196 0))))
f964dfcb
GM
3197
3198(defun sh-set-var-value (var value &optional no-symbol)
3199 "Set variable VAR to VALUE.
8db2b9fb 3200Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
f964dfcb
GM
3201can be represented by a symbol then do so."
3202 (cond
3203 (no-symbol
3204 (set var value))
3205 ((= value sh-basic-offset)
3206 (set var '+))
3207 ((= value (- sh-basic-offset))
3208 (set var '-))
3209 ((eq value (* 2 sh-basic-offset))
3210 (set var '++))
3211 ((eq value (* 2 (- sh-basic-offset)))
3212 (set var '--))
3213 ((eq value (/ sh-basic-offset 2))
3214 (set var '*))
3215 ((eq value (/ (- sh-basic-offset) 2))
3216 (set var '/))
3217 (t
3218 (set var value)))
3219 )
3220
3221
3222(defun sh-calculate-indent (&optional info)
3223 "Return the indentation for the current line.
3224If INFO is supplied it is used, else it is calculated from current line."
6c5bcbc1 3225 (let ((ofs 0)
f964dfcb 3226 (base-value 0)
e02f48d7 3227 elt a b val)
f964dfcb
GM
3228 (or info
3229 (setq info (sh-get-indent-info)))
6c5bcbc1 3230 (when info
f964dfcb
GM
3231 (while info
3232 (sh-debug "info: %s ofs=%s" info ofs)
3233 (setq elt (car info))
3234 (cond
6c5bcbc1 3235 ((stringp elt)) ;; do nothing?
f964dfcb
GM
3236 ((listp elt)
3237 (setq a (car (car info)))
3238 (setq b (nth 1 (car info)))
3239 (cond
3240 ((eq a t)
3241 (save-excursion
3242 (goto-char b)
3243 (setq val (current-indentation)))
3244 (setq base-value val))
3245 ((symbolp b)
3246 (setq val (sh-var-value b))
3247 (cond
3248 ((eq a '=)
3249 (cond
3250 ((null val)
3251 ;; no indentation
3252 ;; set info to nil so we stop immediately
3253 (setq base-value nil ofs nil info nil))
6c5bcbc1 3254 ((eq val t) (setq ofs 0)) ;; indent as normal line
f964dfcb
GM
3255 (t
3256 ;; The following assume the (t POS) come first!
3257 (setq ofs val base-value 0)
6c5bcbc1
SM
3258 (setq info nil)))) ;; ? stop now
3259 ((eq a '+) (setq ofs (+ ofs val)))
3260 ((eq a '-) (setq ofs (- ofs val)))
f964dfcb
GM
3261 (t
3262 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
3263 (t
6c5bcbc1 3264 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
f964dfcb 3265 (t
6c5bcbc1
SM
3266 (error "sh-calculate-indent invalid elt %s" elt)))
3267 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
3268 a b val base-value ofs)
3269 (setq info (cdr info)))
f964dfcb
GM
3270 ;; return value:
3271 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
3272
3273 (cond
3274 ((or (null base-value)(null ofs))
3275 nil)
3276 ((and (numberp base-value)(numberp ofs))
3277 (sh-debug "base (%d) + ofs (%d) = %d"
6c5bcbc1 3278 base-value ofs (+ base-value ofs))
f964dfcb
GM
3279 (+ base-value ofs)) ;; return value
3280 (t
3281 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
3282 base-value ofs)
6c5bcbc1 3283 nil)))))
f964dfcb
GM
3284
3285
3e2dd647 3286(defun sh-indent-line ()
f964dfcb
GM
3287 "Indent the current line."
3288 (interactive)
017708e9 3289 (let ((indent (sh-calculate-indent))
f964dfcb 3290 (pos (- (point-max) (point))))
6c5bcbc1
SM
3291 (when indent
3292 (beginning-of-line)
6c5bcbc1 3293 (skip-chars-forward " \t")
017708e9 3294 (indent-line-to indent)
6c5bcbc1
SM
3295 ;; If initial point was within line's indentation,
3296 ;; position after the indentation. Else stay at same point in text.
3297 (if (> (- (point-max) pos) (point))
3298 (goto-char (- (point-max) pos))))))
f964dfcb
GM
3299
3300
3301(defun sh-blink (blinkpos &optional msg)
3302 "Move cursor momentarily to BLINKPOS and display MSG."
3303 ;; We can get here without it being a number on first line
3304 (if (numberp blinkpos)
3305 (save-excursion
3306 (goto-char blinkpos)
29a4e67d 3307 (if msg (message "%s" msg) (message nil))
f964dfcb 3308 (sit-for blink-matching-delay))
7fa1a8f9 3309 (if msg (message "%s" msg) (message nil))))
f964dfcb
GM
3310
3311(defun sh-show-indent (arg)
63616f52 3312 "Show the how the current line would be indented.
f964dfcb
GM
3313This tells you which variable, if any, controls the indentation of
3314this line.
3315If optional arg ARG is non-null (called interactively with a prefix),
3316a pop up window describes this variable.
3317If variable `sh-blink' is non-nil then momentarily go to the line
3318we are indenting relative to, if applicable."
3319 (interactive "P")
3320 (sh-must-support-indent)
71e3276b
SM
3321 (if sh-use-smie
3322 (smie-config-show-indent)
3323 (let* ((info (sh-get-indent-info))
3324 (var (sh-get-indent-var-for-line info))
3325 (curr-indent (current-indentation))
3326 val msg)
3327 (if (stringp var)
3328 (message "%s" (setq msg var))
3329 (setq val (sh-calculate-indent info))
3330
3331 (if (eq curr-indent val)
3332 (setq msg (format "%s is %s" var (symbol-value var)))
3333 (setq msg
3334 (if val
3335 (format "%s (%s) would change indent from %d to: %d"
3336 var (symbol-value var) curr-indent val)
3337 (format "%s (%s) would leave line as is"
3338 var (symbol-value var)))
3339 ))
3340 (if (and arg var)
3341 (describe-variable var)))
3342 (if sh-blink
3343 (let ((info (sh-get-indent-info)))
3344 (if (and info (listp (car info))
3345 (eq (car (car info)) t))
3346 (sh-blink (nth 1 (car info)) msg)
3347 (message "%s" msg)))
3348 (message "%s" msg))
3349 )))
f964dfcb
GM
3350
3351(defun sh-set-indent ()
3352 "Set the indentation for the current line.
3353If the current line is controlled by an indentation variable, prompt
3354for a new value for it."
3355 (interactive)
3356 (sh-must-support-indent)
71e3276b
SM
3357 (if sh-use-smie
3358 (smie-config-set-indent)
3359 (let* ((info (sh-get-indent-info))
3360 (var (sh-get-indent-var-for-line info))
3361 val old-val indent-val)
3362 (if (stringp var)
3363 (message "Cannot set indent - %s" var)
3364 (setq old-val (symbol-value var))
3365 (setq val (sh-read-variable var))
3366 (condition-case nil
3367 (progn
3368 (set var val)
3369 (setq indent-val (sh-calculate-indent info))
3370 (if indent-val
3371 (message "Variable: %s Value: %s would indent to: %d"
3372 var (symbol-value var) indent-val)
3373 (message "Variable: %s Value: %s would leave line as is."
3374 var (symbol-value var)))
3375 ;; I'm not sure about this, indenting it now?
3376 ;; No. Because it would give the impression that an undo would
3377 ;; restore thing, but the value has been altered.
3378 ;; (sh-indent-line)
3379 )
3380 (error
3381 (set var old-val)
3382 (message "Bad value for %s, restoring to previous value %s"
3383 var old-val)
3384 (sit-for 1)
3385 nil))
3386 ))))
f964dfcb
GM
3387
3388
3389(defun sh-learn-line-indent (arg)
3390 "Learn how to indent a line as it currently is indented.
3391
3392If there is an indentation variable which controls this line's indentation,
3393then set it to a value which would indent the line the way it
3394presently is.
3395
3396If the value can be represented by one of the symbols then do so
3397unless optional argument ARG (the prefix when interactive) is non-nil."
3398 (interactive "*P")
3399 (sh-must-support-indent)
71e3276b
SM
3400 (if sh-use-smie
3401 (smie-config-set-indent)
3402 ;; I'm not sure if we show allow learning on an empty line.
3403 ;; Though it might occasionally be useful I think it usually
3404 ;; would just be confusing.
3405 (if (save-excursion
3406 (beginning-of-line)
3407 (looking-at "\\s-*$"))
3408 (message "sh-learn-line-indent ignores empty lines.")
3409 (let* ((info (sh-get-indent-info))
3410 (var (sh-get-indent-var-for-line info))
3411 ival sval diff new-val
3412 (no-symbol arg)
3413 (curr-indent (current-indentation)))
3414 (cond
3415 ((stringp var)
3416 (message "Cannot learn line - %s" var))
3417 ((eq var 'sh-indent-comment)
3418 ;; This is arbitrary...
3419 ;; - if curr-indent is 0, set to curr-indent
3420 ;; - else if it has the indentation of a "normal" line,
3421 ;; then set to t
3422 ;; - else set to curr-indent.
3423 (setq sh-indent-comment
3424 (if (= curr-indent 0)
3425 0
3426 (let* ((sh-indent-comment t)
3427 (val2 (sh-calculate-indent info)))
3428 (if (= val2 curr-indent)
3429 t
3430 curr-indent))))
3431 (message "%s set to %s" var (symbol-value var))
3432 )
3433 ((numberp (setq sval (sh-var-value var)))
3434 (setq ival (sh-calculate-indent info))
3435 (setq diff (- curr-indent ival))
3436
3437 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
3438 curr-indent ival diff var sval)
3439 (setq new-val (+ sval diff))
3440 ;; I commented out this because someone might want to replace
3441 ;; a value of `+' with the current value of sh-basic-offset
3442 ;; or vice-versa.
3443 ;;(if (= 0 diff)
3444 ;; (message "No change needed!")
3445 (sh-set-var-value var new-val no-symbol)
3446 (message "%s set to %s" var (symbol-value var))
3447 )
3448 (t
3449 (debug)
3450 (message "Cannot change %s" var)))))))
f964dfcb
GM
3451
3452
3453
3454(defun sh-mark-init (buffer)
3455 "Initialize a BUFFER to be used by `sh-mark-line'."
090475f3 3456 (with-current-buffer (get-buffer-create buffer)
348e1411 3457 (erase-buffer)
090475f3 3458 (occur-mode)))
f964dfcb
GM
3459
3460
3461(defun sh-mark-line (message point buffer &optional add-linenum occur-point)
3462 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
3463Buffer BUFFER is in `occur-mode'.
3464If ADD-LINENUM is non-nil the message is preceded by the line number.
8db2b9fb 3465If OCCUR-POINT is non-nil then the line is marked as a new occurrence
f964dfcb
GM
3466so that `occur-next' and `occur-prev' will work."
3467 (let ((m1 (make-marker))
f964dfcb 3468 start
6c5bcbc1
SM
3469 (line ""))
3470 (when point
3471 (set-marker m1 point (current-buffer))
3472 (if add-linenum
3473 (setq line (format "%d: " (1+ (count-lines 1 point))))))
f964dfcb
GM
3474 (save-excursion
3475 (if (get-buffer buffer)
3476 (set-buffer (get-buffer buffer))
3477 (set-buffer (get-buffer-create buffer))
3478 (occur-mode)
f964dfcb
GM
3479 )
3480 (goto-char (point-max))
3481 (setq start (point))
a5d38e34
GM
3482 (let ((inhibit-read-only t))
3483 (insert line)
3484 (if occur-point
3485 (setq occur-point (point)))
3486 (insert message)
3487 (if point
3488 (add-text-properties
3489 start (point)
3490 '(mouse-face highlight
3491 help-echo "mouse-2: go to the line where I learned this")))
3492 (insert "\n")
3493 (when point
3494 (put-text-property start (point) 'occur-target m1)
3495 (if occur-point
3496 (put-text-property start occur-point
3497 'occur-match t))
3498 )))))
f964dfcb
GM
3499
3500;; Is this really worth having?
3501(defvar sh-learned-buffer-hook nil
fb7ada5f 3502 "An abnormal hook, called with an alist of learned variables.")
3e2dd647 3503;; Example of how to use sh-learned-buffer-hook
035107fa 3504;;
f964dfcb
GM
3505;; (defun what-i-learned (list)
3506;; (let ((p list))
9a529312 3507;; (with-current-buffer "*scratch*"
f964dfcb
GM
3508;; (goto-char (point-max))
3509;; (insert "(setq\n")
3510;; (while p
3511;; (insert (format " %s %s \n"
3512;; (nth 0 (car p)) (nth 1 (car p))))
3513;; (setq p (cdr p)))
3514;; (insert ")\n")
3515;; )))
035107fa 3516;;
f964dfcb
GM
3517;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
3518
3519
3520;; Originally this was sh-learn-region-indent (beg end)
8db2b9fb 3521;; However, in practice this was awkward so I changed it to
4fa51741 3522;; use the whole buffer. Use narrowing if need be.
f964dfcb
GM
3523(defun sh-learn-buffer-indent (&optional arg)
3524 "Learn how to indent the buffer the way it currently is.
3525
3526Output in buffer \"*indent*\" shows any lines which have conflicting
8db2b9fb 3527values of a variable, and the final value of all variables learned.
946c009b
CY
3528When called interactively, pop to this buffer automatically if
3529there are any discrepancies.
f964dfcb 3530
8db2b9fb
SM
3531If no prefix ARG is given, then variables are set to numbers.
3532If a prefix arg is given, then variables are set to symbols when
f964dfcb
GM
3533applicable -- e.g. to symbol `+' if the value is that of the
3534basic indent.
3535If a positive numerical prefix is given, then `sh-basic-offset'
3536is set to the prefix's numerical value.
8db2b9fb 3537Otherwise, sh-basic-offset may or may not be changed, according
f964dfcb
GM
3538to the value of variable `sh-learn-basic-offset'.
3539
3540Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
3541function completes. The function is abnormal because it is called
8db2b9fb 3542with an alist of variables learned. This feature may be changed or
f964dfcb
GM
3543removed in the future.
3544
3545This command can often take a long time to run."
3546 (interactive "P")
3547 (sh-must-support-indent)
71e3276b
SM
3548 (if sh-use-smie
3549 (smie-config-guess)
3550 (save-excursion
3551 (goto-char (point-min))
3552 (let ((learned-var-list nil)
3553 (out-buffer "*indent*")
3554 (num-diffs 0)
3555 previous-set-info
3556 (max 17)
3557 vec
3558 msg
3559 (comment-col nil) ;; number if all same, t if seen diff values
3560 (comments-always-default t) ;; nil if we see one not default
3561 initial-msg
3562 (specified-basic-offset (and arg (numberp arg)
3563 (> arg 0)))
3564 (linenum 0)
3565 suggested)
3566 (setq vec (make-vector max 0))
3567 (sh-mark-init out-buffer)
3568
3569 (if specified-basic-offset
3570 (progn
3571 (setq sh-basic-offset arg)
3572 (setq initial-msg
3573 (format "Using specified sh-basic-offset of %d"
3574 sh-basic-offset)))
3575 (setq initial-msg
3576 (format "Initial value of sh-basic-offset: %s"
3577 sh-basic-offset)))
3578
3579 (while (< (point) (point-max))
3580 (setq linenum (1+ linenum))
3581 ;; (if (zerop (% linenum 10))
3582 (message "line %d" linenum)
3583 ;; )
3584 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3585 (let* ((sh-indent-comment t) ;; info must return default indent
3586 (info (sh-get-indent-info))
3587 (var (sh-get-indent-var-for-line info))
3588 sval ival diff new-val
3589 (curr-indent (current-indentation)))
3590 (cond
3591 ((null var)
3592 nil)
3593 ((stringp var)
3594 nil)
3595 ((numberp (setq sval (sh-var-value var 'no-error)))
3596 ;; the numberp excludes comments since sval will be t.
3597 (setq ival (sh-calculate-indent))
3598 (setq diff (- curr-indent ival))
3599 (setq new-val (+ sval diff))
3600 (sh-set-var-value var new-val 'no-symbol)
3601 (unless (looking-at "\\s-*#") ;; don't learn from comments
3602 (if (setq previous-set-info (assoc var learned-var-list))
3603 (progn
3604 ;; it was already there, is it same value ?
3605 (unless (eq (symbol-value var)
3606 (nth 1 previous-set-info))
3607 (sh-mark-line
3608 (format "Variable %s was set to %s"
3609 var (symbol-value var))
3610 (point) out-buffer t t)
3611 (sh-mark-line
3612 (format " but was previously set to %s"
3613 (nth 1 previous-set-info))
3614 (nth 2 previous-set-info) out-buffer t)
3615 (setq num-diffs (1+ num-diffs))
3616 ;; (delete previous-set-info learned-var-list)
3617 (setcdr previous-set-info
3618 (list (symbol-value var) (point)))
3619 )
3620 )
3621 (setq learned-var-list
3622 (append (list (list var (symbol-value var)
3623 (point)))
3624 learned-var-list)))
3625 (if (numberp new-val)
3626 (progn
3627 (sh-debug
3628 "This line's indent value: %d" new-val)
3629 (if (< new-val 0)
3630 (setq new-val (- new-val)))
3631 (if (< new-val max)
3632 (aset vec new-val (1+ (aref vec new-val))))))
3633 ))
3634 ((eq var 'sh-indent-comment)
3635 (unless (= curr-indent (sh-calculate-indent info))
3636 ;; this is not the default indentation
3637 (setq comments-always-default nil)
3638 (if comment-col ;; then we have see one before
3639 (or (eq comment-col curr-indent)
3640 (setq comment-col t)) ;; seen a different one
3641 (setq comment-col curr-indent))
3642 ))
3643 (t
3644 (sh-debug "Cannot learn this line!!!")
3645 ))
3646 (sh-debug
3647 "at %s learned-var-list is %s" (point) learned-var-list)
3648 ))
3649 (forward-line 1)
3650 ) ;; while
3651 (if sh-debug
3652 (progn
3653 (setq msg (format
3654 "comment-col = %s comments-always-default = %s"
3655 comment-col comments-always-default))
3656 ;; (message msg)
3657 (sh-mark-line msg nil out-buffer)))
3658 (cond
3659 ((eq comment-col 0)
3660 (setq msg "\nComments are all in 1st column.\n"))
3661 (comments-always-default
3662 (setq msg "\nComments follow default indentation.\n")
3663 (setq comment-col t))
3664 ((numberp comment-col)
3665 (setq msg (format "\nComments are in col %d." comment-col)))
3666 (t
3667 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3668 (setq comment-col nil)
3669 ))
3670 (sh-debug msg)
3671 (sh-mark-line msg nil out-buffer)
3672
3673 (sh-mark-line initial-msg nil out-buffer t t)
3674
3675 (setq suggested (sh-guess-basic-offset vec))
3676
3677 (if (and suggested (not specified-basic-offset))
3678 (let ((new-value
3679 (cond
3680 ;; t => set it if we have a single value as a number
3681 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3682 suggested)
3683 ;; other non-nil => set it if only one value was found
3684 (sh-learn-basic-offset
3685 (if (numberp suggested)
3686 suggested
3687 (if (= (length suggested) 1)
3688 (car suggested))))
3689 (t
3690 nil))))
3691 (if new-value
3692 (progn
3693 (setq learned-var-list
3694 (append (list (list 'sh-basic-offset
3695 (setq sh-basic-offset new-value)
3696 (point-max)))
3697 learned-var-list))
3698 ;; Not sure if we need to put this line in, since
3699 ;; it will appear in the "Learned variable settings".
3700 (sh-mark-line
3701 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3702 nil out-buffer))
3703 (sh-mark-line
3704 (if (listp suggested)
3705 (format "Possible value(s) for sh-basic-offset: %s"
3706 (mapconcat 'int-to-string suggested " "))
3707 (format "Suggested sh-basic-offset: %d" suggested))
3708 nil out-buffer))))
3709
3710
3711 (setq learned-var-list
3712 (append (list (list 'sh-indent-comment comment-col (point-max)))
3713 learned-var-list))
3714 (setq sh-indent-comment comment-col)
3715 (let ((name (buffer-name)))
3716 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3717 (if arg
3718 ;; Set learned variables to symbolic rather than numeric
3719 ;; values where possible.
3720 (dolist (learned-var (reverse learned-var-list))
3721 (let ((var (car learned-var))
3722 (val (nth 1 learned-var)))
3723 (when (and (not (eq var 'sh-basic-offset))
3724 (numberp val))
3725 (sh-set-var-value var val)))))
3726 (dolist (learned-var (reverse learned-var-list))
3727 (let ((var (car learned-var)))
3728 (sh-mark-line (format " %s %s" var (symbol-value var))
3729 (nth 2 learned-var) out-buffer)))
3730 (with-current-buffer out-buffer
3731 (goto-char (point-min))
3732 (let ((inhibit-read-only t))
3733 (insert
3734 (format "Indentation values for buffer %s.\n" name)
3735 (format "%d indentation variable%s different values%s\n\n"
3736 num-diffs
3737 (if (= num-diffs 1)
3738 " has" "s have")
3739 (if (zerop num-diffs)
3740 "." ":"))))))
3741 ;; Are abnormal hooks considered bad form?
3742 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3743 (and (called-interactively-p 'any)
3744 (or sh-popup-occur-buffer (> num-diffs 0))
3745 (pop-to-buffer out-buffer))))))
f964dfcb
GM
3746
3747(defun sh-guess-basic-offset (vec)
8db2b9fb 3748 "See if we can determine a reasonable value for `sh-basic-offset'.
f964dfcb
GM
3749This is experimental, heuristic and arbitrary!
3750Argument VEC is a vector of information collected by
3751`sh-learn-buffer-indent'.
3752Return values:
3753 number - there appears to be a good single value
8db2b9fb 3754 list of numbers - no obvious one, here is a list of one or more
f964dfcb
GM
3755 reasonable choices
3756 nil - we couldn't find a reasonable one."
3757 (let* ((max (1- (length vec)))
6c5bcbc1 3758 (i 1)
485219e0 3759 (totals (make-vector max 0)))
f964dfcb 3760 (while (< i max)
71e3276b 3761 (cl-incf (aref totals i) (* 4 (aref vec i)))
f964dfcb 3762 (if (zerop (% i 2))
71e3276b 3763 (cl-incf (aref totals i) (aref vec (/ i 2))))
f964dfcb 3764 (if (< (* i 2) max)
71e3276b 3765 (cl-incf (aref totals i) (aref vec (* i 2))))
6c5bcbc1
SM
3766 (setq i (1+ i)))
3767
f964dfcb
GM
3768 (let ((x nil)
3769 (result nil)
3770 tot sum p)
3771 (setq i 1)
3772 (while (< i max)
3773 (if (/= (aref totals i) 0)
71e3276b 3774 (push (cons i (aref totals i)) x))
f964dfcb
GM
3775 (setq i (1+ i)))
3776
71e3276b 3777 (setq x (sort (nreverse x) (lambda (a b) (> (cdr a) (cdr b)))))
f964dfcb
GM
3778 (setq tot (apply '+ (append totals nil)))
3779 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
6c5bcbc1 3780 vec totals tot))
f964dfcb
GM
3781 (cond
3782 ((zerop (length x))
3783 (message "no values!")) ;; we return nil
3784 ((= (length x) 1)
3785 (message "only value is %d" (car (car x)))
6c5bcbc1 3786 (setq result (car (car x)))) ;; return single value
f964dfcb
GM
3787 ((> (cdr (car x)) (/ tot 2))
3788 ;; 1st is > 50%
3789 (message "basic-offset is probably %d" (car (car x)))
3790 (setq result (car (car x)))) ;; again, return a single value
3791 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3792 ;; 1st is >= 2 * 2nd
3793 (message "basic-offset could be %d" (car (car x)))
3794 (setq result (car (car x))))
3795 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3796 ;; 1st & 2nd together >= 50% - return a list
3797 (setq p x sum 0 result nil)
3798 (while (and p
3799 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3800 (setq result (append result (list (car (car p)))))
3801 (setq p (cdr p)))
3802 (message "Possible choices for sh-basic-offset: %s"
3803 (mapconcat 'int-to-string result " ")))
3804 (t
3805 (message "No obvious value for sh-basic-offset. Perhaps %d"
3806 (car (car x)))
3807 ;; result is nil here
3808 ))
34939e2c 3809 result)))
f964dfcb
GM
3810
3811;; ========================================================================
3812
8db2b9fb 3813;; Styles -- a quick and dirty way of saving the indentation settings.
f964dfcb
GM
3814
3815(defvar sh-styles-alist nil
3816 "A list of all known shell indentation styles.")
3817
3818(defun sh-name-style (name &optional confirm-overwrite)
3819 "Name the current indentation settings as a style called NAME.
8db2b9fb 3820If this name exists, the command will prompt whether it should be
f964dfcb 3821overwritten if
8db2b9fb 3822- - it was called interactively with a prefix argument, or
f964dfcb
GM
3823- - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3824 ;; (interactive "sName for this style: ")
3825 (interactive
3826 (list
3827 (read-from-minibuffer "Name for this style? " )
3828 (not current-prefix-arg)))
6c5bcbc1
SM
3829 (let ((slist (cons name
3830 (mapcar (lambda (var) (cons var (symbol-value var)))
3831 sh-var-list)))
3832 (style (assoc name sh-styles-alist)))
3833 (if style
3834 (if (and confirm-overwrite
3835 (not (y-or-n-p "This style exists. Overwrite it? ")))
3836 (message "Not changing style %s" name)
3837 (message "Updating style %s" name)
3838 (setcdr style (cdr slist)))
f964dfcb 3839 (message "Creating new style %s" name)
6c5bcbc1 3840 (push slist sh-styles-alist))))
f964dfcb
GM
3841
3842(defun sh-load-style (name)
3843 "Set shell indentation values for this buffer from those in style NAME."
3844 (interactive (list (completing-read
3845 "Which style to use for this buffer? "
3846 sh-styles-alist nil t)))
3847 (let ((sl (assoc name sh-styles-alist)))
3848 (if (null sl)
3849 (error "sh-load-style - style %s not known" name)
6c5bcbc1
SM
3850 (dolist (var (cdr sl))
3851 (set (car var) (cdr var))))))
f964dfcb
GM
3852
3853(defun sh-save-styles-to-buffer (buff)
3854 "Save all current styles in elisp to buffer BUFF.
3855This is always added to the end of the buffer."
ff46c759
SM
3856 (interactive
3857 (list
3858 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
6c5bcbc1 3859 (with-current-buffer (get-buffer-create buff)
f964dfcb
GM
3860 (goto-char (point-max))
3861 (insert "\n")
6c5bcbc1 3862 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
f964dfcb
GM
3863
3864
3865\f
ac59aed8
RS
3866;; statement syntax-commands for various shells
3867
3868;; You are welcome to add the syntax or even completely new statements as
3869;; appropriate for your favorite shell.
3870
017708e9
SM
3871(defconst sh-non-closing-paren
3872 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3873 ;; that inherits this property, which then confuses the indentation.
3874 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3875
c410bd65
RS
3876(define-skeleton sh-case
3877 "Insert a case/switch statement. See `sh-feature'."
cef926f3
RS
3878 (csh "expression: "
3879 "switch( " str " )" \n
3880 > "case " (read-string "pattern: ") ?: \n
c410bd65 3881 > _ \n
cef926f3 3882 "breaksw" \n
c410bd65 3883 ( "other pattern, %s: "
cef926f3 3884 < "case " str ?: \n
c410bd65 3885 > _ \n
cef926f3
RS
3886 "breaksw" \n)
3887 < "default:" \n
c410bd65
RS
3888 > _ \n
3889 resume:
3e2dd647 3890 < < "endsw" \n)
cef926f3
RS
3891 (es)
3892 (rc "expression: "
f964dfcb 3893 > "switch( " str " ) {" \n
cef926f3
RS
3894 > "case " (read-string "pattern: ") \n
3895 > _ \n
3896 ( "other pattern, %s: "
f964dfcb 3897 "case " str > \n
cef926f3 3898 > _ \n)
f964dfcb 3899 "case *" > \n
cef926f3
RS
3900 > _ \n
3901 resume:
035107fa 3902 ?\} > \n)
cef926f3 3903 (sh "expression: "
f964dfcb 3904 > "case " str " in" \n
017708e9
SM
3905 ( "pattern, %s: "
3906 > str sh-non-closing-paren \n
cef926f3 3907 > _ \n
8f0b0ca5 3908 ";;" \n)
017708e9 3909 > "*" sh-non-closing-paren \n
cef926f3
RS
3910 > _ \n
3911 resume:
3e2dd647 3912 "esac" > \n))
133693bc
KH
3913
3914(define-skeleton sh-for
3915 "Insert a for loop. See `sh-feature'."
6b61353c 3916 (csh sh-modify sh
f964dfcb
GM
3917 1 ""
3918 2 "foreach "
3919 4 " ( "
3920 6 " )"
3921 15 '<
b36581fb 3922 16 "end")
6b61353c 3923 (es sh-modify rc
f964dfcb 3924 4 " = ")
6b61353c 3925 (rc sh-modify sh
f964dfcb
GM
3926 2 "for( "
3927 6 " ) {"
035107fa 3928 15 ?\} )
ac59aed8 3929 (sh "Index variable: "
f964dfcb 3930 > "for " str " in " _ "; do" \n
133693bc 3931 > _ | ?$ & (sh-remember-variable str) \n
3e2dd647 3932 "done" > \n))
ac59aed8
RS
3933
3934
3935
133693bc
KH
3936(define-skeleton sh-indexed-loop
3937 "Insert an indexed loop from 1 to n. See `sh-feature'."
6b61353c 3938 (bash sh-modify posix)
ac59aed8
RS
3939 (csh "Index variable: "
3940 "@ " str " = 1" \n
133693bc
KH
3941 "while( $" str " <= " (read-string "upper limit: ") " )" \n
3942 > _ ?$ str \n
ac59aed8 3943 "@ " str "++" \n
3e2dd647 3944 < "end" \n)
6b61353c 3945 (es sh-modify rc
f964dfcb 3946 4 " =")
133693bc 3947 (ksh88 "Index variable: "
f964dfcb
GM
3948 > "integer " str "=0" \n
3949 > "while (( ( " str " += 1 ) <= "
133693bc
KH
3950 (read-string "upper limit: ")
3951 " )); do" \n
f964dfcb 3952 > _ ?$ (sh-remember-variable str) > \n
3e2dd647 3953 "done" > \n)
133693bc 3954 (posix "Index variable: "
f964dfcb 3955 > str "=1" \n
133693bc
KH
3956 "while [ $" str " -le "
3957 (read-string "upper limit: ")
3958 " ]; do" \n
3959 > _ ?$ str \n
3960 str ?= (sh-add (sh-remember-variable str) 1) \n
3e2dd647 3961 "done" > \n)
133693bc 3962 (rc "Index variable: "
f964dfcb 3963 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
133693bc 3964 (read-string "upper limit: ")
f964dfcb 3965 "; i++ ) print i }'`}) {" \n
133693bc 3966 > _ ?$ (sh-remember-variable str) \n
035107fa 3967 ?\} > \n)
133693bc 3968 (sh "Index variable: "
f964dfcb 3969 > "for " str " in `awk 'BEGIN { for( i=1; i<="
133693bc
KH
3970 (read-string "upper limit: ")
3971 "; i++ ) print i }'`; do" \n
3972 > _ ?$ (sh-remember-variable str) \n
3e2dd647 3973 "done" > \n))
ac59aed8
RS
3974
3975
5d73ac66
RS
3976(defun sh-shell-initialize-variables ()
3977 "Scan the buffer for variable assignments.
3978Add these variables to `sh-shell-variables'."
3979 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3980 (save-excursion
3981 (goto-char (point-min))
3982 (setq sh-shell-variables-initialized t)
3983 (while (search-forward "=" nil t)
3984 (sh-assignment 0)))
3985 (message "Scanning buffer `%s' for variable assignments...done"
3986 (buffer-name)))
3987
3988(defvar sh-add-buffer)
3989
3990(defun sh-add-completer (string predicate code)
3991 "Do completion using `sh-shell-variables', but initialize it first.
3992This function is designed for use as the \"completion table\",
3993so it takes three arguments:
3994 STRING, the current buffer contents;
3995 PREDICATE, the predicate for filtering possible matches;
3996 CODE, which says what kind of things to do.
3997CODE can be nil, t or `lambda'.
3998nil means to return the best completion of STRING, or nil if there is none.
3999t means to return a list of all possible completions of STRING.
4000`lambda' means to return t if STRING is a valid completion as it stands."
5ccaa359 4001 (let ((vars
090475f3 4002 (with-current-buffer sh-add-buffer
5d73ac66
RS
4003 (or sh-shell-variables-initialized
4004 (sh-shell-initialize-variables))
4005 (nconc (mapcar (lambda (var)
5ccaa359 4006 (substring var 0 (string-match "=" var)))
5d73ac66
RS
4007 process-environment)
4008 sh-shell-variables))))
5ccaa359 4009 (complete-with-action code vars string predicate)))
5d73ac66 4010
ac59aed8 4011(defun sh-add (var delta)
133693bc 4012 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
ac59aed8 4013 (interactive
5d73ac66
RS
4014 (let ((sh-add-buffer (current-buffer)))
4015 (list (completing-read "Variable: " 'sh-add-completer)
4016 (prefix-numeric-value current-prefix-arg))))
546e2f6f 4017 (insert (sh-feature '((bash . "$(( ")
133693bc
KH
4018 (ksh88 . "$(( ")
4019 (posix . "$(( ")
4020 (rc . "`{expr $")
4021 (sh . "`expr $")
4022 (zsh . "$[ ")))
4023 (sh-remember-variable var)
4024 (if (< delta 0) " - " " + ")
4025 (number-to-string (abs delta))
546e2f6f 4026 (sh-feature '((bash . " ))")
133693bc
KH
4027 (ksh88 . " ))")
4028 (posix . " ))")
4029 (rc . "}")
4030 (sh . "`")
4031 (zsh . " ]")))))
4032
4033
4034
4035(define-skeleton sh-function
4036 "Insert a function definition. See `sh-feature'."
6b61353c 4037 (bash sh-modify ksh88
133693bc
KH
4038 3 "() {")
4039 (ksh88 "name: "
4040 "function " str " {" \n
4041 > _ \n
3e2dd647 4042 < "}" \n)
6b61353c 4043 (rc sh-modify ksh88
6c5bcbc1 4044 1 "fn ")
ac59aed8
RS
4045 (sh ()
4046 "() {" \n
4047 > _ \n
3e2dd647 4048 < "}" \n))
ac59aed8
RS
4049
4050
4051
133693bc
KH
4052(define-skeleton sh-if
4053 "Insert an if statement. See `sh-feature'."
ac59aed8
RS
4054 (csh "condition: "
4055 "if( " str " ) then" \n
4056 > _ \n
4057 ( "other condition, %s: "
133693bc
KH
4058 < "else if( " str " ) then" \n
4059 > _ \n)
ac59aed8 4060 < "else" \n
133693bc 4061 > _ \n
ac59aed8 4062 resume:
3e2dd647 4063 < "endif" \n)
133693bc 4064 (es "condition: "
6c5bcbc1
SM
4065 > "if { " str " } {" \n
4066 > _ \n
4067 ( "other condition, %s: "
4068 "} { " str " } {" > \n
4069 > _ \n)
4070 "} {" > \n
4071 > _ \n
4072 resume:
035107fa 4073 ?\} > \n)
f964dfcb 4074 (rc "condition: "
6c5bcbc1
SM
4075 > "if( " str " ) {" \n
4076 > _ \n
4077 ( "other condition, %s: "
4078 "} else if( " str " ) {" > \n
4079 > _ \n)
4080 "} else {" > \n
4081 > _ \n
4082 resume:
035107fa 4083 ?\} > \n)
133693bc 4084 (sh "condition: "
225f6185 4085 '(setq input (sh-feature sh-test))
f964dfcb 4086 > "if " str "; then" \n
133693bc
KH
4087 > _ \n
4088 ( "other condition, %s: "
6c5bcbc1 4089 > "elif " str "; then" > \n
8f0b0ca5 4090 > \n)
6c5bcbc1 4091 "else" > \n
f964dfcb 4092 > \n
133693bc 4093 resume:
3e2dd647 4094 "fi" > \n))
ac59aed8
RS
4095
4096
4097
133693bc
KH
4098(define-skeleton sh-repeat
4099 "Insert a repeat loop definition. See `sh-feature'."
4100 (es nil
f964dfcb 4101 > "forever {" \n
133693bc 4102 > _ \n
035107fa 4103 ?\} > \n)
133693bc 4104 (zsh "factor: "
f964dfcb 4105 > "repeat " str "; do" > \n
6c5bcbc1 4106 > \n
3e2dd647 4107 "done" > \n))
f964dfcb 4108
ea39159e 4109;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
133693bc
KH
4110
4111
4112
4113(define-skeleton sh-select
4114 "Insert a select statement. See `sh-feature'."
4115 (ksh88 "Index variable: "
f964dfcb 4116 > "select " str " in " _ "; do" \n
133693bc 4117 > ?$ str \n
3e2dd647 4118 "done" > \n)
6b61353c 4119 (bash sh-append ksh88))
ea39159e 4120;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
133693bc
KH
4121
4122
4123
4124(define-skeleton sh-tmp-file
4125 "Insert code to setup temporary file handling. See `sh-feature'."
6b61353c 4126 (bash sh-append ksh88)
133693bc 4127 (csh (file-name-nondirectory (buffer-file-name))
decb2a9e 4128 "set tmp = `mktemp -t " str ".XXXXXX`" \n
133693bc
KH
4129 "onintr exit" \n _
4130 (and (goto-char (point-max))
4131 (not (bolp))
4132 ?\n)
4133 "exit:\n"
3e2dd647 4134 "rm $tmp* >&/dev/null" > \n)
133693bc 4135 (es (file-name-nondirectory (buffer-file-name))
decb2a9e
RS
4136 > "local( signals = $signals sighup sigint;" \n
4137 > "tmp = `{ mktemp -t " str ".XXXXXX } ) {" \n
133693bc
KH
4138 > "catch @ e {" \n
4139 > "rm $tmp^* >[2]/dev/null" \n
4140 "throw $e" \n
f964dfcb 4141 "} {" > \n
6c5bcbc1 4142 _ \n
035107fa
SS
4143 ?\} > \n
4144 ?\} > \n)
6b61353c 4145 (ksh88 sh-modify sh
f964dfcb 4146 7 "EXIT")
133693bc 4147 (rc (file-name-nondirectory (buffer-file-name))
decb2a9e 4148 > "tmp = `{ mktemp -t " str ".XXXXXX }" \n
3e2dd647 4149 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
133693bc 4150 (sh (file-name-nondirectory (buffer-file-name))
decb2a9e 4151 > "TMP=`mktemp -t " str ".XXXXXX`" \n
3e2dd647 4152 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
ac59aed8
RS
4153
4154
4155
133693bc
KH
4156(define-skeleton sh-until
4157 "Insert an until loop. See `sh-feature'."
ac59aed8 4158 (sh "condition: "
225f6185 4159 '(setq input (sh-feature sh-test))
f964dfcb 4160 > "until " str "; do" \n
ac59aed8 4161 > _ \n
3e2dd647 4162 "done" > \n))
ea39159e 4163;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
133693bc
KH
4164
4165
4166
4167(define-skeleton sh-while
4168 "Insert a while loop. See `sh-feature'."
6b61353c 4169 (csh sh-modify sh
f964dfcb
GM
4170 2 ""
4171 3 "while( "
4172 5 " )"
4173 10 '<
b36581fb 4174 11 "end")
6b61353c 4175 (es sh-modify sh
f964dfcb
GM
4176 3 "while { "
4177 5 " } {"
035107fa 4178 10 ?\} )
6b61353c 4179 (rc sh-modify sh
f964dfcb
GM
4180 3 "while( "
4181 5 " ) {"
035107fa 4182 10 ?\} )
ac59aed8 4183 (sh "condition: "
225f6185 4184 '(setq input (sh-feature sh-test))
f964dfcb 4185 > "while " str "; do" \n
ac59aed8 4186 > _ \n
3e2dd647 4187 "done" > \n))
133693bc
KH
4188
4189
4190
4191(define-skeleton sh-while-getopts
4192 "Insert a while getopts loop. See `sh-feature'.
4193Prompts for an options string which consists of letters for each recognized
4194option followed by a colon `:' if the option accepts an argument."
6b61353c 4195 (bash sh-modify sh
133693bc 4196 18 "${0##*/}")
225f6185
KH
4197 (csh nil
4198 "while( 1 )" \n
4199 > "switch( \"$1\" )" \n
4200 '(setq input '("- x" . 2))
4201 > >
4202 ( "option, %s: "
4203 < "case " '(eval str)
4204 '(if (string-match " +" str)
4205 (setq v1 (substring str (match-end 0))
4206 str (substring str 0 (match-beginning 0)))
4207 (setq v1 nil))
4208 str ?: \n
4209 > "set " v1 & " = $2" | -4 & _ \n
4210 (if v1 "shift") & \n
4211 "breaksw" \n)
4212 < "case --:" \n
4213 > "shift" \n
4214 < "default:" \n
4215 > "break" \n
4216 resume:
4217 < < "endsw" \n
4218 "shift" \n
3e2dd647 4219 < "end" \n)
6b61353c 4220 (ksh88 sh-modify sh
133693bc
KH
4221 16 "print"
4222 18 "${0##*/}"
bc387269 4223 37 "OPTIND-1")
6b61353c 4224 (posix sh-modify sh
133693bc
KH
4225 18 "$(basename $0)")
4226 (sh "optstring: "
f964dfcb 4227 > "while getopts :" str " OPT; do" \n
133693bc 4228 > "case $OPT in" \n
133693bc
KH
4229 '(setq v1 (append (vconcat str) nil))
4230 ( (prog1 (if v1 (char-to-string (car v1)))
4231 (if (eq (nth 1 v1) ?:)
4232 (setq v1 (nthcdr 2 v1)
4233 v2 "\"$OPTARG\"")
4234 (setq v1 (cdr v1)
4235 v2 nil)))
017708e9 4236 > str "|+" str sh-non-closing-paren \n
133693bc 4237 > _ v2 \n
8f0b0ca5 4238 > ";;" \n)
017708e9 4239 > "*" sh-non-closing-paren \n
133693bc 4240 > "echo" " \"usage: " "`basename $0`"
c898fb28 4241 " [+-" '(setq v1 (point)) str
133693bc
KH
4242 '(save-excursion
4243 (while (search-backward ":" v1 t)
c898fb28 4244 (replace-match " ARG] [+-" t t)))
133693bc 4245 (if (eq (preceding-char) ?-) -5)
16ed8416 4246 (if (and (sequencep v1) (length v1)) "] " "} ")
119b42eb 4247 "[--] ARGS...\"" \n
f964dfcb 4248 "exit 2" > \n
6c5bcbc1
SM
4249 "esac" >
4250 \n "done"
4251 > \n
546e2f6f
GM
4252 "shift " (sh-add "OPTIND" -1) \n
4253 "OPTIND=1" \n))
ac59aed8
RS
4254
4255
4256
4257(defun sh-assignment (arg)
133693bc 4258 "Remember preceding identifier for future completion and do self-insert."
ac59aed8 4259 (interactive "p")
133693bc
KH
4260 (self-insert-command arg)
4261 (if (<= arg 1)
ac59aed8
RS
4262 (sh-remember-variable
4263 (save-excursion
133693bc
KH
4264 (if (re-search-forward (sh-feature sh-assignment-regexp)
4265 (prog1 (point)
4266 (beginning-of-line 1))
4267 t)
84bfbb44 4268 (match-string 1))))))
ac59aed8
RS
4269
4270
ac59aed8 4271(defun sh-maybe-here-document (arg)
6c5bcbc1 4272 "Insert self. Without prefix, following unquoted `<' inserts here document.
ac59aed8 4273The document is bounded by `sh-here-document-word'."
59f7af81 4274 (declare (obsolete sh-electric-here-document-mode "24.3"))
ac59aed8
RS
4275 (interactive "*P")
4276 (self-insert-command (prefix-numeric-value arg))
ff46c759 4277 (or arg (sh--maybe-here-document)))
ff46c759
SM
4278
4279(defun sh--maybe-here-document ()
4280 (or (not (looking-back "[^<]<<"))
ac59aed8 4281 (save-excursion
133693bc 4282 (backward-char 2)
00d2a6bb
DC
4283 (or (sh-quoted-p)
4284 (sh--inside-noncommand-expression (point))))
867cab74 4285 (nth 8 (syntax-ppss))
546e2f6f
GM
4286 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
4287 (make-string (/ (current-indentation) tab-width) ?\t)
4288 ""))
4289 (delim (replace-regexp-in-string "['\"]" ""
4290 sh-here-document-word)))
ac59aed8 4291 (insert sh-here-document-word)
1689f309 4292 (or (eolp) (looking-at "[ \t]") (insert ?\s))
ac59aed8 4293 (end-of-line 1)
133693bc
KH
4294 (while
4295 (sh-quoted-p)
4296 (end-of-line 2))
546e2f6f 4297 (insert ?\n tabs)
18368c4a 4298 (save-excursion
546e2f6f
GM
4299 (insert ?\n tabs (replace-regexp-in-string
4300 "\\`-?[ \t]*" "" delim))))))
ac59aed8 4301
ff46c759
SM
4302(define-minor-mode sh-electric-here-document-mode
4303 "Make << insert a here document skeleton."
4304 nil nil nil
4305 (if sh-electric-here-document-mode
4306 (add-hook 'post-self-insert-hook #'sh--maybe-here-document nil t)
4307 (remove-hook 'post-self-insert-hook #'sh--maybe-here-document t)))
ac59aed8
RS
4308\f
4309;; various other commands
4310
ac59aed8 4311(defun sh-beginning-of-command ()
ff46c759 4312 ;; FIXME: Redefine using SMIE.
ac59aed8
RS
4313 "Move point to successive beginnings of commands."
4314 (interactive)
4315 (if (re-search-backward sh-beginning-of-command nil t)
4316 (goto-char (match-beginning 2))))
4317
ac59aed8 4318(defun sh-end-of-command ()
ff46c759 4319 ;; FIXME: Redefine using SMIE.
ac59aed8
RS
4320 "Move point to successive ends of commands."
4321 (interactive)
4322 (if (re-search-forward sh-end-of-command nil t)
4323 (goto-char (match-end 1))))
4324
bdd5fa99
RS
4325;; Backslashification. Stolen from make-mode.el.
4326
4327(defun sh-backslash-region (from to delete-flag)
4328 "Insert, align, or delete end-of-line backslashes on the lines in the region.
4329With no argument, inserts backslashes and aligns existing backslashes.
4330With an argument, deletes the backslashes.
4331
4332This function does not modify the last line of the region if the region ends
4333right at the start of the following line; it does not modify blank lines
546e2f6f 4334at the start of the region. So you can put the region around an entire
bdd5fa99
RS
4335shell command and conveniently use this command."
4336 (interactive "r\nP")
4337 (save-excursion
4338 (goto-char from)
4339 (let ((column sh-backslash-column)
4340 (endmark (make-marker)))
4341 (move-marker endmark to)
4342 ;; Compute the smallest column number past the ends of all the lines.
4343 (if sh-backslash-align
4344 (progn
4345 (if (not delete-flag)
4346 (while (< (point) to)
4347 (end-of-line)
4348 (if (= (preceding-char) ?\\)
4349 (progn (forward-char -1)
4350 (skip-chars-backward " \t")))
4351 (setq column (max column (1+ (current-column))))
4352 (forward-line 1)))
4353 ;; Adjust upward to a tab column, if that doesn't push
4354 ;; past the margin.
4355 (if (> (% column tab-width) 0)
4356 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
4357 tab-width)))
4358 (if (< adjusted (window-width))
4359 (setq column adjusted))))))
4360 ;; Don't modify blank lines at start of region.
4361 (goto-char from)
4362 (while (and (< (point) endmark) (eolp))
4363 (forward-line 1))
4364 ;; Add or remove backslashes on all the lines.
4365 (while (and (< (point) endmark)
4366 ;; Don't backslashify the last line
4367 ;; if the region ends right at the start of the next line.
4368 (save-excursion
4369 (forward-line 1)
4370 (< (point) endmark)))
4371 (if (not delete-flag)
4372 (sh-append-backslash column)
4373 (sh-delete-backslash))
4374 (forward-line 1))
4375 (move-marker endmark nil))))
4376
4377(defun sh-append-backslash (column)
4378 (end-of-line)
4379 ;; Note that "\\\\" is needed to get one backslash.
4380 (if (= (preceding-char) ?\\)
4381 (progn (forward-char -1)
4382 (delete-horizontal-space)
4383 (indent-to column (if sh-backslash-align nil 1)))
4384 (indent-to column (if sh-backslash-align nil 1))
4385 (insert "\\")))
4386
4387(defun sh-delete-backslash ()
4388 (end-of-line)
4389 (or (bolp)
4390 (progn
4391 (forward-char -1)
4392 (if (looking-at "\\\\")
4393 (delete-region (1+ (point))
4394 (progn (skip-chars-backward " \t") (point)))))))
4395
f7c7053e 4396(provide 'sh-script)
43c89a96 4397
f964dfcb 4398;;; sh-script.el ends here