1 ;;; sh-script.el --- shell-script editing commands for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1993-1997, 1999, 2001-2015 Free Software Foundation,
6 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
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/>.
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.
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.
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,
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:
70 ;; This shows what variable controls the indentation of the current
71 ;; line and its value.
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
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
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
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
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 "$#".
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.
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
204 (require 'executable
)
206 (autoload 'comint-completion-at-point
"comint")
207 (autoload 'comint-filename-completion
"comint")
208 (autoload 'shell-command-completion
"shell")
209 (autoload 'shell-environment-variable-completion
"shell")
211 (defvar font-lock-comment-face
)
212 (defvar font-lock-set-defaults
)
213 (defvar font-lock-string-face
)
217 "Shell programming utilities."
220 (defgroup sh-script nil
222 :link
'(custom-group-link :tag
"Font Lock Faces group" font-lock-faces
)
227 (defcustom sh-ancestor-alist
248 "Alist showing the direct ancestor of various shells.
249 This is the basis for `sh-feature'. See also `sh-alias-alist'.
250 By default we have the following three hierarchies:
253 jcsh C Shell with Job Control
255 itcsh Ian's TENEX C Shell
260 dash Debian Almquist Shell
261 jsh Bourne Shell with Job Control
262 bash GNU Bourne Again Shell
265 dtksh CDE Desktop Korn Shell
266 pdksh Public Domain Korn Shell
267 mksh MirOS BSD Korn Shell
268 wksh Window Korn Shell
270 oash SCO OA (curses) Shell
271 posix IEEE 1003.2 Shell Standard
273 :type
'(repeat (cons symbol symbol
))
274 :version
"24.4" ; added dash
277 (defcustom sh-alias-alist
278 (append (if (eq system-type
'gnu
/linux
)
281 ;; for the time being
285 ;; Android's system shell
286 ("^/system/bin/sh$" . mksh
)))
287 "Alist for transforming shell names to what they really are.
288 Use this where the name of the executable doesn't correspond to
289 the type of shell it really is. Keys are regular expressions
290 matched against the full path of the interpreter. (For backward
291 compatibility, keys may also be symbols, which are matched
292 against the interpreter's basename. The values are symbols
294 :type
'(repeat (cons (radio
295 (regexp :tag
"Regular expression")
296 (symbol :tag
"Basename"))
297 (symbol :tag
"Shell")))
301 (defcustom sh-shell-file
303 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
304 ;; the executable extension, so comparisons with the list of
305 ;; known shells work.
306 (and (memq system-type
'(ms-dos windows-nt
))
307 (let* ((shell (getenv "SHELL"))
309 (and shell
(file-name-nondirectory shell
))))
310 ;; shell-script mode doesn't support DOS/Windows shells,
311 ;; so use the default instead.
313 (member (downcase shell-base
)
314 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
317 (file-name-sans-extension (downcase shell
)))))
320 "The executable file name for the shell being programmed."
325 (defcustom sh-shell-arg
326 ;; bash does not need any options when run in a shell script,
330 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
332 ;; -p means don't initialize functions from the environment.
334 ;; Someone proposed -motif, but we don't want to encourage
335 ;; use of a non-free widget set.
337 ;; -f means don't run .zshrc.
339 "Single argument string for the magic number. See `sh-feature'."
340 :type
'(repeat (cons (symbol :tag
"Shell")
341 (choice (const :tag
"No Arguments" nil
)
342 (string :tag
"Arguments")
343 (sexp :format
"Evaluate: %v"))))
346 (defcustom sh-imenu-generic-expression
351 "^\\s-*function\\s-+\\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*\\(?:()\\)?"
355 "^\\s-*\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*()"
358 "Alist of regular expressions for recognizing shell function definitions.
359 See `sh-feature' and `imenu-generic-expression'."
360 :type
'(alist :key-type
(symbol :tag
"Shell")
361 :value-type
(alist :key-type
(choice :tag
"Title"
363 (const :tag
"None" nil
))
365 (repeat :tag
"Regexp, index..." sexp
)))
369 (defun sh-current-defun-name ()
370 "Find the name of function or variable at point.
371 For use in `add-log-current-defun-function'."
374 (when (re-search-backward
378 "^\\s-*function\\s-+\\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*\\(?:()\\)?"
381 "^\\s-*\\([[:alpha:]_][[:alnum:]_]*\\)\\s-*()"
384 "^\\([[:alpha:]_][[:alnum:]_]*\\)="
387 (or (match-string-no-properties 1)
388 (match-string-no-properties 2)
389 (match-string-no-properties 3)))))
391 (defvar sh-shell-variables nil
392 "Alist of shell variable names that should be included in completion.
393 These are used for completion in addition to all the variables named
394 in `process-environment'. Each element looks like (VAR . VAR), where
395 the car and cdr are the same symbol.")
397 (defvar sh-shell-variables-initialized nil
398 "Non-nil if `sh-shell-variables' is initialized.")
400 (defun sh-canonicalize-shell (shell)
401 "Convert a shell name SHELL to the one we should handle it as.
402 SHELL is a full path to the shell interpreter; return a shell
405 with shell
= (cond ((string-match "\\.exe\\'" shell
)
406 (substring shell
0 (match-beginning 0)))
408 with shell-base
= (intern (file-name-nondirectory shell
))
409 for
(key . value
) in sh-alias-alist
410 if
(and (stringp key
) (string-match key shell
)) return value
411 if
(eq key shell-base
) return value
412 finally return shell-base
))
414 (defvar sh-shell
(sh-canonicalize-shell sh-shell-file
)
415 "The shell being programmed. This is set by \\[sh-set-shell].")
416 ;;;###autoload(put 'sh-shell 'safe-local-variable 'symbolp)
418 (define-abbrev-table 'sh-mode-abbrev-table
())
421 ;; I turned off this feature because it doesn't permit typing commands
422 ;; in the usual way without help.
424 ;; '((csh sh-abbrevs shell
426 ;; "getopts" 'sh-while-getopts)
428 ;; (es sh-abbrevs shell
429 ;; "function" 'sh-function)
431 ;; (ksh88 sh-abbrevs sh
432 ;; "select" 'sh-select)
434 ;; (rc sh-abbrevs shell
436 ;; "function" 'sh-function)
438 ;; (sh sh-abbrevs shell
440 ;; "function" 'sh-function
442 ;; "getopts" 'sh-while-getopts)
444 ;; ;; The next entry is only used for defining the others
445 ;; (shell "for" sh-for
446 ;; "loop" sh-indexed-loop
448 ;; "tmpfile" sh-tmp-file
451 ;; (zsh sh-abbrevs ksh88
452 ;; "repeat" 'sh-repeat))
453 ;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
454 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
455 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
459 (defun sh-mode-syntax-table (table &rest list
)
460 "Copy TABLE and set syntax for successive CHARs according to strings S."
461 (setq table
(copy-syntax-table table
))
463 (modify-syntax-entry (pop list
) (pop list
) table
))
466 (defvar sh-mode-syntax-table
467 (sh-mode-syntax-table ()
473 ;; ?$ might also have a ". p" syntax. Both "'" and ". p" seem
474 ;; to work fine. This is needed so that dabbrev-expand
490 "The syntax table to use for Shell-Script mode.
491 This is buffer-local in every such buffer.")
493 (defvar sh-mode-syntax-table-input
495 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
498 (let ((map (make-sparse-keymap))
499 (menu-map (make-sparse-keymap)))
500 (define-key map
"\C-c(" 'sh-function
)
501 (define-key map
"\C-c\C-w" 'sh-while
)
502 (define-key map
"\C-c\C-u" 'sh-until
)
503 (define-key map
"\C-c\C-t" 'sh-tmp-file
)
504 (define-key map
"\C-c\C-s" 'sh-select
)
505 (define-key map
"\C-c\C-r" 'sh-repeat
)
506 (define-key map
"\C-c\C-o" 'sh-while-getopts
)
507 (define-key map
"\C-c\C-l" 'sh-indexed-loop
)
508 (define-key map
"\C-c\C-i" 'sh-if
)
509 (define-key map
"\C-c\C-f" 'sh-for
)
510 (define-key map
"\C-c\C-c" 'sh-case
)
511 (define-key map
"\C-c?" 'sh-show-indent
)
512 (define-key map
"\C-c=" 'sh-set-indent
)
513 (define-key map
"\C-c<" 'sh-learn-line-indent
)
514 (define-key map
"\C-c>" 'sh-learn-buffer-indent
)
515 (define-key map
"\C-c\C-\\" 'sh-backslash-region
)
517 (define-key map
"=" 'sh-assignment
)
518 (define-key map
"\C-c+" 'sh-add
)
519 (define-key map
"\C-\M-x" 'sh-execute-region
)
520 (define-key map
"\C-c\C-x" 'executable-interpret
)
521 (define-key map
"\C-c\C-n" 'sh-send-line-or-region-and-step
)
522 (define-key map
"\C-c\C-d" 'sh-cd-here
)
523 (define-key map
"\C-c\C-z" 'sh-show-shell
)
525 (define-key map
[remap delete-backward-char
]
526 'backward-delete-char-untabify
)
527 (define-key map
"\C-c:" 'sh-set-shell
)
528 (define-key map
[remap backward-sentence
] 'sh-beginning-of-command
)
529 (define-key map
[remap forward-sentence
] 'sh-end-of-command
)
530 (define-key map
[menu-bar sh-script
] (cons "Sh-Script" menu-map
))
531 (define-key menu-map
[sh-learn-buffer-indent
]
532 '(menu-item "Learn buffer indentation" sh-learn-buffer-indent
533 :help
"Learn how to indent the buffer the way it currently is."))
534 (define-key menu-map
[sh-learn-line-indent
]
535 '(menu-item "Learn line indentation" sh-learn-line-indent
536 :help
"Learn how to indent a line as it currently is indented"))
537 (define-key menu-map
[sh-show-indent
]
538 '(menu-item "Show indentation" sh-show-indent
539 :help
"Show the how the current line would be indented"))
540 (define-key menu-map
[sh-set-indent
]
541 '(menu-item "Set indentation" sh-set-indent
542 :help
"Set the indentation for the current line"))
544 (define-key menu-map
[sh-pair
]
545 '(menu-item "Insert braces and quotes in pairs"
547 :button
(:toggle .
(bound-and-true-p electric-pair-mode
))
548 :help
"Inserting a brace or quote automatically inserts the matching pair"))
550 (define-key menu-map
[sh-s0
] '("--"))
552 (define-key menu-map
[sh-function
]
553 '(menu-item "Function..." sh-function
554 :help
"Insert a function definition"))
555 (define-key menu-map
[sh-add
]
556 '(menu-item "Addition..." sh-add
557 :help
"Insert an addition of VAR and prefix DELTA for Bourne (type) shell"))
558 (define-key menu-map
[sh-until
]
559 '(menu-item "Until Loop" sh-until
560 :help
"Insert an until loop"))
561 (define-key menu-map
[sh-repeat
]
562 '(menu-item "Repeat Loop" sh-repeat
563 :help
"Insert a repeat loop definition"))
564 (define-key menu-map
[sh-while
]
565 '(menu-item "While Loop" sh-while
566 :help
"Insert a while loop"))
567 (define-key menu-map
[sh-getopts
]
568 '(menu-item "Options Loop" sh-while-getopts
569 :help
"Insert a while getopts loop."))
570 (define-key menu-map
[sh-indexed-loop
]
571 '(menu-item "Indexed Loop" sh-indexed-loop
572 :help
"Insert an indexed loop from 1 to n."))
573 (define-key menu-map
[sh-select
]
574 '(menu-item "Select Statement" sh-select
575 :help
"Insert a select statement "))
576 (define-key menu-map
[sh-if
]
577 '(menu-item "If Statement" sh-if
578 :help
"Insert an if statement"))
579 (define-key menu-map
[sh-for
]
580 '(menu-item "For Loop" sh-for
581 :help
"Insert a for loop"))
582 (define-key menu-map
[sh-case
]
583 '(menu-item "Case Statement" sh-case
584 :help
"Insert a case/switch statement"))
585 (define-key menu-map
[sh-s1
] '("--"))
586 (define-key menu-map
[sh-exec
]
587 '(menu-item "Execute region" sh-execute-region
588 :help
"Pass optional header and region to a subshell for noninteractive execution"))
589 (define-key menu-map
[sh-exec-interpret
]
590 '(menu-item "Execute script..." executable-interpret
591 :help
"Run script with user-specified args, and collect output in a buffer"))
592 (define-key menu-map
[sh-set-shell
]
593 '(menu-item "Set shell type..." sh-set-shell
594 :help
"Set this buffer's shell to SHELL (a string)"))
595 (define-key menu-map
[sh-backslash-region
]
596 '(menu-item "Backslash region" sh-backslash-region
597 :help
"Insert, align, or delete end-of-line backslashes on the lines in the region."))
599 "Keymap used in Shell-Script mode.")
601 (defvar sh-skeleton-pair-default-alist
'((?
( _ ?
)) (?\
))
602 (?
[ ?\s _ ?\s ?
]) (?\
])
604 "Value to use for `skeleton-pair-default-alist' in Shell-Script mode.")
606 (defcustom sh-dynamic-complete-functions
607 '(shell-environment-variable-completion
608 shell-command-completion
609 comint-filename-completion
)
610 "Functions for doing TAB dynamic completion."
611 :type
'(repeat function
)
614 (defcustom sh-assignment-regexp
615 `((csh .
"\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
616 ;; actually spaces are only supported in let/(( ... ))
617 (ksh88 .
,(concat "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?"
618 "[ \t]*\\(?:[-+*/%&|~^]\\|<<\\|>>\\)?="))
619 (bash .
"\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?\\+?=")
620 (rc .
"\\<\\([[:alnum:]_*]+\\)[ \t]*=")
621 (sh .
"\\<\\([[:alnum:]_]+\\)="))
622 "Regexp for the variable name and what may follow in an assignment.
623 First grouping matches the variable name. This is upto and including the `='
624 sign. See `sh-feature'."
625 :type
'(repeat (cons (symbol :tag
"Shell")
627 (sexp :format
"Evaluate: %v"))))
631 (defcustom sh-indentation
4
632 "The width for further indentation in Shell-Script mode."
635 (put 'sh-indentation
'safe-local-variable
'integerp
)
637 (defcustom sh-remember-variable-min
3
638 "Don't remember variables less than this length for completing reads."
643 (defvar sh-header-marker nil
644 "When non-nil is the end of header for prepending by \\[sh-execute-region].
645 That command is also used for setting this variable.")
646 (make-variable-buffer-local 'sh-header-marker
)
648 (defcustom sh-beginning-of-command
649 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~[:alnum:]:]\\)"
650 "Regexp to determine the beginning of a shell command.
651 The actual command starts at the beginning of the second \\(grouping\\)."
656 (defcustom sh-end-of-command
657 "\\([/~[:alnum:]:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
658 "Regexp to determine the end of a shell command.
659 The actual command ends at the end of the first \\(grouping\\)."
665 (defcustom sh-here-document-word
"EOF"
666 "Word to delimit here documents.
667 If the first character of this string is \"-\", this is taken as
668 part of the redirection operator, rather than part of the
669 word (that is, \"<<-\" instead of \"<<\"). This is a feature
670 used by some shells (for example Bash) to indicate that leading
671 tabs inside the here document should be ignored. In this case,
672 Emacs indents the initial body and end of the here document with
673 tabs, to the same level as the start (note that apart from this
674 there is no support for indentation of here documents). This
675 will only work correctly if `sh-basic-offset' is a multiple of
678 Any quote characters or leading whitespace in the word are
679 removed when closing the here document."
687 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
690 ;; customized this out of sheer bravado. not for the faint of heart.
691 ;; but it *did* have an asterisk in the docstring!
692 (defcustom sh-builtins
693 '((bash sh-append posix
694 "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
695 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
696 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
697 "source" "suspend" "typeset" "unalias"
699 "mapfile" "readarray" "coproc")
701 ;; The next entry is only used for defining the others
702 (bourne sh-append shell
703 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
707 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
708 "setenv" "source" "time" "unalias" "unhash")
710 (dtksh sh-append wksh
)
712 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
713 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
716 "bg" "fg" "jobs" "kill" "stop" "suspend")
719 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
721 (ksh88 sh-append bourne
722 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
723 "typeset" "unalias" "whence")
726 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
727 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
728 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
729 "wmtitle" "wrefresh")
731 (pdksh sh-append ksh88
737 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
741 "hash" "test" "type")
743 ;; The next entry is only used for defining the others
744 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
746 (wksh sh-append ksh88
747 ;; FIXME: This looks too much like a regexp. --Stef
751 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
752 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
753 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
754 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
755 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
757 "List of all shell builtins for completing read and fontification.
758 Note that on some systems not all builtins are available or some are
759 implemented as aliases. See `sh-feature'."
760 :type
'(repeat (cons (symbol :tag
"Shell")
761 (choice (repeat string
)
762 (sexp :format
"Evaluate: %v"))))
763 :version
"24.4" ; bash4 additions
768 (defcustom sh-leading-keywords
774 (es "true" "unwind-protect" "whatis")
778 (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
779 "List of keywords that may be immediately followed by a builtin or keyword.
780 Given some confusion between keywords and builtins depending on shell and
781 system, the distinction here has been based on whether they influence the
782 flow of control or syntax. See `sh-feature'."
783 :type
'(repeat (cons (symbol :tag
"Shell")
784 (choice (repeat string
)
785 (sexp :format
"Evaluate: %v"))))
789 (defcustom sh-other-keywords
790 '((bash sh-append bourne
791 "bye" "logout" "select")
793 ;; The next entry is only used for defining the others
798 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
799 "if" "logout" "onintr" "repeat" "switch" "then" "while")
801 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
802 "return" "throw" "while")
804 (ksh88 sh-append bourne
807 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
811 "done" "esac" "fi" "for" "in" "return")
813 ;; The next entry is only used for defining the others
814 (shell "break" "case" "continue" "exec" "exit")
818 "List of keywords not in `sh-leading-keywords'.
820 :type
'(repeat (cons (symbol :tag
"Shell")
821 (choice (repeat string
)
822 (sexp :format
"Evaluate: %v"))))
829 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
830 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
831 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
832 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
833 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
834 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
835 "HISTIGNORE" "history_control" "HISTSIZE"
836 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
837 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
838 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
839 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
840 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
841 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
842 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
845 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
846 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
847 "shell" "status" "time" "verbose")
850 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
851 "pid" "prompt" "signals")
857 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
858 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
862 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
865 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
869 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
871 ;; The next entry is only used for defining the others
872 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
873 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
874 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
875 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
878 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
879 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
880 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
881 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
882 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
883 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
884 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
885 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
889 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
890 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
891 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
892 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
893 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
894 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
895 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
896 "List of all shell variables available for completing read.
903 '((((min-colors 88) (class color
)
905 (:foreground
"yellow1" :weight bold
))
908 (:foreground
"yellow" :weight bold
))
911 (:foreground
"tan1" ))
914 "Face to show a here-document."
915 :group
'sh-indentation
)
917 ;; These colors are probably icky. It's just a placeholder though.
918 (defface sh-quoted-exec
919 '((((class color
) (background dark
))
920 (:foreground
"salmon"))
921 (((class color
) (background light
))
922 (:foreground
"magenta"))
925 "Face to show quoted execs like `blabla`."
926 :group
'sh-indentation
)
927 (define-obsolete-face-alias 'sh-heredoc-face
'sh-heredoc
"22.1")
928 (defvar sh-heredoc-face
'sh-heredoc
)
930 (defface sh-escaped-newline
'((t :inherit font-lock-string-face
))
931 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
935 (defvar sh-font-lock-keywords-var
936 '((csh sh-append shell
937 ("\\${?[#?]?\\([[:alpha:]_][[:alnum:]_]*\\|0\\)" 1
938 font-lock-variable-name-face
))
940 (es sh-append executable-font-lock-keywords
941 ("\\$#?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\)" 1
942 font-lock-variable-name-face
))
945 (bash sh-append sh
("\\$(\\(\\sw+\\)" (1 'sh-quoted-exec t
) ))
948 ("\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?@!]\\)" 2
949 font-lock-variable-name-face
)
951 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face
)
952 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
953 (1 font-lock-keyword-face
) (2 font-lock-function-name-face nil t
))
954 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
955 1 font-lock-negation-char-face
))
957 ;; The next entry is only used for defining the others
959 ;; Using font-lock-string-face here confuses sh-get-indent-info.
960 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline
)
961 ("\\\\[^[:alnum:]]" 0 font-lock-string-face
)
962 ("\\${?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\|[$*_]\\)" 1
963 font-lock-variable-name-face
))
965 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face
))
966 (rpm2 sh-append shell
967 ("^Summary:\\(.*\\)$" (1 font-lock-doc-face t
))
968 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face
)))
969 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
971 (defvar sh-font-lock-keywords-var-1
973 "Subdued level highlighting for Shell Script modes.")
975 (defvar sh-font-lock-keywords-var-2
()
976 "Gaudy level highlighting for Shell Script modes.")
978 ;; These are used for the syntax table stuff (derived from cperl-mode).
979 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
980 (defconst sh-st-punc
(string-to-syntax "."))
981 (defconst sh-here-doc-syntax
(string-to-syntax "|")) ;; generic string
984 (defconst sh-escaped-line-re
985 ;; Should match until the real end-of-continued-line, but if that is not
986 ;; possible (because we bump into EOB or the search bound), then we should
987 ;; match until the search bound.
988 "\\(?:\\(?:.*[^\\\n]\\)?\\(?:\\\\\\\\\\)*\\\\\n\\)*.*")
990 (defconst sh-here-doc-open-re
991 (concat "<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\|[-/~._]\\)+\\)"
992 sh-escaped-line-re
"\\(\n\\)")))
994 (defun sh--inside-noncommand-expression (pos)
996 (let ((ppss (syntax-ppss pos
)))
998 (goto-char (nth 1 ppss
))
1001 ;; ((...)) or $((...)) or $[...] or ${...}. Nested
1002 ;; parenthesis can occur inside the first of these forms, so
1003 ;; parse backward recursively.
1004 (`?\
( (eq ?\
( (char-before)))
1005 ((or `?\
{ `?\
[) (eq ?\$
(char-before))))
1006 (sh--inside-noncommand-expression (1- (point))))))))
1008 (defun sh-font-lock-open-heredoc (start string eol
)
1009 "Determine the syntax of the \\n after a <<EOF.
1010 START is the position of <<.
1011 STRING is the actual word used as delimiter (e.g. \"EOF\").
1012 INDENTED is non-nil if the here document's content (and the EOF mark) can
1013 be indented (i.e. a <<- was used rather than just <<).
1014 Point is at the beginning of the next line."
1015 (unless (or (memq (char-before start
) '(?
< ?
>))
1016 (sh-in-comment-or-string start
)
1017 (sh--inside-noncommand-expression start
))
1018 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
1019 ;; font-lock keywords to detect the end of this here document.
1020 (let ((str (replace-regexp-in-string "['\"]" "" string
))
1021 (ppss (save-excursion (syntax-ppss eol
))))
1023 ;; The \n not only starts the heredoc but also closes a comment.
1024 ;; Let's close the comment just before the \n.
1025 (put-text-property (1- eol
) eol
'syntax-table
'(12))) ;">"
1026 (if (or (nth 5 ppss
) (> (count-lines start eol
) 1))
1027 ;; If the sh-escaped-line-re part of sh-here-doc-open-re has matched
1028 ;; several lines, make sure we refontify them together.
1029 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
1030 ;; escaped), it means the right \n is actually further down.
1031 ;; Don't bother fixing it now, but place a multiline property so
1032 ;; that when jit-lock-context-* refontifies the rest of the
1033 ;; buffer, it also refontifies the current line with it.
1034 (put-text-property start
(1+ eol
) 'syntax-multiline t
))
1035 (put-text-property eol
(1+ eol
) 'sh-here-doc-marker str
)
1036 (prog1 sh-here-doc-syntax
1037 (goto-char (+ 2 start
))))))
1039 (defun sh-syntax-propertize-here-doc (end)
1040 (let ((ppss (syntax-ppss)))
1041 (when (eq t
(nth 3 ppss
))
1042 (let ((key (get-text-property (nth 8 ppss
) 'sh-here-doc-marker
))
1043 (case-fold-search nil
))
1044 (when (re-search-forward
1045 (concat "^\\([ \t]*\\)" (regexp-quote key
) "\\(\n\\)")
1047 (let ((eol (match-beginning 2)))
1048 (put-text-property eol
(1+ eol
)
1049 'syntax-table sh-here-doc-syntax
)))))))
1051 (defun sh-font-lock-quoted-subshell (limit)
1052 "Search for a subshell embedded in a string.
1053 Find all the unescaped \" characters within said subshell, remembering that
1054 subshells can nest."
1055 (when (eq ?
\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
1056 ;; bingo we have a $( or a ` inside a ""
1057 (let (;; `state' can be: double-quote, backquote, code.
1058 (state (if (eq (char-before) ?
`) 'backquote
'code
))
1060 ;; Stacked states in the context.
1061 (states '(double-quote)))
1062 (while (and state
(progn (skip-chars-forward "^'\\\\\"`$()" limit
)
1064 ;; unescape " inside a $( ... ) construct.
1068 (_ (forward-char 1) (skip-chars-forward "^'" limit
))))
1069 (?
\\ (forward-char 1))
1071 (`double-quote
(setq state
(pop states
)))
1072 (_ (push state states
) (setq state
'double-quote
)))
1073 (if state
(put-text-property (point) (1+ (point))
1074 'syntax-table
'(1))))
1076 (`backquote
(setq state
(pop states
)))
1077 (_ (push state states
) (setq state
'backquote
))))
1078 (?\$
(if (not (eq (char-after (1+ (point))) ?\
())
1082 (_ (push state states
) (setq state
'code
)))))
1085 (_ (push state states
) (setq state
'code
))))
1088 (_ (setq state
(pop states
)))))
1089 (_ (error "Internal error in sh-font-lock-quoted-subshell")))
1091 (when (< startpos
(line-beginning-position))
1092 (put-text-property startpos
(point) 'syntax-multiline t
)
1093 (add-hook 'syntax-propertize-extend-region-functions
1094 'syntax-propertize-multiline nil t
))
1098 (defun sh-is-quoted-p (pos)
1099 (and (eq (char-before pos
) ?
\\)
1100 (not (sh-is-quoted-p (1- pos
)))))
1102 (defun sh-font-lock-paren (start)
1103 (unless (nth 8 (syntax-ppss))
1107 ;; Skip through all patterns
1112 (forward-comment (- (point-max)))
1113 (when (and (eolp) (sh-is-quoted-p (point)))
1116 ;; Skip through one pattern
1118 (or (/= 0 (skip-syntax-backward "w_"))
1119 (/= 0 (skip-chars-backward "-$=?[]*@/\\\\"))
1120 (and (sh-is-quoted-p (1- (point)))
1121 (goto-char (- (point) 2)))
1122 (when (memq (char-before) '(?
\" ?
\' ?\
}))
1123 (condition-case nil
(progn (backward-sexp 1) t
)
1125 ;; Patterns can be preceded by an open-paren (bug#1320).
1126 (when (eq (char-before (point)) ?\
()
1128 (setq open
(point)))
1130 (forward-comment (- (point-max)))
1131 ;; Maybe we've bumped into an escaped newline.
1132 (sh-is-quoted-p (point)))
1134 (when (eq (char-before) ?|
)
1135 (backward-char 1) t
)))
1136 (and (> (point) (1+ (point-min)))
1137 (progn (backward-char 2)
1138 (if (> start
(line-end-position))
1139 (put-text-property (point) (1+ start
)
1140 'syntax-multiline t
))
1141 ;; FIXME: The `in' may just be a random argument to
1142 ;; a normal command rather than the real `in' keyword.
1143 ;; I.e. we should look back to try and find the
1144 ;; corresponding `case'.
1145 (and (looking-at ";[;&]\\|\\_<in")
1146 ;; ";; esac )" is a case that looks
1147 ;; like a case-pattern but it's really just a close
1148 ;; paren after a case statement. I.e. if we skipped
1149 ;; over `esac' just now, we're not looking
1150 ;; at a case-pattern.
1151 (not (looking-at "..[ \t\n]+esac[^[:word:]_]"))))
1154 (put-text-property open
(1+ open
) 'syntax-table sh-st-punc
))
1157 (defun sh-font-lock-backslash-quote ()
1158 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?
\')
1159 ;; In a '...' the backslash is not escaping.
1163 (defun sh-syntax-propertize-function (start end
)
1165 (sh-syntax-propertize-here-doc end
)
1167 (syntax-propertize-rules
1168 (sh-here-doc-open-re
1169 (2 (sh-font-lock-open-heredoc
1170 (match-beginning 0) (match-string 1) (match-beginning 2))))
1171 ("\\s|" (0 (prog1 nil
(sh-syntax-propertize-here-doc end
))))
1172 ;; A `#' begins a comment when it is unquoted and at the
1173 ;; beginning of a word. In the shell, words are separated by
1174 ;; metacharacters. The list of special chars is taken from
1175 ;; the single-unix spec of the shell command language (under
1176 ;; `quoting') but with `$' removed.
1177 ("\\(?:[^|&;<>()`\\\"' \t\n]\\|\\${\\)\\(#+\\)" (1 "_"))
1178 ;; In a '...' the backslash is not escaping.
1179 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1180 ;; Make sure $@ and $? are correctly recognized as sexps.
1181 ("\\$\\([?@]\\)" (1 "_"))
1182 ;; Distinguish the special close-paren in `case'.
1183 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1184 ;; Highlight (possibly nested) subshells inside "" quoted
1185 ;; regions correctly.
1186 ("\"\\(?:\\(?:[^\\\"]\\|\\\\.\\)*?\\)??\\(\\$(\\|`\\)"
1188 (if (nth 8 (save-excursion (syntax-ppss (match-beginning 0))))
1189 (goto-char (1+ (match-beginning 0)))
1190 ;; Save excursion because we want to also apply other
1191 ;; syntax-propertize rules within the affected region.
1193 (sh-font-lock-quoted-subshell end
)))))))
1195 (defun sh-font-lock-syntactic-face-function (state)
1196 (let ((q (nth 3 state
)))
1199 (if (eq q ?\
`) 'sh-quoted-exec font-lock-string-face
)
1201 font-lock-comment-face
)))
1203 (defgroup sh-indentation nil
1204 "Variables controlling indentation in shell scripts.
1206 Note: customizing these variables will not affect existing buffers if
1207 `sh-make-vars-local' is non-nil. See the documentation for
1208 variable `sh-make-vars-local', command `sh-make-vars-local'
1209 and command `sh-reset-indent-vars-to-global-values'."
1213 (defcustom sh-set-shell-hook nil
1214 "Hook run by `sh-set-shell'."
1218 (defcustom sh-mode-hook nil
1219 "Hook run by `sh-mode'."
1223 (defcustom sh-learn-basic-offset nil
1224 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1227 t means: only if there seems to be an obvious value.
1228 Anything else means: whenever we have a \"good guess\" as to the value."
1230 (const :tag
"Never" nil
)
1231 (const :tag
"Only if sure" t
)
1232 (const :tag
"If have a good guess" usually
))
1233 :group
'sh-indentation
)
1235 (defcustom sh-popup-occur-buffer nil
1236 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1237 If t it is always shown. If nil, it is shown only when there
1240 (const :tag
"Only when there are conflicts." nil
)
1241 (const :tag
"Always" t
))
1242 :group
'sh-indentation
)
1244 (defcustom sh-blink t
1245 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
1246 The position on the line is not necessarily meaningful.
1247 In some cases the line will be the matching keyword, but this is not
1250 :group
'sh-indentation
)
1252 (defcustom sh-first-lines-indent
0
1253 "The indentation of the first non-blank non-comment line.
1254 Usually 0 meaning first column.
1255 Can be set to a number, or to nil which means leave it as is."
1257 (const :tag
"Leave as is" nil
)
1258 (integer :tag
"Column number"
1259 :menu-tag
"Indent to this col (0 means first col)" ))
1260 :group
'sh-indentation
)
1263 (defcustom sh-basic-offset
4
1264 "The default indentation increment.
1265 This value is used for the `+' and `-' symbols in an indentation variable."
1267 :group
'sh-indentation
)
1268 (put 'sh-basic-offset
'safe-local-variable
'integerp
)
1270 (defcustom sh-indent-comment t
1271 "How a comment line is to be indented.
1272 nil means leave it as it is;
1273 t means indent it as a normal line, aligning it to previous non-blank
1275 a number means align to that column, e.g. 0 means first column."
1277 (const :tag
"Leave as is." nil
)
1278 (const :tag
"Indent as a normal line." t
)
1279 (integer :menu-tag
"Indent to this col (0 means first col)."
1280 :tag
"Indent to column number.") )
1282 :group
'sh-indentation
)
1285 (defvar sh-debug nil
1286 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1289 ;; Uncomment this defun and comment the defmacro for debugging.
1290 ;; (defun sh-debug (&rest args)
1291 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1293 ;; (apply 'message args)))
1294 (defmacro sh-debug
(&rest _args
))
1296 (defconst sh-symbol-list
1297 '((const :tag
"+ " :value
+
1298 :menu-tag
"+ Indent right by sh-basic-offset")
1299 (const :tag
"- " :value -
1300 :menu-tag
"- Indent left by sh-basic-offset")
1301 (const :tag
"++" :value
++
1302 :menu-tag
"++ Indent right twice sh-basic-offset")
1303 (const :tag
"--" :value --
1304 :menu-tag
"-- Indent left twice sh-basic-offset")
1305 (const :tag
"* " :value
*
1306 :menu-tag
"* Indent right half sh-basic-offset")
1307 (const :tag
"/ " :value
/
1308 :menu-tag
"/ Indent left half sh-basic-offset")))
1310 (defcustom sh-indent-for-else
0
1311 "How much to indent an `else' relative to its `if'. Usually 0."
1313 (integer :menu-tag
"A number (positive=>indent right)"
1315 (const :tag
"--") ;; separator!
1318 :group
'sh-indentation
)
1320 (defconst sh-number-or-symbol-list
1321 (append '((integer :menu-tag
"A number (positive=>indent right)"
1323 (const :tag
"--")) ; separator
1326 (defcustom sh-indent-for-fi
0
1327 "How much to indent a `fi' relative to its `if'. Usually 0."
1328 :type
`(choice ,@ sh-number-or-symbol-list
)
1329 :group
'sh-indentation
)
1331 (defcustom sh-indent-for-done
0
1332 "How much to indent a `done' relative to its matching stmt. Usually 0."
1333 :type
`(choice ,@ sh-number-or-symbol-list
)
1334 :group
'sh-indentation
)
1336 (defcustom sh-indent-after-else
'+
1337 "How much to indent a statement after an `else' statement."
1338 :type
`(choice ,@ sh-number-or-symbol-list
)
1339 :group
'sh-indentation
)
1341 (defcustom sh-indent-after-if
'+
1342 "How much to indent a statement after an `if' statement.
1343 This includes lines after `else' and `elif' statements, too, but
1344 does not affect the `else', `elif' or `fi' statements themselves."
1345 :type
`(choice ,@ sh-number-or-symbol-list
)
1346 :group
'sh-indentation
)
1348 (defcustom sh-indent-for-then
0
1349 "How much to indent a `then' relative to its `if'."
1350 :type
`(choice ,@ sh-number-or-symbol-list
)
1351 :group
'sh-indentation
)
1353 (defcustom sh-indent-for-do
0
1354 "How much to indent a `do' statement.
1355 This is relative to the statement before the `do', typically a
1356 `while', `until', `for', `repeat' or `select' statement."
1357 :type
`(choice ,@ sh-number-or-symbol-list
)
1358 :group
'sh-indentation
)
1360 (defcustom sh-indent-after-do
'+
1361 "How much to indent a line after a `do' statement.
1362 This is used when the `do' is the first word of the line.
1363 This is relative to the statement before the `do', typically a
1364 `while', `until', `for', `repeat' or `select' statement."
1365 :type
`(choice ,@ sh-number-or-symbol-list
)
1366 :group
'sh-indentation
)
1368 (defcustom sh-indent-after-loop-construct
'+
1369 "How much to indent a statement after a loop construct.
1371 This variable is used when the keyword `do' is on the same line as the
1372 loop statement (e.g., `until', `while' or `for').
1373 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1374 :type
`(choice ,@ sh-number-or-symbol-list
)
1375 :group
'sh-indentation
)
1378 (defcustom sh-indent-after-done
0
1379 "How much to indent a statement after a `done' keyword.
1380 Normally this is 0, which aligns the `done' to the matching
1381 looping construct line.
1382 Setting it non-zero allows you to have the `do' statement on a line
1383 by itself and align the done under to do."
1384 :type
`(choice ,@ sh-number-or-symbol-list
)
1385 :group
'sh-indentation
)
1387 (defcustom sh-indent-for-case-label
'+
1388 "How much to indent a case label statement.
1389 This is relative to the line containing the `case' statement."
1390 :type
`(choice ,@ sh-number-or-symbol-list
)
1391 :group
'sh-indentation
)
1393 (defcustom sh-indent-for-case-alt
'++
1394 "How much to indent statements after the case label.
1395 This is relative to the line containing the `case' statement."
1396 :type
`(choice ,@ sh-number-or-symbol-list
)
1397 :group
'sh-indentation
)
1400 (defcustom sh-indent-for-continuation
'+
1401 "How much to indent for a continuation statement."
1402 :type
`(choice ,@ sh-number-or-symbol-list
)
1403 :group
'sh-indentation
)
1405 (defcustom sh-indent-after-open
'+
1406 "How much to indent after a line with an opening parenthesis or brace.
1407 For an open paren after a function, `sh-indent-after-function' is used."
1408 :type
`(choice ,@ sh-number-or-symbol-list
)
1409 :group
'sh-indentation
)
1411 (defcustom sh-indent-after-function
'+
1412 "How much to indent after a function line."
1413 :type
`(choice ,@ sh-number-or-symbol-list
)
1414 :group
'sh-indentation
)
1416 ;; These 2 are for the rc shell:
1418 (defcustom sh-indent-after-switch
'+
1419 "How much to indent a `case' statement relative to the `switch' statement.
1420 This is for the rc shell."
1421 :type
`(choice ,@ sh-number-or-symbol-list
)
1422 :group
'sh-indentation
)
1424 (defcustom sh-indent-after-case
'+
1425 "How much to indent a statement relative to the `case' statement.
1426 This is for the rc shell."
1427 :type
`(choice ,@ sh-number-or-symbol-list
)
1428 :group
'sh-indentation
)
1430 (defcustom sh-backslash-column
48
1431 "Column in which `sh-backslash-region' inserts backslashes."
1435 (defcustom sh-backslash-align t
1436 "If non-nil, `sh-backslash-region' will align backslashes."
1440 ;; Internal use - not designed to be changed by the user:
1442 (defun sh-mkword-regexpr (word)
1443 "Make a regexp which matches WORD as a word.
1444 This specifically excludes an occurrence of WORD followed by
1445 punctuation characters like '-'."
1446 (concat word
"\\([^-[:alnum:]_]\\|$\\)"))
1448 (defconst sh-re-done
(sh-mkword-regexpr "done"))
1451 (defconst sh-kws-for-done
1452 '((sh .
( "while" "until" "for" ) )
1453 (bash .
( "while" "until" "for" "select" ) )
1454 (ksh88 .
( "while" "until" "for" "select" ) )
1455 (zsh .
( "while" "until" "for" "repeat" "select" ) ) )
1456 "Which keywords can match the word `done' in this shell.")
1459 (defconst sh-indent-supported
1463 "Indentation rule set to use for each shell type.")
1465 (defvar sh-indent-supported-here nil
1466 "Non-nil if we support indentation for the current buffer's shell type.")
1468 (defconst sh-var-list
1470 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1471 sh-indent-after-do sh-indent-after-done
1472 sh-indent-after-else
1474 sh-indent-after-loop-construct
1475 sh-indent-after-open
1477 sh-indent-for-case-alt
1478 sh-indent-for-case-label
1479 sh-indent-for-continuation
1486 "A list of variables used by script mode to control indentation.
1487 This list is used when switching between buffer-local and global
1488 values of variables, and for the commands using indentation styles.")
1490 (defvar sh-make-vars-local t
1491 "Controls whether indentation variables are local to the buffer.
1492 If non-nil, indentation variables are made local initially.
1493 If nil, you can later make the variables local by invoking
1494 command `sh-make-vars-local'.
1495 The default is t because I assume that in one Emacs session one is
1496 frequently editing existing scripts with different styles.")
1499 ;; inferior shell interaction
1500 ;; TODO: support multiple interactive shells
1501 (defvar-local sh-shell-process nil
1502 "The inferior shell process for interaction.")
1504 (defvar explicit-shell-file-name
)
1506 (defun sh-shell-process (force)
1507 "Get a shell process for interaction.
1508 If FORCE is non-nil and no process found, create one."
1509 (if (process-live-p sh-shell-process
)
1511 (setq sh-shell-process
1512 (let ((found nil
) proc
1513 (procs (process-list)))
1514 (while (and (not found
) procs
1515 (process-live-p (setq proc
(pop procs
)))
1516 (process-command proc
))
1517 (when (string-equal sh-shell
(file-name-nondirectory
1518 (car (process-command proc
))))
1523 (let ((explicit-shell-file-name sh-shell-file
))
1526 (defun sh-show-shell ()
1527 "Pop the shell interaction buffer."
1529 (pop-to-buffer (process-buffer (sh-shell-process t
))))
1531 (defun sh-send-text (text)
1532 "Send the text to the `sh-shell-process'."
1533 (comint-send-string (sh-shell-process t
) (concat text
"\n")))
1535 (defun sh-cd-here ()
1536 "Change directory in the current interaction shell to the current one."
1538 (sh-send-text (concat "cd " default-directory
)))
1540 (defun sh-send-line-or-region-and-step ()
1541 "Send the current line to the inferior shell and step to the next line.
1542 When the region is active, send the region instead."
1546 (setq from
(region-beginning)
1549 (setq from
(line-beginning-position)
1550 to
(line-end-position)
1552 (sh-send-text (buffer-substring-no-properties from to
))
1556 ;; mode-command and utility functions
1558 (defun sh-after-hack-local-variables ()
1559 (when (assq 'sh-shell file-local-variables-alist
)
1560 (sh-set-shell (if (symbolp sh-shell
)
1561 (symbol-name sh-shell
)
1565 (define-derived-mode sh-mode prog-mode
"Shell-script"
1566 "Major mode for editing shell scripts.
1567 This mode works for many shells, since they all have roughly the same syntax,
1568 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1569 Unless the file's magic number indicates the shell, your usual shell is
1570 assumed. Since filenames rarely give a clue, they are not further analyzed.
1572 This mode adapts to the variations between shells (see `sh-set-shell') by
1573 means of an inheritance based feature lookup (see `sh-feature'). This
1574 mechanism applies to all variables (including skeletons) that pertain to
1575 shell-specific features.
1577 The default style of this mode is that of Rosenblatt's Korn shell book.
1578 The syntax of the statements varies with the shell being used. The
1579 following commands are available, based on the current shell's syntax:
1581 \\[sh-case] case statement
1583 \\[sh-function] function definition
1584 \\[sh-if] if statement
1585 \\[sh-indexed-loop] indexed loop from 1 to n
1586 \\[sh-while-getopts] while getopts loop
1587 \\[sh-repeat] repeat loop
1588 \\[sh-select] select loop
1589 \\[sh-until] until loop
1590 \\[sh-while] while loop
1592 For sh and rc shells indentation commands are:
1593 \\[sh-show-indent] Show the variable controlling this line's indentation.
1594 \\[sh-set-indent] Set then variable controlling this line's indentation.
1595 \\[sh-learn-line-indent] Change the indentation variable so this line
1596 would indent to the way it currently is.
1597 \\[sh-learn-buffer-indent] Set the indentation variables so the
1598 buffer indents as it currently is indented.
1601 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1602 \\[newline-and-indent] Delete unquoted space and indent new line same as this one.
1603 \\[sh-end-of-command] Go to end of successive commands.
1604 \\[sh-beginning-of-command] Go to beginning of successive commands.
1605 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1606 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1608 `sh-electric-here-document-mode' controls whether insertion of two
1609 unquoted < insert a here document.
1611 If you generally program a shell different from your login shell you can
1612 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1613 indicate what shell it is use `sh-alias-alist' to translate.
1615 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1616 with your script for an edit-interpret-debug cycle."
1617 (make-local-variable 'sh-shell-file
)
1618 (make-local-variable 'sh-shell
)
1620 (setq-local skeleton-pair-default-alist
1621 sh-skeleton-pair-default-alist
)
1622 (setq-local skeleton-end-hook
1623 (lambda () (or (eolp) (newline) (indent-relative))))
1625 (setq-local paragraph-start
(concat page-delimiter
"\\|$"))
1626 (setq-local paragraph-separate
(concat paragraph-start
"\\|#!/"))
1627 (setq-local comment-start
"# ")
1628 (setq-local comment-start-skip
"#+[\t ]*")
1629 (setq-local local-abbrev-table sh-mode-abbrev-table
)
1630 (setq-local comint-dynamic-complete-functions
1631 sh-dynamic-complete-functions
)
1632 (add-hook 'completion-at-point-functions
'comint-completion-at-point nil t
)
1633 ;; we can't look if previous line ended with `\'
1634 (setq-local comint-prompt-regexp
"^[ \t]*")
1635 (setq-local imenu-case-fold-search nil
)
1636 (setq font-lock-defaults
1637 `((sh-font-lock-keywords
1638 sh-font-lock-keywords-1 sh-font-lock-keywords-2
)
1640 ((?
/ .
"w") (?~ .
"w") (?. .
"w") (?- .
"w") (?_ .
"w")) nil
1641 (font-lock-syntactic-face-function
1642 . sh-font-lock-syntactic-face-function
)))
1643 (setq-local syntax-propertize-function
#'sh-syntax-propertize-function
)
1644 (add-hook 'syntax-propertize-extend-region-functions
1645 #'syntax-propertize-multiline
'append
'local
)
1646 (sh-electric-here-document-mode 1)
1647 (setq-local skeleton-pair-alist
'((?
` _ ?
`)))
1648 (setq-local skeleton-pair-filter-function
'sh-quoted-p
)
1649 (setq-local skeleton-further-elements
1650 '((< '(- (min sh-indentation
(current-column))))))
1651 (setq-local skeleton-filter-function
'sh-feature
)
1652 (setq-local skeleton-newline-indent-rigidly t
)
1653 (setq-local defun-prompt-regexp
1654 (concat "^\\(function[ \t]\\|[[:alnum:]]+[ \t]+()[ \t]+\\)"))
1655 (setq-local add-log-current-defun-function
#'sh-current-defun-name
)
1656 (add-hook 'completion-at-point-functions
1657 #'sh-completion-at-point-function nil t
)
1658 ;; Parse or insert magic number for exec, and set all variables depending
1659 ;; on the shell thus determined.
1661 (cond ((save-excursion
1662 (goto-char (point-min))
1663 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1665 ((not buffer-file-name
) sh-shell-file
)
1666 ;; Checks that use `buffer-file-name' follow.
1667 ((string-match "\\.m?spec\\'" buffer-file-name
) "rpm")
1668 ((string-match "[.]sh\\>" buffer-file-name
) "sh")
1669 ((string-match "[.]bash\\>" buffer-file-name
) "bash")
1670 ((string-match "[.]ksh\\>" buffer-file-name
) "ksh")
1671 ((string-match "[.]csh\\>" buffer-file-name
) "csh")
1672 ((equal (file-name-nondirectory buffer-file-name
) ".profile") "sh")
1675 (add-hook 'hack-local-variables-hook
1676 #'sh-after-hack-local-variables nil t
))
1679 (defalias 'shell-script-mode
'sh-mode
)
1682 (defun sh-font-lock-keywords (&optional keywords
)
1683 "Function to get simple fontification based on `sh-font-lock-keywords'.
1684 This adds rules for comments and assignments."
1685 (sh-feature sh-font-lock-keywords-var
1686 (when (stringp (sh-feature sh-assignment-regexp
))
1688 `((,(sh-feature sh-assignment-regexp
)
1689 1 font-lock-variable-name-face
)
1692 ,@executable-font-lock-keywords
)))))
1694 (defun sh-font-lock-keywords-1 (&optional builtins
)
1695 "Function to get better fontification including keywords."
1696 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1697 (regexp-opt (sh-feature sh-leading-keywords
) t
)
1699 (regexp-opt (append (sh-feature sh-leading-keywords
)
1700 (sh-feature sh-other-keywords
))
1702 (sh-font-lock-keywords
1704 `((,(concat keywords
"[ \t]+\\)?"
1705 (regexp-opt (sh-feature sh-builtins
) t
)
1707 (2 font-lock-keyword-face nil t
)
1708 (6 font-lock-builtin-face
))
1709 ,@(sh-feature sh-font-lock-keywords-var-2
)))
1710 (,(concat keywords
"\\)\\>")
1711 2 font-lock-keyword-face
)
1712 ,@(sh-feature sh-font-lock-keywords-var-1
)))))
1714 (defun sh-font-lock-keywords-2 ()
1715 "Function to get better fontification including keywords and builtins."
1716 (sh-font-lock-keywords-1 t
))
1720 (defun sh--vars-before-point ()
1723 (while (re-search-backward "^[ \t]*\\([[:alnum:]_]+\\)=" nil t
)
1724 (push (match-string 1) vars
))
1727 ;; (defun sh--var-completion-table (string pred action)
1728 ;; (complete-with-action action (sh--vars-before-point) string pred))
1730 (defun sh--cmd-completion-table (string pred action
)
1732 (append (when (fboundp 'imenu--make-index-alist
)
1733 (mapcar #'car
(imenu--make-index-alist)))
1734 (mapcar (lambda (v) (concat v
"="))
1735 (sh--vars-before-point))
1736 (locate-file-completion-table
1737 exec-path exec-suffixes string pred t
)
1738 '("if" "while" "until" "for"))))
1739 (complete-with-action action cmds string pred
)))
1741 (defun sh-completion-at-point-function ()
1743 (skip-chars-forward "[:alnum:]_")
1745 (_ (skip-chars-backward "[:alnum:]_"))
1748 ((eq (char-before) ?$
)
1749 (list start end
(sh--vars-before-point)))
1750 ((sh-smie--keyword-p)
1751 (list start end
#'sh--cmd-completion-table
))))))
1753 ;;; Indentation and navigation with SMIE.
1757 ;; The SMIE code should generally be preferred, but it currently does not obey
1758 ;; the various indentation custom-vars, and it misses some important features
1759 ;; of the old code, mostly: sh-learn-line/buffer-indent, sh-show-indent,
1760 ;; sh-name/save/load-style.
1761 (defvar sh-use-smie t
1762 "Whether to use the SMIE code for navigation and indentation.")
1764 (defun sh-smie--keyword-p ()
1765 "Non-nil if we're at a keyword position.
1766 A keyword position is one where if we're looking at something that looks
1767 like a keyword, then it is a keyword."
1768 (let ((prev (funcall smie-backward-token-function
)))
1769 (if (zerop (length prev
))
1770 (looking-back "\\`\\|\\s(" (1- (point)))
1771 (assoc prev smie-grammar
))))
1773 (defun sh-smie--newline-semi-p (&optional tok
)
1774 "Return non-nil if a newline should be treated as a semi-colon.
1775 Here we assume that a newline should be treated as a semi-colon unless it
1776 comes right after a special keyword.
1777 This function does not pay attention to line-continuations.
1778 If TOK is nil, point should be before the newline; otherwise, TOK is the token
1779 before the newline and in that case point should be just before the token."
1782 (setq tok
(funcall smie-backward-token-function
)))
1783 (if (and (zerop (length tok
))
1784 (looking-back "\\s(" (1- (point))))
1786 (not (numberp (nth 2 (assoc tok smie-grammar
)))))))
1788 ;;;; SMIE support for `sh'.
1790 (defconst sh-smie-sh-grammar
1791 (smie-prec2->grammar
1793 '((exp) ;A constant, or a $var, or a sequence of them...
1794 (cmd ("case" exp
"in" branches
"esac")
1795 ("if" cmd
"then" cmd
"fi")
1796 ("if" cmd
"then" cmd
"else" cmd
"fi")
1797 ("if" cmd
"then" cmd
"elif" cmd
"then" cmd
"fi")
1798 ("if" cmd
"then" cmd
"elif" cmd
"then" cmd
"else" cmd
"fi")
1799 ("if" cmd
"then" cmd
"elif" cmd
"then" cmd
1800 "elif" cmd
"then" cmd
"else" cmd
"fi")
1801 ("while" cmd
"do" cmd
"done")
1802 ("until" cmd
"do" cmd
"done")
1803 ("for" exp
"in" cmd
"do" cmd
"done")
1804 ("for" exp
"do" cmd
"done")
1805 ("select" exp
"in" cmd
"do" cmd
"done") ;bash&zsh&ksh88.
1806 ("repeat" exp
"do" cmd
"done") ;zsh.
1807 (exp "always" exp
) ;zsh.
1808 (cmd "|" cmd
) (cmd "|&" cmd
)
1809 (cmd "&&" cmd
) (cmd "||" cmd
)
1810 (cmd ";" cmd
) (cmd "&" cmd
))
1811 (rpattern (rpattern "|" rpattern
))
1812 (pattern (rpattern) ("case-(" rpattern
))
1813 (branches (branches ";;" branches
)
1814 (branches ";&" branches
) (branches ";;&" branches
) ;bash.
1815 (pattern "case-)" cmd
)))
1816 '((assoc ";;" ";&" ";;&"))
1817 '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
1819 (defconst sh-smie--sh-operators
1820 (delq nil
(mapcar (lambda (x)
1823 (not (string-match "\\`[a-z]" x
))
1825 sh-smie-sh-grammar
)))
1827 (defconst sh-smie--sh-operators-re
(regexp-opt sh-smie--sh-operators
))
1828 (defconst sh-smie--sh-operators-back-re
1829 (concat "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*"
1830 "\\(" sh-smie--sh-operators-re
"\\)"))
1832 (defun sh-smie--sh-keyword-in-p ()
1833 "Assuming we're looking at \"in\", return non-nil if it's a keyword.
1834 Does not preserve point."
1835 (let ((forward-sexp-function nil
)
1836 (words nil
) ;We've seen words.
1837 (newline nil
) ;We've seen newlines after the words.
1841 (setq prev
(funcall smie-backward-token-function
))
1843 ((zerop (length prev
))
1845 (newline (cl-assert words
) (setq res
'word
))
1846 ((bobp) (setq res
'word
))
1851 (scan-error (setq res
'unknown
))))))
1853 (if words
(setq newline t
)
1854 (setq res
'keyword
)))
1855 ((member prev
'("case" "for" "select")) (setq res
'keyword
))
1856 ((assoc prev smie-grammar
) (setq res
'word
))
1859 (progn (cl-assert words
) (setq res
'word
))
1863 (defun sh-smie--sh-keyword-p (tok)
1864 "Non-nil if TOK (at which we're looking) really is a keyword."
1866 ((looking-at "[[:alnum:]_]+=") nil
)
1867 ((equal tok
"in") (sh-smie--sh-keyword-in-p))
1868 (t (sh-smie--keyword-p))))
1870 (defun sh-smie--default-forward-token ()
1871 (forward-comment (point-max))
1872 (buffer-substring-no-properties
1874 (progn (if (zerop (skip-syntax-forward "."))
1875 (while (progn (skip-syntax-forward "w_'")
1876 (looking-at "\\\\"))
1880 (defun sh-smie--default-backward-token ()
1881 (forward-comment (- (point)))
1883 (n (skip-syntax-backward ".")))
1887 (if (eq -
1 (%
(skip-syntax-backward "\\") 2))
1892 (progn (skip-syntax-backward "w_'")
1893 (or (not (zerop (skip-syntax-backward "\\")))
1894 (when (eq ?
\\ (char-before (1- (point))))
1897 (if (eq -
1 (%
(skip-syntax-backward "\\") 2))
1901 (goto-char (- (point) (%
(skip-syntax-backward "\\") 2))))
1902 (buffer-substring-no-properties (point) pos
)))
1904 (defun sh-smie-sh-forward-token ()
1905 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
1907 (skip-chars-backward " \t")
1909 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
1910 ;; Right before a here-doc.
1911 (let ((forward-sexp-function nil
))
1913 ;; Pretend the here-document is a "newline representing a
1914 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1916 (let ((semi (sh-smie--newline-semi-p)))
1918 (if (or semi
(eobp)) ";"
1919 (sh-smie-sh-forward-token))))
1920 (forward-comment (point-max))
1922 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-sh-forward-token))
1923 ((looking-at sh-smie--sh-operators-re
)
1924 (goto-char (match-end 0))
1925 (let ((tok (match-string-no-properties 0)))
1926 (if (and (memq (aref tok
(1- (length tok
))) '(?\
; ?\& ?\|))
1927 (looking-at "[ \t]*\\(?:#\\|$\\)"))
1931 (let* ((pos (point))
1932 (tok (sh-smie--default-forward-token)))
1934 ((equal tok
")") "case-)")
1935 ((equal tok
"(") "case-(")
1936 ((and tok
(string-match "\\`[a-z]" tok
)
1937 (assoc tok smie-grammar
)
1941 (sh-smie--sh-keyword-p tok
))))
1945 (defun sh-smie--looking-back-at-continuation-p ()
1947 (and (if (eq (char-before) ?
\n) (progn (forward-char -
1) t
) (eolp))
1948 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
1949 (line-beginning-position)))))
1951 (defun sh-smie-sh-backward-token ()
1952 (let ((bol (line-beginning-position)))
1953 (forward-comment (- (point)))
1955 ((and (bolp) (not (bobp))
1956 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
1957 (not (nth 3 (syntax-ppss))))
1958 ;; Right after a here-document.
1959 (let ((forward-sexp-function nil
))
1961 ;; Pretend the here-document is a "newline representing a
1962 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1966 ((sh-smie--looking-back-at-continuation-p)
1968 (funcall smie-backward-token-function
))
1969 ((sh-smie--newline-semi-p) ";")
1970 (t (funcall smie-backward-token-function
))))
1971 ((looking-back sh-smie--sh-operators-back-re
1972 (line-beginning-position) 'greedy
)
1973 (goto-char (match-beginning 1))
1974 (match-string-no-properties 1))
1976 (let ((tok (sh-smie--default-backward-token)))
1978 ((equal tok
")") "case-)")
1979 ((equal tok
"(") "case-(")
1980 ((and tok
(string-match "\\`[a-z]" tok
)
1981 (assoc tok smie-grammar
)
1982 (not (save-excursion (sh-smie--sh-keyword-p tok
))))
1986 (defcustom sh-indent-after-continuation t
1987 "If non-nil, try to make sure text is indented after a line continuation."
1990 :group
'sh-indentation
)
1992 (defun sh-smie--continuation-start-indent ()
1993 "Return the initial indentation of a continued line.
1994 May return nil if the line should not be treated as continued."
1997 (unless (sh-smie--looking-back-at-continuation-p)
1998 (current-indentation))))
2000 (defun sh-smie-sh-rules (kind token
)
2001 (pcase (cons kind token
)
2002 (`(:elem . basic
) sh-indentation
)
2003 (`(:after .
"case-)") (- (sh-var-value 'sh-indent-for-case-alt
)
2004 (sh-var-value 'sh-indent-for-case-label
)))
2005 ((and `(:before .
,_
)
2006 ;; After a line-continuation, make sure the rest is indented.
2007 (guard sh-indent-after-continuation
)
2008 (guard (save-excursion
2010 (skip-chars-backward " \t")
2011 (sh-smie--looking-back-at-continuation-p))))
2012 (let initial
(sh-smie--continuation-start-indent))
2013 (guard (let* ((sh-indent-after-continuation nil
)
2014 (indent (smie-indent-calculate)))
2015 (and (numberp indent
) (numberp initial
)
2016 (<= indent initial
)))))
2017 `(column .
,(+ initial sh-indentation
)))
2018 (`(:before .
,(or `"(" `"{" `"[" "while" "if" "for" "case"))
2019 (if (not (smie-rule-prev-p "&&" "||" "|"))
2020 (when (smie-rule-hanging-p)
2022 (unless (smie-rule-bolp)
2023 (while (equal "|" (nth 2 (smie-backward-sexp 'halfexp
))))
2024 `(column .
,(smie-indent-virtual)))))
2025 ;; FIXME: Maybe this handling of ;; should be made into
2026 ;; a smie-rule-terminator function that takes the substitute ";" as arg.
2027 (`(:before .
,(or `";;" `";&" `";;&"))
2028 (if (and (smie-rule-bolp) (looking-at ";;?&?[ \t]*\\(#\\|$\\)"))
2029 (cons 'column
(smie-indent-keyword ";"))
2030 (smie-rule-separator kind
)))
2031 (`(:after .
,(or `";;" `";&" `";;&"))
2032 (with-demoted-errors
2033 (smie-backward-sexp token
)
2035 (if (or (smie-rule-bolp)
2037 (and (member (funcall smie-backward-token-function
)
2041 (smie-indent-calculate)))))
2042 (`(:before .
,(or `"|" `"&&" `"||"))
2043 (unless (smie-rule-parent-p token
)
2044 (smie-backward-sexp token
)
2045 `(column .
,(+ (funcall smie-rules-function
:elem
'basic
)
2046 (smie-indent-virtual)))))
2048 ;; Attempt at backward compatibility with the old config variables.
2049 (`(:before .
"fi") (sh-var-value 'sh-indent-for-fi
))
2050 (`(:before .
"done") (sh-var-value 'sh-indent-for-done
))
2051 (`(:after .
"else") (sh-var-value 'sh-indent-after-else
))
2052 (`(:after .
"if") (sh-var-value 'sh-indent-after-if
))
2053 (`(:before .
"then") (sh-var-value 'sh-indent-for-then
))
2054 (`(:before .
"do") (sh-var-value 'sh-indent-for-do
))
2056 (sh-var-value (if (smie-rule-hanging-p)
2057 'sh-indent-after-loop-construct
'sh-indent-after-do
)))
2058 ;; sh-indent-after-done: aligned completely differently.
2059 (`(:after .
"in") (sh-var-value 'sh-indent-for-case-label
))
2060 ;; sh-indent-for-continuation: Line continuations are handled differently.
2061 (`(:after .
,(or `"(" `"{" `"[")) (sh-var-value 'sh-indent-after-open
))
2062 ;; sh-indent-after-function: we don't handle it differently.
2065 ;; (defconst sh-smie-csh-grammar
2066 ;; (smie-prec2->grammar
2068 ;; '((exp) ;A constant, or a $var, or a sequence of them...
2070 ;; (cmd "else" "else-if" exp "then" elseifcmd))
2071 ;; (cmd ("switch" branches "endsw")
2073 ;; ("if" exp "then" cmd "endif")
2074 ;; ("if" exp "then" cmd "else" cmd "endif")
2075 ;; ("if" exp "then" elseifcmd "endif")
2076 ;; ;; ("if" exp "then" cmd "else" cmd "endif")
2077 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd "endif")
2078 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2079 ;; ;; "else" cmd "endif")
2080 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
2081 ;; ;; "else" "if" exp "then" cmd "endif")
2082 ;; ("while" cmd "end")
2083 ;; ("foreach" cmd "end")
2084 ;; (cmd "|" cmd) (cmd "|&" cmd)
2085 ;; (cmd "&&" cmd) (cmd "||" cmd)
2086 ;; (cmd ";" cmd) (cmd "&" cmd))
2087 ;; ;; This is a lie, but (combined with the corresponding disambiguation
2088 ;; ;; rule) it makes it more clear that `case' and `default' are the key
2089 ;; ;; separators and the `:' is a secondary tokens.
2090 ;; (branches (branches "case" branches)
2091 ;; (branches "default" branches)
2092 ;; (exp ":" branches)))
2093 ;; '((assoc "else" "then" "endif"))
2094 ;; '((assoc "case" "default") (nonassoc ":"))
2095 ;; '((assoc ";;" ";&" ";;&"))
2096 ;; '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2098 ;;;; SMIE support for `rc'.
2100 (defconst sh-smie-rc-grammar
2101 (smie-prec2->grammar
2103 '((exp) ;A constant, or a $var, or a sequence of them...
2104 (cmd (cmd "case" cmd
)
2107 ("for" exp
) ("while" exp
)
2108 (cmd "|" cmd
) (cmd "|&" cmd
)
2109 (cmd "&&" cmd
) (cmd "||" cmd
)
2110 (cmd ";" cmd
) (cmd "&" cmd
))
2111 (pattern (pattern "|" pattern
))
2112 (branches (branches ";;" branches
)
2113 (branches ";&" branches
) (branches ";;&" branches
) ;bash.
2114 (pattern "case-)" cmd
)))
2115 '((assoc ";;" ";&" ";;&"))
2116 '((assoc "case") (assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
2118 (defun sh-smie--rc-after-special-arg-p ()
2119 "Check if we're after the first arg of an if/while/for/... construct.
2120 Returns the construct's token and moves point before it, if so."
2121 (forward-comment (- (point)))
2122 (when (looking-back ")\\|\\_<not" (- (point) 3))
2124 (let ((forward-sexp-function nil
))
2126 (car (member (funcall smie-backward-token-function
)
2127 '("if" "for" "switch" "while")))))))
2129 (defun sh-smie--rc-newline-semi-p ()
2130 "Return non-nil if a newline should be treated as a semi-colon.
2131 Point should be before the newline."
2133 (let ((tok (funcall smie-backward-token-function
)))
2134 (if (or (when (equal tok
"not") (forward-word 1) t
)
2135 (and (zerop (length tok
)) (eq (char-before) ?\
))))
2136 (not (sh-smie--rc-after-special-arg-p))
2137 (sh-smie--newline-semi-p tok
)))))
2139 (defun sh-smie-rc-forward-token ()
2140 ;; FIXME: Code duplication with sh-smie-sh-forward-token.
2141 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
2143 (skip-chars-backward " \t")
2145 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
2146 ;; Right before a here-doc.
2147 (let ((forward-sexp-function nil
))
2149 ;; Pretend the here-document is a "newline representing a
2150 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2152 (let ((semi (sh-smie--rc-newline-semi-p)))
2154 (if (or semi
(eobp)) ";"
2155 (sh-smie-rc-forward-token))))
2156 (forward-comment (point-max))
2158 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-rc-forward-token))
2159 ;; ((looking-at sh-smie--rc-operators-re)
2160 ;; (goto-char (match-end 0))
2161 ;; (let ((tok (match-string-no-properties 0)))
2162 ;; (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
2163 ;; (looking-at "[ \t]*\\(?:#\\|$\\)"))
2164 ;; (forward-line 1))
2167 (let* ((pos (point))
2168 (tok (sh-smie--default-forward-token)))
2170 ;; ((equal tok ")") "case-)")
2171 ((and tok
(string-match "\\`[a-z]" tok
)
2172 (assoc tok smie-grammar
)
2176 (sh-smie--keyword-p))))
2180 (defun sh-smie-rc-backward-token ()
2181 ;; FIXME: Code duplication with sh-smie-sh-backward-token.
2182 (let ((bol (line-beginning-position)))
2183 (forward-comment (- (point)))
2185 ((and (bolp) (not (bobp))
2186 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
2187 (not (nth 3 (syntax-ppss))))
2188 ;; Right after a here-document.
2189 (let ((forward-sexp-function nil
))
2191 ;; Pretend the here-document is a "newline representing a
2192 ;; semi-colon", since the here-doc otherwise covers the newline(s).
2194 ((< (point) bol
) ;We skipped over a newline.
2196 ;; A continued line.
2198 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
2199 (line-beginning-position)))
2201 (funcall smie-backward-token-function
))
2202 ((sh-smie--rc-newline-semi-p) ";")
2203 (t (funcall smie-backward-token-function
))))
2204 ;; ((looking-back sh-smie--sh-operators-back-re
2205 ;; (line-beginning-position) 'greedy)
2206 ;; (goto-char (match-beginning 1))
2207 ;; (match-string-no-properties 1))
2209 (let ((tok (sh-smie--default-backward-token)))
2211 ;; ((equal tok ")") "case-)")
2212 ((and tok
(string-match "\\`[a-z]" tok
)
2213 (assoc tok smie-grammar
)
2214 (not (save-excursion (sh-smie--keyword-p))))
2218 (defun sh-smie-rc-rules (kind token
)
2219 (pcase (cons kind token
)
2220 (`(:elem . basic
) sh-indentation
)
2221 ;; (`(:after . "case") (or sh-indentation smie-indent-basic))
2223 (if (smie-rule-parent-p "case")
2224 (smie-rule-parent (sh-var-value 'sh-indent-after-case
))))
2227 (when (sh-smie--rc-after-special-arg-p)
2228 `(column .
,(current-column)))))
2229 (`(:before .
,(or `"(" `"{" `"["))
2230 (if (smie-rule-hanging-p) (smie-rule-parent)))
2231 ;; FIXME: SMIE parses "if (exp) cmd" as "(if ((exp) cmd))" so "cmd" is
2232 ;; treated as an arg to (exp) by default, which indents it all wrong.
2233 ;; To handle it right, we should extend smie-indent-exps so that the
2234 ;; preceding keyword can give special rules. Currently the only special
2235 ;; rule we have is the :list-intro hack, which we use here to align "cmd"
2236 ;; with "(exp)", which is rarely the right thing to do, but is better
2238 (`(:list-intro .
,(or `"for" `"if" `"while")) t
)
2239 ;; sh-indent-after-switch: handled implicitly by the default { rule.
2242 ;;; End of SMIE code.
2244 (defvar sh-regexp-for-done nil
2245 "A buffer-local regexp to match opening keyword for done.")
2247 (defvar sh-kw-alist nil
2248 "A buffer-local, since it is shell-type dependent, list of keywords.")
2250 ;; ( key-word first-on-this on-prev-line )
2251 ;; This is used to set `sh-kw-alist' which is a list of sublists each
2252 ;; having 3 elements:
2254 ;; a rule to check when the keyword appears on "this" line
2255 ;; a rule to check when the keyword appears on "the previous" line
2256 ;; The keyword is usually a string and is the first word on a line.
2257 ;; If this keyword appears on the line whose indentation is to be
2258 ;; calculated, the rule in element 2 is called. If this returns
2259 ;; non-zero, the resulting point (which may be changed by the rule)
2260 ;; is used as the default indentation.
2261 ;; If it returned false or the keyword was not found in the table,
2262 ;; then the keyword from the previous line is looked up and the rule
2263 ;; in element 3 is called. In this case, however,
2264 ;; `sh-get-indent-info' does not stop but may keep going and test
2265 ;; other keywords against rules in element 3. This is because the
2266 ;; preceding line could have, for example, an opening "if" and an
2267 ;; opening "while" keyword and we need to add the indentation offsets
2272 ("if" nil sh-handle-prev-if
)
2273 ("elif" sh-handle-this-else sh-handle-prev-else
)
2274 ("else" sh-handle-this-else sh-handle-prev-else
)
2275 ("fi" sh-handle-this-fi sh-handle-prev-fi
)
2276 ("then" sh-handle-this-then sh-handle-prev-then
)
2277 ("(" nil sh-handle-prev-open
)
2278 ("{" nil sh-handle-prev-open
)
2279 ("[" nil sh-handle-prev-open
)
2280 ("}" sh-handle-this-close nil
)
2281 (")" sh-handle-this-close nil
)
2282 ("]" sh-handle-this-close nil
)
2283 ("case" nil sh-handle-prev-case
)
2284 ("esac" sh-handle-this-esac sh-handle-prev-esac
)
2285 (case-label nil sh-handle-after-case-label
) ;; ???
2286 (";;" nil sh-handle-prev-case-alt-end
) ;; ???
2287 (";;&" nil sh-handle-prev-case-alt-end
) ;Like ";;" with diff semantics.
2288 (";&" nil sh-handle-prev-case-alt-end
) ;Like ";;" with diff semantics.
2289 ("done" sh-handle-this-done sh-handle-prev-done
)
2290 ("do" sh-handle-this-do sh-handle-prev-do
))
2292 ;; Note: we don't need specific stuff for bash and zsh shells;
2293 ;; the regexp `sh-regexp-for-done' handles the extra keywords
2294 ;; these shells use.
2296 ("{" nil sh-handle-prev-open
)
2297 ("}" sh-handle-this-close nil
)
2298 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case
))))
2302 (defun sh-set-shell (shell &optional no-query-flag insert-flag
)
2303 "Set this buffer's shell to SHELL (a string).
2304 When used interactively, insert the proper starting #!-line,
2305 and make the visited file executable via `executable-set-magic',
2306 perhaps querying depending on the value of `executable-query'.
2308 When this function is called noninteractively, INSERT-FLAG (the third
2309 argument) controls whether to insert a #!-line and think about making
2310 the visited file executable, and NO-QUERY-FLAG (the second argument)
2311 controls whether to query about making the visited file executable.
2313 Calls the value of `sh-set-shell-hook' if set."
2314 (interactive (list (completing-read
2315 (format "Shell \(default %s\): "
2317 ;; This used to use interpreter-mode-alist, but that is
2318 ;; no longer appropriate now that uses regexps.
2319 ;; Maybe there could be a separate variable that lists
2320 ;; the shells, used here and to construct i-mode-alist.
2321 ;; But the following is probably good enough:
2322 (append (mapcar (lambda (e) (symbol-name (car e
)))
2325 nil nil nil nil sh-shell-file
)
2326 (eq executable-query
'function
)
2328 (if (string-match "\\.exe\\'" shell
)
2329 (setq shell
(substring shell
0 (match-beginning 0))))
2330 (setq sh-shell
(sh-canonicalize-shell shell
))
2333 (executable-set-magic shell
(sh-feature sh-shell-arg
)
2334 no-query-flag insert-flag
)))
2335 (setq mode-line-process
(format "[%s]" sh-shell
))
2336 (setq-local sh-shell-variables nil
)
2337 (setq-local sh-shell-variables-initialized nil
)
2338 (setq-local imenu-generic-expression
2339 (sh-feature sh-imenu-generic-expression
))
2340 (let ((tem (sh-feature sh-mode-syntax-table-input
)))
2342 (setq-local sh-mode-syntax-table
2343 (apply 'sh-mode-syntax-table tem
))
2344 (set-syntax-table sh-mode-syntax-table
)))
2345 (dolist (var (sh-feature sh-variables
))
2346 (sh-remember-variable var
))
2347 (if (setq-local sh-indent-supported-here
2348 (sh-feature sh-indent-supported
))
2350 (message "Setting up indent for shell type %s" sh-shell
)
2351 (let ((mksym (lambda (name)
2352 (intern (format "sh-smie-%s-%s"
2353 sh-indent-supported-here name
)))))
2354 (add-function :around
(local 'smie--hanging-eolp-function
)
2356 (if (looking-at "[ \t]*\\\\\n")
2357 (goto-char (match-end 0))
2359 (smie-setup (symbol-value (funcall mksym
"grammar"))
2360 (funcall mksym
"rules")
2361 :forward-token
(funcall mksym
"forward-token")
2362 :backward-token
(funcall mksym
"backward-token")))
2364 (setq-local parse-sexp-lookup-properties t
)
2365 (setq-local sh-kw-alist
(sh-feature sh-kw
))
2366 (let ((regexp (sh-feature sh-kws-for-done
)))
2368 (setq-local sh-regexp-for-done
2369 (sh-mkword-regexpr (regexp-opt regexp t
)))))
2370 (message "setting up indent stuff")
2371 ;; sh-mode has already made indent-line-function local
2372 ;; but do it in case this is called before that.
2373 (setq-local indent-line-function
'sh-indent-line
))
2374 (if sh-make-vars-local
2375 (sh-make-vars-local))
2376 (message "Indentation setup for shell type %s" sh-shell
))
2377 (message "No indentation for this shell type.")
2378 (setq-local indent-line-function
'sh-basic-indent-line
))
2379 (when font-lock-mode
2380 (setq font-lock-set-defaults nil
)
2381 (font-lock-set-defaults)
2383 (setq sh-shell-process nil
)
2384 (run-hooks 'sh-set-shell-hook
))
2387 (defun sh-feature (alist &optional function
)
2388 "Index ALIST by the current shell.
2389 If ALIST isn't a list where every element is a cons, it is returned as is.
2390 Else indexing follows an inheritance logic which works in two ways:
2392 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
2393 the alist contains no value for the current shell.
2394 The ultimate default is always `sh'.
2396 - If the value thus looked up is a list starting with `sh-append',
2397 we call the function `sh-append' with the rest of the list as
2398 arguments, and use the value. However, the next element of the
2399 list is not used as-is; instead, we look it up recursively
2400 in ALIST to allow the function called to define the value for
2401 one shell to be derived from another shell.
2402 The value thus determined is physically replaced into the alist.
2404 If FUNCTION is non-nil, it is called with one argument,
2405 the value thus obtained, and the result is used instead."
2406 (or (if (consp alist
)
2407 ;; Check for something that isn't a valid alist.
2409 (while (and l
(consp (car l
)))
2413 (let ((orig-sh-shell sh-shell
))
2414 (let ((sh-shell sh-shell
)
2416 (while (and sh-shell
2417 (not (setq elt
(assq sh-shell alist
))))
2418 (setq sh-shell
(cdr (assq sh-shell sh-ancestor-alist
))))
2419 ;; If the shell is not known, treat it as sh.
2421 (setq elt
(assq 'sh alist
)))
2422 (setq val
(cdr elt
))
2423 (if (and (consp val
)
2424 (memq (car val
) '(sh-append sh-modify
)))
2427 ;; Refer to the value for a different shell,
2428 ;; as a kind of inheritance.
2429 (let ((sh-shell (car (cdr val
))))
2433 (setq sh-shell orig-sh-shell
2434 val
(funcall function val
)))
2439 ;; I commented this out because nobody calls it -- rms.
2440 ;;(defun sh-abbrevs (ancestor &rest list)
2441 ;; "If it isn't, define the current shell as abbrev table and fill that.
2442 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
2443 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
2444 ;;according to the remaining arguments NAMEi EXPANSIONi ...
2445 ;;EXPANSION may be either a string or a skeleton command."
2446 ;; (or (if (boundp sh-shell)
2447 ;; (symbol-value sh-shell))
2449 ;; (if (listp ancestor)
2450 ;; (nconc list ancestor))
2451 ;; (define-abbrev-table sh-shell ())
2452 ;; (if (vectorp ancestor)
2453 ;; (mapatoms (lambda (atom)
2455 ;; (define-abbrev (symbol-value sh-shell)
2456 ;; (symbol-name atom)
2457 ;; (symbol-value atom)
2458 ;; (symbol-function atom))))
2461 ;; (define-abbrev (symbol-value sh-shell)
2463 ;; (if (stringp (car (cdr list)))
2466 ;; (if (symbolp (car (cdr list)))
2467 ;; (car (cdr list))))
2468 ;; (setq list (cdr (cdr list)))))
2469 ;; (symbol-value sh-shell)))
2472 (defun sh-append (ancestor &rest list
)
2473 "Return list composed of first argument (a list) physically appended to rest."
2474 (nconc list ancestor
))
2477 (defun sh-modify (skeleton &rest list
)
2478 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
2479 (setq skeleton
(copy-sequence skeleton
))
2481 (setcar (or (nthcdr (car list
) skeleton
)
2482 (error "Index %d out of bounds" (car list
)))
2484 (setq list
(nthcdr 2 list
)))
2488 (defun sh-basic-indent-line ()
2489 "Indent a line for Sh mode (shell script mode).
2490 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
2491 Lines containing only comments are considered empty."
2493 (let ((previous (save-excursion
2494 (while (and (progn (beginning-of-line)
2498 (back-to-indentation)
2500 (eq (following-char) ?
#)))))
2504 (indent-to (if (eq this-command
'newline-and-indent
)
2506 (if (< (current-column)
2507 (setq current
(progn (back-to-indentation)
2509 (if (eolp) previous
0)
2510 (delete-region (point)
2511 (progn (beginning-of-line) (point)))
2513 (max previous
(* (1+ (/ current sh-indentation
))
2515 (* (1+ (/ current sh-indentation
)) sh-indentation
))))))
2516 (if (< (current-column) (current-indentation))
2517 (skip-chars-forward " \t"))))
2520 (defun sh-execute-region (start end
&optional flag
)
2521 "Pass optional header and region to a subshell for noninteractive execution.
2522 The working directory is that of the buffer, and only environment variables
2523 are already set which is why you can mark a header within the script.
2525 With a positive prefix ARG, instead of sending region, define header from
2526 beginning of buffer to point. With a negative prefix ARG, instead of sending
2527 region, clear header."
2528 (interactive "r\nP")
2530 (setq sh-header-marker
(if (> (prefix-numeric-value flag
) 0)
2532 (if sh-header-marker
2534 (let (buffer-undo-list)
2535 (goto-char sh-header-marker
)
2536 (append-to-buffer (current-buffer) start end
)
2537 (shell-command-on-region (point-min)
2538 (setq end
(+ sh-header-marker
2541 (delete-region sh-header-marker end
)))
2542 (shell-command-on-region start end
(concat sh-shell-file
" -")))))
2545 (defun sh-remember-variable (var)
2546 "Make VARIABLE available for future completing reads in this buffer."
2547 (or (< (length var
) sh-remember-variable-min
)
2549 (assoc var sh-shell-variables
)
2550 (push (cons var var
) sh-shell-variables
))
2555 (defun sh-quoted-p ()
2556 "Is point preceded by an odd number of backslashes?"
2557 (eq -
1 (%
(save-excursion (skip-chars-backward "\\\\")) 2)))
2559 ;; Indentation stuff.
2560 (defun sh-must-support-indent ()
2561 "Signal an error if the shell type for this buffer is not supported.
2562 Also, the buffer must be in Shell-script mode."
2563 (unless sh-indent-supported-here
2564 (error "This buffer's shell does not support indentation through Emacs")))
2566 (defun sh-make-vars-local ()
2567 "Make the indentation variables local to this buffer.
2568 Normally they already are local. This command is provided in case
2569 variable `sh-make-vars-local' has been set to nil.
2571 To revert all these variables to the global values, use
2572 command `sh-reset-indent-vars-to-global-values'."
2574 (mapc 'make-local-variable sh-var-list
)
2575 (message "Indentation variables are now local."))
2577 (defun sh-reset-indent-vars-to-global-values ()
2578 "Reset local indentation variables to the global values.
2579 Then, if variable `sh-make-vars-local' is non-nil, make them local."
2581 (mapc 'kill-local-variable sh-var-list
)
2582 (if sh-make-vars-local
2583 (mapcar 'make-local-variable sh-var-list
)))
2586 ;; Theoretically these are only needed in shell and derived modes.
2587 ;; However, the routines which use them are only called in those modes.
2588 (defconst sh-special-keywords
"then\\|do")
2590 (defun sh-help-string-for-variable (var)
2591 "Construct a string for `sh-read-variable' when changing variable VAR ."
2592 (let ((msg (documentation-property var
'variable-documentation
))
2594 (unless (memq var
'(sh-first-lines-indent sh-indent-comment
))
2597 You can enter a number (positive to increase indentation,
2598 negative to decrease indentation, zero for no change to indentation).
2600 Or, you can enter one of the following symbols which are relative to
2601 the value of variable `sh-basic-offset'
2602 which in this buffer is currently %s.
2606 (mapconcat (lambda (x)
2607 (nth (1- (length x
)) x
))
2608 sh-symbol-list
"\n\t"))))
2610 ;; The following shows the global not the local value!
2611 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
2614 (defun sh-read-variable (var)
2615 "Read a new value for indentation variable VAR."
2616 (let ((minibuffer-help-form `(sh-help-string-for-variable
2619 (setq val
(read-from-minibuffer
2620 (format "New value for %s (press %s for help): "
2621 var
(single-key-description help-char
))
2622 (format "%s" (symbol-value var
))
2628 (defun sh-in-comment-or-string (start)
2629 "Return non-nil if START is in a comment or string."
2631 (let ((state (syntax-ppss start
)))
2632 (or (nth 3 state
) (nth 4 state
)))))
2634 (defun sh-goto-matching-if ()
2635 "Go to the matching if for a fi.
2636 This handles nested if..fi pairs."
2637 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
2639 (goto-char found
))))
2642 ;; Functions named sh-handle-this-XXX are called when the keyword on the
2643 ;; line whose indentation is being handled contain XXX;
2644 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
2646 (defun sh-handle-prev-if ()
2647 (list '(+ sh-indent-after-if
)))
2649 (defun sh-handle-this-else ()
2650 (if (sh-goto-matching-if)
2651 ;; (list "aligned to if")
2652 (list "aligned to if" '(+ sh-indent-for-else
))
2656 (defun sh-handle-prev-else ()
2657 (if (sh-goto-matching-if)
2658 (list '(+ sh-indent-after-if
))
2661 (defun sh-handle-this-fi ()
2662 (if (sh-goto-matching-if)
2663 (list "aligned to if" '(+ sh-indent-for-fi
))
2667 (defun sh-handle-prev-fi ()
2668 ;; Why do we have this rule? Because we must go back to the if
2669 ;; to get its indent. We may continue back from there.
2670 ;; We return nil because we don't have anything to add to result,
2671 ;; the side affect of setting align-point is all that matters.
2672 ;; we could return a comment (a string) but I can't think of a good one...
2673 (sh-goto-matching-if)
2676 (defun sh-handle-this-then ()
2677 (let ((p (sh-goto-matching-if)))
2679 (list '(+ sh-indent-for-then
))
2682 (defun sh-handle-prev-then ()
2683 (let ((p (sh-goto-matching-if)))
2685 (list '(+ sh-indent-after-if
))
2688 (defun sh-handle-prev-open ()
2690 (let ((x (sh-prev-stmt)))
2695 (looking-at "function\\b")
2696 (looking-at "\\s-*\\S-+\\s-*()")
2698 (list '(+ sh-indent-after-function
))
2699 (list '(+ sh-indent-after-open
)))
2702 (defun sh-handle-this-close ()
2703 (forward-char 1) ;; move over ")"
2704 (if (sh-safe-forward-sexp -
1)
2705 (list "aligned to opening paren")))
2707 (defun sh-goto-matching-case ()
2708 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2709 (if found
(goto-char found
))))
2711 (defun sh-handle-prev-case ()
2712 ;; This is typically called when point is on same line as a case
2713 ;; we shouldn't -- and can't find prev-case
2714 (if (looking-at ".*\\<case\\>")
2715 (list '(+ sh-indent-for-case-label
))
2716 (error "We don't seem to be on a line with a case"))) ;; debug
2718 (defun sh-handle-this-esac ()
2719 (if (sh-goto-matching-case)
2720 (list "aligned to matching case")))
2722 (defun sh-handle-prev-esac ()
2723 (if (sh-goto-matching-case)
2724 (list "matching case")))
2726 (defun sh-handle-after-case-label ()
2727 (if (sh-goto-matching-case)
2728 (list '(+ sh-indent-for-case-alt
))))
2730 (defun sh-handle-prev-case-alt-end ()
2731 (if (sh-goto-matching-case)
2732 (list '(+ sh-indent-for-case-label
))))
2734 (defun sh-safe-forward-sexp (&optional arg
)
2735 "Try and do a `forward-sexp', but do not error.
2736 Return new point if successful, nil if an error occurred."
2739 (forward-sexp (or arg
1))
2740 (point)) ;; return point if successful
2742 (sh-debug "oops!(1) %d" (point))
2743 nil
))) ;; return nil if fail
2745 (defun sh-goto-match-for-done ()
2746 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done
1)))
2748 (goto-char found
))))
2750 (defun sh-handle-this-done ()
2751 (if (sh-goto-match-for-done)
2752 (list "aligned to do stmt" '(+ sh-indent-for-done
))))
2754 (defun sh-handle-prev-done ()
2755 (if (sh-goto-match-for-done)
2756 (list "previous done")))
2758 (defun sh-handle-this-do ()
2759 (if (sh-goto-match-for-done)
2760 (list '(+ sh-indent-for-do
))))
2762 (defun sh-handle-prev-do ()
2765 (narrow-to-region (point) (line-beginning-position))
2766 (sh-goto-match-for-done))
2767 (sh-debug "match for done found on THIS line")
2768 (list '(+ sh-indent-after-loop-construct
)))
2769 ((sh-goto-match-for-done)
2770 (sh-debug "match for done found on PREV line")
2771 (list '(+ sh-indent-after-do
)))
2773 (message "match for done NOT found")
2777 (defun sh-find-prev-switch ()
2778 "Find the line for the switch keyword matching this line's case keyword."
2779 (re-search-backward "\\<switch\\>" nil t
))
2781 (defun sh-handle-this-rc-case ()
2782 (if (sh-find-prev-switch)
2783 (list '(+ sh-indent-after-switch
))
2784 ;; (list '(+ sh-indent-for-case-label))
2787 (defun sh-handle-prev-rc-case ()
2788 (list '(+ sh-indent-after-case
)))
2790 (defun sh-check-rule (n thing
)
2791 (let ((rule (nth n
(assoc thing sh-kw-alist
)))
2795 (setq val
(funcall rule
))
2796 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2797 n thing
(point) rule val
)))
2801 (defun sh-get-indent-info ()
2802 "Return indent-info for this line.
2803 This is a list. nil means the line is to be left as is.
2804 Otherwise it contains one or more of the following sublists:
2805 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2806 relative to. If present, this is always the first of the
2807 sublists. The indentation of the line in question is
2808 derived from the indentation of this point, possibly
2809 modified by subsequent sublists.
2811 \(- VAR\) Get the value of variable VAR and add to or subtract from
2812 the indentation calculated so far.
2813 \(= VAR\) Get the value of variable VAR and *replace* the
2814 indentation with its value. This only occurs for
2815 special variables such as `sh-indent-comment'.
2816 STRING This is ignored for the purposes of calculating
2817 indentation, it is printed in certain cases to help show
2818 what the indentation is based on."
2819 ;; See comments before `sh-kw'.
2821 (let ((have-result nil
)
2828 ;; Note: setting result to t means we are done and will return nil.
2829 ;;(This function never returns just t.)
2831 ((or (nth 3 (syntax-ppss (point)))
2832 (eq (get-text-property (point) 'face
) sh-heredoc-face
))
2833 ;; String continuation -- don't indent
2835 (setq have-result t
))
2836 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2838 (setq result t
) ;; return nil if 1st line!
2839 (setq result
(list '(= sh-indent-comment
)))
2840 ;; we still need to get previous line in case
2841 ;; sh-indent-comment is t (indent as normal)
2842 (setq align-point
(sh-prev-line nil
))
2843 (setq have-result nil
)
2848 ;; Continuation lines are handled specially
2849 (if (sh-this-is-a-continuation)
2854 (not (memq (char-before (- (point) 2)) '(?\s ?
\t))))
2855 ;; By convention, if the continuation \ is not
2856 ;; preceded by a SPC or a TAB it means that the line
2857 ;; is cut at a place where spaces cannot be freely
2858 ;; added/removed. I.e. do not indent the line.
2860 ;; We assume the line being continued is already
2861 ;; properly indented...
2862 ;; (setq prev-line-end (sh-prev-line))
2863 (setq align-point
(sh-prev-line nil
))
2864 (list '(+ sh-indent-for-continuation
))))
2865 (setq have-result t
))
2867 (skip-chars-forward " \t")
2868 (setq this-kw
(sh-get-kw)))
2870 ;; Handle "this" keyword: first word on the line we're
2871 ;; calculating indentation info for.
2873 (if (setq val
(sh-check-rule 1 this-kw
))
2875 (setq align-point
(point))
2877 "this - setting align-point to %d" align-point
)
2878 (setq result
(append result val
))
2879 (setq have-result t
)
2880 ;; set prev-line to continue processing remainder
2881 ;; of this line as a previous line
2882 (setq prev-line-end
(point))
2886 (setq prev-line-end
(sh-prev-line 'end
)))
2890 ;; We start off at beginning of this line.
2891 ;; Scan previous statements while this is <=
2892 ;; start of previous line.
2893 (goto-char prev-line-end
)
2895 (while (and x
(setq x
(sh-prev-thing)))
2896 (sh-debug "at %d x is: %s result is: %s" (point) x result
)
2899 (equal (get-text-property (1- (point)) 'syntax-table
)
2901 (sh-debug "Case label) here")
2902 (setq x
'case-label
)
2903 (if (setq val
(sh-check-rule 2 x
))
2905 (setq result
(append result val
))
2906 (setq align-point
(point))))
2909 ;; FIXME: This charset looks too much like a regexp. --Stef
2910 (skip-chars-forward "[a-z0-9]*?")
2912 ((string-match "[])}]" x
)
2913 (setq x
(sh-safe-forward-sexp -
1))
2916 (setq align-point
(point))
2917 (setq result
(append result
2918 (list "aligned to opening paren")))
2920 ((string-match "[[({]" x
)
2921 (sh-debug "Checking special thing: %s" x
)
2922 (if (setq val
(sh-check-rule 2 x
))
2923 (setq result
(append result val
)))
2925 (setq align-point
(point)))
2926 ((string-match "[\"'`]" x
)
2927 (sh-debug "Skipping back for %s" x
)
2929 (setq x
(sh-safe-forward-sexp -
1)))
2931 (sh-debug "Checking string %s at %s" x
(point))
2932 (if (setq val
(sh-check-rule 2 x
))
2933 ;; (or (eq t (car val))
2934 ;; (eq t (car (car val))))
2935 (setq result
(append result val
)))
2936 ;; not sure about this test Wed Jan 27 23:48:35 1999
2937 (setq align-point
(point))
2941 (error "Don't know what to do with %s" x
))
2944 (sh-debug "result is %s" result
)
2946 (sh-debug "No prev line!")
2947 (sh-debug "result: %s align-point: %s" result align-point
)
2951 ;; was: (setq result (append result (list (list t align-point))))
2952 (setq result
(append (list (list t align-point
)) result
))
2954 (sh-debug "result is now: %s" result
)
2957 (setq result
(list (if prev-line-end
2958 (list t prev-line-end
)
2959 (list '= 'sh-first-lines-indent
)))))
2963 (sh-debug "result is: %s" result
)
2969 (defun sh-get-indent-var-for-line (&optional info
)
2970 "Return the variable controlling indentation for this line.
2971 If there is not [just] one such variable, return a string
2972 indicating the problem.
2973 If INFO is supplied it is used, else it is calculated."
2979 (setq info
(sh-get-indent-info)))
2981 (setq result
"this line to be left as is")
2982 (while (and info
(null result
))
2983 (setq elt
(car info
))
2989 (error "sh-get-indent-var-for-line invalid elt: %s" elt
))
2993 ((symbolp (setq sym
(nth 1 elt
)))
2994 ;; A bit of a kludge - when we see the sh-indent-comment
2995 ;; ignore other variables. Otherwise it is tricky to
2996 ;; "learn" the comment indentation.
2997 (if (eq var
'sh-indent-comment
)
3001 "this line is controlled by more than 1 variable.")
3004 (error "sh-get-indent-var-for-line invalid list elt: %s" elt
)))
3005 (setq info
(cdr info
))
3010 (setq result reason
))
3012 ;; e.g. just had (t POS)
3013 (setq result
"line has default indentation"))
3018 ;; Finding the previous line isn't trivial.
3019 ;; We must *always* go back one more and see if that is a continuation
3020 ;; line -- it is the PREVIOUS line which is continued, not the one
3022 ;; Also, we want to treat a whole "here document" as one big line,
3023 ;; because we may want to a align to the beginning of it.
3026 ;; - go back to previous non-empty line
3027 ;; - if this is in a here-document, go to the beginning of it
3028 ;; - while previous line is continued, go back one line
3029 (defun sh-prev-line (&optional end
)
3030 "Back to end of previous non-comment non-empty line.
3031 Go to beginning of logical line unless END is non-nil, in which case
3032 we go to the end of the previous line and do not check for continuations."
3035 (forward-comment (- (point-max)))
3036 (unless end
(beginning-of-line))
3037 (when (and (not (bobp))
3038 (equal (get-text-property (1- (point)) 'face
)
3040 (let ((p1 (previous-single-property-change (1- (point)) 'face
)))
3045 (beginning-of-line)))))
3047 ;; we must check previous lines to see if they are continuation lines
3048 ;; if so, we must return position of first of them
3049 (while (and (sh-this-is-a-continuation)
3050 (>= 0 (forward-line -
1))))
3052 (skip-chars-forward " \t"))
3056 (defun sh-prev-stmt ()
3057 "Return the address of the previous stmt or nil."
3058 ;; This is used when we are trying to find a matching keyword.
3059 ;; Searching backward for the keyword would certainly be quicker, but
3060 ;; it is hard to remove "false matches" -- such as if the keyword
3061 ;; appears in a string or quote. This way is slower, but (I think) safer.
3068 (skip-chars-backward " \t;|&({[")
3069 (while (and (not found
)
3072 ;; Do a backward-sexp if possible, else backup bit by bit...
3073 (if (sh-safe-forward-sexp -
1)
3075 (if (looking-at sh-special-keywords
)
3080 ;; backward-sexp failed
3081 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
3084 (let ((back (sh-prev-line nil
)))
3087 (setq going nil
)))))
3089 (skip-chars-backward " \t")
3090 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
3091 (eq (char-before) ?\
;)
3092 (looking-at "\\s-*[|&]"))
3093 (setq found
(point)))))
3098 (skip-chars-forward " \t|&({[")
3099 (setq found
(point))))
3100 (if (>= (point) start
)
3102 (debug "We didn't move!")
3105 (sh-debug "Did not find prev stmt.")))
3109 (defun sh-get-word ()
3110 "Get a shell word skipping whitespace from point."
3112 (skip-chars-forward "\t ")
3113 (let ((start (point)))
3115 (if (looking-at "[\"'`]")
3116 (sh-safe-forward-sexp)
3117 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
3118 (> (skip-chars-forward "-_$[:alnum:]") 0)
3120 (buffer-substring start
(point))
3123 (defun sh-prev-thing ()
3124 "Return the previous thing this logical line."
3125 ;; This is called when `sh-get-indent-info' is working backwards on
3126 ;; the previous line(s) finding what keywords may be relevant for
3127 ;; indenting. It moves over sexps if possible, and will stop
3128 ;; on a ; and at the beginning of a line if it is not a continuation
3131 ;; Added a kludge for ";;"
3132 ;; Possible return values:
3134 ;; a string - possibly a keyword
3138 (let ((start (point))
3139 (min-point (if (sh-this-is-a-continuation)
3141 (line-beginning-position))))
3142 (skip-chars-backward " \t;" min-point
)
3143 (if (looking-at "\\s-*;[;&]")
3144 ;; (message "Found ;; !")
3146 (skip-chars-backward "^)}];\"'`({[" min-point
)
3147 (let ((c (if (> (point) min-point
) (char-before))))
3148 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
3149 (point) c start min-point
)
3150 (if (not (memq c
'(?
\n nil ?\
;)))
3151 ;; c -- return a string
3153 ;; Return the leading keyword of the "command" we supposedly
3154 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
3155 ;; `then' that precedes the actual command), so check whether
3156 ;; we're looking at such a keyword and if so, move back forward.
3157 (let ((boundary (point))
3161 ;; Skip forward over white space newline and \ at eol.
3162 (skip-chars-forward " \t\n\\\\" start
)
3163 (if (>= (point) start
)
3165 (sh-debug "point: %d >= start: %d" (point) start
)
3167 (if next
(setq boundary next
))
3168 (sh-debug "Now at %d start=%d" (point) start
)
3169 (setq kwd
(sh-get-word))
3170 (if (member kwd
(sh-feature sh-leading-keywords
))
3175 (goto-char boundary
)
3179 (defun sh-this-is-a-continuation ()
3180 "Return non-nil if current line is a continuation of previous line."
3182 (and (zerop (forward-line -
1))
3183 (looking-at ".*\\\\$")
3184 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
3187 (defun sh-get-kw (&optional where and-move
)
3188 "Return first word of line from WHERE.
3189 If AND-MOVE is non-nil then move to end of word."
3190 (let ((start (point)))
3194 (buffer-substring (point)
3195 (progn (skip-chars-forward "^ \t\n;&|")(point)))
3197 (goto-char start
)))))
3199 (defun sh-find-prev-matching (open close
&optional depth
)
3200 "Find a matching token for a set of opening and closing keywords.
3201 This takes into account that there may be nested open..close pairings.
3202 OPEN and CLOSE are regexps denoting the tokens to be matched.
3203 Optional parameter DEPTH (usually 1) says how many to look for."
3204 (let ((parse-sexp-ignore-comments t
)
3205 (forward-sexp-function nil
)
3207 (setq depth
(or depth
1))
3213 (setq prev
(sh-prev-stmt)))
3216 (if (looking-at "\\\\\n")
3219 (skip-chars-forward " \t")))
3222 (setq depth
(1- depth
))
3223 (sh-debug "found open at %d - depth = %d" (point) depth
))
3225 (setq depth
(1+ depth
))
3226 (sh-debug "found close - depth = %d" depth
))
3236 (defun sh-var-value (var &optional ignore-error
)
3237 "Return the value of variable VAR, interpreting symbols.
3238 It can also return t or nil.
3239 If an invalid value is found, throw an error unless Optional argument
3240 IGNORE-ERROR is non-nil."
3241 (let ((val (symbol-value var
)))
3252 (- sh-basic-offset
))
3254 (* 2 sh-basic-offset
))
3256 (* 2 (- sh-basic-offset
)))
3258 (/ sh-basic-offset
2))
3260 (/ (- sh-basic-offset
) 2))
3262 (funcall (if ignore-error
#'message
#'error
)
3263 "Don't know how to handle %s's value of %s" var val
)
3266 (defun sh-set-var-value (var value
&optional no-symbol
)
3267 "Set variable VAR to VALUE.
3268 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
3269 can be represented by a symbol then do so."
3273 ((= value sh-basic-offset
)
3275 ((= value
(- sh-basic-offset
))
3277 ((eq value
(* 2 sh-basic-offset
))
3279 ((eq value
(* 2 (- sh-basic-offset
)))
3281 ((eq value
(/ sh-basic-offset
2))
3283 ((eq value
(/ (- sh-basic-offset
) 2))
3290 (defun sh-calculate-indent (&optional info
)
3291 "Return the indentation for the current line.
3292 If INFO is supplied it is used, else it is calculated from current line."
3297 (setq info
(sh-get-indent-info)))
3300 (sh-debug "info: %s ofs=%s" info ofs
)
3301 (setq elt
(car info
))
3303 ((stringp elt
)) ;; do nothing?
3305 (setq a
(car (car info
)))
3306 (setq b
(nth 1 (car info
)))
3311 (setq val
(current-indentation)))
3312 (setq base-value val
))
3314 (setq val
(sh-var-value b
))
3320 ;; set info to nil so we stop immediately
3321 (setq base-value nil ofs nil info nil
))
3322 ((eq val t
) (setq ofs
0)) ;; indent as normal line
3324 ;; The following assume the (t POS) come first!
3325 (setq ofs val base-value
0)
3326 (setq info nil
)))) ;; ? stop now
3327 ((eq a
'+) (setq ofs
(+ ofs val
)))
3328 ((eq a
'-
) (setq ofs
(- ofs val
)))
3330 (error "sh-calculate-indent invalid a a=%s b=%s" a b
))))
3332 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b
))))
3334 (error "sh-calculate-indent invalid elt %s" elt
)))
3335 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
3336 a b val base-value ofs
)
3337 (setq info
(cdr info
)))
3339 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs
)
3342 ((or (null base-value
)(null ofs
))
3344 ((and (numberp base-value
)(numberp ofs
))
3345 (sh-debug "base (%d) + ofs (%d) = %d"
3346 base-value ofs
(+ base-value ofs
))
3347 (+ base-value ofs
)) ;; return value
3349 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
3354 (defun sh-indent-line ()
3355 "Indent the current line."
3357 (let ((indent (sh-calculate-indent))
3358 (pos (- (point-max) (point))))
3361 (skip-chars-forward " \t")
3362 (indent-line-to indent
)
3363 ;; If initial point was within line's indentation,
3364 ;; position after the indentation. Else stay at same point in text.
3365 (if (> (- (point-max) pos
) (point))
3366 (goto-char (- (point-max) pos
))))))
3369 (defun sh-blink (blinkpos &optional msg
)
3370 "Move cursor momentarily to BLINKPOS and display MSG."
3371 ;; We can get here without it being a number on first line
3372 (if (numberp blinkpos
)
3374 (goto-char blinkpos
)
3375 (if msg
(message "%s" msg
) (message nil
))
3376 (sit-for blink-matching-delay
))
3377 (if msg
(message "%s" msg
) (message nil
))))
3379 (defun sh-show-indent (arg)
3380 "Show the how the current line would be indented.
3381 This tells you which variable, if any, controls the indentation of
3383 If optional arg ARG is non-null (called interactively with a prefix),
3384 a pop up window describes this variable.
3385 If variable `sh-blink' is non-nil then momentarily go to the line
3386 we are indenting relative to, if applicable."
3388 (sh-must-support-indent)
3390 (smie-config-show-indent)
3391 (let* ((info (sh-get-indent-info))
3392 (var (sh-get-indent-var-for-line info
))
3393 (curr-indent (current-indentation))
3396 (message "%s" (setq msg var
))
3397 (setq val
(sh-calculate-indent info
))
3399 (if (eq curr-indent val
)
3400 (setq msg
(format "%s is %s" var
(symbol-value var
)))
3403 (format "%s (%s) would change indent from %d to: %d"
3404 var
(symbol-value var
) curr-indent val
)
3405 (format "%s (%s) would leave line as is"
3406 var
(symbol-value var
)))
3409 (describe-variable var
)))
3411 (let ((info (sh-get-indent-info)))
3412 (if (and info
(listp (car info
))
3413 (eq (car (car info
)) t
))
3414 (sh-blink (nth 1 (car info
)) msg
)
3415 (message "%s" msg
)))
3419 (defun sh-set-indent ()
3420 "Set the indentation for the current line.
3421 If the current line is controlled by an indentation variable, prompt
3422 for a new value for it."
3424 (sh-must-support-indent)
3426 (smie-config-set-indent)
3427 (let* ((info (sh-get-indent-info))
3428 (var (sh-get-indent-var-for-line info
))
3429 val old-val indent-val
)
3431 (message "Cannot set indent - %s" var
)
3432 (setq old-val
(symbol-value var
))
3433 (setq val
(sh-read-variable var
))
3437 (setq indent-val
(sh-calculate-indent info
))
3439 (message "Variable: %s Value: %s would indent to: %d"
3440 var
(symbol-value var
) indent-val
)
3441 (message "Variable: %s Value: %s would leave line as is."
3442 var
(symbol-value var
)))
3443 ;; I'm not sure about this, indenting it now?
3444 ;; No. Because it would give the impression that an undo would
3445 ;; restore thing, but the value has been altered.
3450 (message "Bad value for %s, restoring to previous value %s"
3457 (defun sh-learn-line-indent (arg)
3458 "Learn how to indent a line as it currently is indented.
3460 If there is an indentation variable which controls this line's indentation,
3461 then set it to a value which would indent the line the way it
3464 If the value can be represented by one of the symbols then do so
3465 unless optional argument ARG (the prefix when interactive) is non-nil."
3467 (sh-must-support-indent)
3469 (smie-config-set-indent)
3470 ;; I'm not sure if we show allow learning on an empty line.
3471 ;; Though it might occasionally be useful I think it usually
3472 ;; would just be confusing.
3475 (looking-at "\\s-*$"))
3476 (message "sh-learn-line-indent ignores empty lines.")
3477 (let* ((info (sh-get-indent-info))
3478 (var (sh-get-indent-var-for-line info
))
3479 ival sval diff new-val
3481 (curr-indent (current-indentation)))
3484 (message "Cannot learn line - %s" var
))
3485 ((eq var
'sh-indent-comment
)
3486 ;; This is arbitrary...
3487 ;; - if curr-indent is 0, set to curr-indent
3488 ;; - else if it has the indentation of a "normal" line,
3490 ;; - else set to curr-indent.
3491 (setq sh-indent-comment
3492 (if (= curr-indent
0)
3494 (let* ((sh-indent-comment t
)
3495 (val2 (sh-calculate-indent info
)))
3496 (if (= val2 curr-indent
)
3499 (message "%s set to %s" var
(symbol-value var
))
3501 ((numberp (setq sval
(sh-var-value var
)))
3502 (setq ival
(sh-calculate-indent info
))
3503 (setq diff
(- curr-indent ival
))
3505 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
3506 curr-indent ival diff var sval
)
3507 (setq new-val
(+ sval diff
))
3508 ;; I commented out this because someone might want to replace
3509 ;; a value of `+' with the current value of sh-basic-offset
3512 ;; (message "No change needed!")
3513 (sh-set-var-value var new-val no-symbol
)
3514 (message "%s set to %s" var
(symbol-value var
))
3518 (message "Cannot change %s" var
)))))))
3522 (defun sh-mark-init (buffer)
3523 "Initialize a BUFFER to be used by `sh-mark-line'."
3524 (with-current-buffer (get-buffer-create buffer
)
3529 (defun sh-mark-line (message point buffer
&optional add-linenum occur-point
)
3530 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
3531 Buffer BUFFER is in `occur-mode'.
3532 If ADD-LINENUM is non-nil the message is preceded by the line number.
3533 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
3534 so that `occur-next' and `occur-prev' will work."
3535 (let ((m1 (make-marker))
3539 (set-marker m1 point
(current-buffer))
3541 (setq line
(format "%d: " (1+ (count-lines 1 point
))))))
3543 (if (get-buffer buffer
)
3544 (set-buffer (get-buffer buffer
))
3545 (set-buffer (get-buffer-create buffer
))
3548 (goto-char (point-max))
3549 (setq start
(point))
3550 (let ((inhibit-read-only t
))
3553 (setq occur-point
(point)))
3556 (add-text-properties
3558 '(mouse-face highlight
3559 help-echo
"mouse-2: go to the line where I learned this")))
3562 (put-text-property start
(point) 'occur-target m1
)
3564 (put-text-property start occur-point
3568 ;; Is this really worth having?
3569 (defvar sh-learned-buffer-hook nil
3570 "An abnormal hook, called with an alist of learned variables.")
3571 ;; Example of how to use sh-learned-buffer-hook
3573 ;; (defun what-i-learned (list)
3575 ;; (with-current-buffer "*scratch*"
3576 ;; (goto-char (point-max))
3577 ;; (insert "(setq\n")
3579 ;; (insert (format " %s %s \n"
3580 ;; (nth 0 (car p)) (nth 1 (car p))))
3581 ;; (setq p (cdr p)))
3585 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
3588 ;; Originally this was sh-learn-region-indent (beg end)
3589 ;; However, in practice this was awkward so I changed it to
3590 ;; use the whole buffer. Use narrowing if need be.
3591 (defun sh-learn-buffer-indent (&optional arg
)
3592 "Learn how to indent the buffer the way it currently is.
3594 Output in buffer \"*indent*\" shows any lines which have conflicting
3595 values of a variable, and the final value of all variables learned.
3596 When called interactively, pop to this buffer automatically if
3597 there are any discrepancies.
3599 If no prefix ARG is given, then variables are set to numbers.
3600 If a prefix arg is given, then variables are set to symbols when
3601 applicable -- e.g. to symbol `+' if the value is that of the
3603 If a positive numerical prefix is given, then `sh-basic-offset'
3604 is set to the prefix's numerical value.
3605 Otherwise, sh-basic-offset may or may not be changed, according
3606 to the value of variable `sh-learn-basic-offset'.
3608 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
3609 function completes. The function is abnormal because it is called
3610 with an alist of variables learned. This feature may be changed or
3611 removed in the future.
3613 This command can often take a long time to run."
3615 (sh-must-support-indent)
3619 (goto-char (point-min))
3620 (let ((learned-var-list nil
)
3621 (out-buffer "*indent*")
3627 (comment-col nil
) ;; number if all same, t if seen diff values
3628 (comments-always-default t
) ;; nil if we see one not default
3630 (specified-basic-offset (and arg
(numberp arg
)
3634 (setq vec
(make-vector max
0))
3635 (sh-mark-init out-buffer
)
3637 (if specified-basic-offset
3639 (setq sh-basic-offset arg
)
3641 (format "Using specified sh-basic-offset of %d"
3644 (format "Initial value of sh-basic-offset: %s"
3647 (while (< (point) (point-max))
3648 (setq linenum
(1+ linenum
))
3649 ;; (if (zerop (% linenum 10))
3650 (message "line %d" linenum
)
3652 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3653 (let* ((sh-indent-comment t
) ;; info must return default indent
3654 (info (sh-get-indent-info))
3655 (var (sh-get-indent-var-for-line info
))
3656 sval ival diff new-val
3657 (curr-indent (current-indentation)))
3663 ((numberp (setq sval
(sh-var-value var
'no-error
)))
3664 ;; the numberp excludes comments since sval will be t.
3665 (setq ival
(sh-calculate-indent))
3666 (setq diff
(- curr-indent ival
))
3667 (setq new-val
(+ sval diff
))
3668 (sh-set-var-value var new-val
'no-symbol
)
3669 (unless (looking-at "\\s-*#") ;; don't learn from comments
3670 (if (setq previous-set-info
(assoc var learned-var-list
))
3672 ;; it was already there, is it same value ?
3673 (unless (eq (symbol-value var
)
3674 (nth 1 previous-set-info
))
3676 (format "Variable %s was set to %s"
3677 var
(symbol-value var
))
3678 (point) out-buffer t t
)
3680 (format " but was previously set to %s"
3681 (nth 1 previous-set-info
))
3682 (nth 2 previous-set-info
) out-buffer t
)
3683 (setq num-diffs
(1+ num-diffs
))
3684 ;; (delete previous-set-info learned-var-list)
3685 (setcdr previous-set-info
3686 (list (symbol-value var
) (point)))
3689 (setq learned-var-list
3690 (append (list (list var
(symbol-value var
)
3693 (if (numberp new-val
)
3696 "This line's indent value: %d" new-val
)
3698 (setq new-val
(- new-val
)))
3700 (aset vec new-val
(1+ (aref vec new-val
))))))
3702 ((eq var
'sh-indent-comment
)
3703 (unless (= curr-indent
(sh-calculate-indent info
))
3704 ;; this is not the default indentation
3705 (setq comments-always-default nil
)
3706 (if comment-col
;; then we have see one before
3707 (or (eq comment-col curr-indent
)
3708 (setq comment-col t
)) ;; seen a different one
3709 (setq comment-col curr-indent
))
3712 (sh-debug "Cannot learn this line!!!")
3715 "at %s learned-var-list is %s" (point) learned-var-list
)
3722 "comment-col = %s comments-always-default = %s"
3723 comment-col comments-always-default
))
3725 (sh-mark-line msg nil out-buffer
)))
3728 (setq msg
"\nComments are all in 1st column.\n"))
3729 (comments-always-default
3730 (setq msg
"\nComments follow default indentation.\n")
3731 (setq comment-col t
))
3732 ((numberp comment-col
)
3733 (setq msg
(format "\nComments are in col %d." comment-col
)))
3735 (setq msg
"\nComments seem to be mixed, leaving them as is.\n")
3736 (setq comment-col nil
)
3739 (sh-mark-line msg nil out-buffer
)
3741 (sh-mark-line initial-msg nil out-buffer t t
)
3743 (setq suggested
(sh-guess-basic-offset vec
))
3745 (if (and suggested
(not specified-basic-offset
))
3748 ;; t => set it if we have a single value as a number
3749 ((and (eq sh-learn-basic-offset t
) (numberp suggested
))
3751 ;; other non-nil => set it if only one value was found
3752 (sh-learn-basic-offset
3753 (if (numberp suggested
)
3755 (if (= (length suggested
) 1)
3761 (setq learned-var-list
3762 (append (list (list 'sh-basic-offset
3763 (setq sh-basic-offset new-value
)
3766 ;; Not sure if we need to put this line in, since
3767 ;; it will appear in the "Learned variable settings".
3769 (format "Changed sh-basic-offset to: %d" sh-basic-offset
)
3772 (if (listp suggested
)
3773 (format "Possible value(s) for sh-basic-offset: %s"
3774 (mapconcat 'int-to-string suggested
" "))
3775 (format "Suggested sh-basic-offset: %d" suggested
))
3779 (setq learned-var-list
3780 (append (list (list 'sh-indent-comment comment-col
(point-max)))
3782 (setq sh-indent-comment comment-col
)
3783 (let ((name (buffer-name)))
3784 (sh-mark-line "\nLearned variable settings:" nil out-buffer
)
3786 ;; Set learned variables to symbolic rather than numeric
3787 ;; values where possible.
3788 (dolist (learned-var (reverse learned-var-list
))
3789 (let ((var (car learned-var
))
3790 (val (nth 1 learned-var
)))
3791 (when (and (not (eq var
'sh-basic-offset
))
3793 (sh-set-var-value var val
)))))
3794 (dolist (learned-var (reverse learned-var-list
))
3795 (let ((var (car learned-var
)))
3796 (sh-mark-line (format " %s %s" var
(symbol-value var
))
3797 (nth 2 learned-var
) out-buffer
)))
3798 (with-current-buffer out-buffer
3799 (goto-char (point-min))
3800 (let ((inhibit-read-only t
))
3802 (format "Indentation values for buffer %s.\n" name
)
3803 (format "%d indentation variable%s different values%s\n\n"
3807 (if (zerop num-diffs
)
3809 ;; Are abnormal hooks considered bad form?
3810 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list
)
3811 (and (called-interactively-p 'any
)
3812 (or sh-popup-occur-buffer
(> num-diffs
0))
3813 (pop-to-buffer out-buffer
))))))
3815 (defun sh-guess-basic-offset (vec)
3816 "See if we can determine a reasonable value for `sh-basic-offset'.
3817 This is experimental, heuristic and arbitrary!
3818 Argument VEC is a vector of information collected by
3819 `sh-learn-buffer-indent'.
3821 number - there appears to be a good single value
3822 list of numbers - no obvious one, here is a list of one or more
3824 nil - we couldn't find a reasonable one."
3825 (let* ((max (1- (length vec
)))
3827 (totals (make-vector max
0)))
3829 (cl-incf (aref totals i
) (* 4 (aref vec i
)))
3831 (cl-incf (aref totals i
) (aref vec
(/ i
2))))
3833 (cl-incf (aref totals i
) (aref vec
(* i
2))))
3841 (if (/= (aref totals i
) 0)
3842 (push (cons i
(aref totals i
)) x
))
3845 (setq x
(sort (nreverse x
) (lambda (a b
) (> (cdr a
) (cdr b
)))))
3846 (setq tot
(apply '+ (append totals nil
)))
3847 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3851 (message "no values!")) ;; we return nil
3853 (message "only value is %d" (car (car x
)))
3854 (setq result
(car (car x
)))) ;; return single value
3855 ((> (cdr (car x
)) (/ tot
2))
3857 (message "basic-offset is probably %d" (car (car x
)))
3858 (setq result
(car (car x
)))) ;; again, return a single value
3859 ((>= (cdr (car x
)) (* 2 (cdr (car (cdr x
)))))
3860 ;; 1st is >= 2 * 2nd
3861 (message "basic-offset could be %d" (car (car x
)))
3862 (setq result
(car (car x
))))
3863 ((>= (+ (cdr (car x
))(cdr (car (cdr x
)))) (/ tot
2))
3864 ;; 1st & 2nd together >= 50% - return a list
3865 (setq p x sum
0 result nil
)
3867 (<= (setq sum
(+ sum
(cdr (car p
)))) (/ tot
2)))
3868 (setq result
(append result
(list (car (car p
)))))
3870 (message "Possible choices for sh-basic-offset: %s"
3871 (mapconcat 'int-to-string result
" ")))
3873 (message "No obvious value for sh-basic-offset. Perhaps %d"
3875 ;; result is nil here
3879 ;; ========================================================================
3881 ;; Styles -- a quick and dirty way of saving the indentation settings.
3883 (defvar sh-styles-alist nil
3884 "A list of all known shell indentation styles.")
3886 (defun sh-name-style (name &optional confirm-overwrite
)
3887 "Name the current indentation settings as a style called NAME.
3888 If this name exists, the command will prompt whether it should be
3890 - - it was called interactively with a prefix argument, or
3891 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3892 ;; (interactive "sName for this style: ")
3895 (read-from-minibuffer "Name for this style? " )
3896 (not current-prefix-arg
)))
3897 (let ((slist (cons name
3898 (mapcar (lambda (var) (cons var
(symbol-value var
)))
3900 (style (assoc name sh-styles-alist
)))
3902 (if (and confirm-overwrite
3903 (not (y-or-n-p "This style exists. Overwrite it? ")))
3904 (message "Not changing style %s" name
)
3905 (message "Updating style %s" name
)
3906 (setcdr style
(cdr slist
)))
3907 (message "Creating new style %s" name
)
3908 (push slist sh-styles-alist
))))
3910 (defun sh-load-style (name)
3911 "Set shell indentation values for this buffer from those in style NAME."
3912 (interactive (list (completing-read
3913 "Which style to use for this buffer? "
3914 sh-styles-alist nil t
)))
3915 (let ((sl (assoc name sh-styles-alist
)))
3917 (error "sh-load-style - style %s not known" name
)
3918 (dolist (var (cdr sl
))
3919 (set (car var
) (cdr var
))))))
3921 (defun sh-save-styles-to-buffer (buff)
3922 "Save all current styles in elisp to buffer BUFF.
3923 This is always added to the end of the buffer."
3926 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3927 (with-current-buffer (get-buffer-create buff
)
3928 (goto-char (point-max))
3930 (pp `(setq sh-styles-alist
',sh-styles-alist
) (current-buffer))))
3934 ;; statement syntax-commands for various shells
3936 ;; You are welcome to add the syntax or even completely new statements as
3937 ;; appropriate for your favorite shell.
3939 (defconst sh-non-closing-paren
3940 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3941 ;; that inherits this property, which then confuses the indentation.
3942 (propertize ")" 'syntax-table sh-st-punc
'rear-nonsticky t
))
3944 (define-skeleton sh-case
3945 "Insert a case/switch statement. See `sh-feature'."
3947 "switch( " str
" )" \n
3948 > "case " (read-string "pattern: ") ?
: \n
3951 ( "other pattern, %s: "
3961 > "switch( " str
" ) {" \n
3962 > "case " (read-string "pattern: ") \n
3964 ( "other pattern, %s: "
3972 > "case " str
" in" \n
3974 > str sh-non-closing-paren
\n
3977 > "*" sh-non-closing-paren
\n
3982 (define-skeleton sh-for
3983 "Insert a for loop. See `sh-feature'."
3997 (sh "Index variable: "
3998 > "for " str
" in " _
"; do" \n
3999 > _ | ?$
& (sh-remember-variable str
) \n
4004 (define-skeleton sh-indexed-loop
4005 "Insert an indexed loop from 1 to n. See `sh-feature'."
4006 (bash sh-modify posix
)
4007 (csh "Index variable: "
4009 "while( $" str
" <= " (read-string "upper limit: ") " )" \n
4015 (ksh88 "Index variable: "
4016 > "integer " str
"=0" \n
4017 > "while (( ( " str
" += 1 ) <= "
4018 (read-string "upper limit: ")
4020 > _ ?$
(sh-remember-variable str
) > \n
4022 (posix "Index variable: "
4024 "while [ $" str
" -le "
4025 (read-string "upper limit: ")
4028 str ?
= (sh-add (sh-remember-variable str
) 1) \n
4030 (rc "Index variable: "
4031 > "for( " str
" in" " `{awk 'BEGIN { for( i=1; i<="
4032 (read-string "upper limit: ")
4033 "; i++ ) print i }'`}) {" \n
4034 > _ ?$
(sh-remember-variable str
) \n
4036 (sh "Index variable: "
4037 > "for " str
" in `awk 'BEGIN { for( i=1; i<="
4038 (read-string "upper limit: ")
4039 "; i++ ) print i }'`; do" \n
4040 > _ ?$
(sh-remember-variable str
) \n
4044 (defun sh-shell-initialize-variables ()
4045 "Scan the buffer for variable assignments.
4046 Add these variables to `sh-shell-variables'."
4047 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
4049 (goto-char (point-min))
4050 (setq sh-shell-variables-initialized t
)
4051 (while (search-forward "=" nil t
)
4053 (message "Scanning buffer `%s' for variable assignments...done"
4056 (defvar sh-add-buffer
)
4058 (defun sh-add-completer (string predicate code
)
4059 "Do completion using `sh-shell-variables', but initialize it first.
4060 This function is designed for use as the \"completion table\",
4061 so it takes three arguments:
4062 STRING, the current buffer contents;
4063 PREDICATE, the predicate for filtering possible matches;
4064 CODE, which says what kind of things to do.
4065 CODE can be nil, t or `lambda'.
4066 nil means to return the best completion of STRING, or nil if there is none.
4067 t means to return a list of all possible completions of STRING.
4068 `lambda' means to return t if STRING is a valid completion as it stands."
4070 (with-current-buffer sh-add-buffer
4071 (or sh-shell-variables-initialized
4072 (sh-shell-initialize-variables))
4073 (nconc (mapcar (lambda (var)
4074 (substring var
0 (string-match "=" var
)))
4075 process-environment
)
4076 sh-shell-variables
))))
4077 (complete-with-action code vars string predicate
)))
4079 (defun sh-add (var delta
)
4080 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
4082 (let ((sh-add-buffer (current-buffer)))
4083 (list (completing-read "Variable: " 'sh-add-completer
)
4084 (prefix-numeric-value current-prefix-arg
))))
4085 (insert (sh-feature '((bash .
"$(( ")
4091 (sh-remember-variable var
)
4092 (if (< delta
0) " - " " + ")
4093 (number-to-string (abs delta
))
4094 (sh-feature '((bash .
" ))")
4103 (define-skeleton sh-function
4104 "Insert a function definition. See `sh-feature'."
4105 (bash sh-modify ksh88
4108 "function " str
" {" \n
4120 (define-skeleton sh-if
4121 "Insert an if statement. See `sh-feature'."
4123 "if( " str
" ) then" \n
4125 ( "other condition, %s: "
4126 < "else if( " str
" ) then" \n
4133 > "if { " str
" } {" \n
4135 ( "other condition, %s: "
4136 "} { " str
" } {" > \n
4143 > "if( " str
" ) {" \n
4145 ( "other condition, %s: "
4146 "} else if( " str
" ) {" > \n
4153 '(setq input
(sh-feature sh-test
))
4154 > "if " str
"; then" \n
4156 ( "other condition, %s: "
4157 > "elif " str
"; then" > \n
4166 (define-skeleton sh-repeat
4167 "Insert a repeat loop definition. See `sh-feature'."
4173 > "repeat " str
"; do" > \n
4177 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
4181 (define-skeleton sh-select
4182 "Insert a select statement. See `sh-feature'."
4183 (ksh88 "Index variable: "
4184 > "select " str
" in " _
"; do" \n
4187 (bash sh-append ksh88
))
4188 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
4192 (define-skeleton sh-tmp-file
4193 "Insert code to setup temporary file handling. See `sh-feature'."
4194 (bash sh-append ksh88
)
4195 (csh (file-name-nondirectory (buffer-file-name))
4196 "set tmp = `mktemp -t " str
".XXXXXX`" \n
4198 (and (goto-char (point-max))
4202 "rm $tmp* >&/dev/null" > \n)
4203 (es (file-name-nondirectory (buffer-file-name))
4204 > "local( signals = $signals sighup sigint;" \n
4205 > "tmp = `{ mktemp -t " str
".XXXXXX } ) {" \n
4207 > "rm $tmp^* >[2]/dev/null" \n
4215 (rc (file-name-nondirectory (buffer-file-name))
4216 > "tmp = `{ mktemp -t " str
".XXXXXX }" \n
4217 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
4218 (sh (file-name-nondirectory (buffer-file-name))
4219 > "TMP=`mktemp -t " str
".XXXXXX`" \n
4220 "trap \"rm $TMP* 2>/dev/null\" " ?
0 \n))
4224 (define-skeleton sh-until
4225 "Insert an until loop. See `sh-feature'."
4227 '(setq input
(sh-feature sh-test
))
4228 > "until " str
"; do" \n
4231 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
4235 (define-skeleton sh-while
4236 "Insert a while loop. See `sh-feature'."
4252 '(setq input
(sh-feature sh-test
))
4253 > "while " str
"; do" \n
4259 (define-skeleton sh-while-getopts
4260 "Insert a while getopts loop. See `sh-feature'.
4261 Prompts for an options string which consists of letters for each recognized
4262 option followed by a colon `:' if the option accepts an argument."
4267 > "switch( \"$1\" )" \n
4268 '(setq input
'("- x" .
2))
4271 < "case " '(eval str
)
4272 '(if (string-match " +" str
)
4273 (setq v1
(substring str
(match-end 0))
4274 str
(substring str
0 (match-beginning 0)))
4277 > "set " v1
& " = $2" | -
4 & _
\n
4278 (if v1
"shift") & \n
4293 18 "$(basename $0)")
4295 > "while getopts :" str
" OPT; do" \n
4297 '(setq v1
(append (vconcat str
) nil
))
4298 ( (prog1 (if v1
(char-to-string (car v1
)))
4299 (if (eq (nth 1 v1
) ?
:)
4300 (setq v1
(nthcdr 2 v1
)
4304 > str
"|+" str sh-non-closing-paren
\n
4307 > "*" sh-non-closing-paren
\n
4308 > "echo" " \"usage: " "`basename $0`"
4309 " [+-" '(setq v1
(point)) str
4311 (while (search-backward ":" v1 t
)
4312 (replace-match " ARG] [+-" t t
)))
4313 (if (eq (preceding-char) ?-
) -
5)
4314 (if (and (sequencep v1
) (length v1
)) "] " "} ")
4320 "shift " (sh-add "OPTIND" -
1) \n
4325 (defun sh-assignment (arg)
4326 "Remember preceding identifier for future completion and do self-insert."
4328 (self-insert-command arg
)
4330 (sh-remember-variable
4332 (if (re-search-forward (sh-feature sh-assignment-regexp
)
4334 (beginning-of-line 1))
4336 (match-string 1))))))
4339 (defun sh-maybe-here-document (arg)
4340 "Insert self. Without prefix, following unquoted `<' inserts here document.
4341 The document is bounded by `sh-here-document-word'."
4342 (declare (obsolete sh-electric-here-document-mode
"24.3"))
4344 (self-insert-command (prefix-numeric-value arg
))
4345 (or arg
(sh--maybe-here-document)))
4347 (defun sh--maybe-here-document ()
4348 (or (not (looking-back "[^<]<<"))
4352 (sh--inside-noncommand-expression (point))))
4353 (nth 8 (syntax-ppss))
4354 (let ((tabs (if (string-match "\\`-" sh-here-document-word
)
4355 (make-string (/ (current-indentation) tab-width
) ?
\t)
4357 (delim (replace-regexp-in-string "['\"]" ""
4358 sh-here-document-word
)))
4359 (insert sh-here-document-word
)
4360 (or (eolp) (looking-at "[ \t]") (insert ?\s
))
4367 (insert ?
\n tabs
(replace-regexp-in-string
4368 "\\`-?[ \t]*" "" delim
))))))
4370 (define-minor-mode sh-electric-here-document-mode
4371 "Make << insert a here document skeleton."
4373 (if sh-electric-here-document-mode
4374 (add-hook 'post-self-insert-hook
#'sh--maybe-here-document nil t
)
4375 (remove-hook 'post-self-insert-hook
#'sh--maybe-here-document t
)))
4377 ;; various other commands
4379 (defun sh-beginning-of-command ()
4380 ;; FIXME: Redefine using SMIE.
4381 "Move point to successive beginnings of commands."
4383 (if (re-search-backward sh-beginning-of-command nil t
)
4384 (goto-char (match-beginning 2))))
4386 (defun sh-end-of-command ()
4387 ;; FIXME: Redefine using SMIE.
4388 "Move point to successive ends of commands."
4390 (if (re-search-forward sh-end-of-command nil t
)
4391 (goto-char (match-end 1))))
4393 ;; Backslashification. Stolen from make-mode.el.
4395 (defun sh-backslash-region (from to delete-flag
)
4396 "Insert, align, or delete end-of-line backslashes on the lines in the region.
4397 With no argument, inserts backslashes and aligns existing backslashes.
4398 With an argument, deletes the backslashes.
4400 This function does not modify the last line of the region if the region ends
4401 right at the start of the following line; it does not modify blank lines
4402 at the start of the region. So you can put the region around an entire
4403 shell command and conveniently use this command."
4404 (interactive "r\nP")
4407 (let ((column sh-backslash-column
)
4408 (endmark (make-marker)))
4409 (move-marker endmark to
)
4410 ;; Compute the smallest column number past the ends of all the lines.
4411 (if sh-backslash-align
4413 (if (not delete-flag
)
4414 (while (< (point) to
)
4416 (if (= (preceding-char) ?
\\)
4417 (progn (forward-char -
1)
4418 (skip-chars-backward " \t")))
4419 (setq column
(max column
(1+ (current-column))))
4421 ;; Adjust upward to a tab column, if that doesn't push
4423 (if (> (% column tab-width
) 0)
4424 (let ((adjusted (* (/ (+ column tab-width -
1) tab-width
)
4426 (if (< adjusted
(window-width))
4427 (setq column adjusted
))))))
4428 ;; Don't modify blank lines at start of region.
4430 (while (and (< (point) endmark
) (eolp))
4432 ;; Add or remove backslashes on all the lines.
4433 (while (and (< (point) endmark
)
4434 ;; Don't backslashify the last line
4435 ;; if the region ends right at the start of the next line.
4438 (< (point) endmark
)))
4439 (if (not delete-flag
)
4440 (sh-append-backslash column
)
4441 (sh-delete-backslash))
4443 (move-marker endmark nil
))))
4445 (defun sh-append-backslash (column)
4447 ;; Note that "\\\\" is needed to get one backslash.
4448 (if (= (preceding-char) ?
\\)
4449 (progn (forward-char -
1)
4450 (delete-horizontal-space)
4451 (indent-to column
(if sh-backslash-align nil
1)))
4452 (indent-to column
(if sh-backslash-align nil
1))
4455 (defun sh-delete-backslash ()
4460 (if (looking-at "\\\\")
4461 (delete-region (1+ (point))
4462 (progn (skip-chars-backward " \t") (point)))))))
4464 (provide 'sh-script
)
4466 ;;; sh-script.el ends here