1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993-1997, 1999, 2001-2012 Free Software Foundation, Inc.
5 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
8 ;; Keywords: languages, unix
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
28 ;; as various derivatives are supported and easily derived from. Structured
29 ;; statements can be inserted with one command or abbrev. Completion is
30 ;; available for filenames, variables known from the script, the shell and
31 ;; the environment as well as commands.
35 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
36 ;; - Variables in `"' strings aren't fontified because there's no way of
37 ;; syntactically distinguishing those from `'' strings.
41 ;; Indentation for rc and es modes is very limited, but for Bourne shells
42 ;; and its derivatives it is quite customizable.
44 ;; The following description applies to sh and derived shells (bash,
47 ;; There are various customization variables which allow tailoring to
48 ;; a wide variety of styles. Most of these variables are named
49 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
50 ;; sh-indent-after-if controls the indenting of a line following
51 ;; an if statement, and sh-indent-for-fi controls the indentation
52 ;; of the line containing the fi.
54 ;; You can set each to a numeric value, but it is often more convenient
55 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
56 ;; By changing this one variable you can increase or decrease how much
57 ;; indentation there is. Valid symbols:
59 ;; + Indent right by sh-basic-offset
60 ;; - Indent left by sh-basic-offset
61 ;; ++ Indent right twice sh-basic-offset
62 ;; -- Indent left twice sh-basic-offset
63 ;; * Indent right half sh-basic-offset
64 ;; / Indent left half sh-basic-offset.
66 ;; There are 4 commands to help set the indentation variables:
69 ;; This shows what variable controls the indentation of the current
70 ;; line and its value.
73 ;; This allows you to set the value of the variable controlling the
74 ;; current line's indentation. You can enter a number or one of a
75 ;; number of special symbols to denote the value of sh-basic-offset,
76 ;; or its negative, or half it, or twice it, etc. If you've used
77 ;; cc-mode this should be familiar. If you forget which symbols are
78 ;; valid simply press C-h at the prompt.
80 ;; `sh-learn-line-indent'
81 ;; Simply make the line look the way you want it, then invoke this
82 ;; command. It will set the variable to the value that makes the line
83 ;; indent like that. If called with a prefix argument then it will set
84 ;; the value to one of the symbols if applicable.
86 ;; `sh-learn-buffer-indent'
87 ;; This is the deluxe function! It "learns" the whole buffer (use
88 ;; narrowing if you want it to process only part). It outputs to a
89 ;; buffer *indent* any conflicts it finds, and all the variables it has
90 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
91 ;; easily find where something was set. It is popped to automatically
92 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
94 ;; `sh-indent-comment' will be set if all comments follow the same
95 ;; pattern; if they don't it will be set to nil.
96 ;; Whether `sh-basic-offset' is set is determined by variable
97 ;; `sh-learn-basic-offset'.
99 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
100 ;; (e.g. if there are large case statements). Perhaps it does not make
101 ;; sense to run it on large buffers: if lots of lines have different
102 ;; indentation styles it will produce a lot of diagnostics in the
103 ;; *indent* buffer; if there is a consistent style then running
104 ;; `sh-learn-buffer-indent' on a small region of the buffer should
107 ;; Saving indentation values
108 ;; -------------------------
109 ;; After you've learned the values in a buffer, how to you remember
110 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
111 ;; would make this unnecessary; simply learn the values when you visit
113 ;; You can do this automatically like this:
114 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
116 ;; However... `sh-learn-buffer-indent' is extremely slow,
117 ;; especially on large-ish buffer. Also, if there are conflicts the
118 ;; "last one wins" which may not produce the desired setting.
120 ;; So...There is a minimal way of being able to save indentation values and
121 ;; to reload them in another buffer or at another point in time.
123 ;; Use `sh-name-style' to give a name to the indentation settings of
124 ;; the current buffer.
125 ;; Use `sh-load-style' to load indentation settings for the current
126 ;; buffer from a specific style.
127 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
128 ;; in lisp code. You can then store it in a file and later use
129 ;; `load-file' to load it.
131 ;; Indentation variables - buffer local or global?
132 ;; ----------------------------------------------
133 ;; I think that often having them buffer-local makes sense,
134 ;; especially if one is using `sh-learn-buffer-indent'. However, if
135 ;; a user sets values using customization, these changes won't appear
136 ;; to work if the variables are already local!
138 ;; To get round this, there is a variable `sh-make-vars-local' and 2
139 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
141 ;; If `sh-make-vars-local' is non-nil, then these variables become
142 ;; buffer local when the mode is established.
143 ;; If this is nil, then the variables are global. At any time you
144 ;; can make them local with the command `sh-make-vars-local'.
145 ;; Conversely, to update with the global values you can use the
146 ;; command `sh-reset-indent-vars-to-global-values'.
148 ;; This may be awkward, but the intent is to cover all cases.
150 ;; Awkward things, pitfalls
151 ;; ------------------------
152 ;; Indentation for a sh script is complicated for a number of reasons:
154 ;; 1. You can't format by simply looking at symbols, you need to look
155 ;; at keywords. [This is not the case for rc and es shells.]
156 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
157 ;; as a stand-alone symbol (in a case alternative). This makes
158 ;; things quite tricky!
159 ;; 3. Here-documents in a script should be treated "as is", and when
160 ;; they terminate we want to revert to the indentation of the line
161 ;; containing the "<<" symbol.
162 ;; 4. A line may be continued using the "\".
163 ;; 5. The character "#" (outside a string) normally starts a comment,
164 ;; but it doesn't in the sequence "$#"!
166 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
167 ;; uses, that of a text's syntax property. This, however, has 2
169 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
170 ;; case alternative, to find any here documents, and handle "$#".
174 ;; - Indenting many lines is slow. It currently does each line
175 ;; independently, rather than saving state information.
177 ;; - `sh-learn-buffer-indent' is extremely slow.
179 ;; - "case $x in y) echo ;; esac)" the last ) is mis-identified as being
180 ;; part of a case-pattern. You need to add a semi-colon after "esac" to
181 ;; coerce sh-script into doing the right thing.
183 ;; - "echo $z in ps | head)" the last ) is mis-identified as being part of
184 ;; a case-pattern. You need to put the "in" between quotes to coerce
185 ;; sh-script into doing the right thing.
187 ;; - A line starting with "}>foo" is not indented like "} >foo".
189 ;; Richard Sharman <rsharman@pobox.com> June 1999.
193 ;; page 1: variables and settings
194 ;; page 2: indentation stuff
195 ;; page 3: mode-command and utility functions
196 ;; page 4: statement syntax-commands for various shells
197 ;; page 5: various other commands
203 (require 'executable
)
205 (defvar font-lock-comment-face
)
206 (defvar font-lock-set-defaults
)
207 (defvar font-lock-string-face
)
211 "Shell programming utilities."
214 (defgroup sh-script nil
216 :link
'(custom-group-link :tag
"Font Lock Faces group" font-lock-faces
)
221 (defcustom sh-ancestor-alist
240 "Alist showing the direct ancestor of various shells.
241 This is the basis for `sh-feature'. See also `sh-alias-alist'.
242 By default we have the following three hierarchies:
245 jcsh C Shell with Job Control
247 itcsh Ian's TENEX C Shell
252 jsh Bourne Shell with Job Control
253 bash GNU Bourne Again Shell
256 dtksh CDE Desktop Korn Shell
257 pdksh Public Domain Korn Shell
258 wksh Window Korn Shell
260 oash SCO OA (curses) Shell
261 posix IEEE 1003.2 Shell Standard
263 :type
'(repeat (cons symbol symbol
))
267 (defcustom sh-alias-alist
268 (append (if (eq system-type
'gnu
/linux
)
271 ;; for the time being
275 "Alist for transforming shell names to what they really are.
276 Use this where the name of the executable doesn't correspond to the type of
278 :type
'(repeat (cons symbol symbol
))
282 (defcustom sh-shell-file
284 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
285 ;; the executable extension, so comparisons with the list of
286 ;; known shells work.
287 (and (memq system-type
'(ms-dos windows-nt
))
288 (let* ((shell (getenv "SHELL"))
290 (and shell
(file-name-nondirectory shell
))))
291 ;; shell-script mode doesn't support DOS/Windows shells,
292 ;; so use the default instead.
294 (member (downcase shell-base
)
295 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
298 (file-name-sans-extension (downcase shell
)))))
301 "The executable file name for the shell being programmed."
306 (defcustom sh-shell-arg
307 ;; bash does not need any options when run in a shell script,
311 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
313 ;; -p means don't initialize functions from the environment.
315 ;; Someone proposed -motif, but we don't want to encourage
316 ;; use of a non-free widget set.
318 ;; -f means don't run .zshrc.
320 "Single argument string for the magic number. See `sh-feature'."
321 :type
'(repeat (cons (symbol :tag
"Shell")
322 (choice (const :tag
"No Arguments" nil
)
323 (string :tag
"Arguments")
324 (sexp :format
"Evaluate: %v"))))
327 (defcustom sh-imenu-generic-expression
330 "^\\s-*\\(function\\s-+\\)?\\([[:alpha:]_][[:alnum:]_]+\\)\\s-*()"
332 "Alist of regular expressions for recognizing shell function definitions.
333 See `sh-feature' and `imenu-generic-expression'."
334 :type
'(alist :key-type
(symbol :tag
"Shell")
335 :value-type
(alist :key-type
(choice :tag
"Title"
337 (const :tag
"None" nil
))
339 (repeat :tag
"Regexp, index..." sexp
)))
343 (defvar sh-shell-variables nil
344 "Alist of shell variable names that should be included in completion.
345 These are used for completion in addition to all the variables named
346 in `process-environment'. Each element looks like (VAR . VAR), where
347 the car and cdr are the same symbol.")
349 (defvar sh-shell-variables-initialized nil
350 "Non-nil if `sh-shell-variables' is initialized.")
352 (defun sh-canonicalize-shell (shell)
353 "Convert a shell name SHELL to the one we should handle it as."
354 (if (string-match "\\.exe\\'" shell
)
355 (setq shell
(substring shell
0 (match-beginning 0))))
357 (setq shell
(intern shell
)))
358 (or (cdr (assq shell sh-alias-alist
))
361 (defvar sh-shell
(sh-canonicalize-shell (file-name-nondirectory sh-shell-file
))
362 "The shell being programmed. This is set by \\[sh-set-shell].")
363 ;;;###autoload(put 'sh-shell 'safe-local-variable 'symbolp)
365 (define-abbrev-table 'sh-mode-abbrev-table
())
368 ;; I turned off this feature because it doesn't permit typing commands
369 ;; in the usual way without help.
371 ;; '((csh sh-abbrevs shell
373 ;; "getopts" 'sh-while-getopts)
375 ;; (es sh-abbrevs shell
376 ;; "function" 'sh-function)
378 ;; (ksh88 sh-abbrevs sh
379 ;; "select" 'sh-select)
381 ;; (rc sh-abbrevs shell
383 ;; "function" 'sh-function)
385 ;; (sh sh-abbrevs shell
387 ;; "function" 'sh-function
389 ;; "getopts" 'sh-while-getopts)
391 ;; ;; The next entry is only used for defining the others
392 ;; (shell "for" sh-for
393 ;; "loop" sh-indexed-loop
395 ;; "tmpfile" sh-tmp-file
398 ;; (zsh sh-abbrevs ksh88
399 ;; "repeat" 'sh-repeat))
400 ;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
401 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
402 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
406 (defun sh-mode-syntax-table (table &rest list
)
407 "Copy TABLE and set syntax for successive CHARs according to strings S."
408 (setq table
(copy-syntax-table table
))
410 (modify-syntax-entry (pop list
) (pop list
) table
))
413 (defvar sh-mode-syntax-table
414 (sh-mode-syntax-table ()
420 ;; ?$ might also have a ". p" syntax. Both "'" and ". p" seem
421 ;; to work fine. This is needed so that dabbrev-expand
434 "The syntax table to use for Shell-Script mode.
435 This is buffer-local in every such buffer.")
437 (defvar sh-mode-syntax-table-input
439 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
442 (let ((map (make-sparse-keymap))
443 (menu-map (make-sparse-keymap)))
444 (define-key map
"\C-c(" 'sh-function
)
445 (define-key map
"\C-c\C-w" 'sh-while
)
446 (define-key map
"\C-c\C-u" 'sh-until
)
447 (define-key map
"\C-c\C-t" 'sh-tmp-file
)
448 (define-key map
"\C-c\C-s" 'sh-select
)
449 (define-key map
"\C-c\C-r" 'sh-repeat
)
450 (define-key map
"\C-c\C-o" 'sh-while-getopts
)
451 (define-key map
"\C-c\C-l" 'sh-indexed-loop
)
452 (define-key map
"\C-c\C-i" 'sh-if
)
453 (define-key map
"\C-c\C-f" 'sh-for
)
454 (define-key map
"\C-c\C-c" 'sh-case
)
455 (define-key map
"\C-c?" 'sh-show-indent
)
456 (define-key map
"\C-c=" 'sh-set-indent
)
457 (define-key map
"\C-c<" 'sh-learn-line-indent
)
458 (define-key map
"\C-c>" 'sh-learn-buffer-indent
)
459 (define-key map
"\C-c\C-\\" 'sh-backslash-region
)
461 (define-key map
"=" 'sh-assignment
)
462 (define-key map
"\C-c+" 'sh-add
)
463 (define-key map
"\C-\M-x" 'sh-execute-region
)
464 (define-key map
"\C-c\C-x" 'executable-interpret
)
466 (define-key map
[remap complete-tag
] 'comint-dynamic-complete
)
467 (define-key map
[remap delete-backward-char
]
468 'backward-delete-char-untabify
)
469 (define-key map
"\C-c:" 'sh-set-shell
)
470 (define-key map
[remap backward-sentence
] 'sh-beginning-of-command
)
471 (define-key map
[remap forward-sentence
] 'sh-end-of-command
)
472 (define-key map
[menu-bar sh-script
] (cons "Sh-Script" menu-map
))
473 (define-key menu-map
[sh-learn-buffer-indent
]
474 '(menu-item "Learn buffer indentation" sh-learn-buffer-indent
475 :help
"Learn how to indent the buffer the way it currently is."))
476 (define-key menu-map
[sh-learn-line-indent
]
477 '(menu-item "Learn line indentation" sh-learn-line-indent
478 :help
"Learn how to indent a line as it currently is indented"))
479 (define-key menu-map
[sh-show-indent
]
480 '(menu-item "Show indentation" sh-show-indent
481 :help
"Show the how the current line would be indented"))
482 (define-key menu-map
[sh-set-indent
]
483 '(menu-item "Set indentation" sh-set-indent
484 :help
"Set the indentation for the current line"))
486 (define-key menu-map
[sh-pair
]
487 '(menu-item "Insert braces and quotes in pairs"
489 :button
(:toggle .
(bound-and-true-p electric-pair-mode
))
490 :help
"Inserting a brace or quote automatically inserts the matching pair"))
492 (define-key menu-map
[sh-s0
] '("--"))
494 (define-key menu-map
[sh-function
]
495 '(menu-item "Function..." sh-function
496 :help
"Insert a function definition"))
497 (define-key menu-map
[sh-add
]
498 '(menu-item "Addition..." sh-add
499 :help
"Insert an addition of VAR and prefix DELTA for Bourne (type) shell"))
500 (define-key menu-map
[sh-until
]
501 '(menu-item "Until Loop" sh-until
502 :help
"Insert an until loop"))
503 (define-key menu-map
[sh-repeat
]
504 '(menu-item "Repeat Loop" sh-repeat
505 :help
"Insert a repeat loop definition"))
506 (define-key menu-map
[sh-while
]
507 '(menu-item "While Loop" sh-while
508 :help
"Insert a while loop"))
509 (define-key menu-map
[sh-getopts
]
510 '(menu-item "Options Loop" sh-while-getopts
511 :help
"Insert a while getopts loop."))
512 (define-key menu-map
[sh-indexed-loop
]
513 '(menu-item "Indexed Loop" sh-indexed-loop
514 :help
"Insert an indexed loop from 1 to n."))
515 (define-key menu-map
[sh-select
]
516 '(menu-item "Select Statement" sh-select
517 :help
"Insert a select statement "))
518 (define-key menu-map
[sh-if
]
519 '(menu-item "If Statement" sh-if
520 :help
"Insert an if statement"))
521 (define-key menu-map
[sh-for
]
522 '(menu-item "For Loop" sh-for
523 :help
"Insert a for loop"))
524 (define-key menu-map
[sh-case
]
525 '(menu-item "Case Statement" sh-case
526 :help
"Insert a case/switch statement"))
527 (define-key menu-map
[sh-s1
] '("--"))
528 (define-key menu-map
[sh-exec
]
529 '(menu-item "Execute region" sh-execute-region
530 :help
"Pass optional header and region to a subshell for noninteractive execution"))
531 (define-key menu-map
[sh-exec-interpret
]
532 '(menu-item "Execute script..." executable-interpret
533 :help
"Run script with user-specified args, and collect output in a buffer"))
534 (define-key menu-map
[sh-set-shell
]
535 '(menu-item "Set shell type..." sh-set-shell
536 :help
"Set this buffer's shell to SHELL (a string)"))
537 (define-key menu-map
[sh-backslash-region
]
538 '(menu-item "Backslash region" sh-backslash-region
539 :help
"Insert, align, or delete end-of-line backslashes on the lines in the region."))
541 "Keymap used in Shell-Script mode.")
543 (defvar sh-skeleton-pair-default-alist
'((?
( _ ?
)) (?\
))
544 (?
[ ?\s _ ?\s ?
]) (?\
])
546 "Value to use for `skeleton-pair-default-alist' in Shell-Script mode.")
548 (defcustom sh-dynamic-complete-functions
549 '(shell-dynamic-complete-environment-variable
550 shell-dynamic-complete-command
551 comint-dynamic-complete-filename
)
552 "Functions for doing TAB dynamic completion."
553 :type
'(repeat function
)
556 (defcustom sh-assignment-regexp
557 `((csh .
"\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
558 ;; actually spaces are only supported in let/(( ... ))
559 (ksh88 .
,(concat "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?"
560 "[ \t]*\\(?:[-+*/%&|~^]\\|<<\\|>>\\)?="))
561 (bash .
"\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?\\+?=")
562 (rc .
"\\<\\([[:alnum:]_*]+\\)[ \t]*=")
563 (sh .
"\\<\\([[:alnum:]_]+\\)="))
564 "Regexp for the variable name and what may follow in an assignment.
565 First grouping matches the variable name. This is upto and including the `='
566 sign. See `sh-feature'."
567 :type
'(repeat (cons (symbol :tag
"Shell")
569 (sexp :format
"Evaluate: %v"))))
573 (defcustom sh-indentation
4
574 "The width for further indentation in Shell-Script mode."
577 (put 'sh-indentation
'safe-local-variable
'integerp
)
579 (defcustom sh-remember-variable-min
3
580 "Don't remember variables less than this length for completing reads."
585 (defvar sh-header-marker nil
586 "When non-nil is the end of header for prepending by \\[sh-execute-region].
587 That command is also used for setting this variable.")
588 (make-variable-buffer-local 'sh-header-marker
)
590 (defcustom sh-beginning-of-command
591 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~[:alnum:]:]\\)"
592 "Regexp to determine the beginning of a shell command.
593 The actual command starts at the beginning of the second \\(grouping\\)."
598 (defcustom sh-end-of-command
599 "\\([/~[:alnum:]:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
600 "Regexp to determine the end of a shell command.
601 The actual command ends at the end of the first \\(grouping\\)."
607 (defcustom sh-here-document-word
"EOF"
608 "Word to delimit here documents.
609 If the first character of this string is \"-\", this is taken as
610 part of the redirection operator, rather than part of the
611 word (that is, \"<<-\" instead of \"<<\"). This is a feature
612 used by some shells (for example Bash) to indicate that leading
613 tabs inside the here document should be ignored. In this case,
614 Emacs indents the initial body and end of the here document with
615 tabs, to the same level as the start (note that apart from this
616 there is no support for indentation of here documents). This
617 will only work correctly if `sh-basic-offset' is a multiple of
620 Any quote characters or leading whitespace in the word are
621 removed when closing the here document."
629 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
632 ;; customized this out of sheer bravado. not for the faint of heart.
633 ;; but it *did* have an asterisk in the docstring!
634 (defcustom sh-builtins
635 '((bash sh-append posix
636 "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
637 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
638 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
639 "source" "suspend" "typeset" "unalias")
641 ;; The next entry is only used for defining the others
642 (bourne sh-append shell
643 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
647 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
648 "setenv" "source" "time" "unalias" "unhash")
650 (dtksh sh-append wksh
)
652 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
653 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
656 "bg" "fg" "jobs" "kill" "stop" "suspend")
659 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
661 (ksh88 sh-append bourne
662 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
663 "typeset" "unalias" "whence")
666 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
667 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
668 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
669 "wmtitle" "wrefresh")
671 (pdksh sh-append ksh88
677 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
681 "hash" "test" "type")
683 ;; The next entry is only used for defining the others
684 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
686 (wksh sh-append ksh88
687 ;; FIXME: This looks too much like a regexp. --Stef
691 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
692 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
693 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
694 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
695 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
697 "List of all shell builtins for completing read and fontification.
698 Note that on some systems not all builtins are available or some are
699 implemented as aliases. See `sh-feature'."
700 :type
'(repeat (cons (symbol :tag
"Shell")
701 (choice (repeat string
)
702 (sexp :format
"Evaluate: %v"))))
707 (defcustom sh-leading-keywords
713 (es "true" "unwind-protect" "whatis")
717 (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
718 "List of keywords that may be immediately followed by a builtin or keyword.
719 Given some confusion between keywords and builtins depending on shell and
720 system, the distinction here has been based on whether they influence the
721 flow of control or syntax. See `sh-feature'."
722 :type
'(repeat (cons (symbol :tag
"Shell")
723 (choice (repeat string
)
724 (sexp :format
"Evaluate: %v"))))
728 (defcustom sh-other-keywords
729 '((bash sh-append bourne
730 "bye" "logout" "select")
732 ;; The next entry is only used for defining the others
737 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
738 "if" "logout" "onintr" "repeat" "switch" "then" "while")
740 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
741 "return" "throw" "while")
743 (ksh88 sh-append bourne
746 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
750 "done" "esac" "fi" "for" "in" "return")
752 ;; The next entry is only used for defining the others
753 (shell "break" "case" "continue" "exec" "exit")
757 "List of keywords not in `sh-leading-keywords'.
759 :type
'(repeat (cons (symbol :tag
"Shell")
760 (choice (repeat string
)
761 (sexp :format
"Evaluate: %v"))))
768 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
769 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
770 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
771 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
772 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
773 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
774 "HISTIGNORE" "history_control" "HISTSIZE"
775 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
776 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
777 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
778 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
779 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
780 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
781 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
784 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
785 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
786 "shell" "status" "time" "verbose")
789 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
790 "pid" "prompt" "signals")
796 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
797 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
801 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
804 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
808 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
810 ;; The next entry is only used for defining the others
811 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
812 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
813 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
814 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
817 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
818 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
819 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
820 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
821 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
822 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
823 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
824 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
828 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
829 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
830 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
831 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
832 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
833 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
834 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
835 "List of all shell variables available for completing read.
842 '((((min-colors 88) (class color
)
844 (:foreground
"yellow1" :weight bold
))
847 (:foreground
"yellow" :weight bold
))
850 (:foreground
"tan1" ))
853 "Face to show a here-document"
854 :group
'sh-indentation
)
856 ;; These colors are probably icky. It's just a placeholder though.
857 (defface sh-quoted-exec
858 '((((class color
) (background dark
))
859 (:foreground
"salmon"))
860 (((class color
) (background light
))
861 (:foreground
"magenta"))
864 "Face to show quoted execs like ``"
865 :group
'sh-indentation
)
866 (define-obsolete-face-alias 'sh-heredoc-face
'sh-heredoc
"22.1")
867 (defvar sh-heredoc-face
'sh-heredoc
)
869 (defface sh-escaped-newline
'((t :inherit font-lock-string-face
))
870 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
874 (defvar sh-font-lock-keywords-var
875 '((csh sh-append shell
876 ("\\${?[#?]?\\([[:alpha:]_][[:alnum:]_]*\\|0\\)" 1
877 font-lock-variable-name-face
))
879 (es sh-append executable-font-lock-keywords
880 ("\\$#?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\)" 1
881 font-lock-variable-name-face
))
884 (bash sh-append sh
("\\$(\\(\\sw+\\)" (1 'sh-quoted-exec t
) ))
887 ("\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?@!]\\)" 2
888 font-lock-variable-name-face
)
890 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face
)
891 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
892 (1 font-lock-keyword-face
) (2 font-lock-function-name-face nil t
))
893 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
894 1 font-lock-negation-char-face
))
896 ;; The next entry is only used for defining the others
898 ;; Using font-lock-string-face here confuses sh-get-indent-info.
899 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline
)
900 ("\\\\[^[:alnum:]]" 0 font-lock-string-face
)
901 ("\\${?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\|[$*_]\\)" 1
902 font-lock-variable-name-face
))
904 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face
))
905 (rpm2 sh-append shell
906 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face
)))
907 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
909 (defvar sh-font-lock-keywords-var-1
911 "Subdued level highlighting for Shell Script modes.")
913 (defvar sh-font-lock-keywords-var-2
()
914 "Gaudy level highlighting for Shell Script modes.")
916 ;; These are used for the syntax table stuff (derived from cperl-mode).
917 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
918 (defconst sh-st-punc
(string-to-syntax "."))
919 (defconst sh-here-doc-syntax
(string-to-syntax "|")) ;; generic string
922 (defconst sh-escaped-line-re
923 ;; Should match until the real end-of-continued-line, but if that is not
924 ;; possible (because we bump into EOB or the search bound), then we should
925 ;; match until the search bound.
926 "\\(?:\\(?:.*[^\\\n]\\)?\\(?:\\\\\\\\\\)*\\\\\n\\)*.*")
928 (defconst sh-here-doc-open-re
929 (concat "<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\|[-/~._]\\)+\\)"
930 sh-escaped-line-re
"\\(\n\\)")))
932 (defun sh-font-lock-open-heredoc (start string eol
)
933 "Determine the syntax of the \\n after a <<EOF.
934 START is the position of <<.
935 STRING is the actual word used as delimiter (e.g. \"EOF\").
936 INDENTED is non-nil if the here document's content (and the EOF mark) can
937 be indented (i.e. a <<- was used rather than just <<).
938 Point is at the beginning of the next line."
939 (unless (or (memq (char-before start
) '(?
< ?
>))
940 (sh-in-comment-or-string start
))
941 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
942 ;; font-lock keywords to detect the end of this here document.
943 (let ((str (replace-regexp-in-string "['\"]" "" string
))
944 (ppss (save-excursion (syntax-ppss eol
))))
946 ;; The \n not only starts the heredoc but also closes a comment.
947 ;; Let's close the comment just before the \n.
948 (put-text-property (1- eol
) eol
'syntax-table
'(12))) ;">"
949 (if (or (nth 5 ppss
) (> (count-lines start eol
) 1))
950 ;; If the sh-escaped-line-re part of sh-here-doc-open-re has matched
951 ;; several lines, make sure we refontify them together.
952 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
953 ;; escaped), it means the right \n is actually further down.
954 ;; Don't bother fixing it now, but place a multiline property so
955 ;; that when jit-lock-context-* refontifies the rest of the
956 ;; buffer, it also refontifies the current line with it.
957 (put-text-property start
(1+ eol
) 'syntax-multiline t
))
958 (put-text-property eol
(1+ eol
) 'sh-here-doc-marker str
)
959 (prog1 sh-here-doc-syntax
960 (goto-char (+ 2 start
))))))
962 (defun sh-syntax-propertize-here-doc (end)
963 (let ((ppss (syntax-ppss)))
964 (when (eq t
(nth 3 ppss
))
965 (let ((key (get-text-property (nth 8 ppss
) 'sh-here-doc-marker
))
966 (case-fold-search nil
))
967 (when (re-search-forward
968 (concat "^\\([ \t]*\\)" (regexp-quote key
) "\\(\n\\)")
970 (let ((eol (match-beginning 2)))
971 (put-text-property eol
(1+ eol
)
972 'syntax-table sh-here-doc-syntax
)))))))
974 (defun sh-font-lock-quoted-subshell (limit)
975 "Search for a subshell embedded in a string.
976 Find all the unescaped \" characters within said subshell, remembering that
978 ;; FIXME: This can (and often does) match multiple lines, yet it makes no
979 ;; effort to handle multiline cases correctly, so it ends up being
981 (when (eq ?
\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
982 ;; bingo we have a $( or a ` inside a ""
983 (let (;; `state' can be: double-quote, backquote, code.
984 (state (if (eq (char-before) ?
`) 'backquote
'code
))
985 ;; Stacked states in the context.
986 (states '(double-quote)))
987 (while (and state
(progn (skip-chars-forward "^'\\\\\"`$()" limit
)
989 ;; unescape " inside a $( ... ) construct.
993 (t (forward-char 1) (skip-chars-forward "^'" limit
))))
994 (?
\\ (forward-char 1))
996 (double-quote (setq state
(pop states
)))
997 (t (push state states
) (setq state
'double-quote
)))
998 (if state
(put-text-property (point) (1+ (point))
999 'syntax-table
'(1))))
1001 (backquote (setq state
(pop states
)))
1002 (t (push state states
) (setq state
'backquote
))))
1003 (?\$
(if (not (eq (char-after (1+ (point))) ?\
())
1007 (t (push state states
) (setq state
'code
)))))
1010 (t (push state states
) (setq state
'code
))))
1013 (t (setq state
(pop states
)))))
1014 (t (error "Internal error in sh-font-lock-quoted-subshell")))
1015 (forward-char 1)))))
1018 (defun sh-is-quoted-p (pos)
1019 (and (eq (char-before pos
) ?
\\)
1020 (not (sh-is-quoted-p (1- pos
)))))
1022 (defun sh-font-lock-paren (start)
1023 (unless (nth 8 (syntax-ppss))
1026 ;; Skip through all patterns
1031 (forward-comment (- (point-max)))
1032 (when (and (eolp) (sh-is-quoted-p (point)))
1035 ;; Skip through one pattern
1037 (or (/= 0 (skip-syntax-backward "w_"))
1038 (/= 0 (skip-chars-backward "-$=?[]*@/\\\\"))
1039 (and (sh-is-quoted-p (1- (point)))
1040 (goto-char (- (point) 2)))
1041 (when (memq (char-before) '(?
\" ?
\' ?\
}))
1042 (condition-case nil
(progn (backward-sexp 1) t
)
1044 ;; Patterns can be preceded by an open-paren (Bug#1320).
1045 (if (eq (char-before (point)) ?\
()
1048 (forward-comment (- (point-max)))
1049 ;; Maybe we've bumped into an escaped newline.
1050 (sh-is-quoted-p (point)))
1052 (when (eq (char-before) ?|
)
1053 (backward-char 1) t
)))
1054 (when (progn (backward-char 2)
1055 (if (> start
(line-end-position))
1056 (put-text-property (point) (1+ start
)
1057 'syntax-multiline t
))
1058 ;; FIXME: The `in' may just be a random argument to
1059 ;; a normal command rather than the real `in' keyword.
1060 ;; I.e. we should look back to try and find the
1061 ;; corresponding `case'.
1062 (and (looking-at ";[;&]\\|\\_<in")
1063 ;; ";; esac )" is a case that looks like a case-pattern
1064 ;; but it's really just a close paren after a case
1065 ;; statement. I.e. if we skipped over `esac' just now,
1066 ;; we're not looking at a case-pattern.
1067 (not (looking-at "..[ \t\n]+esac[^[:word:]_]"))))
1070 (defun sh-font-lock-backslash-quote ()
1071 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?
\')
1072 ;; In a '...' the backslash is not escaping.
1076 (defun sh-syntax-propertize-function (start end
)
1078 (sh-syntax-propertize-here-doc end
)
1080 (syntax-propertize-rules
1081 (sh-here-doc-open-re
1082 (2 (sh-font-lock-open-heredoc
1083 (match-beginning 0) (match-string 1) (match-beginning 2))))
1084 ("\\s|" (0 (prog1 nil
(sh-syntax-propertize-here-doc end
))))
1085 ;; A `#' begins a comment when it is unquoted and at the
1086 ;; beginning of a word. In the shell, words are separated by
1087 ;; metacharacters. The list of special chars is taken from
1088 ;; the single-unix spec of the shell command language (under
1089 ;; `quoting') but with `$' removed.
1090 ("[^|&;<>()`\\\"' \t\n]\\(#+\\)" (1 "_"))
1091 ;; In a '...' the backslash is not escaping.
1092 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1093 ;; Make sure $@ and $? are correctly recognized as sexps.
1094 ("\\$\\([?@]\\)" (1 "_"))
1095 ;; Distinguish the special close-paren in `case'.
1096 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1097 ;; Highlight (possibly nested) subshells inside "" quoted
1098 ;; regions correctly.
1099 ("\"\\(?:\\(?:[^\\\"]\\|\\)*?[^\\]\\(?:\\\\\\\\\\)*\\)??\\(\\$(\\|`\\)"
1101 ;; Save excursion because we want to also apply other
1102 ;; syntax-propertize rules within the affected region.
1103 (if (nth 8 (syntax-ppss))
1104 (goto-char (1+ (match-beginning 0)))
1106 (sh-font-lock-quoted-subshell end
)))))))
1109 (defun sh-font-lock-syntactic-face-function (state)
1110 (let ((q (nth 3 state
)))
1113 (if (eq q ?\
`) 'sh-quoted-exec font-lock-string-face
)
1115 font-lock-comment-face
)))
1117 (defgroup sh-indentation nil
1118 "Variables controlling indentation in shell scripts.
1120 Note: customizing these variables will not affect existing buffers if
1121 `sh-make-vars-local' is non-nil. See the documentation for
1122 variable `sh-make-vars-local', command `sh-make-vars-local'
1123 and command `sh-reset-indent-vars-to-global-values'."
1127 (defcustom sh-set-shell-hook nil
1128 "Hook run by `sh-set-shell'."
1132 (defcustom sh-mode-hook nil
1133 "Hook run by `sh-mode'."
1137 (defcustom sh-learn-basic-offset nil
1138 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1141 t means: only if there seems to be an obvious value.
1142 Anything else means: whenever we have a \"good guess\" as to the value."
1144 (const :tag
"Never" nil
)
1145 (const :tag
"Only if sure" t
)
1146 (const :tag
"If have a good guess" usually
))
1147 :group
'sh-indentation
)
1149 (defcustom sh-popup-occur-buffer nil
1150 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1151 If t it is always shown. If nil, it is shown only when there
1154 (const :tag
"Only when there are conflicts." nil
)
1155 (const :tag
"Always" t
))
1156 :group
'sh-indentation
)
1158 (defcustom sh-blink t
1159 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
1160 The position on the line is not necessarily meaningful.
1161 In some cases the line will be the matching keyword, but this is not
1164 :group
'sh-indentation
)
1166 (defcustom sh-first-lines-indent
0
1167 "The indentation of the first non-blank non-comment line.
1168 Usually 0 meaning first column.
1169 Can be set to a number, or to nil which means leave it as is."
1171 (const :tag
"Leave as is" nil
)
1172 (integer :tag
"Column number"
1173 :menu-tag
"Indent to this col (0 means first col)" ))
1174 :group
'sh-indentation
)
1177 (defcustom sh-basic-offset
4
1178 "The default indentation increment.
1179 This value is used for the `+' and `-' symbols in an indentation variable."
1181 :group
'sh-indentation
)
1182 (put 'sh-basic-offset
'safe-local-variable
'integerp
)
1184 (defcustom sh-indent-comment nil
1185 "How a comment line is to be indented.
1186 nil means leave it as it is;
1187 t means indent it as a normal line, aligning it to previous non-blank
1189 a number means align to that column, e.g. 0 means first column."
1191 (const :tag
"Leave as is." nil
)
1192 (const :tag
"Indent as a normal line." t
)
1193 (integer :menu-tag
"Indent to this col (0 means first col)."
1194 :tag
"Indent to column number.") )
1195 :group
'sh-indentation
)
1198 (defvar sh-debug nil
1199 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1202 ;; Uncomment this defun and comment the defmacro for debugging.
1203 ;; (defun sh-debug (&rest args)
1204 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1206 ;; (apply 'message args)))
1207 (defmacro sh-debug
(&rest _args
))
1209 (defconst sh-symbol-list
1210 '((const :tag
"+ " :value
+
1211 :menu-tag
"+ Indent right by sh-basic-offset")
1212 (const :tag
"- " :value -
1213 :menu-tag
"- Indent left by sh-basic-offset")
1214 (const :tag
"++" :value
++
1215 :menu-tag
"++ Indent right twice sh-basic-offset")
1216 (const :tag
"--" :value --
1217 :menu-tag
"-- Indent left twice sh-basic-offset")
1218 (const :tag
"* " :value
*
1219 :menu-tag
"* Indent right half sh-basic-offset")
1220 (const :tag
"/ " :value
/
1221 :menu-tag
"/ Indent left half sh-basic-offset")))
1223 (defcustom sh-indent-for-else
0
1224 "How much to indent an `else' relative to its `if'. Usually 0."
1226 (integer :menu-tag
"A number (positive=>indent right)"
1228 (const :tag
"--") ;; separator!
1231 :group
'sh-indentation
)
1233 (defconst sh-number-or-symbol-list
1234 (append '((integer :menu-tag
"A number (positive=>indent right)"
1236 (const :tag
"--")) ; separator
1239 (defcustom sh-indent-for-fi
0
1240 "How much to indent a `fi' relative to its `if'. Usually 0."
1241 :type
`(choice ,@ sh-number-or-symbol-list
)
1242 :group
'sh-indentation
)
1244 (defcustom sh-indent-for-done
0
1245 "How much to indent a `done' relative to its matching stmt. Usually 0."
1246 :type
`(choice ,@ sh-number-or-symbol-list
)
1247 :group
'sh-indentation
)
1249 (defcustom sh-indent-after-else
'+
1250 "How much to indent a statement after an `else' statement."
1251 :type
`(choice ,@ sh-number-or-symbol-list
)
1252 :group
'sh-indentation
)
1254 (defcustom sh-indent-after-if
'+
1255 "How much to indent a statement after an `if' statement.
1256 This includes lines after `else' and `elif' statements, too, but
1257 does not affect the `else', `elif' or `fi' statements themselves."
1258 :type
`(choice ,@ sh-number-or-symbol-list
)
1259 :group
'sh-indentation
)
1261 (defcustom sh-indent-for-then
0
1262 "How much to indent a `then' relative to its `if'."
1263 :type
`(choice ,@ sh-number-or-symbol-list
)
1264 :group
'sh-indentation
)
1266 (defcustom sh-indent-for-do
0
1267 "How much to indent a `do' statement.
1268 This is relative to the statement before the `do', typically a
1269 `while', `until', `for', `repeat' or `select' statement."
1270 :type
`(choice ,@ sh-number-or-symbol-list
)
1271 :group
'sh-indentation
)
1273 (defcustom sh-indent-after-do
'+
1274 "How much to indent a line after a `do' statement.
1275 This is used when the `do' is the first word of the line.
1276 This is relative to the statement before the `do', typically a
1277 `while', `until', `for', `repeat' or `select' statement."
1278 :type
`(choice ,@ sh-number-or-symbol-list
)
1279 :group
'sh-indentation
)
1281 (defcustom sh-indent-after-loop-construct
'+
1282 "How much to indent a statement after a loop construct.
1284 This variable is used when the keyword `do' is on the same line as the
1285 loop statement (e.g., `until', `while' or `for').
1286 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1287 :type
`(choice ,@ sh-number-or-symbol-list
)
1288 :group
'sh-indentation
)
1291 (defcustom sh-indent-after-done
0
1292 "How much to indent a statement after a `done' keyword.
1293 Normally this is 0, which aligns the `done' to the matching
1294 looping construct line.
1295 Setting it non-zero allows you to have the `do' statement on a line
1296 by itself and align the done under to do."
1297 :type
`(choice ,@ sh-number-or-symbol-list
)
1298 :group
'sh-indentation
)
1300 (defcustom sh-indent-for-case-label
'+
1301 "How much to indent a case label statement.
1302 This is relative to the line containing the `case' statement."
1303 :type
`(choice ,@ sh-number-or-symbol-list
)
1304 :group
'sh-indentation
)
1306 (defcustom sh-indent-for-case-alt
'++
1307 "How much to indent statements after the case label.
1308 This is relative to the line containing the `case' statement."
1309 :type
`(choice ,@ sh-number-or-symbol-list
)
1310 :group
'sh-indentation
)
1313 (defcustom sh-indent-for-continuation
'+
1314 "How much to indent for a continuation statement."
1315 :type
`(choice ,@ sh-number-or-symbol-list
)
1316 :group
'sh-indentation
)
1318 (defcustom sh-indent-after-open
'+
1319 "How much to indent after a line with an opening parenthesis or brace.
1320 For an open paren after a function, `sh-indent-after-function' is used."
1321 :type
`(choice ,@ sh-number-or-symbol-list
)
1322 :group
'sh-indentation
)
1324 (defcustom sh-indent-after-function
'+
1325 "How much to indent after a function line."
1326 :type
`(choice ,@ sh-number-or-symbol-list
)
1327 :group
'sh-indentation
)
1329 ;; These 2 are for the rc shell:
1331 (defcustom sh-indent-after-switch
'+
1332 "How much to indent a `case' statement relative to the `switch' statement.
1333 This is for the rc shell."
1334 :type
`(choice ,@ sh-number-or-symbol-list
)
1335 :group
'sh-indentation
)
1337 (defcustom sh-indent-after-case
'+
1338 "How much to indent a statement relative to the `case' statement.
1339 This is for the rc shell."
1340 :type
`(choice ,@ sh-number-or-symbol-list
)
1341 :group
'sh-indentation
)
1343 (defcustom sh-backslash-column
48
1344 "Column in which `sh-backslash-region' inserts backslashes."
1348 (defcustom sh-backslash-align t
1349 "If non-nil, `sh-backslash-region' will align backslashes."
1353 ;; Internal use - not designed to be changed by the user:
1355 (defun sh-mkword-regexpr (word)
1356 "Make a regexp which matches WORD as a word.
1357 This specifically excludes an occurrence of WORD followed by
1358 punctuation characters like '-'."
1359 (concat word
"\\([^-[:alnum:]_]\\|$\\)"))
1361 (defconst sh-re-done
(sh-mkword-regexpr "done"))
1364 (defconst sh-kws-for-done
1365 '((sh .
( "while" "until" "for" ) )
1366 (bash .
( "while" "until" "for" "select" ) )
1367 (ksh88 .
( "while" "until" "for" "select" ) )
1368 (zsh .
( "while" "until" "for" "repeat" "select" ) ) )
1369 "Which keywords can match the word `done' in this shell.")
1372 (defconst sh-indent-supported
1376 "Indentation rule set to use for each shell type.")
1378 (defvar sh-indent-supported-here nil
1379 "Non-nil if we support indentation for the current buffer's shell type.")
1381 (defconst sh-var-list
1383 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1384 sh-indent-after-do sh-indent-after-done
1385 sh-indent-after-else
1387 sh-indent-after-loop-construct
1388 sh-indent-after-open
1390 sh-indent-for-case-alt
1391 sh-indent-for-case-label
1392 sh-indent-for-continuation
1399 "A list of variables used by script mode to control indentation.
1400 This list is used when switching between buffer-local and global
1401 values of variables, and for the commands using indentation styles.")
1403 (defvar sh-make-vars-local t
1404 "Controls whether indentation variables are local to the buffer.
1405 If non-nil, indentation variables are made local initially.
1406 If nil, you can later make the variables local by invoking
1407 command `sh-make-vars-local'.
1408 The default is t because I assume that in one Emacs session one is
1409 frequently editing existing scripts with different styles.")
1412 ;; mode-command and utility functions
1415 (define-derived-mode sh-mode prog-mode
"Shell-script"
1416 "Major mode for editing shell scripts.
1417 This mode works for many shells, since they all have roughly the same syntax,
1418 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1419 Unless the file's magic number indicates the shell, your usual shell is
1420 assumed. Since filenames rarely give a clue, they are not further analyzed.
1422 This mode adapts to the variations between shells (see `sh-set-shell') by
1423 means of an inheritance based feature lookup (see `sh-feature'). This
1424 mechanism applies to all variables (including skeletons) that pertain to
1425 shell-specific features.
1427 The default style of this mode is that of Rosenblatt's Korn shell book.
1428 The syntax of the statements varies with the shell being used. The
1429 following commands are available, based on the current shell's syntax:
1431 \\[sh-case] case statement
1433 \\[sh-function] function definition
1434 \\[sh-if] if statement
1435 \\[sh-indexed-loop] indexed loop from 1 to n
1436 \\[sh-while-getopts] while getopts loop
1437 \\[sh-repeat] repeat loop
1438 \\[sh-select] select loop
1439 \\[sh-until] until loop
1440 \\[sh-while] while loop
1442 For sh and rc shells indentation commands are:
1443 \\[sh-show-indent] Show the variable controlling this line's indentation.
1444 \\[sh-set-indent] Set then variable controlling this line's indentation.
1445 \\[sh-learn-line-indent] Change the indentation variable so this line
1446 would indent to the way it currently is.
1447 \\[sh-learn-buffer-indent] Set the indentation variables so the
1448 buffer indents as it currently is indented.
1451 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1452 \\[newline-and-indent] Delete unquoted space and indent new line same as this one.
1453 \\[sh-end-of-command] Go to end of successive commands.
1454 \\[sh-beginning-of-command] Go to beginning of successive commands.
1455 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1456 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1458 `sh-electric-here-document-mode' controls whether insertion of two
1459 unquoted < insert a here document.
1461 If you generally program a shell different from your login shell you can
1462 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1463 indicate what shell it is use `sh-alias-alist' to translate.
1465 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1466 with your script for an edit-interpret-debug cycle."
1467 (make-local-variable 'sh-shell-file
)
1468 (make-local-variable 'sh-shell
)
1470 (set (make-local-variable 'skeleton-pair-default-alist
)
1471 sh-skeleton-pair-default-alist
)
1472 (set (make-local-variable 'skeleton-end-hook
)
1473 (lambda () (or (eolp) (newline) (indent-relative))))
1475 (set (make-local-variable 'paragraph-start
) (concat page-delimiter
"\\|$"))
1476 (set (make-local-variable 'paragraph-separate
) paragraph-start
)
1477 (set (make-local-variable 'comment-start
) "# ")
1478 (set (make-local-variable 'comment-start-skip
) "#+[\t ]*")
1479 (set (make-local-variable 'local-abbrev-table
) sh-mode-abbrev-table
)
1480 (set (make-local-variable 'comint-dynamic-complete-functions
)
1481 sh-dynamic-complete-functions
)
1482 ;; we can't look if previous line ended with `\'
1483 (set (make-local-variable 'comint-prompt-regexp
) "^[ \t]*")
1484 (set (make-local-variable 'imenu-case-fold-search
) nil
)
1485 (set (make-local-variable 'font-lock-defaults
)
1486 `((sh-font-lock-keywords
1487 sh-font-lock-keywords-1 sh-font-lock-keywords-2
)
1489 ((?
/ .
"w") (?~ .
"w") (?. .
"w") (?- .
"w") (?_ .
"w")) nil
1490 (font-lock-syntactic-face-function
1491 . sh-font-lock-syntactic-face-function
)))
1492 (set (make-local-variable 'syntax-propertize-function
)
1493 #'sh-syntax-propertize-function
)
1494 (add-hook 'syntax-propertize-extend-region-functions
1495 #'syntax-propertize-multiline
'append
'local
)
1496 (sh-electric-here-document-mode 1)
1497 (set (make-local-variable 'skeleton-pair-alist
) '((?
` _ ?
`)))
1498 (set (make-local-variable 'skeleton-pair-filter-function
) 'sh-quoted-p
)
1499 (set (make-local-variable 'skeleton-further-elements
)
1500 '((< '(- (min sh-indentation
(current-column))))))
1501 (set (make-local-variable 'skeleton-filter-function
) 'sh-feature
)
1502 (set (make-local-variable 'skeleton-newline-indent-rigidly
) t
)
1503 (set (make-local-variable 'defun-prompt-regexp
)
1504 (concat "^\\(function[ \t]\\|[[:alnum:]]+[ \t]+()[ \t]+\\)"))
1505 ;; Parse or insert magic number for exec, and set all variables depending
1506 ;; on the shell thus determined.
1508 (cond ((save-excursion
1509 (goto-char (point-min))
1510 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1512 ((not buffer-file-name
) sh-shell-file
)
1513 ;; Checks that use `buffer-file-name' follow.
1514 ((string-match "\\.m?spec\\'" buffer-file-name
) "rpm")
1515 ((string-match "[.]sh\\>" buffer-file-name
) "sh")
1516 ((string-match "[.]bash\\>" buffer-file-name
) "bash")
1517 ((string-match "[.]ksh\\>" buffer-file-name
) "ksh")
1518 ((string-match "[.]csh\\>" buffer-file-name
) "csh")
1519 ((equal (file-name-nondirectory buffer-file-name
) ".profile") "sh")
1524 (defalias 'shell-script-mode
'sh-mode
)
1527 (defun sh-font-lock-keywords (&optional keywords
)
1528 "Function to get simple fontification based on `sh-font-lock-keywords'.
1529 This adds rules for comments and assignments."
1530 (sh-feature sh-font-lock-keywords-var
1531 (when (stringp (sh-feature sh-assignment-regexp
))
1533 `((,(sh-feature sh-assignment-regexp
)
1534 1 font-lock-variable-name-face
)
1537 ,@executable-font-lock-keywords
)))))
1539 (defun sh-font-lock-keywords-1 (&optional builtins
)
1540 "Function to get better fontification including keywords."
1541 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1542 (regexp-opt (sh-feature sh-leading-keywords
) t
)
1544 (regexp-opt (append (sh-feature sh-leading-keywords
)
1545 (sh-feature sh-other-keywords
))
1547 (sh-font-lock-keywords
1549 `((,(concat keywords
"[ \t]+\\)?"
1550 (regexp-opt (sh-feature sh-builtins
) t
)
1552 (2 font-lock-keyword-face nil t
)
1553 (6 font-lock-builtin-face
))
1554 ,@(sh-feature sh-font-lock-keywords-var-2
)))
1555 (,(concat keywords
"\\)\\>")
1556 2 font-lock-keyword-face
)
1557 ,@(sh-feature sh-font-lock-keywords-var-1
)))))
1559 (defun sh-font-lock-keywords-2 ()
1560 "Function to get better fontification including keywords and builtins."
1561 (sh-font-lock-keywords-1 t
))
1563 ;;; Indentation and navigation with SMIE.
1567 ;; The SMIE code should generally be preferred, but it currently does not obey
1568 ;; the various indentation custom-vars, and it misses some important features
1569 ;; of the old code, mostly: sh-learn-line/buffer-indent, sh-show-indent,
1570 ;; sh-name/save/load-style.
1571 (defvar sh-use-smie nil
1572 "Whether to use the SMIE code for navigation and indentation.")
1574 (defun sh-smie--keyword-p (tok)
1575 "Non-nil if TOK (at which we're looking) really is a keyword."
1576 (let ((prev (funcall smie-backward-token-function
)))
1577 (if (zerop (length prev
))
1578 (looking-back "\\s(" (1- (point)))
1579 (assoc prev smie-grammar
))))
1581 (defun sh-smie--newline-semi-p (&optional tok
)
1582 "Return non-nil if a newline should be treated as a semi-colon.
1583 Here we assume that a newline should be treated as a semi-colon unless it
1584 comes right after a special keyword.
1585 This function does not pay attention to line-continuations.
1586 If TOK is nil, point should be before the newline; otherwise, TOK is the token
1587 before the newline and in that case point should be just before the token."
1590 (setq tok
(funcall smie-backward-token-function
)))
1591 (if (and (zerop (length tok
))
1592 (looking-back "\\s(" (1- (point))))
1594 (not (numberp (nth 2 (assoc tok smie-grammar
)))))))
1596 ;;;; SMIE support for `sh'.
1598 (defconst sh-smie-sh-grammar
1599 (smie-prec2->grammar
1601 '((exp) ;A constant, or a $var, or a sequence of them...
1602 (cmd ("case" exp
"in" branches
"esac")
1603 ("if" cmd
"then" cmd
"fi")
1604 ("if" cmd
"then" cmd
"else" cmd
"fi")
1605 ("if" cmd
"then" cmd
"elif" cmd
"then" cmd
"fi")
1606 ("if" cmd
"then" cmd
"elif" cmd
"then" cmd
"else" cmd
"fi")
1607 ("if" cmd
"then" cmd
"elif" cmd
"then" cmd
1608 "elif" cmd
"then" cmd
"else" cmd
"fi")
1609 ("while" cmd
"do" cmd
"done")
1610 ("until" cmd
"do" cmd
"done")
1611 ("for" exp
"in" cmd
"do" cmd
"done")
1612 ("for" exp
"do" cmd
"done")
1613 ("select" exp
"in" cmd
"do" cmd
"done") ;bash&zsh&ksh88.
1614 ("repeat" exp
"do" cmd
"done") ;zsh.
1615 (exp "always" exp
) ;zsh.
1616 (cmd "|" cmd
) (cmd "|&" cmd
)
1617 (cmd "&&" cmd
) (cmd "||" cmd
)
1618 (cmd ";" cmd
) (cmd "&" cmd
))
1619 (pattern (pattern "|" pattern
))
1620 (branches (branches ";;" branches
)
1621 (branches ";&" branches
) (branches ";;&" branches
) ;bash.
1622 (pattern "case-)" cmd
)))
1623 '((assoc ";;" ";&" ";;&"))
1624 '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
1626 (defconst sh-smie--sh-operators
1627 (delq nil
(mapcar (lambda (x)
1630 (not (string-match "\\`[a-z]" x
))
1632 sh-smie-sh-grammar
)))
1634 (defconst sh-smie--sh-operators-re
(regexp-opt sh-smie--sh-operators
))
1635 (defconst sh-smie--sh-operators-back-re
1636 (concat "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*"
1637 "\\(" sh-smie--sh-operators-re
"\\)"))
1639 (defun sh-smie--sh-keyword-in-p ()
1640 "Assuming we're looking at \"in\", return non-nil if it's a keyword.
1641 Does not preserve point."
1642 (let ((forward-sexp-function nil
)
1643 (words nil
) ;We've seen words.
1644 (newline nil
) ;We've seen newlines after the words.
1648 (setq prev
(funcall smie-backward-token-function
))
1650 ((zerop (length prev
))
1652 (progn (assert words
) (setq res
'word
))
1656 (scan-error (setq res
'unknown
)))))
1658 (if words
(setq newline t
)
1659 (setq res
'keyword
)))
1660 ((member prev
'("case" "for" "select")) (setq res
'keyword
))
1661 ((assoc prev smie-grammar
) (setq res
'word
))
1664 (progn (assert words
) (setq res
'word
))
1668 (defun sh-smie--sh-keyword-p (tok)
1669 "Non-nil if TOK (at which we're looking) really is a keyword."
1670 (if (equal tok
"in")
1671 (sh-smie--sh-keyword-in-p)
1672 (sh-smie--keyword-p tok
)))
1674 (defun sh-smie-sh-forward-token ()
1675 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
1677 (skip-chars-backward " \t")
1679 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
1680 ;; Right before a here-doc.
1681 (let ((forward-sexp-function nil
))
1683 ;; Pretend the here-document is a "newline representing a
1684 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1686 (let ((semi (sh-smie--newline-semi-p)))
1689 (sh-smie-sh-forward-token))))
1690 (forward-comment (point-max))
1692 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-sh-forward-token))
1693 ((looking-at sh-smie--sh-operators-re
)
1694 (goto-char (match-end 0))
1695 (let ((tok (match-string-no-properties 0)))
1696 (if (and (memq (aref tok
(1- (length tok
))) '(?\
; ?\& ?\|))
1697 (looking-at "[ \t]*\\(?:#\\|$\\)"))
1701 (let* ((pos (point))
1702 (tok (smie-default-forward-token)))
1704 ((equal tok
")") "case-)")
1705 ((and tok
(string-match "\\`[a-z]" tok
)
1706 (assoc tok smie-grammar
)
1710 (sh-smie--sh-keyword-p tok
))))
1714 (defun sh-smie--looking-back-at-continuation-p ()
1716 (and (if (eq (char-before) ?
\n) (progn (forward-char -
1) t
) (eolp))
1717 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
1718 (line-beginning-position)))))
1720 (defun sh-smie-sh-backward-token ()
1721 (let ((bol (line-beginning-position))
1723 (forward-comment (- (point)))
1725 ((and (bolp) (not (bobp))
1726 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
1727 (not (nth 3 (syntax-ppss))))
1728 ;; Right after a here-document.
1729 (let ((forward-sexp-function nil
))
1731 ;; Pretend the here-document is a "newline representing a
1732 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1736 ((sh-smie--looking-back-at-continuation-p)
1738 (funcall smie-backward-token-function
))
1739 ((sh-smie--newline-semi-p) ";")
1740 (t (funcall smie-backward-token-function
))))
1741 ((looking-back sh-smie--sh-operators-back-re
1742 (line-beginning-position) 'greedy
)
1743 (goto-char (match-beginning 1))
1744 (match-string-no-properties 1))
1746 (let ((tok (smie-default-backward-token)))
1748 ((equal tok
")") "case-)")
1749 ((and tok
(string-match "\\`[a-z]" tok
)
1750 (assoc tok smie-grammar
)
1751 (not (save-excursion (sh-smie--sh-keyword-p tok
))))
1755 (defcustom sh-indent-after-continuation t
1756 "If non-nil, try to make sure text is indented after a line continuation."
1759 (defun sh-smie--continuation-start-indent ()
1760 "Return the initial indentation of a continued line.
1761 May return nil if the line should not be treated as continued."
1764 (unless (sh-smie--looking-back-at-continuation-p)
1765 (current-indentation))))
1767 (defun sh-smie-sh-rules (kind token
)
1768 (pcase (cons kind token
)
1769 (`(:elem . basic
) sh-indentation
)
1770 (`(:after .
"case-)") (or sh-indentation smie-indent-basic
))
1771 ((and `(:before .
,_
)
1772 (guard (when sh-indent-after-continuation
1775 (skip-chars-backward " \t")
1776 (sh-smie--looking-back-at-continuation-p))))))
1777 ;; After a line-continuation, make sure the rest is indented.
1778 (let* ((sh-indent-after-continuation nil
)
1779 (indent (smie-indent-calculate))
1780 (initial (sh-smie--continuation-start-indent)))
1781 (when (and (numberp indent
) (numberp initial
)
1782 (<= indent initial
))
1783 `(column .
,(+ initial sh-indentation
)))))
1784 (`(:before .
,(or `"(" `"{" `"["))
1785 (if (smie-rule-hanging-p) (smie-rule-parent)))
1786 ;; FIXME: Maybe this handling of ;; should be made into
1787 ;; a smie-rule-terminator function that takes the substitute ";" as arg.
1788 (`(:before .
,(or `";;" `";&" `";;&"))
1789 (if (and (smie-rule-bolp) (looking-at ";;?&?[ \t]*\\(#\\|$\\)"))
1790 (cons 'column
(smie-indent-keyword ";"))
1791 (smie-rule-separator kind
)))
1792 (`(:after .
,(or `";;" `";&" `";;&"))
1793 (with-demoted-errors
1794 (smie-backward-sexp token
)
1796 (if (or (smie-rule-bolp)
1798 (and (member (funcall smie-backward-token-function
)
1802 (smie-indent-calculate)))))
1803 (`(:after .
"|") (if (smie-rule-parent-p "|") nil
4))
1806 ;; (defconst sh-smie-csh-grammar
1807 ;; (smie-prec2->grammar
1809 ;; '((exp) ;A constant, or a $var, or a sequence of them…
1811 ;; (cmd "else" "else-if" exp "then" elseifcmd))
1812 ;; (cmd ("switch" branches "endsw")
1814 ;; ("if" exp "then" cmd "endif")
1815 ;; ("if" exp "then" cmd "else" cmd "endif")
1816 ;; ("if" exp "then" elseifcmd "endif")
1817 ;; ;; ("if" exp "then" cmd "else" cmd "endif")
1818 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd "endif")
1819 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
1820 ;; ;; "else" cmd "endif")
1821 ;; ;; ("if" exp "then" cmd "else" "if" exp "then" cmd
1822 ;; ;; "else" "if" exp "then" cmd "endif")
1823 ;; ("while" cmd "end")
1824 ;; ("foreach" cmd "end")
1825 ;; (cmd "|" cmd) (cmd "|&" cmd)
1826 ;; (cmd "&&" cmd) (cmd "||" cmd)
1827 ;; (cmd ";" cmd) (cmd "&" cmd))
1828 ;; ;; This is a lie, but (combined with the corresponding disambiguation
1829 ;; ;; rule) it makes it more clear that `case' and `default' are the key
1830 ;; ;; separators and the `:' is a secondary tokens.
1831 ;; (branches (branches "case" branches)
1832 ;; (branches "default" branches)
1833 ;; (exp ":" branches)))
1834 ;; '((assoc "else" "then" "endif"))
1835 ;; '((assoc "case" "default") (nonassoc ":"))
1836 ;; '((assoc ";;" ";&" ";;&"))
1837 ;; '((assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
1839 ;;;; SMIE support for `rc'.
1841 (defconst sh-smie-rc-grammar
1842 (smie-prec2->grammar
1844 '((exp) ;A constant, or a $var, or a sequence of them...
1845 (cmd (cmd "case" cmd
)
1848 ("for" exp
) ("while" exp
)
1849 (cmd "|" cmd
) (cmd "|&" cmd
)
1850 (cmd "&&" cmd
) (cmd "||" cmd
)
1851 (cmd ";" cmd
) (cmd "&" cmd
))
1852 (pattern (pattern "|" pattern
))
1853 (branches (branches ";;" branches
)
1854 (branches ";&" branches
) (branches ";;&" branches
) ;bash.
1855 (pattern "case-)" cmd
)))
1856 '((assoc ";;" ";&" ";;&"))
1857 '((assoc "case") (assoc ";" "&") (assoc "&&" "||") (assoc "|" "|&")))))
1859 (defun sh-smie--rc-after-special-arg-p ()
1860 "Check if we're after the first arg of an if/while/for/... construct.
1861 Returns the construct's token and moves point before it, if so."
1862 (forward-comment (- (point)))
1863 (when (looking-back ")\\|\\_<not" (- (point) 3))
1865 (let ((forward-sexp-function nil
))
1867 (car (member (funcall smie-backward-token-function
)
1868 '("if" "for" "switch" "while")))))))
1870 (defun sh-smie--rc-newline-semi-p ()
1871 "Return non-nil if a newline should be treated as a semi-colon.
1872 Point should be before the newline."
1874 (let ((tok (funcall smie-backward-token-function
)))
1875 (if (or (when (equal tok
"not") (forward-word 1) t
)
1876 (and (zerop (length tok
)) (eq (char-before) ?\
))))
1877 (not (sh-smie--rc-after-special-arg-p))
1878 (sh-smie--newline-semi-p tok
)))))
1880 (defun sh-smie-rc-forward-token ()
1881 ;; FIXME: Code duplication with sh-smie-sh-forward-token.
1882 (if (and (looking-at "[ \t]*\\(?:#\\|\\(\\s|\\)\\|$\\)")
1884 (skip-chars-backward " \t")
1886 (if (and (match-end 1) (not (nth 3 (syntax-ppss))))
1887 ;; Right before a here-doc.
1888 (let ((forward-sexp-function nil
))
1890 ;; Pretend the here-document is a "newline representing a
1891 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1893 (let ((semi (sh-smie--rc-newline-semi-p)))
1896 (sh-smie-rc-forward-token))))
1897 (forward-comment (point-max))
1899 ((looking-at "\\\\\n") (forward-line 1) (sh-smie-rc-forward-token))
1900 ;; ((looking-at sh-smie--rc-operators-re)
1901 ;; (goto-char (match-end 0))
1902 ;; (let ((tok (match-string-no-properties 0)))
1903 ;; (if (and (memq (aref tok (1- (length tok))) '(?\; ?\& ?\|))
1904 ;; (looking-at "[ \t]*\\(?:#\\|$\\)"))
1905 ;; (forward-line 1))
1908 (let* ((pos (point))
1909 (tok (smie-default-forward-token)))
1911 ;; ((equal tok ")") "case-)")
1912 ((and tok
(string-match "\\`[a-z]" tok
)
1913 (assoc tok smie-grammar
)
1917 (sh-smie--keyword-p tok
))))
1921 (defun sh-smie-rc-backward-token ()
1922 ;; FIXME: Code duplication with sh-smie-sh-backward-token.
1923 (let ((bol (line-beginning-position))
1925 (forward-comment (- (point)))
1927 ((and (bolp) (not (bobp))
1928 (equal (syntax-after (1- (point))) (string-to-syntax "|"))
1929 (not (nth 3 (syntax-ppss))))
1930 ;; Right after a here-document.
1931 (let ((forward-sexp-function nil
))
1933 ;; Pretend the here-document is a "newline representing a
1934 ;; semi-colon", since the here-doc otherwise covers the newline(s).
1936 ((< (point) bol
) ;We skipped over a newline.
1938 ;; A continued line.
1940 (looking-back "\\(?:^\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\\\"
1941 (line-beginning-position)))
1943 (funcall smie-backward-token-function
))
1944 ((sh-smie--rc-newline-semi-p) ";")
1945 (t (funcall smie-backward-token-function
))))
1946 ;; ((looking-back sh-smie--sh-operators-back-re
1947 ;; (line-beginning-position) 'greedy)
1948 ;; (goto-char (match-beginning 1))
1949 ;; (match-string-no-properties 1))
1951 (let ((tok (smie-default-backward-token)))
1953 ;; ((equal tok ")") "case-)")
1954 ((and tok
(string-match "\\`[a-z]" tok
)
1955 (assoc tok smie-grammar
)
1956 (not (save-excursion (sh-smie--keyword-p tok
))))
1960 (defun sh-smie-rc-rules (kind token
)
1961 (pcase (cons kind token
)
1962 (`(:elem . basic
) sh-indentation
)
1963 ;; (`(:after . "case") (or sh-indentation smie-indent-basic))
1964 (`(:after .
";") (if (smie-rule-parent-p "case")
1965 (smie-rule-parent sh-indentation
)))
1968 (when (sh-smie--rc-after-special-arg-p)
1969 `(column .
,(current-column)))))
1970 (`(:before .
,(or `"(" `"{" `"["))
1971 (if (smie-rule-hanging-p) (smie-rule-parent)))
1972 ;; FIXME: SMIE parses "if (exp) cmd" as "(if ((exp) cmd))" so "cmd" is
1973 ;; treated as an arg to (exp) by default, which indents it all wrong.
1974 ;; To handle it right, we should extend smie-indent-exps so that the
1975 ;; preceding keyword can give special rules. Currently the only special
1976 ;; rule we have is the :list-intro hack, which we use here to align "cmd"
1977 ;; with "(exp)", which is rarely the right thing to do, but is better
1979 (`(:list-intro .
,(or `"for" `"if" `"while")) t
)
1982 ;;; End of SMIE code.
1984 (defvar sh-regexp-for-done nil
1985 "A buffer-local regexp to match opening keyword for done.")
1987 (defvar sh-kw-alist nil
1988 "A buffer-local, since it is shell-type dependent, list of keywords.")
1990 ;; ( key-word first-on-this on-prev-line )
1991 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1992 ;; having 3 elements:
1994 ;; a rule to check when the keyword appears on "this" line
1995 ;; a rule to check when the keyword appears on "the previous" line
1996 ;; The keyword is usually a string and is the first word on a line.
1997 ;; If this keyword appears on the line whose indentation is to be
1998 ;; calculated, the rule in element 2 is called. If this returns
1999 ;; non-zero, the resulting point (which may be changed by the rule)
2000 ;; is used as the default indentation.
2001 ;; If it returned false or the keyword was not found in the table,
2002 ;; then the keyword from the previous line is looked up and the rule
2003 ;; in element 3 is called. In this case, however,
2004 ;; `sh-get-indent-info' does not stop but may keep going and test
2005 ;; other keywords against rules in element 3. This is because the
2006 ;; preceding line could have, for example, an opening "if" and an
2007 ;; opening "while" keyword and we need to add the indentation offsets
2012 ("if" nil sh-handle-prev-if
)
2013 ("elif" sh-handle-this-else sh-handle-prev-else
)
2014 ("else" sh-handle-this-else sh-handle-prev-else
)
2015 ("fi" sh-handle-this-fi sh-handle-prev-fi
)
2016 ("then" sh-handle-this-then sh-handle-prev-then
)
2017 ("(" nil sh-handle-prev-open
)
2018 ("{" nil sh-handle-prev-open
)
2019 ("[" nil sh-handle-prev-open
)
2020 ("}" sh-handle-this-close nil
)
2021 (")" sh-handle-this-close nil
)
2022 ("]" sh-handle-this-close nil
)
2023 ("case" nil sh-handle-prev-case
)
2024 ("esac" sh-handle-this-esac sh-handle-prev-esac
)
2025 (case-label nil sh-handle-after-case-label
) ;; ???
2026 (";;" nil sh-handle-prev-case-alt-end
) ;; ???
2027 (";;&" nil sh-handle-prev-case-alt-end
) ;Like ";;" with diff semantics.
2028 (";&" nil sh-handle-prev-case-alt-end
) ;Like ";;" with diff semantics.
2029 ("done" sh-handle-this-done sh-handle-prev-done
)
2030 ("do" sh-handle-this-do sh-handle-prev-do
))
2032 ;; Note: we don't need specific stuff for bash and zsh shells;
2033 ;; the regexp `sh-regexp-for-done' handles the extra keywords
2034 ;; these shells use.
2036 ("{" nil sh-handle-prev-open
)
2037 ("}" sh-handle-this-close nil
)
2038 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case
))))
2042 (defun sh-set-shell (shell &optional no-query-flag insert-flag
)
2043 "Set this buffer's shell to SHELL (a string).
2044 When used interactively, insert the proper starting #!-line,
2045 and make the visited file executable via `executable-set-magic',
2046 perhaps querying depending on the value of `executable-query'.
2048 When this function is called noninteractively, INSERT-FLAG (the third
2049 argument) controls whether to insert a #!-line and think about making
2050 the visited file executable, and NO-QUERY-FLAG (the second argument)
2051 controls whether to query about making the visited file executable.
2053 Calls the value of `sh-set-shell-hook' if set."
2054 (interactive (list (completing-read (format "Shell \(default %s\): "
2056 interpreter-mode-alist
2057 (lambda (x) (eq (cdr x
) 'sh-mode
))
2058 nil nil nil sh-shell-file
)
2059 (eq executable-query
'function
)
2061 (if (string-match "\\.exe\\'" shell
)
2062 (setq shell
(substring shell
0 (match-beginning 0))))
2063 (setq sh-shell
(intern (file-name-nondirectory shell
))
2064 sh-shell
(or (cdr (assq sh-shell sh-alias-alist
))
2068 (executable-set-magic shell
(sh-feature sh-shell-arg
)
2069 no-query-flag insert-flag
)))
2070 (setq mode-line-process
(format "[%s]" sh-shell
))
2071 (set (make-local-variable 'sh-shell-variables
) nil
)
2072 (set (make-local-variable 'sh-shell-variables-initialized
) nil
)
2073 (set (make-local-variable 'imenu-generic-expression
)
2074 (sh-feature sh-imenu-generic-expression
))
2075 (let ((tem (sh-feature sh-mode-syntax-table-input
)))
2077 (set (make-local-variable 'sh-mode-syntax-table
)
2078 (apply 'sh-mode-syntax-table tem
))
2079 (set-syntax-table sh-mode-syntax-table
)))
2080 (dolist (var (sh-feature sh-variables
))
2081 (sh-remember-variable var
))
2082 (if (set (make-local-variable 'sh-indent-supported-here
)
2083 (sh-feature sh-indent-supported
))
2085 (message "Setting up indent for shell type %s" sh-shell
)
2087 (let ((mksym (lambda (name)
2088 (intern (format "sh-smie-%s-%s"
2089 sh-indent-supported-here name
)))))
2090 (smie-setup (symbol-value (funcall mksym
"grammar"))
2091 (funcall mksym
"rules")
2092 :forward-token
(funcall mksym
"forward-token")
2093 :backward-token
(funcall mksym
"backward-token")))
2094 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
2095 (set (make-local-variable 'sh-kw-alist
) (sh-feature sh-kw
))
2096 (let ((regexp (sh-feature sh-kws-for-done
)))
2098 (set (make-local-variable 'sh-regexp-for-done
)
2099 (sh-mkword-regexpr (regexp-opt regexp t
)))))
2100 (message "setting up indent stuff")
2101 ;; sh-mode has already made indent-line-function local
2102 ;; but do it in case this is called before that.
2103 (set (make-local-variable 'indent-line-function
) 'sh-indent-line
))
2104 (if sh-make-vars-local
2105 (sh-make-vars-local))
2106 (message "Indentation setup for shell type %s" sh-shell
))
2107 (message "No indentation for this shell type.")
2108 (setq indent-line-function
'sh-basic-indent-line
))
2109 (when font-lock-mode
2110 (setq font-lock-set-defaults nil
)
2111 (font-lock-set-defaults)
2112 (font-lock-fontify-buffer))
2113 (run-hooks 'sh-set-shell-hook
))
2116 (defun sh-feature (alist &optional function
)
2117 "Index ALIST by the current shell.
2118 If ALIST isn't a list where every element is a cons, it is returned as is.
2119 Else indexing follows an inheritance logic which works in two ways:
2121 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
2122 the alist contains no value for the current shell.
2123 The ultimate default is always `sh'.
2125 - If the value thus looked up is a list starting with `sh-append',
2126 we call the function `sh-append' with the rest of the list as
2127 arguments, and use the value. However, the next element of the
2128 list is not used as-is; instead, we look it up recursively
2129 in ALIST to allow the function called to define the value for
2130 one shell to be derived from another shell.
2131 The value thus determined is physically replaced into the alist.
2133 If FUNCTION is non-nil, it is called with one argument,
2134 the value thus obtained, and the result is used instead."
2135 (or (if (consp alist
)
2136 ;; Check for something that isn't a valid alist.
2138 (while (and l
(consp (car l
)))
2142 (let ((orig-sh-shell sh-shell
))
2143 (let ((sh-shell sh-shell
)
2145 (while (and sh-shell
2146 (not (setq elt
(assq sh-shell alist
))))
2147 (setq sh-shell
(cdr (assq sh-shell sh-ancestor-alist
))))
2148 ;; If the shell is not known, treat it as sh.
2150 (setq elt
(assq 'sh alist
)))
2151 (setq val
(cdr elt
))
2152 (if (and (consp val
)
2153 (memq (car val
) '(sh-append sh-modify
)))
2156 ;; Refer to the value for a different shell,
2157 ;; as a kind of inheritance.
2158 (let ((sh-shell (car (cdr val
))))
2162 (setq sh-shell orig-sh-shell
2163 val
(funcall function val
)))
2168 ;; I commented this out because nobody calls it -- rms.
2169 ;;(defun sh-abbrevs (ancestor &rest list)
2170 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
2171 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
2172 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
2173 ;;according to the remaining arguments NAMEi EXPANSIONi ...
2174 ;;EXPANSION may be either a string or a skeleton command."
2175 ;; (or (if (boundp sh-shell)
2176 ;; (symbol-value sh-shell))
2178 ;; (if (listp ancestor)
2179 ;; (nconc list ancestor))
2180 ;; (define-abbrev-table sh-shell ())
2181 ;; (if (vectorp ancestor)
2182 ;; (mapatoms (lambda (atom)
2184 ;; (define-abbrev (symbol-value sh-shell)
2185 ;; (symbol-name atom)
2186 ;; (symbol-value atom)
2187 ;; (symbol-function atom))))
2190 ;; (define-abbrev (symbol-value sh-shell)
2192 ;; (if (stringp (car (cdr list)))
2195 ;; (if (symbolp (car (cdr list)))
2196 ;; (car (cdr list))))
2197 ;; (setq list (cdr (cdr list)))))
2198 ;; (symbol-value sh-shell)))
2201 (defun sh-append (ancestor &rest list
)
2202 "Return list composed of first argument (a list) physically appended to rest."
2203 (nconc list ancestor
))
2206 (defun sh-modify (skeleton &rest list
)
2207 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
2208 (setq skeleton
(copy-sequence skeleton
))
2210 (setcar (or (nthcdr (car list
) skeleton
)
2211 (error "Index %d out of bounds" (car list
)))
2213 (setq list
(nthcdr 2 list
)))
2217 (defun sh-basic-indent-line ()
2218 "Indent a line for Sh mode (shell script mode).
2219 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
2220 Lines containing only comments are considered empty."
2222 (let ((previous (save-excursion
2223 (while (and (progn (beginning-of-line)
2227 (back-to-indentation)
2229 (eq (following-char) ?
#)))))
2233 (indent-to (if (eq this-command
'newline-and-indent
)
2235 (if (< (current-column)
2236 (setq current
(progn (back-to-indentation)
2238 (if (eolp) previous
0)
2239 (delete-region (point)
2240 (progn (beginning-of-line) (point)))
2242 (max previous
(* (1+ (/ current sh-indentation
))
2244 (* (1+ (/ current sh-indentation
)) sh-indentation
))))))
2245 (if (< (current-column) (current-indentation))
2246 (skip-chars-forward " \t"))))
2249 (defun sh-execute-region (start end
&optional flag
)
2250 "Pass optional header and region to a subshell for noninteractive execution.
2251 The working directory is that of the buffer, and only environment variables
2252 are already set which is why you can mark a header within the script.
2254 With a positive prefix ARG, instead of sending region, define header from
2255 beginning of buffer to point. With a negative prefix ARG, instead of sending
2256 region, clear header."
2257 (interactive "r\nP")
2259 (setq sh-header-marker
(if (> (prefix-numeric-value flag
) 0)
2261 (if sh-header-marker
2263 (let (buffer-undo-list)
2264 (goto-char sh-header-marker
)
2265 (append-to-buffer (current-buffer) start end
)
2266 (shell-command-on-region (point-min)
2267 (setq end
(+ sh-header-marker
2270 (delete-region sh-header-marker end
)))
2271 (shell-command-on-region start end
(concat sh-shell-file
" -")))))
2274 (defun sh-remember-variable (var)
2275 "Make VARIABLE available for future completing reads in this buffer."
2276 (or (< (length var
) sh-remember-variable-min
)
2278 (assoc var sh-shell-variables
)
2279 (push (cons var var
) sh-shell-variables
))
2284 (defun sh-quoted-p ()
2285 "Is point preceded by an odd number of backslashes?"
2286 (eq -
1 (%
(save-excursion (skip-chars-backward "\\\\")) 2)))
2288 ;; Indentation stuff.
2289 (defun sh-must-support-indent ()
2290 "Signal an error if the shell type for this buffer is not supported.
2291 Also, the buffer must be in Shell-script mode."
2292 (unless sh-indent-supported-here
2293 (error "This buffer's shell does not support indentation through Emacs")))
2295 (defun sh-make-vars-local ()
2296 "Make the indentation variables local to this buffer.
2297 Normally they already are local. This command is provided in case
2298 variable `sh-make-vars-local' has been set to nil.
2300 To revert all these variables to the global values, use
2301 command `sh-reset-indent-vars-to-global-values'."
2303 (mapc 'make-local-variable sh-var-list
)
2304 (message "Indentation variables are now local."))
2306 (defun sh-reset-indent-vars-to-global-values ()
2307 "Reset local indentation variables to the global values.
2308 Then, if variable `sh-make-vars-local' is non-nil, make them local."
2310 (mapc 'kill-local-variable sh-var-list
)
2311 (if sh-make-vars-local
2312 (mapcar 'make-local-variable sh-var-list
)))
2315 ;; Theoretically these are only needed in shell and derived modes.
2316 ;; However, the routines which use them are only called in those modes.
2317 (defconst sh-special-keywords
"then\\|do")
2319 (defun sh-help-string-for-variable (var)
2320 "Construct a string for `sh-read-variable' when changing variable VAR ."
2321 (let ((msg (documentation-property var
'variable-documentation
))
2323 (unless (memq var
'(sh-first-lines-indent sh-indent-comment
))
2326 You can enter a number (positive to increase indentation,
2327 negative to decrease indentation, zero for no change to indentation).
2329 Or, you can enter one of the following symbols which are relative to
2330 the value of variable `sh-basic-offset'
2331 which in this buffer is currently %s.
2335 (mapconcat (lambda (x)
2336 (nth (1- (length x
)) x
))
2337 sh-symbol-list
"\n\t"))))
2339 ;; The following shows the global not the local value!
2340 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
2343 (defun sh-read-variable (var)
2344 "Read a new value for indentation variable VAR."
2345 (interactive "*variable? ") ;; to test
2346 (let ((minibuffer-help-form `(sh-help-string-for-variable
2349 (setq val
(read-from-minibuffer
2350 (format "New value for %s (press %s for help): "
2351 var
(single-key-description help-char
))
2352 (format "%s" (symbol-value var
))
2358 (defun sh-in-comment-or-string (start)
2359 "Return non-nil if START is in a comment or string."
2361 (let ((state (syntax-ppss start
)))
2362 (or (nth 3 state
) (nth 4 state
)))))
2364 (defun sh-goto-matching-if ()
2365 "Go to the matching if for a fi.
2366 This handles nested if..fi pairs."
2367 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
2369 (goto-char found
))))
2372 ;; Functions named sh-handle-this-XXX are called when the keyword on the
2373 ;; line whose indentation is being handled contain XXX;
2374 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
2376 (defun sh-handle-prev-if ()
2377 (list '(+ sh-indent-after-if
)))
2379 (defun sh-handle-this-else ()
2380 (if (sh-goto-matching-if)
2381 ;; (list "aligned to if")
2382 (list "aligned to if" '(+ sh-indent-for-else
))
2386 (defun sh-handle-prev-else ()
2387 (if (sh-goto-matching-if)
2388 (list '(+ sh-indent-after-if
))
2391 (defun sh-handle-this-fi ()
2392 (if (sh-goto-matching-if)
2393 (list "aligned to if" '(+ sh-indent-for-fi
))
2397 (defun sh-handle-prev-fi ()
2398 ;; Why do we have this rule? Because we must go back to the if
2399 ;; to get its indent. We may continue back from there.
2400 ;; We return nil because we don't have anything to add to result,
2401 ;; the side affect of setting align-point is all that matters.
2402 ;; we could return a comment (a string) but I can't think of a good one...
2403 (sh-goto-matching-if)
2406 (defun sh-handle-this-then ()
2407 (let ((p (sh-goto-matching-if)))
2409 (list '(+ sh-indent-for-then
))
2412 (defun sh-handle-prev-then ()
2413 (let ((p (sh-goto-matching-if)))
2415 (list '(+ sh-indent-after-if
))
2418 (defun sh-handle-prev-open ()
2420 (let ((x (sh-prev-stmt)))
2425 (looking-at "function\\b")
2426 (looking-at "\\s-*\\S-+\\s-*()")
2428 (list '(+ sh-indent-after-function
))
2429 (list '(+ sh-indent-after-open
)))
2432 (defun sh-handle-this-close ()
2433 (forward-char 1) ;; move over ")"
2434 (if (sh-safe-forward-sexp -
1)
2435 (list "aligned to opening paren")))
2437 (defun sh-goto-matching-case ()
2438 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2439 (if found
(goto-char found
))))
2441 (defun sh-handle-prev-case ()
2442 ;; This is typically called when point is on same line as a case
2443 ;; we shouldn't -- and can't find prev-case
2444 (if (looking-at ".*\\<case\\>")
2445 (list '(+ sh-indent-for-case-label
))
2446 (error "We don't seem to be on a line with a case"))) ;; debug
2448 (defun sh-handle-this-esac ()
2449 (if (sh-goto-matching-case)
2450 (list "aligned to matching case")))
2452 (defun sh-handle-prev-esac ()
2453 (if (sh-goto-matching-case)
2454 (list "matching case")))
2456 (defun sh-handle-after-case-label ()
2457 (if (sh-goto-matching-case)
2458 (list '(+ sh-indent-for-case-alt
))))
2460 (defun sh-handle-prev-case-alt-end ()
2461 (if (sh-goto-matching-case)
2462 (list '(+ sh-indent-for-case-label
))))
2464 (defun sh-safe-forward-sexp (&optional arg
)
2465 "Try and do a `forward-sexp', but do not error.
2466 Return new point if successful, nil if an error occurred."
2469 (forward-sexp (or arg
1))
2470 (point)) ;; return point if successful
2472 (sh-debug "oops!(1) %d" (point))
2473 nil
))) ;; return nil if fail
2475 (defun sh-goto-match-for-done ()
2476 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done
1)))
2478 (goto-char found
))))
2480 (defun sh-handle-this-done ()
2481 (if (sh-goto-match-for-done)
2482 (list "aligned to do stmt" '(+ sh-indent-for-done
))))
2484 (defun sh-handle-prev-done ()
2485 (if (sh-goto-match-for-done)
2486 (list "previous done")))
2488 (defun sh-handle-this-do ()
2489 (if (sh-goto-match-for-done)
2490 (list '(+ sh-indent-for-do
))))
2492 (defun sh-handle-prev-do ()
2495 (narrow-to-region (point) (line-beginning-position))
2496 (sh-goto-match-for-done))
2497 (sh-debug "match for done found on THIS line")
2498 (list '(+ sh-indent-after-loop-construct
)))
2499 ((sh-goto-match-for-done)
2500 (sh-debug "match for done found on PREV line")
2501 (list '(+ sh-indent-after-do
)))
2503 (message "match for done NOT found")
2507 (defun sh-find-prev-switch ()
2508 "Find the line for the switch keyword matching this line's case keyword."
2509 (re-search-backward "\\<switch\\>" nil t
))
2511 (defun sh-handle-this-rc-case ()
2512 (if (sh-find-prev-switch)
2513 (list '(+ sh-indent-after-switch
))
2514 ;; (list '(+ sh-indent-for-case-label))
2517 (defun sh-handle-prev-rc-case ()
2518 (list '(+ sh-indent-after-case
)))
2520 (defun sh-check-rule (n thing
)
2521 (let ((rule (nth n
(assoc thing sh-kw-alist
)))
2525 (setq val
(funcall rule
))
2526 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2527 n thing
(point) rule val
)))
2531 (defun sh-get-indent-info ()
2532 "Return indent-info for this line.
2533 This is a list. nil means the line is to be left as is.
2534 Otherwise it contains one or more of the following sublists:
2535 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2536 relative to. If present, this is always the first of the
2537 sublists. The indentation of the line in question is
2538 derived from the indentation of this point, possibly
2539 modified by subsequent sublists.
2541 \(- VAR\) Get the value of variable VAR and add to or subtract from
2542 the indentation calculated so far.
2543 \(= VAR\) Get the value of variable VAR and *replace* the
2544 indentation with its value. This only occurs for
2545 special variables such as `sh-indent-comment'.
2546 STRING This is ignored for the purposes of calculating
2547 indentation, it is printed in certain cases to help show
2548 what the indentation is based on."
2549 ;; See comments before `sh-kw'.
2551 (let ((have-result nil
)
2558 ;; Note: setting result to t means we are done and will return nil.
2559 ;;(This function never returns just t.)
2561 ((or (nth 3 (syntax-ppss (point)))
2562 (eq (get-text-property (point) 'face
) sh-heredoc-face
))
2563 ;; String continuation -- don't indent
2565 (setq have-result t
))
2566 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2568 (setq result t
) ;; return nil if 1st line!
2569 (setq result
(list '(= sh-indent-comment
)))
2570 ;; we still need to get previous line in case
2571 ;; sh-indent-comment is t (indent as normal)
2572 (setq align-point
(sh-prev-line nil
))
2573 (setq have-result nil
)
2578 ;; Continuation lines are handled specially
2579 (if (sh-this-is-a-continuation)
2584 (not (memq (char-before (- (point) 2)) '(?\s ?
\t))))
2585 ;; By convention, if the continuation \ is not
2586 ;; preceded by a SPC or a TAB it means that the line
2587 ;; is cut at a place where spaces cannot be freely
2588 ;; added/removed. I.e. do not indent the line.
2590 ;; We assume the line being continued is already
2591 ;; properly indented...
2592 ;; (setq prev-line-end (sh-prev-line))
2593 (setq align-point
(sh-prev-line nil
))
2594 (list '(+ sh-indent-for-continuation
))))
2595 (setq have-result t
))
2597 (skip-chars-forward " \t")
2598 (setq this-kw
(sh-get-kw)))
2600 ;; Handle "this" keyword: first word on the line we're
2601 ;; calculating indentation info for.
2603 (if (setq val
(sh-check-rule 1 this-kw
))
2605 (setq align-point
(point))
2607 "this - setting align-point to %d" align-point
)
2608 (setq result
(append result val
))
2609 (setq have-result t
)
2610 ;; set prev-line to continue processing remainder
2611 ;; of this line as a previous line
2612 (setq prev-line-end
(point))
2616 (setq prev-line-end
(sh-prev-line 'end
)))
2620 ;; We start off at beginning of this line.
2621 ;; Scan previous statements while this is <=
2622 ;; start of previous line.
2623 (goto-char prev-line-end
)
2625 (while (and x
(setq x
(sh-prev-thing)))
2626 (sh-debug "at %d x is: %s result is: %s" (point) x result
)
2629 (equal (get-text-property (1- (point)) 'syntax-table
)
2631 (sh-debug "Case label) here")
2632 (setq x
'case-label
)
2633 (if (setq val
(sh-check-rule 2 x
))
2635 (setq result
(append result val
))
2636 (setq align-point
(point))))
2639 ;; FIXME: This charset looks too much like a regexp. --Stef
2640 (skip-chars-forward "[a-z0-9]*?")
2642 ((string-match "[])}]" x
)
2643 (setq x
(sh-safe-forward-sexp -
1))
2646 (setq align-point
(point))
2647 (setq result
(append result
2648 (list "aligned to opening paren")))
2650 ((string-match "[[({]" x
)
2651 (sh-debug "Checking special thing: %s" x
)
2652 (if (setq val
(sh-check-rule 2 x
))
2653 (setq result
(append result val
)))
2655 (setq align-point
(point)))
2656 ((string-match "[\"'`]" x
)
2657 (sh-debug "Skipping back for %s" x
)
2659 (setq x
(sh-safe-forward-sexp -
1)))
2661 (sh-debug "Checking string %s at %s" x
(point))
2662 (if (setq val
(sh-check-rule 2 x
))
2663 ;; (or (eq t (car val))
2664 ;; (eq t (car (car val))))
2665 (setq result
(append result val
)))
2666 ;; not sure about this test Wed Jan 27 23:48:35 1999
2667 (setq align-point
(point))
2671 (error "Don't know what to do with %s" x
))
2674 (sh-debug "result is %s" result
)
2676 (sh-debug "No prev line!")
2677 (sh-debug "result: %s align-point: %s" result align-point
)
2681 ;; was: (setq result (append result (list (list t align-point))))
2682 (setq result
(append (list (list t align-point
)) result
))
2684 (sh-debug "result is now: %s" result
)
2687 (setq result
(list (if prev-line-end
2688 (list t prev-line-end
)
2689 (list '= 'sh-first-lines-indent
)))))
2693 (sh-debug "result is: %s" result
)
2699 (defun sh-get-indent-var-for-line (&optional info
)
2700 "Return the variable controlling indentation for this line.
2701 If there is not [just] one such variable, return a string
2702 indicating the problem.
2703 If INFO is supplied it is used, else it is calculated."
2709 (setq info
(sh-get-indent-info)))
2711 (setq result
"this line to be left as is")
2712 (while (and info
(null result
))
2713 (setq elt
(car info
))
2719 (error "sh-get-indent-var-for-line invalid elt: %s" elt
))
2723 ((symbolp (setq sym
(nth 1 elt
)))
2724 ;; A bit of a kludge - when we see the sh-indent-comment
2725 ;; ignore other variables. Otherwise it is tricky to
2726 ;; "learn" the comment indentation.
2727 (if (eq var
'sh-indent-comment
)
2731 "this line is controlled by more than 1 variable.")
2734 (error "sh-get-indent-var-for-line invalid list elt: %s" elt
)))
2735 (setq info
(cdr info
))
2740 (setq result reason
))
2742 ;; e.g. just had (t POS)
2743 (setq result
"line has default indentation"))
2748 ;; Finding the previous line isn't trivial.
2749 ;; We must *always* go back one more and see if that is a continuation
2750 ;; line -- it is the PREVIOUS line which is continued, not the one
2752 ;; Also, we want to treat a whole "here document" as one big line,
2753 ;; because we may want to a align to the beginning of it.
2756 ;; - go back to previous non-empty line
2757 ;; - if this is in a here-document, go to the beginning of it
2758 ;; - while previous line is continued, go back one line
2759 (defun sh-prev-line (&optional end
)
2760 "Back to end of previous non-comment non-empty line.
2761 Go to beginning of logical line unless END is non-nil, in which case
2762 we go to the end of the previous line and do not check for continuations."
2765 (forward-comment (- (point-max)))
2766 (unless end
(beginning-of-line))
2767 (when (and (not (bobp))
2768 (equal (get-text-property (1- (point)) 'face
)
2770 (let ((p1 (previous-single-property-change (1- (point)) 'face
)))
2775 (beginning-of-line)))))
2777 ;; we must check previous lines to see if they are continuation lines
2778 ;; if so, we must return position of first of them
2779 (while (and (sh-this-is-a-continuation)
2780 (>= 0 (forward-line -
1))))
2782 (skip-chars-forward " \t"))
2786 (defun sh-prev-stmt ()
2787 "Return the address of the previous stmt or nil."
2788 ;; This is used when we are trying to find a matching keyword.
2789 ;; Searching backward for the keyword would certainly be quicker, but
2790 ;; it is hard to remove "false matches" -- such as if the keyword
2791 ;; appears in a string or quote. This way is slower, but (I think) safer.
2798 (skip-chars-backward " \t;|&({[")
2799 (while (and (not found
)
2802 ;; Do a backward-sexp if possible, else backup bit by bit...
2803 (if (sh-safe-forward-sexp -
1)
2805 (if (looking-at sh-special-keywords
)
2810 ;; backward-sexp failed
2811 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2814 (let ((back (sh-prev-line nil
)))
2817 (setq going nil
)))))
2819 (skip-chars-backward " \t")
2820 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2821 (eq (char-before) ?\
;)
2822 (looking-at "\\s-*[|&]"))
2823 (setq found
(point)))))
2828 (skip-chars-forward " \t|&({[")
2829 (setq found
(point))))
2830 (if (>= (point) start
)
2832 (debug "We didn't move!")
2835 (sh-debug "Did not find prev stmt.")))
2839 (defun sh-get-word ()
2840 "Get a shell word skipping whitespace from point."
2842 (skip-chars-forward "\t ")
2843 (let ((start (point)))
2845 (if (looking-at "[\"'`]")
2846 (sh-safe-forward-sexp)
2847 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2848 (> (skip-chars-forward "-_$[:alnum:]") 0)
2850 (buffer-substring start
(point))
2853 (defun sh-prev-thing ()
2854 "Return the previous thing this logical line."
2855 ;; This is called when `sh-get-indent-info' is working backwards on
2856 ;; the previous line(s) finding what keywords may be relevant for
2857 ;; indenting. It moves over sexps if possible, and will stop
2858 ;; on a ; and at the beginning of a line if it is not a continuation
2861 ;; Added a kludge for ";;"
2862 ;; Possible return values:
2864 ;; a string - possibly a keyword
2868 (let ((start (point))
2869 (min-point (if (sh-this-is-a-continuation)
2871 (line-beginning-position))))
2872 (skip-chars-backward " \t;" min-point
)
2873 (if (looking-at "\\s-*;[;&]")
2874 ;; (message "Found ;; !")
2876 (skip-chars-backward "^)}];\"'`({[" min-point
)
2877 (let ((c (if (> (point) min-point
) (char-before))))
2878 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2879 (point) c start min-point
)
2880 (if (not (memq c
'(?
\n nil ?\
;)))
2881 ;; c -- return a string
2883 ;; Return the leading keyword of the "command" we supposedly
2884 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
2885 ;; `then' that precedes the actual command), so check whether
2886 ;; we're looking at such a keyword and if so, move back forward.
2887 (let ((boundary (point))
2891 ;; Skip forward over white space newline and \ at eol.
2892 (skip-chars-forward " \t\n\\\\" start
)
2893 (if (>= (point) start
)
2895 (sh-debug "point: %d >= start: %d" (point) start
)
2897 (if next
(setq boundary next
))
2898 (sh-debug "Now at %d start=%d" (point) start
)
2899 (setq kwd
(sh-get-word))
2900 (if (member kwd
(sh-feature sh-leading-keywords
))
2905 (goto-char boundary
)
2909 (defun sh-this-is-a-continuation ()
2910 "Return non-nil if current line is a continuation of previous line."
2912 (and (zerop (forward-line -
1))
2913 (looking-at ".*\\\\$")
2914 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2917 (defun sh-get-kw (&optional where and-move
)
2918 "Return first word of line from WHERE.
2919 If AND-MOVE is non-nil then move to end of word."
2920 (let ((start (point)))
2924 (buffer-substring (point)
2925 (progn (skip-chars-forward "^ \t\n;&|")(point)))
2927 (goto-char start
)))))
2929 (defun sh-find-prev-matching (open close
&optional depth
)
2930 "Find a matching token for a set of opening and closing keywords.
2931 This takes into account that there may be nested open..close pairings.
2932 OPEN and CLOSE are regexps denoting the tokens to be matched.
2933 Optional parameter DEPTH (usually 1) says how many to look for."
2934 (let ((parse-sexp-ignore-comments t
)
2936 (setq depth
(or depth
1))
2942 (setq prev
(sh-prev-stmt)))
2945 (if (looking-at "\\\\\n")
2948 (skip-chars-forward " \t")))
2951 (setq depth
(1- depth
))
2952 (sh-debug "found open at %d - depth = %d" (point) depth
))
2954 (setq depth
(1+ depth
))
2955 (sh-debug "found close - depth = %d" depth
))
2965 (defun sh-var-value (var &optional ignore-error
)
2966 "Return the value of variable VAR, interpreting symbols.
2967 It can also return t or nil.
2968 If an invalid value is found, throw an error unless Optional argument
2969 IGNORE-ERROR is non-nil."
2970 (let ((val (symbol-value var
)))
2981 (- sh-basic-offset
))
2983 (* 2 sh-basic-offset
))
2985 (* 2 (- sh-basic-offset
)))
2987 (/ sh-basic-offset
2))
2989 (/ (- sh-basic-offset
) 2))
2993 (message "Don't know how to handle %s's value of %s" var val
)
2995 (error "Don't know how to handle %s's value of %s" var val
))
2998 (defun sh-set-var-value (var value
&optional no-symbol
)
2999 "Set variable VAR to VALUE.
3000 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
3001 can be represented by a symbol then do so."
3005 ((= value sh-basic-offset
)
3007 ((= value
(- sh-basic-offset
))
3009 ((eq value
(* 2 sh-basic-offset
))
3011 ((eq value
(* 2 (- sh-basic-offset
)))
3013 ((eq value
(/ sh-basic-offset
2))
3015 ((eq value
(/ (- sh-basic-offset
) 2))
3022 (defun sh-calculate-indent (&optional info
)
3023 "Return the indentation for the current line.
3024 If INFO is supplied it is used, else it is calculated from current line."
3029 (setq info
(sh-get-indent-info)))
3032 (sh-debug "info: %s ofs=%s" info ofs
)
3033 (setq elt
(car info
))
3035 ((stringp elt
)) ;; do nothing?
3037 (setq a
(car (car info
)))
3038 (setq b
(nth 1 (car info
)))
3043 (setq val
(current-indentation)))
3044 (setq base-value val
))
3046 (setq val
(sh-var-value b
))
3052 ;; set info to nil so we stop immediately
3053 (setq base-value nil ofs nil info nil
))
3054 ((eq val t
) (setq ofs
0)) ;; indent as normal line
3056 ;; The following assume the (t POS) come first!
3057 (setq ofs val base-value
0)
3058 (setq info nil
)))) ;; ? stop now
3059 ((eq a
'+) (setq ofs
(+ ofs val
)))
3060 ((eq a
'-
) (setq ofs
(- ofs val
)))
3062 (error "sh-calculate-indent invalid a a=%s b=%s" a b
))))
3064 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b
))))
3066 (error "sh-calculate-indent invalid elt %s" elt
)))
3067 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
3068 a b val base-value ofs
)
3069 (setq info
(cdr info
)))
3071 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs
)
3074 ((or (null base-value
)(null ofs
))
3076 ((and (numberp base-value
)(numberp ofs
))
3077 (sh-debug "base (%d) + ofs (%d) = %d"
3078 base-value ofs
(+ base-value ofs
))
3079 (+ base-value ofs
)) ;; return value
3081 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
3086 (defun sh-indent-line ()
3087 "Indent the current line."
3089 (let ((indent (sh-calculate-indent))
3090 (pos (- (point-max) (point))))
3093 (skip-chars-forward " \t")
3094 (indent-line-to indent
)
3095 ;; If initial point was within line's indentation,
3096 ;; position after the indentation. Else stay at same point in text.
3097 (if (> (- (point-max) pos
) (point))
3098 (goto-char (- (point-max) pos
))))))
3101 (defun sh-blink (blinkpos &optional msg
)
3102 "Move cursor momentarily to BLINKPOS and display MSG."
3103 ;; We can get here without it being a number on first line
3104 (if (numberp blinkpos
)
3106 (goto-char blinkpos
)
3107 (if msg
(message "%s" msg
) (message nil
))
3108 (sit-for blink-matching-delay
))
3109 (if msg
(message "%s" msg
) (message nil
))))
3111 (defun sh-show-indent (arg)
3112 "Show the how the current line would be indented.
3113 This tells you which variable, if any, controls the indentation of
3115 If optional arg ARG is non-null (called interactively with a prefix),
3116 a pop up window describes this variable.
3117 If variable `sh-blink' is non-nil then momentarily go to the line
3118 we are indenting relative to, if applicable."
3120 (sh-must-support-indent)
3121 (let* ((info (sh-get-indent-info))
3122 (var (sh-get-indent-var-for-line info
))
3123 (curr-indent (current-indentation))
3126 (message "%s" (setq msg var
))
3127 (setq val
(sh-calculate-indent info
))
3129 (if (eq curr-indent val
)
3130 (setq msg
(format "%s is %s" var
(symbol-value var
)))
3133 (format "%s (%s) would change indent from %d to: %d"
3134 var
(symbol-value var
) curr-indent val
)
3135 (format "%s (%s) would leave line as is"
3136 var
(symbol-value var
)))
3139 (describe-variable var
)))
3141 (let ((info (sh-get-indent-info)))
3142 (if (and info
(listp (car info
))
3143 (eq (car (car info
)) t
))
3144 (sh-blink (nth 1 (car info
)) msg
)
3145 (message "%s" msg
)))
3149 (defun sh-set-indent ()
3150 "Set the indentation for the current line.
3151 If the current line is controlled by an indentation variable, prompt
3152 for a new value for it."
3154 (sh-must-support-indent)
3155 (let* ((info (sh-get-indent-info))
3156 (var (sh-get-indent-var-for-line info
))
3157 val old-val indent-val
)
3159 (message "Cannot set indent - %s" var
)
3160 (setq old-val
(symbol-value var
))
3161 (setq val
(sh-read-variable var
))
3165 (setq indent-val
(sh-calculate-indent info
))
3167 (message "Variable: %s Value: %s would indent to: %d"
3168 var
(symbol-value var
) indent-val
)
3169 (message "Variable: %s Value: %s would leave line as is."
3170 var
(symbol-value var
)))
3171 ;; I'm not sure about this, indenting it now?
3172 ;; No. Because it would give the impression that an undo would
3173 ;; restore thing, but the value has been altered.
3178 (message "Bad value for %s, restoring to previous value %s"
3185 (defun sh-learn-line-indent (arg)
3186 "Learn how to indent a line as it currently is indented.
3188 If there is an indentation variable which controls this line's indentation,
3189 then set it to a value which would indent the line the way it
3192 If the value can be represented by one of the symbols then do so
3193 unless optional argument ARG (the prefix when interactive) is non-nil."
3195 (sh-must-support-indent)
3196 ;; I'm not sure if we show allow learning on an empty line.
3197 ;; Though it might occasionally be useful I think it usually
3198 ;; would just be confusing.
3201 (looking-at "\\s-*$"))
3202 (message "sh-learn-line-indent ignores empty lines.")
3203 (let* ((info (sh-get-indent-info))
3204 (var (sh-get-indent-var-for-line info
))
3205 ival sval diff new-val
3207 (curr-indent (current-indentation)))
3210 (message "Cannot learn line - %s" var
))
3211 ((eq var
'sh-indent-comment
)
3212 ;; This is arbitrary...
3213 ;; - if curr-indent is 0, set to curr-indent
3214 ;; - else if it has the indentation of a "normal" line,
3216 ;; - else set to curr-indent.
3217 (setq sh-indent-comment
3218 (if (= curr-indent
0)
3220 (let* ((sh-indent-comment t
)
3221 (val2 (sh-calculate-indent info
)))
3222 (if (= val2 curr-indent
)
3225 (message "%s set to %s" var
(symbol-value var
))
3227 ((numberp (setq sval
(sh-var-value var
)))
3228 (setq ival
(sh-calculate-indent info
))
3229 (setq diff
(- curr-indent ival
))
3231 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
3232 curr-indent ival diff var sval
)
3233 (setq new-val
(+ sval diff
))
3234 ;;; I commented out this because someone might want to replace
3235 ;;; a value of `+' with the current value of sh-basic-offset
3238 ;;; (message "No change needed!")
3239 (sh-set-var-value var new-val no-symbol
)
3240 (message "%s set to %s" var
(symbol-value var
))
3244 (message "Cannot change %s" var
))))))
3248 (defun sh-mark-init (buffer)
3249 "Initialize a BUFFER to be used by `sh-mark-line'."
3250 (with-current-buffer (get-buffer-create buffer
)
3255 (defun sh-mark-line (message point buffer
&optional add-linenum occur-point
)
3256 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
3257 Buffer BUFFER is in `occur-mode'.
3258 If ADD-LINENUM is non-nil the message is preceded by the line number.
3259 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
3260 so that `occur-next' and `occur-prev' will work."
3261 (let ((m1 (make-marker))
3265 (set-marker m1 point
(current-buffer))
3267 (setq line
(format "%d: " (1+ (count-lines 1 point
))))))
3269 (if (get-buffer buffer
)
3270 (set-buffer (get-buffer buffer
))
3271 (set-buffer (get-buffer-create buffer
))
3274 (goto-char (point-max))
3275 (setq start
(point))
3278 (setq occur-point
(point)))
3281 (add-text-properties
3283 '(mouse-face highlight
3284 help-echo
"mouse-2: go to the line where I learned this")))
3288 (put-text-property start
(point) 'occur-target m1
)
3290 (put-text-property start occur-point
3297 ;; Is this really worth having?
3298 (defvar sh-learned-buffer-hook nil
3299 "An abnormal hook, called with an alist of learned variables.")
3300 ;; Example of how to use sh-learned-buffer-hook
3302 ;; (defun what-i-learned (list)
3304 ;; (with-current-buffer "*scratch*"
3305 ;; (goto-char (point-max))
3306 ;; (insert "(setq\n")
3308 ;; (insert (format " %s %s \n"
3309 ;; (nth 0 (car p)) (nth 1 (car p))))
3310 ;; (setq p (cdr p)))
3314 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
3317 ;; Originally this was sh-learn-region-indent (beg end)
3318 ;; However, in practice this was awkward so I changed it to
3319 ;; use the whole buffer. Use narrowing if needbe.
3320 (defun sh-learn-buffer-indent (&optional arg
)
3321 "Learn how to indent the buffer the way it currently is.
3323 Output in buffer \"*indent*\" shows any lines which have conflicting
3324 values of a variable, and the final value of all variables learned.
3325 When called interactively, pop to this buffer automatically if
3326 there are any discrepancies.
3328 If no prefix ARG is given, then variables are set to numbers.
3329 If a prefix arg is given, then variables are set to symbols when
3330 applicable -- e.g. to symbol `+' if the value is that of the
3332 If a positive numerical prefix is given, then `sh-basic-offset'
3333 is set to the prefix's numerical value.
3334 Otherwise, sh-basic-offset may or may not be changed, according
3335 to the value of variable `sh-learn-basic-offset'.
3337 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
3338 function completes. The function is abnormal because it is called
3339 with an alist of variables learned. This feature may be changed or
3340 removed in the future.
3342 This command can often take a long time to run."
3344 (sh-must-support-indent)
3346 (goto-char (point-min))
3347 (let ((learned-var-list nil
)
3348 (out-buffer "*indent*")
3354 (comment-col nil
) ;; number if all same, t if seen diff values
3355 (comments-always-default t
) ;; nil if we see one not default
3357 (specified-basic-offset (and arg
(numberp arg
)
3361 (setq vec
(make-vector max
0))
3362 (sh-mark-init out-buffer
)
3364 (if specified-basic-offset
3366 (setq sh-basic-offset arg
)
3368 (format "Using specified sh-basic-offset of %d"
3371 (format "Initial value of sh-basic-offset: %s"
3374 (while (< (point) (point-max))
3375 (setq linenum
(1+ linenum
))
3376 ;; (if (zerop (% linenum 10))
3377 (message "line %d" linenum
)
3379 (unless (looking-at "\\s-*$") ;; ignore empty lines!
3380 (let* ((sh-indent-comment t
) ;; info must return default indent
3381 (info (sh-get-indent-info))
3382 (var (sh-get-indent-var-for-line info
))
3383 sval ival diff new-val
3384 (curr-indent (current-indentation)))
3390 ((numberp (setq sval
(sh-var-value var
'no-error
)))
3391 ;; the numberp excludes comments since sval will be t.
3392 (setq ival
(sh-calculate-indent))
3393 (setq diff
(- curr-indent ival
))
3394 (setq new-val
(+ sval diff
))
3395 (sh-set-var-value var new-val
'no-symbol
)
3396 (unless (looking-at "\\s-*#") ;; don't learn from comments
3397 (if (setq previous-set-info
(assoc var learned-var-list
))
3399 ;; it was already there, is it same value ?
3400 (unless (eq (symbol-value var
)
3401 (nth 1 previous-set-info
))
3403 (format "Variable %s was set to %s"
3404 var
(symbol-value var
))
3405 (point) out-buffer t t
)
3407 (format " but was previously set to %s"
3408 (nth 1 previous-set-info
))
3409 (nth 2 previous-set-info
) out-buffer t
)
3410 (setq num-diffs
(1+ num-diffs
))
3411 ;; (delete previous-set-info learned-var-list)
3412 (setcdr previous-set-info
3413 (list (symbol-value var
) (point)))
3416 (setq learned-var-list
3417 (append (list (list var
(symbol-value var
)
3420 (if (numberp new-val
)
3423 "This line's indent value: %d" new-val
)
3425 (setq new-val
(- new-val
)))
3427 (aset vec new-val
(1+ (aref vec new-val
))))))
3429 ((eq var
'sh-indent-comment
)
3430 (unless (= curr-indent
(sh-calculate-indent info
))
3431 ;; this is not the default indentation
3432 (setq comments-always-default nil
)
3433 (if comment-col
;; then we have see one before
3434 (or (eq comment-col curr-indent
)
3435 (setq comment-col t
)) ;; seen a different one
3436 (setq comment-col curr-indent
))
3439 (sh-debug "Cannot learn this line!!!")
3442 "at %s learned-var-list is %s" (point) learned-var-list
)
3449 "comment-col = %s comments-always-default = %s"
3450 comment-col comments-always-default
))
3452 (sh-mark-line msg nil out-buffer
)))
3455 (setq msg
"\nComments are all in 1st column.\n"))
3456 (comments-always-default
3457 (setq msg
"\nComments follow default indentation.\n")
3458 (setq comment-col t
))
3459 ((numberp comment-col
)
3460 (setq msg
(format "\nComments are in col %d." comment-col
)))
3462 (setq msg
"\nComments seem to be mixed, leaving them as is.\n")
3463 (setq comment-col nil
)
3466 (sh-mark-line msg nil out-buffer
)
3468 (sh-mark-line initial-msg nil out-buffer t t
)
3470 (setq suggested
(sh-guess-basic-offset vec
))
3472 (if (and suggested
(not specified-basic-offset
))
3475 ;; t => set it if we have a single value as a number
3476 ((and (eq sh-learn-basic-offset t
) (numberp suggested
))
3478 ;; other non-nil => set it if only one value was found
3479 (sh-learn-basic-offset
3480 (if (numberp suggested
)
3482 (if (= (length suggested
) 1)
3488 (setq learned-var-list
3489 (append (list (list 'sh-basic-offset
3490 (setq sh-basic-offset new-value
)
3493 ;; Not sure if we need to put this line in, since
3494 ;; it will appear in the "Learned variable settings".
3496 (format "Changed sh-basic-offset to: %d" sh-basic-offset
)
3499 (if (listp suggested
)
3500 (format "Possible value(s) for sh-basic-offset: %s"
3501 (mapconcat 'int-to-string suggested
" "))
3502 (format "Suggested sh-basic-offset: %d" suggested
))
3506 (setq learned-var-list
3507 (append (list (list 'sh-indent-comment comment-col
(point-max)))
3509 (setq sh-indent-comment comment-col
)
3510 (let ((name (buffer-name)))
3511 (sh-mark-line "\nLearned variable settings:" nil out-buffer
)
3513 ;; Set learned variables to symbolic rather than numeric
3514 ;; values where possible.
3515 (dolist (learned-var (reverse learned-var-list
))
3516 (let ((var (car learned-var
))
3517 (val (nth 1 learned-var
)))
3518 (when (and (not (eq var
'sh-basic-offset
))
3520 (sh-set-var-value var val
)))))
3521 (dolist (learned-var (reverse learned-var-list
))
3522 (let ((var (car learned-var
)))
3523 (sh-mark-line (format " %s %s" var
(symbol-value var
))
3524 (nth 2 learned-var
) out-buffer
)))
3525 (with-current-buffer out-buffer
3526 (goto-char (point-min))
3528 (format "Indentation values for buffer %s.\n" name
)
3529 (format "%d indentation variable%s different values%s\n\n"
3533 (if (zerop num-diffs
)
3536 ;; Are abnormal hooks considered bad form?
3537 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list
)
3538 (and (called-interactively-p 'any
)
3539 (or sh-popup-occur-buffer
(> num-diffs
0))
3540 (pop-to-buffer out-buffer
)))))
3542 (defun sh-guess-basic-offset (vec)
3543 "See if we can determine a reasonable value for `sh-basic-offset'.
3544 This is experimental, heuristic and arbitrary!
3545 Argument VEC is a vector of information collected by
3546 `sh-learn-buffer-indent'.
3548 number - there appears to be a good single value
3549 list of numbers - no obvious one, here is a list of one or more
3551 nil - we couldn't find a reasonable one."
3552 (let* ((max (1- (length vec
)))
3554 (totals (make-vector max
0)))
3556 (aset totals i
(+ (aref totals i
) (* 4 (aref vec i
))))
3558 (aset totals i
(+ (aref totals i
) (aref vec
(/ i
2)))))
3560 (aset totals i
(+ (aref totals i
) (aref vec
(* i
2)))))
3568 (if (/= (aref totals i
) 0)
3569 (setq x
(append x
(list (cons i
(aref totals i
))))))
3572 (setq x
(sort x
(lambda (a b
) (> (cdr a
) (cdr b
)))))
3573 (setq tot
(apply '+ (append totals nil
)))
3574 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3578 (message "no values!")) ;; we return nil
3580 (message "only value is %d" (car (car x
)))
3581 (setq result
(car (car x
)))) ;; return single value
3582 ((> (cdr (car x
)) (/ tot
2))
3584 (message "basic-offset is probably %d" (car (car x
)))
3585 (setq result
(car (car x
)))) ;; again, return a single value
3586 ((>= (cdr (car x
)) (* 2 (cdr (car (cdr x
)))))
3587 ;; 1st is >= 2 * 2nd
3588 (message "basic-offset could be %d" (car (car x
)))
3589 (setq result
(car (car x
))))
3590 ((>= (+ (cdr (car x
))(cdr (car (cdr x
)))) (/ tot
2))
3591 ;; 1st & 2nd together >= 50% - return a list
3592 (setq p x sum
0 result nil
)
3594 (<= (setq sum
(+ sum
(cdr (car p
)))) (/ tot
2)))
3595 (setq result
(append result
(list (car (car p
)))))
3597 (message "Possible choices for sh-basic-offset: %s"
3598 (mapconcat 'int-to-string result
" ")))
3600 (message "No obvious value for sh-basic-offset. Perhaps %d"
3602 ;; result is nil here
3606 ;; ========================================================================
3608 ;; Styles -- a quick and dirty way of saving the indentation settings.
3610 (defvar sh-styles-alist nil
3611 "A list of all known shell indentation styles.")
3613 (defun sh-name-style (name &optional confirm-overwrite
)
3614 "Name the current indentation settings as a style called NAME.
3615 If this name exists, the command will prompt whether it should be
3617 - - it was called interactively with a prefix argument, or
3618 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3619 ;; (interactive "sName for this style: ")
3622 (read-from-minibuffer "Name for this style? " )
3623 (not current-prefix-arg
)))
3624 (let ((slist (cons name
3625 (mapcar (lambda (var) (cons var
(symbol-value var
)))
3627 (style (assoc name sh-styles-alist
)))
3629 (if (and confirm-overwrite
3630 (not (y-or-n-p "This style exists. Overwrite it? ")))
3631 (message "Not changing style %s" name
)
3632 (message "Updating style %s" name
)
3633 (setcdr style
(cdr slist
)))
3634 (message "Creating new style %s" name
)
3635 (push slist sh-styles-alist
))))
3637 (defun sh-load-style (name)
3638 "Set shell indentation values for this buffer from those in style NAME."
3639 (interactive (list (completing-read
3640 "Which style to use for this buffer? "
3641 sh-styles-alist nil t
)))
3642 (let ((sl (assoc name sh-styles-alist
)))
3644 (error "sh-load-style - style %s not known" name
)
3645 (dolist (var (cdr sl
))
3646 (set (car var
) (cdr var
))))))
3648 (defun sh-save-styles-to-buffer (buff)
3649 "Save all current styles in elisp to buffer BUFF.
3650 This is always added to the end of the buffer."
3653 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3654 (with-current-buffer (get-buffer-create buff
)
3655 (goto-char (point-max))
3657 (pp `(setq sh-styles-alist
',sh-styles-alist
) (current-buffer))))
3661 ;; statement syntax-commands for various shells
3663 ;; You are welcome to add the syntax or even completely new statements as
3664 ;; appropriate for your favorite shell.
3666 (defconst sh-non-closing-paren
3667 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3668 ;; that inherits this property, which then confuses the indentation.
3669 (propertize ")" 'syntax-table sh-st-punc
'rear-nonsticky t
))
3671 (define-skeleton sh-case
3672 "Insert a case/switch statement. See `sh-feature'."
3674 "switch( " str
" )" \n
3675 > "case " (read-string "pattern: ") ?
: \n
3678 ( "other pattern, %s: "
3688 > "switch( " str
" ) {" \n
3689 > "case " (read-string "pattern: ") \n
3691 ( "other pattern, %s: "
3699 > "case " str
" in" \n
3701 > str sh-non-closing-paren
\n
3704 > "*" sh-non-closing-paren
\n
3709 (define-skeleton sh-for
3710 "Insert a for loop. See `sh-feature'."
3724 (sh "Index variable: "
3725 > "for " str
" in " _
"; do" \n
3726 > _ | ?$
& (sh-remember-variable str
) \n
3731 (define-skeleton sh-indexed-loop
3732 "Insert an indexed loop from 1 to n. See `sh-feature'."
3733 (bash sh-modify posix
)
3734 (csh "Index variable: "
3736 "while( $" str
" <= " (read-string "upper limit: ") " )" \n
3742 (ksh88 "Index variable: "
3743 > "integer " str
"=0" \n
3744 > "while (( ( " str
" += 1 ) <= "
3745 (read-string "upper limit: ")
3747 > _ ?$
(sh-remember-variable str
) > \n
3749 (posix "Index variable: "
3751 "while [ $" str
" -le "
3752 (read-string "upper limit: ")
3755 str ?
= (sh-add (sh-remember-variable str
) 1) \n
3757 (rc "Index variable: "
3758 > "for( " str
" in" " `{awk 'BEGIN { for( i=1; i<="
3759 (read-string "upper limit: ")
3760 "; i++ ) print i }'`}) {" \n
3761 > _ ?$
(sh-remember-variable str
) \n
3763 (sh "Index variable: "
3764 > "for " str
" in `awk 'BEGIN { for( i=1; i<="
3765 (read-string "upper limit: ")
3766 "; i++ ) print i }'`; do" \n
3767 > _ ?$
(sh-remember-variable str
) \n
3771 (defun sh-shell-initialize-variables ()
3772 "Scan the buffer for variable assignments.
3773 Add these variables to `sh-shell-variables'."
3774 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3776 (goto-char (point-min))
3777 (setq sh-shell-variables-initialized t
)
3778 (while (search-forward "=" nil t
)
3780 (message "Scanning buffer `%s' for variable assignments...done"
3783 (defvar sh-add-buffer
)
3785 (defun sh-add-completer (string predicate code
)
3786 "Do completion using `sh-shell-variables', but initialize it first.
3787 This function is designed for use as the \"completion table\",
3788 so it takes three arguments:
3789 STRING, the current buffer contents;
3790 PREDICATE, the predicate for filtering possible matches;
3791 CODE, which says what kind of things to do.
3792 CODE can be nil, t or `lambda'.
3793 nil means to return the best completion of STRING, or nil if there is none.
3794 t means to return a list of all possible completions of STRING.
3795 `lambda' means to return t if STRING is a valid completion as it stands."
3797 (with-current-buffer sh-add-buffer
3798 (or sh-shell-variables-initialized
3799 (sh-shell-initialize-variables))
3800 (nconc (mapcar (lambda (var)
3801 (substring var
0 (string-match "=" var
)))
3802 process-environment
)
3803 sh-shell-variables
))))
3804 (complete-with-action code vars string predicate
)))
3806 (defun sh-add (var delta
)
3807 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3809 (let ((sh-add-buffer (current-buffer)))
3810 (list (completing-read "Variable: " 'sh-add-completer
)
3811 (prefix-numeric-value current-prefix-arg
))))
3812 (insert (sh-feature '((bash .
"$(( ")
3818 (sh-remember-variable var
)
3819 (if (< delta
0) " - " " + ")
3820 (number-to-string (abs delta
))
3821 (sh-feature '((bash .
" ))")
3830 (define-skeleton sh-function
3831 "Insert a function definition. See `sh-feature'."
3832 (bash sh-modify ksh88
3835 "function " str
" {" \n
3847 (define-skeleton sh-if
3848 "Insert an if statement. See `sh-feature'."
3850 "if( " str
" ) then" \n
3852 ( "other condition, %s: "
3853 < "else if( " str
" ) then" \n
3860 > "if { " str
" } {" \n
3862 ( "other condition, %s: "
3863 "} { " str
" } {" > \n
3870 > "if( " str
" ) {" \n
3872 ( "other condition, %s: "
3873 "} else if( " str
" ) {" > \n
3880 '(setq input
(sh-feature sh-test
))
3881 > "if " str
"; then" \n
3883 ( "other condition, %s: "
3884 > "elif " str
"; then" > \n
3893 (define-skeleton sh-repeat
3894 "Insert a repeat loop definition. See `sh-feature'."
3900 > "repeat " str
"; do" > \n
3904 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3908 (define-skeleton sh-select
3909 "Insert a select statement. See `sh-feature'."
3910 (ksh88 "Index variable: "
3911 > "select " str
" in " _
"; do" \n
3914 (bash sh-append ksh88
))
3915 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3919 (define-skeleton sh-tmp-file
3920 "Insert code to setup temporary file handling. See `sh-feature'."
3921 (bash sh-append ksh88
)
3922 (csh (file-name-nondirectory (buffer-file-name))
3923 "set tmp = `mktemp -t " str
".XXXXXX`" \n
3925 (and (goto-char (point-max))
3929 "rm $tmp* >&/dev/null" > \n)
3930 (es (file-name-nondirectory (buffer-file-name))
3931 > "local( signals = $signals sighup sigint;" \n
3932 > "tmp = `{ mktemp -t " str
".XXXXXX } ) {" \n
3934 > "rm $tmp^* >[2]/dev/null" \n
3942 (rc (file-name-nondirectory (buffer-file-name))
3943 > "tmp = `{ mktemp -t " str
".XXXXXX }" \n
3944 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
3945 (sh (file-name-nondirectory (buffer-file-name))
3946 > "TMP=`mktemp -t " str
".XXXXXX`" \n
3947 "trap \"rm $TMP* 2>/dev/null\" " ?
0 \n))
3951 (define-skeleton sh-until
3952 "Insert an until loop. See `sh-feature'."
3954 '(setq input
(sh-feature sh-test
))
3955 > "until " str
"; do" \n
3958 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3962 (define-skeleton sh-while
3963 "Insert a while loop. See `sh-feature'."
3979 '(setq input
(sh-feature sh-test
))
3980 > "while " str
"; do" \n
3986 (define-skeleton sh-while-getopts
3987 "Insert a while getopts loop. See `sh-feature'.
3988 Prompts for an options string which consists of letters for each recognized
3989 option followed by a colon `:' if the option accepts an argument."
3994 > "switch( \"$1\" )" \n
3995 '(setq input
'("- x" .
2))
3998 < "case " '(eval str
)
3999 '(if (string-match " +" str
)
4000 (setq v1
(substring str
(match-end 0))
4001 str
(substring str
0 (match-beginning 0)))
4004 > "set " v1
& " = $2" | -
4 & _
\n
4005 (if v1
"shift") & \n
4020 18 "$(basename $0)")
4022 > "while getopts :" str
" OPT; do" \n
4024 '(setq v1
(append (vconcat str
) nil
))
4025 ( (prog1 (if v1
(char-to-string (car v1
)))
4026 (if (eq (nth 1 v1
) ?
:)
4027 (setq v1
(nthcdr 2 v1
)
4031 > str
"|+" str sh-non-closing-paren
\n
4034 > "*" sh-non-closing-paren
\n
4035 > "echo" " \"usage: " "`basename $0`"
4036 " [+-" '(setq v1
(point)) str
4038 (while (search-backward ":" v1 t
)
4039 (replace-match " ARG] [+-" t t
)))
4040 (if (eq (preceding-char) ?-
) -
5)
4041 (if (and (sequencep v1
) (length v1
)) "] " "} ")
4047 "shift " (sh-add "OPTIND" -
1) \n
4052 (defun sh-assignment (arg)
4053 "Remember preceding identifier for future completion and do self-insert."
4055 (self-insert-command arg
)
4057 (sh-remember-variable
4059 (if (re-search-forward (sh-feature sh-assignment-regexp
)
4061 (beginning-of-line 1))
4063 (match-string 1))))))
4066 (defun sh-maybe-here-document (arg)
4067 "Insert self. Without prefix, following unquoted `<' inserts here document.
4068 The document is bounded by `sh-here-document-word'."
4070 (self-insert-command (prefix-numeric-value arg
))
4071 (or arg
(sh--maybe-here-document)))
4072 (make-obsolete 'sh--maybe-here-document
4073 'sh-electric-here-document-mode
"24.2")
4075 (defun sh--maybe-here-document ()
4076 (or (not (looking-back "[^<]<<"))
4080 (nth 8 (syntax-ppss))
4081 (let ((tabs (if (string-match "\\`-" sh-here-document-word
)
4082 (make-string (/ (current-indentation) tab-width
) ?
\t)
4084 (delim (replace-regexp-in-string "['\"]" ""
4085 sh-here-document-word
)))
4086 (insert sh-here-document-word
)
4087 (or (eolp) (looking-at "[ \t]") (insert ?\s
))
4094 (insert ?
\n tabs
(replace-regexp-in-string
4095 "\\`-?[ \t]*" "" delim
))))))
4097 (define-minor-mode sh-electric-here-document-mode
4098 "Make << insert a here document skeleton."
4100 (if sh-electric-here-document-mode
4101 (add-hook 'post-self-insert-hook
#'sh--maybe-here-document nil t
)
4102 (remove-hook 'post-self-insert-hook
#'sh--maybe-here-document t
)))
4104 ;; various other commands
4106 (autoload 'comint-dynamic-complete
"comint"
4107 "Dynamically perform completion at point." t
)
4109 (autoload 'shell-dynamic-complete-command
"shell"
4110 "Dynamically complete the command at point." t
)
4112 (autoload 'comint-dynamic-complete-filename
"comint"
4113 "Dynamically complete the filename at point." t
)
4115 (autoload 'shell-dynamic-complete-environment-variable
"shell"
4116 "Dynamically complete the environment variable at point." t
)
4120 (defun sh-beginning-of-command ()
4121 ;; FIXME: Redefine using SMIE.
4122 "Move point to successive beginnings of commands."
4124 (if (re-search-backward sh-beginning-of-command nil t
)
4125 (goto-char (match-beginning 2))))
4127 (defun sh-end-of-command ()
4128 ;; FIXME: Redefine using SMIE.
4129 "Move point to successive ends of commands."
4131 (if (re-search-forward sh-end-of-command nil t
)
4132 (goto-char (match-end 1))))
4134 ;; Backslashification. Stolen from make-mode.el.
4136 (defun sh-backslash-region (from to delete-flag
)
4137 "Insert, align, or delete end-of-line backslashes on the lines in the region.
4138 With no argument, inserts backslashes and aligns existing backslashes.
4139 With an argument, deletes the backslashes.
4141 This function does not modify the last line of the region if the region ends
4142 right at the start of the following line; it does not modify blank lines
4143 at the start of the region. So you can put the region around an entire
4144 shell command and conveniently use this command."
4145 (interactive "r\nP")
4148 (let ((column sh-backslash-column
)
4149 (endmark (make-marker)))
4150 (move-marker endmark to
)
4151 ;; Compute the smallest column number past the ends of all the lines.
4152 (if sh-backslash-align
4154 (if (not delete-flag
)
4155 (while (< (point) to
)
4157 (if (= (preceding-char) ?
\\)
4158 (progn (forward-char -
1)
4159 (skip-chars-backward " \t")))
4160 (setq column
(max column
(1+ (current-column))))
4162 ;; Adjust upward to a tab column, if that doesn't push
4164 (if (> (% column tab-width
) 0)
4165 (let ((adjusted (* (/ (+ column tab-width -
1) tab-width
)
4167 (if (< adjusted
(window-width))
4168 (setq column adjusted
))))))
4169 ;; Don't modify blank lines at start of region.
4171 (while (and (< (point) endmark
) (eolp))
4173 ;; Add or remove backslashes on all the lines.
4174 (while (and (< (point) endmark
)
4175 ;; Don't backslashify the last line
4176 ;; if the region ends right at the start of the next line.
4179 (< (point) endmark
)))
4180 (if (not delete-flag
)
4181 (sh-append-backslash column
)
4182 (sh-delete-backslash))
4184 (move-marker endmark nil
))))
4186 (defun sh-append-backslash (column)
4188 ;; Note that "\\\\" is needed to get one backslash.
4189 (if (= (preceding-char) ?
\\)
4190 (progn (forward-char -
1)
4191 (delete-horizontal-space)
4192 (indent-to column
(if sh-backslash-align nil
1)))
4193 (indent-to column
(if sh-backslash-align nil
1))
4196 (defun sh-delete-backslash ()
4201 (if (looking-at "\\\\")
4202 (delete-region (1+ (point))
4203 (progn (skip-chars-backward " \t") (point)))))))
4205 (provide 'sh-script
)
4207 ;;; sh-script.el ends here