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