1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993-1997, 1999, 2001-2011 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
329 .
((nil "^\\s-*\\(function\\s-+\\)?\\([[:alpha:]_][[:alnum:]_]+\\)\\s-*()" 2))))
330 "Alist of regular expressions for recognizing shell function definitions.
331 See `sh-feature' and `imenu-generic-expression'."
332 :type
'(alist :key-type
(symbol :tag
"Shell")
333 :value-type
(alist :key-type
(choice :tag
"Title"
335 (const :tag
"None" nil
))
337 (repeat :tag
"Regexp, index..." sexp
)))
341 (defvar sh-shell-variables nil
342 "Alist of shell variable names that should be included in completion.
343 These are used for completion in addition to all the variables named
344 in `process-environment'. Each element looks like (VAR . VAR), where
345 the car and cdr are the same symbol.")
347 (defvar sh-shell-variables-initialized nil
348 "Non-nil if `sh-shell-variables' is initialized.")
350 (defun sh-canonicalize-shell (shell)
351 "Convert a shell name SHELL to the one we should handle it as."
352 (if (string-match "\\.exe\\'" shell
)
353 (setq shell
(substring shell
0 (match-beginning 0))))
355 (setq shell
(intern shell
)))
356 (or (cdr (assq shell sh-alias-alist
))
359 (defvar sh-shell
(sh-canonicalize-shell (file-name-nondirectory sh-shell-file
))
360 "The shell being programmed. This is set by \\[sh-set-shell].")
361 ;;;###autoload(put 'sh-shell 'safe-local-variable 'symbolp)
363 (define-abbrev-table 'sh-mode-abbrev-table
())
366 ;; I turned off this feature because it doesn't permit typing commands
367 ;; in the usual way without help.
369 ;; '((csh sh-abbrevs shell
371 ;; "getopts" 'sh-while-getopts)
373 ;; (es sh-abbrevs shell
374 ;; "function" 'sh-function)
376 ;; (ksh88 sh-abbrevs sh
377 ;; "select" 'sh-select)
379 ;; (rc sh-abbrevs shell
381 ;; "function" 'sh-function)
383 ;; (sh sh-abbrevs shell
385 ;; "function" 'sh-function
387 ;; "getopts" 'sh-while-getopts)
389 ;; ;; The next entry is only used for defining the others
390 ;; (shell "for" sh-for
391 ;; "loop" sh-indexed-loop
393 ;; "tmpfile" sh-tmp-file
396 ;; (zsh sh-abbrevs ksh88
397 ;; "repeat" 'sh-repeat))
398 ;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
399 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
400 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
404 (defun sh-mode-syntax-table (table &rest list
)
405 "Copy TABLE and set syntax for successive CHARs according to strings S."
406 (setq table
(copy-syntax-table table
))
408 (modify-syntax-entry (pop list
) (pop list
) table
))
411 (defvar sh-mode-syntax-table
412 (sh-mode-syntax-table ()
418 ;; ?$ might also have a ". p" syntax. Both "'" and ". p" seem
419 ;; to work fine. This is needed so that dabbrev-expand
432 "The syntax table to use for Shell-Script mode.
433 This is buffer-local in every such buffer.")
435 (defvar sh-mode-syntax-table-input
437 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
440 (let ((map (make-sparse-keymap))
441 (menu-map (make-sparse-keymap)))
442 (define-key map
"\C-c(" 'sh-function
)
443 (define-key map
"\C-c\C-w" 'sh-while
)
444 (define-key map
"\C-c\C-u" 'sh-until
)
445 (define-key map
"\C-c\C-t" 'sh-tmp-file
)
446 (define-key map
"\C-c\C-s" 'sh-select
)
447 (define-key map
"\C-c\C-r" 'sh-repeat
)
448 (define-key map
"\C-c\C-o" 'sh-while-getopts
)
449 (define-key map
"\C-c\C-l" 'sh-indexed-loop
)
450 (define-key map
"\C-c\C-i" 'sh-if
)
451 (define-key map
"\C-c\C-f" 'sh-for
)
452 (define-key map
"\C-c\C-c" 'sh-case
)
453 (define-key map
"\C-c?" 'sh-show-indent
)
454 (define-key map
"\C-c=" 'sh-set-indent
)
455 (define-key map
"\C-c<" 'sh-learn-line-indent
)
456 (define-key map
"\C-c>" 'sh-learn-buffer-indent
)
457 (define-key map
"\C-c\C-\\" 'sh-backslash-region
)
459 (define-key map
"=" 'sh-assignment
)
460 (define-key map
"\C-c+" 'sh-add
)
461 (define-key map
"\C-\M-x" 'sh-execute-region
)
462 (define-key map
"\C-c\C-x" 'executable-interpret
)
463 (define-key map
"<" 'sh-maybe-here-document
)
464 (define-key map
"(" 'skeleton-pair-insert-maybe
)
465 (define-key map
"{" 'skeleton-pair-insert-maybe
)
466 (define-key map
"[" 'skeleton-pair-insert-maybe
)
467 (define-key map
"'" 'skeleton-pair-insert-maybe
)
468 (define-key map
"`" 'skeleton-pair-insert-maybe
)
469 (define-key map
"\"" 'skeleton-pair-insert-maybe
)
471 (define-key map
[remap complete-tag
] 'comint-dynamic-complete
)
472 (define-key map
[remap delete-backward-char
]
473 'backward-delete-char-untabify
)
474 (define-key map
"\C-c:" 'sh-set-shell
)
475 (define-key map
[remap backward-sentence
] 'sh-beginning-of-command
)
476 (define-key map
[remap forward-sentence
] 'sh-end-of-command
)
477 (define-key map
[menu-bar sh-script
] (cons "Sh-Script" menu-map
))
478 (define-key menu-map
[sh-learn-buffer-indent
]
479 '(menu-item "Learn buffer indentation" sh-learn-buffer-indent
480 :help
"Learn how to indent the buffer the way it currently is."))
481 (define-key menu-map
[sh-learn-line-indent
]
482 '(menu-item "Learn line indentation" sh-learn-line-indent
483 :help
"Learn how to indent a line as it currently is indented"))
484 (define-key menu-map
[sh-show-indent
]
485 '(menu-item "Show indentation" sh-show-indent
486 :help
"Show the how the current line would be indented"))
487 (define-key menu-map
[sh-set-indent
]
488 '(menu-item "Set indentation" sh-set-indent
489 :help
"Set the indentation for the current line"))
491 (define-key menu-map
[sh-pair
]
492 '(menu-item "Insert braces and quotes in pairs"
496 (setq skeleton-pair
(not skeleton-pair
)))
497 :button
(:toggle .
(and (boundp 'skeleton-pair
)
499 :help
"Inserting a brace or quote automatically inserts the matching pair"))
501 (define-key menu-map
[sh-s0
] '("--"))
503 (define-key menu-map
[sh-function
]
504 '(menu-item "Function..." sh-function
505 :help
"Insert a function definition"))
506 (define-key menu-map
[sh-add
]
507 '(menu-item "Addition..." sh-add
508 :help
"Insert an addition of VAR and prefix DELTA for Bourne (type) shell"))
509 (define-key menu-map
[sh-until
]
510 '(menu-item "Until Loop" sh-until
511 :help
"Insert an until loop"))
512 (define-key menu-map
[sh-repeat
]
513 '(menu-item "Repeat Loop" sh-repeat
514 :help
"Insert a repeat loop definition"))
515 (define-key menu-map
[sh-while
]
516 '(menu-item "While Loop" sh-while
517 :help
"Insert a while loop"))
518 (define-key menu-map
[sh-getopts
]
519 '(menu-item "Options Loop" sh-while-getopts
520 :help
"Insert a while getopts loop."))
521 (define-key menu-map
[sh-indexed-loop
]
522 '(menu-item "Indexed Loop" sh-indexed-loop
523 :help
"Insert an indexed loop from 1 to n."))
524 (define-key menu-map
[sh-select
]
525 '(menu-item "Select Statement" sh-select
526 :help
"Insert a select statement "))
527 (define-key menu-map
[sh-if
]
528 '(menu-item "If Statement" sh-if
529 :help
"Insert an if statement"))
530 (define-key menu-map
[sh-for
]
531 '(menu-item "For Loop" sh-for
532 :help
"Insert a for loop"))
533 (define-key menu-map
[sh-case
]
534 '(menu-item "Case Statement" sh-case
535 :help
"Insert a case/switch statement"))
536 (define-key menu-map
[sh-s1
] '("--"))
537 (define-key menu-map
[sh-exec
]
538 '(menu-item "Execute region" sh-execute-region
539 :help
"Pass optional header and region to a subshell for noninteractive execution"))
540 (define-key menu-map
[sh-exec-interpret
]
541 '(menu-item "Execute script..." executable-interpret
542 :help
"Run script with user-specified args, and collect output in a buffer"))
543 (define-key menu-map
[sh-set-shell
]
544 '(menu-item "Set shell type..." sh-set-shell
545 :help
"Set this buffer's shell to SHELL (a string)"))
546 (define-key menu-map
[sh-backslash-region
]
547 '(menu-item "Backslash region" sh-backslash-region
548 :help
"Insert, align, or delete end-of-line backslashes on the lines in the region."))
550 "Keymap used in Shell-Script mode.")
552 (defvar sh-skeleton-pair-default-alist
'((?
( _ ?
)) (?\
))
553 (?
[ ?\s _ ?\s ?
]) (?\
])
555 "Value to use for `skeleton-pair-default-alist' in Shell-Script mode.")
557 (defcustom sh-dynamic-complete-functions
558 '(shell-dynamic-complete-environment-variable
559 shell-dynamic-complete-command
560 comint-dynamic-complete-filename
)
561 "Functions for doing TAB dynamic completion."
562 :type
'(repeat function
)
565 (defcustom sh-assignment-regexp
566 '((csh .
"\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
567 ;; actually spaces are only supported in let/(( ... ))
568 (ksh88 .
"\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
569 (rc .
"\\<\\([[:alnum:]_*]+\\)[ \t]*=")
570 (sh .
"\\<\\([[:alnum:]_]+\\)="))
571 "Regexp for the variable name and what may follow in an assignment.
572 First grouping matches the variable name. This is upto and including the `='
573 sign. See `sh-feature'."
574 :type
'(repeat (cons (symbol :tag
"Shell")
576 (sexp :format
"Evaluate: %v"))))
580 (defcustom sh-indentation
4
581 "The width for further indentation in Shell-Script mode."
584 (put 'sh-indentation
'safe-local-variable
'integerp
)
586 (defcustom sh-remember-variable-min
3
587 "Don't remember variables less than this length for completing reads."
592 (defvar sh-header-marker nil
593 "When non-nil is the end of header for prepending by \\[sh-execute-region].
594 That command is also used for setting this variable.")
595 (make-variable-buffer-local 'sh-header-marker
)
597 (defcustom sh-beginning-of-command
598 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~[:alnum:]:]\\)"
599 "Regexp to determine the beginning of a shell command.
600 The actual command starts at the beginning of the second \\(grouping\\)."
605 (defcustom sh-end-of-command
606 "\\([/~[:alnum:]:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
607 "Regexp to determine the end of a shell command.
608 The actual command ends at the end of the first \\(grouping\\)."
614 (defcustom sh-here-document-word
"EOF"
615 "Word to delimit here documents.
616 If the first character of this string is \"-\", this is taken as
617 part of the redirection operator, rather than part of the
618 word (that is, \"<<-\" instead of \"<<\"). This is a feature
619 used by some shells (for example Bash) to indicate that leading
620 tabs inside the here document should be ignored. In this case,
621 Emacs indents the initial body and end of the here document with
622 tabs, to the same level as the start (note that apart from this
623 there is no support for indentation of here documents). This
624 will only work correctly if `sh-basic-offset' is a multiple of
627 Any quote characters or leading whitespace in the word are
628 removed when closing the here document."
636 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
639 ;; customized this out of sheer bravado. not for the faint of heart.
640 ;; but it *did* have an asterisk in the docstring!
641 (defcustom sh-builtins
642 '((bash sh-append posix
643 "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
644 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
645 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
646 "source" "suspend" "typeset" "unalias")
648 ;; The next entry is only used for defining the others
649 (bourne sh-append shell
650 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
654 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
655 "setenv" "source" "time" "unalias" "unhash")
657 (dtksh sh-append wksh
)
659 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
660 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
663 "bg" "fg" "jobs" "kill" "stop" "suspend")
666 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
668 (ksh88 sh-append bourne
669 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
670 "typeset" "unalias" "whence")
673 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
674 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
675 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
676 "wmtitle" "wrefresh")
678 (pdksh sh-append ksh88
684 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
688 "hash" "test" "type")
690 ;; The next entry is only used for defining the others
691 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
693 (wksh sh-append ksh88
694 ;; FIXME: This looks too much like a regexp. --Stef
698 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
699 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
700 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
701 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
702 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
704 "List of all shell builtins for completing read and fontification.
705 Note that on some systems not all builtins are available or some are
706 implemented as aliases. See `sh-feature'."
707 :type
'(repeat (cons (symbol :tag
"Shell")
708 (choice (repeat string
)
709 (sexp :format
"Evaluate: %v"))))
714 (defcustom sh-leading-keywords
720 (es "true" "unwind-protect" "whatis")
724 (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
725 "List of keywords that may be immediately followed by a builtin or keyword.
726 Given some confusion between keywords and builtins depending on shell and
727 system, the distinction here has been based on whether they influence the
728 flow of control or syntax. See `sh-feature'."
729 :type
'(repeat (cons (symbol :tag
"Shell")
730 (choice (repeat string
)
731 (sexp :format
"Evaluate: %v"))))
735 (defcustom sh-other-keywords
736 '((bash sh-append bourne
737 "bye" "logout" "select")
739 ;; The next entry is only used for defining the others
744 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
745 "if" "logout" "onintr" "repeat" "switch" "then" "while")
747 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
748 "return" "throw" "while")
750 (ksh88 sh-append bourne
753 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
757 "done" "esac" "fi" "for" "in" "return")
759 ;; The next entry is only used for defining the others
760 (shell "break" "case" "continue" "exec" "exit")
764 "List of keywords not in `sh-leading-keywords'.
766 :type
'(repeat (cons (symbol :tag
"Shell")
767 (choice (repeat string
)
768 (sexp :format
"Evaluate: %v"))))
775 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
776 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
777 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
778 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
779 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
780 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
781 "HISTIGNORE" "history_control" "HISTSIZE"
782 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
783 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
784 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
785 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
786 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
787 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
788 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
791 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
792 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
793 "shell" "status" "time" "verbose")
796 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
797 "pid" "prompt" "signals")
803 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
804 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
808 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
811 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
815 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
817 ;; The next entry is only used for defining the others
818 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
819 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
820 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
821 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
824 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
825 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
826 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
827 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
828 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
829 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
830 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
831 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
835 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
836 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
837 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
838 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
839 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
840 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
841 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
842 "List of all shell variables available for completing read.
849 '((((min-colors 88) (class color
)
851 (:foreground
"yellow1" :weight bold
))
854 (:foreground
"yellow" :weight bold
))
857 (:foreground
"tan1" ))
860 "Face to show a here-document"
861 :group
'sh-indentation
)
863 ;; These colors are probably icky. It's just a placeholder though.
864 (defface sh-quoted-exec
865 '((((class color
) (background dark
))
866 (:foreground
"salmon"))
867 (((class color
) (background light
))
868 (:foreground
"magenta"))
871 "Face to show quoted execs like ``"
872 :group
'sh-indentation
)
873 (define-obsolete-face-alias 'sh-heredoc-face
'sh-heredoc
"22.1")
874 (defvar sh-heredoc-face
'sh-heredoc
)
876 (defface sh-escaped-newline
'((t :inherit font-lock-string-face
))
877 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
881 (defvar sh-font-lock-keywords-var
882 '((csh sh-append shell
883 ("\\${?[#?]?\\([[:alpha:]_][[:alnum:]_]*\\|0\\)" 1
884 font-lock-variable-name-face
))
886 (es sh-append executable-font-lock-keywords
887 ("\\$#?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\)" 1
888 font-lock-variable-name-face
))
891 (bash sh-append shell
("\\$(\\(\\sw+\\)" (1 'sh-quoted-exec t
) ))
894 ("\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?@!]\\)" 2
895 font-lock-variable-name-face
)
897 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face
)
898 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
899 (1 font-lock-keyword-face
) (2 font-lock-function-name-face nil t
))
900 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
901 1 font-lock-negation-char-face
))
903 ;; The next entry is only used for defining the others
905 ;; Using font-lock-string-face here confuses sh-get-indent-info.
906 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline
)
907 ("\\\\[^[:alnum:]]" 0 font-lock-string-face
)
908 ("\\${?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\|[$*_]\\)" 1
909 font-lock-variable-name-face
))
911 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face
))
912 (rpm2 sh-append shell
913 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face
)))
914 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
916 (defvar sh-font-lock-keywords-var-1
918 "Subdued level highlighting for Shell Script modes.")
920 (defvar sh-font-lock-keywords-var-2
()
921 "Gaudy level highlighting for Shell Script modes.")
923 ;; These are used for the syntax table stuff (derived from cperl-mode).
924 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
925 (defconst sh-st-punc
(string-to-syntax "."))
926 (defconst sh-here-doc-syntax
(string-to-syntax "|")) ;; generic string
929 (defconst sh-escaped-line-re
930 ;; Should match until the real end-of-continued-line, but if that is not
931 ;; possible (because we bump into EOB or the search bound), then we should
932 ;; match until the search bound.
933 "\\(?:\\(?:.*[^\\\n]\\)?\\(?:\\\\\\\\\\)*\\\\\n\\)*.*")
935 (defconst sh-here-doc-open-re
936 (concat "<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\|[-/~._]\\)+\\)"
937 sh-escaped-line-re
"\\(\n\\)")))
939 (defun sh-font-lock-open-heredoc (start string eol
)
940 "Determine the syntax of the \\n after a <<EOF.
941 START is the position of <<.
942 STRING is the actual word used as delimiter (e.g. \"EOF\").
943 INDENTED is non-nil if the here document's content (and the EOF mark) can
944 be indented (i.e. a <<- was used rather than just <<).
945 Point is at the beginning of the next line."
946 (unless (or (memq (char-before start
) '(?
< ?
>))
947 (sh-in-comment-or-string start
))
948 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
949 ;; font-lock keywords to detect the end of this here document.
950 (let ((str (replace-regexp-in-string "['\"]" "" string
))
951 (ppss (save-excursion (syntax-ppss eol
))))
953 ;; The \n not only starts the heredoc but also closes a comment.
954 ;; Let's close the comment just before the \n.
955 (put-text-property (1- eol
) eol
'syntax-table
'(12))) ;">"
956 (if (or (nth 5 ppss
) (> (count-lines start eol
) 1))
957 ;; If the sh-escaped-line-re part of sh-here-doc-open-re has matched
958 ;; several lines, make sure we refontify them together.
959 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
960 ;; escaped), it means the right \n is actually further down.
961 ;; Don't bother fixing it now, but place a multiline property so
962 ;; that when jit-lock-context-* refontifies the rest of the
963 ;; buffer, it also refontifies the current line with it.
964 (put-text-property start
(1+ eol
) 'syntax-multiline t
))
965 (put-text-property eol
(1+ eol
) 'sh-here-doc-marker str
)
966 (prog1 sh-here-doc-syntax
967 (goto-char (+ 2 start
))))))
969 (defun sh-syntax-propertize-here-doc (end)
970 (let ((ppss (syntax-ppss)))
971 (when (eq t
(nth 3 ppss
))
972 (let ((key (get-text-property (nth 8 ppss
) 'sh-here-doc-marker
))
973 (case-fold-search nil
))
974 (when (re-search-forward
975 (concat "^\\([ \t]*\\)" (regexp-quote key
) "\\(\n\\)")
977 (let ((eol (match-beginning 2)))
978 (put-text-property eol
(1+ eol
)
979 'syntax-table sh-here-doc-syntax
)))))))
981 (defun sh-font-lock-quoted-subshell (limit)
982 "Search for a subshell embedded in a string.
983 Find all the unescaped \" characters within said subshell, remembering that
985 ;; FIXME: This can (and often does) match multiple lines, yet it makes no
986 ;; effort to handle multiline cases correctly, so it ends up being
988 (when (eq ?
\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
989 ;; bingo we have a $( or a ` inside a ""
990 (let (;; `state' can be: double-quote, backquote, code.
991 (state (if (eq (char-before) ?
`) 'backquote
'code
))
992 ;; Stacked states in the context.
993 (states '(double-quote)))
994 (while (and state
(progn (skip-chars-forward "^'\\\\\"`$()" limit
)
996 ;; unescape " inside a $( ... ) construct.
1000 (t (forward-char 1) (skip-chars-forward "^'" limit
))))
1001 (?
\\ (forward-char 1))
1003 (double-quote (setq state
(pop states
)))
1004 (t (push state states
) (setq state
'double-quote
)))
1005 (if state
(put-text-property (point) (1+ (point))
1006 'syntax-table
'(1))))
1008 (backquote (setq state
(pop states
)))
1009 (t (push state states
) (setq state
'backquote
))))
1010 (?\$
(if (not (eq (char-after (1+ (point))) ?\
())
1014 (t (push state states
) (setq state
'code
)))))
1017 (t (push state states
) (setq state
'code
))))
1020 (t (setq state
(pop states
)))))
1021 (t (error "Internal error in sh-font-lock-quoted-subshell")))
1022 (forward-char 1)))))
1025 (defun sh-is-quoted-p (pos)
1026 (and (eq (char-before pos
) ?
\\)
1027 (not (sh-is-quoted-p (1- pos
)))))
1029 (defun sh-font-lock-paren (start)
1030 (unless (nth 8 (syntax-ppss))
1033 ;; Skip through all patterns
1038 (forward-comment (- (point-max)))
1039 (when (and (eolp) (sh-is-quoted-p (point)))
1042 ;; Skip through one pattern
1044 (or (/= 0 (skip-syntax-backward "w_"))
1045 (/= 0 (skip-chars-backward "-$=?[]*@/\\\\"))
1046 (and (sh-is-quoted-p (1- (point)))
1047 (goto-char (- (point) 2)))
1048 (when (memq (char-before) '(?
\" ?
\' ?\
}))
1049 (condition-case nil
(progn (backward-sexp 1) t
)
1051 ;; Patterns can be preceded by an open-paren (Bug#1320).
1052 (if (eq (char-before (point)) ?\
()
1055 (forward-comment (- (point-max)))
1056 ;; Maybe we've bumped into an escaped newline.
1057 (sh-is-quoted-p (point)))
1059 (when (eq (char-before) ?|
)
1060 (backward-char 1) t
)))
1061 (when (progn (backward-char 2)
1062 (if (> start
(line-end-position))
1063 (put-text-property (point) (1+ start
)
1064 'syntax-multiline t
))
1065 ;; FIXME: The `in' may just be a random argument to
1066 ;; a normal command rather than the real `in' keyword.
1067 ;; I.e. we should look back to try and find the
1068 ;; corresponding `case'.
1069 (and (looking-at ";[;&]\\|in")
1070 ;; ";; esac )" is a case that looks like a case-pattern
1071 ;; but it's really just a close paren after a case
1072 ;; statement. I.e. if we skipped over `esac' just now,
1073 ;; we're not looking at a case-pattern.
1074 (not (looking-at "..[ \t\n]+esac[^[:word:]_]"))))
1077 (defun sh-font-lock-backslash-quote ()
1078 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?
\')
1079 ;; In a '...' the backslash is not escaping.
1083 (defun sh-syntax-propertize-function (start end
)
1085 (sh-syntax-propertize-here-doc end
)
1087 (syntax-propertize-rules
1088 (sh-here-doc-open-re
1089 (2 (sh-font-lock-open-heredoc
1090 (match-beginning 0) (match-string 1) (match-beginning 2))))
1091 ("\\s|" (0 (prog1 nil
(sh-syntax-propertize-here-doc end
))))
1092 ;; A `#' begins a comment when it is unquoted and at the
1093 ;; beginning of a word. In the shell, words are separated by
1094 ;; metacharacters. The list of special chars is taken from
1095 ;; the single-unix spec of the shell command language (under
1096 ;; `quoting') but with `$' removed.
1097 ("[^|&;<>()`\\\"' \t\n]\\(#+\\)" (1 "_"))
1098 ;; In a '...' the backslash is not escaping.
1099 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1100 ;; Make sure $@ and $? are correctly recognized as sexps.
1101 ("\\$\\([?@]\\)" (1 "_"))
1102 ;; Distinguish the special close-paren in `case'.
1103 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1104 ;; Highlight (possibly nested) subshells inside "" quoted
1105 ;; regions correctly.
1106 ("\"\\(?:\\(?:[^\\\"]\\|\\)*?[^\\]\\(?:\\\\\\\\\\)*\\)??\\(\\$(\\|`\\)"
1108 ;; Save excursion because we want to also apply other
1109 ;; syntax-propertize rules within the affected region.
1110 (if (nth 8 (syntax-ppss))
1111 (goto-char (1+ (match-beginning 0)))
1113 (sh-font-lock-quoted-subshell end
)))))))
1116 (defun sh-font-lock-syntactic-face-function (state)
1117 (let ((q (nth 3 state
)))
1120 (if (eq q ?\
`) 'sh-quoted-exec font-lock-string-face
)
1122 font-lock-comment-face
)))
1124 (defgroup sh-indentation nil
1125 "Variables controlling indentation in shell scripts.
1127 Note: customizing these variables will not affect existing buffers if
1128 `sh-make-vars-local' is non-nil. See the documentation for
1129 variable `sh-make-vars-local', command `sh-make-vars-local'
1130 and command `sh-reset-indent-vars-to-global-values'."
1134 (defcustom sh-set-shell-hook nil
1135 "Hook run by `sh-set-shell'."
1139 (defcustom sh-mode-hook nil
1140 "Hook run by `sh-mode'."
1144 (defcustom sh-learn-basic-offset nil
1145 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1148 t means: only if there seems to be an obvious value.
1149 Anything else means: whenever we have a \"good guess\" as to the value."
1151 (const :tag
"Never" nil
)
1152 (const :tag
"Only if sure" t
)
1153 (const :tag
"If have a good guess" usually
))
1154 :group
'sh-indentation
)
1156 (defcustom sh-popup-occur-buffer nil
1157 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1158 If t it is always shown. If nil, it is shown only when there
1161 (const :tag
"Only when there are conflicts." nil
)
1162 (const :tag
"Always" t
))
1163 :group
'sh-indentation
)
1165 (defcustom sh-blink t
1166 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
1167 The position on the line is not necessarily meaningful.
1168 In some cases the line will be the matching keyword, but this is not
1171 :group
'sh-indentation
)
1173 (defcustom sh-first-lines-indent
0
1174 "The indentation of the first non-blank non-comment line.
1175 Usually 0 meaning first column.
1176 Can be set to a number, or to nil which means leave it as is."
1178 (const :tag
"Leave as is" nil
)
1179 (integer :tag
"Column number"
1180 :menu-tag
"Indent to this col (0 means first col)" ))
1181 :group
'sh-indentation
)
1184 (defcustom sh-basic-offset
4
1185 "The default indentation increment.
1186 This value is used for the `+' and `-' symbols in an indentation variable."
1188 :group
'sh-indentation
)
1189 (put 'sh-basic-offset
'safe-local-variable
'integerp
)
1191 (defcustom sh-indent-comment nil
1192 "How a comment line is to be indented.
1193 nil means leave it as it is;
1194 t means indent it as a normal line, aligning it to previous non-blank
1196 a number means align to that column, e.g. 0 means first column."
1198 (const :tag
"Leave as is." nil
)
1199 (const :tag
"Indent as a normal line." t
)
1200 (integer :menu-tag
"Indent to this col (0 means first col)."
1201 :tag
"Indent to column number.") )
1202 :group
'sh-indentation
)
1205 (defvar sh-debug nil
1206 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1209 ;; Uncomment this defun and comment the defmacro for debugging.
1210 ;; (defun sh-debug (&rest args)
1211 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1213 ;; (apply 'message args)))
1214 (defmacro sh-debug
(&rest _args
))
1216 (defconst sh-symbol-list
1217 '((const :tag
"+ " :value
+
1218 :menu-tag
"+ Indent right by sh-basic-offset")
1219 (const :tag
"- " :value -
1220 :menu-tag
"- Indent left by sh-basic-offset")
1221 (const :tag
"++" :value
++
1222 :menu-tag
"++ Indent right twice sh-basic-offset")
1223 (const :tag
"--" :value --
1224 :menu-tag
"-- Indent left twice sh-basic-offset")
1225 (const :tag
"* " :value
*
1226 :menu-tag
"* Indent right half sh-basic-offset")
1227 (const :tag
"/ " :value
/
1228 :menu-tag
"/ Indent left half sh-basic-offset")))
1230 (defcustom sh-indent-for-else
0
1231 "How much to indent an `else' relative to its `if'. Usually 0."
1233 (integer :menu-tag
"A number (positive=>indent right)"
1235 (const :tag
"--") ;; separator!
1238 :group
'sh-indentation
)
1240 (defconst sh-number-or-symbol-list
1241 (append '((integer :menu-tag
"A number (positive=>indent right)"
1243 (const :tag
"--")) ; separator
1246 (defcustom sh-indent-for-fi
0
1247 "How much to indent a `fi' relative to its `if'. Usually 0."
1248 :type
`(choice ,@ sh-number-or-symbol-list
)
1249 :group
'sh-indentation
)
1251 (defcustom sh-indent-for-done
0
1252 "How much to indent a `done' relative to its matching stmt. Usually 0."
1253 :type
`(choice ,@ sh-number-or-symbol-list
)
1254 :group
'sh-indentation
)
1256 (defcustom sh-indent-after-else
'+
1257 "How much to indent a statement after an `else' statement."
1258 :type
`(choice ,@ sh-number-or-symbol-list
)
1259 :group
'sh-indentation
)
1261 (defcustom sh-indent-after-if
'+
1262 "How much to indent a statement after an `if' statement.
1263 This includes lines after `else' and `elif' statements, too, but
1264 does not affect the `else', `elif' or `fi' statements themselves."
1265 :type
`(choice ,@ sh-number-or-symbol-list
)
1266 :group
'sh-indentation
)
1268 (defcustom sh-indent-for-then
0
1269 "How much to indent a `then' relative to its `if'."
1270 :type
`(choice ,@ sh-number-or-symbol-list
)
1271 :group
'sh-indentation
)
1273 (defcustom sh-indent-for-do
0
1274 "How much to indent a `do' statement.
1275 This is relative to the statement before the `do', typically a
1276 `while', `until', `for', `repeat' or `select' statement."
1277 :type
`(choice ,@ sh-number-or-symbol-list
)
1278 :group
'sh-indentation
)
1280 (defcustom sh-indent-after-do
'+
1281 "How much to indent a line after a `do' statement.
1282 This is used when the `do' is the first word of the line.
1283 This is relative to the statement before the `do', typically a
1284 `while', `until', `for', `repeat' or `select' statement."
1285 :type
`(choice ,@ sh-number-or-symbol-list
)
1286 :group
'sh-indentation
)
1288 (defcustom sh-indent-after-loop-construct
'+
1289 "How much to indent a statement after a loop construct.
1291 This variable is used when the keyword `do' is on the same line as the
1292 loop statement (e.g., `until', `while' or `for').
1293 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1294 :type
`(choice ,@ sh-number-or-symbol-list
)
1295 :group
'sh-indentation
)
1298 (defcustom sh-indent-after-done
0
1299 "How much to indent a statement after a `done' keyword.
1300 Normally this is 0, which aligns the `done' to the matching
1301 looping construct line.
1302 Setting it non-zero allows you to have the `do' statement on a line
1303 by itself and align the done under to do."
1304 :type
`(choice ,@ sh-number-or-symbol-list
)
1305 :group
'sh-indentation
)
1307 (defcustom sh-indent-for-case-label
'+
1308 "How much to indent a case label statement.
1309 This is relative to the line containing the `case' statement."
1310 :type
`(choice ,@ sh-number-or-symbol-list
)
1311 :group
'sh-indentation
)
1313 (defcustom sh-indent-for-case-alt
'++
1314 "How much to indent statements after the case label.
1315 This is relative to the line containing the `case' statement."
1316 :type
`(choice ,@ sh-number-or-symbol-list
)
1317 :group
'sh-indentation
)
1320 (defcustom sh-indent-for-continuation
'+
1321 "How much to indent for a continuation statement."
1322 :type
`(choice ,@ sh-number-or-symbol-list
)
1323 :group
'sh-indentation
)
1325 (defcustom sh-indent-after-open
'+
1326 "How much to indent after a line with an opening parenthesis or brace.
1327 For an open paren after a function, `sh-indent-after-function' is used."
1328 :type
`(choice ,@ sh-number-or-symbol-list
)
1329 :group
'sh-indentation
)
1331 (defcustom sh-indent-after-function
'+
1332 "How much to indent after a function line."
1333 :type
`(choice ,@ sh-number-or-symbol-list
)
1334 :group
'sh-indentation
)
1336 ;; These 2 are for the rc shell:
1338 (defcustom sh-indent-after-switch
'+
1339 "How much to indent a `case' statement relative to the `switch' statement.
1340 This is for the rc shell."
1341 :type
`(choice ,@ sh-number-or-symbol-list
)
1342 :group
'sh-indentation
)
1344 (defcustom sh-indent-after-case
'+
1345 "How much to indent a statement relative to the `case' statement.
1346 This is for the rc shell."
1347 :type
`(choice ,@ sh-number-or-symbol-list
)
1348 :group
'sh-indentation
)
1350 (defcustom sh-backslash-column
48
1351 "Column in which `sh-backslash-region' inserts backslashes."
1355 (defcustom sh-backslash-align t
1356 "If non-nil, `sh-backslash-region' will align backslashes."
1360 ;; Internal use - not designed to be changed by the user:
1362 (defun sh-mkword-regexpr (word)
1363 "Make a regexp which matches WORD as a word.
1364 This specifically excludes an occurrence of WORD followed by
1365 punctuation characters like '-'."
1366 (concat word
"\\([^-[:alnum:]_]\\|$\\)"))
1368 (defconst sh-re-done
(sh-mkword-regexpr "done"))
1371 (defconst sh-kws-for-done
1372 '((sh .
( "while" "until" "for" ) )
1373 (bash .
( "while" "until" "for" "select" ) )
1374 (ksh88 .
( "while" "until" "for" "select" ) )
1375 (zsh .
( "while" "until" "for" "repeat" "select" ) ) )
1376 "Which keywords can match the word `done' in this shell.")
1379 (defconst sh-indent-supported
1383 "Shell types that shell indenting can do something with.")
1385 (defvar sh-indent-supported-here nil
1386 "Non-nil if we support indentation for the current buffer's shell type.")
1388 (defconst sh-var-list
1390 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1391 sh-indent-after-do sh-indent-after-done
1392 sh-indent-after-else
1394 sh-indent-after-loop-construct
1395 sh-indent-after-open
1397 sh-indent-for-case-alt
1398 sh-indent-for-case-label
1399 sh-indent-for-continuation
1406 "A list of variables used by script mode to control indentation.
1407 This list is used when switching between buffer-local and global
1408 values of variables, and for the commands using indentation styles.")
1410 (defvar sh-make-vars-local t
1411 "*Controls whether indentation variables are local to the buffer.
1412 If non-nil, indentation variables are made local initially.
1413 If nil, you can later make the variables local by invoking
1414 command `sh-make-vars-local'.
1415 The default is t because I assume that in one Emacs session one is
1416 frequently editing existing scripts with different styles.")
1419 ;; mode-command and utility functions
1422 (define-derived-mode sh-mode prog-mode
"Shell-script"
1423 "Major mode for editing shell scripts.
1424 This mode works for many shells, since they all have roughly the same syntax,
1425 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1426 Unless the file's magic number indicates the shell, your usual shell is
1427 assumed. Since filenames rarely give a clue, they are not further analyzed.
1429 This mode adapts to the variations between shells (see `sh-set-shell') by
1430 means of an inheritance based feature lookup (see `sh-feature'). This
1431 mechanism applies to all variables (including skeletons) that pertain to
1432 shell-specific features.
1434 The default style of this mode is that of Rosenblatt's Korn shell book.
1435 The syntax of the statements varies with the shell being used. The
1436 following commands are available, based on the current shell's syntax:
1438 \\[sh-case] case statement
1440 \\[sh-function] function definition
1441 \\[sh-if] if statement
1442 \\[sh-indexed-loop] indexed loop from 1 to n
1443 \\[sh-while-getopts] while getopts loop
1444 \\[sh-repeat] repeat loop
1445 \\[sh-select] select loop
1446 \\[sh-until] until loop
1447 \\[sh-while] while loop
1449 For sh and rc shells indentation commands are:
1450 \\[sh-show-indent] Show the variable controlling this line's indentation.
1451 \\[sh-set-indent] Set then variable controlling this line's indentation.
1452 \\[sh-learn-line-indent] Change the indentation variable so this line
1453 would indent to the way it currently is.
1454 \\[sh-learn-buffer-indent] Set the indentation variables so the
1455 buffer indents as it currently is indented.
1458 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1459 \\[newline-and-indent] Delete unquoted space and indent new line same as this one.
1460 \\[sh-end-of-command] Go to end of successive commands.
1461 \\[sh-beginning-of-command] Go to beginning of successive commands.
1462 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1463 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1465 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
1467 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1469 If you generally program a shell different from your login shell you can
1470 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1471 indicate what shell it is use `sh-alias-alist' to translate.
1473 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1474 with your script for an edit-interpret-debug cycle."
1475 (make-local-variable 'sh-shell-file
)
1476 (make-local-variable 'sh-shell
)
1478 (set (make-local-variable 'skeleton-pair-default-alist
)
1479 sh-skeleton-pair-default-alist
)
1480 (set (make-local-variable 'skeleton-end-hook
)
1481 (lambda () (or (eolp) (newline) (indent-relative))))
1483 (set (make-local-variable 'paragraph-start
) (concat page-delimiter
"\\|$"))
1484 (set (make-local-variable 'paragraph-separate
) paragraph-start
)
1485 (set (make-local-variable 'comment-start
) "# ")
1486 (set (make-local-variable 'comment-start-skip
) "#+[\t ]*")
1487 (set (make-local-variable 'local-abbrev-table
) sh-mode-abbrev-table
)
1488 (set (make-local-variable 'comint-dynamic-complete-functions
)
1489 sh-dynamic-complete-functions
)
1490 ;; we can't look if previous line ended with `\'
1491 (set (make-local-variable 'comint-prompt-regexp
) "^[ \t]*")
1492 (set (make-local-variable 'imenu-case-fold-search
) nil
)
1493 (set (make-local-variable 'font-lock-defaults
)
1494 `((sh-font-lock-keywords
1495 sh-font-lock-keywords-1 sh-font-lock-keywords-2
)
1497 ((?
/ .
"w") (?~ .
"w") (?. .
"w") (?- .
"w") (?_ .
"w")) nil
1498 (font-lock-syntactic-face-function
1499 . sh-font-lock-syntactic-face-function
)))
1500 (set (make-local-variable 'syntax-propertize-function
)
1501 #'sh-syntax-propertize-function
)
1502 (add-hook 'syntax-propertize-extend-region-functions
1503 #'syntax-propertize-multiline
'append
'local
)
1504 (set (make-local-variable 'skeleton-pair-alist
) '((?
` _ ?
`)))
1505 (set (make-local-variable 'skeleton-pair-filter-function
) 'sh-quoted-p
)
1506 (set (make-local-variable 'skeleton-further-elements
)
1507 '((< '(- (min sh-indentation
(current-column))))))
1508 (set (make-local-variable 'skeleton-filter-function
) 'sh-feature
)
1509 (set (make-local-variable 'skeleton-newline-indent-rigidly
) t
)
1510 (set (make-local-variable 'sh-indent-supported-here
) nil
)
1511 (set (make-local-variable 'defun-prompt-regexp
)
1512 (concat "^\\(function[ \t]\\|[[:alnum:]]+[ \t]+()[ \t]+\\)"))
1513 ;; Parse or insert magic number for exec, and set all variables depending
1514 ;; on the shell thus determined.
1516 (cond ((save-excursion
1517 (goto-char (point-min))
1518 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1520 ((not buffer-file-name
)
1522 ;; Checks that use `buffer-file-name' follow.
1523 ((string-match "\\.m?spec\\'" buffer-file-name
)
1525 ((string-match "[.]sh\\>" buffer-file-name
)
1527 ((string-match "[.]bash\\>" buffer-file-name
)
1529 ((string-match "[.]ksh\\>" buffer-file-name
)
1531 ((string-match "[.]csh\\>" buffer-file-name
)
1533 ((equal (file-name-nondirectory buffer-file-name
) ".profile")
1540 (defalias 'shell-script-mode
'sh-mode
)
1543 (defun sh-font-lock-keywords (&optional keywords
)
1544 "Function to get simple fontification based on `sh-font-lock-keywords'.
1545 This adds rules for comments and assignments."
1546 (sh-feature sh-font-lock-keywords-var
1547 (when (stringp (sh-feature sh-assignment-regexp
))
1549 `((,(sh-feature sh-assignment-regexp
)
1550 1 font-lock-variable-name-face
)
1553 ,@executable-font-lock-keywords
)))))
1555 (defun sh-font-lock-keywords-1 (&optional builtins
)
1556 "Function to get better fontification including keywords."
1557 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1558 (regexp-opt (sh-feature sh-leading-keywords
) t
)
1560 (regexp-opt (append (sh-feature sh-leading-keywords
)
1561 (sh-feature sh-other-keywords
))
1563 (sh-font-lock-keywords
1565 `((,(concat keywords
"[ \t]+\\)?"
1566 (regexp-opt (sh-feature sh-builtins
) t
)
1568 (2 font-lock-keyword-face nil t
)
1569 (6 font-lock-builtin-face
))
1570 ,@(sh-feature sh-font-lock-keywords-var-2
)))
1571 (,(concat keywords
"\\)\\>")
1572 2 font-lock-keyword-face
)
1573 ,@(sh-feature sh-font-lock-keywords-var-1
)))))
1575 (defun sh-font-lock-keywords-2 ()
1576 "Function to get better fontification including keywords and builtins."
1577 (sh-font-lock-keywords-1 t
))
1580 (defvar sh-regexp-for-done nil
1581 "A buffer-local regexp to match opening keyword for done.")
1583 (defvar sh-kw-alist nil
1584 "A buffer-local, since it is shell-type dependent, list of keywords.")
1586 ;; ( key-word first-on-this on-prev-line )
1587 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1588 ;; having 3 elements:
1590 ;; a rule to check when the keyword appears on "this" line
1591 ;; a rule to check when the keyword appears on "the previous" line
1592 ;; The keyword is usually a string and is the first word on a line.
1593 ;; If this keyword appears on the line whose indentation is to be
1594 ;; calculated, the rule in element 2 is called. If this returns
1595 ;; non-zero, the resulting point (which may be changed by the rule)
1596 ;; is used as the default indentation.
1597 ;; If it returned false or the keyword was not found in the table,
1598 ;; then the keyword from the previous line is looked up and the rule
1599 ;; in element 3 is called. In this case, however,
1600 ;; `sh-get-indent-info' does not stop but may keep going and test
1601 ;; other keywords against rules in element 3. This is because the
1602 ;; preceding line could have, for example, an opening "if" and an
1603 ;; opening "while" keyword and we need to add the indentation offsets
1608 ("if" nil sh-handle-prev-if
)
1609 ("elif" sh-handle-this-else sh-handle-prev-else
)
1610 ("else" sh-handle-this-else sh-handle-prev-else
)
1611 ("fi" sh-handle-this-fi sh-handle-prev-fi
)
1612 ("then" sh-handle-this-then sh-handle-prev-then
)
1613 ("(" nil sh-handle-prev-open
)
1614 ("{" nil sh-handle-prev-open
)
1615 ("[" nil sh-handle-prev-open
)
1616 ("}" sh-handle-this-close nil
)
1617 (")" sh-handle-this-close nil
)
1618 ("]" sh-handle-this-close nil
)
1619 ("case" nil sh-handle-prev-case
)
1620 ("esac" sh-handle-this-esac sh-handle-prev-esac
)
1621 (case-label nil sh-handle-after-case-label
) ;; ???
1622 (";;" nil sh-handle-prev-case-alt-end
) ;; ???
1623 (";;&" nil sh-handle-prev-case-alt-end
) ;Like ";;" with diff semantics.
1624 (";&" nil sh-handle-prev-case-alt-end
) ;Like ";;" with diff semantics.
1625 ("done" sh-handle-this-done sh-handle-prev-done
)
1626 ("do" sh-handle-this-do sh-handle-prev-do
))
1628 ;; Note: we don't need specific stuff for bash and zsh shells;
1629 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1630 ;; these shells use.
1632 ("{" nil sh-handle-prev-open
)
1633 ("}" sh-handle-this-close nil
)
1634 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case
))))
1638 (defun sh-set-shell (shell &optional no-query-flag insert-flag
)
1639 "Set this buffer's shell to SHELL (a string).
1640 When used interactively, insert the proper starting #!-line,
1641 and make the visited file executable via `executable-set-magic',
1642 perhaps querying depending on the value of `executable-query'.
1644 When this function is called noninteractively, INSERT-FLAG (the third
1645 argument) controls whether to insert a #!-line and think about making
1646 the visited file executable, and NO-QUERY-FLAG (the second argument)
1647 controls whether to query about making the visited file executable.
1649 Calls the value of `sh-set-shell-hook' if set."
1650 (interactive (list (completing-read (format "Shell \(default %s\): "
1652 interpreter-mode-alist
1653 (lambda (x) (eq (cdr x
) 'sh-mode
))
1654 nil nil nil sh-shell-file
)
1655 (eq executable-query
'function
)
1657 (if (string-match "\\.exe\\'" shell
)
1658 (setq shell
(substring shell
0 (match-beginning 0))))
1659 (setq sh-shell
(intern (file-name-nondirectory shell
))
1660 sh-shell
(or (cdr (assq sh-shell sh-alias-alist
))
1664 (executable-set-magic shell
(sh-feature sh-shell-arg
)
1665 no-query-flag insert-flag
)))
1666 (setq mode-line-process
(format "[%s]" sh-shell
))
1667 (set (make-local-variable 'sh-shell-variables
) nil
)
1668 (set (make-local-variable 'sh-shell-variables-initialized
) nil
)
1669 (set (make-local-variable 'imenu-generic-expression
)
1670 (sh-feature sh-imenu-generic-expression
))
1671 (let ((tem (sh-feature sh-mode-syntax-table-input
)))
1673 (set (make-local-variable 'sh-mode-syntax-table
)
1674 (apply 'sh-mode-syntax-table tem
))
1675 (set-syntax-table sh-mode-syntax-table
)))
1676 (dolist (var (sh-feature sh-variables
))
1677 (sh-remember-variable var
))
1678 (if (setq sh-indent-supported-here
(sh-feature sh-indent-supported
))
1680 (message "Setting up indent for shell type %s" sh-shell
)
1681 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
1682 (set (make-local-variable 'sh-kw-alist
) (sh-feature sh-kw
))
1683 (let ((regexp (sh-feature sh-kws-for-done
)))
1685 (set (make-local-variable 'sh-regexp-for-done
)
1686 (sh-mkword-regexpr (regexp-opt regexp t
)))))
1687 (message "setting up indent stuff")
1688 ;; sh-mode has already made indent-line-function local
1689 ;; but do it in case this is called before that.
1690 (set (make-local-variable 'indent-line-function
) 'sh-indent-line
)
1691 (if sh-make-vars-local
1692 (sh-make-vars-local))
1693 (message "Indentation setup for shell type %s" sh-shell
))
1694 (message "No indentation for this shell type.")
1695 (setq indent-line-function
'sh-basic-indent-line
))
1696 (when font-lock-mode
1697 (setq font-lock-set-defaults nil
)
1698 (font-lock-set-defaults)
1699 (font-lock-fontify-buffer))
1700 (run-hooks 'sh-set-shell-hook
))
1703 (defun sh-feature (alist &optional function
)
1704 "Index ALIST by the current shell.
1705 If ALIST isn't a list where every element is a cons, it is returned as is.
1706 Else indexing follows an inheritance logic which works in two ways:
1708 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1709 the alist contains no value for the current shell.
1710 The ultimate default is always `sh'.
1712 - If the value thus looked up is a list starting with `sh-append',
1713 we call the function `sh-append' with the rest of the list as
1714 arguments, and use the value. However, the next element of the
1715 list is not used as-is; instead, we look it up recursively
1716 in ALIST to allow the function called to define the value for
1717 one shell to be derived from another shell.
1718 The value thus determined is physically replaced into the alist.
1720 If FUNCTION is non-nil, it is called with one argument,
1721 the value thus obtained, and the result is used instead."
1722 (or (if (consp alist
)
1723 ;; Check for something that isn't a valid alist.
1725 (while (and l
(consp (car l
)))
1729 (let ((orig-sh-shell sh-shell
))
1730 (let ((sh-shell sh-shell
)
1732 (while (and sh-shell
1733 (not (setq elt
(assq sh-shell alist
))))
1734 (setq sh-shell
(cdr (assq sh-shell sh-ancestor-alist
))))
1735 ;; If the shell is not known, treat it as sh.
1737 (setq elt
(assq 'sh alist
)))
1738 (setq val
(cdr elt
))
1739 (if (and (consp val
)
1740 (memq (car val
) '(sh-append sh-modify
)))
1743 ;; Refer to the value for a different shell,
1744 ;; as a kind of inheritance.
1745 (let ((sh-shell (car (cdr val
))))
1749 (setq sh-shell orig-sh-shell
1750 val
(funcall function val
)))
1755 ;; I commented this out because nobody calls it -- rms.
1756 ;;(defun sh-abbrevs (ancestor &rest list)
1757 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
1758 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1759 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1760 ;;according to the remaining arguments NAMEi EXPANSIONi ...
1761 ;;EXPANSION may be either a string or a skeleton command."
1762 ;; (or (if (boundp sh-shell)
1763 ;; (symbol-value sh-shell))
1765 ;; (if (listp ancestor)
1766 ;; (nconc list ancestor))
1767 ;; (define-abbrev-table sh-shell ())
1768 ;; (if (vectorp ancestor)
1769 ;; (mapatoms (lambda (atom)
1771 ;; (define-abbrev (symbol-value sh-shell)
1772 ;; (symbol-name atom)
1773 ;; (symbol-value atom)
1774 ;; (symbol-function atom))))
1777 ;; (define-abbrev (symbol-value sh-shell)
1779 ;; (if (stringp (car (cdr list)))
1782 ;; (if (symbolp (car (cdr list)))
1783 ;; (car (cdr list))))
1784 ;; (setq list (cdr (cdr list)))))
1785 ;; (symbol-value sh-shell)))
1788 (defun sh-append (ancestor &rest list
)
1789 "Return list composed of first argument (a list) physically appended to rest."
1790 (nconc list ancestor
))
1793 (defun sh-modify (skeleton &rest list
)
1794 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1795 (setq skeleton
(copy-sequence skeleton
))
1797 (setcar (or (nthcdr (car list
) skeleton
)
1798 (error "Index %d out of bounds" (car list
)))
1800 (setq list
(nthcdr 2 list
)))
1804 (defun sh-basic-indent-line ()
1805 "Indent a line for Sh mode (shell script mode).
1806 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1807 Lines containing only comments are considered empty."
1809 (let ((previous (save-excursion
1810 (while (and (progn (beginning-of-line)
1814 (back-to-indentation)
1816 (eq (following-char) ?
#)))))
1820 (indent-to (if (eq this-command
'newline-and-indent
)
1822 (if (< (current-column)
1823 (setq current
(progn (back-to-indentation)
1825 (if (eolp) previous
0)
1826 (delete-region (point)
1827 (progn (beginning-of-line) (point)))
1829 (max previous
(* (1+ (/ current sh-indentation
))
1831 (* (1+ (/ current sh-indentation
)) sh-indentation
))))))
1832 (if (< (current-column) (current-indentation))
1833 (skip-chars-forward " \t"))))
1836 (defun sh-execute-region (start end
&optional flag
)
1837 "Pass optional header and region to a subshell for noninteractive execution.
1838 The working directory is that of the buffer, and only environment variables
1839 are already set which is why you can mark a header within the script.
1841 With a positive prefix ARG, instead of sending region, define header from
1842 beginning of buffer to point. With a negative prefix ARG, instead of sending
1843 region, clear header."
1844 (interactive "r\nP")
1846 (setq sh-header-marker
(if (> (prefix-numeric-value flag
) 0)
1848 (if sh-header-marker
1850 (let (buffer-undo-list)
1851 (goto-char sh-header-marker
)
1852 (append-to-buffer (current-buffer) start end
)
1853 (shell-command-on-region (point-min)
1854 (setq end
(+ sh-header-marker
1857 (delete-region sh-header-marker end
)))
1858 (shell-command-on-region start end
(concat sh-shell-file
" -")))))
1861 (defun sh-remember-variable (var)
1862 "Make VARIABLE available for future completing reads in this buffer."
1863 (or (< (length var
) sh-remember-variable-min
)
1865 (assoc var sh-shell-variables
)
1866 (push (cons var var
) sh-shell-variables
))
1871 (defun sh-quoted-p ()
1872 "Is point preceded by an odd number of backslashes?"
1873 (eq -
1 (%
(save-excursion (skip-chars-backward "\\\\")) 2)))
1875 ;; Indentation stuff.
1876 (defun sh-must-support-indent ()
1877 "*Signal an error if the shell type for this buffer is not supported.
1878 Also, the buffer must be in Shell-script mode."
1879 (unless sh-indent-supported-here
1880 (error "This buffer's shell does not support indentation through Emacs")))
1882 (defun sh-make-vars-local ()
1883 "Make the indentation variables local to this buffer.
1884 Normally they already are local. This command is provided in case
1885 variable `sh-make-vars-local' has been set to nil.
1887 To revert all these variables to the global values, use
1888 command `sh-reset-indent-vars-to-global-values'."
1890 (mapc 'make-local-variable sh-var-list
)
1891 (message "Indentation variables are now local."))
1893 (defun sh-reset-indent-vars-to-global-values ()
1894 "Reset local indentation variables to the global values.
1895 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1897 (mapc 'kill-local-variable sh-var-list
)
1898 (if sh-make-vars-local
1899 (mapcar 'make-local-variable sh-var-list
)))
1902 ;; Theoretically these are only needed in shell and derived modes.
1903 ;; However, the routines which use them are only called in those modes.
1904 (defconst sh-special-keywords
"then\\|do")
1906 (defun sh-help-string-for-variable (var)
1907 "Construct a string for `sh-read-variable' when changing variable VAR ."
1908 (let ((msg (documentation-property var
'variable-documentation
))
1910 (unless (memq var
'(sh-first-lines-indent sh-indent-comment
))
1913 You can enter a number (positive to increase indentation,
1914 negative to decrease indentation, zero for no change to indentation).
1916 Or, you can enter one of the following symbols which are relative to
1917 the value of variable `sh-basic-offset'
1918 which in this buffer is currently %s.
1922 (mapconcat (lambda (x)
1923 (nth (1- (length x
)) x
))
1924 sh-symbol-list
"\n\t"))))
1926 ;; The following shows the global not the local value!
1927 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1930 (defun sh-read-variable (var)
1931 "Read a new value for indentation variable VAR."
1932 (interactive "*variable? ") ;; to test
1933 (let ((minibuffer-help-form `(sh-help-string-for-variable
1936 (setq val
(read-from-minibuffer
1937 (format "New value for %s (press %s for help): "
1938 var
(single-key-description help-char
))
1939 (format "%s" (symbol-value var
))
1945 (defun sh-in-comment-or-string (start)
1946 "Return non-nil if START is in a comment or string."
1948 (let ((state (syntax-ppss start
)))
1949 (or (nth 3 state
) (nth 4 state
)))))
1951 (defun sh-goto-matching-if ()
1952 "Go to the matching if for a fi.
1953 This handles nested if..fi pairs."
1954 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1956 (goto-char found
))))
1959 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1960 ;; line whose indentation is being handled contain XXX;
1961 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
1963 (defun sh-handle-prev-if ()
1964 (list '(+ sh-indent-after-if
)))
1966 (defun sh-handle-this-else ()
1967 (if (sh-goto-matching-if)
1968 ;; (list "aligned to if")
1969 (list "aligned to if" '(+ sh-indent-for-else
))
1973 (defun sh-handle-prev-else ()
1974 (if (sh-goto-matching-if)
1975 (list '(+ sh-indent-after-if
))
1978 (defun sh-handle-this-fi ()
1979 (if (sh-goto-matching-if)
1980 (list "aligned to if" '(+ sh-indent-for-fi
))
1984 (defun sh-handle-prev-fi ()
1985 ;; Why do we have this rule? Because we must go back to the if
1986 ;; to get its indent. We may continue back from there.
1987 ;; We return nil because we don't have anything to add to result,
1988 ;; the side affect of setting align-point is all that matters.
1989 ;; we could return a comment (a string) but I can't think of a good one...
1990 (sh-goto-matching-if)
1993 (defun sh-handle-this-then ()
1994 (let ((p (sh-goto-matching-if)))
1996 (list '(+ sh-indent-for-then
))
1999 (defun sh-handle-prev-then ()
2000 (let ((p (sh-goto-matching-if)))
2002 (list '(+ sh-indent-after-if
))
2005 (defun sh-handle-prev-open ()
2007 (let ((x (sh-prev-stmt)))
2012 (looking-at "function\\b")
2013 (looking-at "\\s-*\\S-+\\s-*()")
2015 (list '(+ sh-indent-after-function
))
2016 (list '(+ sh-indent-after-open
)))
2019 (defun sh-handle-this-close ()
2020 (forward-char 1) ;; move over ")"
2021 (if (sh-safe-forward-sexp -
1)
2022 (list "aligned to opening paren")))
2024 (defun sh-goto-matching-case ()
2025 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2026 (if found
(goto-char found
))))
2028 (defun sh-handle-prev-case ()
2029 ;; This is typically called when point is on same line as a case
2030 ;; we shouldn't -- and can't find prev-case
2031 (if (looking-at ".*\\<case\\>")
2032 (list '(+ sh-indent-for-case-label
))
2033 (error "We don't seem to be on a line with a case"))) ;; debug
2035 (defun sh-handle-this-esac ()
2036 (if (sh-goto-matching-case)
2037 (list "aligned to matching case")))
2039 (defun sh-handle-prev-esac ()
2040 (if (sh-goto-matching-case)
2041 (list "matching case")))
2043 (defun sh-handle-after-case-label ()
2044 (if (sh-goto-matching-case)
2045 (list '(+ sh-indent-for-case-alt
))))
2047 (defun sh-handle-prev-case-alt-end ()
2048 (if (sh-goto-matching-case)
2049 (list '(+ sh-indent-for-case-label
))))
2051 (defun sh-safe-forward-sexp (&optional arg
)
2052 "Try and do a `forward-sexp', but do not error.
2053 Return new point if successful, nil if an error occurred."
2056 (forward-sexp (or arg
1))
2057 (point)) ;; return point if successful
2059 (sh-debug "oops!(1) %d" (point))
2060 nil
))) ;; return nil if fail
2062 (defun sh-goto-match-for-done ()
2063 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done
1)))
2065 (goto-char found
))))
2067 (defun sh-handle-this-done ()
2068 (if (sh-goto-match-for-done)
2069 (list "aligned to do stmt" '(+ sh-indent-for-done
))))
2071 (defun sh-handle-prev-done ()
2072 (if (sh-goto-match-for-done)
2073 (list "previous done")))
2075 (defun sh-handle-this-do ()
2076 (if (sh-goto-match-for-done)
2077 (list '(+ sh-indent-for-do
))))
2079 (defun sh-handle-prev-do ()
2082 (narrow-to-region (point) (line-beginning-position))
2083 (sh-goto-match-for-done))
2084 (sh-debug "match for done found on THIS line")
2085 (list '(+ sh-indent-after-loop-construct
)))
2086 ((sh-goto-match-for-done)
2087 (sh-debug "match for done found on PREV line")
2088 (list '(+ sh-indent-after-do
)))
2090 (message "match for done NOT found")
2094 (defun sh-find-prev-switch ()
2095 "Find the line for the switch keyword matching this line's case keyword."
2096 (re-search-backward "\\<switch\\>" nil t
))
2098 (defun sh-handle-this-rc-case ()
2099 (if (sh-find-prev-switch)
2100 (list '(+ sh-indent-after-switch
))
2101 ;; (list '(+ sh-indent-for-case-label))
2104 (defun sh-handle-prev-rc-case ()
2105 (list '(+ sh-indent-after-case
)))
2107 (defun sh-check-rule (n thing
)
2108 (let ((rule (nth n
(assoc thing sh-kw-alist
)))
2112 (setq val
(funcall rule
))
2113 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2114 n thing
(point) rule val
)))
2118 (defun sh-get-indent-info ()
2119 "Return indent-info for this line.
2120 This is a list. nil means the line is to be left as is.
2121 Otherwise it contains one or more of the following sublists:
2122 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2123 relative to. If present, this is always the first of the
2124 sublists. The indentation of the line in question is
2125 derived from the indentation of this point, possibly
2126 modified by subsequent sublists.
2128 \(- VAR\) Get the value of variable VAR and add to or subtract from
2129 the indentation calculated so far.
2130 \(= VAR\) Get the value of variable VAR and *replace* the
2131 indentation with its value. This only occurs for
2132 special variables such as `sh-indent-comment'.
2133 STRING This is ignored for the purposes of calculating
2134 indentation, it is printed in certain cases to help show
2135 what the indentation is based on."
2136 ;; See comments before `sh-kw'.
2138 (let ((have-result nil
)
2145 ;; Note: setting result to t means we are done and will return nil.
2146 ;;(This function never returns just t.)
2148 ((or (nth 3 (syntax-ppss (point)))
2149 (eq (get-text-property (point) 'face
) sh-heredoc-face
))
2150 ;; String continuation -- don't indent
2152 (setq have-result t
))
2153 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2155 (setq result t
) ;; return nil if 1st line!
2156 (setq result
(list '(= sh-indent-comment
)))
2157 ;; we still need to get previous line in case
2158 ;; sh-indent-comment is t (indent as normal)
2159 (setq align-point
(sh-prev-line nil
))
2160 (setq have-result nil
)
2165 ;; Continuation lines are handled specially
2166 (if (sh-this-is-a-continuation)
2171 (not (memq (char-before (- (point) 2)) '(?\s ?
\t))))
2172 ;; By convention, if the continuation \ is not
2173 ;; preceded by a SPC or a TAB it means that the line
2174 ;; is cut at a place where spaces cannot be freely
2175 ;; added/removed. I.e. do not indent the line.
2177 ;; We assume the line being continued is already
2178 ;; properly indented...
2179 ;; (setq prev-line-end (sh-prev-line))
2180 (setq align-point
(sh-prev-line nil
))
2181 (list '(+ sh-indent-for-continuation
))))
2182 (setq have-result t
))
2184 (skip-chars-forward " \t")
2185 (setq this-kw
(sh-get-kw)))
2187 ;; Handle "this" keyword: first word on the line we're
2188 ;; calculating indentation info for.
2190 (if (setq val
(sh-check-rule 1 this-kw
))
2192 (setq align-point
(point))
2194 "this - setting align-point to %d" align-point
)
2195 (setq result
(append result val
))
2196 (setq have-result t
)
2197 ;; set prev-line to continue processing remainder
2198 ;; of this line as a previous line
2199 (setq prev-line-end
(point))
2203 (setq prev-line-end
(sh-prev-line 'end
)))
2207 ;; We start off at beginning of this line.
2208 ;; Scan previous statements while this is <=
2209 ;; start of previous line.
2210 (goto-char prev-line-end
)
2212 (while (and x
(setq x
(sh-prev-thing)))
2213 (sh-debug "at %d x is: %s result is: %s" (point) x result
)
2216 (equal (get-text-property (1- (point)) 'syntax-table
)
2218 (sh-debug "Case label) here")
2219 (setq x
'case-label
)
2220 (if (setq val
(sh-check-rule 2 x
))
2222 (setq result
(append result val
))
2223 (setq align-point
(point))))
2226 ;; FIXME: This charset looks too much like a regexp. --Stef
2227 (skip-chars-forward "[a-z0-9]*?")
2229 ((string-match "[])}]" x
)
2230 (setq x
(sh-safe-forward-sexp -
1))
2233 (setq align-point
(point))
2234 (setq result
(append result
2235 (list "aligned to opening paren")))
2237 ((string-match "[[({]" x
)
2238 (sh-debug "Checking special thing: %s" x
)
2239 (if (setq val
(sh-check-rule 2 x
))
2240 (setq result
(append result val
)))
2242 (setq align-point
(point)))
2243 ((string-match "[\"'`]" x
)
2244 (sh-debug "Skipping back for %s" x
)
2246 (setq x
(sh-safe-forward-sexp -
1)))
2248 (sh-debug "Checking string %s at %s" x
(point))
2249 (if (setq val
(sh-check-rule 2 x
))
2250 ;; (or (eq t (car val))
2251 ;; (eq t (car (car val))))
2252 (setq result
(append result val
)))
2253 ;; not sure about this test Wed Jan 27 23:48:35 1999
2254 (setq align-point
(point))
2258 (error "Don't know what to do with %s" x
))
2261 (sh-debug "result is %s" result
)
2263 (sh-debug "No prev line!")
2264 (sh-debug "result: %s align-point: %s" result align-point
)
2268 ;; was: (setq result (append result (list (list t align-point))))
2269 (setq result
(append (list (list t align-point
)) result
))
2271 (sh-debug "result is now: %s" result
)
2274 (setq result
(list (if prev-line-end
2275 (list t prev-line-end
)
2276 (list '= 'sh-first-lines-indent
)))))
2280 (sh-debug "result is: %s" result
)
2286 (defun sh-get-indent-var-for-line (&optional info
)
2287 "Return the variable controlling indentation for this line.
2288 If there is not [just] one such variable, return a string
2289 indicating the problem.
2290 If INFO is supplied it is used, else it is calculated."
2296 (setq info
(sh-get-indent-info)))
2298 (setq result
"this line to be left as is")
2299 (while (and info
(null result
))
2300 (setq elt
(car info
))
2306 (error "sh-get-indent-var-for-line invalid elt: %s" elt
))
2310 ((symbolp (setq sym
(nth 1 elt
)))
2311 ;; A bit of a kludge - when we see the sh-indent-comment
2312 ;; ignore other variables. Otherwise it is tricky to
2313 ;; "learn" the comment indentation.
2314 (if (eq var
'sh-indent-comment
)
2318 "this line is controlled by more than 1 variable.")
2321 (error "sh-get-indent-var-for-line invalid list elt: %s" elt
)))
2322 (setq info
(cdr info
))
2327 (setq result reason
))
2329 ;; e.g. just had (t POS)
2330 (setq result
"line has default indentation"))
2335 ;; Finding the previous line isn't trivial.
2336 ;; We must *always* go back one more and see if that is a continuation
2337 ;; line -- it is the PREVIOUS line which is continued, not the one
2339 ;; Also, we want to treat a whole "here document" as one big line,
2340 ;; because we may want to a align to the beginning of it.
2343 ;; - go back to previous non-empty line
2344 ;; - if this is in a here-document, go to the beginning of it
2345 ;; - while previous line is continued, go back one line
2346 (defun sh-prev-line (&optional end
)
2347 "Back to end of previous non-comment non-empty line.
2348 Go to beginning of logical line unless END is non-nil, in which case
2349 we go to the end of the previous line and do not check for continuations."
2352 (forward-comment (- (point-max)))
2353 (unless end
(beginning-of-line))
2354 (when (and (not (bobp))
2355 (equal (get-text-property (1- (point)) 'face
)
2357 (let ((p1 (previous-single-property-change (1- (point)) 'face
)))
2362 (beginning-of-line)))))
2364 ;; we must check previous lines to see if they are continuation lines
2365 ;; if so, we must return position of first of them
2366 (while (and (sh-this-is-a-continuation)
2367 (>= 0 (forward-line -
1))))
2369 (skip-chars-forward " \t"))
2373 (defun sh-prev-stmt ()
2374 "Return the address of the previous stmt or nil."
2375 ;; This is used when we are trying to find a matching keyword.
2376 ;; Searching backward for the keyword would certainly be quicker, but
2377 ;; it is hard to remove "false matches" -- such as if the keyword
2378 ;; appears in a string or quote. This way is slower, but (I think) safer.
2385 (skip-chars-backward " \t;|&({[")
2386 (while (and (not found
)
2389 ;; Do a backward-sexp if possible, else backup bit by bit...
2390 (if (sh-safe-forward-sexp -
1)
2392 (if (looking-at sh-special-keywords
)
2397 ;; backward-sexp failed
2398 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2401 (let ((back (sh-prev-line nil
)))
2404 (setq going nil
)))))
2406 (skip-chars-backward " \t")
2407 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2408 (eq (char-before) ?\
;)
2409 (looking-at "\\s-*[|&]"))
2410 (setq found
(point)))))
2415 (skip-chars-forward " \t|&({[")
2416 (setq found
(point))))
2417 (if (>= (point) start
)
2419 (debug "We didn't move!")
2422 (sh-debug "Did not find prev stmt.")))
2426 (defun sh-get-word ()
2427 "Get a shell word skipping whitespace from point."
2429 (skip-chars-forward "\t ")
2430 (let ((start (point)))
2432 (if (looking-at "[\"'`]")
2433 (sh-safe-forward-sexp)
2434 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2435 (> (skip-chars-forward "-_$[:alnum:]") 0)
2437 (buffer-substring start
(point))
2440 (defun sh-prev-thing ()
2441 "Return the previous thing this logical line."
2442 ;; This is called when `sh-get-indent-info' is working backwards on
2443 ;; the previous line(s) finding what keywords may be relevant for
2444 ;; indenting. It moves over sexps if possible, and will stop
2445 ;; on a ; and at the beginning of a line if it is not a continuation
2448 ;; Added a kludge for ";;"
2449 ;; Possible return values:
2451 ;; a string - possibly a keyword
2455 (let ((start (point))
2456 (min-point (if (sh-this-is-a-continuation)
2458 (line-beginning-position))))
2459 (skip-chars-backward " \t;" min-point
)
2460 (if (looking-at "\\s-*;[;&]")
2461 ;; (message "Found ;; !")
2463 (skip-chars-backward "^)}];\"'`({[" min-point
)
2464 (let ((c (if (> (point) min-point
) (char-before))))
2465 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2466 (point) c start min-point
)
2467 (if (not (memq c
'(?
\n nil ?\
;)))
2468 ;; c -- return a string
2470 ;; Return the leading keyword of the "command" we supposedly
2471 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
2472 ;; `then' that precedes the actual command), so check whether
2473 ;; we're looking at such a keyword and if so, move back forward.
2474 (let ((boundary (point))
2478 ;; Skip forward over white space newline and \ at eol.
2479 (skip-chars-forward " \t\n\\\\" start
)
2480 (if (>= (point) start
)
2482 (sh-debug "point: %d >= start: %d" (point) start
)
2484 (if next
(setq boundary next
))
2485 (sh-debug "Now at %d start=%d" (point) start
)
2486 (setq kwd
(sh-get-word))
2487 (if (member kwd
(sh-feature sh-leading-keywords
))
2492 (goto-char boundary
)
2496 (defun sh-this-is-a-continuation ()
2497 "Return non-nil if current line is a continuation of previous line."
2499 (and (zerop (forward-line -
1))
2500 (looking-at ".*\\\\$")
2501 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2504 (defun sh-get-kw (&optional where and-move
)
2505 "Return first word of line from WHERE.
2506 If AND-MOVE is non-nil then move to end of word."
2507 (let ((start (point)))
2511 (buffer-substring (point)
2512 (progn (skip-chars-forward "^ \t\n;&|")(point)))
2514 (goto-char start
)))))
2516 (defun sh-find-prev-matching (open close
&optional depth
)
2517 "Find a matching token for a set of opening and closing keywords.
2518 This takes into account that there may be nested open..close pairings.
2519 OPEN and CLOSE are regexps denoting the tokens to be matched.
2520 Optional parameter DEPTH (usually 1) says how many to look for."
2521 (let ((parse-sexp-ignore-comments t
)
2523 (setq depth
(or depth
1))
2529 (setq prev
(sh-prev-stmt)))
2532 (if (looking-at "\\\\\n")
2535 (skip-chars-forward " \t")))
2538 (setq depth
(1- depth
))
2539 (sh-debug "found open at %d - depth = %d" (point) depth
))
2541 (setq depth
(1+ depth
))
2542 (sh-debug "found close - depth = %d" depth
))
2552 (defun sh-var-value (var &optional ignore-error
)
2553 "Return the value of variable VAR, interpreting symbols.
2554 It can also return t or nil.
2555 If an invalid value is found, throw an error unless Optional argument
2556 IGNORE-ERROR is non-nil."
2557 (let ((val (symbol-value var
)))
2568 (- sh-basic-offset
))
2570 (* 2 sh-basic-offset
))
2572 (* 2 (- sh-basic-offset
)))
2574 (/ sh-basic-offset
2))
2576 (/ (- sh-basic-offset
) 2))
2580 (message "Don't know how to handle %s's value of %s" var val
)
2582 (error "Don't know how to handle %s's value of %s" var val
))
2585 (defun sh-set-var-value (var value
&optional no-symbol
)
2586 "Set variable VAR to VALUE.
2587 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2588 can be represented by a symbol then do so."
2592 ((= value sh-basic-offset
)
2594 ((= value
(- sh-basic-offset
))
2596 ((eq value
(* 2 sh-basic-offset
))
2598 ((eq value
(* 2 (- sh-basic-offset
)))
2600 ((eq value
(/ sh-basic-offset
2))
2602 ((eq value
(/ (- sh-basic-offset
) 2))
2609 (defun sh-calculate-indent (&optional info
)
2610 "Return the indentation for the current line.
2611 If INFO is supplied it is used, else it is calculated from current line."
2616 (setq info
(sh-get-indent-info)))
2619 (sh-debug "info: %s ofs=%s" info ofs
)
2620 (setq elt
(car info
))
2622 ((stringp elt
)) ;; do nothing?
2624 (setq a
(car (car info
)))
2625 (setq b
(nth 1 (car info
)))
2630 (setq val
(current-indentation)))
2631 (setq base-value val
))
2633 (setq val
(sh-var-value b
))
2639 ;; set info to nil so we stop immediately
2640 (setq base-value nil ofs nil info nil
))
2641 ((eq val t
) (setq ofs
0)) ;; indent as normal line
2643 ;; The following assume the (t POS) come first!
2644 (setq ofs val base-value
0)
2645 (setq info nil
)))) ;; ? stop now
2646 ((eq a
'+) (setq ofs
(+ ofs val
)))
2647 ((eq a
'-
) (setq ofs
(- ofs val
)))
2649 (error "sh-calculate-indent invalid a a=%s b=%s" a b
))))
2651 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b
))))
2653 (error "sh-calculate-indent invalid elt %s" elt
)))
2654 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2655 a b val base-value ofs
)
2656 (setq info
(cdr info
)))
2658 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs
)
2661 ((or (null base-value
)(null ofs
))
2663 ((and (numberp base-value
)(numberp ofs
))
2664 (sh-debug "base (%d) + ofs (%d) = %d"
2665 base-value ofs
(+ base-value ofs
))
2666 (+ base-value ofs
)) ;; return value
2668 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2673 (defun sh-indent-line ()
2674 "Indent the current line."
2676 (let ((indent (sh-calculate-indent))
2677 (pos (- (point-max) (point))))
2680 (skip-chars-forward " \t")
2681 (indent-line-to indent
)
2682 ;; If initial point was within line's indentation,
2683 ;; position after the indentation. Else stay at same point in text.
2684 (if (> (- (point-max) pos
) (point))
2685 (goto-char (- (point-max) pos
))))))
2688 (defun sh-blink (blinkpos &optional msg
)
2689 "Move cursor momentarily to BLINKPOS and display MSG."
2690 ;; We can get here without it being a number on first line
2691 (if (numberp blinkpos
)
2693 (goto-char blinkpos
)
2694 (if msg
(message "%s" msg
) (message nil
))
2695 (sit-for blink-matching-delay
))
2696 (if msg
(message "%s" msg
) (message nil
))))
2698 (defun sh-show-indent (arg)
2699 "Show the how the current line would be indented.
2700 This tells you which variable, if any, controls the indentation of
2702 If optional arg ARG is non-null (called interactively with a prefix),
2703 a pop up window describes this variable.
2704 If variable `sh-blink' is non-nil then momentarily go to the line
2705 we are indenting relative to, if applicable."
2707 (sh-must-support-indent)
2708 (let* ((info (sh-get-indent-info))
2709 (var (sh-get-indent-var-for-line info
))
2710 (curr-indent (current-indentation))
2713 (message "%s" (setq msg var
))
2714 (setq val
(sh-calculate-indent info
))
2716 (if (eq curr-indent val
)
2717 (setq msg
(format "%s is %s" var
(symbol-value var
)))
2720 (format "%s (%s) would change indent from %d to: %d"
2721 var
(symbol-value var
) curr-indent val
)
2722 (format "%s (%s) would leave line as is"
2723 var
(symbol-value var
)))
2726 (describe-variable var
)))
2728 (let ((info (sh-get-indent-info)))
2729 (if (and info
(listp (car info
))
2730 (eq (car (car info
)) t
))
2731 (sh-blink (nth 1 (car info
)) msg
)
2732 (message "%s" msg
)))
2736 (defun sh-set-indent ()
2737 "Set the indentation for the current line.
2738 If the current line is controlled by an indentation variable, prompt
2739 for a new value for it."
2741 (sh-must-support-indent)
2742 (let* ((info (sh-get-indent-info))
2743 (var (sh-get-indent-var-for-line info
))
2744 val old-val indent-val
)
2746 (message "Cannot set indent - %s" var
)
2747 (setq old-val
(symbol-value var
))
2748 (setq val
(sh-read-variable var
))
2752 (setq indent-val
(sh-calculate-indent info
))
2754 (message "Variable: %s Value: %s would indent to: %d"
2755 var
(symbol-value var
) indent-val
)
2756 (message "Variable: %s Value: %s would leave line as is."
2757 var
(symbol-value var
)))
2758 ;; I'm not sure about this, indenting it now?
2759 ;; No. Because it would give the impression that an undo would
2760 ;; restore thing, but the value has been altered.
2765 (message "Bad value for %s, restoring to previous value %s"
2772 (defun sh-learn-line-indent (arg)
2773 "Learn how to indent a line as it currently is indented.
2775 If there is an indentation variable which controls this line's indentation,
2776 then set it to a value which would indent the line the way it
2779 If the value can be represented by one of the symbols then do so
2780 unless optional argument ARG (the prefix when interactive) is non-nil."
2782 (sh-must-support-indent)
2783 ;; I'm not sure if we show allow learning on an empty line.
2784 ;; Though it might occasionally be useful I think it usually
2785 ;; would just be confusing.
2788 (looking-at "\\s-*$"))
2789 (message "sh-learn-line-indent ignores empty lines.")
2790 (let* ((info (sh-get-indent-info))
2791 (var (sh-get-indent-var-for-line info
))
2792 ival sval diff new-val
2794 (curr-indent (current-indentation)))
2797 (message "Cannot learn line - %s" var
))
2798 ((eq var
'sh-indent-comment
)
2799 ;; This is arbitrary...
2800 ;; - if curr-indent is 0, set to curr-indent
2801 ;; - else if it has the indentation of a "normal" line,
2803 ;; - else set to curr-indent.
2804 (setq sh-indent-comment
2805 (if (= curr-indent
0)
2807 (let* ((sh-indent-comment t
)
2808 (val2 (sh-calculate-indent info
)))
2809 (if (= val2 curr-indent
)
2812 (message "%s set to %s" var
(symbol-value var
))
2814 ((numberp (setq sval
(sh-var-value var
)))
2815 (setq ival
(sh-calculate-indent info
))
2816 (setq diff
(- curr-indent ival
))
2818 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2819 curr-indent ival diff var sval
)
2820 (setq new-val
(+ sval diff
))
2821 ;;; I commented out this because someone might want to replace
2822 ;;; a value of `+' with the current value of sh-basic-offset
2825 ;;; (message "No change needed!")
2826 (sh-set-var-value var new-val no-symbol
)
2827 (message "%s set to %s" var
(symbol-value var
))
2831 (message "Cannot change %s" var
))))))
2835 (defun sh-mark-init (buffer)
2836 "Initialize a BUFFER to be used by `sh-mark-line'."
2837 (with-current-buffer (get-buffer-create buffer
)
2842 (defun sh-mark-line (message point buffer
&optional add-linenum occur-point
)
2843 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2844 Buffer BUFFER is in `occur-mode'.
2845 If ADD-LINENUM is non-nil the message is preceded by the line number.
2846 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2847 so that `occur-next' and `occur-prev' will work."
2848 (let ((m1 (make-marker))
2852 (set-marker m1 point
(current-buffer))
2854 (setq line
(format "%d: " (1+ (count-lines 1 point
))))))
2856 (if (get-buffer buffer
)
2857 (set-buffer (get-buffer buffer
))
2858 (set-buffer (get-buffer-create buffer
))
2861 (goto-char (point-max))
2862 (setq start
(point))
2865 (setq occur-point
(point)))
2868 (add-text-properties
2870 '(mouse-face highlight
2871 help-echo
"mouse-2: go to the line where I learned this")))
2875 (put-text-property start
(point) 'occur-target m1
)
2877 (put-text-property start occur-point
2884 ;; Is this really worth having?
2885 (defvar sh-learned-buffer-hook nil
2886 "*An abnormal hook, called with an alist of learned variables.")
2887 ;; Example of how to use sh-learned-buffer-hook
2889 ;; (defun what-i-learned (list)
2891 ;; (with-current-buffer "*scratch*"
2892 ;; (goto-char (point-max))
2893 ;; (insert "(setq\n")
2895 ;; (insert (format " %s %s \n"
2896 ;; (nth 0 (car p)) (nth 1 (car p))))
2897 ;; (setq p (cdr p)))
2901 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2904 ;; Originally this was sh-learn-region-indent (beg end)
2905 ;; However, in practice this was awkward so I changed it to
2906 ;; use the whole buffer. Use narrowing if needbe.
2907 (defun sh-learn-buffer-indent (&optional arg
)
2908 "Learn how to indent the buffer the way it currently is.
2910 Output in buffer \"*indent*\" shows any lines which have conflicting
2911 values of a variable, and the final value of all variables learned.
2912 When called interactively, pop to this buffer automatically if
2913 there are any discrepancies.
2915 If no prefix ARG is given, then variables are set to numbers.
2916 If a prefix arg is given, then variables are set to symbols when
2917 applicable -- e.g. to symbol `+' if the value is that of the
2919 If a positive numerical prefix is given, then `sh-basic-offset'
2920 is set to the prefix's numerical value.
2921 Otherwise, sh-basic-offset may or may not be changed, according
2922 to the value of variable `sh-learn-basic-offset'.
2924 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2925 function completes. The function is abnormal because it is called
2926 with an alist of variables learned. This feature may be changed or
2927 removed in the future.
2929 This command can often take a long time to run."
2931 (sh-must-support-indent)
2933 (goto-char (point-min))
2934 (let ((learned-var-list nil
)
2935 (out-buffer "*indent*")
2941 (comment-col nil
) ;; number if all same, t if seen diff values
2942 (comments-always-default t
) ;; nil if we see one not default
2944 (specified-basic-offset (and arg
(numberp arg
)
2948 (setq vec
(make-vector max
0))
2949 (sh-mark-init out-buffer
)
2951 (if specified-basic-offset
2953 (setq sh-basic-offset arg
)
2955 (format "Using specified sh-basic-offset of %d"
2958 (format "Initial value of sh-basic-offset: %s"
2961 (while (< (point) (point-max))
2962 (setq linenum
(1+ linenum
))
2963 ;; (if (zerop (% linenum 10))
2964 (message "line %d" linenum
)
2966 (unless (looking-at "\\s-*$") ;; ignore empty lines!
2967 (let* ((sh-indent-comment t
) ;; info must return default indent
2968 (info (sh-get-indent-info))
2969 (var (sh-get-indent-var-for-line info
))
2970 sval ival diff new-val
2971 (curr-indent (current-indentation)))
2977 ((numberp (setq sval
(sh-var-value var
'no-error
)))
2978 ;; the numberp excludes comments since sval will be t.
2979 (setq ival
(sh-calculate-indent))
2980 (setq diff
(- curr-indent ival
))
2981 (setq new-val
(+ sval diff
))
2982 (sh-set-var-value var new-val
'no-symbol
)
2983 (unless (looking-at "\\s-*#") ;; don't learn from comments
2984 (if (setq previous-set-info
(assoc var learned-var-list
))
2986 ;; it was already there, is it same value ?
2987 (unless (eq (symbol-value var
)
2988 (nth 1 previous-set-info
))
2990 (format "Variable %s was set to %s"
2991 var
(symbol-value var
))
2992 (point) out-buffer t t
)
2994 (format " but was previously set to %s"
2995 (nth 1 previous-set-info
))
2996 (nth 2 previous-set-info
) out-buffer t
)
2997 (setq num-diffs
(1+ num-diffs
))
2998 ;; (delete previous-set-info learned-var-list)
2999 (setcdr previous-set-info
3000 (list (symbol-value var
) (point)))
3003 (setq learned-var-list
3004 (append (list (list var
(symbol-value var
)
3007 (if (numberp new-val
)
3010 "This line's indent value: %d" new-val
)
3012 (setq new-val
(- new-val
)))
3014 (aset vec new-val
(1+ (aref vec new-val
))))))
3016 ((eq var
'sh-indent-comment
)
3017 (unless (= curr-indent
(sh-calculate-indent info
))
3018 ;; this is not the default indentation
3019 (setq comments-always-default nil
)
3020 (if comment-col
;; then we have see one before
3021 (or (eq comment-col curr-indent
)
3022 (setq comment-col t
)) ;; seen a different one
3023 (setq comment-col curr-indent
))
3026 (sh-debug "Cannot learn this line!!!")
3029 "at %s learned-var-list is %s" (point) learned-var-list
)
3036 "comment-col = %s comments-always-default = %s"
3037 comment-col comments-always-default
))
3039 (sh-mark-line msg nil out-buffer
)))
3042 (setq msg
"\nComments are all in 1st column.\n"))
3043 (comments-always-default
3044 (setq msg
"\nComments follow default indentation.\n")
3045 (setq comment-col t
))
3046 ((numberp comment-col
)
3047 (setq msg
(format "\nComments are in col %d." comment-col
)))
3049 (setq msg
"\nComments seem to be mixed, leaving them as is.\n")
3050 (setq comment-col nil
)
3053 (sh-mark-line msg nil out-buffer
)
3055 (sh-mark-line initial-msg nil out-buffer t t
)
3057 (setq suggested
(sh-guess-basic-offset vec
))
3059 (if (and suggested
(not specified-basic-offset
))
3062 ;; t => set it if we have a single value as a number
3063 ((and (eq sh-learn-basic-offset t
) (numberp suggested
))
3065 ;; other non-nil => set it if only one value was found
3066 (sh-learn-basic-offset
3067 (if (numberp suggested
)
3069 (if (= (length suggested
) 1)
3075 (setq learned-var-list
3076 (append (list (list 'sh-basic-offset
3077 (setq sh-basic-offset new-value
)
3080 ;; Not sure if we need to put this line in, since
3081 ;; it will appear in the "Learned variable settings".
3083 (format "Changed sh-basic-offset to: %d" sh-basic-offset
)
3086 (if (listp suggested
)
3087 (format "Possible value(s) for sh-basic-offset: %s"
3088 (mapconcat 'int-to-string suggested
" "))
3089 (format "Suggested sh-basic-offset: %d" suggested
))
3093 (setq learned-var-list
3094 (append (list (list 'sh-indent-comment comment-col
(point-max)))
3096 (setq sh-indent-comment comment-col
)
3097 (let ((name (buffer-name)))
3098 (sh-mark-line "\nLearned variable settings:" nil out-buffer
)
3100 ;; Set learned variables to symbolic rather than numeric
3101 ;; values where possible.
3102 (dolist (learned-var (reverse learned-var-list
))
3103 (let ((var (car learned-var
))
3104 (val (nth 1 learned-var
)))
3105 (when (and (not (eq var
'sh-basic-offset
))
3107 (sh-set-var-value var val
)))))
3108 (dolist (learned-var (reverse learned-var-list
))
3109 (let ((var (car learned-var
)))
3110 (sh-mark-line (format " %s %s" var
(symbol-value var
))
3111 (nth 2 learned-var
) out-buffer
)))
3112 (with-current-buffer out-buffer
3113 (goto-char (point-min))
3115 (format "Indentation values for buffer %s.\n" name
)
3116 (format "%d indentation variable%s different values%s\n\n"
3120 (if (zerop num-diffs
)
3123 ;; Are abnormal hooks considered bad form?
3124 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list
)
3125 (and (called-interactively-p 'any
)
3126 (or sh-popup-occur-buffer
(> num-diffs
0))
3127 (pop-to-buffer out-buffer
)))))
3129 (defun sh-guess-basic-offset (vec)
3130 "See if we can determine a reasonable value for `sh-basic-offset'.
3131 This is experimental, heuristic and arbitrary!
3132 Argument VEC is a vector of information collected by
3133 `sh-learn-buffer-indent'.
3135 number - there appears to be a good single value
3136 list of numbers - no obvious one, here is a list of one or more
3138 nil - we couldn't find a reasonable one."
3139 (let* ((max (1- (length vec
)))
3141 (totals (make-vector max
0)))
3143 (aset totals i
(+ (aref totals i
) (* 4 (aref vec i
))))
3145 (aset totals i
(+ (aref totals i
) (aref vec
(/ i
2)))))
3147 (aset totals i
(+ (aref totals i
) (aref vec
(* i
2)))))
3155 (if (/= (aref totals i
) 0)
3156 (setq x
(append x
(list (cons i
(aref totals i
))))))
3159 (setq x
(sort x
(lambda (a b
) (> (cdr a
) (cdr b
)))))
3160 (setq tot
(apply '+ (append totals nil
)))
3161 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3165 (message "no values!")) ;; we return nil
3167 (message "only value is %d" (car (car x
)))
3168 (setq result
(car (car x
)))) ;; return single value
3169 ((> (cdr (car x
)) (/ tot
2))
3171 (message "basic-offset is probably %d" (car (car x
)))
3172 (setq result
(car (car x
)))) ;; again, return a single value
3173 ((>= (cdr (car x
)) (* 2 (cdr (car (cdr x
)))))
3174 ;; 1st is >= 2 * 2nd
3175 (message "basic-offset could be %d" (car (car x
)))
3176 (setq result
(car (car x
))))
3177 ((>= (+ (cdr (car x
))(cdr (car (cdr x
)))) (/ tot
2))
3178 ;; 1st & 2nd together >= 50% - return a list
3179 (setq p x sum
0 result nil
)
3181 (<= (setq sum
(+ sum
(cdr (car p
)))) (/ tot
2)))
3182 (setq result
(append result
(list (car (car p
)))))
3184 (message "Possible choices for sh-basic-offset: %s"
3185 (mapconcat 'int-to-string result
" ")))
3187 (message "No obvious value for sh-basic-offset. Perhaps %d"
3189 ;; result is nil here
3193 ;; ========================================================================
3195 ;; Styles -- a quick and dirty way of saving the indentation settings.
3197 (defvar sh-styles-alist nil
3198 "A list of all known shell indentation styles.")
3200 (defun sh-name-style (name &optional confirm-overwrite
)
3201 "Name the current indentation settings as a style called NAME.
3202 If this name exists, the command will prompt whether it should be
3204 - - it was called interactively with a prefix argument, or
3205 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3206 ;; (interactive "sName for this style: ")
3209 (read-from-minibuffer "Name for this style? " )
3210 (not current-prefix-arg
)))
3211 (let ((slist (cons name
3212 (mapcar (lambda (var) (cons var
(symbol-value var
)))
3214 (style (assoc name sh-styles-alist
)))
3216 (if (and confirm-overwrite
3217 (not (y-or-n-p "This style exists. Overwrite it? ")))
3218 (message "Not changing style %s" name
)
3219 (message "Updating style %s" name
)
3220 (setcdr style
(cdr slist
)))
3221 (message "Creating new style %s" name
)
3222 (push slist sh-styles-alist
))))
3224 (defun sh-load-style (name)
3225 "Set shell indentation values for this buffer from those in style NAME."
3226 (interactive (list (completing-read
3227 "Which style to use for this buffer? "
3228 sh-styles-alist nil t
)))
3229 (let ((sl (assoc name sh-styles-alist
)))
3231 (error "sh-load-style - style %s not known" name
)
3232 (dolist (var (cdr sl
))
3233 (set (car var
) (cdr var
))))))
3235 (defun sh-save-styles-to-buffer (buff)
3236 "Save all current styles in elisp to buffer BUFF.
3237 This is always added to the end of the buffer."
3239 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3240 (with-current-buffer (get-buffer-create buff
)
3241 (goto-char (point-max))
3243 (pp `(setq sh-styles-alist
',sh-styles-alist
) (current-buffer))))
3247 ;; statement syntax-commands for various shells
3249 ;; You are welcome to add the syntax or even completely new statements as
3250 ;; appropriate for your favorite shell.
3252 (defconst sh-non-closing-paren
3253 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3254 ;; that inherits this property, which then confuses the indentation.
3255 (propertize ")" 'syntax-table sh-st-punc
'rear-nonsticky t
))
3257 (define-skeleton sh-case
3258 "Insert a case/switch statement. See `sh-feature'."
3260 "switch( " str
" )" \n
3261 > "case " (read-string "pattern: ") ?
: \n
3264 ( "other pattern, %s: "
3274 > "switch( " str
" ) {" \n
3275 > "case " (read-string "pattern: ") \n
3277 ( "other pattern, %s: "
3285 > "case " str
" in" \n
3287 > str sh-non-closing-paren
\n
3290 > "*" sh-non-closing-paren
\n
3295 (define-skeleton sh-for
3296 "Insert a for loop. See `sh-feature'."
3310 (sh "Index variable: "
3311 > "for " str
" in " _
"; do" \n
3312 > _ | ?$
& (sh-remember-variable str
) \n
3317 (define-skeleton sh-indexed-loop
3318 "Insert an indexed loop from 1 to n. See `sh-feature'."
3319 (bash sh-modify posix
)
3320 (csh "Index variable: "
3322 "while( $" str
" <= " (read-string "upper limit: ") " )" \n
3328 (ksh88 "Index variable: "
3329 > "integer " str
"=0" \n
3330 > "while (( ( " str
" += 1 ) <= "
3331 (read-string "upper limit: ")
3333 > _ ?$
(sh-remember-variable str
) > \n
3335 (posix "Index variable: "
3337 "while [ $" str
" -le "
3338 (read-string "upper limit: ")
3341 str ?
= (sh-add (sh-remember-variable str
) 1) \n
3343 (rc "Index variable: "
3344 > "for( " str
" in" " `{awk 'BEGIN { for( i=1; i<="
3345 (read-string "upper limit: ")
3346 "; i++ ) print i }'`}) {" \n
3347 > _ ?$
(sh-remember-variable str
) \n
3349 (sh "Index variable: "
3350 > "for " str
" in `awk 'BEGIN { for( i=1; i<="
3351 (read-string "upper limit: ")
3352 "; i++ ) print i }'`; do" \n
3353 > _ ?$
(sh-remember-variable str
) \n
3357 (defun sh-shell-initialize-variables ()
3358 "Scan the buffer for variable assignments.
3359 Add these variables to `sh-shell-variables'."
3360 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3362 (goto-char (point-min))
3363 (setq sh-shell-variables-initialized t
)
3364 (while (search-forward "=" nil t
)
3366 (message "Scanning buffer `%s' for variable assignments...done"
3369 (defvar sh-add-buffer
)
3371 (defun sh-add-completer (string predicate code
)
3372 "Do completion using `sh-shell-variables', but initialize it first.
3373 This function is designed for use as the \"completion table\",
3374 so it takes three arguments:
3375 STRING, the current buffer contents;
3376 PREDICATE, the predicate for filtering possible matches;
3377 CODE, which says what kind of things to do.
3378 CODE can be nil, t or `lambda'.
3379 nil means to return the best completion of STRING, or nil if there is none.
3380 t means to return a list of all possible completions of STRING.
3381 `lambda' means to return t if STRING is a valid completion as it stands."
3383 (with-current-buffer sh-add-buffer
3384 (or sh-shell-variables-initialized
3385 (sh-shell-initialize-variables))
3386 (nconc (mapcar (lambda (var)
3387 (substring var
0 (string-match "=" var
)))
3388 process-environment
)
3389 sh-shell-variables
))))
3390 (complete-with-action code vars string predicate
)))
3392 (defun sh-add (var delta
)
3393 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3395 (let ((sh-add-buffer (current-buffer)))
3396 (list (completing-read "Variable: " 'sh-add-completer
)
3397 (prefix-numeric-value current-prefix-arg
))))
3398 (insert (sh-feature '((bash .
"$(( ")
3404 (sh-remember-variable var
)
3405 (if (< delta
0) " - " " + ")
3406 (number-to-string (abs delta
))
3407 (sh-feature '((bash .
" ))")
3416 (define-skeleton sh-function
3417 "Insert a function definition. See `sh-feature'."
3418 (bash sh-modify ksh88
3421 "function " str
" {" \n
3433 (define-skeleton sh-if
3434 "Insert an if statement. See `sh-feature'."
3436 "if( " str
" ) then" \n
3438 ( "other condition, %s: "
3439 < "else if( " str
" ) then" \n
3446 > "if { " str
" } {" \n
3448 ( "other condition, %s: "
3449 "} { " str
" } {" > \n
3456 > "if( " str
" ) {" \n
3458 ( "other condition, %s: "
3459 "} else if( " str
" ) {" > \n
3466 '(setq input
(sh-feature sh-test
))
3467 > "if " str
"; then" \n
3469 ( "other condition, %s: "
3470 > "elif " str
"; then" > \n
3479 (define-skeleton sh-repeat
3480 "Insert a repeat loop definition. See `sh-feature'."
3486 > "repeat " str
"; do" > \n
3490 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3494 (define-skeleton sh-select
3495 "Insert a select statement. See `sh-feature'."
3496 (ksh88 "Index variable: "
3497 > "select " str
" in " _
"; do" \n
3500 (bash sh-append ksh88
))
3501 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3505 (define-skeleton sh-tmp-file
3506 "Insert code to setup temporary file handling. See `sh-feature'."
3507 (bash sh-append ksh88
)
3508 (csh (file-name-nondirectory (buffer-file-name))
3509 "set tmp = `mktemp -t " str
".XXXXXX`" \n
3511 (and (goto-char (point-max))
3515 "rm $tmp* >&/dev/null" > \n)
3516 (es (file-name-nondirectory (buffer-file-name))
3517 > "local( signals = $signals sighup sigint;" \n
3518 > "tmp = `{ mktemp -t " str
".XXXXXX } ) {" \n
3520 > "rm $tmp^* >[2]/dev/null" \n
3528 (rc (file-name-nondirectory (buffer-file-name))
3529 > "tmp = `{ mktemp -t " str
".XXXXXX }" \n
3530 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
3531 (sh (file-name-nondirectory (buffer-file-name))
3532 > "TMP=`mktemp -t " str
".XXXXXX`" \n
3533 "trap \"rm $TMP* 2>/dev/null\" " ?
0 \n))
3537 (define-skeleton sh-until
3538 "Insert an until loop. See `sh-feature'."
3540 '(setq input
(sh-feature sh-test
))
3541 > "until " str
"; do" \n
3544 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3548 (define-skeleton sh-while
3549 "Insert a while loop. See `sh-feature'."
3565 '(setq input
(sh-feature sh-test
))
3566 > "while " str
"; do" \n
3572 (define-skeleton sh-while-getopts
3573 "Insert a while getopts loop. See `sh-feature'.
3574 Prompts for an options string which consists of letters for each recognized
3575 option followed by a colon `:' if the option accepts an argument."
3580 > "switch( \"$1\" )" \n
3581 '(setq input
'("- x" .
2))
3584 < "case " '(eval str
)
3585 '(if (string-match " +" str
)
3586 (setq v1
(substring str
(match-end 0))
3587 str
(substring str
0 (match-beginning 0)))
3590 > "set " v1
& " = $2" | -
4 & _
\n
3591 (if v1
"shift") & \n
3606 18 "$(basename $0)")
3608 > "while getopts :" str
" OPT; do" \n
3610 '(setq v1
(append (vconcat str
) nil
))
3611 ( (prog1 (if v1
(char-to-string (car v1
)))
3612 (if (eq (nth 1 v1
) ?
:)
3613 (setq v1
(nthcdr 2 v1
)
3617 > str
"|+" str sh-non-closing-paren
\n
3620 > "*" sh-non-closing-paren
\n
3621 > "echo" " \"usage: " "`basename $0`"
3622 " [+-" '(setq v1
(point)) str
3624 (while (search-backward ":" v1 t
)
3625 (replace-match " ARG] [+-" t t
)))
3626 (if (eq (preceding-char) ?-
) -
5)
3627 (if (and (sequencep v1
) (length v1
)) "] " "} ")
3633 "shift " (sh-add "OPTIND" -
1) \n
3638 (defun sh-assignment (arg)
3639 "Remember preceding identifier for future completion and do self-insert."
3641 (self-insert-command arg
)
3643 (sh-remember-variable
3645 (if (re-search-forward (sh-feature sh-assignment-regexp
)
3647 (beginning-of-line 1))
3649 (match-string 1))))))
3652 (defun sh-maybe-here-document (arg)
3653 "Insert self. Without prefix, following unquoted `<' inserts here document.
3654 The document is bounded by `sh-here-document-word'."
3656 (self-insert-command (prefix-numeric-value arg
))
3658 (not (looking-back "[^<]<<"))
3662 (let ((tabs (if (string-match "\\`-" sh-here-document-word
)
3663 (make-string (/ (current-indentation) tab-width
) ?
\t)
3665 (delim (replace-regexp-in-string "['\"]" ""
3666 sh-here-document-word
)))
3667 (insert sh-here-document-word
)
3668 (or (eolp) (looking-at "[ \t]") (insert ?\s
))
3675 (insert ?
\n tabs
(replace-regexp-in-string
3676 "\\`-?[ \t]*" "" delim
))))))
3679 ;; various other commands
3681 (autoload 'comint-dynamic-complete
"comint"
3682 "Dynamically perform completion at point." t
)
3684 (autoload 'shell-dynamic-complete-command
"shell"
3685 "Dynamically complete the command at point." t
)
3687 (autoload 'comint-dynamic-complete-filename
"comint"
3688 "Dynamically complete the filename at point." t
)
3690 (autoload 'shell-dynamic-complete-environment-variable
"shell"
3691 "Dynamically complete the environment variable at point." t
)
3695 (defun sh-beginning-of-command ()
3696 "Move point to successive beginnings of commands."
3698 (if (re-search-backward sh-beginning-of-command nil t
)
3699 (goto-char (match-beginning 2))))
3701 (defun sh-end-of-command ()
3702 "Move point to successive ends of commands."
3704 (if (re-search-forward sh-end-of-command nil t
)
3705 (goto-char (match-end 1))))
3707 ;; Backslashification. Stolen from make-mode.el.
3709 (defun sh-backslash-region (from to delete-flag
)
3710 "Insert, align, or delete end-of-line backslashes on the lines in the region.
3711 With no argument, inserts backslashes and aligns existing backslashes.
3712 With an argument, deletes the backslashes.
3714 This function does not modify the last line of the region if the region ends
3715 right at the start of the following line; it does not modify blank lines
3716 at the start of the region. So you can put the region around an entire
3717 shell command and conveniently use this command."
3718 (interactive "r\nP")
3721 (let ((column sh-backslash-column
)
3722 (endmark (make-marker)))
3723 (move-marker endmark to
)
3724 ;; Compute the smallest column number past the ends of all the lines.
3725 (if sh-backslash-align
3727 (if (not delete-flag
)
3728 (while (< (point) to
)
3730 (if (= (preceding-char) ?
\\)
3731 (progn (forward-char -
1)
3732 (skip-chars-backward " \t")))
3733 (setq column
(max column
(1+ (current-column))))
3735 ;; Adjust upward to a tab column, if that doesn't push
3737 (if (> (% column tab-width
) 0)
3738 (let ((adjusted (* (/ (+ column tab-width -
1) tab-width
)
3740 (if (< adjusted
(window-width))
3741 (setq column adjusted
))))))
3742 ;; Don't modify blank lines at start of region.
3744 (while (and (< (point) endmark
) (eolp))
3746 ;; Add or remove backslashes on all the lines.
3747 (while (and (< (point) endmark
)
3748 ;; Don't backslashify the last line
3749 ;; if the region ends right at the start of the next line.
3752 (< (point) endmark
)))
3753 (if (not delete-flag
)
3754 (sh-append-backslash column
)
3755 (sh-delete-backslash))
3757 (move-marker endmark nil
))))
3759 (defun sh-append-backslash (column)
3761 ;; Note that "\\\\" is needed to get one backslash.
3762 (if (= (preceding-char) ?
\\)
3763 (progn (forward-char -
1)
3764 (delete-horizontal-space)
3765 (indent-to column
(if sh-backslash-align nil
1)))
3766 (indent-to column
(if sh-backslash-align nil
1))
3769 (defun sh-delete-backslash ()
3774 (if (looking-at "\\\\")
3775 (delete-region (1+ (point))
3776 (progn (skip-chars-backward " \t") (point)))))))
3778 (provide 'sh-script
)
3780 ;;; sh-script.el ends here