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