1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993, 94, 95, 96, 97, 1999, 2001
4 ;; Free Software Foundation, Inc.
6 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
9 ;; Keywords: languages, unix
11 ;; This file is part of XEmacs.
13 ;; XEmacs is free software; you can redistribute it and/or modify it
14 ;; 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 ;; XEmacs is distributed in the hope that it will be useful, but
19 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 ;; General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with XEmacs; see the file COPYING. If not, write to the Free
25 ;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
28 ;;; Synched up with: FSF 21.4.
32 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
33 ;; as various derivatives are supported and easily derived from. Structured
34 ;; statements can be inserted with one command or abbrev. Completion is
35 ;; available for filenames, variables known from the script, the shell and
36 ;; the environment as well as commands.
40 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
41 ;; - Variables in `"' strings aren't fontified because there's no way of
42 ;; syntactically distinguishing those from `'' strings.
46 ;; Indentation for rc and es modes is very limited, but for Bourne shells
47 ;; and its derivatives it is quite customizable.
49 ;; The following description applies to sh and derived shells (bash,
52 ;; There are various customization variables which allow tailoring to
53 ;; a wide variety of styles. Most of these variables are named
54 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
55 ;; sh-indent-after-if controls the indenting of a line following
56 ;; an if statement, and sh-indent-for-fi controls the indentation
57 ;; of the line containing the fi.
59 ;; You can set each to a numeric value, but it is often more convenient
60 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
61 ;; By changing this one variable you can increase or decrease how much
62 ;; indentation there is. Valid symbols:
64 ;; + Indent right by sh-basic-offset
65 ;; - Indent left by sh-basic-offset
66 ;; ++ Indent right twice sh-basic-offset
67 ;; -- Indent left twice sh-basic-offset
68 ;; * Indent right half sh-basic-offset
69 ;; / Indent left half sh-basic-offset.
71 ;; There are 4 commands to help set the indentation variables:
74 ;; This shows what variable controls the indentation of the current
75 ;; line and its value.
78 ;; This allows you to set the value of the variable controlling the
79 ;; current line's indentation. You can enter a number or one of a
80 ;; number of special symbols to denote the value of sh-basic-offset,
81 ;; or its negative, or half it, or twice it, etc. If you've used
82 ;; cc-mode this should be familiar. If you forget which symbols are
83 ;; valid simply press C-h at the prompt.
85 ;; `sh-learn-line-indent'
86 ;; Simply make the line look the way you want it, then invoke this
87 ;; command. It will set the variable to the value that makes the line
88 ;; indent like that. If called with a prefix argument then it will set
89 ;; the value to one of the symbols if applicable.
91 ;; `sh-learn-buffer-indent'
92 ;; This is the deluxe function! It "learns" the whole buffer (use
93 ;; narrowing if you want it to process only part). It outputs to a
94 ;; buffer *indent* any conflicts it finds, and all the variables it has
95 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
96 ;; easily find where something was set. It is popped to automatically
97 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
99 ;; `sh-indent-comment' will be set if all comments follow the same
100 ;; pattern; if they don't it will be set to nil.
101 ;; Whether `sh-basic-offset' is set is determined by variable
102 ;; `sh-learn-basic-offset'.
104 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
105 ;; (e.g. if there are large case statements). Perhaps it does not make
106 ;; sense to run it on large buffers: if lots of lines have different
107 ;; indentation styles it will produce a lot of diagnostics in the
108 ;; *indent* buffer; if there is a consistent style then running
109 ;; `sh-learn-buffer-indent' on a small region of the buffer should
112 ;; Saving indentation values
113 ;; -------------------------
114 ;; After you've learned the values in a buffer, how to you remember
115 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
116 ;; would make this unnecessary; simply learn the values when you visit
118 ;; You can do this automatically like this:
119 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
121 ;; However... `sh-learn-buffer-indent' is extremely slow,
122 ;; especially on large-ish buffer. Also, if there are conflicts the
123 ;; "last one wins" which may not produce the desired setting.
125 ;; So...There is a minimal way of being able to save indentation values and
126 ;; to reload them in another buffer or at another point in time.
128 ;; Use `sh-name-style' to give a name to the indentation settings of
129 ;; the current buffer.
130 ;; Use `sh-load-style' to load indentation settings for the current
131 ;; buffer from a specific style.
132 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
133 ;; in lisp code. You can then store it in a file and later use
134 ;; `load-file' to load it.
136 ;; Indentation variables - buffer local or global?
137 ;; ----------------------------------------------
138 ;; I think that often having them buffer-local makes sense,
139 ;; especially if one is using `sh-learn-buffer-indent'. However, if
140 ;; a user sets values using customization, these changes won't appear
141 ;; to work if the variables are already local!
143 ;; To get round this, there is a variable `sh-make-vars-local' and 2
144 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
146 ;; If `sh-make-vars-local' is non-nil, then these variables become
147 ;; buffer local when the mode is established.
148 ;; If this is nil, then the variables are global. At any time you
149 ;; can make them local with the command `sh-make-vars-local'.
150 ;; Conversely, to update with the global values you can use the
151 ;; command `sh-reset-indent-vars-to-global-values'.
153 ;; This may be awkward, but the intent is to cover all cases.
155 ;; Awkward things, pitfalls
156 ;; ------------------------
157 ;; Indentation for a sh script is complicated for a number of reasons:
159 ;; 1. You can't format by simply looking at symbols, you need to look
160 ;; at keywords. [This is not the case for rc and es shells.]
161 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
162 ;; as a stand-alone symbol (in a case alternative). This makes
163 ;; things quite tricky!
164 ;; 3. Here-documents in a script should be treated "as is", and when
165 ;; they terminate we want to revert to the indentation of the line
166 ;; containing the "<<" symbol.
167 ;; 4. A line may be continued using the "\".
168 ;; 5. The character "#" (outside a string) normally starts a comment,
169 ;; but it doesn't in the sequence "$#"!
171 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
172 ;; uses, that of a text's syntax property. This, however, has 2
174 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
175 ;; case alternative, to find any here documents, and handle "$#".
176 ;; 2. Setting the text property makes the buffer modified. If the
177 ;; buffer is read-only buffer we have to cheat and bypass the read-only
178 ;; status. This is for cases where the buffer started read-only buffer
179 ;; but the user issued `toggle-read-only'.
183 ;; - Indenting many lines is slow. It currently does each line
184 ;; independently, rather than saving state information.
186 ;; - `sh-learn-buffer-indent' is extremely slow.
188 ;; Richard Sharman <rsharman@pobox.com> June 1999.
192 ;; page 1: variables and settings
193 ;; page 2: indentation stuff
194 ;; page 3: mode-command and utility functions
195 ;; page 4: statement syntax-commands for various shells
196 ;; page 5: various other commands
201 (require 'executable)
206 "Shell programming utilities"
210 (defgroup sh-script nil
215 ;;; interpreter-mode-alist is not compatible between Emacs and XEmacs.
218 (defvar sh-interpreter-mode-alist
219 '(("perl" . perl-mode)
220 ("perl5" . perl-mode)
229 ("scm" . scheme-mode)
252 "Alist mapping interpreter names to major modes.
253 This alist applies to files whose first line starts with `#!'.
254 Each element looks like (INTERPRETER . MODE).
255 The car of each element is compared with
256 the name of the interpreter specified in the first line.
257 If it matches, mode MODE is selected.")
259 (defcustom sh-ancestor-alist
278 "*Alist showing the direct ancestor of various shells.
279 This is the basis for `sh-feature'. See also `sh-alias-alist'.
280 By default we have the following three hierarchies:
283 jcsh C Shell with Job Control
285 itcsh ? Toronto C Shell
290 jsh Bourne Shell with Job Control
291 bash GNU Bourne Again Shell
294 dtksh CDE Desktop Korn Shell
295 pdksh Public Domain Korn Shell
296 wksh Window Korn Shell
298 oash SCO OA (curses) Shell
299 posix IEEE 1003.2 Shell Standard
301 :type '(repeat (cons symbol symbol))
305 (defcustom sh-alias-alist
306 ;; XEmacs change: Linux is spelled `linux'
307 (nconc (if (eq system-type 'linux)
310 ;; for the time being
314 "*Alist for transforming shell names to what they really are.
315 Use this where the name of the executable doesn't correspond to the type of
317 :type '(repeat (cons symbol symbol))
321 (defcustom sh-shell-file
323 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
324 ;; the executable extension, so comparisons with the list of
325 ;; known shells work.
326 (and (memq system-type '(ms-dos windows-nt))
327 (let* ((shell (getenv "SHELL"))
329 (and shell (file-name-nondirectory shell))))
330 ;; shell-script mode doesn't support DOS/Windows shells,
331 ;; so use the default instead.
333 (member (downcase shell-base)
334 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
337 (file-name-sans-extension (downcase shell)))))
340 "*The executable file name for the shell being programmed."
345 (defcustom sh-shell-arg
346 ;; bash does not need any options when run in a shell script,
350 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
352 ;; -p means don't initialize functions from the environment.
354 ;; Someone proposed -motif, but we don't want to encourage
355 ;; use of a non-free widget set.
357 ;; -f means don't run .zshrc.
359 "*Single argument string for the magic number. See `sh-feature'."
360 :type '(repeat (cons (symbol :tag "Shell")
361 (choice (const :tag "No Arguments" nil)
362 (string :tag "Arguments")
363 (cons :format "Evaluate: %v"
364 (const :format "" eval)
368 (defcustom sh-imenu-generic-expression
370 . ((nil "^\\s-*\\(function\\s-+\\)?\\([A-Za-z_][A-Za-z_0-9]+\\)\\s-*()" 2))))
371 "*Alist of regular expressions for recognizing shell function definitions.
372 See `sh-feature' and `imenu-generic-expression'."
373 :type '(alist :key-type (symbol :tag "Shell")
374 :value-type (alist :key-type (choice :tag "Title"
376 (const :tag "None" nil))
378 (repeat :tag "Regexp, index..." sexp)))
382 (defvar sh-shell-variables nil
383 "Alist of shell variable names that should be included in completion.
384 These are used for completion in addition to all the variables named
385 in `process-environment'. Each element looks like (VAR . VAR), where
386 the car and cdr are the same symbol.")
388 (defvar sh-shell-variables-initialized nil
389 "Non-nil if `sh-shell-variables' is initialized.")
391 (defun sh-canonicalize-shell (shell)
392 "Convert a shell name SHELL to the one we should handle it as."
393 (if (string-match "\\.exe\\'" shell)
394 (setq shell (substring shell 0 (match-beginning 0))))
396 (setq shell (intern shell)))
397 (or (cdr (assq shell sh-alias-alist))
400 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
401 "The shell being programmed. This is set by \\[sh-set-shell].")
403 ;;; I turned off this feature because it doesn't permit typing commands
404 ;;; in the usual way without help.
405 ;;;(defvar sh-abbrevs
406 ;;; '((csh eval sh-abbrevs shell
407 ;;; "switch" 'sh-case
408 ;;; "getopts" 'sh-while-getopts)
410 ;;; (es eval sh-abbrevs shell
411 ;;; "function" 'sh-function)
413 ;;; (ksh88 eval sh-abbrevs sh
414 ;;; "select" 'sh-select)
416 ;;; (rc eval sh-abbrevs shell
418 ;;; "function" 'sh-function)
420 ;;; (sh eval sh-abbrevs shell
422 ;;; "function" 'sh-function
423 ;;; "until" 'sh-until
424 ;;; "getopts" 'sh-while-getopts)
426 ;;; ;; The next entry is only used for defining the others
427 ;;; (shell "for" sh-for
428 ;;; "loop" sh-indexed-loop
430 ;;; "tmpfile" sh-tmp-file
431 ;;; "while" sh-while)
433 ;;; (zsh eval sh-abbrevs ksh88
434 ;;; "repeat" 'sh-repeat))
435 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
436 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
437 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
441 (easy-mmode-defsyntax sh-mode-syntax-table
456 "Syntax-table used in Shell-Script mode.")
460 (let ((map (make-sparse-keymap))
461 (menu-map (make-sparse-keymap "Insert")))
462 (define-key map "\C-c(" 'sh-function)
463 (define-key map "\C-c\C-w" 'sh-while)
464 (define-key map "\C-c\C-u" 'sh-until)
465 (define-key map "\C-c\C-t" 'sh-tmp-file)
466 (define-key map "\C-c\C-s" 'sh-select)
467 (define-key map "\C-c\C-r" 'sh-repeat)
468 (define-key map "\C-c\C-o" 'sh-while-getopts)
469 (define-key map "\C-c\C-l" 'sh-indexed-loop)
470 (define-key map "\C-c\C-i" 'sh-if)
471 (define-key map "\C-c\C-f" 'sh-for)
472 (define-key map "\C-c\C-c" 'sh-case)
473 (define-key map "\C-c?" 'sh-show-indent)
474 (define-key map "\C-c=" 'sh-set-indent)
475 (define-key map "\C-c<" 'sh-learn-line-indent)
476 (define-key map "\C-c>" 'sh-learn-buffer-indent)
478 (define-key map "=" 'sh-assignment)
479 (define-key map "\C-c+" 'sh-add)
480 (define-key map "\C-\M-x" 'sh-execute-region)
481 (define-key map "\C-c\C-x" 'executable-interpret)
482 (define-key map "<" 'sh-maybe-here-document)
483 (define-key map "(" 'skeleton-pair-insert-maybe)
484 (define-key map "{" 'skeleton-pair-insert-maybe)
485 (define-key map "[" 'skeleton-pair-insert-maybe)
486 (define-key map "'" 'skeleton-pair-insert-maybe)
487 (define-key map "`" 'skeleton-pair-insert-maybe)
488 (define-key map "\"" 'skeleton-pair-insert-maybe)
490 (substitute-key-definition 'complete-tag 'comint-dynamic-complete
491 map (current-global-map))
492 (substitute-key-definition 'newline-and-indent 'sh-newline-and-indent
493 map (current-global-map))
494 ;; XEmacs change: Don't mess around with the DEL bindings
495 ; (substitute-key-definition 'delete-backward-char
496 ; 'backward-delete-char-untabify
497 ; map (current-global-map))
498 (define-key map "\C-c:" 'sh-set-shell)
499 (substitute-key-definition 'beginning-of-defun
500 'sh-beginning-of-compound-command
501 map (current-global-map))
502 (substitute-key-definition 'backward-sentence 'sh-beginning-of-command
503 map (current-global-map))
504 (substitute-key-definition 'forward-sentence 'sh-end-of-command
505 map (current-global-map))
507 "Keymap used in Shell-Script mode.")
511 sh-mode-menu sh-mode-map "Menu for sh-script mode"
513 ["While Loop" sh-while t]
514 ["Until Loop" sh-until t]
515 ["Temporary File" sh-tmp-file t]
516 ["Select Statement" sh-select t]
517 ["Repeat Loop" sh-repeat t]
518 ["Options Loop" sh-while-getopts t]
519 ["Indexed Loop" sh-indexed-loop t]
520 ["If Statement" sh-if t]
521 ["For Loop" sh-for t]
522 ["Case Statement" sh-case t]))
524 (defcustom sh-dynamic-complete-functions
525 '(shell-dynamic-complete-environment-variable
526 shell-dynamic-complete-command
527 comint-dynamic-complete-filename)
528 "*Functions for doing TAB dynamic completion."
529 :type '(repeat function)
533 (defcustom sh-require-final-newline
536 (rc eval . require-final-newline)
537 (sh eval . require-final-newline))
538 "*Value of `require-final-newline' in Shell-Script mode buffers.
540 :type '(repeat (cons (symbol :tag "Shell")
541 (choice (const :tag "require" t)
542 (cons :format "Evaluate: %v"
543 (const :format "" eval)
548 (defcustom sh-assignment-regexp
549 '((csh . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
550 ;; actually spaces are only supported in let/(( ... ))
551 (ksh88 . "\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
552 (rc . "\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
553 (sh . "\\<\\([a-zA-Z0-9_]+\\)="))
554 "*Regexp for the variable name and what may follow in an assignment.
555 First grouping matches the variable name. This is upto and including the `='
556 sign. See `sh-feature'."
557 :type '(repeat (cons (symbol :tag "Shell")
559 (cons :format "Evaluate: %v"
560 (const :format "" eval)
565 (defcustom sh-indentation 4
566 "The width for further indentation in Shell-Script mode."
571 (defcustom sh-remember-variable-min 3
572 "*Don't remember variables less than this length for completing reads."
577 (defvar sh-header-marker nil
578 "When non-nil is the end of header for prepending by \\[sh-execute-region].
579 That command is also used for setting this variable.")
582 (defcustom sh-beginning-of-command
583 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
584 "*Regexp to determine the beginning of a shell command.
585 The actual command starts at the beginning of the second \\(grouping\\)."
590 (defcustom sh-end-of-command
591 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
592 "*Regexp to determine the end of a shell command.
593 The actual command ends at the end of the first \\(grouping\\)."
599 (defvar sh-here-document-word "EOF"
600 "Word to delimit here documents.")
602 ;; XEmacs change: indexes decreased by one (behaviour difference with GNU?)
606 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
609 ;; customized this out of sheer bravado. not for the faint of heart.
610 ;; but it *did* have an asterisk in the docstring!
611 (defcustom sh-builtins
612 '((bash eval sh-append posix
613 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
614 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
615 "suspend" "typeset" "unalias")
617 ;; The next entry is only used for defining the others
618 (bourne eval sh-append shell
619 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
622 (csh eval sh-append shell
623 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
624 "setenv" "source" "time" "unalias" "unhash")
626 (dtksh eval identity wksh)
628 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
629 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
631 (jsh eval sh-append sh
632 "bg" "fg" "jobs" "kill" "stop" "suspend")
634 (jcsh eval sh-append csh
635 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
637 (ksh88 eval sh-append bourne
638 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
639 "typeset" "unalias" "whence")
641 (oash eval sh-append sh
642 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
643 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
644 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
645 "wmtitle" "wrefresh")
647 (pdksh eval sh-append ksh88
650 (posix eval sh-append sh
653 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
656 (sh eval sh-append bourne
657 "hash" "test" "type")
659 ;; The next entry is only used for defining the others
660 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
662 (wksh eval sh-append ksh88
665 (zsh eval sh-append ksh88
666 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
667 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
668 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
669 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
670 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
672 "*List of all shell builtins for completing read and fontification.
673 Note that on some systems not all builtins are available or some are
674 implemented as aliases. See `sh-feature'."
675 :type '(repeat (cons (symbol :tag "Shell")
676 (choice (repeat string)
677 (cons :format "Evaluate: %v"
678 (const :format "" eval)
684 (defcustom sh-leading-keywords
687 (es "true" "unwind-protect" "whatis")
691 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
692 "*List of keywords that may be immediately followed by a builtin or keyword.
693 Given some confusion between keywords and builtins depending on shell and
694 system, the distinction here has been based on whether they influence the
695 flow of control or syntax. See `sh-feature'."
696 :type '(repeat (cons (symbol :tag "Shell")
697 (choice (repeat string)
698 (cons :format "Evaluate: %v"
699 (const :format "" eval)
704 (defcustom sh-other-keywords
705 '((bash eval sh-append bourne
708 ;; The next entry is only used for defining the others
709 (bourne eval sh-append sh
712 (csh eval sh-append shell
713 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
714 "if" "logout" "onintr" "repeat" "switch" "then" "while")
716 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
717 "return" "throw" "while")
719 (ksh88 eval sh-append bourne
722 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
725 (sh eval sh-append shell
726 "done" "esac" "fi" "for" "in" "return")
728 ;; The next entry is only used for defining the others
729 (shell "break" "case" "continue" "exec" "exit")
731 (zsh eval sh-append bash
733 "*List of keywords not in `sh-leading-keywords'.
735 :type '(repeat (cons (symbol :tag "Shell")
736 (choice (repeat string)
737 (cons :format "Evaluate: %v"
738 (const :format "" eval)
745 '((bash eval sh-append sh
746 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
747 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
748 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
749 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
750 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
751 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
752 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
753 "SECONDS" "SHLVL" "TMOUT" "UID")
755 (csh eval sh-append shell
756 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
757 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
758 "shell" "status" "time" "verbose")
760 (es eval sh-append shell
761 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
762 "pid" "prompt" "signals")
764 (jcsh eval sh-append csh
767 (ksh88 eval sh-append sh
768 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
769 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
772 (oash eval sh-append sh
773 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
775 (rc eval sh-append shell
776 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
779 (sh eval sh-append shell
780 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
782 ;; The next entry is only used for defining the others
783 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
784 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
785 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
786 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
788 (tcsh eval sh-append csh
789 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
790 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
791 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
792 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
793 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
794 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
795 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
796 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
799 (zsh eval sh-append ksh88
800 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
801 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
802 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
803 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
804 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
805 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
806 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
807 "List of all shell variables available for completing read.
811 ;;; Font-Lock support
813 (defface sh-heredoc-face
816 (:foreground "yellow" :bold t))
819 (:foreground "tan" ))
822 "Face to show a here-document"
823 :group 'sh-indentation)
824 (defvar sh-heredoc-face 'sh-heredoc-face)
827 (defvar sh-font-lock-keywords
828 '((csh eval sh-append shell
829 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
830 font-lock-variable-name-face))
832 (es eval sh-append executable-font-lock-keywords
833 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
834 font-lock-variable-name-face))
836 (rc eval identity es)
838 (sh eval sh-append shell
840 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
841 font-lock-variable-name-face)
843 '("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
844 '("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
845 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t)))
847 ;; The next entry is only used for defining the others
848 (shell eval sh-append executable-font-lock-keywords
849 '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face)
850 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
851 font-lock-variable-name-face))
852 (rpm eval sh-append rpm2
853 '("%{?\\(\\sw+\\)" 1 font-lock-keyword-face))
854 (rpm2 eval sh-append shell
855 '("^\\(\\sw+\\):" 1 font-lock-variable-name-face)))
856 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
858 (defvar sh-font-lock-keywords-1
860 "Subdued level highlighting for Shell Script modes.")
862 (defvar sh-font-lock-keywords-2 ()
863 "Gaudy level highlighting for Shell Script modes.")
865 ;; These are used for the syntax table stuff (derived from cperl-mode).
866 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
868 ;; XEmacs change: syntax-string-to-code replaces string-to-syntax
869 (defconst sh-st-punc (syntax-string-to-code "."))
870 (defconst sh-st-symbol (syntax-string-to-code "_"))
871 (defconst sh-here-doc-syntax (syntax-string-to-code "|")) ;; generic string
873 (defun sh-font-lock-heredoc (start string quoted)
874 "Determine the syntax of the \\n after a <<HEREDOC."
875 (unless (sh-in-comment-or-string start)
876 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
877 ;; font-lock keywords to detect the end of this here document.
879 "^" (if quoted "[ \t]*")
880 (regexp-quote (replace-regexp-in-string "['\"]" "" string))
882 (unless (assoc ere font-lock-syntactic-keywords)
883 (let* ( ;; A rough regexp that should find us back.
884 (sre (concat "<<\\(-\\)?\\s-*\\\\?['\"]?"
885 (regexp-quote string) "['\"]?[ \t\n]"))
887 ((save-excursion (re-search-backward ,sre nil t))
888 ;; This ^STRING$ is indeed following a <<STRING
890 ((not (save-excursion (re-search-forward ,sre nil t)))
891 ;; There's no <<STRING either before or after us,
892 ;; so we should remove this now obsolete entry.
893 (setq font-lock-syntactic-keywords
894 (delq (assoc ,ere font-lock-syntactic-keywords)
895 font-lock-syntactic-keywords))
897 ;; Use destructive update so the new keyword gets used right away.
898 (setq font-lock-syntactic-keywords
899 (nconc font-lock-syntactic-keywords
900 (list (font-lock-compile-keyword `(,ere 1 ,code))))))))
903 (defun sh-font-lock-paren (start)
906 ;; Skip through all patterns
909 (forward-comment (- (point-max)))
910 ;; Skip through one pattern
912 (or (/= 0 (skip-syntax-backward "w_"))
913 (/= 0 (skip-chars-backward "?*/"))
914 (when (memq (char-before) '(?\" ?\'))
915 (condition-case nil (progn (backward-sexp 1) t)
917 (forward-comment (- (point-max)))
918 (when (eq (char-before) ?|)
919 (backward-char 1) t)))
920 (when (save-excursion (backward-char 2) (looking-at ";;\\|in"))
923 (defconst sh-font-lock-syntactic-keywords
924 ;; A `#' begins a comment when it is unquoted and at the beginning of a
925 ;; word. In the shell, words are separated by metacharacters.
926 ;; The list of special chars is taken from the single-unix spec
927 ;; of the shell command language (under `quoting') but with `$' removed.
928 `(("[^|&;<>()`\\\"' \t\n]\\(#+\\)" 1 ,sh-st-symbol)
929 ;; Find HEREDOC starters and add a corresponding rule for the ender.
930 ("[^<>]<<\\(-\\)?\\s-*\\\\?\\(\\(['\"][^'\"]+['\"]\\|\\sw\\|\\s_\\)+\\).*\\(\n\\)"
931 4 (sh-font-lock-heredoc
932 (match-beginning 0) (match-string 2) (match-end 1)))
933 ;; Distinguish the special close-paren in `case'.
934 (")" 0 (sh-font-lock-paren (match-beginning 0)))))
936 (defun sh-font-lock-syntactic-face-function (state)
938 (if (char-valid-p (nth 3 state))
939 font-lock-string-face
941 font-lock-comment-face))
943 (defgroup sh-indentation nil
944 "Variables controlling indentation in shell scripts.
946 Note: customizing these variables will not affect existing buffers if
947 `sh-make-vars-local' is no-nil. See the documentation for
948 variable `sh-make-vars-local', command `sh-make-vars-local'
949 and command `sh-reset-indent-vars-to-global-values'."
953 (defcustom sh-set-shell-hook nil
954 "*Hook run by `sh-set-shell'."
958 (defcustom sh-mode-hook nil
959 "*Hook run by `sh-mode'."
963 (defcustom sh-learn-basic-offset nil
964 "*When `sh-guess-basic-offset' should learn `sh-basic-offset'.
967 t means: only if there seems to be an obvious value.
968 Anything else means: whenever we have a \"good guess\" as to the value."
970 (const :tag "Never" nil)
971 (const :tag "Only if sure" t)
972 (const :tag "If have a good guess" usually))
973 :group 'sh-indentation)
975 (defcustom sh-popup-occur-buffer nil
976 "*Controls when `sh-learn-buffer-indent' pops the *indent* buffer.
977 If t it is always shown. If nil, it is shown only when there
980 (const :tag "Only when there are conflicts." nil)
981 (const :tag "Always" t))
982 :group 'sh-indentation)
984 (defcustom sh-blink t
985 "*If non-nil, `sh-show-indent' shows the line indentation is relative to.
986 The position on the line is not necessarily meaningful.
987 In some cases the line will be the matching keyword, but this is not
990 :group 'sh-indentation)
992 (defcustom sh-first-lines-indent 0
993 "*The indentation of the first non-blank non-comment line.
994 Usually 0 meaning first column.
995 Can be set to a number, or to nil which means leave it as is."
997 (const :tag "Leave as is" nil)
998 (integer :tag "Column number"
999 :menu-tag "Indent to this col (0 means first col)" ))
1000 :group 'sh-indentation)
1003 (defcustom sh-basic-offset 4
1004 "*The default indentation increment.
1005 This value is used for the + and - symbols in an indentation variable."
1007 :group 'sh-indentation)
1009 (defcustom sh-indent-comment nil
1010 "*How a comment line is to be indented.
1011 nil means leave it as it is;
1012 t means indent it as a normal line, aligning it to previous non-blank
1014 a number means align to that column, e.g. 0 means fist column."
1016 (const :tag "Leave as is." nil)
1017 (const :tag "Indent as a normal line." t)
1018 (integer :menu-tag "Indent to this col (0 means first col)."
1019 :tag "Indent to column number.") )
1020 :group 'sh-indentation)
1023 (defvar sh-debug nil
1024 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1027 ;; Uncomment this defun and comment the defmacro for debugging.
1028 ;; (defun sh-debug (&rest args)
1029 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1031 ;; (apply 'message args)))
1032 (defmacro sh-debug (&rest args))
1034 (defconst sh-symbol-list
1035 '((const :tag "+ " :value +
1036 :menu-tag "+ Indent right by sh-basic-offset")
1037 (const :tag "- " :value -
1038 :menu-tag "- Indent left by sh-basic-offset")
1039 (const :tag "++" :value ++
1040 :menu-tag "++ Indent right twice sh-basic-offset")
1041 (const :tag "--" :value --
1042 :menu-tag "-- Indent left twice sh-basic-offset")
1043 (const :tag "* " :value *
1044 :menu-tag "* Indent right half sh-basic-offset")
1045 (const :tag "/ " :value /
1046 :menu-tag "/ Indent left half sh-basic-offset")))
1048 (defcustom sh-indent-for-else 0
1049 "*How much to indent an else relative to an if. Usually 0."
1051 (integer :menu-tag "A number (positive=>indent right)"
1053 (const :tag "--") ;; separator!
1056 :group 'sh-indentation)
1058 (defconst sh-number-or-symbol-list
1059 (append '((integer :menu-tag "A number (positive=>indent right)"
1061 (const :tag "--")) ; separator
1064 (defcustom sh-indent-for-fi 0
1065 "*How much to indent a fi relative to an if. Usually 0."
1066 :type `(choice ,@ sh-number-or-symbol-list )
1067 :group 'sh-indentation)
1069 (defcustom sh-indent-for-done '0
1070 "*How much to indent a done relative to its matching stmt. Usually 0."
1071 :type `(choice ,@ sh-number-or-symbol-list )
1072 :group 'sh-indentation)
1074 (defcustom sh-indent-after-else '+
1075 "*How much to indent a statement after an else statement."
1076 :type `(choice ,@ sh-number-or-symbol-list )
1077 :group 'sh-indentation)
1079 (defcustom sh-indent-after-if '+
1080 "*How much to indent a statement after an if statement.
1081 This includes lines after else and elif statements, too, but
1082 does not affect then else elif or fi statements themselves."
1083 :type `(choice ,@ sh-number-or-symbol-list )
1084 :group 'sh-indentation)
1086 (defcustom sh-indent-for-then '+
1087 "*How much to indent a then relative to an if."
1088 :type `(choice ,@ sh-number-or-symbol-list )
1089 :group 'sh-indentation)
1091 (defcustom sh-indent-for-do '*
1092 "*How much to indent a do statement.
1093 This is relative to the statement before the do, i.e. the
1094 while until or for statement."
1095 :type `(choice ,@ sh-number-or-symbol-list)
1096 :group 'sh-indentation)
1098 (defcustom sh-indent-after-do '*
1099 "*How much to indent a line after a do statement.
1100 This is used when the do is the first word of the line.
1101 This is relative to the statement before the do, e.g. a
1102 while for repeat or select statement."
1103 :type `(choice ,@ sh-number-or-symbol-list)
1104 :group 'sh-indentation)
1106 (defcustom sh-indent-after-loop-construct '+
1107 "*How much to indent a statement after a loop construct.
1109 This variable is used when the keyword \"do\" is on the same line as the
1110 loop statement (e.g. \"until\", \"while\" or \"for\").
1111 If the do is on a line by itself, then `sh-indent-after-do' is used instead."
1112 :type `(choice ,@ sh-number-or-symbol-list)
1113 :group 'sh-indentation)
1116 (defcustom sh-indent-after-done 0
1117 "*How much to indent a statement after a \"done\" keyword.
1118 Normally this is 0, which aligns the \"done\" to the matching
1119 looping construct line.
1120 Setting it non-zero allows you to have the \"do\" statement on a line
1121 by itself and align the done under to do."
1122 :type `(choice ,@ sh-number-or-symbol-list)
1123 :group 'sh-indentation)
1125 (defcustom sh-indent-for-case-label '+
1126 "*How much to indent a case label statement.
1127 This is relative to the line containing the case statement."
1128 :type `(choice ,@ sh-number-or-symbol-list)
1129 :group 'sh-indentation)
1131 (defcustom sh-indent-for-case-alt '++
1132 "*How much to indent statements after the case label.
1133 This is relative to the line containing the case statement."
1134 :type `(choice ,@ sh-number-or-symbol-list)
1135 :group 'sh-indentation)
1138 (defcustom sh-indent-for-continuation '+
1139 "*How much to indent for a continuation statement."
1140 :type `(choice ,@ sh-number-or-symbol-list)
1141 :group 'sh-indentation)
1143 (defcustom sh-indent-after-open '+
1144 "*How much to indent after a line with an opening parenthesis or brace.
1145 For an open paren after a function `sh-indent-after-function' is used."
1146 :type `(choice ,@ sh-number-or-symbol-list)
1147 :group 'sh-indentation)
1149 (defcustom sh-indent-after-function '+
1150 "*How much to indent after a function line."
1151 :type `(choice ,@ sh-number-or-symbol-list)
1152 :group 'sh-indentation)
1154 ;; These 2 are for the rc shell:
1156 (defcustom sh-indent-after-switch '+
1157 "*How much to indent a case statement relative to the switch statement.
1158 This is for the rc shell."
1159 :type `(choice ,@ sh-number-or-symbol-list)
1160 :group 'sh-indentation)
1162 (defcustom sh-indent-after-case '+
1163 "*How much to indent a statement relative to the case statement.
1164 This is for the rc shell."
1165 :type `(choice ,@ sh-number-or-symbol-list)
1166 :group 'sh-indentation)
1168 ;; Internal use - not designed to be changed by the user:
1170 (defun sh-mkword-regexpr (word)
1171 "Make a regexp which matches WORD as a word.
1172 This specifically excludes an occurrence of WORD followed by
1173 punctuation characters like '-'."
1174 (concat word "\\([^-a-z0-9_]\\|$\\)"))
1176 (defconst sh-re-done (sh-mkword-regexpr "done"))
1179 (defconst sh-kws-for-done
1180 '((sh . ( "while" "until" "for" ) )
1181 (bash . ( "while" "until" "for" "select" ) )
1182 (ksh88 . ( "while" "until" "for" "select" ) )
1183 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1184 "Which keywords can match the word `done' in this shell.")
1187 (defconst sh-indent-supported
1191 "Shell types that shell indenting can do something with.")
1193 (defvar sh-indent-supported-here nil
1194 "Non-nil if we support indentation for the current buffer's shell type.")
1196 (defconst sh-electric-rparen-needed
1198 "Non-nil if the shell type needs an electric handling of case alternatives.")
1200 (defconst sh-var-list
1202 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1203 sh-indent-after-do sh-indent-after-done
1204 sh-indent-after-else
1206 sh-indent-after-loop-construct
1207 sh-indent-after-open
1209 sh-indent-for-case-alt
1210 sh-indent-for-case-label
1211 sh-indent-for-continuation
1218 "A list of variables used by script mode to control indentation.
1219 This list is used when switching between buffer-local and global
1220 values of variables, and for the commands using indentation styles.")
1222 (defvar sh-make-vars-local t
1223 "*Controls whether indentation variables are local to the buffer.
1224 If non-nil, indentation variables are made local initially.
1225 If nil, you can later make the variables local by invoking
1226 command `sh-make-vars-local'.
1227 The default is t because I assume that in one Emacs session one is
1228 frequently editing existing scripts with different styles.")
1231 ;; mode-command and utility functions
1234 (put 'sh-mode 'mode-class 'special)
1237 (define-derived-mode sh-mode fundamental-mode "Shell-script"
1238 "Major mode for editing shell scripts.
1239 This mode works for many shells, since they all have roughly the same syntax,
1240 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1241 Unless the file's magic number indicates the shell, your usual shell is
1242 assumed. Since filenames rarely give a clue, they are not further analyzed.
1244 This mode adapts to the variations between shells (see `sh-set-shell') by
1245 means of an inheritance based feature lookup (see `sh-feature'). This
1246 mechanism applies to all variables (including skeletons) that pertain to
1247 shell-specific features.
1249 The default style of this mode is that of Rosenblatt's Korn shell book.
1250 The syntax of the statements varies with the shell being used. The
1251 following commands are available, based on the current shell's syntax:
1253 \\[sh-case] case statement
1255 \\[sh-function] function definition
1256 \\[sh-if] if statement
1257 \\[sh-indexed-loop] indexed loop from 1 to n
1258 \\[sh-while-getopts] while getopts loop
1259 \\[sh-repeat] repeat loop
1260 \\[sh-select] select loop
1261 \\[sh-until] until loop
1262 \\[sh-while] while loop
1264 For sh and rc shells indentation commands are:
1265 \\[sh-show-indent] Show the variable controlling this line's indentation.
1266 \\[sh-set-indent] Set then variable controlling this line's indentation.
1267 \\[sh-learn-line-indent] Change the indentation variable so this line
1268 would indent to the way it currently is.
1269 \\[sh-learn-buffer-indent] Set the indentation variables so the
1270 buffer indents as it currently is indented.
1273 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1274 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
1275 \\[sh-end-of-command] Go to end of successive commands.
1276 \\[sh-beginning-of-command] Go to beginning of successive commands.
1277 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1278 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1280 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
1282 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1284 If you generally program a shell different from your login shell you can
1285 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1286 indicate what shell it is use `sh-alias-alist' to translate.
1288 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1289 with your script for an edit-interpret-debug cycle."
1290 (make-local-variable 'skeleton-end-hook)
1291 (make-local-variable 'paragraph-start)
1292 (make-local-variable 'paragraph-separate)
1293 (make-local-variable 'comment-start)
1294 (make-local-variable 'comment-start-skip)
1295 (make-local-variable 'require-final-newline)
1296 (make-local-variable 'sh-header-marker)
1297 (make-local-variable 'sh-shell-file)
1298 (make-local-variable 'sh-shell)
1299 (make-local-variable 'skeleton-pair-alist)
1300 (make-local-variable 'skeleton-pair-filter)
1301 (make-local-variable 'comint-dynamic-complete-functions)
1302 (make-local-variable 'comint-prompt-regexp)
1303 (make-local-variable 'font-lock-defaults)
1304 (make-local-variable 'skeleton-filter)
1305 (make-local-variable 'skeleton-newline-indent-rigidly)
1306 (make-local-variable 'sh-shell-variables)
1307 (make-local-variable 'sh-shell-variables-initialized)
1308 (make-local-variable 'imenu-generic-expression)
1309 (make-local-variable 'sh-indent-supported-here)
1310 (setq skeleton-end-hook (lambda ()
1311 (or (eolp) (newline) (indent-relative)))
1312 paragraph-start (concat page-delimiter "\\|$")
1313 paragraph-separate paragraph-start
1315 comint-dynamic-complete-functions sh-dynamic-complete-functions
1316 ;; we can't look if previous line ended with `\'
1317 comint-prompt-regexp "^[ \t]*"
1319 `((sh-font-lock-keywords
1320 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1322 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1323 (font-lock-syntactic-keywords
1324 ;; Copy so we can use destructive update in `sh-font-lock-heredoc'.
1325 . ,(copy-sequence sh-font-lock-syntactic-keywords))
1326 (font-lock-syntactic-face-function
1327 . sh-font-lock-syntactic-face-function))
1328 skeleton-pair-alist '((?` _ ?`))
1329 skeleton-pair-filter 'sh-quoted-p
1330 skeleton-further-elements '((< '(- (min sh-indentation
1331 (current-column)))))
1332 skeleton-filter 'sh-feature
1333 skeleton-newline-indent-rigidly t
1334 sh-indent-supported-here nil)
1335 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1336 ;; Parse or insert magic number for exec, and set all variables depending
1337 ;; on the shell thus determined.
1340 (goto-char (point-min))
1341 (cond ((looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1343 ((and buffer-file-name
1344 (string-match "\\.m?spec$" buffer-file-name))
1346 (sh-set-shell (or interpreter sh-shell-file) nil nil))
1349 (easy-menu-add sh-mode-menu)))
1352 (defalias 'shell-script-mode 'sh-mode)
1355 (put 'sh-mode 'font-lock-defaults
1356 `((sh-font-lock-keywords
1357 sh-font-lock-keywords-1
1358 sh-font-lock-keywords-2)))
1359 ;; ,sh-font-lock-keywords-only
1361 ;; ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w"))))
1364 (defun sh-font-lock-keywords (&optional keywords)
1365 "Function to get simple fontification based on `sh-font-lock-keywords'.
1366 This adds rules for comments and assignments."
1367 (sh-feature sh-font-lock-keywords
1368 (when (stringp (sh-feature sh-assignment-regexp))
1370 `((,(sh-feature sh-assignment-regexp)
1371 1 font-lock-variable-name-face)
1375 (defun sh-font-lock-keywords-1 (&optional builtins)
1376 "Function to get better fontification including keywords."
1377 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
1378 (mapconcat 'identity
1379 (sh-feature sh-leading-keywords)
1382 (mapconcat 'identity
1383 (append (sh-feature sh-leading-keywords)
1384 (sh-feature sh-other-keywords))
1387 (sh-font-lock-keywords
1389 `((,(concat keywords "[ \t]+\\)?\\("
1390 (mapconcat 'identity (sh-feature sh-builtins) "\\|")
1392 (2 font-lock-keyword-face nil t)
1393 (6 font-lock-builtin-face))
1394 ,@(sh-feature sh-font-lock-keywords-2)))
1395 (,(concat keywords "\\)\\>")
1396 2 font-lock-keyword-face)
1397 ,@(sh-feature sh-font-lock-keywords-1)))))
1399 (defun sh-font-lock-keywords-2 ()
1400 "Function to get better fontification including keywords and builtins."
1401 (sh-font-lock-keywords-1 t))
1404 (defvar sh-regexp-for-done nil
1405 "A buffer-local regexp to match opening keyword for done.")
1407 (defvar sh-kw-alist nil
1408 "A buffer-local, since it is shell-type dependent, list of keywords.")
1410 ;; ( key-word first-on-this on-prev-line )
1411 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1412 ;; having 3 elements:
1414 ;; a rule to check when the keyword appears on "this" line
1415 ;; a rule to check when the keyword appears on "the previous" line
1416 ;; The keyword is usually a string and is the first word on a line.
1417 ;; If this keyword appears on the line whose indentation is to be
1418 ;; calculated, the rule in element 2 is called. If this returns
1419 ;; non-zero, the resulting point (which may be changed by the rule)
1420 ;; is used as the default indentation.
1421 ;; If it returned false or the keyword was not found in the table,
1422 ;; then the keyword from the previous line is looked up and the rule
1423 ;; in element 3 is called. In this case, however,
1424 ;; `sh-get-indent-info' does not stop but may keep going and test
1425 ;; other keywords against rules in element 3. This is because the
1426 ;; preceding line could have, for example, an opening "if" and an
1427 ;; opening "while" keyword and we need to add the indentation offsets
1432 ("if" nil sh-handle-prev-if)
1433 ("elif" sh-handle-this-else sh-handle-prev-else)
1434 ("else" sh-handle-this-else sh-handle-prev-else)
1435 ("fi" sh-handle-this-fi sh-handle-prev-fi)
1436 ("then" sh-handle-this-then sh-handle-prev-then)
1437 ("(" nil sh-handle-prev-open)
1438 ("{" nil sh-handle-prev-open)
1439 ("[" nil sh-handle-prev-open)
1440 ("}" sh-handle-this-close nil)
1441 (")" sh-handle-this-close nil)
1442 ("]" sh-handle-this-close nil)
1443 ("case" nil sh-handle-prev-case)
1444 ("esac" sh-handle-this-esac sh-handle-prev-esac)
1445 (case-label nil sh-handle-after-case-label) ;; ???
1446 (";;" nil sh-handle-prev-case-alt-end) ;; ???
1447 ("done" sh-handle-this-done sh-handle-prev-done)
1448 ("do" sh-handle-this-do sh-handle-prev-do))
1450 ;; Note: we don't need specific stuff for bash and zsh shells;
1451 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1452 ;; these shells use.
1454 ("{" nil sh-handle-prev-open)
1455 ("}" sh-handle-this-close nil)
1456 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
1459 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
1460 "Set this buffer's shell to SHELL (a string).
1461 Makes this script executable via `executable-set-magic', and sets up the
1462 proper starting #!-line, if INSERT-FLAG is non-nil.
1463 Calls the value of `sh-set-shell-hook' if set."
1464 (interactive (list (completing-read "Name or path of shell: "
1466 sh-interpreter-mode-alist
1467 (lambda (x) (eq (cdr x) 'sh-mode)))
1468 (eq executable-query 'function)
1470 (if (string-match "\\.exe\\'" shell)
1471 (setq shell (substring shell 0 (match-beginning 0))))
1472 (setq sh-shell (intern (file-name-nondirectory shell))
1473 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
1477 (executable-set-magic shell (sh-feature sh-shell-arg)
1478 no-query-flag insert-flag)))
1479 (setq require-final-newline (sh-feature sh-require-final-newline)
1480 ;;; local-abbrev-table (sh-feature sh-abbrevs)
1481 comment-start-skip "#+[\t ]*"
1482 mode-line-process (format "[%s]" sh-shell)
1483 sh-shell-variables nil
1484 sh-shell-variables-initialized nil
1485 imenu-generic-expression (sh-feature sh-imenu-generic-expression)
1486 imenu-case-fold-search nil)
1487 (dolist (var (sh-feature sh-variables))
1488 (sh-remember-variable var))
1489 (make-local-variable 'indent-line-function)
1490 (if (setq sh-indent-supported-here (sh-feature sh-indent-supported))
1492 (message "Setting up indent for shell type %s" sh-shell)
1493 (set (make-local-variable 'parse-sexp-lookup-properties) t)
1494 (set (make-local-variable 'sh-kw-alist) (sh-feature sh-kw))
1495 (let ((regexp (sh-feature sh-kws-for-done)))
1497 (set (make-local-variable 'sh-regexp-for-done)
1498 (sh-mkword-regexpr (regexp-opt regexp t)))))
1499 (message "setting up indent stuff")
1500 ;; sh-mode has already made indent-line-function local
1501 ;; but do it in case this is called before that.
1502 (setq indent-line-function 'sh-indent-line)
1503 (if sh-make-vars-local
1504 (sh-make-vars-local))
1505 (message "Indentation setup for shell type %s" sh-shell))
1506 (message "No indentation for this shell type.")
1507 (setq indent-line-function 'sh-basic-indent-line))
1508 (run-hooks 'sh-set-shell-hook))
1512 (defun sh-feature (list &optional function)
1513 "Index ALIST by the current shell.
1514 If ALIST isn't a list where every element is a cons, it is returned as is.
1515 Else indexing follows an inheritance logic which works in two ways:
1517 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1518 the alist contains no value for the current shell.
1519 The ultimate default is always `sh'.
1521 - If the value thus looked up is a list starting with `eval' its `cdr' is
1522 first evaluated. If that is also a list and the first argument is a
1523 symbol in ALIST it is not evaluated, but rather recursively looked up in
1524 ALIST to allow the function called to define the value for one shell to be
1525 derived from another shell. While calling the function, is the car of the
1526 alist element is the current shell.
1527 The value thus determined is physically replaced into the alist.
1529 Optional FUNCTION is applied to the determined value and the result is cached
1531 (or (if (consp list)
1533 (while (and l (consp (car l)))
1537 (cdr (assoc (setq function (cons sh-shell function)) list)))
1538 (let ((sh-shell sh-shell)
1540 (while (and sh-shell
1541 (not (setq elt (assq sh-shell list))))
1542 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
1543 ;; If the shell is not known, treat it as sh.
1545 (setq elt (assq 'sh list)))
1546 (if (and (consp (setq val (cdr elt)))
1547 (eq (car val) 'eval))
1550 (eval (if (consp (setq val (cdr val)))
1551 (let ((sh-shell (car (cdr val)))
1553 (if (assq sh-shell list)
1556 (sh-feature list))))
1561 (list (cons function
1562 (setq sh-shell (car function)
1563 val (funcall (cdr function) val))))))
1568 ;;; I commented this out because nobody calls it -- rms.
1569 ;;;(defun sh-abbrevs (ancestor &rest list)
1570 ;;; "Iff it isn't, define the current shell as abbrev table and fill that.
1571 ;;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1572 ;;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1573 ;;;according to the remaining arguments NAMEi EXPANSIONi ...
1574 ;;;EXPANSION may be either a string or a skeleton command."
1575 ;;; (or (if (boundp sh-shell)
1576 ;;; (symbol-value sh-shell))
1578 ;;; (if (listp ancestor)
1579 ;;; (nconc list ancestor))
1580 ;;; (define-abbrev-table sh-shell ())
1581 ;;; (if (vectorp ancestor)
1582 ;;; (mapatoms (lambda (atom)
1584 ;;; (define-abbrev (symbol-value sh-shell)
1585 ;;; (symbol-name atom)
1586 ;;; (symbol-value atom)
1587 ;;; (symbol-function atom))))
1590 ;;; (define-abbrev (symbol-value sh-shell)
1592 ;;; (if (stringp (car (cdr list)))
1593 ;;; (car (cdr list))
1595 ;;; (if (symbolp (car (cdr list)))
1596 ;;; (car (cdr list))))
1597 ;;; (setq list (cdr (cdr list)))))
1598 ;;; (symbol-value sh-shell)))
1601 (defun sh-append (ancestor &rest list)
1602 "Return list composed of first argument (a list) physically appended to rest."
1603 (nconc list ancestor))
1606 (defun sh-modify (skeleton &rest list)
1607 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1608 (setq skeleton (copy-sequence skeleton))
1610 (setcar (or (nthcdr (car list) skeleton)
1611 (error "Index %d out of bounds" (car list)))
1613 (setq list (nthcdr 2 list)))
1617 (defun sh-basic-indent-line ()
1618 "Indent a line for Sh mode (shell script mode).
1619 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1620 Lines containing only comments are considered empty."
1622 (let ((previous (save-excursion
1623 (while (and (progn (beginning-of-line)
1627 (back-to-indentation)
1629 (eq (following-char) ?#)))))
1633 (indent-to (if (eq this-command 'newline-and-indent)
1635 (if (< (current-column)
1636 (setq current (progn (back-to-indentation)
1638 (if (eolp) previous 0)
1639 (delete-region (point)
1640 (progn (beginning-of-line) (point)))
1642 (max previous (* (1+ (/ current sh-indentation))
1644 (* (1+ (/ current sh-indentation)) sh-indentation))))))
1645 (if (< (current-column) (current-indentation))
1646 (skip-chars-forward " \t"))))
1649 (defun sh-execute-region (start end &optional flag)
1650 "Pass optional header and region to a subshell for noninteractive execution.
1651 The working directory is that of the buffer, and only environment variables
1652 are already set which is why you can mark a header within the script.
1654 With a positive prefix ARG, instead of sending region, define header from
1655 beginning of buffer to point. With a negative prefix ARG, instead of sending
1656 region, clear header."
1657 (interactive "r\nP")
1659 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
1661 (if sh-header-marker
1663 (let (buffer-undo-list)
1664 (goto-char sh-header-marker)
1665 (append-to-buffer (current-buffer) start end)
1666 (shell-command-on-region (point-min)
1667 (setq end (+ sh-header-marker
1670 (delete-region sh-header-marker end)))
1671 (shell-command-on-region start end (concat sh-shell-file " -")))))
1674 (defun sh-remember-variable (var)
1675 "Make VARIABLE available for future completing reads in this buffer."
1676 (or (< (length var) sh-remember-variable-min)
1678 (assoc var sh-shell-variables)
1679 (push (cons var var) sh-shell-variables))
1684 (defun sh-quoted-p ()
1685 "Is point preceded by an odd number of backslashes?"
1686 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
1688 ;; Indentation stuff.
1689 (defun sh-must-be-shell-mode ()
1690 "Signal an error if not in Shell-script mode."
1691 (unless (eq major-mode 'sh-mode)
1692 (error "This buffer is not in Shell-script mode")))
1694 (defun sh-must-support-indent ()
1695 "*Signal an error if the shell type for this buffer is not supported.
1696 Also, the buffer must be in Shell-script mode."
1697 (sh-must-be-shell-mode)
1698 (unless sh-indent-supported-here
1699 (error "This buffer's shell type is not supported for this command")))
1701 (defun sh-make-vars-local ()
1702 "Make the indentation variables local to this buffer.
1703 Normally they already are local. This command is provided in case
1704 variable `sh-make-vars-local' has been set to nil.
1706 To revert all these variables to the global values, use
1707 command `sh-reset-indent-vars-to-global-values'."
1709 (sh-must-be-shell-mode)
1710 (mapcar 'make-local-variable sh-var-list)
1711 (message "Indentation variable are now local."))
1713 (defun sh-reset-indent-vars-to-global-values ()
1714 "Reset local indentation variables to the global values.
1715 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1717 (sh-must-be-shell-mode)
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."
1771 (setq state (parse-partial-sexp (point) start nil nil nil t))
1772 (or (nth 3 state)(nth 4 state)))))
1774 (defun sh-goto-matching-if ()
1775 "Go to the matching if for a fi.
1776 This handles nested if..fi pairs."
1777 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1779 (goto-char found))))
1782 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1783 ;; line whose indentation is being handled contain XXX;
1784 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
1786 (defun sh-handle-prev-if ()
1787 (list '(+ sh-indent-after-if)))
1789 (defun sh-handle-this-else ()
1790 (if (sh-goto-matching-if)
1791 ;; (list "aligned to if")
1792 (list "aligned to if" '(+ sh-indent-for-else))
1796 (defun sh-handle-prev-else ()
1797 (if (sh-goto-matching-if)
1798 (list '(+ sh-indent-after-if))
1801 (defun sh-handle-this-fi ()
1802 (if (sh-goto-matching-if)
1803 (list "aligned to if" '(+ sh-indent-for-fi))
1807 (defun sh-handle-prev-fi ()
1808 ;; Why do we have this rule? Because we must go back to the if
1809 ;; to get its indent. We may continue back from there.
1810 ;; We return nil because we don't have anything to add to result,
1811 ;; the side affect of setting align-point is all that matters.
1812 ;; we could return a comment (a string) but I can't think of a good one...
1813 (sh-goto-matching-if)
1816 (defun sh-handle-this-then ()
1817 (let ((p (sh-goto-matching-if)))
1819 (list '(+ sh-indent-for-then))
1822 (defun sh-handle-prev-then ()
1823 (let ((p (sh-goto-matching-if)))
1825 (list '(+ sh-indent-after-if))
1828 (defun sh-handle-prev-open ()
1830 (let ((x (sh-prev-stmt)))
1835 (looking-at "function\\b")
1836 (looking-at "\\s-*\\S-+\\s-*()")
1838 (list '(+ sh-indent-after-function))
1839 (list '(+ sh-indent-after-open)))
1842 (defun sh-handle-this-close ()
1843 (forward-char 1) ;; move over ")"
1844 (if (sh-safe-forward-sexp -1)
1845 (list "aligned to opening paren")))
1847 (defun sh-goto-matching-case ()
1848 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
1849 (if found (goto-char found))))
1851 (defun sh-handle-prev-case ()
1852 ;; This is typically called when point is on same line as a case
1853 ;; we shouldn't -- and can't find prev-case
1854 (if (looking-at ".*\\<case\\>")
1855 (list '(+ sh-indent-for-case-label))
1856 (error "We don't seem to be on a line with a case"))) ;; debug
1858 (defun sh-handle-this-esac ()
1859 (if (sh-goto-matching-case)
1860 (list "aligned to matching case")))
1862 (defun sh-handle-prev-esac ()
1863 (if (sh-goto-matching-case)
1864 (list "matching case")))
1866 (defun sh-handle-after-case-label ()
1867 (if (sh-goto-matching-case)
1868 (list '(+ sh-indent-for-case-alt))))
1870 (defun sh-handle-prev-case-alt-end ()
1871 (if (sh-goto-matching-case)
1872 (list '(+ sh-indent-for-case-label))))
1874 (defun sh-safe-forward-sexp (&optional arg)
1875 "Try and do a `forward-sexp', but do not error.
1876 Return new point if successful, nil if an error occurred."
1879 (forward-sexp (or arg 1))
1880 (point)) ;; return point if successful
1882 (sh-debug "oops!(1) %d" (point))
1883 nil))) ;; return nil if fail
1885 (defun sh-goto-match-for-done ()
1886 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
1888 (goto-char found))))
1890 (defun sh-handle-this-done ()
1891 (if (sh-goto-match-for-done)
1892 (list "aligned to do stmt" '(+ sh-indent-for-done))))
1894 (defun sh-handle-prev-done ()
1895 (if (sh-goto-match-for-done)
1896 (list "previous done")))
1898 (defun sh-handle-this-do ()
1899 (if (sh-goto-match-for-done)
1900 (list '(+ sh-indent-for-do))))
1902 (defun sh-handle-prev-do ()
1910 (sh-goto-match-for-done))
1911 (sh-debug "match for done found on THIS line")
1912 (list '(+ sh-indent-after-loop-construct)))
1913 ((sh-goto-match-for-done)
1914 (sh-debug "match for done found on PREV line")
1915 (list '(+ sh-indent-after-do)))
1917 (message "match for done NOT found")
1921 (defun sh-find-prev-switch ()
1922 "Find the line for the switch keyword matching this line's case keyword."
1923 (re-search-backward "\\<switch\\>" nil t))
1925 (defun sh-handle-this-rc-case ()
1926 (if (sh-find-prev-switch)
1927 (list '(+ sh-indent-after-switch))
1928 ;; (list '(+ sh-indent-for-case-label))
1931 (defun sh-handle-prev-rc-case ()
1932 (list '(+ sh-indent-after-case)))
1934 (defun sh-check-rule (n thing)
1935 (let ((rule (nth n (assoc thing sh-kw-alist)))
1939 (setq val (funcall rule))
1940 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
1941 n thing (point) rule val)))
1945 (defun sh-get-indent-info ()
1946 "Return indent-info for this line.
1947 This is a list. nil means the line is to be left as is.
1948 Otherwise it contains one or more of the following sublists:
1949 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
1950 relative to. If present, this is always the first of the
1951 sublists. The indentation of the line in question is
1952 derived from the indentation of this point, possibly
1953 modified by subsequent sublists.
1955 \(- VAR\) Get the value of variable VAR and add to or subtract from
1956 the indentation calculated so far.
1957 \(= VAR\) Get the value of variable VAR and *replace* the
1958 indentation with its value. This only occurs for
1959 special variables such as `sh-indent-comment'.
1960 STRING This is ignored for the purposes of calculating
1961 indentation, it is printed in certain cases to help show
1962 what the indentation is based on."
1963 ;; See comments before `sh-kw'.
1972 (depth-prev-bol nil)
1982 ;; Note: setting result to t means we are done and will return nil.
1983 ;;(This function never returns just t.)
1985 ((or (and (boundp 'font-lock-string-face)
1986 (eq (get-text-property (point) 'face) font-lock-string-face))
1987 (eq (get-text-property (point) 'face) sh-heredoc-face))
1989 (setq have-result t))
1990 ((looking-at "\\s-*#") ; was (equal this-kw "#")
1992 (setq result t) ;; return nil if 1st line!
1993 (setq result (list '(= sh-indent-comment)))
1994 ;; we still need to get previous line in case
1995 ;; sh-indent-comment is t (indent as normal)
1996 (setq align-point (sh-prev-line nil))
1997 (setq have-result nil)
2002 ;; Continuation lines are handled specially
2003 (if (sh-this-is-a-continuation)
2005 ;; We assume the line being continued is already
2006 ;; properly indented...
2007 ;; (setq prev-line-end (sh-prev-line))
2008 (setq align-point (sh-prev-line nil))
2009 (setq result (list '(+ sh-indent-for-continuation)))
2010 (setq have-result t))
2012 (skip-chars-forward " \t")
2013 (setq this-kw (sh-get-kw)))
2015 ;; Handle "this" keyword: first word on the line we're
2016 ;; calculating indentation info for.
2018 (if (setq val (sh-check-rule 1 this-kw))
2020 (setq align-point (point))
2022 "this - setting align-point to %d" align-point)
2023 (setq result (append result val))
2024 (setq have-result t)
2025 ;; set prev-line to continue processing remainder
2026 ;; of this line as a previous line
2027 (setq prev-line-end (point))
2031 (setq prev-line-end (sh-prev-line 'end)))
2035 ;; We start off at beginning of this line.
2036 ;; Scan previous statements while this is <=
2037 ;; start of previous line.
2038 (setq start (point)) ;; for debug only
2039 (goto-char prev-line-end)
2041 (while (and x (setq x (sh-prev-thing)))
2042 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2045 (equal (get-text-property (1- (point)) 'syntax-table)
2047 (sh-debug "Case label) here")
2048 (setq x 'case-label)
2049 (if (setq val (sh-check-rule 2 x))
2051 (setq result (append result val))
2052 (setq align-point (point))))
2054 (skip-chars-forward "[a-z0-9]*?")
2056 ((string-match "[])}]" x)
2057 (setq x (sh-safe-forward-sexp -1))
2060 (setq align-point (point))
2061 (setq result (append result
2062 (list "aligned to opening paren")))
2064 ((string-match "[[({]" x)
2065 (sh-debug "Checking special thing: %s" x)
2066 (if (setq val (sh-check-rule 2 x))
2067 (setq result (append result val)))
2069 (setq align-point (point)))
2070 ((string-match "[\"'`]" x)
2071 (sh-debug "Skipping back for %s" x)
2073 (setq x (sh-safe-forward-sexp -1)))
2075 (sh-debug "Checking string %s at %s" x (point))
2076 (if (setq val (sh-check-rule 2 x))
2077 ;; (or (eq t (car val))
2078 ;; (eq t (car (car val))))
2079 (setq result (append result val)))
2080 ;; not sure about this test Wed Jan 27 23:48:35 1999
2081 (setq align-point (point))
2085 (error "Don't know what to do with %s" x))
2088 (sh-debug "result is %s" result)
2090 (sh-debug "No prev line!")
2091 (sh-debug "result: %s align-point: %s" result align-point)
2095 ;; was: (setq result (append result (list (list t align-point))))
2096 (setq result (append (list (list t align-point)) result))
2098 (sh-debug "result is now: %s" result)
2102 (setq result (list (list t prev-line-end)))
2103 (setq result (list (list '= 'sh-first-lines-indent)))
2108 (sh-debug "result is: %s" result)
2114 (defun sh-get-indent-var-for-line (&optional info)
2115 "Return the variable controlling indentation for this line.
2116 If there is not [just] one such variable, return a string
2117 indicating the problem.
2118 If INFO is supplied it is used, else it is calculated."
2124 (setq info (sh-get-indent-info)))
2126 (setq result "this line to be left as is")
2127 (while (and info (null result))
2128 (setq elt (car info))
2134 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2138 ((symbolp (setq sym (nth 1 elt)))
2139 ;; A bit of a kludge - when we see the sh-indent-comment
2140 ;; ignore other variables. Otherwise it is tricky to
2141 ;; "learn" the comment indentation.
2142 (if (eq var 'sh-indent-comment)
2146 "this line is controlled by more than 1 variable.")
2149 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2150 (setq info (cdr info))
2155 (setq result reason))
2157 ;; e.g. just had (t POS)
2158 (setq result "line has default indentation"))
2163 ;; Finding the previous line isn't trivial.
2164 ;; We must *always* go back one more and see if that is a continuation
2165 ;; line -- it is the PREVIOUS line which is continued, not the one
2167 ;; Also, we want to treat a whole "here document" as one big line,
2168 ;; because we may want to a align to the beginning of it.
2171 ;; - go back to previous non-empty line
2172 ;; - if this is in a here-document, go to the beginning of it
2173 ;; - while previous line is continued, go back one line
2174 (defun sh-prev-line (&optional end)
2175 "Back to end of previous non-comment non-empty line.
2176 Go to beginning of logical line unless END is non-nil, in which case
2177 we go to the end of the previous line and do not check for continuations."
2178 (sh-must-be-shell-mode)
2181 (forward-comment (- (point-max)))
2182 (unless end (beginning-of-line))
2183 (when (and (not (bobp))
2184 (equal (get-text-property (1- (point)) 'face)
2186 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
2191 (beginning-of-line)))))
2193 ;; we must check previous lines to see if they are continuation lines
2194 ;; if so, we must return position of first of them
2195 (while (and (sh-this-is-a-continuation)
2196 (>= 0 (forward-line -1))))
2198 (skip-chars-forward " \t"))
2202 (defun sh-prev-stmt ()
2203 "Return the address of the previous stmt or nil."
2204 ;; This is used when we are trying to find a matching keyword.
2205 ;; Searching backward for the keyword would certainly be quicker, but
2206 ;; it is hard to remove "false matches" -- such as if the keyword
2207 ;; appears in a string or quote. This way is slower, but (I think) safer.
2214 (skip-chars-backward " \t;|&({[")
2215 (while (and (not found)
2218 ;; Do a backward-sexp if possible, else backup bit by bit...
2219 (if (sh-safe-forward-sexp -1)
2221 (if (looking-at sh-special-keywords)
2226 ;; backward-sexp failed
2227 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2230 (let ((back (sh-prev-line nil)))
2233 (setq going nil)))))
2235 (skip-chars-backward " \t")
2236 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2237 (eq (char-before) ?\;)
2238 (looking-at "\\s-*[|&]"))
2239 (setq found (point)))))
2244 (skip-chars-forward " \t|&({[")
2245 (setq found (point))))
2246 (if (>= (point) start)
2248 (debug "We didn't move!")
2251 (sh-debug "Did not find prev stmt.")))
2255 (defun sh-get-word ()
2256 "Get a shell word skipping whitespace from point."
2258 (skip-chars-forward "\t ")
2259 (let ((start (point)))
2261 (if (looking-at "[\"'`]")
2262 (sh-safe-forward-sexp)
2263 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2264 (> (skip-chars-forward "-_a-zA-Z\$0-9") 0)
2266 (buffer-substring start (point))
2269 (defun sh-prev-thing ()
2270 "Return the previous thing this logical line."
2271 ;; This is called when `sh-get-indent-info' is working backwards on
2272 ;; the previous line(s) finding what keywords may be relevant for
2273 ;; indenting. It moves over sexps if possible, and will stop
2274 ;; on a ; and at the beginning of a line if it is not a continuation
2277 ;; Added a kludge for ";;"
2278 ;; Possible return values:
2280 ;; a string - possibly a keyword
2291 (if (sh-this-is-a-continuation)
2292 (setq min-point (sh-prev-line nil))
2295 (setq min-point (point))))
2297 (skip-chars-backward " \t;")
2298 (unless (looking-at "\\s-*;;")
2299 (skip-chars-backward "^)}];\"'`({[")
2300 (setq c (char-before))))
2301 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2302 (point) c start min-point)
2303 (if (< (point) min-point)
2304 (error "point %d < min-point %d" (point) min-point))
2306 ((looking-at "\\s-*;;")
2307 ;; (message "Found ;; !")
2313 ;; skip forward over white space newline and \ at eol
2314 (skip-chars-forward " \t\n\\\\")
2315 (sh-debug "Now at %d start=%d" (point) start)
2316 (if (>= (point) start)
2318 (sh-debug "point: %d >= start: %d" (point) start)
2323 ;; c -- return a string
2329 (defun sh-this-is-a-continuation ()
2330 "Return non-nil if current line is a continuation of previous line."
2332 (and (zerop (forward-line -1))
2333 (looking-at ".*\\\\$")
2334 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2337 (defun sh-get-kw (&optional where and-move)
2338 "Return first word of line from WHERE.
2339 If AND-MOVE is non-nil then move to end of word."
2340 (let ((start (point)))
2344 (buffer-substring (point)
2345 (progn (skip-chars-forward "^ \t\n;")(point)))
2347 (goto-char start)))))
2349 (defun sh-find-prev-matching (open close &optional depth)
2350 "Find a matching token for a set of opening and closing keywords.
2351 This takes into account that there may be nested open..close pairings.
2352 OPEN and CLOSE are regexps denoting the tokens to be matched.
2353 Optional parameter DEPTH (usually 1) says how many to look for."
2354 (let ((parse-sexp-ignore-comments t)
2356 (setq depth (or depth 1))
2362 (setq prev (sh-prev-stmt)))
2365 (if (looking-at "\\\\\n")
2368 (skip-chars-forward " \t")))
2371 (setq depth (1- depth))
2372 (sh-debug "found open at %d - depth = %d" (point) depth))
2374 (setq depth (1+ depth))
2375 (sh-debug "found close - depth = %d" depth))
2385 (defun sh-var-value (var &optional ignore-error)
2386 "Return the value of variable VAR, interpreting symbols.
2387 It can also return t or nil.
2388 If an illegal value is found, throw an error unless Optional argument
2389 IGNORE-ERROR is non-nil."
2390 (let ((val (symbol-value var)))
2401 (- sh-basic-offset))
2403 (* 2 sh-basic-offset))
2405 (* 2 (- sh-basic-offset)))
2407 (/ sh-basic-offset 2))
2409 (/ (- sh-basic-offset) 2))
2413 (message "Don't know how to handle %s's value of %s" var val)
2415 (error "Don't know how to handle %s's value of %s" var val))
2418 (defun sh-set-var-value (var value &optional no-symbol)
2419 "Set variable VAR to VALUE.
2420 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2421 can be represented by a symbol then do so."
2425 ((= value sh-basic-offset)
2427 ((= value (- sh-basic-offset))
2429 ((eq value (* 2 sh-basic-offset))
2431 ((eq value (* 2 (- sh-basic-offset)))
2433 ((eq value (/ sh-basic-offset 2))
2435 ((eq value (/ (- sh-basic-offset) 2))
2442 (defun sh-calculate-indent (&optional info)
2443 "Return the indentation for the current line.
2444 If INFO is supplied it is used, else it is calculated from current line."
2449 (setq info (sh-get-indent-info)))
2452 (sh-debug "info: %s ofs=%s" info ofs)
2453 (setq elt (car info))
2455 ((stringp elt)) ;; do nothing?
2457 (setq a (car (car info)))
2458 (setq b (nth 1 (car info)))
2463 (setq val (current-indentation)))
2464 (setq base-value val))
2466 (setq val (sh-var-value b))
2472 ;; set info to nil so we stop immediately
2473 (setq base-value nil ofs nil info nil))
2474 ((eq val t) (setq ofs 0)) ;; indent as normal line
2476 ;; The following assume the (t POS) come first!
2477 (setq ofs val base-value 0)
2478 (setq info nil)))) ;; ? stop now
2479 ((eq a '+) (setq ofs (+ ofs val)))
2480 ((eq a '-) (setq ofs (- ofs val)))
2482 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
2484 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
2486 (error "sh-calculate-indent invalid elt %s" elt)))
2487 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2488 a b val base-value ofs)
2489 (setq info (cdr info)))
2491 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
2494 ((or (null base-value)(null ofs))
2496 ((and (numberp base-value)(numberp ofs))
2497 (sh-debug "base (%d) + ofs (%d) = %d"
2498 base-value ofs (+ base-value ofs))
2499 (+ base-value ofs)) ;; return value
2501 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2506 (defun sh-indent-line (&optional prefix-arg)
2507 "Indent the current line."
2509 (sh-must-be-shell-mode)
2510 (let ((indent (sh-calculate-indent)) shift-amt beg end
2511 (pos (- (point-max) (point))))
2515 (skip-chars-forward " \t")
2516 (setq shift-amt (- indent (current-column)))
2517 (unless (zerop shift-amt)
2518 (delete-region beg (point))
2520 ;; If initial point was within line's indentation,
2521 ;; position after the indentation. Else stay at same point in text.
2522 (if (> (- (point-max) pos) (point))
2523 (goto-char (- (point-max) pos))))))
2526 (defun sh-blink (blinkpos &optional msg)
2527 "Move cursor momentarily to BLINKPOS and display MSG."
2528 ;; We can get here without it being a number on first line
2529 (if (numberp blinkpos)
2531 (goto-char blinkpos)
2533 (sit-for blink-matching-delay))
2536 (defun sh-show-indent (arg)
2537 "Show the how the currently line would be indented.
2538 This tells you which variable, if any, controls the indentation of
2540 If optional arg ARG is non-null (called interactively with a prefix),
2541 a pop up window describes this variable.
2542 If variable `sh-blink' is non-nil then momentarily go to the line
2543 we are indenting relative to, if applicable."
2545 (sh-must-support-indent)
2546 (let* ((info (sh-get-indent-info))
2547 (var (sh-get-indent-var-for-line info))
2548 (curr-indent (current-indentation))
2551 (message (setq msg var))
2552 (setq val (sh-calculate-indent info))
2554 (if (eq curr-indent val)
2555 (setq msg (format "%s is %s" var (symbol-value var)))
2558 (format "%s (%s) would change indent from %d to: %d"
2559 var (symbol-value var) curr-indent val)
2560 (format "%s (%s) would leave line as is"
2561 var (symbol-value var)))
2564 (describe-variable var)))
2566 (let ((info (sh-get-indent-info)))
2567 (if (and info (listp (car info))
2568 (eq (car (car info)) t))
2569 (sh-blink (nth 1 (car info)) msg)
2574 (defun sh-set-indent ()
2575 "Set the indentation for the current line.
2576 If the current line is controlled by an indentation variable, prompt
2577 for a new value for it."
2579 (sh-must-support-indent)
2580 (let* ((info (sh-get-indent-info))
2581 (var (sh-get-indent-var-for-line info))
2582 val val0 new-val old-val indent-val)
2584 (message (format "Cannot set indent - %s" var))
2585 (setq old-val (symbol-value var))
2586 (setq val (sh-read-variable var))
2590 (setq indent-val (sh-calculate-indent info))
2592 (message "Variable: %s Value: %s would indent to: %d"
2593 var (symbol-value var) indent-val)
2594 (message "Variable: %s Value: %s would leave line as is."
2595 var (symbol-value var)))
2596 ;; I'm not sure about this, indenting it now?
2597 ;; No. Because it would give the impression that an undo would
2598 ;; restore thing, but the value has been altered.
2603 (message "Bad value for %s, restoring to previous value %s"
2610 (defun sh-learn-line-indent (arg)
2611 "Learn how to indent a line as it currently is indented.
2613 If there is an indentation variable which controls this line's indentation,
2614 then set it to a value which would indent the line the way it
2617 If the value can be represented by one of the symbols then do so
2618 unless optional argument ARG (the prefix when interactive) is non-nil."
2620 (sh-must-support-indent)
2621 ;; I'm not sure if we show allow learning on an empty line.
2622 ;; Though it might occasionally be useful I think it usually
2623 ;; would just be confusing.
2626 (looking-at "\\s-*$"))
2627 (message "sh-learn-line-indent ignores empty lines.")
2628 (let* ((info (sh-get-indent-info))
2629 (var (sh-get-indent-var-for-line info))
2630 ival sval diff new-val
2632 (curr-indent (current-indentation)))
2635 (message (format "Cannot learn line - %s" var)))
2636 ((eq var 'sh-indent-comment)
2637 ;; This is arbitrary...
2638 ;; - if curr-indent is 0, set to curr-indent
2639 ;; - else if it has the indentation of a "normal" line,
2641 ;; - else set to curr-indent.
2642 (setq sh-indent-comment
2643 (if (= curr-indent 0)
2645 (let* ((sh-indent-comment t)
2646 (val2 (sh-calculate-indent info)))
2647 (if (= val2 curr-indent)
2650 (message "%s set to %s" var (symbol-value var))
2652 ((numberp (setq sval (sh-var-value var)))
2653 (setq ival (sh-calculate-indent info))
2654 (setq diff (- curr-indent ival))
2656 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2657 curr-indent ival diff var sval)
2658 (setq new-val (+ sval diff))
2659 ;;; I commented out this because someone might want to replace
2660 ;;; a value of `+' with the current value of sh-basic-offset
2663 ;;; (message "No change needed!")
2664 (sh-set-var-value var new-val no-symbol)
2665 (message "%s set to %s" var (symbol-value var))
2669 (message "Cannot change %s" var))))))
2673 (defun sh-mark-init (buffer)
2674 "Initialize a BUFFER to be used by `sh-mark-line'."
2675 (let ((main-buffer (current-buffer)))
2677 (set-buffer (get-buffer-create buffer))
2680 (setq occur-buffer main-buffer)
2684 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
2685 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2686 Buffer BUFFER is in `occur-mode'.
2687 If ADD-LINENUM is non-nil the message is preceded by the line number.
2688 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2689 so that `occur-next' and `occur-prev' will work."
2690 (let ((m1 (make-marker))
2691 (main-buffer (current-buffer))
2695 (set-marker m1 point (current-buffer))
2697 (setq line (format "%d: " (1+ (count-lines 1 point))))))
2699 (if (get-buffer buffer)
2700 (set-buffer (get-buffer buffer))
2701 (set-buffer (get-buffer-create buffer))
2703 (setq occur-buffer main-buffer)
2705 (goto-char (point-max))
2706 (setq start (point))
2709 (setq occur-point (point)))
2712 (add-text-properties
2714 '(mouse-face highlight
2715 help-echo "mouse-2: go to the line where I learned this")))
2719 (put-text-property start (point) 'occur m1)
2721 (put-text-property occur-point (1+ occur-point)
2728 ;; Is this really worth having?
2729 (defvar sh-learned-buffer-hook nil
2730 "*An abnormal hook, called with an alist of learned variables.")
2731 ;;; Example of how to use sh-learned-buffer-hook
2733 ;; (defun what-i-learned (list)
2736 ;; (set-buffer "*scratch*")
2737 ;; (goto-char (point-max))
2738 ;; (insert "(setq\n")
2740 ;; (insert (format " %s %s \n"
2741 ;; (nth 0 (car p)) (nth 1 (car p))))
2742 ;; (setq p (cdr p)))
2746 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2749 ;; Originally this was sh-learn-region-indent (beg end)
2750 ;; However, in practice this was awkward so I changed it to
2751 ;; use the whole buffer. Use narrowing if needbe.
2752 (defun sh-learn-buffer-indent (&optional arg)
2753 "Learn how to indent the buffer the way it currently is.
2755 Output in buffer \"*indent*\" shows any lines which have conflicting
2756 values of a variable, and the final value of all variables learned.
2757 This buffer is popped to automatically if there are any discrepancies.
2759 If no prefix ARG is given, then variables are set to numbers.
2760 If a prefix arg is given, then variables are set to symbols when
2761 applicable -- e.g. to symbol `+' if the value is that of the
2763 If a positive numerical prefix is given, then `sh-basic-offset'
2764 is set to the prefix's numerical value.
2765 Otherwise, sh-basic-offset may or may not be changed, according
2766 to the value of variable `sh-learn-basic-offset'.
2768 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2769 function completes. The function is abnormal because it is called
2770 with an alist of variables learned. This feature may be changed or
2771 removed in the future.
2773 This command can often take a long time to run."
2775 (sh-must-support-indent)
2777 (goto-char (point-min))
2778 (let ((learned-var-list nil)
2779 (out-buffer "*indent*")
2786 (comment-col nil) ;; number if all same, t if seen diff values
2787 (comments-always-default t) ;; nil if we see one not default
2789 (specified-basic-offset (and arg (numberp arg)
2793 (setq vec (make-vector max 0))
2794 (sh-mark-init out-buffer)
2796 (if specified-basic-offset
2798 (setq sh-basic-offset arg)
2800 (format "Using specified sh-basic-offset of %d"
2803 (format "Initial value of sh-basic-offset: %s"
2806 (while (< (point) (point-max))
2807 (setq linenum (1+ linenum))
2808 ;; (if (zerop (% linenum 10))
2809 (message "line %d" linenum)
2811 (unless (looking-at "\\s-*$") ;; ignore empty lines!
2812 (let* ((sh-indent-comment t) ;; info must return default indent
2813 (info (sh-get-indent-info))
2814 (var (sh-get-indent-var-for-line info))
2815 sval ival diff new-val
2816 (curr-indent (current-indentation)))
2822 ((numberp (setq sval (sh-var-value var 'no-error)))
2823 ;; the numberp excludes comments since sval will be t.
2824 (setq ival (sh-calculate-indent))
2825 (setq diff (- curr-indent ival))
2826 (setq new-val (+ sval diff))
2827 (sh-set-var-value var new-val 'no-symbol)
2828 (unless (looking-at "\\s-*#") ;; don't learn from comments
2829 (if (setq previous-set-info (assoc var learned-var-list))
2831 ;; it was already there, is it same value ?
2832 (unless (eq (symbol-value var)
2833 (nth 1 previous-set-info))
2835 (format "Variable %s was set to %s"
2836 var (symbol-value var))
2837 (point) out-buffer t t)
2839 (format " but was previously set to %s"
2840 (nth 1 previous-set-info))
2841 (nth 2 previous-set-info) out-buffer t)
2842 (setq num-diffs (1+ num-diffs))
2843 ;; (delete previous-set-info learned-var-list)
2844 (setcdr previous-set-info
2845 (list (symbol-value var) (point)))
2848 (setq learned-var-list
2849 (append (list (list var (symbol-value var)
2852 (if (numberp new-val)
2855 "This line's indent value: %d" new-val)
2857 (setq new-val (- new-val)))
2859 (aset vec new-val (1+ (aref vec new-val))))))
2861 ((eq var 'sh-indent-comment)
2862 (unless (= curr-indent (sh-calculate-indent info))
2863 ;; this is not the default indentation
2864 (setq comments-always-default nil)
2865 (if comment-col ;; then we have see one before
2866 (or (eq comment-col curr-indent)
2867 (setq comment-col t)) ;; seen a different one
2868 (setq comment-col curr-indent))
2871 (sh-debug "Cannot learn this line!!!")
2874 "at %s learned-var-list is %s" (point) learned-var-list)
2881 "comment-col = %s comments-always-default = %s"
2882 comment-col comments-always-default))
2884 (sh-mark-line msg nil out-buffer)))
2887 (setq msg "\nComments are all in 1st column.\n"))
2888 (comments-always-default
2889 (setq msg "\nComments follow default indentation.\n")
2890 (setq comment-col t))
2891 ((numberp comment-col)
2892 (setq msg (format "\nComments are in col %d." comment-col)))
2894 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
2895 (setq comment-col nil)
2898 (sh-mark-line msg nil out-buffer)
2900 (sh-mark-line initial-msg nil out-buffer t t)
2902 (setq suggested (sh-guess-basic-offset vec))
2904 (if (and suggested (not specified-basic-offset))
2907 ;; t => set it if we have a single value as a number
2908 ((and (eq sh-learn-basic-offset t) (numberp suggested))
2910 ;; other non-nil => set it if only one value was found
2911 (sh-learn-basic-offset
2912 (if (numberp suggested)
2914 (if (= (length suggested) 1)
2920 (setq learned-var-list
2921 (append (list (list 'sh-basic-offset
2922 (setq sh-basic-offset new-value)
2925 ;; Not sure if we need to put this line in, since
2926 ;; it will appear in the "Learned variable settings".
2928 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
2931 (if (listp suggested)
2932 (format "Possible value(s) for sh-basic-offset: %s"
2933 (mapconcat 'int-to-string suggested " "))
2934 (format "Suggested sh-basic-offset: %d" suggested))
2938 (setq learned-var-list
2939 (append (list (list 'sh-indent-comment comment-col (point-max)))
2941 (setq sh-indent-comment comment-col)
2942 (let ((name (buffer-name))
2943 (lines (if (and (eq (point-min) 1)
2944 (eq (point-max) (1+ (buffer-size))))
2946 (format "lines %d to %d of "
2947 (1+ (count-lines 1 (point-min)))
2948 (1+ (count-lines 1 (point-max))))))
2950 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
2952 ;; Set learned variables to symbolic rather than numeric
2953 ;; values where possible.
2954 (dolist (learned-var (reverse learned-var-list))
2955 (let ((var (car learned-var))
2956 (val (nth 1 learned-var)))
2957 (when (and (not (eq var 'sh-basic-offset))
2959 (sh-set-var-value var val)))))
2960 (dolist (learned-var (reverse learned-var-list))
2961 (let ((var (car learned-var)))
2962 (sh-mark-line (format " %s %s" var (symbol-value var))
2963 (nth 2 learned-var) out-buffer)))
2965 (set-buffer out-buffer)
2966 (goto-char (point-min))
2968 (format "Indentation values for buffer %s.\n" name)
2969 (format "%d indentation variable%s different values%s\n\n"
2973 (if (zerop num-diffs)
2976 ;; Are abnormal hooks considered bad form?
2977 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
2978 (if (or sh-popup-occur-buffer (> num-diffs 0))
2979 (pop-to-buffer out-buffer))
2982 (defun sh-guess-basic-offset (vec)
2983 "See if we can determine a reasonable value for `sh-basic-offset'.
2984 This is experimental, heuristic and arbitrary!
2985 Argument VEC is a vector of information collected by
2986 `sh-learn-buffer-indent'.
2988 number - there appears to be a good single value
2989 list of numbers - no obvious one, here is a list of one or more
2991 nil - we couldn't find a reasonable one."
2992 (let* ((max (1- (length vec)))
2994 (totals (make-vector max 0))
2998 (aset totals i (+ (aref totals i) (* 4 (aref vec i))))
3001 (aset totals i (+ (aref totals i) (aref vec (/ i 2)))))
3003 (aset totals i (+ (aref totals i) (aref vec (* i 2)))))
3011 (if (/= (aref totals i) 0)
3012 (setq x (append x (list (cons i (aref totals i))))))
3015 (setq x (sort x (lambda (a b) (> (cdr a) (cdr b)))))
3016 (setq tot (apply '+ (append totals nil)))
3017 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3021 (message "no values!")) ;; we return nil
3023 (message "only value is %d" (car (car x)))
3024 (setq result (car (car x)))) ;; return single value
3025 ((> (cdr (car x)) (/ tot 2))
3027 (message "basic-offset is probably %d" (car (car x)))
3028 (setq result (car (car x)))) ;; again, return a single value
3029 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3030 ;; 1st is >= 2 * 2nd
3031 (message "basic-offset could be %d" (car (car x)))
3032 (setq result (car (car x))))
3033 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3034 ;; 1st & 2nd together >= 50% - return a list
3035 (setq p x sum 0 result nil)
3037 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3038 (setq result (append result (list (car (car p)))))
3040 (message "Possible choices for sh-basic-offset: %s"
3041 (mapconcat 'int-to-string result " ")))
3043 (message "No obvious value for sh-basic-offset. Perhaps %d"
3045 ;; result is nil here
3049 ;; ========================================================================
3051 ;; Styles -- a quick and dirty way of saving the indentation settings.
3053 (defvar sh-styles-alist nil
3054 "A list of all known shell indentation styles.")
3056 (defun sh-name-style (name &optional confirm-overwrite)
3057 "Name the current indentation settings as a style called NAME.
3058 If this name exists, the command will prompt whether it should be
3060 - - it was called interactively with a prefix argument, or
3061 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3062 ;; (interactive "sName for this style: ")
3065 (read-from-minibuffer "Name for this style? " )
3066 (not current-prefix-arg)))
3067 (let ((slist (cons name
3068 (mapcar (lambda (var) (cons var (symbol-value var)))
3070 (style (assoc name sh-styles-alist)))
3072 (if (and confirm-overwrite
3073 (not (y-or-n-p "This style exists. Overwrite it? ")))
3074 (message "Not changing style %s" name)
3075 (message "Updating style %s" name)
3076 (setcdr style (cdr slist)))
3077 (message "Creating new style %s" name)
3078 (push slist sh-styles-alist))))
3080 (defun sh-load-style (name)
3081 "Set shell indentation values for this buffer from those in style NAME."
3082 (interactive (list (completing-read
3083 "Which style to use for this buffer? "
3084 sh-styles-alist nil t)))
3085 (let ((sl (assoc name sh-styles-alist)))
3087 (error "sh-load-style - style %s not known" name)
3088 (dolist (var (cdr sl))
3089 (set (car var) (cdr var))))))
3091 (defun sh-save-styles-to-buffer (buff)
3092 "Save all current styles in elisp to buffer BUFF.
3093 This is always added to the end of the buffer."
3095 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3096 (with-current-buffer (get-buffer-create buff)
3097 (goto-char (point-max))
3099 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3103 ;; statement syntax-commands for various shells
3105 ;; You are welcome to add the syntax or even completely new statements as
3106 ;; appropriate for your favorite shell.
3108 (define-skeleton sh-case
3109 "Insert a case/switch statement. See `sh-feature'."
3111 "switch( " str " )" \n
3112 > "case " (read-string "pattern: ") ?: \n
3115 ( "other pattern, %s: "
3125 > "switch( " str " ) {" \n
3126 > "case " (read-string "pattern: ") \n
3128 ( "other pattern, %s: "
3136 > "case " str " in" \n
3137 > (read-string "pattern: ")
3138 (propertize ")" 'syntax-table sh-st-punc)
3142 ( "other pattern, %s: "
3143 > str (propertize ")" 'syntax-table sh-st-punc) \n
3146 > "*" (propertize ")" 'syntax-table sh-st-punc) \n
3151 (define-skeleton sh-for
3152 "Insert a for loop. See `sh-feature'."
3153 (csh eval sh-modify sh
3160 (es eval sh-modify rc
3162 (rc eval sh-modify sh
3166 (sh "Index variable: "
3167 > "for " str " in " _ "; do" \n
3168 > _ | ?$ & (sh-remember-variable str) \n
3173 (define-skeleton sh-indexed-loop
3174 "Insert an indexed loop from 1 to n. See `sh-feature'."
3175 (bash eval identity posix)
3176 (csh "Index variable: "
3178 "while( $" str " <= " (read-string "upper limit: ") " )" \n
3182 (es eval sh-modify rc
3184 (ksh88 "Index variable: "
3185 > "integer " str "=0" \n
3186 > "while (( ( " str " += 1 ) <= "
3187 (read-string "upper limit: ")
3189 > _ ?$ (sh-remember-variable str) > \n
3191 (posix "Index variable: "
3193 "while [ $" str " -le "
3194 (read-string "upper limit: ")
3197 str ?= (sh-add (sh-remember-variable str) 1) \n
3199 (rc "Index variable: "
3200 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
3201 (read-string "upper limit: ")
3202 "; i++ ) print i }'`}) {" \n
3203 > _ ?$ (sh-remember-variable str) \n
3205 (sh "Index variable: "
3206 > "for " str " in `awk 'BEGIN { for( i=1; i<="
3207 (read-string "upper limit: ")
3208 "; i++ ) print i }'`; do" \n
3209 > _ ?$ (sh-remember-variable str) \n
3213 (defun sh-shell-initialize-variables ()
3214 "Scan the buffer for variable assignments.
3215 Add these variables to `sh-shell-variables'."
3216 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3218 (goto-char (point-min))
3219 (setq sh-shell-variables-initialized t)
3220 (while (search-forward "=" nil t)
3222 (message "Scanning buffer `%s' for variable assignments...done"
3225 (defvar sh-add-buffer)
3227 (defun sh-add-completer (string predicate code)
3228 "Do completion using `sh-shell-variables', but initialize it first.
3229 This function is designed for use as the \"completion table\",
3230 so it takes three arguments:
3231 STRING, the current buffer contents;
3232 PREDICATE, the predicate for filtering possible matches;
3233 CODE, which says what kind of things to do.
3234 CODE can be nil, t or `lambda'.
3235 nil means to return the best completion of STRING, or nil if there is none.
3236 t means to return a list of all possible completions of STRING.
3237 `lambda' means to return t if STRING is a valid completion as it stands."
3238 (let ((sh-shell-variables
3240 (set-buffer sh-add-buffer)
3241 (or sh-shell-variables-initialized
3242 (sh-shell-initialize-variables))
3243 (nconc (mapcar (lambda (var)
3245 (substring var 0 (string-match "=" var))))
3247 process-environment)
3248 sh-shell-variables))))
3250 (try-completion string sh-shell-variables predicate))
3252 (all-completions string sh-shell-variables predicate))
3254 (assoc string sh-shell-variables)))))
3256 (defun sh-add (var delta)
3257 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3259 (let ((sh-add-buffer (current-buffer)))
3260 (list (completing-read "Variable: " 'sh-add-completer)
3261 (prefix-numeric-value current-prefix-arg))))
3262 (insert (sh-feature '((bash . "$[ ")
3268 (sh-remember-variable var)
3269 (if (< delta 0) " - " " + ")
3270 (number-to-string (abs delta))
3271 (sh-feature '((bash . " ]")
3280 (define-skeleton sh-function
3281 "Insert a function definition. See `sh-feature'."
3282 (bash eval sh-modify ksh88
3285 "function " str " {" \n
3288 (rc eval sh-modify ksh88
3297 (define-skeleton sh-if
3298 "Insert an if statement. See `sh-feature'."
3300 "if( " str " ) then" \n
3302 ( "other condition, %s: "
3303 < "else if( " str " ) then" \n
3310 > "if { " str " } {" \n
3312 ( "other condition, %s: "
3313 "} { " str " } {" > \n
3320 > "if( " str " ) {" \n
3322 ( "other condition, %s: "
3323 "} else if( " str " ) {" > \n
3331 '(setq input (sh-feature sh-test))
3332 > "if " str "; then" \n
3334 ( "other condition, %s: "
3335 > "elif " str "; then" > \n
3344 (define-skeleton sh-repeat
3345 "Insert a repeat loop definition. See `sh-feature'."
3351 > "repeat " str "; do" > \n
3355 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3359 (define-skeleton sh-select
3360 "Insert a select statement. See `sh-feature'."
3361 (ksh88 "Index variable: "
3362 > "select " str " in " _ "; do" \n
3365 (bash eval sh-append ksh88))
3366 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3370 (define-skeleton sh-tmp-file
3371 "Insert code to setup temporary file handling. See `sh-feature'."
3372 (bash eval identity ksh88)
3373 (csh (file-name-nondirectory (buffer-file-name))
3374 "set tmp = /tmp/" str ".$$" \n
3376 (and (goto-char (point-max))
3380 "rm $tmp* >&/dev/null" >)
3381 (es (file-name-nondirectory (buffer-file-name))
3382 > "local( signals = $signals sighup sigint; tmp = /tmp/" str
3385 > "rm $tmp^* >[2]/dev/null" \n
3391 (ksh88 eval sh-modify sh
3393 (rc (file-name-nondirectory (buffer-file-name))
3394 > "tmp = /tmp/" str ".$pid" \n
3395 "fn sigexit { rm $tmp^* >[2]/dev/null }")
3396 (sh (file-name-nondirectory (buffer-file-name))
3397 > "TMP=${TMPDIR:-/tmp}/" str ".$$" \n
3398 "trap \"rm $TMP* 2>/dev/null\" " ?0))
3402 (define-skeleton sh-until
3403 "Insert an until loop. See `sh-feature'."
3405 '(setq input (sh-feature sh-test))
3406 > "until " str "; do" \n
3409 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3413 (define-skeleton sh-while
3414 "Insert a while loop. See `sh-feature'."
3415 (csh eval sh-modify sh
3421 (es eval sh-modify sh
3425 (rc eval sh-modify sh
3430 '(setq input (sh-feature sh-test))
3431 > "while " str "; do" \n
3437 (define-skeleton sh-while-getopts
3438 "Insert a while getopts loop. See `sh-feature'.
3439 Prompts for an options string which consists of letters for each recognized
3440 option followed by a colon `:' if the option accepts an argument."
3441 (bash eval sh-modify sh
3445 > "switch( \"$1\" )" \n
3446 '(setq input '("- x" . 2))
3449 < "case " '(eval str)
3450 '(if (string-match " +" str)
3451 (setq v1 (substring str (match-end 0))
3452 str (substring str 0 (match-beginning 0)))
3455 > "set " v1 & " = $2" | -4 & _ \n
3456 (if v1 "shift") & \n
3466 (ksh88 eval sh-modify sh
3470 (posix eval sh-modify sh
3471 18 "$(basename $0)")
3473 > "while getopts :" str " OPT; do" \n
3475 '(setq v1 (append (vconcat str) nil))
3476 ( (prog1 (if v1 (char-to-string (car v1)))
3477 (if (eq (nth 1 v1) ?:)
3478 (setq v1 (nthcdr 2 v1)
3482 > str "|+" str (propertize ")" 'syntax-table sh-st-punc) \n
3485 > "*" (propertize ")" 'syntax-table sh-st-punc) \n
3486 > "echo" " \"usage: " "`basename $0`"
3487 " [+-" '(setq v1 (point)) str
3489 (while (search-backward ":" v1 t)
3490 (replace-match " ARG] [+-" t t)))
3491 (if (eq (preceding-char) ?-) -5)
3492 (if (and (sequencep v1) (length v1)) "] " "} ")
3498 "shift " (sh-add "OPTIND" -1)))
3502 (defun sh-assignment (arg)
3503 "Remember preceding identifier for future completion and do self-insert."
3505 (self-insert-command arg)
3507 (sh-remember-variable
3509 (if (re-search-forward (sh-feature sh-assignment-regexp)
3511 (beginning-of-line 1))
3513 (match-string 1))))))
3517 (defun sh-maybe-here-document (arg)
3518 "Insert self. Without prefix, following unquoted `<' inserts here document.
3519 The document is bounded by `sh-here-document-word'."
3521 (self-insert-command (prefix-numeric-value arg))
3523 (not (eq (char-after (- (point) 2)) last-command-char))
3528 (insert sh-here-document-word)
3529 (or (eolp) (looking-at "[ \t]") (insert ? ))
3535 (save-excursion (insert ?\n sh-here-document-word)))))
3538 ;; various other commands
3540 (autoload 'comint-dynamic-complete "comint"
3541 "Dynamically perform completion at point." t)
3543 (autoload 'shell-dynamic-complete-command "shell"
3544 "Dynamically complete the command at point." t)
3546 (autoload 'comint-dynamic-complete-filename "comint"
3547 "Dynamically complete the filename at point." t)
3549 (autoload 'shell-dynamic-complete-environment-variable "shell"
3550 "Dynamically complete the environment variable at point." t)
3554 (defun sh-newline-and-indent ()
3555 "Strip unquoted whitespace, insert newline, and indent like current line."
3557 (indent-to (prog1 (current-indentation)
3558 (delete-region (point)
3560 (or (zerop (skip-chars-backward " \t"))
3566 (defun sh-beginning-of-command ()
3567 "Move point to successive beginnings of commands."
3569 (if (re-search-backward sh-beginning-of-command nil t)
3570 (goto-char (match-beginning 2))))
3572 (defun sh-end-of-command ()
3573 "Move point to successive ends of commands."
3575 (if (re-search-forward sh-end-of-command nil t)
3576 (goto-char (match-end 1))))
3579 ;;;###autoload(add-to-list 'auto-mode-alist '("/\\.\\(?:bash_\\|z\\)?\\(profile\\|login\\|logout\\)\\'" . sh-mode))
3580 ;;;###autoload(add-to-list 'auto-mode-alist '("/\\.\\(?:[ckz]sh\\|bash\\|tcsh\\|es\\|xinit\\|startx\\)rc\\(?:\\.in\\)?\\'" . sh-mode))
3581 ;;;###autoload(add-to-list 'auto-mode-alist '("/\\.\\(?:[kz]shenv\\|xsession\\)\\'" . sh-mode))
3582 ;;;###autoload(setq auto-mode-alist (append auto-mode-alist '(("\\.m?spec$" . sh-mode))))
3583 ;;;###autoload(add-to-list 'auto-mode-alist '("\\.\\(?:\\(?:ba\\|[ckz]\\)?sh\\|shar\\)\\(?:\\.in\\)?\\'" . sh-mode))
3584 ;;;###autoload(add-to-list 'interpreter-mode-alist '("^#!.*csh" . sh-mode))
3585 ;;;###autoload(add-to-list 'interpreter-mode-alist '("^#!.*sh\\b" . sh-mode))
3586 ;;;###autoload(add-to-list 'interpreter-mode-alist '("^:" . sh-mode))
3588 (provide 'sh-script)
3590 ;;; sh-script.el ends here