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