1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993, 94, 95, 96, 97, 1999, 2001, 03, 2004
4 ;; Free Software Foundation, Inc.
6 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
9 ;; Keywords: languages, unix
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
30 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
31 ;; as various derivatives are supported and easily derived from. Structured
32 ;; statements can be inserted with one command or abbrev. Completion is
33 ;; available for filenames, variables known from the script, the shell and
34 ;; the environment as well as commands.
38 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
39 ;; - Variables in `"' strings aren't fontified because there's no way of
40 ;; syntactically distinguishing those from `'' strings.
44 ;; Indentation for rc and es modes is very limited, but for Bourne shells
45 ;; and its derivatives it is quite customizable.
47 ;; The following description applies to sh and derived shells (bash,
50 ;; There are various customization variables which allow tailoring to
51 ;; a wide variety of styles. Most of these variables are named
52 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
53 ;; sh-indent-after-if controls the indenting of a line following
54 ;; an if statement, and sh-indent-for-fi controls the indentation
55 ;; of the line containing the fi.
57 ;; You can set each to a numeric value, but it is often more convenient
58 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
59 ;; By changing this one variable you can increase or decrease how much
60 ;; indentation there is. Valid symbols:
62 ;; + Indent right by sh-basic-offset
63 ;; - Indent left by sh-basic-offset
64 ;; ++ Indent right twice sh-basic-offset
65 ;; -- Indent left twice sh-basic-offset
66 ;; * Indent right half sh-basic-offset
67 ;; / Indent left half sh-basic-offset.
69 ;; There are 4 commands to help set the indentation variables:
72 ;; This shows what variable controls the indentation of the current
73 ;; line and its value.
76 ;; This allows you to set the value of the variable controlling the
77 ;; current line's indentation. You can enter a number or one of a
78 ;; number of special symbols to denote the value of sh-basic-offset,
79 ;; or its negative, or half it, or twice it, etc. If you've used
80 ;; cc-mode this should be familiar. If you forget which symbols are
81 ;; valid simply press C-h at the prompt.
83 ;; `sh-learn-line-indent'
84 ;; Simply make the line look the way you want it, then invoke this
85 ;; command. It will set the variable to the value that makes the line
86 ;; indent like that. If called with a prefix argument then it will set
87 ;; the value to one of the symbols if applicable.
89 ;; `sh-learn-buffer-indent'
90 ;; This is the deluxe function! It "learns" the whole buffer (use
91 ;; narrowing if you want it to process only part). It outputs to a
92 ;; buffer *indent* any conflicts it finds, and all the variables it has
93 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
94 ;; easily find where something was set. It is popped to automatically
95 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
97 ;; `sh-indent-comment' will be set if all comments follow the same
98 ;; pattern; if they don't it will be set to nil.
99 ;; Whether `sh-basic-offset' is set is determined by variable
100 ;; `sh-learn-basic-offset'.
102 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
103 ;; (e.g. if there are large case statements). Perhaps it does not make
104 ;; sense to run it on large buffers: if lots of lines have different
105 ;; indentation styles it will produce a lot of diagnostics in the
106 ;; *indent* buffer; if there is a consistent style then running
107 ;; `sh-learn-buffer-indent' on a small region of the buffer should
110 ;; Saving indentation values
111 ;; -------------------------
112 ;; After you've learned the values in a buffer, how to you remember
113 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
114 ;; would make this unnecessary; simply learn the values when you visit
116 ;; You can do this automatically like this:
117 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
119 ;; However... `sh-learn-buffer-indent' is extremely slow,
120 ;; especially on large-ish buffer. Also, if there are conflicts the
121 ;; "last one wins" which may not produce the desired setting.
123 ;; So...There is a minimal way of being able to save indentation values and
124 ;; to reload them in another buffer or at another point in time.
126 ;; Use `sh-name-style' to give a name to the indentation settings of
127 ;; the current buffer.
128 ;; Use `sh-load-style' to load indentation settings for the current
129 ;; buffer from a specific style.
130 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
131 ;; in lisp code. You can then store it in a file and later use
132 ;; `load-file' to load it.
134 ;; Indentation variables - buffer local or global?
135 ;; ----------------------------------------------
136 ;; I think that often having them buffer-local makes sense,
137 ;; especially if one is using `sh-learn-buffer-indent'. However, if
138 ;; a user sets values using customization, these changes won't appear
139 ;; to work if the variables are already local!
141 ;; To get round this, there is a variable `sh-make-vars-local' and 2
142 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
144 ;; If `sh-make-vars-local' is non-nil, then these variables become
145 ;; buffer local when the mode is established.
146 ;; If this is nil, then the variables are global. At any time you
147 ;; can make them local with the command `sh-make-vars-local'.
148 ;; Conversely, to update with the global values you can use the
149 ;; command `sh-reset-indent-vars-to-global-values'.
151 ;; This may be awkward, but the intent is to cover all cases.
153 ;; Awkward things, pitfalls
154 ;; ------------------------
155 ;; Indentation for a sh script is complicated for a number of reasons:
157 ;; 1. You can't format by simply looking at symbols, you need to look
158 ;; at keywords. [This is not the case for rc and es shells.]
159 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
160 ;; as a stand-alone symbol (in a case alternative). This makes
161 ;; things quite tricky!
162 ;; 3. Here-documents in a script should be treated "as is", and when
163 ;; they terminate we want to revert to the indentation of the line
164 ;; containing the "<<" symbol.
165 ;; 4. A line may be continued using the "\".
166 ;; 5. The character "#" (outside a string) normally starts a comment,
167 ;; but it doesn't in the sequence "$#"!
169 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
170 ;; uses, that of a text's syntax property. This, however, has 2
172 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
173 ;; case alternative, to find any here documents, and handle "$#".
174 ;; 2. Setting the text property makes the buffer modified. If the
175 ;; buffer is read-only buffer we have to cheat and bypass the read-only
176 ;; status. This is for cases where the buffer started read-only buffer
177 ;; but the user issued `toggle-read-only'.
181 ;; - Indenting many lines is slow. It currently does each line
182 ;; independently, rather than saving state information.
184 ;; - `sh-learn-buffer-indent' is extremely slow.
186 ;; Richard Sharman <rsharman@pobox.com> June 1999.
190 ;; page 1: variables and settings
191 ;; page 2: indentation stuff
192 ;; page 3: mode-command and utility functions
193 ;; page 4: statement syntax-commands for various shells
194 ;; page 5: various other commands
200 (require 'executable
)
205 "Shell programming utilities"
209 (defgroup sh-script nil
215 (defcustom sh-ancestor-alist
234 "*Alist showing the direct ancestor of various shells.
235 This is the basis for `sh-feature'. See also `sh-alias-alist'.
236 By default we have the following three hierarchies:
239 jcsh C Shell with Job Control
241 itcsh ? Turbo C Shell
246 jsh Bourne Shell with Job Control
247 bash GNU Bourne Again Shell
250 dtksh CDE Desktop Korn Shell
251 pdksh Public Domain Korn Shell
252 wksh Window Korn Shell
254 oash SCO OA (curses) Shell
255 posix IEEE 1003.2 Shell Standard
257 :type
'(repeat (cons symbol symbol
))
261 (defcustom sh-alias-alist
262 (append (if (eq system-type
'gnu
/linux
)
265 ;; for the time being
269 "*Alist for transforming shell names to what they really are.
270 Use this where the name of the executable doesn't correspond to the type of
272 :type
'(repeat (cons symbol symbol
))
276 (defcustom sh-shell-file
278 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
279 ;; the executable extension, so comparisons with the list of
280 ;; known shells work.
281 (and (memq system-type
'(ms-dos windows-nt
))
282 (let* ((shell (getenv "SHELL"))
284 (and shell
(file-name-nondirectory shell
))))
285 ;; shell-script mode doesn't support DOS/Windows shells,
286 ;; so use the default instead.
288 (member (downcase shell-base
)
289 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
292 (file-name-sans-extension (downcase shell
)))))
295 "*The executable file name for the shell being programmed."
300 (defcustom sh-shell-arg
301 ;; bash does not need any options when run in a shell script,
305 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
307 ;; -p means don't initialize functions from the environment.
309 ;; Someone proposed -motif, but we don't want to encourage
310 ;; use of a non-free widget set.
312 ;; -f means don't run .zshrc.
314 "*Single argument string for the magic number. See `sh-feature'."
315 :type
'(repeat (cons (symbol :tag
"Shell")
316 (choice (const :tag
"No Arguments" nil
)
317 (string :tag
"Arguments")
318 (sexp :format
"Evaluate: %v"))))
321 (defcustom sh-imenu-generic-expression
323 .
((nil "^\\s-*\\(function\\s-+\\)?\\([A-Za-z_][A-Za-z_0-9]+\\)\\s-*()" 2))))
324 "*Alist of regular expressions for recognizing shell function definitions.
325 See `sh-feature' and `imenu-generic-expression'."
326 :type
'(alist :key-type
(symbol :tag
"Shell")
327 :value-type
(alist :key-type
(choice :tag
"Title"
329 (const :tag
"None" nil
))
331 (repeat :tag
"Regexp, index..." sexp
)))
335 (defvar sh-shell-variables nil
336 "Alist of shell variable names that should be included in completion.
337 These are used for completion in addition to all the variables named
338 in `process-environment'. Each element looks like (VAR . VAR), where
339 the car and cdr are the same symbol.")
341 (defvar sh-shell-variables-initialized nil
342 "Non-nil if `sh-shell-variables' is initialized.")
344 (defun sh-canonicalize-shell (shell)
345 "Convert a shell name SHELL to the one we should handle it as."
346 (if (string-match "\\.exe\\'" shell
)
347 (setq shell
(substring shell
0 (match-beginning 0))))
349 (setq shell
(intern shell
)))
350 (or (cdr (assq shell sh-alias-alist
))
353 (defvar sh-shell
(sh-canonicalize-shell (file-name-nondirectory sh-shell-file
))
354 "The shell being programmed. This is set by \\[sh-set-shell].")
356 ;; I turned off this feature because it doesn't permit typing commands
357 ;; in the usual way without help.
359 ;; '((csh sh-abbrevs shell
361 ;; "getopts" 'sh-while-getopts)
363 ;; (es sh-abbrevs shell
364 ;; "function" 'sh-function)
366 ;; (ksh88 sh-abbrevs sh
367 ;; "select" 'sh-select)
369 ;; (rc sh-abbrevs shell
371 ;; "function" 'sh-function)
373 ;; (sh sh-abbrevs shell
375 ;; "function" 'sh-function
377 ;; "getopts" 'sh-while-getopts)
379 ;; ;; The next entry is only used for defining the others
380 ;; (shell "for" sh-for
381 ;; "loop" sh-indexed-loop
383 ;; "tmpfile" sh-tmp-file
386 ;; (zsh sh-abbrevs ksh88
387 ;; "repeat" 'sh-repeat))
388 ;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
389 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
390 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
394 (defun sh-mode-syntax-table (table &rest list
)
395 "Copy TABLE and set syntax for successive CHARs according to strings S."
396 (setq table
(copy-syntax-table table
))
398 (modify-syntax-entry (pop list
) (pop list
) table
))
401 (defvar sh-mode-syntax-table nil
402 "The syntax table to use for Shell-Script mode.
403 This is buffer-local in every such buffer.")
405 (defvar sh-mode-default-syntax-table
406 (sh-mode-syntax-table ()
421 "Default syntax table for shell mode.")
423 (defvar sh-mode-syntax-table-input
425 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
428 (let ((map (make-sparse-keymap))
429 (menu-map (make-sparse-keymap "Insert")))
430 (define-key map
"\C-c(" 'sh-function
)
431 (define-key map
"\C-c\C-w" 'sh-while
)
432 (define-key map
"\C-c\C-u" 'sh-until
)
433 (define-key map
"\C-c\C-t" 'sh-tmp-file
)
434 (define-key map
"\C-c\C-s" 'sh-select
)
435 (define-key map
"\C-c\C-r" 'sh-repeat
)
436 (define-key map
"\C-c\C-o" 'sh-while-getopts
)
437 (define-key map
"\C-c\C-l" 'sh-indexed-loop
)
438 (define-key map
"\C-c\C-i" 'sh-if
)
439 (define-key map
"\C-c\C-f" 'sh-for
)
440 (define-key map
"\C-c\C-c" 'sh-case
)
441 (define-key map
"\C-c?" 'sh-show-indent
)
442 (define-key map
"\C-c=" 'sh-set-indent
)
443 (define-key map
"\C-c<" 'sh-learn-line-indent
)
444 (define-key map
"\C-c>" 'sh-learn-buffer-indent
)
446 (define-key map
"=" 'sh-assignment
)
447 (define-key map
"\C-c+" 'sh-add
)
448 (define-key map
"\C-\M-x" 'sh-execute-region
)
449 (define-key map
"\C-c\C-x" 'executable-interpret
)
450 (define-key map
"<" 'sh-maybe-here-document
)
451 (define-key map
"(" 'skeleton-pair-insert-maybe
)
452 (define-key map
"{" 'skeleton-pair-insert-maybe
)
453 (define-key map
"[" 'skeleton-pair-insert-maybe
)
454 (define-key map
"'" 'skeleton-pair-insert-maybe
)
455 (define-key map
"`" 'skeleton-pair-insert-maybe
)
456 (define-key map
"\"" 'skeleton-pair-insert-maybe
)
458 (define-key map
[remap complete-tag
] 'comint-dynamic-complete
)
459 (define-key map
[remap newline-and-indent
] 'sh-newline-and-indent
)
460 (define-key map
[remap delete-backward-char
]
461 'backward-delete-char-untabify
)
462 (define-key map
"\C-c:" 'sh-set-shell
)
463 (define-key map
[remap backward-sentence
] 'sh-beginning-of-command
)
464 (define-key map
[remap forward-sentence
] 'sh-end-of-command
)
465 (define-key map
[menu-bar insert
] (cons "Insert" menu-map
))
466 (define-key menu-map
[sh-while
] '("While Loop" . sh-while
))
467 (define-key menu-map
[sh-until
] '("Until Loop" . sh-until
))
468 (define-key menu-map
[sh-tmp-file
] '("Temporary File" . sh-tmp-file
))
469 (define-key menu-map
[sh-select
] '("Select Statement" . sh-select
))
470 (define-key menu-map
[sh-repeat
] '("Repeat Loop" . sh-repeat
))
471 (define-key menu-map
[sh-getopts
] '("Options Loop" . sh-while-getopts
))
472 (define-key menu-map
[sh-indexed-loop
] '("Indexed Loop" . sh-indexed-loop
))
473 (define-key menu-map
[sh-if
] '("If Statement" . sh-if
))
474 (define-key menu-map
[sh-for
] '("For Loop" . sh-for
))
475 (define-key menu-map
[sh-case
] '("Case Statement" . sh-case
))
477 "Keymap used in Shell-Script mode.")
481 (defcustom sh-dynamic-complete-functions
482 '(shell-dynamic-complete-environment-variable
483 shell-dynamic-complete-command
484 comint-dynamic-complete-filename
)
485 "*Functions for doing TAB dynamic completion."
486 :type
'(repeat function
)
490 (defcustom sh-require-final-newline
493 (rc . require-final-newline
)
494 (sh . require-final-newline
))
495 "*Value of `require-final-newline' in Shell-Script mode buffers.
497 :type
'(repeat (cons (symbol :tag
"Shell")
498 (choice (const :tag
"require" t
)
499 (sexp :format
"Evaluate: %v"))))
503 (defcustom sh-assignment-regexp
504 '((csh .
"\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
505 ;; actually spaces are only supported in let/(( ... ))
506 (ksh88 .
"\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
507 (rc .
"\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
508 (sh .
"\\<\\([a-zA-Z0-9_]+\\)="))
509 "*Regexp for the variable name and what may follow in an assignment.
510 First grouping matches the variable name. This is upto and including the `='
511 sign. See `sh-feature'."
512 :type
'(repeat (cons (symbol :tag
"Shell")
514 (sexp :format
"Evaluate: %v"))))
518 (defcustom sh-indentation
4
519 "The width for further indentation in Shell-Script mode."
524 (defcustom sh-remember-variable-min
3
525 "*Don't remember variables less than this length for completing reads."
530 (defvar sh-header-marker nil
531 "When non-nil is the end of header for prepending by \\[sh-execute-region].
532 That command is also used for setting this variable.")
535 (defcustom sh-beginning-of-command
536 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
537 "*Regexp to determine the beginning of a shell command.
538 The actual command starts at the beginning of the second \\(grouping\\)."
543 (defcustom sh-end-of-command
544 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
545 "*Regexp to determine the end of a shell command.
546 The actual command ends at the end of the first \\(grouping\\)."
552 (defvar sh-here-document-word
"EOF"
553 "Word to delimit here documents.
554 If the first character of this string is \"-\", this character will
555 be removed from the string when it is used to close the here document.
556 This convention is used by the Bash shell, for example, to indicate
557 that leading tabs inside the here document should be ignored.
558 Note that Emacs currently has no support for indenting inside here
559 documents - you must insert literal tabs by hand.")
564 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
567 ;; customized this out of sheer bravado. not for the faint of heart.
568 ;; but it *did* have an asterisk in the docstring!
569 (defcustom sh-builtins
570 '((bash sh-append posix
571 "." "alias" "bg" "bind" "builtin" "compgen" "complete"
572 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
573 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
574 "source" "suspend" "typeset" "unalias")
576 ;; The next entry is only used for defining the others
577 (bourne sh-append shell
578 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
582 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
583 "setenv" "source" "time" "unalias" "unhash")
585 (dtksh sh-append wksh
)
587 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
588 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
591 "bg" "fg" "jobs" "kill" "stop" "suspend")
594 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
596 (ksh88 sh-append bourne
597 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
598 "typeset" "unalias" "whence")
601 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
602 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
603 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
604 "wmtitle" "wrefresh")
606 (pdksh sh-append ksh88
612 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
616 "hash" "test" "type")
618 ;; The next entry is only used for defining the others
619 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
621 (wksh sh-append ksh88
625 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
626 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
627 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
628 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
629 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
631 "*List of all shell builtins for completing read and fontification.
632 Note that on some systems not all builtins are available or some are
633 implemented as aliases. See `sh-feature'."
634 :type
'(repeat (cons (symbol :tag
"Shell")
635 (choice (repeat string
)
636 (sexp :format
"Evaluate: %v"))))
641 (defcustom sh-leading-keywords
647 (es "true" "unwind-protect" "whatis")
651 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
652 "*List of keywords that may be immediately followed by a builtin or keyword.
653 Given some confusion between keywords and builtins depending on shell and
654 system, the distinction here has been based on whether they influence the
655 flow of control or syntax. See `sh-feature'."
656 :type
'(repeat (cons (symbol :tag
"Shell")
657 (choice (repeat string
)
658 (sexp :format
"Evaluate: %v"))))
662 (defcustom sh-other-keywords
663 '((bash sh-append bourne
664 "bye" "logout" "select")
666 ;; The next entry is only used for defining the others
671 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
672 "if" "logout" "onintr" "repeat" "switch" "then" "while")
674 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
675 "return" "throw" "while")
677 (ksh88 sh-append bourne
680 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
684 "done" "esac" "fi" "for" "in" "return")
686 ;; The next entry is only used for defining the others
687 (shell "break" "case" "continue" "exec" "exit")
691 "*List of keywords not in `sh-leading-keywords'.
693 :type
'(repeat (cons (symbol :tag
"Shell")
694 (choice (repeat string
)
695 (sexp :format
"Evaluate: %v"))))
702 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
703 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
704 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
705 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
706 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
707 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
708 "HISTIGNORE" "history_control" "HISTSIZE"
709 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
710 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
711 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
712 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
713 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
714 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
715 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
718 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
719 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
720 "shell" "status" "time" "verbose")
723 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
724 "pid" "prompt" "signals")
730 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
731 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
735 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
738 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
742 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
744 ;; The next entry is only used for defining the others
745 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
746 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
747 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
748 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
751 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
752 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
753 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
754 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
755 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
756 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
757 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
758 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
762 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
763 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
764 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
765 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
766 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
767 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
768 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
769 "List of all shell variables available for completing read.
775 (defface sh-heredoc-face
778 (:foreground
"yellow" :weight bold
))
781 (:foreground
"tan" ))
784 "Face to show a here-document"
785 :group
'sh-indentation
)
786 (defvar sh-heredoc-face
'sh-heredoc-face
)
789 (defvar sh-font-lock-keywords
790 '((csh sh-append shell
791 ("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
792 font-lock-variable-name-face
))
794 (es sh-append executable-font-lock-keywords
795 ("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
796 font-lock-variable-name-face
))
802 ("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
803 font-lock-variable-name-face
)
805 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face
)
806 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
807 (1 font-lock-keyword-face
) (2 font-lock-function-name-face nil t
)))
809 ;; The next entry is only used for defining the others
810 (shell sh-append executable-font-lock-keywords
811 ;; Using font-lock-string-face here confuses sh-get-indent-info.
812 ("\\\\$" 0 font-lock-warning-face
)
813 ("\\\\[^A-Za-z0-9]" 0 font-lock-string-face
)
814 ("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
815 font-lock-variable-name-face
))
817 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face
))
818 (rpm2 sh-append shell
819 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face
)))
820 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
822 (defvar sh-font-lock-keywords-1
824 "Subdued level highlighting for Shell Script modes.")
826 (defvar sh-font-lock-keywords-2
()
827 "Gaudy level highlighting for Shell Script modes.")
829 ;; These are used for the syntax table stuff (derived from cperl-mode).
830 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
831 (defconst sh-st-punc
(string-to-syntax "."))
832 (defconst sh-st-symbol
(string-to-syntax "_"))
833 (defconst sh-here-doc-syntax
(string-to-syntax "|")) ;; generic string
835 (defconst sh-here-doc-open-re
"<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\|\\s_\\)+\\).*\\(\n\\)")
837 (defvar sh-here-doc-markers nil
)
838 (make-variable-buffer-local 'sh-here-doc-markers
)
839 (defvar sh-here-doc-re sh-here-doc-open-re
)
840 (make-variable-buffer-local 'sh-here-doc-re
)
842 (defun sh-font-lock-close-heredoc (bol eof indented
)
843 "Determine the syntax of the \\n after an EOF.
844 If non-nil INDENTED indicates that the EOF was indented."
845 (let* ((eof-re (if eof
(regexp-quote eof
) ""))
846 ;; A rough regexp that should find the opening <<EOF back.
847 (sre (concat "<<\\(-?\\)\\s-*['\"\\]?"
848 ;; Use \s| to cheaply check it's an open-heredoc.
849 eof-re
"['\"]?\\([ \t|;&)<>].*\\)?\\s|"))
850 ;; A regexp that will find other EOFs.
851 (ere (concat "^" (if indented
"[ \t]*") eof-re
"\n"))
852 (start (save-excursion
854 (re-search-backward (concat sre
"\\|" ere
) nil t
))))
855 ;; If subgroup 1 matched, we found an open-heredoc, otherwise we first
856 ;; found a close-heredoc which makes the current close-heredoc inoperant.
858 ((when (and start
(match-end 1)
859 (not (and indented
(= (match-beginning 1) (match-end 1))))
860 (not (sh-in-comment-or-string (match-beginning 0))))
861 ;; Make sure our `<<' is not the EOF1 of a `cat <<EOF1 <<EOF2'.
864 (setq start
(line-beginning-position 2))
867 (re-search-forward "<<") ; Skip ourselves.
868 (and (re-search-forward sh-here-doc-open-re start
'move
)
869 (goto-char (match-beginning 0))
870 (sh-in-comment-or-string (point)))))
871 ;; No <<EOF2 found after our <<.
874 ((not (or start
(save-excursion (re-search-forward sre nil t
))))
875 ;; There's no <<EOF either before or after us,
876 ;; so we should remove ourselves from font-lock's keywords.
877 (setq sh-here-doc-markers
(delete eof sh-here-doc-markers
))
879 (concat sh-here-doc-open-re
"\\|^\\([ \t]*\\)"
880 (regexp-opt sh-here-doc-markers t
) "\\(\n\\)"))
883 (defun sh-font-lock-open-heredoc (start string
)
884 "Determine the syntax of the \\n after a <<EOF.
885 START is the position of <<.
886 STRING is the actual word used as delimiter (f.ex. \"EOF\").
887 INDENTED is non-nil if the here document's content (and the EOF mark) can
888 be indented (i.e. a <<- was used rather than just <<)."
889 (unless (or (memq (char-before start
) '(?
< ?
>))
890 (sh-in-comment-or-string start
))
891 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
892 ;; font-lock keywords to detect the end of this here document.
893 (let ((str (replace-regexp-in-string "['\"]" "" string
)))
894 (unless (member str sh-here-doc-markers
)
895 (push str sh-here-doc-markers
)
897 (concat sh-here-doc-open-re
"\\|^\\([ \t]*\\)"
898 (regexp-opt sh-here-doc-markers t
) "\\(\n\\)"))))
901 (defun sh-font-lock-here-doc (limit)
902 "Search for a heredoc marker."
903 ;; This looks silly, but it's because `sh-here-doc-re' keeps changing.
904 (re-search-forward sh-here-doc-re limit t
))
906 (defun sh-is-quoted-p (pos)
907 (and (eq (char-before pos
) ?
\\)
908 (not (sh-is-quoted-p (1- pos
)))))
910 (defun sh-font-lock-paren (start)
913 ;; Skip through all patterns
916 (forward-comment (- (point-max)))
917 ;; Skip through one pattern
919 (or (/= 0 (skip-syntax-backward "w_"))
920 (/= 0 (skip-chars-backward "?[]*@/\\"))
921 (and (sh-is-quoted-p (1- (point)))
922 (goto-char (- (point) 2)))
923 (when (memq (char-before) '(?
\" ?
\'))
924 (condition-case nil
(progn (backward-sexp 1) t
)
926 (forward-comment (- (point-max)))
927 (when (eq (char-before) ?|
)
928 (backward-char 1) t
)))
929 (when (save-excursion (backward-char 2) (looking-at ";;\\|in"))
932 (defconst sh-font-lock-syntactic-keywords
933 ;; A `#' begins a comment when it is unquoted and at the beginning of a
934 ;; word. In the shell, words are separated by metacharacters.
935 ;; The list of special chars is taken from the single-unix spec
936 ;; of the shell command language (under `quoting') but with `$' removed.
937 `(("[^|&;<>()`\\\"' \t\n]\\(#+\\)" 1 ,sh-st-symbol
)
938 ;; Find HEREDOC starters and add a corresponding rule for the ender.
939 (sh-font-lock-here-doc
940 (2 (sh-font-lock-open-heredoc
941 (match-beginning 0) (match-string 1)) nil t
)
942 (5 (sh-font-lock-close-heredoc
943 (match-beginning 0) (match-string 4)
944 (and (match-beginning 3) (/= (match-beginning 3) (match-end 3))))
946 ;; Distinguish the special close-paren in `case'.
947 (")" 0 (sh-font-lock-paren (match-beginning 0)))))
949 (defun sh-font-lock-syntactic-face-function (state)
951 (if (characterp (nth 3 state
))
952 font-lock-string-face
954 font-lock-comment-face
))
956 (defgroup sh-indentation nil
957 "Variables controlling indentation in shell scripts.
959 Note: customizing these variables will not affect existing buffers if
960 `sh-make-vars-local' is no-nil. See the documentation for
961 variable `sh-make-vars-local', command `sh-make-vars-local'
962 and command `sh-reset-indent-vars-to-global-values'."
966 (defcustom sh-set-shell-hook nil
967 "*Hook run by `sh-set-shell'."
971 (defcustom sh-mode-hook nil
972 "*Hook run by `sh-mode'."
976 (defcustom sh-learn-basic-offset nil
977 "*When `sh-guess-basic-offset' should learn `sh-basic-offset'.
980 t means: only if there seems to be an obvious value.
981 Anything else means: whenever we have a \"good guess\" as to the value."
983 (const :tag
"Never" nil
)
984 (const :tag
"Only if sure" t
)
985 (const :tag
"If have a good guess" usually
))
986 :group
'sh-indentation
)
988 (defcustom sh-popup-occur-buffer nil
989 "*Controls when `sh-learn-buffer-indent' pops the *indent* buffer.
990 If t it is always shown. If nil, it is shown only when there
993 (const :tag
"Only when there are conflicts." nil
)
994 (const :tag
"Always" t
))
995 :group
'sh-indentation
)
997 (defcustom sh-blink t
998 "*If non-nil, `sh-show-indent' shows the line indentation is relative to.
999 The position on the line is not necessarily meaningful.
1000 In some cases the line will be the matching keyword, but this is not
1003 :group
'sh-indentation
)
1005 (defcustom sh-first-lines-indent
0
1006 "*The indentation of the first non-blank non-comment line.
1007 Usually 0 meaning first column.
1008 Can be set to a number, or to nil which means leave it as is."
1010 (const :tag
"Leave as is" nil
)
1011 (integer :tag
"Column number"
1012 :menu-tag
"Indent to this col (0 means first col)" ))
1013 :group
'sh-indentation
)
1016 (defcustom sh-basic-offset
4
1017 "*The default indentation increment.
1018 This value is used for the + and - symbols in an indentation variable."
1020 :group
'sh-indentation
)
1022 (defcustom sh-indent-comment nil
1023 "*How a comment line is to be indented.
1024 nil means leave it as it is;
1025 t means indent it as a normal line, aligning it to previous non-blank
1027 a number means align to that column, e.g. 0 means fist column."
1029 (const :tag
"Leave as is." nil
)
1030 (const :tag
"Indent as a normal line." t
)
1031 (integer :menu-tag
"Indent to this col (0 means first col)."
1032 :tag
"Indent to column number.") )
1033 :group
'sh-indentation
)
1036 (defvar sh-debug nil
1037 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1040 ;; Uncomment this defun and comment the defmacro for debugging.
1041 ;; (defun sh-debug (&rest args)
1042 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1044 ;; (apply 'message args)))
1045 (defmacro sh-debug
(&rest args
))
1047 (defconst sh-symbol-list
1048 '((const :tag
"+ " :value
+
1049 :menu-tag
"+ Indent right by sh-basic-offset")
1050 (const :tag
"- " :value -
1051 :menu-tag
"- Indent left by sh-basic-offset")
1052 (const :tag
"++" :value
++
1053 :menu-tag
"++ Indent right twice sh-basic-offset")
1054 (const :tag
"--" :value --
1055 :menu-tag
"-- Indent left twice sh-basic-offset")
1056 (const :tag
"* " :value
*
1057 :menu-tag
"* Indent right half sh-basic-offset")
1058 (const :tag
"/ " :value
/
1059 :menu-tag
"/ Indent left half sh-basic-offset")))
1061 (defcustom sh-indent-for-else
0
1062 "*How much to indent an else relative to an if. Usually 0."
1064 (integer :menu-tag
"A number (positive=>indent right)"
1066 (const :tag
"--") ;; separator!
1069 :group
'sh-indentation
)
1071 (defconst sh-number-or-symbol-list
1072 (append '((integer :menu-tag
"A number (positive=>indent right)"
1074 (const :tag
"--")) ; separator
1077 (defcustom sh-indent-for-fi
0
1078 "*How much to indent a fi relative to an if. Usually 0."
1079 :type
`(choice ,@ sh-number-or-symbol-list
)
1080 :group
'sh-indentation
)
1082 (defcustom sh-indent-for-done
'0
1083 "*How much to indent a done relative to its matching stmt. Usually 0."
1084 :type
`(choice ,@ sh-number-or-symbol-list
)
1085 :group
'sh-indentation
)
1087 (defcustom sh-indent-after-else
'+
1088 "*How much to indent a statement after an else statement."
1089 :type
`(choice ,@ sh-number-or-symbol-list
)
1090 :group
'sh-indentation
)
1092 (defcustom sh-indent-after-if
'+
1093 "*How much to indent a statement after an if statement.
1094 This includes lines after else and elif statements, too, but
1095 does not affect then else elif or fi statements themselves."
1096 :type
`(choice ,@ sh-number-or-symbol-list
)
1097 :group
'sh-indentation
)
1099 (defcustom sh-indent-for-then
'+
1100 "*How much to indent a then relative to an if."
1101 :type
`(choice ,@ sh-number-or-symbol-list
)
1102 :group
'sh-indentation
)
1104 (defcustom sh-indent-for-do
'*
1105 "*How much to indent a do statement.
1106 This is relative to the statement before the do, i.e. the
1107 while until or for statement."
1108 :type
`(choice ,@ sh-number-or-symbol-list
)
1109 :group
'sh-indentation
)
1111 (defcustom sh-indent-after-do
'*
1112 "*How much to indent a line after a do statement.
1113 This is used when the do is the first word of the line.
1114 This is relative to the statement before the do, e.g. a
1115 while for repeat or select statement."
1116 :type
`(choice ,@ sh-number-or-symbol-list
)
1117 :group
'sh-indentation
)
1119 (defcustom sh-indent-after-loop-construct
'+
1120 "*How much to indent a statement after a loop construct.
1122 This variable is used when the keyword \"do\" is on the same line as the
1123 loop statement (e.g. \"until\", \"while\" or \"for\").
1124 If the do is on a line by itself, then `sh-indent-after-do' is used instead."
1125 :type
`(choice ,@ sh-number-or-symbol-list
)
1126 :group
'sh-indentation
)
1129 (defcustom sh-indent-after-done
0
1130 "*How much to indent a statement after a \"done\" keyword.
1131 Normally this is 0, which aligns the \"done\" to the matching
1132 looping construct line.
1133 Setting it non-zero allows you to have the \"do\" statement on a line
1134 by itself and align the done under to do."
1135 :type
`(choice ,@ sh-number-or-symbol-list
)
1136 :group
'sh-indentation
)
1138 (defcustom sh-indent-for-case-label
'+
1139 "*How much to indent a case label statement.
1140 This is relative to the line containing the case statement."
1141 :type
`(choice ,@ sh-number-or-symbol-list
)
1142 :group
'sh-indentation
)
1144 (defcustom sh-indent-for-case-alt
'++
1145 "*How much to indent statements after the case label.
1146 This is relative to the line containing the case statement."
1147 :type
`(choice ,@ sh-number-or-symbol-list
)
1148 :group
'sh-indentation
)
1151 (defcustom sh-indent-for-continuation
'+
1152 "*How much to indent for a continuation statement."
1153 :type
`(choice ,@ sh-number-or-symbol-list
)
1154 :group
'sh-indentation
)
1156 (defcustom sh-indent-after-open
'+
1157 "*How much to indent after a line with an opening parenthesis or brace.
1158 For an open paren after a function `sh-indent-after-function' is used."
1159 :type
`(choice ,@ sh-number-or-symbol-list
)
1160 :group
'sh-indentation
)
1162 (defcustom sh-indent-after-function
'+
1163 "*How much to indent after a function line."
1164 :type
`(choice ,@ sh-number-or-symbol-list
)
1165 :group
'sh-indentation
)
1167 ;; These 2 are for the rc shell:
1169 (defcustom sh-indent-after-switch
'+
1170 "*How much to indent a case statement relative to the switch statement.
1171 This is for the rc shell."
1172 :type
`(choice ,@ sh-number-or-symbol-list
)
1173 :group
'sh-indentation
)
1175 (defcustom sh-indent-after-case
'+
1176 "*How much to indent a statement relative to the case statement.
1177 This is for the rc shell."
1178 :type
`(choice ,@ sh-number-or-symbol-list
)
1179 :group
'sh-indentation
)
1181 ;; Internal use - not designed to be changed by the user:
1183 (defun sh-mkword-regexpr (word)
1184 "Make a regexp which matches WORD as a word.
1185 This specifically excludes an occurrence of WORD followed by
1186 punctuation characters like '-'."
1187 (concat word
"\\([^-a-z0-9_]\\|$\\)"))
1189 (defconst sh-re-done
(sh-mkword-regexpr "done"))
1192 (defconst sh-kws-for-done
1193 '((sh .
( "while" "until" "for" ) )
1194 (bash .
( "while" "until" "for" "select" ) )
1195 (ksh88 .
( "while" "until" "for" "select" ) )
1196 (zsh .
( "while" "until" "for" "repeat" "select" ) ) )
1197 "Which keywords can match the word `done' in this shell.")
1200 (defconst sh-indent-supported
1204 "Shell types that shell indenting can do something with.")
1206 (defvar sh-indent-supported-here nil
1207 "Non-nil if we support indentation for the current buffer's shell type.")
1209 (defconst sh-var-list
1211 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1212 sh-indent-after-do sh-indent-after-done
1213 sh-indent-after-else
1215 sh-indent-after-loop-construct
1216 sh-indent-after-open
1218 sh-indent-for-case-alt
1219 sh-indent-for-case-label
1220 sh-indent-for-continuation
1227 "A list of variables used by script mode to control indentation.
1228 This list is used when switching between buffer-local and global
1229 values of variables, and for the commands using indentation styles.")
1231 (defvar sh-make-vars-local t
1232 "*Controls whether indentation variables are local to the buffer.
1233 If non-nil, indentation variables are made local initially.
1234 If nil, you can later make the variables local by invoking
1235 command `sh-make-vars-local'.
1236 The default is t because I assume that in one Emacs session one is
1237 frequently editing existing scripts with different styles.")
1240 ;; mode-command and utility functions
1244 "Major mode for editing shell scripts.
1245 This mode works for many shells, since they all have roughly the same syntax,
1246 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1247 Unless the file's magic number indicates the shell, your usual shell is
1248 assumed. Since filenames rarely give a clue, they are not further analyzed.
1250 This mode adapts to the variations between shells (see `sh-set-shell') by
1251 means of an inheritance based feature lookup (see `sh-feature'). This
1252 mechanism applies to all variables (including skeletons) that pertain to
1253 shell-specific features.
1255 The default style of this mode is that of Rosenblatt's Korn shell book.
1256 The syntax of the statements varies with the shell being used. The
1257 following commands are available, based on the current shell's syntax:
1259 \\[sh-case] case statement
1261 \\[sh-function] function definition
1262 \\[sh-if] if statement
1263 \\[sh-indexed-loop] indexed loop from 1 to n
1264 \\[sh-while-getopts] while getopts loop
1265 \\[sh-repeat] repeat loop
1266 \\[sh-select] select loop
1267 \\[sh-until] until loop
1268 \\[sh-while] while loop
1270 For sh and rc shells indentation commands are:
1271 \\[sh-show-indent] Show the variable controlling this line's indentation.
1272 \\[sh-set-indent] Set then variable controlling this line's indentation.
1273 \\[sh-learn-line-indent] Change the indentation variable so this line
1274 would indent to the way it currently is.
1275 \\[sh-learn-buffer-indent] Set the indentation variables so the
1276 buffer indents as it currently is indented.
1279 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1280 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
1281 \\[sh-end-of-command] Go to end of successive commands.
1282 \\[sh-beginning-of-command] Go to beginning of successive commands.
1283 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1284 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1286 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
1288 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1290 If you generally program a shell different from your login shell you can
1291 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1292 indicate what shell it is use `sh-alias-alist' to translate.
1294 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1295 with your script for an edit-interpret-debug cycle."
1297 (kill-all-local-variables)
1298 (setq major-mode
'sh-mode
1299 mode-name
"Shell-script")
1300 (use-local-map sh-mode-map
)
1301 (make-local-variable 'skeleton-end-hook
)
1302 (make-local-variable 'paragraph-start
)
1303 (make-local-variable 'paragraph-separate
)
1304 (make-local-variable 'comment-start
)
1305 (make-local-variable 'comment-start-skip
)
1306 (make-local-variable 'require-final-newline
)
1307 (make-local-variable 'sh-header-marker
)
1308 (make-local-variable 'sh-shell-file
)
1309 (make-local-variable 'sh-shell
)
1310 (make-local-variable 'skeleton-pair-alist
)
1311 (make-local-variable 'skeleton-pair-filter
)
1312 (make-local-variable 'comint-dynamic-complete-functions
)
1313 (make-local-variable 'comint-prompt-regexp
)
1314 (make-local-variable 'font-lock-defaults
)
1315 (make-local-variable 'skeleton-filter
)
1316 (make-local-variable 'skeleton-newline-indent-rigidly
)
1317 (make-local-variable 'sh-shell-variables
)
1318 (make-local-variable 'sh-shell-variables-initialized
)
1319 (make-local-variable 'imenu-generic-expression
)
1320 (make-local-variable 'sh-indent-supported-here
)
1321 (setq skeleton-end-hook
(lambda ()
1322 (or (eolp) (newline) (indent-relative)))
1323 paragraph-start
(concat page-delimiter
"\\|$")
1324 paragraph-separate paragraph-start
1326 comint-dynamic-complete-functions sh-dynamic-complete-functions
1327 ;; we can't look if previous line ended with `\'
1328 comint-prompt-regexp
"^[ \t]*"
1330 `((sh-font-lock-keywords
1331 sh-font-lock-keywords-1 sh-font-lock-keywords-2
)
1333 ((?
/ .
"w") (?~ .
"w") (?. .
"w") (?- .
"w") (?_ .
"w")) nil
1334 (font-lock-syntactic-keywords . sh-font-lock-syntactic-keywords
)
1335 (font-lock-syntactic-face-function
1336 . sh-font-lock-syntactic-face-function
))
1337 skeleton-pair-alist
'((?
` _ ?
`))
1338 skeleton-pair-filter
'sh-quoted-p
1339 skeleton-further-elements
'((< '(- (min sh-indentation
1340 (current-column)))))
1341 skeleton-filter
'sh-feature
1342 skeleton-newline-indent-rigidly t
1343 sh-indent-supported-here nil
)
1344 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
1345 ;; Parse or insert magic number for exec, and set all variables depending
1346 ;; on the shell thus determined.
1349 (goto-char (point-min))
1350 (cond ((looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1352 ((and buffer-file-name
1353 (string-match "\\.m?spec$" buffer-file-name
))
1355 (sh-set-shell (or interpreter sh-shell-file
) nil nil
))
1356 (run-hooks 'sh-mode-hook
))
1359 (defalias 'shell-script-mode
'sh-mode
)
1362 (defun sh-font-lock-keywords (&optional keywords
)
1363 "Function to get simple fontification based on `sh-font-lock-keywords'.
1364 This adds rules for comments and assignments."
1365 (sh-feature sh-font-lock-keywords
1366 (when (stringp (sh-feature sh-assignment-regexp
))
1368 `((,(sh-feature sh-assignment-regexp
)
1369 1 font-lock-variable-name-face
)
1373 (defun sh-font-lock-keywords-1 (&optional builtins
)
1374 "Function to get better fontification including keywords."
1375 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1376 (regexp-opt (sh-feature sh-leading-keywords
) t
)
1378 (regexp-opt (append (sh-feature sh-leading-keywords
)
1379 (sh-feature sh-other-keywords
))
1381 (sh-font-lock-keywords
1383 `((,(concat keywords
"[ \t]+\\)?"
1384 (regexp-opt (sh-feature sh-builtins
) t
)
1386 (2 font-lock-keyword-face nil t
)
1387 (6 font-lock-builtin-face
))
1388 ,@(sh-feature sh-font-lock-keywords-2
)))
1389 (,(concat keywords
"\\)\\>")
1390 2 font-lock-keyword-face
)
1391 ,@(sh-feature sh-font-lock-keywords-1
)))))
1393 (defun sh-font-lock-keywords-2 ()
1394 "Function to get better fontification including keywords and builtins."
1395 (sh-font-lock-keywords-1 t
))
1398 (defvar sh-regexp-for-done nil
1399 "A buffer-local regexp to match opening keyword for done.")
1401 (defvar sh-kw-alist nil
1402 "A buffer-local, since it is shell-type dependent, list of keywords.")
1404 ;; ( key-word first-on-this on-prev-line )
1405 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1406 ;; having 3 elements:
1408 ;; a rule to check when the keyword appears on "this" line
1409 ;; a rule to check when the keyword appears on "the previous" line
1410 ;; The keyword is usually a string and is the first word on a line.
1411 ;; If this keyword appears on the line whose indentation is to be
1412 ;; calculated, the rule in element 2 is called. If this returns
1413 ;; non-zero, the resulting point (which may be changed by the rule)
1414 ;; is used as the default indentation.
1415 ;; If it returned false or the keyword was not found in the table,
1416 ;; then the keyword from the previous line is looked up and the rule
1417 ;; in element 3 is called. In this case, however,
1418 ;; `sh-get-indent-info' does not stop but may keep going and test
1419 ;; other keywords against rules in element 3. This is because the
1420 ;; preceding line could have, for example, an opening "if" and an
1421 ;; opening "while" keyword and we need to add the indentation offsets
1426 ("if" nil sh-handle-prev-if
)
1427 ("elif" sh-handle-this-else sh-handle-prev-else
)
1428 ("else" sh-handle-this-else sh-handle-prev-else
)
1429 ("fi" sh-handle-this-fi sh-handle-prev-fi
)
1430 ("then" sh-handle-this-then sh-handle-prev-then
)
1431 ("(" nil sh-handle-prev-open
)
1432 ("{" nil sh-handle-prev-open
)
1433 ("[" nil sh-handle-prev-open
)
1434 ("}" sh-handle-this-close nil
)
1435 (")" sh-handle-this-close nil
)
1436 ("]" sh-handle-this-close nil
)
1437 ("case" nil sh-handle-prev-case
)
1438 ("esac" sh-handle-this-esac sh-handle-prev-esac
)
1439 (case-label nil sh-handle-after-case-label
) ;; ???
1440 (";;" nil sh-handle-prev-case-alt-end
) ;; ???
1441 ("done" sh-handle-this-done sh-handle-prev-done
)
1442 ("do" sh-handle-this-do sh-handle-prev-do
))
1444 ;; Note: we don't need specific stuff for bash and zsh shells;
1445 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1446 ;; these shells use.
1448 ("{" nil sh-handle-prev-open
)
1449 ("}" sh-handle-this-close nil
)
1450 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case
))))
1453 (defun sh-set-shell (shell &optional no-query-flag insert-flag
)
1454 "Set this buffer's shell to SHELL (a string).
1455 When used interactively, insert the proper starting #!-line,
1456 and make the visited file executable via `executable-set-magic',
1457 perhaps querying depending on the value of `executable-query'.
1459 When this function is called noninteractively, INSERT-FLAG (the third
1460 argument) controls whether to insert a #!-line and think about making
1461 the visited file executable, and NO-QUERY-FLAG (the second argument)
1462 controls whether to query about making the visited file executable.
1464 Calls the value of `sh-set-shell-hook' if set."
1465 (interactive (list (completing-read (format "Shell \(default %s\): "
1467 interpreter-mode-alist
1468 (lambda (x) (eq (cdr x
) 'sh-mode
))
1469 nil nil nil sh-shell-file
)
1470 (eq executable-query
'function
)
1472 (if (string-match "\\.exe\\'" shell
)
1473 (setq shell
(substring shell
0 (match-beginning 0))))
1474 (setq sh-shell
(intern (file-name-nondirectory shell
))
1475 sh-shell
(or (cdr (assq sh-shell sh-alias-alist
))
1479 (executable-set-magic shell
(sh-feature sh-shell-arg
)
1480 no-query-flag insert-flag
)))
1481 (let ((tem (sh-feature sh-require-final-newline
)))
1482 (unless (eq tem
'require-final-newline
)
1483 (setq require-final-newline tem
)))
1485 comment-start-skip
"#+[\t ]*"
1486 ;;; local-abbrev-table (sh-feature sh-abbrevs)
1487 mode-line-process
(format "[%s]" sh-shell
)
1488 sh-shell-variables nil
1489 sh-shell-variables-initialized nil
1490 imenu-generic-expression
(sh-feature sh-imenu-generic-expression
)
1491 imenu-case-fold-search nil
)
1492 (make-local-variable 'sh-mode-syntax-table
)
1493 (let ((tem (sh-feature sh-mode-syntax-table-input
)))
1494 (setq sh-mode-syntax-table
1495 (if tem
(apply 'sh-mode-syntax-table tem
)
1496 sh-mode-default-syntax-table
)))
1497 (set-syntax-table sh-mode-syntax-table
)
1498 (dolist (var (sh-feature sh-variables
))
1499 (sh-remember-variable var
))
1500 (make-local-variable 'indent-line-function
)
1501 (if (setq sh-indent-supported-here
(sh-feature sh-indent-supported
))
1503 (message "Setting up indent for shell type %s" sh-shell
)
1504 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
1505 (set (make-local-variable 'sh-kw-alist
) (sh-feature sh-kw
))
1506 (let ((regexp (sh-feature sh-kws-for-done
)))
1508 (set (make-local-variable 'sh-regexp-for-done
)
1509 (sh-mkword-regexpr (regexp-opt regexp t
)))))
1510 (message "setting up indent stuff")
1511 ;; sh-mode has already made indent-line-function local
1512 ;; but do it in case this is called before that.
1513 (setq indent-line-function
'sh-indent-line
)
1514 (if sh-make-vars-local
1515 (sh-make-vars-local))
1516 (message "Indentation setup for shell type %s" sh-shell
))
1517 (message "No indentation for this shell type.")
1518 (setq indent-line-function
'sh-basic-indent-line
))
1519 (run-hooks 'sh-set-shell-hook
))
1523 (defun sh-feature (alist &optional function
)
1524 "Index ALIST by the current shell.
1525 If ALIST isn't a list where every element is a cons, it is returned as is.
1526 Else indexing follows an inheritance logic which works in two ways:
1528 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1529 the alist contains no value for the current shell.
1530 The ultimate default is always `sh'.
1532 - If the value thus looked up is a list starting with `sh-append',
1533 we call the function `sh-append' with the rest of the list as
1534 arguments, and use the value. However, the next element of the
1535 list is not used as-is; instead, we look it up recursively
1536 in ALIST to allow the function called to define the value for
1537 one shell to be derived from another shell.
1538 The value thus determined is physically replaced into the alist.
1540 Optional FUNCTION is applied to the determined value and the result is cached
1542 (or (if (consp alist
)
1544 (while (and l
(consp (car l
)))
1548 (cdr (assoc (setq function
(cons sh-shell function
)) alist
)))
1549 (let ((sh-shell sh-shell
)
1551 (while (and sh-shell
1552 (not (setq elt
(assq sh-shell alist
))))
1553 (setq sh-shell
(cdr (assq sh-shell sh-ancestor-alist
))))
1554 ;; If the shell is not known, treat it as sh.
1556 (setq elt
(assq 'sh alist
)))
1557 (if (and (consp (setq val
(cdr elt
)))
1558 (memq (car val
) '(sh-append sh-modify
)))
1562 (let ((sh-shell (car (cdr val
))))
1563 (if (assq sh-shell alist
)
1569 (list (cons function
1570 (setq sh-shell
(car function
)
1571 val
(funcall (cdr function
) val
))))))
1576 ;; I commented this out because nobody calls it -- rms.
1577 ;;(defun sh-abbrevs (ancestor &rest list)
1578 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
1579 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1580 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1581 ;;according to the remaining arguments NAMEi EXPANSIONi ...
1582 ;;EXPANSION may be either a string or a skeleton command."
1583 ;; (or (if (boundp sh-shell)
1584 ;; (symbol-value sh-shell))
1586 ;; (if (listp ancestor)
1587 ;; (nconc list ancestor))
1588 ;; (define-abbrev-table sh-shell ())
1589 ;; (if (vectorp ancestor)
1590 ;; (mapatoms (lambda (atom)
1592 ;; (define-abbrev (symbol-value sh-shell)
1593 ;; (symbol-name atom)
1594 ;; (symbol-value atom)
1595 ;; (symbol-function atom))))
1598 ;; (define-abbrev (symbol-value sh-shell)
1600 ;; (if (stringp (car (cdr list)))
1603 ;; (if (symbolp (car (cdr list)))
1604 ;; (car (cdr list))))
1605 ;; (setq list (cdr (cdr list)))))
1606 ;; (symbol-value sh-shell)))
1609 (defun sh-append (ancestor &rest list
)
1610 "Return list composed of first argument (a list) physically appended to rest."
1611 (nconc list ancestor
))
1614 (defun sh-modify (skeleton &rest list
)
1615 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1616 (setq skeleton
(copy-sequence skeleton
))
1618 (setcar (or (nthcdr (car list
) skeleton
)
1619 (error "Index %d out of bounds" (car list
)))
1621 (setq list
(nthcdr 2 list
)))
1625 (defun sh-basic-indent-line ()
1626 "Indent a line for Sh mode (shell script mode).
1627 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1628 Lines containing only comments are considered empty."
1630 (let ((previous (save-excursion
1631 (while (and (progn (beginning-of-line)
1635 (back-to-indentation)
1637 (eq (following-char) ?
#)))))
1641 (indent-to (if (eq this-command
'newline-and-indent
)
1643 (if (< (current-column)
1644 (setq current
(progn (back-to-indentation)
1646 (if (eolp) previous
0)
1647 (delete-region (point)
1648 (progn (beginning-of-line) (point)))
1650 (max previous
(* (1+ (/ current sh-indentation
))
1652 (* (1+ (/ current sh-indentation
)) sh-indentation
))))))
1653 (if (< (current-column) (current-indentation))
1654 (skip-chars-forward " \t"))))
1657 (defun sh-execute-region (start end
&optional flag
)
1658 "Pass optional header and region to a subshell for noninteractive execution.
1659 The working directory is that of the buffer, and only environment variables
1660 are already set which is why you can mark a header within the script.
1662 With a positive prefix ARG, instead of sending region, define header from
1663 beginning of buffer to point. With a negative prefix ARG, instead of sending
1664 region, clear header."
1665 (interactive "r\nP")
1667 (setq sh-header-marker
(if (> (prefix-numeric-value flag
) 0)
1669 (if sh-header-marker
1671 (let (buffer-undo-list)
1672 (goto-char sh-header-marker
)
1673 (append-to-buffer (current-buffer) start end
)
1674 (shell-command-on-region (point-min)
1675 (setq end
(+ sh-header-marker
1678 (delete-region sh-header-marker end
)))
1679 (shell-command-on-region start end
(concat sh-shell-file
" -")))))
1682 (defun sh-remember-variable (var)
1683 "Make VARIABLE available for future completing reads in this buffer."
1684 (or (< (length var
) sh-remember-variable-min
)
1686 (assoc var sh-shell-variables
)
1687 (push (cons var var
) sh-shell-variables
))
1692 (defun sh-quoted-p ()
1693 "Is point preceded by an odd number of backslashes?"
1694 (eq -
1 (%
(save-excursion (skip-chars-backward "\\\\")) 2)))
1696 ;; Indentation stuff.
1697 (defun sh-must-support-indent ()
1698 "*Signal an error if the shell type for this buffer is not supported.
1699 Also, the buffer must be in Shell-script mode."
1700 (unless sh-indent-supported-here
1701 (error "This buffer's shell does not support indentation through Emacs")))
1703 (defun sh-make-vars-local ()
1704 "Make the indentation variables local to this buffer.
1705 Normally they already are local. This command is provided in case
1706 variable `sh-make-vars-local' has been set to nil.
1708 To revert all these variables to the global values, use
1709 command `sh-reset-indent-vars-to-global-values'."
1711 (mapcar 'make-local-variable sh-var-list
)
1712 (message "Indentation variable are now local."))
1714 (defun sh-reset-indent-vars-to-global-values ()
1715 "Reset local indentation variables to the global values.
1716 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1718 (mapcar 'kill-local-variable sh-var-list
)
1719 (if sh-make-vars-local
1720 (mapcar 'make-local-variable sh-var-list
)))
1723 ;; Theoretically these are only needed in shell and derived modes.
1724 ;; However, the routines which use them are only called in those modes.
1725 (defconst sh-special-keywords
"then\\|do")
1727 (defun sh-help-string-for-variable (var)
1728 "Construct a string for `sh-read-variable' when changing variable VAR ."
1729 (let ((msg (documentation-property var
'variable-documentation
))
1731 (unless (memq var
'(sh-first-lines-indent sh-indent-comment
))
1734 You can enter a number (positive to increase indentation,
1735 negative to decrease indentation, zero for no change to indentation).
1737 Or, you can enter one of the following symbols which are relative to
1738 the value of variable `sh-basic-offset'
1739 which in this buffer is currently %s.
1743 (mapconcat (lambda (x)
1744 (nth (1- (length x
)) x
))
1745 sh-symbol-list
"\n\t"))))
1747 ;; The following shows the global not the local value!
1748 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1751 (defun sh-read-variable (var)
1752 "Read a new value for indentation variable VAR."
1753 (interactive "*variable? ") ;; to test
1754 (let ((minibuffer-help-form `(sh-help-string-for-variable
1757 (setq val
(read-from-minibuffer
1758 (format "New value for %s (press %s for help): "
1759 var
(single-key-description help-char
))
1760 (format "%s" (symbol-value var
))
1766 (defun sh-in-comment-or-string (start)
1767 "Return non-nil if START is in a comment or string."
1769 (let ((state (syntax-ppss start
)))
1770 (or (nth 3 state
) (nth 4 state
)))))
1772 (defun sh-goto-matching-if ()
1773 "Go to the matching if for a fi.
1774 This handles nested if..fi pairs."
1775 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1777 (goto-char found
))))
1780 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1781 ;; line whose indentation is being handled contain XXX;
1782 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
1784 (defun sh-handle-prev-if ()
1785 (list '(+ sh-indent-after-if
)))
1787 (defun sh-handle-this-else ()
1788 (if (sh-goto-matching-if)
1789 ;; (list "aligned to if")
1790 (list "aligned to if" '(+ sh-indent-for-else
))
1794 (defun sh-handle-prev-else ()
1795 (if (sh-goto-matching-if)
1796 (list '(+ sh-indent-after-if
))
1799 (defun sh-handle-this-fi ()
1800 (if (sh-goto-matching-if)
1801 (list "aligned to if" '(+ sh-indent-for-fi
))
1805 (defun sh-handle-prev-fi ()
1806 ;; Why do we have this rule? Because we must go back to the if
1807 ;; to get its indent. We may continue back from there.
1808 ;; We return nil because we don't have anything to add to result,
1809 ;; the side affect of setting align-point is all that matters.
1810 ;; we could return a comment (a string) but I can't think of a good one...
1811 (sh-goto-matching-if)
1814 (defun sh-handle-this-then ()
1815 (let ((p (sh-goto-matching-if)))
1817 (list '(+ sh-indent-for-then
))
1820 (defun sh-handle-prev-then ()
1821 (let ((p (sh-goto-matching-if)))
1823 (list '(+ sh-indent-after-if
))
1826 (defun sh-handle-prev-open ()
1828 (let ((x (sh-prev-stmt)))
1833 (looking-at "function\\b")
1834 (looking-at "\\s-*\\S-+\\s-*()")
1836 (list '(+ sh-indent-after-function
))
1837 (list '(+ sh-indent-after-open
)))
1840 (defun sh-handle-this-close ()
1841 (forward-char 1) ;; move over ")"
1842 (if (sh-safe-forward-sexp -
1)
1843 (list "aligned to opening paren")))
1845 (defun sh-goto-matching-case ()
1846 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
1847 (if found
(goto-char found
))))
1849 (defun sh-handle-prev-case ()
1850 ;; This is typically called when point is on same line as a case
1851 ;; we shouldn't -- and can't find prev-case
1852 (if (looking-at ".*\\<case\\>")
1853 (list '(+ sh-indent-for-case-label
))
1854 (error "We don't seem to be on a line with a case"))) ;; debug
1856 (defun sh-handle-this-esac ()
1857 (if (sh-goto-matching-case)
1858 (list "aligned to matching case")))
1860 (defun sh-handle-prev-esac ()
1861 (if (sh-goto-matching-case)
1862 (list "matching case")))
1864 (defun sh-handle-after-case-label ()
1865 (if (sh-goto-matching-case)
1866 (list '(+ sh-indent-for-case-alt
))))
1868 (defun sh-handle-prev-case-alt-end ()
1869 (if (sh-goto-matching-case)
1870 (list '(+ sh-indent-for-case-label
))))
1872 (defun sh-safe-forward-sexp (&optional arg
)
1873 "Try and do a `forward-sexp', but do not error.
1874 Return new point if successful, nil if an error occurred."
1877 (forward-sexp (or arg
1))
1878 (point)) ;; return point if successful
1880 (sh-debug "oops!(1) %d" (point))
1881 nil
))) ;; return nil if fail
1883 (defun sh-goto-match-for-done ()
1884 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done
1)))
1886 (goto-char found
))))
1888 (defun sh-handle-this-done ()
1889 (if (sh-goto-match-for-done)
1890 (list "aligned to do stmt" '(+ sh-indent-for-done
))))
1892 (defun sh-handle-prev-done ()
1893 (if (sh-goto-match-for-done)
1894 (list "previous done")))
1896 (defun sh-handle-this-do ()
1897 (if (sh-goto-match-for-done)
1898 (list '(+ sh-indent-for-do
))))
1900 (defun sh-handle-prev-do ()
1908 (sh-goto-match-for-done))
1909 (sh-debug "match for done found on THIS line")
1910 (list '(+ sh-indent-after-loop-construct
)))
1911 ((sh-goto-match-for-done)
1912 (sh-debug "match for done found on PREV line")
1913 (list '(+ sh-indent-after-do
)))
1915 (message "match for done NOT found")
1919 (defun sh-find-prev-switch ()
1920 "Find the line for the switch keyword matching this line's case keyword."
1921 (re-search-backward "\\<switch\\>" nil t
))
1923 (defun sh-handle-this-rc-case ()
1924 (if (sh-find-prev-switch)
1925 (list '(+ sh-indent-after-switch
))
1926 ;; (list '(+ sh-indent-for-case-label))
1929 (defun sh-handle-prev-rc-case ()
1930 (list '(+ sh-indent-after-case
)))
1932 (defun sh-check-rule (n thing
)
1933 (let ((rule (nth n
(assoc thing sh-kw-alist
)))
1937 (setq val
(funcall rule
))
1938 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
1939 n thing
(point) rule val
)))
1943 (defun sh-get-indent-info ()
1944 "Return indent-info for this line.
1945 This is a list. nil means the line is to be left as is.
1946 Otherwise it contains one or more of the following sublists:
1947 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
1948 relative to. If present, this is always the first of the
1949 sublists. The indentation of the line in question is
1950 derived from the indentation of this point, possibly
1951 modified by subsequent sublists.
1953 \(- VAR\) Get the value of variable VAR and add to or subtract from
1954 the indentation calculated so far.
1955 \(= VAR\) Get the value of variable VAR and *replace* the
1956 indentation with its value. This only occurs for
1957 special variables such as `sh-indent-comment'.
1958 STRING This is ignored for the purposes of calculating
1959 indentation, it is printed in certain cases to help show
1960 what the indentation is based on."
1961 ;; See comments before `sh-kw'.
1963 (let ((have-result nil
)
1971 ;; Note: setting result to t means we are done and will return nil.
1972 ;;(This function never returns just t.)
1974 ((or (and (boundp 'font-lock-string-face
) (not (bobp))
1975 (eq (get-text-property (1- (point)) 'face
)
1976 font-lock-string-face
))
1977 (eq (get-text-property (point) 'face
) sh-heredoc-face
))
1979 (setq have-result t
))
1980 ((looking-at "\\s-*#") ; was (equal this-kw "#")
1982 (setq result t
) ;; return nil if 1st line!
1983 (setq result
(list '(= sh-indent-comment
)))
1984 ;; we still need to get previous line in case
1985 ;; sh-indent-comment is t (indent as normal)
1986 (setq align-point
(sh-prev-line nil
))
1987 (setq have-result nil
)
1992 ;; Continuation lines are handled specially
1993 (if (sh-this-is-a-continuation)
1995 ;; We assume the line being continued is already
1996 ;; properly indented...
1997 ;; (setq prev-line-end (sh-prev-line))
1998 (setq align-point
(sh-prev-line nil
))
1999 (setq result
(list '(+ sh-indent-for-continuation
)))
2000 (setq have-result t
))
2002 (skip-chars-forward " \t")
2003 (setq this-kw
(sh-get-kw)))
2005 ;; Handle "this" keyword: first word on the line we're
2006 ;; calculating indentation info for.
2008 (if (setq val
(sh-check-rule 1 this-kw
))
2010 (setq align-point
(point))
2012 "this - setting align-point to %d" align-point
)
2013 (setq result
(append result val
))
2014 (setq have-result t
)
2015 ;; set prev-line to continue processing remainder
2016 ;; of this line as a previous line
2017 (setq prev-line-end
(point))
2021 (setq prev-line-end
(sh-prev-line 'end
)))
2025 ;; We start off at beginning of this line.
2026 ;; Scan previous statements while this is <=
2027 ;; start of previous line.
2028 (setq start
(point)) ;; for debug only
2029 (goto-char prev-line-end
)
2031 (while (and x
(setq x
(sh-prev-thing)))
2032 (sh-debug "at %d x is: %s result is: %s" (point) x result
)
2035 (equal (get-text-property (1- (point)) 'syntax-table
)
2037 (sh-debug "Case label) here")
2038 (setq x
'case-label
)
2039 (if (setq val
(sh-check-rule 2 x
))
2041 (setq result
(append result val
))
2042 (setq align-point
(point))))
2045 (skip-chars-forward "[a-z0-9]*?")
2047 ((string-match "[])}]" x
)
2048 (setq x
(sh-safe-forward-sexp -
1))
2051 (setq align-point
(point))
2052 (setq result
(append result
2053 (list "aligned to opening paren")))
2055 ((string-match "[[({]" x
)
2056 (sh-debug "Checking special thing: %s" x
)
2057 (if (setq val
(sh-check-rule 2 x
))
2058 (setq result
(append result val
)))
2060 (setq align-point
(point)))
2061 ((string-match "[\"'`]" x
)
2062 (sh-debug "Skipping back for %s" x
)
2064 (setq x
(sh-safe-forward-sexp -
1)))
2066 (sh-debug "Checking string %s at %s" x
(point))
2067 (if (setq val
(sh-check-rule 2 x
))
2068 ;; (or (eq t (car val))
2069 ;; (eq t (car (car val))))
2070 (setq result
(append result val
)))
2071 ;; not sure about this test Wed Jan 27 23:48:35 1999
2072 (setq align-point
(point))
2076 (error "Don't know what to do with %s" x
))
2079 (sh-debug "result is %s" result
)
2081 (sh-debug "No prev line!")
2082 (sh-debug "result: %s align-point: %s" result align-point
)
2086 ;; was: (setq result (append result (list (list t align-point))))
2087 (setq result
(append (list (list t align-point
)) result
))
2089 (sh-debug "result is now: %s" result
)
2093 (setq result
(list (list t prev-line-end
)))
2094 (setq result
(list (list '= 'sh-first-lines-indent
)))
2099 (sh-debug "result is: %s" result
)
2105 (defun sh-get-indent-var-for-line (&optional info
)
2106 "Return the variable controlling indentation for this line.
2107 If there is not [just] one such variable, return a string
2108 indicating the problem.
2109 If INFO is supplied it is used, else it is calculated."
2115 (setq info
(sh-get-indent-info)))
2117 (setq result
"this line to be left as is")
2118 (while (and info
(null result
))
2119 (setq elt
(car info
))
2125 (error "sh-get-indent-var-for-line invalid elt: %s" elt
))
2129 ((symbolp (setq sym
(nth 1 elt
)))
2130 ;; A bit of a kludge - when we see the sh-indent-comment
2131 ;; ignore other variables. Otherwise it is tricky to
2132 ;; "learn" the comment indentation.
2133 (if (eq var
'sh-indent-comment
)
2137 "this line is controlled by more than 1 variable.")
2140 (error "sh-get-indent-var-for-line invalid list elt: %s" elt
)))
2141 (setq info
(cdr info
))
2146 (setq result reason
))
2148 ;; e.g. just had (t POS)
2149 (setq result
"line has default indentation"))
2154 ;; Finding the previous line isn't trivial.
2155 ;; We must *always* go back one more and see if that is a continuation
2156 ;; line -- it is the PREVIOUS line which is continued, not the one
2158 ;; Also, we want to treat a whole "here document" as one big line,
2159 ;; because we may want to a align to the beginning of it.
2162 ;; - go back to previous non-empty line
2163 ;; - if this is in a here-document, go to the beginning of it
2164 ;; - while previous line is continued, go back one line
2165 (defun sh-prev-line (&optional end
)
2166 "Back to end of previous non-comment non-empty line.
2167 Go to beginning of logical line unless END is non-nil, in which case
2168 we go to the end of the previous line and do not check for continuations."
2171 (forward-comment (- (point-max)))
2172 (unless end
(beginning-of-line))
2173 (when (and (not (bobp))
2174 (equal (get-text-property (1- (point)) 'face
)
2176 (let ((p1 (previous-single-property-change (1- (point)) 'face
)))
2181 (beginning-of-line)))))
2183 ;; we must check previous lines to see if they are continuation lines
2184 ;; if so, we must return position of first of them
2185 (while (and (sh-this-is-a-continuation)
2186 (>= 0 (forward-line -
1))))
2188 (skip-chars-forward " \t"))
2192 (defun sh-prev-stmt ()
2193 "Return the address of the previous stmt or nil."
2194 ;; This is used when we are trying to find a matching keyword.
2195 ;; Searching backward for the keyword would certainly be quicker, but
2196 ;; it is hard to remove "false matches" -- such as if the keyword
2197 ;; appears in a string or quote. This way is slower, but (I think) safer.
2204 (skip-chars-backward " \t;|&({[")
2205 (while (and (not found
)
2208 ;; Do a backward-sexp if possible, else backup bit by bit...
2209 (if (sh-safe-forward-sexp -
1)
2211 (if (looking-at sh-special-keywords
)
2216 ;; backward-sexp failed
2217 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2220 (let ((back (sh-prev-line nil
)))
2223 (setq going nil
)))))
2225 (skip-chars-backward " \t")
2226 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2227 (eq (char-before) ?\
;)
2228 (looking-at "\\s-*[|&]"))
2229 (setq found
(point)))))
2234 (skip-chars-forward " \t|&({[")
2235 (setq found
(point))))
2236 (if (>= (point) start
)
2238 (debug "We didn't move!")
2241 (sh-debug "Did not find prev stmt.")))
2245 (defun sh-get-word ()
2246 "Get a shell word skipping whitespace from point."
2248 (skip-chars-forward "\t ")
2249 (let ((start (point)))
2251 (if (looking-at "[\"'`]")
2252 (sh-safe-forward-sexp)
2253 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2254 (> (skip-chars-forward "-_a-zA-Z\$0-9") 0)
2256 (buffer-substring start
(point))
2259 (defun sh-prev-thing ()
2260 "Return the previous thing this logical line."
2261 ;; This is called when `sh-get-indent-info' is working backwards on
2262 ;; the previous line(s) finding what keywords may be relevant for
2263 ;; indenting. It moves over sexps if possible, and will stop
2264 ;; on a ; and at the beginning of a line if it is not a continuation
2267 ;; Added a kludge for ";;"
2268 ;; Possible return values:
2270 ;; a string - possibly a keyword
2278 (if (sh-this-is-a-continuation)
2279 (setq min-point
(sh-prev-line nil
))
2282 (setq min-point
(point))))
2284 (skip-chars-backward " \t;")
2285 (unless (looking-at "\\s-*;;")
2286 (skip-chars-backward "^)}];\"'`({[")
2287 (setq c
(char-before))))
2288 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2289 (point) c start min-point
)
2290 (if (< (point) min-point
)
2291 (error "point %d < min-point %d" (point) min-point
))
2293 ((looking-at "\\s-*;;")
2294 ;; (message "Found ;; !")
2300 ;; skip forward over white space newline and \ at eol
2301 (skip-chars-forward " \t\n\\\\")
2302 (sh-debug "Now at %d start=%d" (point) start
)
2303 (if (>= (point) start
)
2305 (sh-debug "point: %d >= start: %d" (point) start
)
2310 ;; c -- return a string
2316 (defun sh-this-is-a-continuation ()
2317 "Return non-nil if current line is a continuation of previous line."
2319 (and (zerop (forward-line -
1))
2320 (looking-at ".*\\\\$")
2321 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2324 (defun sh-get-kw (&optional where and-move
)
2325 "Return first word of line from WHERE.
2326 If AND-MOVE is non-nil then move to end of word."
2327 (let ((start (point)))
2331 (buffer-substring (point)
2332 (progn (skip-chars-forward "^ \t\n;")(point)))
2334 (goto-char start
)))))
2336 (defun sh-find-prev-matching (open close
&optional depth
)
2337 "Find a matching token for a set of opening and closing keywords.
2338 This takes into account that there may be nested open..close pairings.
2339 OPEN and CLOSE are regexps denoting the tokens to be matched.
2340 Optional parameter DEPTH (usually 1) says how many to look for."
2341 (let ((parse-sexp-ignore-comments t
)
2343 (setq depth
(or depth
1))
2349 (setq prev
(sh-prev-stmt)))
2352 (if (looking-at "\\\\\n")
2355 (skip-chars-forward " \t")))
2358 (setq depth
(1- depth
))
2359 (sh-debug "found open at %d - depth = %d" (point) depth
))
2361 (setq depth
(1+ depth
))
2362 (sh-debug "found close - depth = %d" depth
))
2372 (defun sh-var-value (var &optional ignore-error
)
2373 "Return the value of variable VAR, interpreting symbols.
2374 It can also return t or nil.
2375 If an illegal value is found, throw an error unless Optional argument
2376 IGNORE-ERROR is non-nil."
2377 (let ((val (symbol-value var
)))
2388 (- sh-basic-offset
))
2390 (* 2 sh-basic-offset
))
2392 (* 2 (- sh-basic-offset
)))
2394 (/ sh-basic-offset
2))
2396 (/ (- sh-basic-offset
) 2))
2400 (message "Don't know how to handle %s's value of %s" var val
)
2402 (error "Don't know how to handle %s's value of %s" var val
))
2405 (defun sh-set-var-value (var value
&optional no-symbol
)
2406 "Set variable VAR to VALUE.
2407 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2408 can be represented by a symbol then do so."
2412 ((= value sh-basic-offset
)
2414 ((= value
(- sh-basic-offset
))
2416 ((eq value
(* 2 sh-basic-offset
))
2418 ((eq value
(* 2 (- sh-basic-offset
)))
2420 ((eq value
(/ sh-basic-offset
2))
2422 ((eq value
(/ (- sh-basic-offset
) 2))
2429 (defun sh-calculate-indent (&optional info
)
2430 "Return the indentation for the current line.
2431 If INFO is supplied it is used, else it is calculated from current line."
2436 (setq info
(sh-get-indent-info)))
2439 (sh-debug "info: %s ofs=%s" info ofs
)
2440 (setq elt
(car info
))
2442 ((stringp elt
)) ;; do nothing?
2444 (setq a
(car (car info
)))
2445 (setq b
(nth 1 (car info
)))
2450 (setq val
(current-indentation)))
2451 (setq base-value val
))
2453 (setq val
(sh-var-value b
))
2459 ;; set info to nil so we stop immediately
2460 (setq base-value nil ofs nil info nil
))
2461 ((eq val t
) (setq ofs
0)) ;; indent as normal line
2463 ;; The following assume the (t POS) come first!
2464 (setq ofs val base-value
0)
2465 (setq info nil
)))) ;; ? stop now
2466 ((eq a
'+) (setq ofs
(+ ofs val
)))
2467 ((eq a
'-
) (setq ofs
(- ofs val
)))
2469 (error "sh-calculate-indent invalid a a=%s b=%s" a b
))))
2471 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b
))))
2473 (error "sh-calculate-indent invalid elt %s" elt
)))
2474 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2475 a b val base-value ofs
)
2476 (setq info
(cdr info
)))
2478 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs
)
2481 ((or (null base-value
)(null ofs
))
2483 ((and (numberp base-value
)(numberp ofs
))
2484 (sh-debug "base (%d) + ofs (%d) = %d"
2485 base-value ofs
(+ base-value ofs
))
2486 (+ base-value ofs
)) ;; return value
2488 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2493 (defun sh-indent-line ()
2494 "Indent the current line."
2496 (let ((indent (sh-calculate-indent))
2497 (pos (- (point-max) (point))))
2500 (skip-chars-forward " \t")
2501 (indent-line-to indent
)
2502 ;; If initial point was within line's indentation,
2503 ;; position after the indentation. Else stay at same point in text.
2504 (if (> (- (point-max) pos
) (point))
2505 (goto-char (- (point-max) pos
))))))
2508 (defun sh-blink (blinkpos &optional msg
)
2509 "Move cursor momentarily to BLINKPOS and display MSG."
2510 ;; We can get here without it being a number on first line
2511 (if (numberp blinkpos
)
2513 (goto-char blinkpos
)
2515 (sit-for blink-matching-delay
))
2518 (defun sh-show-indent (arg)
2519 "Show the how the currently line would be indented.
2520 This tells you which variable, if any, controls the indentation of
2522 If optional arg ARG is non-null (called interactively with a prefix),
2523 a pop up window describes this variable.
2524 If variable `sh-blink' is non-nil then momentarily go to the line
2525 we are indenting relative to, if applicable."
2527 (sh-must-support-indent)
2528 (let* ((info (sh-get-indent-info))
2529 (var (sh-get-indent-var-for-line info
))
2530 (curr-indent (current-indentation))
2533 (message (setq msg var
))
2534 (setq val
(sh-calculate-indent info
))
2536 (if (eq curr-indent val
)
2537 (setq msg
(format "%s is %s" var
(symbol-value var
)))
2540 (format "%s (%s) would change indent from %d to: %d"
2541 var
(symbol-value var
) curr-indent val
)
2542 (format "%s (%s) would leave line as is"
2543 var
(symbol-value var
)))
2546 (describe-variable var
)))
2548 (let ((info (sh-get-indent-info)))
2549 (if (and info
(listp (car info
))
2550 (eq (car (car info
)) t
))
2551 (sh-blink (nth 1 (car info
)) msg
)
2556 (defun sh-set-indent ()
2557 "Set the indentation for the current line.
2558 If the current line is controlled by an indentation variable, prompt
2559 for a new value for it."
2561 (sh-must-support-indent)
2562 (let* ((info (sh-get-indent-info))
2563 (var (sh-get-indent-var-for-line info
))
2564 val old-val indent-val
)
2566 (message (format "Cannot set indent - %s" var
))
2567 (setq old-val
(symbol-value var
))
2568 (setq val
(sh-read-variable var
))
2572 (setq indent-val
(sh-calculate-indent info
))
2574 (message "Variable: %s Value: %s would indent to: %d"
2575 var
(symbol-value var
) indent-val
)
2576 (message "Variable: %s Value: %s would leave line as is."
2577 var
(symbol-value var
)))
2578 ;; I'm not sure about this, indenting it now?
2579 ;; No. Because it would give the impression that an undo would
2580 ;; restore thing, but the value has been altered.
2585 (message "Bad value for %s, restoring to previous value %s"
2592 (defun sh-learn-line-indent (arg)
2593 "Learn how to indent a line as it currently is indented.
2595 If there is an indentation variable which controls this line's indentation,
2596 then set it to a value which would indent the line the way it
2599 If the value can be represented by one of the symbols then do so
2600 unless optional argument ARG (the prefix when interactive) is non-nil."
2602 (sh-must-support-indent)
2603 ;; I'm not sure if we show allow learning on an empty line.
2604 ;; Though it might occasionally be useful I think it usually
2605 ;; would just be confusing.
2608 (looking-at "\\s-*$"))
2609 (message "sh-learn-line-indent ignores empty lines.")
2610 (let* ((info (sh-get-indent-info))
2611 (var (sh-get-indent-var-for-line info
))
2612 ival sval diff new-val
2614 (curr-indent (current-indentation)))
2617 (message (format "Cannot learn line - %s" var
)))
2618 ((eq var
'sh-indent-comment
)
2619 ;; This is arbitrary...
2620 ;; - if curr-indent is 0, set to curr-indent
2621 ;; - else if it has the indentation of a "normal" line,
2623 ;; - else set to curr-indent.
2624 (setq sh-indent-comment
2625 (if (= curr-indent
0)
2627 (let* ((sh-indent-comment t
)
2628 (val2 (sh-calculate-indent info
)))
2629 (if (= val2 curr-indent
)
2632 (message "%s set to %s" var
(symbol-value var
))
2634 ((numberp (setq sval
(sh-var-value var
)))
2635 (setq ival
(sh-calculate-indent info
))
2636 (setq diff
(- curr-indent ival
))
2638 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2639 curr-indent ival diff var sval
)
2640 (setq new-val
(+ sval diff
))
2641 ;;; I commented out this because someone might want to replace
2642 ;;; a value of `+' with the current value of sh-basic-offset
2645 ;;; (message "No change needed!")
2646 (sh-set-var-value var new-val no-symbol
)
2647 (message "%s set to %s" var
(symbol-value var
))
2651 (message "Cannot change %s" var
))))))
2655 (defun sh-mark-init (buffer)
2656 "Initialize a BUFFER to be used by `sh-mark-line'."
2658 (set-buffer (get-buffer-create buffer
))
2664 (defun sh-mark-line (message point buffer
&optional add-linenum occur-point
)
2665 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2666 Buffer BUFFER is in `occur-mode'.
2667 If ADD-LINENUM is non-nil the message is preceded by the line number.
2668 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2669 so that `occur-next' and `occur-prev' will work."
2670 (let ((m1 (make-marker))
2674 (set-marker m1 point
(current-buffer))
2676 (setq line
(format "%d: " (1+ (count-lines 1 point
))))))
2678 (if (get-buffer buffer
)
2679 (set-buffer (get-buffer buffer
))
2680 (set-buffer (get-buffer-create buffer
))
2683 (goto-char (point-max))
2684 (setq start
(point))
2687 (setq occur-point
(point)))
2690 (add-text-properties
2692 '(mouse-face highlight
2693 help-echo
"mouse-2: go to the line where I learned this")))
2697 (put-text-property start
(point) 'occur-target m1
)
2699 (put-text-property start occur-point
2706 ;; Is this really worth having?
2707 (defvar sh-learned-buffer-hook nil
2708 "*An abnormal hook, called with an alist of learned variables.")
2709 ;; Example of how to use sh-learned-buffer-hook
2711 ;; (defun what-i-learned (list)
2714 ;; (set-buffer "*scratch*")
2715 ;; (goto-char (point-max))
2716 ;; (insert "(setq\n")
2718 ;; (insert (format " %s %s \n"
2719 ;; (nth 0 (car p)) (nth 1 (car p))))
2720 ;; (setq p (cdr p)))
2724 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2727 ;; Originally this was sh-learn-region-indent (beg end)
2728 ;; However, in practice this was awkward so I changed it to
2729 ;; use the whole buffer. Use narrowing if needbe.
2730 (defun sh-learn-buffer-indent (&optional arg
)
2731 "Learn how to indent the buffer the way it currently is.
2733 Output in buffer \"*indent*\" shows any lines which have conflicting
2734 values of a variable, and the final value of all variables learned.
2735 This buffer is popped to automatically if there are any discrepancies.
2737 If no prefix ARG is given, then variables are set to numbers.
2738 If a prefix arg is given, then variables are set to symbols when
2739 applicable -- e.g. to symbol `+' if the value is that of the
2741 If a positive numerical prefix is given, then `sh-basic-offset'
2742 is set to the prefix's numerical value.
2743 Otherwise, sh-basic-offset may or may not be changed, according
2744 to the value of variable `sh-learn-basic-offset'.
2746 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2747 function completes. The function is abnormal because it is called
2748 with an alist of variables learned. This feature may be changed or
2749 removed in the future.
2751 This command can often take a long time to run."
2753 (sh-must-support-indent)
2755 (goto-char (point-min))
2756 (let ((learned-var-list nil
)
2757 (out-buffer "*indent*")
2763 (comment-col nil
) ;; number if all same, t if seen diff values
2764 (comments-always-default t
) ;; nil if we see one not default
2766 (specified-basic-offset (and arg
(numberp arg
)
2770 (setq vec
(make-vector max
0))
2771 (sh-mark-init out-buffer
)
2773 (if specified-basic-offset
2775 (setq sh-basic-offset arg
)
2777 (format "Using specified sh-basic-offset of %d"
2780 (format "Initial value of sh-basic-offset: %s"
2783 (while (< (point) (point-max))
2784 (setq linenum
(1+ linenum
))
2785 ;; (if (zerop (% linenum 10))
2786 (message "line %d" linenum
)
2788 (unless (looking-at "\\s-*$") ;; ignore empty lines!
2789 (let* ((sh-indent-comment t
) ;; info must return default indent
2790 (info (sh-get-indent-info))
2791 (var (sh-get-indent-var-for-line info
))
2792 sval ival diff new-val
2793 (curr-indent (current-indentation)))
2799 ((numberp (setq sval
(sh-var-value var
'no-error
)))
2800 ;; the numberp excludes comments since sval will be t.
2801 (setq ival
(sh-calculate-indent))
2802 (setq diff
(- curr-indent ival
))
2803 (setq new-val
(+ sval diff
))
2804 (sh-set-var-value var new-val
'no-symbol
)
2805 (unless (looking-at "\\s-*#") ;; don't learn from comments
2806 (if (setq previous-set-info
(assoc var learned-var-list
))
2808 ;; it was already there, is it same value ?
2809 (unless (eq (symbol-value var
)
2810 (nth 1 previous-set-info
))
2812 (format "Variable %s was set to %s"
2813 var
(symbol-value var
))
2814 (point) out-buffer t t
)
2816 (format " but was previously set to %s"
2817 (nth 1 previous-set-info
))
2818 (nth 2 previous-set-info
) out-buffer t
)
2819 (setq num-diffs
(1+ num-diffs
))
2820 ;; (delete previous-set-info learned-var-list)
2821 (setcdr previous-set-info
2822 (list (symbol-value var
) (point)))
2825 (setq learned-var-list
2826 (append (list (list var
(symbol-value var
)
2829 (if (numberp new-val
)
2832 "This line's indent value: %d" new-val
)
2834 (setq new-val
(- new-val
)))
2836 (aset vec new-val
(1+ (aref vec new-val
))))))
2838 ((eq var
'sh-indent-comment
)
2839 (unless (= curr-indent
(sh-calculate-indent info
))
2840 ;; this is not the default indentation
2841 (setq comments-always-default nil
)
2842 (if comment-col
;; then we have see one before
2843 (or (eq comment-col curr-indent
)
2844 (setq comment-col t
)) ;; seen a different one
2845 (setq comment-col curr-indent
))
2848 (sh-debug "Cannot learn this line!!!")
2851 "at %s learned-var-list is %s" (point) learned-var-list
)
2858 "comment-col = %s comments-always-default = %s"
2859 comment-col comments-always-default
))
2861 (sh-mark-line msg nil out-buffer
)))
2864 (setq msg
"\nComments are all in 1st column.\n"))
2865 (comments-always-default
2866 (setq msg
"\nComments follow default indentation.\n")
2867 (setq comment-col t
))
2868 ((numberp comment-col
)
2869 (setq msg
(format "\nComments are in col %d." comment-col
)))
2871 (setq msg
"\nComments seem to be mixed, leaving them as is.\n")
2872 (setq comment-col nil
)
2875 (sh-mark-line msg nil out-buffer
)
2877 (sh-mark-line initial-msg nil out-buffer t t
)
2879 (setq suggested
(sh-guess-basic-offset vec
))
2881 (if (and suggested
(not specified-basic-offset
))
2884 ;; t => set it if we have a single value as a number
2885 ((and (eq sh-learn-basic-offset t
) (numberp suggested
))
2887 ;; other non-nil => set it if only one value was found
2888 (sh-learn-basic-offset
2889 (if (numberp suggested
)
2891 (if (= (length suggested
) 1)
2897 (setq learned-var-list
2898 (append (list (list 'sh-basic-offset
2899 (setq sh-basic-offset new-value
)
2902 ;; Not sure if we need to put this line in, since
2903 ;; it will appear in the "Learned variable settings".
2905 (format "Changed sh-basic-offset to: %d" sh-basic-offset
)
2908 (if (listp suggested
)
2909 (format "Possible value(s) for sh-basic-offset: %s"
2910 (mapconcat 'int-to-string suggested
" "))
2911 (format "Suggested sh-basic-offset: %d" suggested
))
2915 (setq learned-var-list
2916 (append (list (list 'sh-indent-comment comment-col
(point-max)))
2918 (setq sh-indent-comment comment-col
)
2919 (let ((name (buffer-name)))
2920 (sh-mark-line "\nLearned variable settings:" nil out-buffer
)
2922 ;; Set learned variables to symbolic rather than numeric
2923 ;; values where possible.
2924 (dolist (learned-var (reverse learned-var-list
))
2925 (let ((var (car learned-var
))
2926 (val (nth 1 learned-var
)))
2927 (when (and (not (eq var
'sh-basic-offset
))
2929 (sh-set-var-value var val
)))))
2930 (dolist (learned-var (reverse learned-var-list
))
2931 (let ((var (car learned-var
)))
2932 (sh-mark-line (format " %s %s" var
(symbol-value var
))
2933 (nth 2 learned-var
) out-buffer
)))
2935 (set-buffer out-buffer
)
2936 (goto-char (point-min))
2938 (format "Indentation values for buffer %s.\n" name
)
2939 (format "%d indentation variable%s different values%s\n\n"
2943 (if (zerop num-diffs
)
2946 ;; Are abnormal hooks considered bad form?
2947 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list
)
2948 (if (or sh-popup-occur-buffer
(> num-diffs
0))
2949 (pop-to-buffer out-buffer
))
2952 (defun sh-guess-basic-offset (vec)
2953 "See if we can determine a reasonable value for `sh-basic-offset'.
2954 This is experimental, heuristic and arbitrary!
2955 Argument VEC is a vector of information collected by
2956 `sh-learn-buffer-indent'.
2958 number - there appears to be a good single value
2959 list of numbers - no obvious one, here is a list of one or more
2961 nil - we couldn't find a reasonable one."
2962 (let* ((max (1- (length vec
)))
2964 (totals (make-vector max
0)))
2966 (aset totals i
(+ (aref totals i
) (* 4 (aref vec i
))))
2968 (aset totals i
(+ (aref totals i
) (aref vec
(/ i
2)))))
2970 (aset totals i
(+ (aref totals i
) (aref vec
(* i
2)))))
2978 (if (/= (aref totals i
) 0)
2979 (setq x
(append x
(list (cons i
(aref totals i
))))))
2982 (setq x
(sort x
(lambda (a b
) (> (cdr a
) (cdr b
)))))
2983 (setq tot
(apply '+ (append totals nil
)))
2984 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
2988 (message "no values!")) ;; we return nil
2990 (message "only value is %d" (car (car x
)))
2991 (setq result
(car (car x
)))) ;; return single value
2992 ((> (cdr (car x
)) (/ tot
2))
2994 (message "basic-offset is probably %d" (car (car x
)))
2995 (setq result
(car (car x
)))) ;; again, return a single value
2996 ((>= (cdr (car x
)) (* 2 (cdr (car (cdr x
)))))
2997 ;; 1st is >= 2 * 2nd
2998 (message "basic-offset could be %d" (car (car x
)))
2999 (setq result
(car (car x
))))
3000 ((>= (+ (cdr (car x
))(cdr (car (cdr x
)))) (/ tot
2))
3001 ;; 1st & 2nd together >= 50% - return a list
3002 (setq p x sum
0 result nil
)
3004 (<= (setq sum
(+ sum
(cdr (car p
)))) (/ tot
2)))
3005 (setq result
(append result
(list (car (car p
)))))
3007 (message "Possible choices for sh-basic-offset: %s"
3008 (mapconcat 'int-to-string result
" ")))
3010 (message "No obvious value for sh-basic-offset. Perhaps %d"
3012 ;; result is nil here
3016 ;; ========================================================================
3018 ;; Styles -- a quick and dirty way of saving the indentation settings.
3020 (defvar sh-styles-alist nil
3021 "A list of all known shell indentation styles.")
3023 (defun sh-name-style (name &optional confirm-overwrite
)
3024 "Name the current indentation settings as a style called NAME.
3025 If this name exists, the command will prompt whether it should be
3027 - - it was called interactively with a prefix argument, or
3028 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3029 ;; (interactive "sName for this style: ")
3032 (read-from-minibuffer "Name for this style? " )
3033 (not current-prefix-arg
)))
3034 (let ((slist (cons name
3035 (mapcar (lambda (var) (cons var
(symbol-value var
)))
3037 (style (assoc name sh-styles-alist
)))
3039 (if (and confirm-overwrite
3040 (not (y-or-n-p "This style exists. Overwrite it? ")))
3041 (message "Not changing style %s" name
)
3042 (message "Updating style %s" name
)
3043 (setcdr style
(cdr slist
)))
3044 (message "Creating new style %s" name
)
3045 (push slist sh-styles-alist
))))
3047 (defun sh-load-style (name)
3048 "Set shell indentation values for this buffer from those in style NAME."
3049 (interactive (list (completing-read
3050 "Which style to use for this buffer? "
3051 sh-styles-alist nil t
)))
3052 (let ((sl (assoc name sh-styles-alist
)))
3054 (error "sh-load-style - style %s not known" name
)
3055 (dolist (var (cdr sl
))
3056 (set (car var
) (cdr var
))))))
3058 (defun sh-save-styles-to-buffer (buff)
3059 "Save all current styles in elisp to buffer BUFF.
3060 This is always added to the end of the buffer."
3062 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3063 (with-current-buffer (get-buffer-create buff
)
3064 (goto-char (point-max))
3066 (pp `(setq sh-styles-alist
',sh-styles-alist
) (current-buffer))))
3070 ;; statement syntax-commands for various shells
3072 ;; You are welcome to add the syntax or even completely new statements as
3073 ;; appropriate for your favorite shell.
3075 (defconst sh-non-closing-paren
3076 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3077 ;; that inherits this property, which then confuses the indentation.
3078 (propertize ")" 'syntax-table sh-st-punc
'rear-nonsticky t
))
3080 (define-skeleton sh-case
3081 "Insert a case/switch statement. See `sh-feature'."
3083 "switch( " str
" )" \n
3084 > "case " (read-string "pattern: ") ?
: \n
3087 ( "other pattern, %s: "
3097 > "switch( " str
" ) {" \n
3098 > "case " (read-string "pattern: ") \n
3100 ( "other pattern, %s: "
3108 > "case " str
" in" \n
3110 > str sh-non-closing-paren
\n
3113 > "*" sh-non-closing-paren
\n
3118 (define-skeleton sh-for
3119 "Insert a for loop. See `sh-feature'."
3133 (sh "Index variable: "
3134 > "for " str
" in " _
"; do" \n
3135 > _ | ?$
& (sh-remember-variable str
) \n
3140 (define-skeleton sh-indexed-loop
3141 "Insert an indexed loop from 1 to n. See `sh-feature'."
3142 (bash sh-modify posix
)
3143 (csh "Index variable: "
3145 "while( $" str
" <= " (read-string "upper limit: ") " )" \n
3151 (ksh88 "Index variable: "
3152 > "integer " str
"=0" \n
3153 > "while (( ( " str
" += 1 ) <= "
3154 (read-string "upper limit: ")
3156 > _ ?$
(sh-remember-variable str
) > \n
3158 (posix "Index variable: "
3160 "while [ $" str
" -le "
3161 (read-string "upper limit: ")
3164 str ?
= (sh-add (sh-remember-variable str
) 1) \n
3166 (rc "Index variable: "
3167 > "for( " str
" in" " `{awk 'BEGIN { for( i=1; i<="
3168 (read-string "upper limit: ")
3169 "; i++ ) print i }'`}) {" \n
3170 > _ ?$
(sh-remember-variable str
) \n
3172 (sh "Index variable: "
3173 > "for " str
" in `awk 'BEGIN { for( i=1; i<="
3174 (read-string "upper limit: ")
3175 "; i++ ) print i }'`; do" \n
3176 > _ ?$
(sh-remember-variable str
) \n
3180 (defun sh-shell-initialize-variables ()
3181 "Scan the buffer for variable assignments.
3182 Add these variables to `sh-shell-variables'."
3183 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3185 (goto-char (point-min))
3186 (setq sh-shell-variables-initialized t
)
3187 (while (search-forward "=" nil t
)
3189 (message "Scanning buffer `%s' for variable assignments...done"
3192 (defvar sh-add-buffer
)
3194 (defun sh-add-completer (string predicate code
)
3195 "Do completion using `sh-shell-variables', but initialize it first.
3196 This function is designed for use as the \"completion table\",
3197 so it takes three arguments:
3198 STRING, the current buffer contents;
3199 PREDICATE, the predicate for filtering possible matches;
3200 CODE, which says what kind of things to do.
3201 CODE can be nil, t or `lambda'.
3202 nil means to return the best completion of STRING, or nil if there is none.
3203 t means to return a list of all possible completions of STRING.
3204 `lambda' means to return t if STRING is a valid completion as it stands."
3205 (let ((sh-shell-variables
3207 (set-buffer sh-add-buffer
)
3208 (or sh-shell-variables-initialized
3209 (sh-shell-initialize-variables))
3210 (nconc (mapcar (lambda (var)
3212 (substring var
0 (string-match "=" var
))))
3214 process-environment
)
3215 sh-shell-variables
))))
3217 ((nil) (try-completion string sh-shell-variables predicate
))
3218 (lambda (test-completion string sh-shell-variables predicate
))
3219 (t (all-completions string sh-shell-variables predicate
)))))
3221 (defun sh-add (var delta
)
3222 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3224 (let ((sh-add-buffer (current-buffer)))
3225 (list (completing-read "Variable: " 'sh-add-completer
)
3226 (prefix-numeric-value current-prefix-arg
))))
3227 (insert (sh-feature '((bash .
"$[ ")
3233 (sh-remember-variable var
)
3234 (if (< delta
0) " - " " + ")
3235 (number-to-string (abs delta
))
3236 (sh-feature '((bash .
" ]")
3245 (define-skeleton sh-function
3246 "Insert a function definition. See `sh-feature'."
3247 (bash sh-modify ksh88
3250 "function " str
" {" \n
3262 (define-skeleton sh-if
3263 "Insert an if statement. See `sh-feature'."
3265 "if( " str
" ) then" \n
3267 ( "other condition, %s: "
3268 < "else if( " str
" ) then" \n
3275 > "if { " str
" } {" \n
3277 ( "other condition, %s: "
3278 "} { " str
" } {" > \n
3285 > "if( " str
" ) {" \n
3287 ( "other condition, %s: "
3288 "} else if( " str
" ) {" > \n
3295 '(setq input
(sh-feature sh-test
))
3296 > "if " str
"; then" \n
3298 ( "other condition, %s: "
3299 > "elif " str
"; then" > \n
3308 (define-skeleton sh-repeat
3309 "Insert a repeat loop definition. See `sh-feature'."
3315 > "repeat " str
"; do" > \n
3319 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3323 (define-skeleton sh-select
3324 "Insert a select statement. See `sh-feature'."
3325 (ksh88 "Index variable: "
3326 > "select " str
" in " _
"; do" \n
3329 (bash sh-append ksh88
))
3330 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3334 (define-skeleton sh-tmp-file
3335 "Insert code to setup temporary file handling. See `sh-feature'."
3336 (bash sh-append ksh88
)
3337 (csh (file-name-nondirectory (buffer-file-name))
3338 "set tmp = /tmp/" str
".$$" \n
3340 (and (goto-char (point-max))
3344 "rm $tmp* >&/dev/null" > \n)
3345 (es (file-name-nondirectory (buffer-file-name))
3346 > "local( signals = $signals sighup sigint; tmp = /tmp/" str
3349 > "rm $tmp^* >[2]/dev/null" \n
3357 (rc (file-name-nondirectory (buffer-file-name))
3358 > "tmp = /tmp/" str
".$pid" \n
3359 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
3360 (sh (file-name-nondirectory (buffer-file-name))
3361 > "TMP=${TMPDIR:-/tmp}/" str
".$$" \n
3362 "trap \"rm $TMP* 2>/dev/null\" " ?
0 \n))
3366 (define-skeleton sh-until
3367 "Insert an until loop. See `sh-feature'."
3369 '(setq input
(sh-feature sh-test
))
3370 > "until " str
"; do" \n
3373 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3377 (define-skeleton sh-while
3378 "Insert a while loop. See `sh-feature'."
3394 '(setq input
(sh-feature sh-test
))
3395 > "while " str
"; do" \n
3401 (define-skeleton sh-while-getopts
3402 "Insert a while getopts loop. See `sh-feature'.
3403 Prompts for an options string which consists of letters for each recognized
3404 option followed by a colon `:' if the option accepts an argument."
3409 > "switch( \"$1\" )" \n
3410 '(setq input
'("- x" .
2))
3413 < "case " '(eval str
)
3414 '(if (string-match " +" str
)
3415 (setq v1
(substring str
(match-end 0))
3416 str
(substring str
0 (match-beginning 0)))
3419 > "set " v1
& " = $2" | -
4 & _
\n
3420 (if v1
"shift") & \n
3435 18 "$(basename $0)")
3437 > "while getopts :" str
" OPT; do" \n
3439 '(setq v1
(append (vconcat str
) nil
))
3440 ( (prog1 (if v1
(char-to-string (car v1
)))
3441 (if (eq (nth 1 v1
) ?
:)
3442 (setq v1
(nthcdr 2 v1
)
3446 > str
"|+" str sh-non-closing-paren
\n
3449 > "*" sh-non-closing-paren
\n
3450 > "echo" " \"usage: " "`basename $0`"
3451 " [+-" '(setq v1
(point)) str
3453 (while (search-backward ":" v1 t
)
3454 (replace-match " ARG] [+-" t t
)))
3455 (if (eq (preceding-char) ?-
) -
5)
3456 (if (and (sequencep v1
) (length v1
)) "] " "} ")
3462 "shift " (sh-add "OPTIND" -
1) \n))
3466 (defun sh-assignment (arg)
3467 "Remember preceding identifier for future completion and do self-insert."
3469 (self-insert-command arg
)
3471 (sh-remember-variable
3473 (if (re-search-forward (sh-feature sh-assignment-regexp
)
3475 (beginning-of-line 1))
3477 (match-string 1))))))
3481 (defun sh-maybe-here-document (arg)
3482 "Insert self. Without prefix, following unquoted `<' inserts here document.
3483 The document is bounded by `sh-here-document-word'."
3485 (self-insert-command (prefix-numeric-value arg
))
3487 (not (eq (char-after (- (point) 2)) last-command-char
))
3492 (insert sh-here-document-word
)
3493 (or (eolp) (looking-at "[ \t]") (insert ?
))
3500 (insert ?
\n (substring
3501 sh-here-document-word
3502 (if (string-match "^-" sh-here-document-word
) 1 0)))))))
3505 ;; various other commands
3507 (autoload 'comint-dynamic-complete
"comint"
3508 "Dynamically perform completion at point." t
)
3510 (autoload 'shell-dynamic-complete-command
"shell"
3511 "Dynamically complete the command at point." t
)
3513 (autoload 'comint-dynamic-complete-filename
"comint"
3514 "Dynamically complete the filename at point." t
)
3516 (autoload 'shell-dynamic-complete-environment-variable
"shell"
3517 "Dynamically complete the environment variable at point." t
)
3521 (defun sh-newline-and-indent ()
3522 "Strip unquoted whitespace, insert newline, and indent like current line."
3524 (indent-to (prog1 (current-indentation)
3525 (delete-region (point)
3527 (or (zerop (skip-chars-backward " \t"))
3533 (defun sh-beginning-of-command ()
3534 "Move point to successive beginnings of commands."
3536 (if (re-search-backward sh-beginning-of-command nil t
)
3537 (goto-char (match-beginning 2))))
3539 (defun sh-end-of-command ()
3540 "Move point to successive ends of commands."
3542 (if (re-search-forward sh-end-of-command nil t
)
3543 (goto-char (match-end 1))))
3545 (provide 'sh-script
)
3547 ;;; arch-tag: eccd8b72-f337-4fc2-ae86-18155a69d937
3548 ;;; sh-script.el ends here