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