1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993, 94, 95, 96, 97, 1999 by Free Software Foundation, Inc.
5 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
8 ;; Keywords: languages, unix
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
29 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
30 ;; as various derivatives are supported and easily derived from. Structured
31 ;; statements can be inserted with one command or abbrev. Completion is
32 ;; available for filenames, variables known from the script, the shell and
33 ;; the environment as well as commands.
37 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
38 ;; - Variables in `"' strings aren't fontified because there's no way of
39 ;; syntactically distinguishing those from `'' strings.
43 ;; Indentation for rc and es modes is very limited, but for Bourne shells
44 ;; and its derivatives it is quite customizable.
46 ;; The following description applies to sh and derived shells (bash,
49 ;; There are various customization variables which allow tailoring to
50 ;; a wide variety of styles. Most of these variables are named
51 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
52 ;; sh-indent-after-if controls the indenting of a line following
53 ;; an if statement, and sh-indent-for-fi controls the indentation
54 ;; of the line containing the fi.
56 ;; You can set each to a numeric value, but it is often more convenient
57 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
58 ;; By changing this one variable you can increase or decrease how much
59 ;; indentation there is. Valid symbols:
61 ;; + Indent right by sh-basic-offset
62 ;; - Indent left by sh-basic-offset
63 ;; ++ Indent right twice sh-basic-offset
64 ;; -- Indent left twice sh-basic-offset
65 ;; * Indent right half sh-basic-offset
66 ;; / Indent left half sh-basic-offset.
68 ;; There are 4 commands to help set the indentation variables:
71 ;; This shows what variable controls the indentation of the current
72 ;; line and its value.
75 ;; This allows you to set the value of the variable controlling the
76 ;; current line's indentation. You can enter a number or one of a
77 ;; number of special symbols to denote the value of sh-basic-offset,
78 ;; or its negative, or half it, or twice it, etc. If you've used
79 ;; cc-mode this should be familiar. If you forget which symbols are
80 ;; valid simply press C-h at the prompt.
82 ;; `sh-learn-line-indent'
83 ;; Simply make the line look the way you want it, then invoke this
84 ;; command. It will set the variable to the value that makes the line
85 ;; indent like that. If called with a prefix argument then it will set
86 ;; the value to one of the symbols if applicable.
88 ;; `sh-learn-buffer-indent'
89 ;; This is the deluxe function! It "learns" the whole buffer (use
90 ;; narrowing if you want it to process only part). It outputs to a
91 ;; buffer *indent* any conflicts it finds, and all the variables it has
92 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
93 ;; easily find where something was set. It is popped to automatically
94 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
96 ;; `sh-indent-comment' will be set if all comments follow the same
97 ;; pattern; if they don't it will be set to nil.
98 ;; Whether `sh-basic-offset' is set is determined by variable
99 ;; `sh-learn-basic-offset'.
101 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
102 ;; (e.g. if there are large case statements). Perhaps it does not make
103 ;; sense to run it on large buffers: if lots of lines have different
104 ;; indentation styles it will produce a lot of diagnostics in the
105 ;; *indent* buffer; if there is a consistent style then running
106 ;; `sh-learn-buffer-indent' on a small region of the buffer should
109 ;; Saving indentation values
110 ;; -------------------------
111 ;; After you've learned the values in a buffer, how to you remember
112 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
113 ;; would make this unnecessary; simply learn the values when you visit
115 ;; You can do this automatically like this:
116 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
118 ;; However... `sh-learn-buffer-indent' is extremely slow,
119 ;; especially on large-ish buffer. Also, if there are conflicts the
120 ;; "last one wins" which may not produce the desired setting.
122 ;; So...There is a minimal way of being able to save indentation values and
123 ;; to reload them in another buffer or at another point in time.
125 ;; Use `sh-name-style' to give a name to the indentation settings of
126 ;; the current buffer.
127 ;; Use `sh-load-style' to load indentation settings for the current
128 ;; buffer from a specific style.
129 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
130 ;; in lisp code. You can then store it in a file and later use
131 ;; `load-file' to load it.
133 ;; Indentation variables - buffer local or global?
134 ;; ----------------------------------------------
135 ;; I think that often having them buffer-local makes sense,
136 ;; especially if one is using `sh-learn-buffer-indent'. However, if
137 ;; a user sets values using customization, these changes won't appear
138 ;; to work if the variables are already local!
140 ;; To get round this, there is a variable `sh-make-vars-local' and 2
141 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
143 ;; If `sh-make-vars-local' is non-nil, then these variables become
144 ;; buffer local when the mode is established.
145 ;; If this is nil, then the variables are global. At any time you
146 ;; can make them local with the command `sh-make-vars-local'.
147 ;; Conversely, to update with the global values you can use the
148 ;; command `sh-reset-indent-vars-to-global-values'.
150 ;; This may be awkward, but the intent is to cover all cases.
152 ;; Awkward things, pitfalls
153 ;; ------------------------
154 ;; Indentation for a sh script is complicated for a number of reasons:
156 ;; 1. You can't format by simply looking at symbols, you need to look
157 ;; at keywords. [This is not the case for rc and es shells.]
158 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
159 ;; as a stand-alone symbol (in a case alternative). This makes
160 ;; things quite tricky!
161 ;; 3. Here-documents in a script should be treated "as is", and when
162 ;; they terminate we want to revert to the indentation of the line
163 ;; containing the "<<" symbol.
164 ;; 4. A line may be continued using the "\".
165 ;; 5. The character "#" (outside a string) normally starts a comment,
166 ;; but it doesn't in the sequence "$#"!
168 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
169 ;; uses, that of a text's syntax property. This, however, has 2
171 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
172 ;; case alternative, to find any here documents, and handle "$#".
173 ;; 2. Setting the text property makes the buffer modified. If the
174 ;; buffer is read-only buffer we have to cheat and bypass the read-only
175 ;; status. This is for cases where the buffer started read-only buffer
176 ;; but the user issued `toggle-read-only'.
180 ;; - Indenting many lines is slow. It currently does each line
181 ;; independently, rather than saving state information.
183 ;; - `sh-learn-buffer-indent' is extremely slow.
185 ;; Richard Sharman <rsharman@pobox.com> June 1999.
189 ;; page 1: variables and settings
190 ;; page 2: indentation stuff
191 ;; page 3: mode-command and utility functions
192 ;; page 4: statement syntax-commands for various shells
193 ;; page 5: various other commands
198 (require 'executable
)
203 "Shell programming utilities"
207 (defgroup sh-script nil
213 (defcustom sh-ancestor-alist
232 "*Alist showing the direct ancestor of various shells.
233 This is the basis for `sh-feature'. See also `sh-alias-alist'.
234 By default we have the following three hierarchies:
237 jcsh C Shell with Job Control
239 itcsh ? Toronto C Shell
244 jsh Bourne Shell with Job Control
245 bash GNU Bourne Again Shell
248 dtksh CDE Desktop Korn Shell
249 pdksh Public Domain Korn Shell
250 wksh Window Korn Shell
252 oash SCO OA (curses) Shell
253 posix IEEE 1003.2 Shell Standard
255 :type
'(repeat (cons symbol symbol
))
259 (defcustom sh-alias-alist
260 (nconc (if (eq system-type
'gnu
/linux
)
263 ;; for the time being
267 "*Alist for transforming shell names to what they really are.
268 Use this where the name of the executable doesn't correspond to the type of
270 :type
'(repeat (cons symbol symbol
))
274 (defcustom sh-shell-file
276 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
277 ;; the executable extension, so comparisons with the list of
278 ;; known shells work.
279 (and (memq system-type
'(ms-dos windows-nt
))
280 (let* ((shell (getenv "SHELL"))
282 (and shell
(file-name-nondirectory shell
))))
283 ;; shell-script mode doesn't support DOS/Windows shells,
284 ;; so use the default instead.
286 (member (downcase shell-base
)
287 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
290 (file-name-sans-extension (downcase shell
)))))
293 "*The executable file name for the shell being programmed."
298 (defcustom sh-shell-arg
299 ;; bash does not need any options when run in a shell script,
303 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
305 ;; -p means don't initialize functions from the environment.
307 ;; Someone proposed -motif, but we don't want to encourage
308 ;; use of a non-free widget set.
310 ;; -f means don't run .zshrc.
312 "*Single argument string for the magic number. See `sh-feature'."
313 :type
'(repeat (cons (symbol :tag
"Shell")
314 (choice (const :tag
"No Arguments" nil
)
315 (string :tag
"Arguments")
316 (cons :format
"Evaluate: %v"
317 (const :format
"" eval
)
321 (defcustom sh-imenu-generic-expression
323 .
((nil "^\\s-*\\(function\\s-+\\)?\\([A-Za-z_][A-Za-z_0-9]+\\)\\s-*()" 2))))
324 "*Regular expression for recognizing shell function definitions.
326 :type
'(repeat (cons (symbol :tag
"Shell")
331 (defvar sh-shell-variables nil
332 "Alist of shell variable names that should be included in completion.
333 These are used for completion in addition to all the variables named
334 in `process-environment'. Each element looks like (VAR . VAR), where
335 the car and cdr are the same symbol.")
337 (defvar sh-shell-variables-initialized nil
338 "Non-nil if `sh-shell-variables' is initialized.")
340 (defun sh-canonicalize-shell (shell)
341 "Convert a shell name SHELL to the one we should handle it as."
342 (if (string-match "\\.exe\\'" shell
)
343 (setq shell
(substring shell
0 (match-beginning 0))))
345 (setq shell
(intern shell
)))
346 (or (cdr (assq shell sh-alias-alist
))
349 (defvar sh-shell
(sh-canonicalize-shell (file-name-nondirectory sh-shell-file
))
350 "The shell being programmed. This is set by \\[sh-set-shell].")
352 ;;; I turned off this feature because it doesn't permit typing commands
353 ;;; in the usual way without help.
354 ;;;(defvar sh-abbrevs
355 ;;; '((csh eval sh-abbrevs shell
356 ;;; "switch" 'sh-case
357 ;;; "getopts" 'sh-while-getopts)
359 ;;; (es eval sh-abbrevs shell
360 ;;; "function" 'sh-function)
362 ;;; (ksh88 eval sh-abbrevs sh
363 ;;; "select" 'sh-select)
365 ;;; (rc eval sh-abbrevs shell
367 ;;; "function" 'sh-function)
369 ;;; (sh eval sh-abbrevs shell
371 ;;; "function" 'sh-function
372 ;;; "until" 'sh-until
373 ;;; "getopts" 'sh-while-getopts)
375 ;;; ;; The next entry is only used for defining the others
376 ;;; (shell "for" sh-for
377 ;;; "loop" sh-indexed-loop
379 ;;; "tmpfile" sh-tmp-file
380 ;;; "while" sh-while)
382 ;;; (zsh eval sh-abbrevs ksh88
383 ;;; "repeat" 'sh-repeat))
384 ;;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
385 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
386 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
390 (defvar sh-mode-syntax-table
391 '((sh eval sh-mode-syntax-table
()
406 (csh eval identity sh
)
407 (rc eval identity sh
))
408 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
413 (let ((map (make-sparse-keymap))
414 (menu-map (make-sparse-keymap "Insert")))
415 (define-key map
"\C-c(" 'sh-function
)
416 (define-key map
"\C-c\C-w" 'sh-while
)
417 (define-key map
"\C-c\C-u" 'sh-until
)
418 (define-key map
"\C-c\C-t" 'sh-tmp-file
)
419 (define-key map
"\C-c\C-s" 'sh-select
)
420 (define-key map
"\C-c\C-r" 'sh-repeat
)
421 (define-key map
"\C-c\C-o" 'sh-while-getopts
)
422 (define-key map
"\C-c\C-l" 'sh-indexed-loop
)
423 (define-key map
"\C-c\C-i" 'sh-if
)
424 (define-key map
"\C-c\C-f" 'sh-for
)
425 (define-key map
"\C-c\C-c" 'sh-case
)
426 (define-key map
"\C-c?" 'sh-show-indent
)
427 (define-key map
"\C-c=" 'sh-set-indent
)
428 (define-key map
"\C-c<" 'sh-learn-line-indent
)
429 (define-key map
"\C-c>" 'sh-learn-buffer-indent
)
431 (define-key map
"=" 'sh-assignment
)
432 (define-key map
"\C-c+" 'sh-add
)
433 (define-key map
"\C-\M-x" 'sh-execute-region
)
434 (define-key map
"\C-c\C-x" 'executable-interpret
)
435 (define-key map
"<" 'sh-maybe-here-document
)
436 (define-key map
"(" 'skeleton-pair-insert-maybe
)
437 (define-key map
"{" 'skeleton-pair-insert-maybe
)
438 (define-key map
"[" 'skeleton-pair-insert-maybe
)
439 (define-key map
"'" 'skeleton-pair-insert-maybe
)
440 (define-key map
"`" 'skeleton-pair-insert-maybe
)
441 (define-key map
"\"" 'skeleton-pair-insert-maybe
)
443 (substitute-key-definition 'complete-tag
'comint-dynamic-complete
444 map
(current-global-map))
445 (substitute-key-definition 'newline-and-indent
'sh-newline-and-indent
446 map
(current-global-map))
447 (substitute-key-definition 'delete-backward-char
448 'backward-delete-char-untabify
449 map
(current-global-map))
450 (define-key map
"\C-c:" 'sh-set-shell
)
451 (substitute-key-definition 'beginning-of-defun
452 'sh-beginning-of-compound-command
453 map
(current-global-map))
454 (substitute-key-definition 'backward-sentence
'sh-beginning-of-command
455 map
(current-global-map))
456 (substitute-key-definition 'forward-sentence
'sh-end-of-command
457 map
(current-global-map))
458 (define-key map
[menu-bar insert
] (cons "Insert" menu-map
))
459 (define-key menu-map
[sh-while
] '("While Loop" . sh-while
))
460 (define-key menu-map
[sh-until
] '("Until Loop" . sh-until
))
461 (define-key menu-map
[sh-tmp-file
] '("Temporary File" . sh-tmp-file
))
462 (define-key menu-map
[sh-select
] '("Select Statement" . sh-select
))
463 (define-key menu-map
[sh-repeat
] '("Repeat Loop" . sh-repeat
))
464 (define-key menu-map
[sh-getopts
] '("Options Loop" . sh-while-getopts
))
465 (define-key menu-map
[sh-indexed-loop
] '("Indexed Loop" . sh-indexed-loop
))
466 (define-key menu-map
[sh-if
] '("If Statement" . sh-if
))
467 (define-key menu-map
[sh-for
] '("For Loop" . sh-for
))
468 (define-key menu-map
[sh-case
] '("Case Statement" . sh-case
))
470 "Keymap used in Shell-Script mode.")
474 (defcustom sh-dynamic-complete-functions
475 '(shell-dynamic-complete-environment-variable
476 shell-dynamic-complete-command
477 comint-dynamic-complete-filename
)
478 "*Functions for doing TAB dynamic completion."
479 :type
'(repeat function
)
483 (defcustom sh-require-final-newline
486 (rc eval . require-final-newline
)
487 (sh eval . require-final-newline
))
488 "*Value of `require-final-newline' in Shell-Script mode buffers.
490 :type
'(repeat (cons (symbol :tag
"Shell")
491 (choice (const :tag
"require" t
)
492 (cons :format
"Evaluate: %v"
493 (const :format
"" eval
)
498 (defcustom sh-assignment-regexp
499 '((csh .
"\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
500 ;; actually spaces are only supported in let/(( ... ))
501 (ksh88 .
"\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
502 (rc .
"\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
503 (sh .
"\\<\\([a-zA-Z0-9_]+\\)="))
504 "*Regexp for the variable name and what may follow in an assignment.
505 First grouping matches the variable name. This is upto and including the `='
506 sign. See `sh-feature'."
507 :type
'(repeat (cons (symbol :tag
"Shell")
509 (cons :format
"Evaluate: %v"
510 (const :format
"" eval
)
515 (defcustom sh-indentation
4
516 "The width for further indentation in Shell-Script mode."
521 (defcustom sh-remember-variable-min
3
522 "*Don't remember variables less than this length for completing reads."
527 (defvar sh-header-marker nil
528 "When non-nil is the end of header for prepending by \\[sh-execute-region].
529 That command is also used for setting this variable.")
532 (defcustom sh-beginning-of-command
533 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
534 "*Regexp to determine the beginning of a shell command.
535 The actual command starts at the beginning of the second \\(grouping\\)."
540 (defcustom sh-end-of-command
541 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
542 "*Regexp to determine the end of a shell command.
543 The actual command ends at the end of the first \\(grouping\\)."
549 (defvar sh-here-document-word
"EOF"
550 "Word to delimit here documents.")
555 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
558 ;; customized this out of sheer bravado. not for the faint of heart.
559 ;; but it *did* have an asterisk in the docstring!
560 (defcustom sh-builtins
561 '((bash eval sh-append posix
562 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
563 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
564 "suspend" "typeset" "unalias")
566 ;; The next entry is only used for defining the others
567 (bourne eval sh-append shell
568 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
571 (csh eval sh-append shell
572 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
573 "setenv" "source" "time" "unalias" "unhash")
575 (dtksh eval identity wksh
)
577 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
578 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
580 (jsh eval sh-append sh
581 "bg" "fg" "jobs" "kill" "stop" "suspend")
583 (jcsh eval sh-append csh
584 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
586 (ksh88 eval sh-append bourne
587 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
588 "typeset" "unalias" "whence")
590 (oash eval sh-append sh
591 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
592 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
593 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
594 "wmtitle" "wrefresh")
596 (pdksh eval sh-append ksh88
599 (posix eval sh-append sh
602 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
605 (sh eval sh-append bourne
606 "hash" "test" "type")
608 ;; The next entry is only used for defining the others
609 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
611 (wksh eval sh-append ksh88
614 (zsh eval sh-append ksh88
615 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
616 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
617 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
618 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
619 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
621 "*List of all shell builtins for completing read and fontification.
622 Note that on some systems not all builtins are available or some are
623 implemented as aliases. See `sh-feature'."
624 :type
'(repeat (cons (symbol :tag
"Shell")
625 (choice (repeat string
)
626 (cons :format
"Evaluate: %v"
627 (const :format
"" eval
)
633 (defcustom sh-leading-keywords
636 (es "true" "unwind-protect" "whatis")
640 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
641 "*List of keywords that may be immediately followed by a builtin or keyword.
642 Given some confusion between keywords and builtins depending on shell and
643 system, the distinction here has been based on whether they influence the
644 flow of control or syntax. See `sh-feature'."
645 :type
'(repeat (cons (symbol :tag
"Shell")
646 (choice (repeat string
)
647 (cons :format
"Evaluate: %v"
648 (const :format
"" eval
)
653 (defcustom sh-other-keywords
654 '((bash eval sh-append bourne
657 ;; The next entry is only used for defining the others
658 (bourne eval sh-append sh
661 (csh eval sh-append shell
662 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
663 "if" "logout" "onintr" "repeat" "switch" "then" "while")
665 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
666 "return" "throw" "while")
668 (ksh88 eval sh-append bourne
671 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
674 (sh eval sh-append shell
675 "done" "esac" "fi" "for" "in" "return")
677 ;; The next entry is only used for defining the others
678 (shell "break" "case" "continue" "exec" "exit")
680 (zsh eval sh-append bash
682 "*List of keywords not in `sh-leading-keywords'.
684 :type
'(repeat (cons (symbol :tag
"Shell")
685 (choice (repeat string
)
686 (cons :format
"Evaluate: %v"
687 (const :format
"" eval
)
694 '((bash eval sh-append sh
695 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
696 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
697 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
698 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
699 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
700 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
701 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
702 "SECONDS" "SHLVL" "TMOUT" "UID")
704 (csh eval sh-append shell
705 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
706 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
707 "shell" "status" "time" "verbose")
709 (es eval sh-append shell
710 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
711 "pid" "prompt" "signals")
713 (jcsh eval sh-append csh
716 (ksh88 eval sh-append sh
717 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
718 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
721 (oash eval sh-append sh
722 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
724 (rc eval sh-append shell
725 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
728 (sh eval sh-append shell
729 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
731 ;; The next entry is only used for defining the others
732 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
733 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
734 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
735 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
737 (tcsh eval sh-append csh
738 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
739 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
740 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
741 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
742 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
743 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
744 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
745 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
748 (zsh eval sh-append ksh88
749 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
750 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
751 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
752 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
753 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
754 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
755 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
756 "List of all shell variables available for completing read.
761 (defvar sh-font-lock-keywords
762 '((csh eval sh-append shell
763 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
764 font-lock-variable-name-face
))
766 (es eval sh-append executable-font-lock-keywords
767 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
768 font-lock-variable-name-face
))
770 (rc eval identity es
)
772 (sh eval sh-append shell
774 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
775 font-lock-variable-name-face
)
777 '("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face
)
778 '("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
779 (1 font-lock-keyword-face
) (2 font-lock-function-name-face nil t
)))
781 ;; The next entry is only used for defining the others
782 (shell eval sh-append executable-font-lock-keywords
783 '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face
)
784 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
785 font-lock-variable-name-face
))
786 (rpm eval sh-append rpm2
787 '("%{?\\(\\sw+\\)" 1 font-lock-keyword-face
))
788 (rpm2 eval sh-append shell
789 '("^\\(\\sw+\\):" 1 font-lock-variable-name-face
)))
790 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
792 (defvar sh-font-lock-keywords-1
794 "Subdued level highlighting for Shell Script modes.")
796 (defvar sh-font-lock-keywords-2
()
797 "Gaudy level highlighting for Shell Script modes.")
799 ;; These are used for the syntax table stuff (derived from cperl-mode).
800 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
801 (defconst sh-st-punc
(string-to-syntax "."))
802 (defconst sh-here-doc-syntax
(string-to-syntax "|")) ;; generic string
804 (defun sh-font-lock-heredoc (start string quoted
)
805 "Determine the syntax of the \\n after a <<HEREDOC."
806 (unless (sh-in-comment-or-string start
)
807 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
808 ;; font-lock keywords to detect the end of this here document.
810 "^" (if quoted
"[ \t]*")
811 (regexp-quote (replace-regexp-in-string "['\"]" "" string
))
813 (unless (assoc ere font-lock-syntactic-keywords
)
814 (let* ( ;; A rough regexp that should find us back.
815 (sre (concat "<<\\(-\\)?\\s-*['\"]?"
816 (regexp-quote string
) "['\"]?[ \t\n]"))
818 ((save-excursion (re-search-backward ,sre nil t
))
819 ;; This ^STRING$ is indeed following a <<STRING
821 ((not (save-excursion (re-search-forward ,sre nil t
)))
822 ;; There's no <<STRING either before or after us,
823 ;; so we should remove this now obsolete entry.
824 (setq font-lock-syntactic-keywords
825 (delq (assoc ,ere font-lock-syntactic-keywords
)
826 font-lock-syntactic-keywords
))
828 ;; Use destructive update so the new keyword gets used right away.
829 (setq font-lock-syntactic-keywords
830 (nconc font-lock-syntactic-keywords
831 (list (font-lock-compile-keyword `(,ere
1 ,code
))))))))
834 (defun sh-font-lock-paren (start)
837 ;; Skip through all patterns
840 (forward-comment (- (point-max)))
841 ;; Skip through one pattern
843 (or (/= 0 (skip-syntax-backward "w_"))
844 (/= 0 (skip-chars-backward "?*/"))
845 (when (memq (char-before) '(?
\" ?
\'))
846 (condition-case nil
(progn (backward-sexp 1) t
)
848 (forward-comment (- (point-max)))
849 (when (eq (char-before) ?|
)
850 (backward-char 1) t
)))
851 (when (save-excursion (backward-char 2) (looking-at ";;\\|in"))
854 (defconst sh-font-lock-syntactic-keywords
855 ;; Mark a `#' character as having punctuation syntax in a variable reference.
856 ;; Really we should do this properly. From Chet Ramey and Brian Fox:
857 ;; "A `#' begins a comment when it is unquoted and at the beginning of a
858 ;; word. In the shell, words are separated by metacharacters."
859 ;; To do this in a regexp would be slow as it would be anchored to the right.
860 ;; But I can't be bothered to write a function to do it properly and
861 ;; efficiently. So we only do it properly for `#' in variable references and
862 ;; do it efficiently by anchoring the regexp to the left.
863 `(("\\${?[^}#\n\t ]*\\(##?\\)" 1 ,sh-st-punc
)
864 ;; Find HEREDOC starters and add a corresponding rule for the ender.
865 ("[^<>]<<\\(-\\)?\\s-*\\(\\(['\"][^'\"]+['\"]\\|\\sw\\|\\s_\\)+\\).*\\(\n\\)"
866 4 (sh-font-lock-heredoc
867 (match-beginning 0) (match-string 2) (match-end 1)))
868 ;; Distinguish the special close-paren in `case'.
869 (")" 0 (sh-font-lock-paren (match-beginning 0)))))
871 (defgroup sh-indentation nil
872 "Variables controlling indentation in shell scripts.
874 Note: customizing these variables will not affect existing buffers if
875 `sh-make-vars-local' is no-nil. See the documentation for
876 variable `sh-make-vars-local', command `sh-make-vars-local'
877 and command `sh-reset-indent-vars-to-global-values'."
881 (defcustom sh-set-shell-hook nil
882 "*Hook run by `sh-set-shell'."
886 (defcustom sh-mode-hook nil
887 "*Hook run by `sh-mode'."
891 (defcustom sh-learn-basic-offset nil
892 "*When `sh-guess-basic-offset' should learn `sh-basic-offset'.
895 t means: only if there seems to be an obvious value.
896 Anything else means: whenever we have a \"good guess\" as to the value."
898 (const :tag
"Never" nil
)
899 (const :tag
"Only if sure" t
)
900 (const :tag
"If have a good guess" usually
))
901 :group
'sh-indentation
)
903 (defcustom sh-popup-occur-buffer nil
904 "*Controls when `sh-learn-buffer-indent' pops the *indent* buffer.
905 If t it is always shown. If nil, it is shown only when there
908 (const :tag
"Only when there are conflicts." nil
)
909 (const :tag
"Always" t
))
910 :group
'sh-indentation
)
912 (defcustom sh-blink t
913 "*If non-nil, `sh-show-indent' shows the line indentation is relative to.
914 The position on the line is not necessarily meaningful.
915 In some cases the line will be the matching keyword, but this is not
918 :group
'sh-indentation
)
920 (defcustom sh-first-lines-indent
0
921 "*The indentation of the first non-blank non-comment line.
922 Usually 0 meaning first column.
923 Can be set to a number, or to nil which means leave it as is."
925 (const :tag
"Leave as is" nil
)
926 (integer :tag
"Column number"
927 :menu-tag
"Indent to this col (0 means first col)" ))
928 :group
'sh-indentation
)
931 (defcustom sh-basic-offset
4
932 "*The default indentation increment.
933 This value is used for the + and - symbols in an indentation variable."
935 :group
'sh-indentation
)
937 (defcustom sh-indent-comment nil
938 "*How a comment line is to be indented.
939 nil means leave it as it is;
940 t means indent it as a normal line, aligning it to previous non-blank
942 a number means align to that column, e.g. 0 means fist column."
944 (const :tag
"Leave as is." nil
)
945 (const :tag
"Indent as a normal line." t
)
946 (integer :menu-tag
"Indent to this col (0 means first col)."
947 :tag
"Indent to column number.") )
948 :group
'sh-indentation
)
952 "Enable lots of debug messages - if function `sh-debug' is enabled.")
955 ;; Uncomment this defun and comment the defmacro for debugging.
956 ;; (defun sh-debug (&rest args)
957 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
959 ;; (apply 'message args)))
960 (defmacro sh-debug
(&rest args
))
962 (defconst sh-symbol-list
963 '((const :tag
"+ " :value
+
964 :menu-tag
"+ Indent right by sh-basic-offset")
965 (const :tag
"- " :value -
966 :menu-tag
"- Indent left by sh-basic-offset")
967 (const :tag
"++" :value
++
968 :menu-tag
"++ Indent right twice sh-basic-offset")
969 (const :tag
"--" :value --
970 :menu-tag
"-- Indent left twice sh-basic-offset")
971 (const :tag
"* " :value
*
972 :menu-tag
"* Indent right half sh-basic-offset")
973 (const :tag
"/ " :value
/
974 :menu-tag
"/ Indent left half sh-basic-offset")))
976 (defcustom sh-indent-for-else
0
977 "*How much to indent an else relative to an if. Usually 0."
979 (integer :menu-tag
"A number (positive=>indent right)"
981 (const :tag
"--") ;; separator!
984 :group
'sh-indentation
)
986 (defconst sh-number-or-symbol-list
987 (append '((integer :menu-tag
"A number (positive=>indent right)"
989 (const :tag
"--")) ; separator
992 (defcustom sh-indent-for-fi
0
993 "*How much to indent a fi relative to an if. Usually 0."
994 :type
`(choice ,@ sh-number-or-symbol-list
)
995 :group
'sh-indentation
)
997 (defcustom sh-indent-for-done
'0
998 "*How much to indent a done relative to its matching stmt. Usually 0."
999 :type
`(choice ,@ sh-number-or-symbol-list
)
1000 :group
'sh-indentation
)
1002 (defcustom sh-indent-after-else
'+
1003 "*How much to indent a statement after an else statement."
1004 :type
`(choice ,@ sh-number-or-symbol-list
)
1005 :group
'sh-indentation
)
1007 (defcustom sh-indent-after-if
'+
1008 "*How much to indent a statement after an if statement.
1009 This includes lines after else and elif statements, too, but
1010 does not affect then else elif or fi statements themselves."
1011 :type
`(choice ,@ sh-number-or-symbol-list
)
1012 :group
'sh-indentation
)
1014 (defcustom sh-indent-for-then
'+
1015 "*How much to indent an then relative to an if."
1016 :type
`(choice ,@ sh-number-or-symbol-list
)
1017 :group
'sh-indentation
)
1019 (defcustom sh-indent-for-do
'*
1020 "*How much to indent a do statement.
1021 This is relative to the statement before the do, i.e. the
1022 while until or for statement."
1023 :type
`(choice ,@ sh-number-or-symbol-list
)
1024 :group
'sh-indentation
)
1026 (defcustom sh-indent-after-do
'*
1027 "*How much to indent a line after a do statement.
1028 This is used when the do is the first word of the line.
1029 This is relative to the statement before the do, e.g. a
1030 while for repeat or select statement."
1031 :type
`(choice ,@ sh-number-or-symbol-list
)
1032 :group
'sh-indentation
)
1034 (defcustom sh-indent-after-loop-construct
'+
1035 "*How much to indent a statement after a loop construct.
1037 This variable is used when the keyword \"do\" is on the same line as the
1038 loop statement (e.g. \"until\", \"while\" or \"for\").
1039 If the do is on a line by itself, then `sh-indent-after-do' is used instead."
1040 :type
`(choice ,@ sh-number-or-symbol-list
)
1041 :group
'sh-indentation
)
1044 (defcustom sh-indent-after-done
0
1045 "*How much to indent a statement after a \"done\" keyword.
1046 Normally this is 0, which aligns the \"done\" to the matching
1047 looping construct line.
1048 Setting it non-zero allows you to have the \"do\" statement on a line
1049 by itself and align the done under to do."
1050 :type
`(choice ,@ sh-number-or-symbol-list
)
1051 :group
'sh-indentation
)
1053 (defcustom sh-indent-for-case-label
'+
1054 "*How much to indent a case label statement.
1055 This is relative to the line containing the case statement."
1056 :type
`(choice ,@ sh-number-or-symbol-list
)
1057 :group
'sh-indentation
)
1059 (defcustom sh-indent-for-case-alt
'++
1060 "*How much to indent statements after the case label.
1061 This is relative to the line containing the case statement."
1062 :type
`(choice ,@ sh-number-or-symbol-list
)
1063 :group
'sh-indentation
)
1066 (defcustom sh-indent-for-continuation
'+
1067 "*How much to indent for a continuation statement."
1068 :type
`(choice ,@ sh-number-or-symbol-list
)
1069 :group
'sh-indentation
)
1071 (defcustom sh-indent-after-open
'+
1072 "*How much to indent after a line with an opening parenthesis or brace.
1073 For an open paren after a function `sh-indent-after-function' is used."
1074 :type
`(choice ,@ sh-number-or-symbol-list
)
1075 :group
'sh-indentation
)
1077 (defcustom sh-indent-after-function
'+
1078 "*How much to indent after a function line."
1079 :type
`(choice ,@ sh-number-or-symbol-list
)
1080 :group
'sh-indentation
)
1082 ;; These 2 are for the rc shell:
1084 (defcustom sh-indent-after-switch
'+
1085 "*How much to indent a case statement relative to the switch statement.
1086 This is for the rc shell."
1087 :type
`(choice ,@ sh-number-or-symbol-list
)
1088 :group
'sh-indentation
)
1090 (defcustom sh-indent-after-case
'+
1091 "*How much to indent a statement relative to the case statement.
1092 This is for the rc shell."
1093 :type
`(choice ,@ sh-number-or-symbol-list
)
1094 :group
'sh-indentation
)
1097 ;; Internal use - not designed to be changed by the user:
1099 (defun sh-mkword-regexpr (word)
1100 "Make a regexp which matches WORD as a word.
1101 This specifically excludes an occurrence of WORD followed by
1102 punctuation characters like '-'."
1103 (concat word
"\\([^-a-z0-9_]\\|$\\)"))
1105 (defconst sh-re-done
(sh-mkword-regexpr "done"))
1108 (defconst sh-kws-for-done
1109 '((sh .
( "while" "until" "for" ) )
1110 (bash .
( "while" "until" "for" "select" ) )
1111 (ksh88 .
( "while" "until" "for" "select" ) )
1112 (zsh .
( "while" "until" "for" "repeat" "select" ) ) )
1113 "Which keywords can match the word `done' in this shell.")
1116 (defconst sh-indent-supported
1120 "Shell types that shell indenting can do something with.")
1122 (defvar sh-indent-supported-here nil
1123 "Non-nil if we support indentation for the current buffer's shell type.")
1125 (defconst sh-electric-rparen-needed
1127 "Non-nil if the shell type needs an electric handling of case alternatives.")
1129 (defconst sh-var-list
1131 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1132 sh-indent-after-do sh-indent-after-done
1133 sh-indent-after-else
1135 sh-indent-after-loop-construct
1136 sh-indent-after-open
1138 sh-indent-for-case-alt
1139 sh-indent-for-case-label
1140 sh-indent-for-continuation
1147 "A list of variables used by script mode to control indentation.
1148 This list is used when switching between buffer-local and global
1149 values of variables, and for the commands using indentation styles.")
1151 (defvar sh-make-vars-local t
1152 "*Controls whether indentation variables are local to the buffer.
1153 If non-nil, indentation variables are made local initially.
1154 If nil, you can later make the variables local by invoking
1155 command `sh-make-vars-local'.
1156 The default is t because I assume that in one Emacs session one is
1157 frequently editing existing scripts with different styles.")
1160 ;; mode-command and utility functions
1163 (put 'sh-mode
'mode-class
'special
)
1167 "Major mode for editing shell scripts.
1168 This mode works for many shells, since they all have roughly the same syntax,
1169 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1170 Unless the file's magic number indicates the shell, your usual shell is
1171 assumed. Since filenames rarely give a clue, they are not further analyzed.
1173 This mode adapts to the variations between shells (see `sh-set-shell') by
1174 means of an inheritance based feature lookup (see `sh-feature'). This
1175 mechanism applies to all variables (including skeletons) that pertain to
1176 shell-specific features.
1178 The default style of this mode is that of Rosenblatt's Korn shell book.
1179 The syntax of the statements varies with the shell being used. The
1180 following commands are available, based on the current shell's syntax:
1182 \\[sh-case] case statement
1184 \\[sh-function] function definition
1185 \\[sh-if] if statement
1186 \\[sh-indexed-loop] indexed loop from 1 to n
1187 \\[sh-while-getopts] while getopts loop
1188 \\[sh-repeat] repeat loop
1189 \\[sh-select] select loop
1190 \\[sh-until] until loop
1191 \\[sh-while] while loop
1193 For sh and rc shells indentation commands are:
1194 \\[sh-show-indent] Show the variable controlling this line's indentation.
1195 \\[sh-set-indent] Set then variable controlling this line's indentation.
1196 \\[sh-learn-line-indent] Change the indentation variable so this line
1197 would indent to the way it currently is.
1198 \\[sh-learn-buffer-indent] Set the indentation variables so the
1199 buffer indents as it currently is indented.
1202 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1203 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
1204 \\[sh-end-of-command] Go to end of successive commands.
1205 \\[sh-beginning-of-command] Go to beginning of successive commands.
1206 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1207 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1209 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
1211 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1213 If you generally program a shell different from your login shell you can
1214 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1215 indicate what shell it is use `sh-alias-alist' to translate.
1217 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1218 with your script for an edit-interpret-debug cycle."
1220 (kill-all-local-variables)
1221 (use-local-map sh-mode-map
)
1222 (make-local-variable 'skeleton-end-hook
)
1223 (make-local-variable 'paragraph-start
)
1224 (make-local-variable 'paragraph-separate
)
1225 (make-local-variable 'comment-start
)
1226 (make-local-variable 'comment-start-skip
)
1227 (make-local-variable 'require-final-newline
)
1228 (make-local-variable 'sh-header-marker
)
1229 (make-local-variable 'sh-shell-file
)
1230 (make-local-variable 'sh-shell
)
1231 (make-local-variable 'skeleton-pair-alist
)
1232 (make-local-variable 'skeleton-pair-filter
)
1233 (make-local-variable 'comint-dynamic-complete-functions
)
1234 (make-local-variable 'comint-prompt-regexp
)
1235 (make-local-variable 'font-lock-defaults
)
1236 (make-local-variable 'skeleton-filter
)
1237 (make-local-variable 'skeleton-newline-indent-rigidly
)
1238 (make-local-variable 'sh-shell-variables
)
1239 (make-local-variable 'sh-shell-variables-initialized
)
1240 (make-local-variable 'imenu-generic-expression
)
1241 (make-local-variable 'sh-indent-supported-here
)
1242 (make-local-variable 'font-lock-unfontify-region-function
)
1243 (setq major-mode
'sh-mode
1244 mode-name
"Shell-script"
1245 ;; not very clever, but enables wrapping skeletons around regions
1246 indent-region-function
(lambda (b e
)
1249 (skip-syntax-backward "-")
1252 (skip-syntax-backward "-")
1253 (indent-rigidly b
(point) sh-indentation
)))
1254 skeleton-end-hook
(lambda ()
1255 (or (eolp) (newline) (indent-relative)))
1256 paragraph-start
(concat page-delimiter
"\\|$")
1257 paragraph-separate paragraph-start
1259 comint-dynamic-complete-functions sh-dynamic-complete-functions
1260 ;; we can't look if previous line ended with `\'
1261 comint-prompt-regexp
"^[ \t]*"
1263 `((sh-font-lock-keywords
1264 sh-font-lock-keywords-1 sh-font-lock-keywords-2
)
1266 ((?
/ .
"w") (?~ .
"w") (?. .
"w") (?- .
"w") (?_ .
"w")) nil
1267 (font-lock-syntactic-keywords
1268 ;; Copy so we can use destructive update in `sh-font-lock-heredoc'.
1269 .
,(copy-sequence sh-font-lock-syntactic-keywords
)))
1270 skeleton-pair-alist
'((?
` _ ?
`))
1271 skeleton-pair-filter
'sh-quoted-p
1272 skeleton-further-elements
'((< '(- (min sh-indentation
1273 (current-column)))))
1274 skeleton-filter
'sh-feature
1275 skeleton-newline-indent-rigidly t
1276 sh-indent-supported-here nil
)
1277 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
1278 ;; Parse or insert magic number for exec, and set all variables depending
1279 ;; on the shell thus determined.
1282 (goto-char (point-min))
1283 (cond ((looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1285 ((and buffer-file-name
1286 (string-match "\\.m?spec$" buffer-file-name
))
1289 (sh-set-shell interpreter nil nil
)
1290 (sh-set-shell sh-shell-file nil nil
))
1291 (run-hooks 'sh-mode-hook
)))
1293 (defalias 'shell-script-mode
'sh-mode
)
1296 (defun sh-font-lock-keywords (&optional keywords
)
1297 "Function to get simple fontification based on `sh-font-lock-keywords'.
1298 This adds rules for comments and assignments."
1299 (sh-feature sh-font-lock-keywords
1300 (when (stringp (sh-feature sh-assignment-regexp
))
1302 `((,(sh-feature sh-assignment-regexp
)
1303 1 font-lock-variable-name-face
)
1307 (defun sh-font-lock-keywords-1 (&optional builtins
)
1308 "Function to get better fontification including keywords."
1309 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
1310 (mapconcat 'identity
1311 (sh-feature sh-leading-keywords
)
1314 (mapconcat 'identity
1315 (append (sh-feature sh-leading-keywords
)
1316 (sh-feature sh-other-keywords
))
1319 (sh-font-lock-keywords
1321 `((,(concat keywords
"[ \t]+\\)?\\("
1322 (mapconcat 'identity
(sh-feature sh-builtins
) "\\|")
1324 (2 font-lock-keyword-face nil t
)
1325 (6 font-lock-builtin-face
))
1326 ,@(sh-feature sh-font-lock-keywords-2
)))
1327 (,(concat keywords
"\\)\\>")
1328 2 font-lock-keyword-face
)
1329 ,@(sh-feature sh-font-lock-keywords-1
)))))
1331 (defun sh-font-lock-keywords-2 ()
1332 "Function to get better fontification including keywords and builtins."
1333 (sh-font-lock-keywords-1 t
))
1336 (defvar sh-regexp-for-done nil
1337 "A buffer-local regexp to match opening keyword for done.")
1339 (defvar sh-kw-alist nil
1340 "A buffer-local, since it is shell-type dependent, list of keywords.")
1342 ;; ( key-word first-on-this on-prev-line )
1343 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1344 ;; having 3 elements:
1346 ;; a rule to check when the keyword appears on "this" line
1347 ;; a rule to check when the keyword appears on "the previous" line
1348 ;; The keyword is usually a string and is the first word on a line.
1349 ;; If this keyword appears on the line whose indentation is to be
1350 ;; calculated, the rule in element 2 is called. If this returns
1351 ;; non-zero, the resulting point (which may be changed by the rule)
1352 ;; is used as the default indentation.
1353 ;; If it returned false or the keyword was not found in the table,
1354 ;; then the keyword from the previous line is looked up and the rule
1355 ;; in element 3 is called. In this case, however,
1356 ;; `sh-get-indent-info' does not stop but may keep going and test
1357 ;; other keywords against rules in element 3. This is because the
1358 ;; preceding line could have, for example, an opening "if" and an
1359 ;; opening "while" keyword and we need to add the indentation offsets
1364 ("if" nil sh-handle-prev-if
)
1365 ("elif" sh-handle-this-else sh-handle-prev-else
)
1366 ("else" sh-handle-this-else sh-handle-prev-else
)
1367 ("fi" sh-handle-this-fi sh-handle-prev-fi
)
1368 ("then" sh-handle-this-then sh-handle-prev-then
)
1369 ("(" nil sh-handle-prev-open
)
1370 ("{" nil sh-handle-prev-open
)
1371 ("[" nil sh-handle-prev-open
)
1372 ("}" sh-handle-this-close nil
)
1373 (")" sh-handle-this-close nil
)
1374 ("]" sh-handle-this-close nil
)
1375 ("case" nil sh-handle-prev-case
)
1376 ("esac" sh-handle-this-esac sh-handle-prev-esac
)
1377 (case-label nil sh-handle-after-case-label
) ;; ???
1378 (";;" nil sh-handle-prev-case-alt-end
) ;; ???
1379 ("done" sh-handle-this-done sh-handle-prev-done
)
1380 ("do" sh-handle-this-do sh-handle-prev-do
))
1382 ;; Note: we don't need specific stuff for bash and zsh shells;
1383 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1384 ;; these shells use.
1386 ("{" nil sh-handle-prev-open
)
1387 ("}" sh-handle-this-close nil
)
1388 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case
))))
1391 (defun sh-set-shell (shell &optional no-query-flag insert-flag
)
1392 "Set this buffer's shell to SHELL (a string).
1393 Makes this script executable via `executable-set-magic', and sets up the
1394 proper starting #!-line, if INSERT-FLAG is non-nil.
1395 Calls the value of `sh-set-shell-hook' if set."
1396 (interactive (list (completing-read "Name or path of shell: "
1397 interpreter-mode-alist
1398 (lambda (x) (eq (cdr x
) 'sh-mode
)))
1399 (eq executable-query
'function
)
1401 (if (string-match "\\.exe\\'" shell
)
1402 (setq shell
(substring shell
0 (match-beginning 0))))
1403 (setq sh-shell
(intern (file-name-nondirectory shell
))
1404 sh-shell
(or (cdr (assq sh-shell sh-alias-alist
))
1408 (executable-set-magic shell
(sh-feature sh-shell-arg
)
1409 no-query-flag insert-flag
)))
1410 (setq require-final-newline
(sh-feature sh-require-final-newline
)
1411 ;;; local-abbrev-table (sh-feature sh-abbrevs)
1412 comment-start-skip
"#+[\t ]*"
1413 mode-line-process
(format "[%s]" sh-shell
)
1414 sh-shell-variables nil
1415 sh-shell-variables-initialized nil
1416 imenu-generic-expression
(sh-feature sh-imenu-generic-expression
)
1417 imenu-case-fold-search nil
)
1418 (set-syntax-table (or (sh-feature sh-mode-syntax-table
)
1419 (standard-syntax-table)))
1420 (dolist (var (sh-feature sh-variables
))
1421 (sh-remember-variable var
))
1422 (make-local-variable 'indent-line-function
)
1423 (if (setq sh-indent-supported-here
(sh-feature sh-indent-supported
))
1425 (message "Setting up indent for shell type %s" sh-shell
)
1426 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
1427 (set (make-local-variable 'sh-kw-alist
) (sh-feature sh-kw
))
1428 (let ((regexp (sh-feature sh-kws-for-done
)))
1430 (set (make-local-variable 'sh-regexp-for-done
)
1431 (sh-mkword-regexpr (regexp-opt regexp t
)))))
1432 (message "setting up indent stuff")
1433 ;; sh-mode has already made indent-line-function local
1434 ;; but do it in case this is called before that.
1435 (setq indent-line-function
'sh-indent-line
)
1436 (if sh-make-vars-local
1437 (sh-make-vars-local))
1438 (message "Indentation setup for shell type %s" sh-shell
))
1439 (message "No indentation for this shell type.")
1440 (setq indent-line-function
'sh-basic-indent-line
))
1441 (run-hooks 'sh-set-shell-hook
))
1445 (defun sh-feature (list &optional function
)
1446 "Index ALIST by the current shell.
1447 If ALIST isn't a list where every element is a cons, it is returned as is.
1448 Else indexing follows an inheritance logic which works in two ways:
1450 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1451 the alist contains no value for the current shell.
1452 The ultimate default is always `sh'.
1454 - If the value thus looked up is a list starting with `eval' its `cdr' is
1455 first evaluated. If that is also a list and the first argument is a
1456 symbol in ALIST it is not evaluated, but rather recursively looked up in
1457 ALIST to allow the function called to define the value for one shell to be
1458 derived from another shell. While calling the function, is the car of the
1459 alist element is the current shell.
1460 The value thus determined is physically replaced into the alist.
1462 Optional FUNCTION is applied to the determined value and the result is cached
1464 (or (if (consp list
)
1466 (while (and l
(consp (car l
)))
1470 (cdr (assoc (setq function
(cons sh-shell function
)) list
)))
1471 (let ((sh-shell sh-shell
)
1473 (while (and sh-shell
1474 (not (setq elt
(assq sh-shell list
))))
1475 (setq sh-shell
(cdr (assq sh-shell sh-ancestor-alist
))))
1476 ;; If the shell is not known, treat it as sh.
1478 (setq elt
(assq 'sh list
)))
1479 (if (and (consp (setq val
(cdr elt
)))
1480 (eq (car val
) 'eval
))
1483 (eval (if (consp (setq val
(cdr val
)))
1484 (let ((sh-shell (car (cdr val
)))
1486 (if (assq sh-shell list
)
1489 (sh-feature list
))))
1494 (list (cons function
1495 (setq sh-shell
(car function
)
1496 val
(funcall (cdr function
) val
))))))
1501 ;;; I commented this out because nobody calls it -- rms.
1502 ;;;(defun sh-abbrevs (ancestor &rest list)
1503 ;;; "Iff it isn't, define the current shell as abbrev table and fill that.
1504 ;;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1505 ;;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1506 ;;;according to the remaining arguments NAMEi EXPANSIONi ...
1507 ;;;EXPANSION may be either a string or a skeleton command."
1508 ;;; (or (if (boundp sh-shell)
1509 ;;; (symbol-value sh-shell))
1511 ;;; (if (listp ancestor)
1512 ;;; (nconc list ancestor))
1513 ;;; (define-abbrev-table sh-shell ())
1514 ;;; (if (vectorp ancestor)
1515 ;;; (mapatoms (lambda (atom)
1517 ;;; (define-abbrev (symbol-value sh-shell)
1518 ;;; (symbol-name atom)
1519 ;;; (symbol-value atom)
1520 ;;; (symbol-function atom))))
1523 ;;; (define-abbrev (symbol-value sh-shell)
1525 ;;; (if (stringp (car (cdr list)))
1526 ;;; (car (cdr list))
1528 ;;; (if (symbolp (car (cdr list)))
1529 ;;; (car (cdr list))))
1530 ;;; (setq list (cdr (cdr list)))))
1531 ;;; (symbol-value sh-shell)))
1534 (defun sh-mode-syntax-table (table &rest list
)
1535 "Copy TABLE and set syntax for successive CHARs according to strings S."
1536 (setq table
(copy-syntax-table table
))
1538 (modify-syntax-entry (pop list
) (pop list
) table
))
1542 (defun sh-append (ancestor &rest list
)
1543 "Return list composed of first argument (a list) physically appended to rest."
1544 (nconc list ancestor
))
1547 (defun sh-modify (skeleton &rest list
)
1548 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1549 (setq skeleton
(copy-sequence skeleton
))
1551 (setcar (or (nthcdr (car list
) skeleton
)
1552 (error "Index %d out of bounds" (car list
)))
1554 (setq list
(nthcdr 2 list
)))
1558 (defun sh-basic-indent-line ()
1559 "Indent a line for Sh mode (shell script mode).
1560 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1561 Lines containing only comments are considered empty."
1563 (let ((previous (save-excursion
1564 (while (and (progn (beginning-of-line)
1568 (back-to-indentation)
1570 (eq (following-char) ?
#)))))
1574 (indent-to (if (eq this-command
'newline-and-indent
)
1576 (if (< (current-column)
1577 (setq current
(progn (back-to-indentation)
1579 (if (eolp) previous
0)
1580 (delete-region (point)
1581 (progn (beginning-of-line) (point)))
1583 (max previous
(* (1+ (/ current sh-indentation
))
1585 (* (1+ (/ current sh-indentation
)) sh-indentation
))))))
1586 (if (< (current-column) (current-indentation))
1587 (skip-chars-forward " \t"))))
1590 (defun sh-execute-region (start end
&optional flag
)
1591 "Pass optional header and region to a subshell for noninteractive execution.
1592 The working directory is that of the buffer, and only environment variables
1593 are already set which is why you can mark a header within the script.
1595 With a positive prefix ARG, instead of sending region, define header from
1596 beginning of buffer to point. With a negative prefix ARG, instead of sending
1597 region, clear header."
1598 (interactive "r\nP")
1600 (setq sh-header-marker
(if (> (prefix-numeric-value flag
) 0)
1602 (if sh-header-marker
1604 (let (buffer-undo-list)
1605 (goto-char sh-header-marker
)
1606 (append-to-buffer (current-buffer) start end
)
1607 (shell-command-on-region (point-min)
1608 (setq end
(+ sh-header-marker
1611 (delete-region sh-header-marker end
)))
1612 (shell-command-on-region start end
(concat sh-shell-file
" -")))))
1615 (defun sh-remember-variable (var)
1616 "Make VARIABLE available for future completing reads in this buffer."
1617 (or (< (length var
) sh-remember-variable-min
)
1619 (assoc var sh-shell-variables
)
1620 (push (cons var var
) sh-shell-variables
))
1625 (defun sh-quoted-p ()
1626 "Is point preceded by an odd number of backslashes?"
1627 (eq -
1 (%
(save-excursion (skip-chars-backward "\\\\")) 2)))
1629 ;; Indentation stuff.
1630 (defun sh-must-be-shell-mode ()
1631 "Signal an error if not in Shell-script mode."
1632 (unless (eq major-mode
'sh-mode
)
1633 (error "This buffer is not in Shell-script mode")))
1635 (defun sh-must-support-indent ()
1636 "*Signal an error if the shell type for this buffer is not supported.
1637 Also, the buffer must be in Shell-script mode."
1638 (sh-must-be-shell-mode)
1639 (unless sh-indent-supported-here
1640 (error "This buffer's shell type is not supported for this command")))
1642 (defun sh-make-vars-local ()
1643 "Make the indentation variables local to this buffer.
1644 Normally they already are local. This command is provided in case
1645 variable `sh-make-vars-local' has been set to nil.
1647 To revert all these variables to the global values, use
1648 command `sh-reset-indent-vars-to-global-values'."
1650 (sh-must-be-shell-mode)
1651 (mapcar 'make-local-variable sh-var-list
)
1652 (message "Indentation variable are now local."))
1654 (defun sh-reset-indent-vars-to-global-values ()
1655 "Reset local indentation variables to the global values.
1656 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1658 (sh-must-be-shell-mode)
1659 (mapcar 'kill-local-variable sh-var-list
)
1660 (if sh-make-vars-local
1661 (mapcar 'make-local-variable sh-var-list
)))
1664 ;; Theoretically these are only needed in shell and derived modes.
1665 ;; However, the routines which use them are only called in those modes.
1666 (defconst sh-special-keywords
"then\\|do")
1668 (defun sh-help-string-for-variable (var)
1669 "Construct a string for `sh-read-variable' when changing variable VAR ."
1670 (let ((msg (documentation-property var
'variable-documentation
))
1672 (unless (memq var
'(sh-first-lines-indent sh-indent-comment
))
1675 You can enter a number (positive to increase indentation,
1676 negative to decrease indentation, zero for no change to indentation).
1678 Or, you can enter one of the following symbols which are relative to
1679 the value of variable `sh-basic-offset'
1680 which in this buffer is currently %s.
1684 (mapconcat (lambda (x)
1685 (nth (1- (length x
)) x
))
1686 sh-symbol-list
"\n\t"))))
1688 ;; The following shows the global not the local value!
1689 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1692 (defun sh-read-variable (var)
1693 "Read a new value for indentation variable VAR."
1694 (interactive "*variable? ") ;; to test
1695 (let ((minibuffer-help-form `(sh-help-string-for-variable
1698 (setq val
(read-from-minibuffer
1699 (format "New value for %s (press %s for help): "
1700 var
(single-key-description help-char
))
1701 (format "%s" (symbol-value var
))
1707 (defun sh-in-comment-or-string (start)
1708 "Return non-nil if START is in a comment or string."
1712 (setq state
(parse-partial-sexp (point) start nil nil nil t
))
1713 (or (nth 3 state
)(nth 4 state
)))))
1715 (defun sh-goto-matching-if ()
1716 "Go to the matching if for a fi.
1717 This handles nested if..fi pairs."
1718 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1720 (goto-char found
))))
1723 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1724 ;; line whose indentation is being handled contain XXX;
1725 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
1727 (defun sh-handle-prev-if ()
1728 (list '(+ sh-indent-after-if
)))
1730 (defun sh-handle-this-else ()
1731 (if (sh-goto-matching-if)
1732 ;; (list "aligned to if")
1733 (list "aligned to if" '(+ sh-indent-for-else
))
1737 (defun sh-handle-prev-else ()
1738 (if (sh-goto-matching-if)
1739 (list '(+ sh-indent-after-if
))
1742 (defun sh-handle-this-fi ()
1743 (if (sh-goto-matching-if)
1744 (list "aligned to if" '(+ sh-indent-for-fi
))
1748 (defun sh-handle-prev-fi ()
1749 ;; Why do we have this rule? Because we must go back to the if
1750 ;; to get its indent. We may continue back from there.
1751 ;; We return nil because we don't have anything to add to result,
1752 ;; the side affect of setting align-point is all that matters.
1753 ;; we could return a comment (a string) but I can't think of a good one...
1754 (sh-goto-matching-if)
1757 (defun sh-handle-this-then ()
1758 (let ((p (sh-goto-matching-if)))
1760 (list '(+ sh-indent-for-then
))
1763 (defun sh-handle-prev-then ()
1764 (let ((p (sh-goto-matching-if)))
1766 (list '(+ sh-indent-after-if
))
1769 (defun sh-handle-prev-open ()
1771 (let ((x (sh-prev-stmt)))
1776 (looking-at "function\\b")
1777 (looking-at "\\s-*\\S-+\\s-*()")
1779 (list '(+ sh-indent-after-function
))
1780 (list '(+ sh-indent-after-open
)))
1783 (defun sh-handle-this-close ()
1784 (forward-char 1) ;; move over ")"
1785 (if (sh-safe-forward-sexp -
1)
1786 (list "aligned to opening paren")))
1788 (defun sh-goto-matching-case ()
1789 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
1790 (if found
(goto-char found
))))
1792 (defun sh-handle-prev-case ()
1793 ;; This is typically called when point is on same line as a case
1794 ;; we shouldn't -- and can't find prev-case
1795 (if (looking-at ".*\\<case\\>")
1796 (list '(+ sh-indent-for-case-label
))
1797 (error "We don't seem to be on a line with a case"))) ;; debug
1799 (defun sh-handle-this-esac ()
1800 (if (sh-goto-matching-case)
1801 (list "aligned to matching case")))
1803 (defun sh-handle-prev-esac ()
1804 (if (sh-goto-matching-case)
1805 (list "matching case")))
1807 (defun sh-handle-after-case-label ()
1808 (if (sh-goto-matching-case)
1809 (list '(+ sh-indent-for-case-alt
))))
1811 (defun sh-handle-prev-case-alt-end ()
1812 (if (sh-goto-matching-case)
1813 (list '(+ sh-indent-for-case-label
))))
1815 (defun sh-safe-forward-sexp (&optional arg
)
1816 "Try and do a `forward-sexp', but do not error.
1817 Return new point if successful, nil if an error occurred."
1820 (forward-sexp (or arg
1))
1821 (point)) ;; return point if successful
1823 (sh-debug "oops!(1) %d" (point))
1824 nil
))) ;; return nil if fail
1826 (defun sh-goto-match-for-done ()
1827 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done
1)))
1829 (goto-char found
))))
1831 (defun sh-handle-this-done ()
1832 (if (sh-goto-match-for-done)
1833 (list "aligned to do stmt" '(+ sh-indent-for-done
))))
1835 (defun sh-handle-prev-done ()
1836 (if (sh-goto-match-for-done)
1837 (list "previous done")))
1839 (defun sh-handle-this-do ()
1840 (if (sh-goto-match-for-done)
1841 (list '(+ sh-indent-for-do
))))
1843 (defun sh-handle-prev-do ()
1851 (sh-goto-match-for-done))
1852 (sh-debug "match for done found on THIS line")
1853 (list '(+ sh-indent-after-loop-construct
)))
1854 ((sh-goto-match-for-done)
1855 (sh-debug "match for done found on PREV line")
1856 (list '(+ sh-indent-after-do
)))
1858 (message "match for done NOT found")
1862 (defun sh-find-prev-switch ()
1863 "Find the line for the switch keyword matching this line's case keyword."
1864 (re-search-backward "\\<switch\\>" nil t
))
1866 (defun sh-handle-this-rc-case ()
1867 (if (sh-find-prev-switch)
1868 (list '(+ sh-indent-after-switch
))
1869 ;; (list '(+ sh-indent-for-case-label))
1872 (defun sh-handle-prev-rc-case ()
1873 (list '(+ sh-indent-after-case
)))
1875 (defun sh-check-rule (n thing
)
1876 (let ((rule (nth n
(assoc thing sh-kw-alist
)))
1880 (setq val
(funcall rule
))
1881 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
1882 n thing
(point) rule val
)))
1886 (defun sh-get-indent-info ()
1887 "Return indent-info for this line.
1888 This is a list. nil means the line is to be left as is.
1889 Otherwise it contains one or more of the following sublists:
1890 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
1891 relative to. If present, this is always the first of the
1892 sublists. The indentation of the line in question is
1893 derived from the indentation of this point, possibly
1894 modified by subsequent sublists.
1896 \(- VAR\) Get the value of variable VAR and add to or subtract from
1897 the indentation calculated so far.
1898 \(= VAR\) Get the value of variable VAR and *replace* the
1899 indentation with its value. This only occurs for
1900 special variables such as `sh-indent-comment'.
1901 STRING This is ignored for the purposes of calculating
1902 indentation, it is printed in certain cases to help show
1903 what the indentation is based on."
1904 ;; See comments before `sh-kw'.
1913 (depth-prev-bol nil
)
1923 ;; Note: setting result to t means we are done and will return nil.
1924 ;;(This function never returns just t.)
1926 ((and (boundp 'font-lock-string-face
)
1927 (equal (get-text-property (point) 'face
) font-lock-string-face
))
1929 (setq have-result t
))
1930 ((looking-at "\\s-*#") ; was (equal this-kw "#")
1932 (setq result t
) ;; return nil if 1st line!
1933 (setq result
(list '(= sh-indent-comment
)))
1934 ;; we still need to get previous line in case
1935 ;; sh-indent-comment is t (indent as normal)
1936 (setq align-point
(sh-prev-line nil
))
1937 (setq have-result nil
)
1942 ;; Continuation lines are handled specially
1943 (if (sh-this-is-a-continuation)
1945 ;; We assume the line being continued is already
1946 ;; properly indented...
1947 ;; (setq prev-line-end (sh-prev-line))
1948 (setq align-point
(sh-prev-line nil
))
1949 (setq result
(list '(+ sh-indent-for-continuation
)))
1950 (setq have-result t
))
1952 (skip-chars-forward " \t")
1953 (setq this-kw
(sh-get-kw)))
1955 ;; Handle "this" keyword: first word on the line we're
1956 ;; calculating indentation info for.
1958 (if (setq val
(sh-check-rule 1 this-kw
))
1960 (setq align-point
(point))
1962 "this - setting align-point to %d" align-point
)
1963 (setq result
(append result val
))
1964 (setq have-result t
)
1965 ;; set prev-line to continue processing remainder
1966 ;; of this line as a previous line
1967 (setq prev-line-end
(point))
1971 (setq prev-line-end
(sh-prev-line 'end
)))
1975 ;; We start off at beginning of this line.
1976 ;; Scan previous statements while this is <=
1977 ;; start of previous line.
1978 (setq start
(point)) ;; for debug only
1979 (goto-char prev-line-end
)
1981 (while (and x
(setq x
(sh-prev-thing)))
1982 (sh-debug "at %d x is: %s result is: %s" (point) x result
)
1985 (equal (get-text-property (1- (point)) 'syntax-table
)
1987 (sh-debug "Case label) here")
1988 (setq x
'case-label
)
1989 (if (setq val
(sh-check-rule 2 x
))
1991 (setq result
(append result val
))
1992 (setq align-point
(point))))
1994 (skip-chars-forward "[a-z0-9]*?")
1996 ((string-match "[])}]" x
)
1997 (setq x
(sh-safe-forward-sexp -
1))
2000 (setq align-point
(point))
2001 (setq result
(append result
2002 (list "aligned to opening paren")))
2004 ((string-match "[[({]" x
)
2005 (sh-debug "Checking special thing: %s" x
)
2006 (if (setq val
(sh-check-rule 2 x
))
2007 (setq result
(append result val
)))
2009 (setq align-point
(point)))
2010 ((string-match "[\"'`]" x
)
2011 (sh-debug "Skipping back for %s" x
)
2013 (setq x
(sh-safe-forward-sexp -
1)))
2015 (sh-debug "Checking string %s at %s" x
(point))
2016 (if (setq val
(sh-check-rule 2 x
))
2017 ;; (or (eq t (car val))
2018 ;; (eq t (car (car val))))
2019 (setq result
(append result val
)))
2020 ;; not sure about this test Wed Jan 27 23:48:35 1999
2021 (setq align-point
(point))
2025 (error "Don't know what to do with %s" x
))
2028 (sh-debug "result is %s" result
)
2030 (sh-debug "No prev line!")
2031 (sh-debug "result: %s align-point: %s" result align-point
)
2035 ;; was: (setq result (append result (list (list t align-point))))
2036 (setq result
(append (list (list t align-point
)) result
))
2038 (sh-debug "result is now: %s" result
)
2042 (setq result
(list (list t prev-line-end
)))
2043 (setq result
(list (list '= 'sh-first-lines-indent
)))
2048 (sh-debug "result is: %s" result
)
2054 (defun sh-get-indent-var-for-line (&optional info
)
2055 "Return the variable controlling indentation for this line.
2056 If there is not [just] one such variable, return a string
2057 indicating the problem.
2058 If INFO is supplied it is used, else it is calculated."
2064 (setq info
(sh-get-indent-info)))
2066 (setq result
"this line to be left as is")
2067 (while (and info
(null result
))
2068 (setq elt
(car info
))
2074 (error "sh-get-indent-var-for-line invalid elt: %s" elt
))
2078 ((symbolp (setq sym
(nth 1 elt
)))
2079 ;; A bit of a kludge - when we see the sh-indent-comment
2080 ;; ignore other variables. Otherwise it is tricky to
2081 ;; "learn" the comment indentation.
2082 (if (eq var
'sh-indent-comment
)
2086 "this line is controlled by more than 1 variable.")
2089 (error "sh-get-indent-var-for-line invalid list elt: %s" elt
)))
2090 (setq info
(cdr info
))
2095 (setq result reason
))
2097 ;; e.g. just had (t POS)
2098 (setq result
"line has default indentation"))
2103 ;; Finding the previous line isn't trivial.
2104 ;; We must *always* go back one more and see if that is a continuation
2105 ;; line -- it is the PREVIOUS line which is continued, not the one
2107 ;; Also, we want to treat a whole "here document" as one big line,
2108 ;; because we may want to a align to the beginning of it.
2111 ;; - go back to previous non-empty line
2112 ;; - if this is in a here-document, go to the beginning of it
2113 ;; - while previous line is continued, go back one line
2114 (defun sh-prev-line (&optional end
)
2115 "Back to end of previous non-comment non-empty line.
2116 Go to beginning of logical line unless END is non-nil, in which case
2117 we go to the end of the previous line and do not check for continuations."
2118 (sh-must-be-shell-mode)
2121 (forward-comment (- (point-max)))
2122 (unless end
(beginning-of-line))
2123 (when (and (not (bobp))
2124 (boundp 'font-lock-string-face
)
2125 (equal (get-text-property (1- (point)) 'face
)
2126 font-lock-string-face
))
2127 (let ((p1 (previous-single-property-change (1- (point)) 'face
)))
2132 (beginning-of-line)))))
2134 ;; we must check previous lines to see if they are continuation lines
2135 ;; if so, we must return position of first of them
2136 (while (and (sh-this-is-a-continuation)
2137 (>= 0 (forward-line -
1))))
2139 (skip-chars-forward " \t"))
2143 (defun sh-prev-stmt ()
2144 "Return the address of the previous stmt or nil."
2145 ;; This is used when we are trying to find a matching keyword.
2146 ;; Searching backward for the keyword would certainly be quicker, but
2147 ;; it is hard to remove "false matches" -- such as if the keyword
2148 ;; appears in a string or quote. This way is slower, but (I think) safer.
2155 (skip-chars-backward " \t;|&({[")
2156 (while (and (not found
)
2159 ;; Do a backward-sexp if possible, else backup bit by bit...
2160 (if (sh-safe-forward-sexp -
1)
2162 (if (looking-at sh-special-keywords
)
2167 ;; backward-sexp failed
2168 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2171 (let ((back (sh-prev-line nil
)))
2174 (setq going nil
)))))
2176 (skip-chars-backward " \t")
2177 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2178 (eq (char-before) ?\
;)
2179 (looking-at "\\s-*[|&]"))
2180 (setq found
(point)))))
2185 (skip-chars-forward " \t|&({[")
2186 (setq found
(point))))
2187 (if (>= (point) start
)
2189 (debug "We didn't move!")
2192 (sh-debug "Did not find prev stmt.")))
2196 (defun sh-get-word ()
2197 "Get a shell word skipping whitespace from point."
2199 (skip-chars-forward "\t ")
2200 (let ((start (point)))
2202 (if (looking-at "[\"'`]")
2203 (sh-safe-forward-sexp)
2204 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2205 (> (skip-chars-forward "-_a-zA-Z\$0-9") 0)
2207 (buffer-substring start
(point))
2210 (defun sh-prev-thing ()
2211 "Return the previous thing this logical line."
2212 ;; This is called when `sh-get-indent-info' is working backwards on
2213 ;; the previous line(s) finding what keywords may be relevant for
2214 ;; indenting. It moves over sexps if possible, and will stop
2215 ;; on a ; and at the beginning of a line if it is not a continuation
2218 ;; Added a kludge for ";;"
2219 ;; Possible return values:
2221 ;; a string - possibly a keyword
2232 (if (sh-this-is-a-continuation)
2233 (setq min-point
(sh-prev-line nil
))
2236 (setq min-point
(point))))
2238 (skip-chars-backward " \t;")
2239 (unless (looking-at "\\s-*;;")
2240 (skip-chars-backward "^)}];\"'`({[")
2241 (setq c
(char-before))))
2242 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2243 (point) c start min-point
)
2244 (if (< (point) min-point
)
2245 (error "point %d < min-point %d" (point) min-point
))
2247 ((looking-at "\\s-*;;")
2248 ;; (message "Found ;; !")
2254 ;; skip forward over white space newline and \ at eol
2255 (skip-chars-forward " \t\n\\\\")
2256 (sh-debug "Now at %d start=%d" (point) start
)
2257 (if (>= (point) start
)
2259 (sh-debug "point: %d >= start: %d" (point) start
)
2264 ;; c -- return a string
2270 (defun sh-this-is-a-continuation ()
2271 "Return non-nil if current line is a continuation of previous line."
2273 (and (zerop (forward-line -
1))
2274 (looking-at ".*\\\\$")
2275 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2278 (defun sh-get-kw (&optional where and-move
)
2279 "Return first word of line from WHERE.
2280 If AND-MOVE is non-nil then move to end of word."
2281 (let ((start (point)))
2285 (buffer-substring (point)
2286 (progn (skip-chars-forward "^ \t\n;")(point)))
2288 (goto-char start
)))))
2290 (defun sh-find-prev-matching (open close
&optional depth
)
2291 "Find a matching token for a set of opening and closing keywords.
2292 This takes into account that there may be nested open..close pairings.
2293 OPEN and CLOSE are regexps denoting the tokens to be matched.
2294 Optional parameter DEPTH (usually 1) says how many to look for."
2295 (let ((parse-sexp-ignore-comments t
)
2297 (setq depth
(or depth
1))
2303 (setq prev
(sh-prev-stmt)))
2306 (if (looking-at "\\\\\n")
2309 (skip-chars-forward " \t")))
2312 (setq depth
(1- depth
))
2313 (sh-debug "found open at %d - depth = %d" (point) depth
))
2315 (setq depth
(1+ depth
))
2316 (sh-debug "found close - depth = %d" depth
))
2326 (defun sh-var-value (var &optional ignore-error
)
2327 "Return the value of variable VAR, interpreting symbols.
2328 It can also return t or nil.
2329 If an illegal value is found, throw an error unless Optional argument
2330 IGNORE-ERROR is non-nil."
2331 (let ((val (symbol-value var
)))
2342 (- sh-basic-offset
))
2344 (* 2 sh-basic-offset
))
2346 (* 2 (- sh-basic-offset
)))
2348 (/ sh-basic-offset
2))
2350 (/ (- sh-basic-offset
) 2))
2354 (message "Don't know how to handle %s's value of %s" var val
)
2356 (error "Don't know how to handle %s's value of %s" var val
))
2359 (defun sh-set-var-value (var value
&optional no-symbol
)
2360 "Set variable VAR to VALUE.
2361 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2362 can be represented by a symbol then do so."
2366 ((= value sh-basic-offset
)
2368 ((= value
(- sh-basic-offset
))
2370 ((eq value
(* 2 sh-basic-offset
))
2372 ((eq value
(* 2 (- sh-basic-offset
)))
2374 ((eq value
(/ sh-basic-offset
2))
2376 ((eq value
(/ (- sh-basic-offset
) 2))
2383 (defun sh-calculate-indent (&optional info
)
2384 "Return the indentation for the current line.
2385 If INFO is supplied it is used, else it is calculated from current line."
2390 (setq info
(sh-get-indent-info)))
2393 (sh-debug "info: %s ofs=%s" info ofs
)
2394 (setq elt
(car info
))
2396 ((stringp elt
)) ;; do nothing?
2398 (setq a
(car (car info
)))
2399 (setq b
(nth 1 (car info
)))
2404 (setq val
(current-indentation)))
2405 (setq base-value val
))
2407 (setq val
(sh-var-value b
))
2413 ;; set info to nil so we stop immediately
2414 (setq base-value nil ofs nil info nil
))
2415 ((eq val t
) (setq ofs
0)) ;; indent as normal line
2417 ;; The following assume the (t POS) come first!
2418 (setq ofs val base-value
0)
2419 (setq info nil
)))) ;; ? stop now
2420 ((eq a
'+) (setq ofs
(+ ofs val
)))
2421 ((eq a
'-
) (setq ofs
(- ofs val
)))
2423 (error "sh-calculate-indent invalid a a=%s b=%s" a b
))))
2425 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b
))))
2427 (error "sh-calculate-indent invalid elt %s" elt
)))
2428 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2429 a b val base-value ofs
)
2430 (setq info
(cdr info
)))
2432 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs
)
2435 ((or (null base-value
)(null ofs
))
2437 ((and (numberp base-value
)(numberp ofs
))
2438 (sh-debug "base (%d) + ofs (%d) = %d"
2439 base-value ofs
(+ base-value ofs
))
2440 (+ base-value ofs
)) ;; return value
2442 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2447 (defun sh-indent-line ()
2448 "Indent the current line."
2450 (sh-must-be-shell-mode)
2451 (let ((indent (sh-calculate-indent)) shift-amt beg end
2452 (pos (- (point-max) (point))))
2456 (skip-chars-forward " \t")
2457 (setq shift-amt
(- indent
(current-column)))
2458 (unless (zerop shift-amt
)
2459 (delete-region beg
(point))
2461 ;; If initial point was within line's indentation,
2462 ;; position after the indentation. Else stay at same point in text.
2463 (if (> (- (point-max) pos
) (point))
2464 (goto-char (- (point-max) pos
))))))
2467 (defun sh-blink (blinkpos &optional msg
)
2468 "Move cursor momentarily to BLINKPOS and display MSG."
2469 ;; We can get here without it being a number on first line
2470 (if (numberp blinkpos
)
2472 (goto-char blinkpos
)
2474 (sit-for blink-matching-delay
))
2477 (defun sh-show-indent (arg)
2478 "Show the how the currently line would be indented.
2479 This tells you which variable, if any, controls the indentation of
2481 If optional arg ARG is non-null (called interactively with a prefix),
2482 a pop up window describes this variable.
2483 If variable `sh-blink' is non-nil then momentarily go to the line
2484 we are indenting relative to, if applicable."
2486 (sh-must-support-indent)
2487 (let* ((info (sh-get-indent-info))
2488 (var (sh-get-indent-var-for-line info
))
2489 (curr-indent (current-indentation))
2492 (message (setq msg var
))
2493 (setq val
(sh-calculate-indent info
))
2495 (if (eq curr-indent val
)
2496 (setq msg
(format "%s is %s" var
(symbol-value var
)))
2499 (format "%s (%s) would change indent from %d to: %d"
2500 var
(symbol-value var
) curr-indent val
)
2501 (format "%s (%s) would leave line as is"
2502 var
(symbol-value var
)))
2505 (describe-variable var
)))
2507 (let ((info (sh-get-indent-info)))
2508 (if (and info
(listp (car info
))
2509 (eq (car (car info
)) t
))
2510 (sh-blink (nth 1 (car info
)) msg
)
2515 (defun sh-set-indent ()
2516 "Set the indentation for the current line.
2517 If the current line is controlled by an indentation variable, prompt
2518 for a new value for it."
2520 (sh-must-support-indent)
2521 (let* ((info (sh-get-indent-info))
2522 (var (sh-get-indent-var-for-line info
))
2523 val val0 new-val old-val indent-val
)
2525 (message (format "Cannot set indent - %s" var
))
2526 (setq old-val
(symbol-value var
))
2527 (setq val
(sh-read-variable var
))
2531 (setq indent-val
(sh-calculate-indent info
))
2533 (message "Variable: %s Value: %s would indent to: %d"
2534 var
(symbol-value var
) indent-val
)
2535 (message "Variable: %s Value: %s would leave line as is."
2536 var
(symbol-value var
)))
2537 ;; I'm not sure about this, indenting it now?
2538 ;; No. Because it would give the impression that an undo would
2539 ;; restore thing, but the value has been altered.
2544 (message "Bad value for %s, restoring to previous value %s"
2551 (defun sh-learn-line-indent (arg)
2552 "Learn how to indent a line as it currently is indented.
2554 If there is an indentation variable which controls this line's indentation,
2555 then set it to a value which would indent the line the way it
2558 If the value can be represented by one of the symbols then do so
2559 unless optional argument ARG (the prefix when interactive) is non-nil."
2561 (sh-must-support-indent)
2562 ;; I'm not sure if we show allow learning on an empty line.
2563 ;; Though it might occasionally be useful I think it usually
2564 ;; would just be confusing.
2567 (looking-at "\\s-*$"))
2568 (message "sh-learn-line-indent ignores empty lines.")
2569 (let* ((info (sh-get-indent-info))
2570 (var (sh-get-indent-var-for-line info
))
2571 ival sval diff new-val
2573 (curr-indent (current-indentation)))
2576 (message (format "Cannot learn line - %s" var
)))
2577 ((eq var
'sh-indent-comment
)
2578 ;; This is arbitrary...
2579 ;; - if curr-indent is 0, set to curr-indent
2580 ;; - else if it has the indentation of a "normal" line,
2582 ;; - else set to curr-indent.
2583 (setq sh-indent-comment
2584 (if (= curr-indent
0)
2586 (let* ((sh-indent-comment t
)
2587 (val2 (sh-calculate-indent info
)))
2588 (if (= val2 curr-indent
)
2591 (message "%s set to %s" var
(symbol-value var
))
2593 ((numberp (setq sval
(sh-var-value var
)))
2594 (setq ival
(sh-calculate-indent info
))
2595 (setq diff
(- curr-indent ival
))
2597 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2598 curr-indent ival diff var sval
)
2599 (setq new-val
(+ sval diff
))
2600 ;;; I commented out this because someone might want to replace
2601 ;;; a value of `+' with the current value of sh-basic-offset
2604 ;;; (message "No change needed!")
2605 (sh-set-var-value var new-val no-symbol
)
2606 (message "%s set to %s" var
(symbol-value var
))
2610 (message "Cannot change %s" var
))))))
2614 (defun sh-mark-init (buffer)
2615 "Initialize a BUFFER to be used by `sh-mark-line'."
2616 (let ((main-buffer (current-buffer)))
2618 (set-buffer (get-buffer-create buffer
))
2621 (setq occur-buffer main-buffer
)
2625 (defun sh-mark-line (message point buffer
&optional add-linenum occur-point
)
2626 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2627 Buffer BUFFER is in `occur-mode'.
2628 If ADD-LINENUM is non-nil the message is preceded by the line number.
2629 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2630 so that `occur-next' and `occur-prev' will work."
2631 (let ((m1 (make-marker))
2632 (main-buffer (current-buffer))
2636 (set-marker m1 point
(current-buffer))
2638 (setq line
(format "%d: " (1+ (count-lines 1 point
))))))
2640 (if (get-buffer buffer
)
2641 (set-buffer (get-buffer buffer
))
2642 (set-buffer (get-buffer-create buffer
))
2644 (setq occur-buffer main-buffer
)
2646 (goto-char (point-max))
2647 (setq start
(point))
2650 (setq occur-point
(point)))
2653 (put-text-property start
(point) 'mouse-face
'highlight
))
2657 (put-text-property start
(point) 'occur m1
)
2659 (put-text-property occur-point
(1+ occur-point
)
2666 ;; Is this really worth having?
2667 (defvar sh-learned-buffer-hook nil
2668 "*An abnormal hook, called with an alist of learned variables.")
2669 ;;; Example of how to use sh-learned-buffer-hook
2671 ;; (defun what-i-learned (list)
2674 ;; (set-buffer "*scratch*")
2675 ;; (goto-char (point-max))
2676 ;; (insert "(setq\n")
2678 ;; (insert (format " %s %s \n"
2679 ;; (nth 0 (car p)) (nth 1 (car p))))
2680 ;; (setq p (cdr p)))
2684 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2687 ;; Originally this was sh-learn-region-indent (beg end)
2688 ;; However, in practice this was awkward so I changed it to
2689 ;; use the whole buffer. Use narrowing if needbe.
2690 (defun sh-learn-buffer-indent (&optional arg
)
2691 "Learn how to indent the buffer the way it currently is.
2693 Output in buffer \"*indent*\" shows any lines which have conflicting
2694 values of a variable, and the final value of all variables learned.
2695 This buffer is popped to automatically if there are any discrepancies.
2697 If no prefix ARG is given, then variables are set to numbers.
2698 If a prefix arg is given, then variables are set to symbols when
2699 applicable -- e.g. to symbol `+' if the value is that of the
2701 If a positive numerical prefix is given, then `sh-basic-offset'
2702 is set to the prefix's numerical value.
2703 Otherwise, sh-basic-offset may or may not be changed, according
2704 to the value of variable `sh-learn-basic-offset'.
2706 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2707 function completes. The function is abnormal because it is called
2708 with an alist of variables learned. This feature may be changed or
2709 removed in the future.
2711 This command can often take a long time to run."
2713 (sh-must-support-indent)
2715 (goto-char (point-min))
2716 (let ((learned-var-list nil
)
2717 (out-buffer "*indent*")
2724 (comment-col nil
) ;; number if all same, t if seen diff values
2725 (comments-always-default t
) ;; nil if we see one not default
2727 (specified-basic-offset (and arg
(numberp arg
)
2731 (setq vec
(make-vector max
0))
2732 (sh-mark-init out-buffer
)
2734 (if specified-basic-offset
2736 (setq sh-basic-offset arg
)
2738 (format "Using specified sh-basic-offset of %d"
2741 (format "Initial value of sh-basic-offset: %s"
2744 (while (< (point) (point-max))
2745 (setq linenum
(1+ linenum
))
2746 ;; (if (zerop (% linenum 10))
2747 (message "line %d" linenum
)
2749 (unless (looking-at "\\s-*$") ;; ignore empty lines!
2750 (let* ((sh-indent-comment t
) ;; info must return default indent
2751 (info (sh-get-indent-info))
2752 (var (sh-get-indent-var-for-line info
))
2753 sval ival diff new-val
2754 (curr-indent (current-indentation)))
2760 ((numberp (setq sval
(sh-var-value var
'no-error
)))
2761 ;; the numberp excludes comments since sval will be t.
2762 (setq ival
(sh-calculate-indent))
2763 (setq diff
(- curr-indent ival
))
2764 (setq new-val
(+ sval diff
))
2765 (sh-set-var-value var new-val
'no-symbol
)
2766 (unless (looking-at "\\s-*#") ;; don't learn from comments
2767 (if (setq previous-set-info
(assoc var learned-var-list
))
2769 ;; it was already there, is it same value ?
2770 (unless (eq (symbol-value var
)
2771 (nth 1 previous-set-info
))
2773 (format "Variable %s was set to %s"
2774 var
(symbol-value var
))
2775 (point) out-buffer t t
)
2777 (format " but was previously set to %s"
2778 (nth 1 previous-set-info
))
2779 (nth 2 previous-set-info
) out-buffer t
)
2780 (setq num-diffs
(1+ num-diffs
))
2781 ;; (delete previous-set-info learned-var-list)
2782 (setcdr previous-set-info
2783 (list (symbol-value var
) (point)))
2786 (setq learned-var-list
2787 (append (list (list var
(symbol-value var
)
2790 (if (numberp new-val
)
2793 "This line's indent value: %d" new-val
)
2795 (setq new-val
(- new-val
)))
2797 (aset vec new-val
(1+ (aref vec new-val
))))))
2799 ((eq var
'sh-indent-comment
)
2800 (unless (= curr-indent
(sh-calculate-indent info
))
2801 ;; this is not the default indentation
2802 (setq comments-always-default nil
)
2803 (if comment-col
;; then we have see one before
2804 (or (eq comment-col curr-indent
)
2805 (setq comment-col t
)) ;; seen a different one
2806 (setq comment-col curr-indent
))
2809 (sh-debug "Cannot learn this line!!!")
2812 "at %s learned-var-list is %s" (point) learned-var-list
)
2819 "comment-col = %s comments-always-default = %s"
2820 comment-col comments-always-default
))
2822 (sh-mark-line msg nil out-buffer
)))
2825 (setq msg
"\nComments are all in 1st column.\n"))
2826 (comments-always-default
2827 (setq msg
"\nComments follow default indentation.\n")
2828 (setq comment-col t
))
2829 ((numberp comment-col
)
2830 (setq msg
(format "\nComments are in col %d." comment-col
)))
2832 (setq msg
"\nComments seem to be mixed, leaving them as is.\n")
2833 (setq comment-col nil
)
2836 (sh-mark-line msg nil out-buffer
)
2838 (sh-mark-line initial-msg nil out-buffer t t
)
2840 (setq suggested
(sh-guess-basic-offset vec
))
2842 (if (and suggested
(not specified-basic-offset
))
2845 ;; t => set it if we have a single value as a number
2846 ((and (eq sh-learn-basic-offset t
) (numberp suggested
))
2848 ;; other non-nil => set it if only one value was found
2849 (sh-learn-basic-offset
2850 (if (numberp suggested
)
2852 (if (= (length suggested
) 1)
2858 (setq learned-var-list
2859 (append (list (list 'sh-basic-offset
2860 (setq sh-basic-offset new-value
)
2863 ;; Not sure if we need to put this line in, since
2864 ;; it will appear in the "Learned variable settings".
2866 (format "Changed sh-basic-offset to: %d" sh-basic-offset
)
2869 (if (listp suggested
)
2870 (format "Possible value(s) for sh-basic-offset: %s"
2871 (mapconcat 'int-to-string suggested
" "))
2872 (format "Suggested sh-basic-offset: %d" suggested
))
2876 (setq learned-var-list
2877 (append (list (list 'sh-indent-comment comment-col
(point-max)))
2879 (setq sh-indent-comment comment-col
)
2880 (let ((name (buffer-name))
2881 (lines (if (and (eq (point-min) 1)
2882 (eq (point-max) (1+ (buffer-size))))
2884 (format "lines %d to %d of "
2885 (1+ (count-lines 1 (point-min)))
2886 (1+ (count-lines 1 (point-max))))))
2888 (sh-mark-line "\nLearned variable settings:" nil out-buffer
)
2890 ;; Set learned variables to symbolic rather than numeric
2891 ;; values where possible.
2892 (dolist (learned-var (reverse learned-var-list
))
2893 (let ((var (car learned-var
))
2894 (val (nth 1 learned-var
)))
2895 (when (and (not (eq var
'sh-basic-offset
))
2897 (sh-set-var-value var val
)))))
2898 (dolist (learned-var (reverse learned-var-list
))
2899 (let ((var (car learned-var
)))
2900 (sh-mark-line (format " %s %s" var
(symbol-value var
))
2901 (nth 2 learned-var
) out-buffer
)))
2903 (set-buffer out-buffer
)
2904 (goto-char (point-min))
2906 (format "Indentation values for buffer %s.\n" name
)
2907 (format "%d indentation variable%s different values%s\n\n"
2911 (if (zerop num-diffs
)
2914 ;; Are abnormal hooks considered bad form?
2915 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list
)
2916 (if (or sh-popup-occur-buffer
(> num-diffs
0))
2917 (pop-to-buffer out-buffer
))
2920 (defun sh-guess-basic-offset (vec)
2921 "See if we can determine a reasonable value for `sh-basic-offset'.
2922 This is experimental, heuristic and arbitrary!
2923 Argument VEC is a vector of information collected by
2924 `sh-learn-buffer-indent'.
2926 number - there appears to be a good single value
2927 list of numbers - no obvious one, here is a list of one or more
2929 nil - we couldn't find a reasonable one."
2930 (let* ((max (1- (length vec
)))
2932 (totals (make-vector max
0))
2936 (aset totals i
(+ (aref totals i
) (* 4 (aref vec i
))))
2939 (aset totals i
(+ (aref totals i
) (aref vec
(/ i
2)))))
2941 (aset totals i
(+ (aref totals i
) (aref vec
(* i
2)))))
2949 (if (/= (aref totals i
) 0)
2950 (setq x
(append x
(list (cons i
(aref totals i
))))))
2953 (setq x
(sort x
(lambda (a b
) (> (cdr a
) (cdr b
)))))
2954 (setq tot
(apply '+ (append totals nil
)))
2955 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
2959 (message "no values!")) ;; we return nil
2961 (message "only value is %d" (car (car x
)))
2962 (setq result
(car (car x
)))) ;; return single value
2963 ((> (cdr (car x
)) (/ tot
2))
2965 (message "basic-offset is probably %d" (car (car x
)))
2966 (setq result
(car (car x
)))) ;; again, return a single value
2967 ((>= (cdr (car x
)) (* 2 (cdr (car (cdr x
)))))
2968 ;; 1st is >= 2 * 2nd
2969 (message "basic-offset could be %d" (car (car x
)))
2970 (setq result
(car (car x
))))
2971 ((>= (+ (cdr (car x
))(cdr (car (cdr x
)))) (/ tot
2))
2972 ;; 1st & 2nd together >= 50% - return a list
2973 (setq p x sum
0 result nil
)
2975 (<= (setq sum
(+ sum
(cdr (car p
)))) (/ tot
2)))
2976 (setq result
(append result
(list (car (car p
)))))
2978 (message "Possible choices for sh-basic-offset: %s"
2979 (mapconcat 'int-to-string result
" ")))
2981 (message "No obvious value for sh-basic-offset. Perhaps %d"
2983 ;; result is nil here
2987 ;; ========================================================================
2989 ;; Styles -- a quick and dirty way of saving the indentation settings.
2991 (defvar sh-styles-alist nil
2992 "A list of all known shell indentation styles.")
2994 (defun sh-name-style (name &optional confirm-overwrite
)
2995 "Name the current indentation settings as a style called NAME.
2996 If this name exists, the command will prompt whether it should be
2998 - - it was called interactively with a prefix argument, or
2999 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3000 ;; (interactive "sName for this style: ")
3003 (read-from-minibuffer "Name for this style? " )
3004 (not current-prefix-arg
)))
3005 (let ((slist (cons name
3006 (mapcar (lambda (var) (cons var
(symbol-value var
)))
3008 (style (assoc name sh-styles-alist
)))
3010 (if (and confirm-overwrite
3011 (not (y-or-n-p "This style exists. Overwrite it? ")))
3012 (message "Not changing style %s" name
)
3013 (message "Updating style %s" name
)
3014 (setcdr style
(cdr slist
)))
3015 (message "Creating new style %s" name
)
3016 (push slist sh-styles-alist
))))
3018 (defun sh-load-style (name)
3019 "Set shell indentation values for this buffer from those in style NAME."
3020 (interactive (list (completing-read
3021 "Which style to use for this buffer? "
3022 sh-styles-alist nil t
)))
3023 (let ((sl (assoc name sh-styles-alist
)))
3025 (error "sh-load-style - style %s not known" name
)
3026 (dolist (var (cdr sl
))
3027 (set (car var
) (cdr var
))))))
3029 (defun sh-save-styles-to-buffer (buff)
3030 "Save all current styles in elisp to buffer BUFF.
3031 This is always added to the end of the buffer."
3033 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3034 (with-current-buffer (get-buffer-create buff
)
3035 (goto-char (point-max))
3037 (pp `(setq sh-styles-alist
',sh-styles-alist
) (current-buffer))))
3041 ;; statement syntax-commands for various shells
3043 ;; You are welcome to add the syntax or even completely new statements as
3044 ;; appropriate for your favorite shell.
3046 (define-skeleton sh-case
3047 "Insert a case/switch statement. See `sh-feature'."
3049 "switch( " str
" )" \n
3050 > "case " (read-string "pattern: ") ?
: \n
3053 ( "other pattern, %s: "
3063 > "switch( " str
" ) {" \n
3064 > "case " (read-string "pattern: ") \n
3066 ( "other pattern, %s: "
3074 > "case " str
" in" \n
3075 > (read-string "pattern: ")
3076 (propertize ")" 'syntax-table sh-st-punc
)
3080 ( "other pattern, %s: "
3081 > str
(propertize ")" 'syntax-table sh-st-punc
) \n
3084 > "*" (propertize ")" 'syntax-table sh-st-punc
) \n
3089 (define-skeleton sh-for
3090 "Insert a for loop. See `sh-feature'."
3091 (csh eval sh-modify sh
3099 (es eval sh-modify rc
3101 (rc eval sh-modify sh
3105 (sh "Index variable: "
3106 > "for " str
" in " _
"; do" \n
3107 > _ | ?$
& (sh-remember-variable str
) \n
3112 (define-skeleton sh-indexed-loop
3113 "Insert an indexed loop from 1 to n. See `sh-feature'."
3114 (bash eval identity posix
)
3115 (csh "Index variable: "
3117 "while( $" str
" <= " (read-string "upper limit: ") " )" \n
3121 (es eval sh-modify rc
3123 (ksh88 "Index variable: "
3124 > "integer " str
"=0" \n
3125 > "while (( ( " str
" += 1 ) <= "
3126 (read-string "upper limit: ")
3128 > _ ?$
(sh-remember-variable str
) > \n
3130 (posix "Index variable: "
3132 "while [ $" str
" -le "
3133 (read-string "upper limit: ")
3136 str ?
= (sh-add (sh-remember-variable str
) 1) \n
3138 (rc "Index variable: "
3139 > "for( " str
" in" " `{awk 'BEGIN { for( i=1; i<="
3140 (read-string "upper limit: ")
3141 "; i++ ) print i }'`}) {" \n
3142 > _ ?$
(sh-remember-variable str
) \n
3144 (sh "Index variable: "
3145 > "for " str
" in `awk 'BEGIN { for( i=1; i<="
3146 (read-string "upper limit: ")
3147 "; i++ ) print i }'`; do" \n
3148 > _ ?$
(sh-remember-variable str
) \n
3152 (defun sh-shell-initialize-variables ()
3153 "Scan the buffer for variable assignments.
3154 Add these variables to `sh-shell-variables'."
3155 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3157 (goto-char (point-min))
3158 (setq sh-shell-variables-initialized t
)
3159 (while (search-forward "=" nil t
)
3161 (message "Scanning buffer `%s' for variable assignments...done"
3164 (defvar sh-add-buffer
)
3166 (defun sh-add-completer (string predicate code
)
3167 "Do completion using `sh-shell-variables', but initialize it first.
3168 This function is designed for use as the \"completion table\",
3169 so it takes three arguments:
3170 STRING, the current buffer contents;
3171 PREDICATE, the predicate for filtering possible matches;
3172 CODE, which says what kind of things to do.
3173 CODE can be nil, t or `lambda'.
3174 nil means to return the best completion of STRING, or nil if there is none.
3175 t means to return a list of all possible completions of STRING.
3176 `lambda' means to return t if STRING is a valid completion as it stands."
3177 (let ((sh-shell-variables
3179 (set-buffer sh-add-buffer
)
3180 (or sh-shell-variables-initialized
3181 (sh-shell-initialize-variables))
3182 (nconc (mapcar (lambda (var)
3184 (substring var
0 (string-match "=" var
))))
3186 process-environment
)
3187 sh-shell-variables
))))
3189 (try-completion string sh-shell-variables predicate
))
3191 (all-completions string sh-shell-variables predicate
))
3193 (assoc string sh-shell-variables
)))))
3195 (defun sh-add (var delta
)
3196 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3198 (let ((sh-add-buffer (current-buffer)))
3199 (list (completing-read "Variable: " 'sh-add-completer
)
3200 (prefix-numeric-value current-prefix-arg
))))
3201 (insert (sh-feature '((bash .
"$[ ")
3207 (sh-remember-variable var
)
3208 (if (< delta
0) " - " " + ")
3209 (number-to-string (abs delta
))
3210 (sh-feature '((bash .
" ]")
3219 (define-skeleton sh-function
3220 "Insert a function definition. See `sh-feature'."
3221 (bash eval sh-modify ksh88
3224 "function " str
" {" \n
3227 (rc eval sh-modify ksh88
3236 (define-skeleton sh-if
3237 "Insert an if statement. See `sh-feature'."
3239 "if( " str
" ) then" \n
3241 ( "other condition, %s: "
3242 < "else if( " str
" ) then" \n
3249 > "if { " str
" } {" \n
3251 ( "other condition, %s: "
3252 "} { " str
" } {" > \n
3259 > "if( " str
" ) {" \n
3261 ( "other condition, %s: "
3262 "} else if( " str
" ) {" > \n
3270 '(setq input
(sh-feature sh-test
))
3271 > "if " str
"; then" \n
3273 ( "other condition, %s: "
3274 > "elif " str
"; then" > \n
3283 (define-skeleton sh-repeat
3284 "Insert a repeat loop definition. See `sh-feature'."
3290 > "repeat " str
"; do" > \n
3294 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3298 (define-skeleton sh-select
3299 "Insert a select statement. See `sh-feature'."
3300 (ksh88 "Index variable: "
3301 > "select " str
" in " _
"; do" \n
3304 (bash eval sh-append ksh88
)
3306 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3310 (define-skeleton sh-tmp-file
3311 "Insert code to setup temporary file handling. See `sh-feature'."
3312 (bash eval identity ksh88
)
3313 (csh (file-name-nondirectory (buffer-file-name))
3314 "set tmp = /tmp/" str
".$$" \n
3316 (and (goto-char (point-max))
3320 "rm $tmp* >&/dev/null" >)
3321 (es (file-name-nondirectory (buffer-file-name))
3322 > "local( signals = $signals sighup sigint; tmp = /tmp/" str
3325 > "rm $tmp^* >[2]/dev/null" \n
3331 (ksh88 eval sh-modify sh
3333 (rc (file-name-nondirectory (buffer-file-name))
3334 > "tmp = /tmp/" str
".$pid" \n
3335 "fn sigexit { rm $tmp^* >[2]/dev/null }")
3336 (sh (file-name-nondirectory (buffer-file-name))
3337 > "TMP=${TMPDIR:-/tmp}/" str
".$$" \n
3338 "trap \"rm $TMP* 2>/dev/null\" " ?
0))
3342 (define-skeleton sh-until
3343 "Insert an until loop. See `sh-feature'."
3345 '(setq input
(sh-feature sh-test
))
3346 > "until " str
"; do" \n
3349 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3353 (define-skeleton sh-while
3354 "Insert a while loop. See `sh-feature'."
3355 (csh eval sh-modify sh
3361 (es eval sh-modify sh
3365 (rc eval sh-modify sh
3370 '(setq input
(sh-feature sh-test
))
3371 > "while " str
"; do" \n
3377 (define-skeleton sh-while-getopts
3378 "Insert a while getopts loop. See `sh-feature'.
3379 Prompts for an options string which consists of letters for each recognized
3380 option followed by a colon `:' if the option accepts an argument."
3381 (bash eval sh-modify sh
3385 > "switch( \"$1\" )" \n
3386 '(setq input
'("- x" .
2))
3389 < "case " '(eval str
)
3390 '(if (string-match " +" str
)
3391 (setq v1
(substring str
(match-end 0))
3392 str
(substring str
0 (match-beginning 0)))
3395 > "set " v1
& " = $2" | -
4 & _
\n
3396 (if v1
"shift") & \n
3406 (ksh88 eval sh-modify sh
3410 (posix eval sh-modify sh
3411 18 "$(basename $0)")
3413 > "while getopts :" str
" OPT; do" \n
3415 '(setq v1
(append (vconcat str
) nil
))
3416 ( (prog1 (if v1
(char-to-string (car v1
)))
3417 (if (eq (nth 1 v1
) ?
:)
3418 (setq v1
(nthcdr 2 v1
)
3422 > str
"|+" str
(propertize ")" 'syntax-table sh-st-punc
) \n
3425 > "*" (propertize ")" 'syntax-table sh-st-punc
) \n
3426 > "echo" " \"usage: " "`basename $0`"
3427 " [+-" '(setq v1
(point)) str
3429 (while (search-backward ":" v1 t
)
3430 (replace-match " ARG] [+-" t t
)))
3431 (if (eq (preceding-char) ?-
) -
5)
3432 (if (and (sequencep v1
) (length v1
)) "] " "} ")
3438 "shift " (sh-add "OPTIND" -
1)))
3442 (defun sh-assignment (arg)
3443 "Remember preceding identifier for future completion and do self-insert."
3445 (self-insert-command arg
)
3447 (sh-remember-variable
3449 (if (re-search-forward (sh-feature sh-assignment-regexp
)
3451 (beginning-of-line 1))
3453 (match-string 1))))))
3457 (defun sh-maybe-here-document (arg)
3458 "Insert self. Without prefix, following unquoted `<' inserts here document.
3459 The document is bounded by `sh-here-document-word'."
3461 (self-insert-command (prefix-numeric-value arg
))
3463 (not (eq (char-after (- (point) 2)) last-command-char
))
3468 (insert sh-here-document-word
)
3469 (or (eolp) (looking-at "[ \t]") (insert ?
))
3475 (save-excursion (insert ?
\n sh-here-document-word
)))))
3478 ;; various other commands
3480 (autoload 'comint-dynamic-complete
"comint"
3481 "Dynamically perform completion at point." t
)
3483 (autoload 'shell-dynamic-complete-command
"shell"
3484 "Dynamically complete the command at point." t
)
3486 (autoload 'comint-dynamic-complete-filename
"comint"
3487 "Dynamically complete the filename at point." t
)
3489 (autoload 'shell-dynamic-complete-environment-variable
"shell"
3490 "Dynamically complete the environment variable at point." t
)
3494 (defun sh-newline-and-indent ()
3495 "Strip unquoted whitespace, insert newline, and indent like current line."
3497 (indent-to (prog1 (current-indentation)
3498 (delete-region (point)
3500 (or (zerop (skip-chars-backward " \t"))
3506 (defun sh-beginning-of-command ()
3507 "Move point to successive beginnings of commands."
3509 (if (re-search-backward sh-beginning-of-command nil t
)
3510 (goto-char (match-beginning 2))))
3512 (defun sh-end-of-command ()
3513 "Move point to successive ends of commands."
3515 (if (re-search-forward sh-end-of-command nil t
)
3516 (goto-char (match-end 1))))
3518 (provide 'sh-script
)
3520 ;;; sh-script.el ends here