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 (easy-mmode-defsyntax sh-mode-syntax-table
405 "Syntax-table used in Shell-Script mode.")
409 (let ((map (make-sparse-keymap))
410 (menu-map (make-sparse-keymap "Insert")))
411 (define-key map
"\C-c(" 'sh-function
)
412 (define-key map
"\C-c\C-w" 'sh-while
)
413 (define-key map
"\C-c\C-u" 'sh-until
)
414 (define-key map
"\C-c\C-t" 'sh-tmp-file
)
415 (define-key map
"\C-c\C-s" 'sh-select
)
416 (define-key map
"\C-c\C-r" 'sh-repeat
)
417 (define-key map
"\C-c\C-o" 'sh-while-getopts
)
418 (define-key map
"\C-c\C-l" 'sh-indexed-loop
)
419 (define-key map
"\C-c\C-i" 'sh-if
)
420 (define-key map
"\C-c\C-f" 'sh-for
)
421 (define-key map
"\C-c\C-c" 'sh-case
)
422 (define-key map
"\C-c?" 'sh-show-indent
)
423 (define-key map
"\C-c=" 'sh-set-indent
)
424 (define-key map
"\C-c<" 'sh-learn-line-indent
)
425 (define-key map
"\C-c>" 'sh-learn-buffer-indent
)
427 (define-key map
"=" 'sh-assignment
)
428 (define-key map
"\C-c+" 'sh-add
)
429 (define-key map
"\C-\M-x" 'sh-execute-region
)
430 (define-key map
"\C-c\C-x" 'executable-interpret
)
431 (define-key map
"<" 'sh-maybe-here-document
)
432 (define-key map
"(" 'skeleton-pair-insert-maybe
)
433 (define-key map
"{" 'skeleton-pair-insert-maybe
)
434 (define-key map
"[" 'skeleton-pair-insert-maybe
)
435 (define-key map
"'" 'skeleton-pair-insert-maybe
)
436 (define-key map
"`" 'skeleton-pair-insert-maybe
)
437 (define-key map
"\"" 'skeleton-pair-insert-maybe
)
439 (substitute-key-definition 'complete-tag
'comint-dynamic-complete
440 map
(current-global-map))
441 (substitute-key-definition 'newline-and-indent
'sh-newline-and-indent
442 map
(current-global-map))
443 (substitute-key-definition 'delete-backward-char
444 'backward-delete-char-untabify
445 map
(current-global-map))
446 (define-key map
"\C-c:" 'sh-set-shell
)
447 (substitute-key-definition 'beginning-of-defun
448 'sh-beginning-of-compound-command
449 map
(current-global-map))
450 (substitute-key-definition 'backward-sentence
'sh-beginning-of-command
451 map
(current-global-map))
452 (substitute-key-definition 'forward-sentence
'sh-end-of-command
453 map
(current-global-map))
454 (define-key map
[menu-bar insert
] (cons "Insert" menu-map
))
455 (define-key menu-map
[sh-while
] '("While Loop" . sh-while
))
456 (define-key menu-map
[sh-until
] '("Until Loop" . sh-until
))
457 (define-key menu-map
[sh-tmp-file
] '("Temporary File" . sh-tmp-file
))
458 (define-key menu-map
[sh-select
] '("Select Statement" . sh-select
))
459 (define-key menu-map
[sh-repeat
] '("Repeat Loop" . sh-repeat
))
460 (define-key menu-map
[sh-getopts
] '("Options Loop" . sh-while-getopts
))
461 (define-key menu-map
[sh-indexed-loop
] '("Indexed Loop" . sh-indexed-loop
))
462 (define-key menu-map
[sh-if
] '("If Statement" . sh-if
))
463 (define-key menu-map
[sh-for
] '("For Loop" . sh-for
))
464 (define-key menu-map
[sh-case
] '("Case Statement" . sh-case
))
466 "Keymap used in Shell-Script mode.")
470 (defcustom sh-dynamic-complete-functions
471 '(shell-dynamic-complete-environment-variable
472 shell-dynamic-complete-command
473 comint-dynamic-complete-filename
)
474 "*Functions for doing TAB dynamic completion."
475 :type
'(repeat function
)
479 (defcustom sh-require-final-newline
482 (rc eval . require-final-newline
)
483 (sh eval . require-final-newline
))
484 "*Value of `require-final-newline' in Shell-Script mode buffers.
486 :type
'(repeat (cons (symbol :tag
"Shell")
487 (choice (const :tag
"require" t
)
488 (cons :format
"Evaluate: %v"
489 (const :format
"" eval
)
494 (defcustom sh-assignment-regexp
495 '((csh .
"\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
496 ;; actually spaces are only supported in let/(( ... ))
497 (ksh88 .
"\\<\\([a-zA-Z0-9_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
498 (rc .
"\\<\\([a-zA-Z0-9_*]+\\)[ \t]*=")
499 (sh .
"\\<\\([a-zA-Z0-9_]+\\)="))
500 "*Regexp for the variable name and what may follow in an assignment.
501 First grouping matches the variable name. This is upto and including the `='
502 sign. See `sh-feature'."
503 :type
'(repeat (cons (symbol :tag
"Shell")
505 (cons :format
"Evaluate: %v"
506 (const :format
"" eval
)
511 (defcustom sh-indentation
4
512 "The width for further indentation in Shell-Script mode."
517 (defcustom sh-remember-variable-min
3
518 "*Don't remember variables less than this length for completing reads."
523 (defvar sh-header-marker nil
524 "When non-nil is the end of header for prepending by \\[sh-execute-region].
525 That command is also used for setting this variable.")
528 (defcustom sh-beginning-of-command
529 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~a-zA-Z0-9:]\\)"
530 "*Regexp to determine the beginning of a shell command.
531 The actual command starts at the beginning of the second \\(grouping\\)."
536 (defcustom sh-end-of-command
537 "\\([/~a-zA-Z0-9:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
538 "*Regexp to determine the end of a shell command.
539 The actual command ends at the end of the first \\(grouping\\)."
545 (defvar sh-here-document-word
"EOF"
546 "Word to delimit here documents.")
551 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
554 ;; customized this out of sheer bravado. not for the faint of heart.
555 ;; but it *did* have an asterisk in the docstring!
556 (defcustom sh-builtins
557 '((bash eval sh-append posix
558 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
559 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
560 "suspend" "typeset" "unalias")
562 ;; The next entry is only used for defining the others
563 (bourne eval sh-append shell
564 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
567 (csh eval sh-append shell
568 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
569 "setenv" "source" "time" "unalias" "unhash")
571 (dtksh eval identity wksh
)
573 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
574 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
576 (jsh eval sh-append sh
577 "bg" "fg" "jobs" "kill" "stop" "suspend")
579 (jcsh eval sh-append csh
580 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
582 (ksh88 eval sh-append bourne
583 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
584 "typeset" "unalias" "whence")
586 (oash eval sh-append sh
587 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
588 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
589 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
590 "wmtitle" "wrefresh")
592 (pdksh eval sh-append ksh88
595 (posix eval sh-append sh
598 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
601 (sh eval sh-append bourne
602 "hash" "test" "type")
604 ;; The next entry is only used for defining the others
605 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
607 (wksh eval sh-append ksh88
610 (zsh eval sh-append ksh88
611 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
612 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
613 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
614 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
615 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
617 "*List of all shell builtins for completing read and fontification.
618 Note that on some systems not all builtins are available or some are
619 implemented as aliases. See `sh-feature'."
620 :type
'(repeat (cons (symbol :tag
"Shell")
621 (choice (repeat string
)
622 (cons :format
"Evaluate: %v"
623 (const :format
"" eval
)
629 (defcustom sh-leading-keywords
632 (es "true" "unwind-protect" "whatis")
636 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
637 "*List of keywords that may be immediately followed by a builtin or keyword.
638 Given some confusion between keywords and builtins depending on shell and
639 system, the distinction here has been based on whether they influence the
640 flow of control or syntax. See `sh-feature'."
641 :type
'(repeat (cons (symbol :tag
"Shell")
642 (choice (repeat string
)
643 (cons :format
"Evaluate: %v"
644 (const :format
"" eval
)
649 (defcustom sh-other-keywords
650 '((bash eval sh-append bourne
653 ;; The next entry is only used for defining the others
654 (bourne eval sh-append sh
657 (csh eval sh-append shell
658 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
659 "if" "logout" "onintr" "repeat" "switch" "then" "while")
661 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
662 "return" "throw" "while")
664 (ksh88 eval sh-append bourne
667 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
670 (sh eval sh-append shell
671 "done" "esac" "fi" "for" "in" "return")
673 ;; The next entry is only used for defining the others
674 (shell "break" "case" "continue" "exec" "exit")
676 (zsh eval sh-append bash
678 "*List of keywords not in `sh-leading-keywords'.
680 :type
'(repeat (cons (symbol :tag
"Shell")
681 (choice (repeat string
)
682 (cons :format
"Evaluate: %v"
683 (const :format
"" eval
)
690 '((bash eval sh-append sh
691 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
692 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
693 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
694 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
695 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
696 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
697 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
698 "SECONDS" "SHLVL" "TMOUT" "UID")
700 (csh eval sh-append shell
701 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
702 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
703 "shell" "status" "time" "verbose")
705 (es eval sh-append shell
706 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
707 "pid" "prompt" "signals")
709 (jcsh eval sh-append csh
712 (ksh88 eval sh-append sh
713 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
714 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
717 (oash eval sh-append sh
718 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
720 (rc eval sh-append shell
721 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
724 (sh eval sh-append shell
725 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
727 ;; The next entry is only used for defining the others
728 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
729 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
730 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
731 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
733 (tcsh eval sh-append csh
734 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
735 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
736 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
737 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
738 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
739 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
740 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
741 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
744 (zsh eval sh-append ksh88
745 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
746 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
747 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
748 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
749 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
750 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
751 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
752 "List of all shell variables available for completing read.
756 ;;; Font-Lock support
758 (defface sh-heredoc-face
761 (:foreground
"yellow" :bold t
))
764 (:foreground
"tan" ))
767 "Face to show a here-document"
768 :group
'sh-indentation
)
769 (defvar sh-heredoc-face
'sh-heredoc-face
)
772 (defvar sh-font-lock-keywords
773 '((csh eval sh-append shell
774 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
775 font-lock-variable-name-face
))
777 (es eval sh-append executable-font-lock-keywords
778 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
779 font-lock-variable-name-face
))
781 (rc eval identity es
)
783 (sh eval sh-append shell
785 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
786 font-lock-variable-name-face
)
788 '("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face
)
789 '("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
790 (1 font-lock-keyword-face
) (2 font-lock-function-name-face nil t
)))
792 ;; The next entry is only used for defining the others
793 (shell eval sh-append executable-font-lock-keywords
794 '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face
)
795 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
796 font-lock-variable-name-face
))
797 (rpm eval sh-append rpm2
798 '("%{?\\(\\sw+\\)" 1 font-lock-keyword-face
))
799 (rpm2 eval sh-append shell
800 '("^\\(\\sw+\\):" 1 font-lock-variable-name-face
)))
801 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
803 (defvar sh-font-lock-keywords-1
805 "Subdued level highlighting for Shell Script modes.")
807 (defvar sh-font-lock-keywords-2
()
808 "Gaudy level highlighting for Shell Script modes.")
810 ;; These are used for the syntax table stuff (derived from cperl-mode).
811 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
812 (defconst sh-st-punc
(string-to-syntax "."))
813 (defconst sh-here-doc-syntax
(string-to-syntax "|")) ;; generic string
815 (defun sh-font-lock-heredoc (start string quoted
)
816 "Determine the syntax of the \\n after a <<HEREDOC."
817 (unless (sh-in-comment-or-string start
)
818 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
819 ;; font-lock keywords to detect the end of this here document.
821 "^" (if quoted
"[ \t]*")
822 (regexp-quote (replace-regexp-in-string "['\"]" "" string
))
824 (unless (assoc ere font-lock-syntactic-keywords
)
825 (let* ( ;; A rough regexp that should find us back.
826 (sre (concat "<<\\(-\\)?\\s-*['\"]?"
827 (regexp-quote string
) "['\"]?[ \t\n]"))
829 ((save-excursion (re-search-backward ,sre nil t
))
830 ;; This ^STRING$ is indeed following a <<STRING
832 ((not (save-excursion (re-search-forward ,sre nil t
)))
833 ;; There's no <<STRING either before or after us,
834 ;; so we should remove this now obsolete entry.
835 (setq font-lock-syntactic-keywords
836 (delq (assoc ,ere font-lock-syntactic-keywords
)
837 font-lock-syntactic-keywords
))
839 ;; Use destructive update so the new keyword gets used right away.
840 (setq font-lock-syntactic-keywords
841 (nconc font-lock-syntactic-keywords
842 (list (font-lock-compile-keyword `(,ere
1 ,code
))))))))
845 (defun sh-font-lock-paren (start)
848 ;; Skip through all patterns
851 (forward-comment (- (point-max)))
852 ;; Skip through one pattern
854 (or (/= 0 (skip-syntax-backward "w_"))
855 (/= 0 (skip-chars-backward "?*/"))
856 (when (memq (char-before) '(?
\" ?
\'))
857 (condition-case nil
(progn (backward-sexp 1) t
)
859 (forward-comment (- (point-max)))
860 (when (eq (char-before) ?|
)
861 (backward-char 1) t
)))
862 (when (save-excursion (backward-char 2) (looking-at ";;\\|in"))
865 (defconst sh-font-lock-syntactic-keywords
866 ;; Mark a `#' character as having punctuation syntax in a variable reference.
867 ;; Really we should do this properly. From Chet Ramey and Brian Fox:
868 ;; "A `#' begins a comment when it is unquoted and at the beginning of a
869 ;; word. In the shell, words are separated by metacharacters."
870 ;; To do this in a regexp would be slow as it would be anchored to the right.
871 ;; But I can't be bothered to write a function to do it properly and
872 ;; efficiently. So we only do it properly for `#' in variable references and
873 ;; do it efficiently by anchoring the regexp to the left.
874 `(("\\${?[^}#\n\t ]*\\(##?\\)" 1 ,sh-st-punc
)
875 ;; Find HEREDOC starters and add a corresponding rule for the ender.
876 ("[^<>]<<\\(-\\)?\\s-*\\(\\(['\"][^'\"]+['\"]\\|\\sw\\|\\s_\\)+\\).*\\(\n\\)"
877 4 (sh-font-lock-heredoc
878 (match-beginning 0) (match-string 2) (match-end 1)))
879 ;; Distinguish the special close-paren in `case'.
880 (")" 0 (sh-font-lock-paren (match-beginning 0)))))
882 (defun sh-font-lock-syntactic-face-function (state)
884 (if (char-valid-p (nth 3 state
))
885 font-lock-string-face
887 font-lock-comment-face
))
889 (defgroup sh-indentation nil
890 "Variables controlling indentation in shell scripts.
892 Note: customizing these variables will not affect existing buffers if
893 `sh-make-vars-local' is no-nil. See the documentation for
894 variable `sh-make-vars-local', command `sh-make-vars-local'
895 and command `sh-reset-indent-vars-to-global-values'."
899 (defcustom sh-set-shell-hook nil
900 "*Hook run by `sh-set-shell'."
904 (defcustom sh-mode-hook nil
905 "*Hook run by `sh-mode'."
909 (defcustom sh-learn-basic-offset nil
910 "*When `sh-guess-basic-offset' should learn `sh-basic-offset'.
913 t means: only if there seems to be an obvious value.
914 Anything else means: whenever we have a \"good guess\" as to the value."
916 (const :tag
"Never" nil
)
917 (const :tag
"Only if sure" t
)
918 (const :tag
"If have a good guess" usually
))
919 :group
'sh-indentation
)
921 (defcustom sh-popup-occur-buffer nil
922 "*Controls when `sh-learn-buffer-indent' pops the *indent* buffer.
923 If t it is always shown. If nil, it is shown only when there
926 (const :tag
"Only when there are conflicts." nil
)
927 (const :tag
"Always" t
))
928 :group
'sh-indentation
)
930 (defcustom sh-blink t
931 "*If non-nil, `sh-show-indent' shows the line indentation is relative to.
932 The position on the line is not necessarily meaningful.
933 In some cases the line will be the matching keyword, but this is not
936 :group
'sh-indentation
)
938 (defcustom sh-first-lines-indent
0
939 "*The indentation of the first non-blank non-comment line.
940 Usually 0 meaning first column.
941 Can be set to a number, or to nil which means leave it as is."
943 (const :tag
"Leave as is" nil
)
944 (integer :tag
"Column number"
945 :menu-tag
"Indent to this col (0 means first col)" ))
946 :group
'sh-indentation
)
949 (defcustom sh-basic-offset
4
950 "*The default indentation increment.
951 This value is used for the + and - symbols in an indentation variable."
953 :group
'sh-indentation
)
955 (defcustom sh-indent-comment nil
956 "*How a comment line is to be indented.
957 nil means leave it as it is;
958 t means indent it as a normal line, aligning it to previous non-blank
960 a number means align to that column, e.g. 0 means fist column."
962 (const :tag
"Leave as is." nil
)
963 (const :tag
"Indent as a normal line." t
)
964 (integer :menu-tag
"Indent to this col (0 means first col)."
965 :tag
"Indent to column number.") )
966 :group
'sh-indentation
)
970 "Enable lots of debug messages - if function `sh-debug' is enabled.")
973 ;; Uncomment this defun and comment the defmacro for debugging.
974 ;; (defun sh-debug (&rest args)
975 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
977 ;; (apply 'message args)))
978 (defmacro sh-debug
(&rest args
))
980 (defconst sh-symbol-list
981 '((const :tag
"+ " :value
+
982 :menu-tag
"+ Indent right by sh-basic-offset")
983 (const :tag
"- " :value -
984 :menu-tag
"- Indent left by sh-basic-offset")
985 (const :tag
"++" :value
++
986 :menu-tag
"++ Indent right twice sh-basic-offset")
987 (const :tag
"--" :value --
988 :menu-tag
"-- Indent left twice sh-basic-offset")
989 (const :tag
"* " :value
*
990 :menu-tag
"* Indent right half sh-basic-offset")
991 (const :tag
"/ " :value
/
992 :menu-tag
"/ Indent left half sh-basic-offset")))
994 (defcustom sh-indent-for-else
0
995 "*How much to indent an else relative to an if. Usually 0."
997 (integer :menu-tag
"A number (positive=>indent right)"
999 (const :tag
"--") ;; separator!
1002 :group
'sh-indentation
)
1004 (defconst sh-number-or-symbol-list
1005 (append '((integer :menu-tag
"A number (positive=>indent right)"
1007 (const :tag
"--")) ; separator
1010 (defcustom sh-indent-for-fi
0
1011 "*How much to indent a fi relative to an if. Usually 0."
1012 :type
`(choice ,@ sh-number-or-symbol-list
)
1013 :group
'sh-indentation
)
1015 (defcustom sh-indent-for-done
'0
1016 "*How much to indent a done relative to its matching stmt. Usually 0."
1017 :type
`(choice ,@ sh-number-or-symbol-list
)
1018 :group
'sh-indentation
)
1020 (defcustom sh-indent-after-else
'+
1021 "*How much to indent a statement after an else statement."
1022 :type
`(choice ,@ sh-number-or-symbol-list
)
1023 :group
'sh-indentation
)
1025 (defcustom sh-indent-after-if
'+
1026 "*How much to indent a statement after an if statement.
1027 This includes lines after else and elif statements, too, but
1028 does not affect then else elif or fi statements themselves."
1029 :type
`(choice ,@ sh-number-or-symbol-list
)
1030 :group
'sh-indentation
)
1032 (defcustom sh-indent-for-then
'+
1033 "*How much to indent an then relative to an if."
1034 :type
`(choice ,@ sh-number-or-symbol-list
)
1035 :group
'sh-indentation
)
1037 (defcustom sh-indent-for-do
'*
1038 "*How much to indent a do statement.
1039 This is relative to the statement before the do, i.e. the
1040 while until or for statement."
1041 :type
`(choice ,@ sh-number-or-symbol-list
)
1042 :group
'sh-indentation
)
1044 (defcustom sh-indent-after-do
'*
1045 "*How much to indent a line after a do statement.
1046 This is used when the do is the first word of the line.
1047 This is relative to the statement before the do, e.g. a
1048 while for repeat or select statement."
1049 :type
`(choice ,@ sh-number-or-symbol-list
)
1050 :group
'sh-indentation
)
1052 (defcustom sh-indent-after-loop-construct
'+
1053 "*How much to indent a statement after a loop construct.
1055 This variable is used when the keyword \"do\" is on the same line as the
1056 loop statement (e.g. \"until\", \"while\" or \"for\").
1057 If the do is on a line by itself, then `sh-indent-after-do' is used instead."
1058 :type
`(choice ,@ sh-number-or-symbol-list
)
1059 :group
'sh-indentation
)
1062 (defcustom sh-indent-after-done
0
1063 "*How much to indent a statement after a \"done\" keyword.
1064 Normally this is 0, which aligns the \"done\" to the matching
1065 looping construct line.
1066 Setting it non-zero allows you to have the \"do\" statement on a line
1067 by itself and align the done under to do."
1068 :type
`(choice ,@ sh-number-or-symbol-list
)
1069 :group
'sh-indentation
)
1071 (defcustom sh-indent-for-case-label
'+
1072 "*How much to indent a case label statement.
1073 This is relative to the line containing the case statement."
1074 :type
`(choice ,@ sh-number-or-symbol-list
)
1075 :group
'sh-indentation
)
1077 (defcustom sh-indent-for-case-alt
'++
1078 "*How much to indent statements after the case label.
1079 This is relative to the line containing the case statement."
1080 :type
`(choice ,@ sh-number-or-symbol-list
)
1081 :group
'sh-indentation
)
1084 (defcustom sh-indent-for-continuation
'+
1085 "*How much to indent for a continuation statement."
1086 :type
`(choice ,@ sh-number-or-symbol-list
)
1087 :group
'sh-indentation
)
1089 (defcustom sh-indent-after-open
'+
1090 "*How much to indent after a line with an opening parenthesis or brace.
1091 For an open paren after a function `sh-indent-after-function' is used."
1092 :type
`(choice ,@ sh-number-or-symbol-list
)
1093 :group
'sh-indentation
)
1095 (defcustom sh-indent-after-function
'+
1096 "*How much to indent after a function line."
1097 :type
`(choice ,@ sh-number-or-symbol-list
)
1098 :group
'sh-indentation
)
1100 ;; These 2 are for the rc shell:
1102 (defcustom sh-indent-after-switch
'+
1103 "*How much to indent a case statement relative to the switch statement.
1104 This is for the rc shell."
1105 :type
`(choice ,@ sh-number-or-symbol-list
)
1106 :group
'sh-indentation
)
1108 (defcustom sh-indent-after-case
'+
1109 "*How much to indent a statement relative to the case statement.
1110 This is for the rc shell."
1111 :type
`(choice ,@ sh-number-or-symbol-list
)
1112 :group
'sh-indentation
)
1114 ;; Internal use - not designed to be changed by the user:
1116 (defun sh-mkword-regexpr (word)
1117 "Make a regexp which matches WORD as a word.
1118 This specifically excludes an occurrence of WORD followed by
1119 punctuation characters like '-'."
1120 (concat word
"\\([^-a-z0-9_]\\|$\\)"))
1122 (defconst sh-re-done
(sh-mkword-regexpr "done"))
1125 (defconst sh-kws-for-done
1126 '((sh .
( "while" "until" "for" ) )
1127 (bash .
( "while" "until" "for" "select" ) )
1128 (ksh88 .
( "while" "until" "for" "select" ) )
1129 (zsh .
( "while" "until" "for" "repeat" "select" ) ) )
1130 "Which keywords can match the word `done' in this shell.")
1133 (defconst sh-indent-supported
1137 "Shell types that shell indenting can do something with.")
1139 (defvar sh-indent-supported-here nil
1140 "Non-nil if we support indentation for the current buffer's shell type.")
1142 (defconst sh-electric-rparen-needed
1144 "Non-nil if the shell type needs an electric handling of case alternatives.")
1146 (defconst sh-var-list
1148 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1149 sh-indent-after-do sh-indent-after-done
1150 sh-indent-after-else
1152 sh-indent-after-loop-construct
1153 sh-indent-after-open
1155 sh-indent-for-case-alt
1156 sh-indent-for-case-label
1157 sh-indent-for-continuation
1164 "A list of variables used by script mode to control indentation.
1165 This list is used when switching between buffer-local and global
1166 values of variables, and for the commands using indentation styles.")
1168 (defvar sh-make-vars-local t
1169 "*Controls whether indentation variables are local to the buffer.
1170 If non-nil, indentation variables are made local initially.
1171 If nil, you can later make the variables local by invoking
1172 command `sh-make-vars-local'.
1173 The default is t because I assume that in one Emacs session one is
1174 frequently editing existing scripts with different styles.")
1177 ;; mode-command and utility functions
1180 (put 'sh-mode
'mode-class
'special
)
1183 (define-derived-mode sh-mode nil
"Shell-script"
1184 "Major mode for editing shell scripts.
1185 This mode works for many shells, since they all have roughly the same syntax,
1186 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1187 Unless the file's magic number indicates the shell, your usual shell is
1188 assumed. Since filenames rarely give a clue, they are not further analyzed.
1190 This mode adapts to the variations between shells (see `sh-set-shell') by
1191 means of an inheritance based feature lookup (see `sh-feature'). This
1192 mechanism applies to all variables (including skeletons) that pertain to
1193 shell-specific features.
1195 The default style of this mode is that of Rosenblatt's Korn shell book.
1196 The syntax of the statements varies with the shell being used. The
1197 following commands are available, based on the current shell's syntax:
1199 \\[sh-case] case statement
1201 \\[sh-function] function definition
1202 \\[sh-if] if statement
1203 \\[sh-indexed-loop] indexed loop from 1 to n
1204 \\[sh-while-getopts] while getopts loop
1205 \\[sh-repeat] repeat loop
1206 \\[sh-select] select loop
1207 \\[sh-until] until loop
1208 \\[sh-while] while loop
1210 For sh and rc shells indentation commands are:
1211 \\[sh-show-indent] Show the variable controlling this line's indentation.
1212 \\[sh-set-indent] Set then variable controlling this line's indentation.
1213 \\[sh-learn-line-indent] Change the indentation variable so this line
1214 would indent to the way it currently is.
1215 \\[sh-learn-buffer-indent] Set the indentation variables so the
1216 buffer indents as it currently is indented.
1219 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1220 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
1221 \\[sh-end-of-command] Go to end of successive commands.
1222 \\[sh-beginning-of-command] Go to beginning of successive commands.
1223 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1224 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1226 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
1228 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1230 If you generally program a shell different from your login shell you can
1231 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1232 indicate what shell it is use `sh-alias-alist' to translate.
1234 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1235 with your script for an edit-interpret-debug cycle."
1236 (make-local-variable 'skeleton-end-hook
)
1237 (make-local-variable 'paragraph-start
)
1238 (make-local-variable 'paragraph-separate
)
1239 (make-local-variable 'comment-start
)
1240 (make-local-variable 'comment-start-skip
)
1241 (make-local-variable 'require-final-newline
)
1242 (make-local-variable 'sh-header-marker
)
1243 (make-local-variable 'sh-shell-file
)
1244 (make-local-variable 'sh-shell
)
1245 (make-local-variable 'skeleton-pair-alist
)
1246 (make-local-variable 'skeleton-pair-filter
)
1247 (make-local-variable 'comint-dynamic-complete-functions
)
1248 (make-local-variable 'comint-prompt-regexp
)
1249 (make-local-variable 'font-lock-defaults
)
1250 (make-local-variable 'skeleton-filter
)
1251 (make-local-variable 'skeleton-newline-indent-rigidly
)
1252 (make-local-variable 'sh-shell-variables
)
1253 (make-local-variable 'sh-shell-variables-initialized
)
1254 (make-local-variable 'imenu-generic-expression
)
1255 (make-local-variable 'sh-indent-supported-here
)
1256 (make-local-variable 'font-lock-unfontify-region-function
)
1257 (setq skeleton-end-hook
(lambda ()
1258 (or (eolp) (newline) (indent-relative)))
1259 paragraph-start
(concat page-delimiter
"\\|$")
1260 paragraph-separate paragraph-start
1262 comint-dynamic-complete-functions sh-dynamic-complete-functions
1263 ;; we can't look if previous line ended with `\'
1264 comint-prompt-regexp
"^[ \t]*"
1266 `((sh-font-lock-keywords
1267 sh-font-lock-keywords-1 sh-font-lock-keywords-2
)
1269 ((?
/ .
"w") (?~ .
"w") (?. .
"w") (?- .
"w") (?_ .
"w")) nil
1270 (font-lock-syntactic-keywords
1271 ;; Copy so we can use destructive update in `sh-font-lock-heredoc'.
1272 .
,(copy-sequence sh-font-lock-syntactic-keywords
))
1273 (font-lock-syntactic-face-function
1274 . sh-font-lock-syntactic-face-function
))
1275 skeleton-pair-alist
'((?
` _ ?
`))
1276 skeleton-pair-filter
'sh-quoted-p
1277 skeleton-further-elements
'((< '(- (min sh-indentation
1278 (current-column)))))
1279 skeleton-filter
'sh-feature
1280 skeleton-newline-indent-rigidly t
1281 sh-indent-supported-here nil
)
1282 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
1283 ;; Parse or insert magic number for exec, and set all variables depending
1284 ;; on the shell thus determined.
1287 (goto-char (point-min))
1288 (cond ((looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1290 ((and buffer-file-name
1291 (string-match "\\.m?spec$" buffer-file-name
))
1293 (sh-set-shell (or interpreter sh-shell-file
) nil nil
)))
1296 (defalias 'shell-script-mode
'sh-mode
)
1299 (defun sh-font-lock-keywords (&optional keywords
)
1300 "Function to get simple fontification based on `sh-font-lock-keywords'.
1301 This adds rules for comments and assignments."
1302 (sh-feature sh-font-lock-keywords
1303 (when (stringp (sh-feature sh-assignment-regexp
))
1305 `((,(sh-feature sh-assignment-regexp
)
1306 1 font-lock-variable-name-face
)
1310 (defun sh-font-lock-keywords-1 (&optional builtins
)
1311 "Function to get better fontification including keywords."
1312 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\(\\("
1313 (mapconcat 'identity
1314 (sh-feature sh-leading-keywords
)
1317 (mapconcat 'identity
1318 (append (sh-feature sh-leading-keywords
)
1319 (sh-feature sh-other-keywords
))
1322 (sh-font-lock-keywords
1324 `((,(concat keywords
"[ \t]+\\)?\\("
1325 (mapconcat 'identity
(sh-feature sh-builtins
) "\\|")
1327 (2 font-lock-keyword-face nil t
)
1328 (6 font-lock-builtin-face
))
1329 ,@(sh-feature sh-font-lock-keywords-2
)))
1330 (,(concat keywords
"\\)\\>")
1331 2 font-lock-keyword-face
)
1332 ,@(sh-feature sh-font-lock-keywords-1
)))))
1334 (defun sh-font-lock-keywords-2 ()
1335 "Function to get better fontification including keywords and builtins."
1336 (sh-font-lock-keywords-1 t
))
1339 (defvar sh-regexp-for-done nil
1340 "A buffer-local regexp to match opening keyword for done.")
1342 (defvar sh-kw-alist nil
1343 "A buffer-local, since it is shell-type dependent, list of keywords.")
1345 ;; ( key-word first-on-this on-prev-line )
1346 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1347 ;; having 3 elements:
1349 ;; a rule to check when the keyword appears on "this" line
1350 ;; a rule to check when the keyword appears on "the previous" line
1351 ;; The keyword is usually a string and is the first word on a line.
1352 ;; If this keyword appears on the line whose indentation is to be
1353 ;; calculated, the rule in element 2 is called. If this returns
1354 ;; non-zero, the resulting point (which may be changed by the rule)
1355 ;; is used as the default indentation.
1356 ;; If it returned false or the keyword was not found in the table,
1357 ;; then the keyword from the previous line is looked up and the rule
1358 ;; in element 3 is called. In this case, however,
1359 ;; `sh-get-indent-info' does not stop but may keep going and test
1360 ;; other keywords against rules in element 3. This is because the
1361 ;; preceding line could have, for example, an opening "if" and an
1362 ;; opening "while" keyword and we need to add the indentation offsets
1367 ("if" nil sh-handle-prev-if
)
1368 ("elif" sh-handle-this-else sh-handle-prev-else
)
1369 ("else" sh-handle-this-else sh-handle-prev-else
)
1370 ("fi" sh-handle-this-fi sh-handle-prev-fi
)
1371 ("then" sh-handle-this-then sh-handle-prev-then
)
1372 ("(" nil sh-handle-prev-open
)
1373 ("{" nil sh-handle-prev-open
)
1374 ("[" nil sh-handle-prev-open
)
1375 ("}" sh-handle-this-close nil
)
1376 (")" sh-handle-this-close nil
)
1377 ("]" sh-handle-this-close nil
)
1378 ("case" nil sh-handle-prev-case
)
1379 ("esac" sh-handle-this-esac sh-handle-prev-esac
)
1380 (case-label nil sh-handle-after-case-label
) ;; ???
1381 (";;" nil sh-handle-prev-case-alt-end
) ;; ???
1382 ("done" sh-handle-this-done sh-handle-prev-done
)
1383 ("do" sh-handle-this-do sh-handle-prev-do
))
1385 ;; Note: we don't need specific stuff for bash and zsh shells;
1386 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1387 ;; these shells use.
1389 ("{" nil sh-handle-prev-open
)
1390 ("}" sh-handle-this-close nil
)
1391 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case
))))
1394 (defun sh-set-shell (shell &optional no-query-flag insert-flag
)
1395 "Set this buffer's shell to SHELL (a string).
1396 Makes this script executable via `executable-set-magic', and sets up the
1397 proper starting #!-line, if INSERT-FLAG is non-nil.
1398 Calls the value of `sh-set-shell-hook' if set."
1399 (interactive (list (completing-read "Name or path of shell: "
1400 interpreter-mode-alist
1401 (lambda (x) (eq (cdr x
) 'sh-mode
)))
1402 (eq executable-query
'function
)
1404 (if (string-match "\\.exe\\'" shell
)
1405 (setq shell
(substring shell
0 (match-beginning 0))))
1406 (setq sh-shell
(intern (file-name-nondirectory shell
))
1407 sh-shell
(or (cdr (assq sh-shell sh-alias-alist
))
1411 (executable-set-magic shell
(sh-feature sh-shell-arg
)
1412 no-query-flag insert-flag
)))
1413 (setq require-final-newline
(sh-feature sh-require-final-newline
)
1414 ;;; local-abbrev-table (sh-feature sh-abbrevs)
1415 comment-start-skip
"#+[\t ]*"
1416 mode-line-process
(format "[%s]" sh-shell
)
1417 sh-shell-variables nil
1418 sh-shell-variables-initialized nil
1419 imenu-generic-expression
(sh-feature sh-imenu-generic-expression
)
1420 imenu-case-fold-search nil
)
1421 (dolist (var (sh-feature sh-variables
))
1422 (sh-remember-variable var
))
1423 (make-local-variable 'indent-line-function
)
1424 (if (setq sh-indent-supported-here
(sh-feature sh-indent-supported
))
1426 (message "Setting up indent for shell type %s" sh-shell
)
1427 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
1428 (set (make-local-variable 'sh-kw-alist
) (sh-feature sh-kw
))
1429 (let ((regexp (sh-feature sh-kws-for-done
)))
1431 (set (make-local-variable 'sh-regexp-for-done
)
1432 (sh-mkword-regexpr (regexp-opt regexp t
)))))
1433 (message "setting up indent stuff")
1434 ;; sh-mode has already made indent-line-function local
1435 ;; but do it in case this is called before that.
1436 (setq indent-line-function
'sh-indent-line
)
1437 (if sh-make-vars-local
1438 (sh-make-vars-local))
1439 (message "Indentation setup for shell type %s" sh-shell
))
1440 (message "No indentation for this shell type.")
1441 (setq indent-line-function
'sh-basic-indent-line
))
1442 (run-hooks 'sh-set-shell-hook
))
1446 (defun sh-feature (list &optional function
)
1447 "Index ALIST by the current shell.
1448 If ALIST isn't a list where every element is a cons, it is returned as is.
1449 Else indexing follows an inheritance logic which works in two ways:
1451 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1452 the alist contains no value for the current shell.
1453 The ultimate default is always `sh'.
1455 - If the value thus looked up is a list starting with `eval' its `cdr' is
1456 first evaluated. If that is also a list and the first argument is a
1457 symbol in ALIST it is not evaluated, but rather recursively looked up in
1458 ALIST to allow the function called to define the value for one shell to be
1459 derived from another shell. While calling the function, is the car of the
1460 alist element is the current shell.
1461 The value thus determined is physically replaced into the alist.
1463 Optional FUNCTION is applied to the determined value and the result is cached
1465 (or (if (consp list
)
1467 (while (and l
(consp (car l
)))
1471 (cdr (assoc (setq function
(cons sh-shell function
)) list
)))
1472 (let ((sh-shell sh-shell
)
1474 (while (and sh-shell
1475 (not (setq elt
(assq sh-shell list
))))
1476 (setq sh-shell
(cdr (assq sh-shell sh-ancestor-alist
))))
1477 ;; If the shell is not known, treat it as sh.
1479 (setq elt
(assq 'sh list
)))
1480 (if (and (consp (setq val
(cdr elt
)))
1481 (eq (car val
) 'eval
))
1484 (eval (if (consp (setq val
(cdr val
)))
1485 (let ((sh-shell (car (cdr val
)))
1487 (if (assq sh-shell list
)
1490 (sh-feature list
))))
1495 (list (cons function
1496 (setq sh-shell
(car function
)
1497 val
(funcall (cdr function
) val
))))))
1502 ;;; I commented this out because nobody calls it -- rms.
1503 ;;;(defun sh-abbrevs (ancestor &rest list)
1504 ;;; "Iff it isn't, define the current shell as abbrev table and fill that.
1505 ;;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1506 ;;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1507 ;;;according to the remaining arguments NAMEi EXPANSIONi ...
1508 ;;;EXPANSION may be either a string or a skeleton command."
1509 ;;; (or (if (boundp sh-shell)
1510 ;;; (symbol-value sh-shell))
1512 ;;; (if (listp ancestor)
1513 ;;; (nconc list ancestor))
1514 ;;; (define-abbrev-table sh-shell ())
1515 ;;; (if (vectorp ancestor)
1516 ;;; (mapatoms (lambda (atom)
1518 ;;; (define-abbrev (symbol-value sh-shell)
1519 ;;; (symbol-name atom)
1520 ;;; (symbol-value atom)
1521 ;;; (symbol-function atom))))
1524 ;;; (define-abbrev (symbol-value sh-shell)
1526 ;;; (if (stringp (car (cdr list)))
1527 ;;; (car (cdr list))
1529 ;;; (if (symbolp (car (cdr list)))
1530 ;;; (car (cdr list))))
1531 ;;; (setq list (cdr (cdr list)))))
1532 ;;; (symbol-value sh-shell)))
1535 (defun sh-append (ancestor &rest list
)
1536 "Return list composed of first argument (a list) physically appended to rest."
1537 (nconc list ancestor
))
1540 (defun sh-modify (skeleton &rest list
)
1541 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1542 (setq skeleton
(copy-sequence skeleton
))
1544 (setcar (or (nthcdr (car list
) skeleton
)
1545 (error "Index %d out of bounds" (car list
)))
1547 (setq list
(nthcdr 2 list
)))
1551 (defun sh-basic-indent-line ()
1552 "Indent a line for Sh mode (shell script mode).
1553 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1554 Lines containing only comments are considered empty."
1556 (let ((previous (save-excursion
1557 (while (and (progn (beginning-of-line)
1561 (back-to-indentation)
1563 (eq (following-char) ?
#)))))
1567 (indent-to (if (eq this-command
'newline-and-indent
)
1569 (if (< (current-column)
1570 (setq current
(progn (back-to-indentation)
1572 (if (eolp) previous
0)
1573 (delete-region (point)
1574 (progn (beginning-of-line) (point)))
1576 (max previous
(* (1+ (/ current sh-indentation
))
1578 (* (1+ (/ current sh-indentation
)) sh-indentation
))))))
1579 (if (< (current-column) (current-indentation))
1580 (skip-chars-forward " \t"))))
1583 (defun sh-execute-region (start end
&optional flag
)
1584 "Pass optional header and region to a subshell for noninteractive execution.
1585 The working directory is that of the buffer, and only environment variables
1586 are already set which is why you can mark a header within the script.
1588 With a positive prefix ARG, instead of sending region, define header from
1589 beginning of buffer to point. With a negative prefix ARG, instead of sending
1590 region, clear header."
1591 (interactive "r\nP")
1593 (setq sh-header-marker
(if (> (prefix-numeric-value flag
) 0)
1595 (if sh-header-marker
1597 (let (buffer-undo-list)
1598 (goto-char sh-header-marker
)
1599 (append-to-buffer (current-buffer) start end
)
1600 (shell-command-on-region (point-min)
1601 (setq end
(+ sh-header-marker
1604 (delete-region sh-header-marker end
)))
1605 (shell-command-on-region start end
(concat sh-shell-file
" -")))))
1608 (defun sh-remember-variable (var)
1609 "Make VARIABLE available for future completing reads in this buffer."
1610 (or (< (length var
) sh-remember-variable-min
)
1612 (assoc var sh-shell-variables
)
1613 (push (cons var var
) sh-shell-variables
))
1618 (defun sh-quoted-p ()
1619 "Is point preceded by an odd number of backslashes?"
1620 (eq -
1 (%
(save-excursion (skip-chars-backward "\\\\")) 2)))
1622 ;; Indentation stuff.
1623 (defun sh-must-be-shell-mode ()
1624 "Signal an error if not in Shell-script mode."
1625 (unless (eq major-mode
'sh-mode
)
1626 (error "This buffer is not in Shell-script mode")))
1628 (defun sh-must-support-indent ()
1629 "*Signal an error if the shell type for this buffer is not supported.
1630 Also, the buffer must be in Shell-script mode."
1631 (sh-must-be-shell-mode)
1632 (unless sh-indent-supported-here
1633 (error "This buffer's shell type is not supported for this command")))
1635 (defun sh-make-vars-local ()
1636 "Make the indentation variables local to this buffer.
1637 Normally they already are local. This command is provided in case
1638 variable `sh-make-vars-local' has been set to nil.
1640 To revert all these variables to the global values, use
1641 command `sh-reset-indent-vars-to-global-values'."
1643 (sh-must-be-shell-mode)
1644 (mapcar 'make-local-variable sh-var-list
)
1645 (message "Indentation variable are now local."))
1647 (defun sh-reset-indent-vars-to-global-values ()
1648 "Reset local indentation variables to the global values.
1649 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1651 (sh-must-be-shell-mode)
1652 (mapcar 'kill-local-variable sh-var-list
)
1653 (if sh-make-vars-local
1654 (mapcar 'make-local-variable sh-var-list
)))
1657 ;; Theoretically these are only needed in shell and derived modes.
1658 ;; However, the routines which use them are only called in those modes.
1659 (defconst sh-special-keywords
"then\\|do")
1661 (defun sh-help-string-for-variable (var)
1662 "Construct a string for `sh-read-variable' when changing variable VAR ."
1663 (let ((msg (documentation-property var
'variable-documentation
))
1665 (unless (memq var
'(sh-first-lines-indent sh-indent-comment
))
1668 You can enter a number (positive to increase indentation,
1669 negative to decrease indentation, zero for no change to indentation).
1671 Or, you can enter one of the following symbols which are relative to
1672 the value of variable `sh-basic-offset'
1673 which in this buffer is currently %s.
1677 (mapconcat (lambda (x)
1678 (nth (1- (length x
)) x
))
1679 sh-symbol-list
"\n\t"))))
1681 ;; The following shows the global not the local value!
1682 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1685 (defun sh-read-variable (var)
1686 "Read a new value for indentation variable VAR."
1687 (interactive "*variable? ") ;; to test
1688 (let ((minibuffer-help-form `(sh-help-string-for-variable
1691 (setq val
(read-from-minibuffer
1692 (format "New value for %s (press %s for help): "
1693 var
(single-key-description help-char
))
1694 (format "%s" (symbol-value var
))
1700 (defun sh-in-comment-or-string (start)
1701 "Return non-nil if START is in a comment or string."
1705 (setq state
(parse-partial-sexp (point) start nil nil nil t
))
1706 (or (nth 3 state
)(nth 4 state
)))))
1708 (defun sh-goto-matching-if ()
1709 "Go to the matching if for a fi.
1710 This handles nested if..fi pairs."
1711 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1713 (goto-char found
))))
1716 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1717 ;; line whose indentation is being handled contain XXX;
1718 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
1720 (defun sh-handle-prev-if ()
1721 (list '(+ sh-indent-after-if
)))
1723 (defun sh-handle-this-else ()
1724 (if (sh-goto-matching-if)
1725 ;; (list "aligned to if")
1726 (list "aligned to if" '(+ sh-indent-for-else
))
1730 (defun sh-handle-prev-else ()
1731 (if (sh-goto-matching-if)
1732 (list '(+ sh-indent-after-if
))
1735 (defun sh-handle-this-fi ()
1736 (if (sh-goto-matching-if)
1737 (list "aligned to if" '(+ sh-indent-for-fi
))
1741 (defun sh-handle-prev-fi ()
1742 ;; Why do we have this rule? Because we must go back to the if
1743 ;; to get its indent. We may continue back from there.
1744 ;; We return nil because we don't have anything to add to result,
1745 ;; the side affect of setting align-point is all that matters.
1746 ;; we could return a comment (a string) but I can't think of a good one...
1747 (sh-goto-matching-if)
1750 (defun sh-handle-this-then ()
1751 (let ((p (sh-goto-matching-if)))
1753 (list '(+ sh-indent-for-then
))
1756 (defun sh-handle-prev-then ()
1757 (let ((p (sh-goto-matching-if)))
1759 (list '(+ sh-indent-after-if
))
1762 (defun sh-handle-prev-open ()
1764 (let ((x (sh-prev-stmt)))
1769 (looking-at "function\\b")
1770 (looking-at "\\s-*\\S-+\\s-*()")
1772 (list '(+ sh-indent-after-function
))
1773 (list '(+ sh-indent-after-open
)))
1776 (defun sh-handle-this-close ()
1777 (forward-char 1) ;; move over ")"
1778 (if (sh-safe-forward-sexp -
1)
1779 (list "aligned to opening paren")))
1781 (defun sh-goto-matching-case ()
1782 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
1783 (if found
(goto-char found
))))
1785 (defun sh-handle-prev-case ()
1786 ;; This is typically called when point is on same line as a case
1787 ;; we shouldn't -- and can't find prev-case
1788 (if (looking-at ".*\\<case\\>")
1789 (list '(+ sh-indent-for-case-label
))
1790 (error "We don't seem to be on a line with a case"))) ;; debug
1792 (defun sh-handle-this-esac ()
1793 (if (sh-goto-matching-case)
1794 (list "aligned to matching case")))
1796 (defun sh-handle-prev-esac ()
1797 (if (sh-goto-matching-case)
1798 (list "matching case")))
1800 (defun sh-handle-after-case-label ()
1801 (if (sh-goto-matching-case)
1802 (list '(+ sh-indent-for-case-alt
))))
1804 (defun sh-handle-prev-case-alt-end ()
1805 (if (sh-goto-matching-case)
1806 (list '(+ sh-indent-for-case-label
))))
1808 (defun sh-safe-forward-sexp (&optional arg
)
1809 "Try and do a `forward-sexp', but do not error.
1810 Return new point if successful, nil if an error occurred."
1813 (forward-sexp (or arg
1))
1814 (point)) ;; return point if successful
1816 (sh-debug "oops!(1) %d" (point))
1817 nil
))) ;; return nil if fail
1819 (defun sh-goto-match-for-done ()
1820 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done
1)))
1822 (goto-char found
))))
1824 (defun sh-handle-this-done ()
1825 (if (sh-goto-match-for-done)
1826 (list "aligned to do stmt" '(+ sh-indent-for-done
))))
1828 (defun sh-handle-prev-done ()
1829 (if (sh-goto-match-for-done)
1830 (list "previous done")))
1832 (defun sh-handle-this-do ()
1833 (if (sh-goto-match-for-done)
1834 (list '(+ sh-indent-for-do
))))
1836 (defun sh-handle-prev-do ()
1844 (sh-goto-match-for-done))
1845 (sh-debug "match for done found on THIS line")
1846 (list '(+ sh-indent-after-loop-construct
)))
1847 ((sh-goto-match-for-done)
1848 (sh-debug "match for done found on PREV line")
1849 (list '(+ sh-indent-after-do
)))
1851 (message "match for done NOT found")
1855 (defun sh-find-prev-switch ()
1856 "Find the line for the switch keyword matching this line's case keyword."
1857 (re-search-backward "\\<switch\\>" nil t
))
1859 (defun sh-handle-this-rc-case ()
1860 (if (sh-find-prev-switch)
1861 (list '(+ sh-indent-after-switch
))
1862 ;; (list '(+ sh-indent-for-case-label))
1865 (defun sh-handle-prev-rc-case ()
1866 (list '(+ sh-indent-after-case
)))
1868 (defun sh-check-rule (n thing
)
1869 (let ((rule (nth n
(assoc thing sh-kw-alist
)))
1873 (setq val
(funcall rule
))
1874 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
1875 n thing
(point) rule val
)))
1879 (defun sh-get-indent-info ()
1880 "Return indent-info for this line.
1881 This is a list. nil means the line is to be left as is.
1882 Otherwise it contains one or more of the following sublists:
1883 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
1884 relative to. If present, this is always the first of the
1885 sublists. The indentation of the line in question is
1886 derived from the indentation of this point, possibly
1887 modified by subsequent sublists.
1889 \(- VAR\) Get the value of variable VAR and add to or subtract from
1890 the indentation calculated so far.
1891 \(= VAR\) Get the value of variable VAR and *replace* the
1892 indentation with its value. This only occurs for
1893 special variables such as `sh-indent-comment'.
1894 STRING This is ignored for the purposes of calculating
1895 indentation, it is printed in certain cases to help show
1896 what the indentation is based on."
1897 ;; See comments before `sh-kw'.
1906 (depth-prev-bol nil
)
1916 ;; Note: setting result to t means we are done and will return nil.
1917 ;;(This function never returns just t.)
1919 ((and (boundp 'font-lock-string-face
)
1920 (equal (get-text-property (point) 'face
) font-lock-string-face
))
1922 (setq have-result t
))
1923 ((looking-at "\\s-*#") ; was (equal this-kw "#")
1925 (setq result t
) ;; return nil if 1st line!
1926 (setq result
(list '(= sh-indent-comment
)))
1927 ;; we still need to get previous line in case
1928 ;; sh-indent-comment is t (indent as normal)
1929 (setq align-point
(sh-prev-line nil
))
1930 (setq have-result nil
)
1935 ;; Continuation lines are handled specially
1936 (if (sh-this-is-a-continuation)
1938 ;; We assume the line being continued is already
1939 ;; properly indented...
1940 ;; (setq prev-line-end (sh-prev-line))
1941 (setq align-point
(sh-prev-line nil
))
1942 (setq result
(list '(+ sh-indent-for-continuation
)))
1943 (setq have-result t
))
1945 (skip-chars-forward " \t")
1946 (setq this-kw
(sh-get-kw)))
1948 ;; Handle "this" keyword: first word on the line we're
1949 ;; calculating indentation info for.
1951 (if (setq val
(sh-check-rule 1 this-kw
))
1953 (setq align-point
(point))
1955 "this - setting align-point to %d" align-point
)
1956 (setq result
(append result val
))
1957 (setq have-result t
)
1958 ;; set prev-line to continue processing remainder
1959 ;; of this line as a previous line
1960 (setq prev-line-end
(point))
1964 (setq prev-line-end
(sh-prev-line 'end
)))
1968 ;; We start off at beginning of this line.
1969 ;; Scan previous statements while this is <=
1970 ;; start of previous line.
1971 (setq start
(point)) ;; for debug only
1972 (goto-char prev-line-end
)
1974 (while (and x
(setq x
(sh-prev-thing)))
1975 (sh-debug "at %d x is: %s result is: %s" (point) x result
)
1978 (equal (get-text-property (1- (point)) 'syntax-table
)
1980 (sh-debug "Case label) here")
1981 (setq x
'case-label
)
1982 (if (setq val
(sh-check-rule 2 x
))
1984 (setq result
(append result val
))
1985 (setq align-point
(point))))
1987 (skip-chars-forward "[a-z0-9]*?")
1989 ((string-match "[])}]" x
)
1990 (setq x
(sh-safe-forward-sexp -
1))
1993 (setq align-point
(point))
1994 (setq result
(append result
1995 (list "aligned to opening paren")))
1997 ((string-match "[[({]" x
)
1998 (sh-debug "Checking special thing: %s" x
)
1999 (if (setq val
(sh-check-rule 2 x
))
2000 (setq result
(append result val
)))
2002 (setq align-point
(point)))
2003 ((string-match "[\"'`]" x
)
2004 (sh-debug "Skipping back for %s" x
)
2006 (setq x
(sh-safe-forward-sexp -
1)))
2008 (sh-debug "Checking string %s at %s" x
(point))
2009 (if (setq val
(sh-check-rule 2 x
))
2010 ;; (or (eq t (car val))
2011 ;; (eq t (car (car val))))
2012 (setq result
(append result val
)))
2013 ;; not sure about this test Wed Jan 27 23:48:35 1999
2014 (setq align-point
(point))
2018 (error "Don't know what to do with %s" x
))
2021 (sh-debug "result is %s" result
)
2023 (sh-debug "No prev line!")
2024 (sh-debug "result: %s align-point: %s" result align-point
)
2028 ;; was: (setq result (append result (list (list t align-point))))
2029 (setq result
(append (list (list t align-point
)) result
))
2031 (sh-debug "result is now: %s" result
)
2035 (setq result
(list (list t prev-line-end
)))
2036 (setq result
(list (list '= 'sh-first-lines-indent
)))
2041 (sh-debug "result is: %s" result
)
2047 (defun sh-get-indent-var-for-line (&optional info
)
2048 "Return the variable controlling indentation for this line.
2049 If there is not [just] one such variable, return a string
2050 indicating the problem.
2051 If INFO is supplied it is used, else it is calculated."
2057 (setq info
(sh-get-indent-info)))
2059 (setq result
"this line to be left as is")
2060 (while (and info
(null result
))
2061 (setq elt
(car info
))
2067 (error "sh-get-indent-var-for-line invalid elt: %s" elt
))
2071 ((symbolp (setq sym
(nth 1 elt
)))
2072 ;; A bit of a kludge - when we see the sh-indent-comment
2073 ;; ignore other variables. Otherwise it is tricky to
2074 ;; "learn" the comment indentation.
2075 (if (eq var
'sh-indent-comment
)
2079 "this line is controlled by more than 1 variable.")
2082 (error "sh-get-indent-var-for-line invalid list elt: %s" elt
)))
2083 (setq info
(cdr info
))
2088 (setq result reason
))
2090 ;; e.g. just had (t POS)
2091 (setq result
"line has default indentation"))
2096 ;; Finding the previous line isn't trivial.
2097 ;; We must *always* go back one more and see if that is a continuation
2098 ;; line -- it is the PREVIOUS line which is continued, not the one
2100 ;; Also, we want to treat a whole "here document" as one big line,
2101 ;; because we may want to a align to the beginning of it.
2104 ;; - go back to previous non-empty line
2105 ;; - if this is in a here-document, go to the beginning of it
2106 ;; - while previous line is continued, go back one line
2107 (defun sh-prev-line (&optional end
)
2108 "Back to end of previous non-comment non-empty line.
2109 Go to beginning of logical line unless END is non-nil, in which case
2110 we go to the end of the previous line and do not check for continuations."
2111 (sh-must-be-shell-mode)
2114 (forward-comment (- (point-max)))
2115 (unless end
(beginning-of-line))
2116 (when (and (not (bobp))
2117 (boundp 'font-lock-string-face
)
2118 (equal (get-text-property (1- (point)) 'face
)
2119 font-lock-string-face
))
2120 (let ((p1 (previous-single-property-change (1- (point)) 'face
)))
2125 (beginning-of-line)))))
2127 ;; we must check previous lines to see if they are continuation lines
2128 ;; if so, we must return position of first of them
2129 (while (and (sh-this-is-a-continuation)
2130 (>= 0 (forward-line -
1))))
2132 (skip-chars-forward " \t"))
2136 (defun sh-prev-stmt ()
2137 "Return the address of the previous stmt or nil."
2138 ;; This is used when we are trying to find a matching keyword.
2139 ;; Searching backward for the keyword would certainly be quicker, but
2140 ;; it is hard to remove "false matches" -- such as if the keyword
2141 ;; appears in a string or quote. This way is slower, but (I think) safer.
2148 (skip-chars-backward " \t;|&({[")
2149 (while (and (not found
)
2152 ;; Do a backward-sexp if possible, else backup bit by bit...
2153 (if (sh-safe-forward-sexp -
1)
2155 (if (looking-at sh-special-keywords
)
2160 ;; backward-sexp failed
2161 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2164 (let ((back (sh-prev-line nil
)))
2167 (setq going nil
)))))
2169 (skip-chars-backward " \t")
2170 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2171 (eq (char-before) ?\
;)
2172 (looking-at "\\s-*[|&]"))
2173 (setq found
(point)))))
2178 (skip-chars-forward " \t|&({[")
2179 (setq found
(point))))
2180 (if (>= (point) start
)
2182 (debug "We didn't move!")
2185 (sh-debug "Did not find prev stmt.")))
2189 (defun sh-get-word ()
2190 "Get a shell word skipping whitespace from point."
2192 (skip-chars-forward "\t ")
2193 (let ((start (point)))
2195 (if (looking-at "[\"'`]")
2196 (sh-safe-forward-sexp)
2197 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2198 (> (skip-chars-forward "-_a-zA-Z\$0-9") 0)
2200 (buffer-substring start
(point))
2203 (defun sh-prev-thing ()
2204 "Return the previous thing this logical line."
2205 ;; This is called when `sh-get-indent-info' is working backwards on
2206 ;; the previous line(s) finding what keywords may be relevant for
2207 ;; indenting. It moves over sexps if possible, and will stop
2208 ;; on a ; and at the beginning of a line if it is not a continuation
2211 ;; Added a kludge for ";;"
2212 ;; Possible return values:
2214 ;; a string - possibly a keyword
2225 (if (sh-this-is-a-continuation)
2226 (setq min-point
(sh-prev-line nil
))
2229 (setq min-point
(point))))
2231 (skip-chars-backward " \t;")
2232 (unless (looking-at "\\s-*;;")
2233 (skip-chars-backward "^)}];\"'`({[")
2234 (setq c
(char-before))))
2235 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2236 (point) c start min-point
)
2237 (if (< (point) min-point
)
2238 (error "point %d < min-point %d" (point) min-point
))
2240 ((looking-at "\\s-*;;")
2241 ;; (message "Found ;; !")
2247 ;; skip forward over white space newline and \ at eol
2248 (skip-chars-forward " \t\n\\\\")
2249 (sh-debug "Now at %d start=%d" (point) start
)
2250 (if (>= (point) start
)
2252 (sh-debug "point: %d >= start: %d" (point) start
)
2257 ;; c -- return a string
2263 (defun sh-this-is-a-continuation ()
2264 "Return non-nil if current line is a continuation of previous line."
2266 (and (zerop (forward-line -
1))
2267 (looking-at ".*\\\\$")
2268 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2271 (defun sh-get-kw (&optional where and-move
)
2272 "Return first word of line from WHERE.
2273 If AND-MOVE is non-nil then move to end of word."
2274 (let ((start (point)))
2278 (buffer-substring (point)
2279 (progn (skip-chars-forward "^ \t\n;")(point)))
2281 (goto-char start
)))))
2283 (defun sh-find-prev-matching (open close
&optional depth
)
2284 "Find a matching token for a set of opening and closing keywords.
2285 This takes into account that there may be nested open..close pairings.
2286 OPEN and CLOSE are regexps denoting the tokens to be matched.
2287 Optional parameter DEPTH (usually 1) says how many to look for."
2288 (let ((parse-sexp-ignore-comments t
)
2290 (setq depth
(or depth
1))
2296 (setq prev
(sh-prev-stmt)))
2299 (if (looking-at "\\\\\n")
2302 (skip-chars-forward " \t")))
2305 (setq depth
(1- depth
))
2306 (sh-debug "found open at %d - depth = %d" (point) depth
))
2308 (setq depth
(1+ depth
))
2309 (sh-debug "found close - depth = %d" depth
))
2319 (defun sh-var-value (var &optional ignore-error
)
2320 "Return the value of variable VAR, interpreting symbols.
2321 It can also return t or nil.
2322 If an illegal value is found, throw an error unless Optional argument
2323 IGNORE-ERROR is non-nil."
2324 (let ((val (symbol-value var
)))
2335 (- sh-basic-offset
))
2337 (* 2 sh-basic-offset
))
2339 (* 2 (- sh-basic-offset
)))
2341 (/ sh-basic-offset
2))
2343 (/ (- sh-basic-offset
) 2))
2347 (message "Don't know how to handle %s's value of %s" var val
)
2349 (error "Don't know how to handle %s's value of %s" var val
))
2352 (defun sh-set-var-value (var value
&optional no-symbol
)
2353 "Set variable VAR to VALUE.
2354 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2355 can be represented by a symbol then do so."
2359 ((= value sh-basic-offset
)
2361 ((= value
(- sh-basic-offset
))
2363 ((eq value
(* 2 sh-basic-offset
))
2365 ((eq value
(* 2 (- sh-basic-offset
)))
2367 ((eq value
(/ sh-basic-offset
2))
2369 ((eq value
(/ (- sh-basic-offset
) 2))
2376 (defun sh-calculate-indent (&optional info
)
2377 "Return the indentation for the current line.
2378 If INFO is supplied it is used, else it is calculated from current line."
2383 (setq info
(sh-get-indent-info)))
2386 (sh-debug "info: %s ofs=%s" info ofs
)
2387 (setq elt
(car info
))
2389 ((stringp elt
)) ;; do nothing?
2391 (setq a
(car (car info
)))
2392 (setq b
(nth 1 (car info
)))
2397 (setq val
(current-indentation)))
2398 (setq base-value val
))
2400 (setq val
(sh-var-value b
))
2406 ;; set info to nil so we stop immediately
2407 (setq base-value nil ofs nil info nil
))
2408 ((eq val t
) (setq ofs
0)) ;; indent as normal line
2410 ;; The following assume the (t POS) come first!
2411 (setq ofs val base-value
0)
2412 (setq info nil
)))) ;; ? stop now
2413 ((eq a
'+) (setq ofs
(+ ofs val
)))
2414 ((eq a
'-
) (setq ofs
(- ofs val
)))
2416 (error "sh-calculate-indent invalid a a=%s b=%s" a b
))))
2418 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b
))))
2420 (error "sh-calculate-indent invalid elt %s" elt
)))
2421 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2422 a b val base-value ofs
)
2423 (setq info
(cdr info
)))
2425 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs
)
2428 ((or (null base-value
)(null ofs
))
2430 ((and (numberp base-value
)(numberp ofs
))
2431 (sh-debug "base (%d) + ofs (%d) = %d"
2432 base-value ofs
(+ base-value ofs
))
2433 (+ base-value ofs
)) ;; return value
2435 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2440 (defun sh-indent-line ()
2441 "Indent the current line."
2443 (sh-must-be-shell-mode)
2444 (let ((indent (sh-calculate-indent)) shift-amt beg end
2445 (pos (- (point-max) (point))))
2449 (skip-chars-forward " \t")
2450 (setq shift-amt
(- indent
(current-column)))
2451 (unless (zerop shift-amt
)
2452 (delete-region beg
(point))
2454 ;; If initial point was within line's indentation,
2455 ;; position after the indentation. Else stay at same point in text.
2456 (if (> (- (point-max) pos
) (point))
2457 (goto-char (- (point-max) pos
))))))
2460 (defun sh-blink (blinkpos &optional msg
)
2461 "Move cursor momentarily to BLINKPOS and display MSG."
2462 ;; We can get here without it being a number on first line
2463 (if (numberp blinkpos
)
2465 (goto-char blinkpos
)
2467 (sit-for blink-matching-delay
))
2470 (defun sh-show-indent (arg)
2471 "Show the how the currently line would be indented.
2472 This tells you which variable, if any, controls the indentation of
2474 If optional arg ARG is non-null (called interactively with a prefix),
2475 a pop up window describes this variable.
2476 If variable `sh-blink' is non-nil then momentarily go to the line
2477 we are indenting relative to, if applicable."
2479 (sh-must-support-indent)
2480 (let* ((info (sh-get-indent-info))
2481 (var (sh-get-indent-var-for-line info
))
2482 (curr-indent (current-indentation))
2485 (message (setq msg var
))
2486 (setq val
(sh-calculate-indent info
))
2488 (if (eq curr-indent val
)
2489 (setq msg
(format "%s is %s" var
(symbol-value var
)))
2492 (format "%s (%s) would change indent from %d to: %d"
2493 var
(symbol-value var
) curr-indent val
)
2494 (format "%s (%s) would leave line as is"
2495 var
(symbol-value var
)))
2498 (describe-variable var
)))
2500 (let ((info (sh-get-indent-info)))
2501 (if (and info
(listp (car info
))
2502 (eq (car (car info
)) t
))
2503 (sh-blink (nth 1 (car info
)) msg
)
2508 (defun sh-set-indent ()
2509 "Set the indentation for the current line.
2510 If the current line is controlled by an indentation variable, prompt
2511 for a new value for it."
2513 (sh-must-support-indent)
2514 (let* ((info (sh-get-indent-info))
2515 (var (sh-get-indent-var-for-line info
))
2516 val val0 new-val old-val indent-val
)
2518 (message (format "Cannot set indent - %s" var
))
2519 (setq old-val
(symbol-value var
))
2520 (setq val
(sh-read-variable var
))
2524 (setq indent-val
(sh-calculate-indent info
))
2526 (message "Variable: %s Value: %s would indent to: %d"
2527 var
(symbol-value var
) indent-val
)
2528 (message "Variable: %s Value: %s would leave line as is."
2529 var
(symbol-value var
)))
2530 ;; I'm not sure about this, indenting it now?
2531 ;; No. Because it would give the impression that an undo would
2532 ;; restore thing, but the value has been altered.
2537 (message "Bad value for %s, restoring to previous value %s"
2544 (defun sh-learn-line-indent (arg)
2545 "Learn how to indent a line as it currently is indented.
2547 If there is an indentation variable which controls this line's indentation,
2548 then set it to a value which would indent the line the way it
2551 If the value can be represented by one of the symbols then do so
2552 unless optional argument ARG (the prefix when interactive) is non-nil."
2554 (sh-must-support-indent)
2555 ;; I'm not sure if we show allow learning on an empty line.
2556 ;; Though it might occasionally be useful I think it usually
2557 ;; would just be confusing.
2560 (looking-at "\\s-*$"))
2561 (message "sh-learn-line-indent ignores empty lines.")
2562 (let* ((info (sh-get-indent-info))
2563 (var (sh-get-indent-var-for-line info
))
2564 ival sval diff new-val
2566 (curr-indent (current-indentation)))
2569 (message (format "Cannot learn line - %s" var
)))
2570 ((eq var
'sh-indent-comment
)
2571 ;; This is arbitrary...
2572 ;; - if curr-indent is 0, set to curr-indent
2573 ;; - else if it has the indentation of a "normal" line,
2575 ;; - else set to curr-indent.
2576 (setq sh-indent-comment
2577 (if (= curr-indent
0)
2579 (let* ((sh-indent-comment t
)
2580 (val2 (sh-calculate-indent info
)))
2581 (if (= val2 curr-indent
)
2584 (message "%s set to %s" var
(symbol-value var
))
2586 ((numberp (setq sval
(sh-var-value var
)))
2587 (setq ival
(sh-calculate-indent info
))
2588 (setq diff
(- curr-indent ival
))
2590 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2591 curr-indent ival diff var sval
)
2592 (setq new-val
(+ sval diff
))
2593 ;;; I commented out this because someone might want to replace
2594 ;;; a value of `+' with the current value of sh-basic-offset
2597 ;;; (message "No change needed!")
2598 (sh-set-var-value var new-val no-symbol
)
2599 (message "%s set to %s" var
(symbol-value var
))
2603 (message "Cannot change %s" var
))))))
2607 (defun sh-mark-init (buffer)
2608 "Initialize a BUFFER to be used by `sh-mark-line'."
2609 (let ((main-buffer (current-buffer)))
2611 (set-buffer (get-buffer-create buffer
))
2614 (setq occur-buffer main-buffer
)
2618 (defun sh-mark-line (message point buffer
&optional add-linenum occur-point
)
2619 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2620 Buffer BUFFER is in `occur-mode'.
2621 If ADD-LINENUM is non-nil the message is preceded by the line number.
2622 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2623 so that `occur-next' and `occur-prev' will work."
2624 (let ((m1 (make-marker))
2625 (main-buffer (current-buffer))
2629 (set-marker m1 point
(current-buffer))
2631 (setq line
(format "%d: " (1+ (count-lines 1 point
))))))
2633 (if (get-buffer buffer
)
2634 (set-buffer (get-buffer buffer
))
2635 (set-buffer (get-buffer-create buffer
))
2637 (setq occur-buffer main-buffer
)
2639 (goto-char (point-max))
2640 (setq start
(point))
2643 (setq occur-point
(point)))
2646 (put-text-property start
(point) 'mouse-face
'highlight
))
2650 (put-text-property start
(point) 'occur m1
)
2652 (put-text-property occur-point
(1+ occur-point
)
2659 ;; Is this really worth having?
2660 (defvar sh-learned-buffer-hook nil
2661 "*An abnormal hook, called with an alist of learned variables.")
2662 ;;; Example of how to use sh-learned-buffer-hook
2664 ;; (defun what-i-learned (list)
2667 ;; (set-buffer "*scratch*")
2668 ;; (goto-char (point-max))
2669 ;; (insert "(setq\n")
2671 ;; (insert (format " %s %s \n"
2672 ;; (nth 0 (car p)) (nth 1 (car p))))
2673 ;; (setq p (cdr p)))
2677 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2680 ;; Originally this was sh-learn-region-indent (beg end)
2681 ;; However, in practice this was awkward so I changed it to
2682 ;; use the whole buffer. Use narrowing if needbe.
2683 (defun sh-learn-buffer-indent (&optional arg
)
2684 "Learn how to indent the buffer the way it currently is.
2686 Output in buffer \"*indent*\" shows any lines which have conflicting
2687 values of a variable, and the final value of all variables learned.
2688 This buffer is popped to automatically if there are any discrepancies.
2690 If no prefix ARG is given, then variables are set to numbers.
2691 If a prefix arg is given, then variables are set to symbols when
2692 applicable -- e.g. to symbol `+' if the value is that of the
2694 If a positive numerical prefix is given, then `sh-basic-offset'
2695 is set to the prefix's numerical value.
2696 Otherwise, sh-basic-offset may or may not be changed, according
2697 to the value of variable `sh-learn-basic-offset'.
2699 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2700 function completes. The function is abnormal because it is called
2701 with an alist of variables learned. This feature may be changed or
2702 removed in the future.
2704 This command can often take a long time to run."
2706 (sh-must-support-indent)
2708 (goto-char (point-min))
2709 (let ((learned-var-list nil
)
2710 (out-buffer "*indent*")
2717 (comment-col nil
) ;; number if all same, t if seen diff values
2718 (comments-always-default t
) ;; nil if we see one not default
2720 (specified-basic-offset (and arg
(numberp arg
)
2724 (setq vec
(make-vector max
0))
2725 (sh-mark-init out-buffer
)
2727 (if specified-basic-offset
2729 (setq sh-basic-offset arg
)
2731 (format "Using specified sh-basic-offset of %d"
2734 (format "Initial value of sh-basic-offset: %s"
2737 (while (< (point) (point-max))
2738 (setq linenum
(1+ linenum
))
2739 ;; (if (zerop (% linenum 10))
2740 (message "line %d" linenum
)
2742 (unless (looking-at "\\s-*$") ;; ignore empty lines!
2743 (let* ((sh-indent-comment t
) ;; info must return default indent
2744 (info (sh-get-indent-info))
2745 (var (sh-get-indent-var-for-line info
))
2746 sval ival diff new-val
2747 (curr-indent (current-indentation)))
2753 ((numberp (setq sval
(sh-var-value var
'no-error
)))
2754 ;; the numberp excludes comments since sval will be t.
2755 (setq ival
(sh-calculate-indent))
2756 (setq diff
(- curr-indent ival
))
2757 (setq new-val
(+ sval diff
))
2758 (sh-set-var-value var new-val
'no-symbol
)
2759 (unless (looking-at "\\s-*#") ;; don't learn from comments
2760 (if (setq previous-set-info
(assoc var learned-var-list
))
2762 ;; it was already there, is it same value ?
2763 (unless (eq (symbol-value var
)
2764 (nth 1 previous-set-info
))
2766 (format "Variable %s was set to %s"
2767 var
(symbol-value var
))
2768 (point) out-buffer t t
)
2770 (format " but was previously set to %s"
2771 (nth 1 previous-set-info
))
2772 (nth 2 previous-set-info
) out-buffer t
)
2773 (setq num-diffs
(1+ num-diffs
))
2774 ;; (delete previous-set-info learned-var-list)
2775 (setcdr previous-set-info
2776 (list (symbol-value var
) (point)))
2779 (setq learned-var-list
2780 (append (list (list var
(symbol-value var
)
2783 (if (numberp new-val
)
2786 "This line's indent value: %d" new-val
)
2788 (setq new-val
(- new-val
)))
2790 (aset vec new-val
(1+ (aref vec new-val
))))))
2792 ((eq var
'sh-indent-comment
)
2793 (unless (= curr-indent
(sh-calculate-indent info
))
2794 ;; this is not the default indentation
2795 (setq comments-always-default nil
)
2796 (if comment-col
;; then we have see one before
2797 (or (eq comment-col curr-indent
)
2798 (setq comment-col t
)) ;; seen a different one
2799 (setq comment-col curr-indent
))
2802 (sh-debug "Cannot learn this line!!!")
2805 "at %s learned-var-list is %s" (point) learned-var-list
)
2812 "comment-col = %s comments-always-default = %s"
2813 comment-col comments-always-default
))
2815 (sh-mark-line msg nil out-buffer
)))
2818 (setq msg
"\nComments are all in 1st column.\n"))
2819 (comments-always-default
2820 (setq msg
"\nComments follow default indentation.\n")
2821 (setq comment-col t
))
2822 ((numberp comment-col
)
2823 (setq msg
(format "\nComments are in col %d." comment-col
)))
2825 (setq msg
"\nComments seem to be mixed, leaving them as is.\n")
2826 (setq comment-col nil
)
2829 (sh-mark-line msg nil out-buffer
)
2831 (sh-mark-line initial-msg nil out-buffer t t
)
2833 (setq suggested
(sh-guess-basic-offset vec
))
2835 (if (and suggested
(not specified-basic-offset
))
2838 ;; t => set it if we have a single value as a number
2839 ((and (eq sh-learn-basic-offset t
) (numberp suggested
))
2841 ;; other non-nil => set it if only one value was found
2842 (sh-learn-basic-offset
2843 (if (numberp suggested
)
2845 (if (= (length suggested
) 1)
2851 (setq learned-var-list
2852 (append (list (list 'sh-basic-offset
2853 (setq sh-basic-offset new-value
)
2856 ;; Not sure if we need to put this line in, since
2857 ;; it will appear in the "Learned variable settings".
2859 (format "Changed sh-basic-offset to: %d" sh-basic-offset
)
2862 (if (listp suggested
)
2863 (format "Possible value(s) for sh-basic-offset: %s"
2864 (mapconcat 'int-to-string suggested
" "))
2865 (format "Suggested sh-basic-offset: %d" suggested
))
2869 (setq learned-var-list
2870 (append (list (list 'sh-indent-comment comment-col
(point-max)))
2872 (setq sh-indent-comment comment-col
)
2873 (let ((name (buffer-name))
2874 (lines (if (and (eq (point-min) 1)
2875 (eq (point-max) (1+ (buffer-size))))
2877 (format "lines %d to %d of "
2878 (1+ (count-lines 1 (point-min)))
2879 (1+ (count-lines 1 (point-max))))))
2881 (sh-mark-line "\nLearned variable settings:" nil out-buffer
)
2883 ;; Set learned variables to symbolic rather than numeric
2884 ;; values where possible.
2885 (dolist (learned-var (reverse learned-var-list
))
2886 (let ((var (car learned-var
))
2887 (val (nth 1 learned-var
)))
2888 (when (and (not (eq var
'sh-basic-offset
))
2890 (sh-set-var-value var val
)))))
2891 (dolist (learned-var (reverse learned-var-list
))
2892 (let ((var (car learned-var
)))
2893 (sh-mark-line (format " %s %s" var
(symbol-value var
))
2894 (nth 2 learned-var
) out-buffer
)))
2896 (set-buffer out-buffer
)
2897 (goto-char (point-min))
2899 (format "Indentation values for buffer %s.\n" name
)
2900 (format "%d indentation variable%s different values%s\n\n"
2904 (if (zerop num-diffs
)
2907 ;; Are abnormal hooks considered bad form?
2908 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list
)
2909 (if (or sh-popup-occur-buffer
(> num-diffs
0))
2910 (pop-to-buffer out-buffer
))
2913 (defun sh-guess-basic-offset (vec)
2914 "See if we can determine a reasonable value for `sh-basic-offset'.
2915 This is experimental, heuristic and arbitrary!
2916 Argument VEC is a vector of information collected by
2917 `sh-learn-buffer-indent'.
2919 number - there appears to be a good single value
2920 list of numbers - no obvious one, here is a list of one or more
2922 nil - we couldn't find a reasonable one."
2923 (let* ((max (1- (length vec
)))
2925 (totals (make-vector max
0))
2929 (aset totals i
(+ (aref totals i
) (* 4 (aref vec i
))))
2932 (aset totals i
(+ (aref totals i
) (aref vec
(/ i
2)))))
2934 (aset totals i
(+ (aref totals i
) (aref vec
(* i
2)))))
2942 (if (/= (aref totals i
) 0)
2943 (setq x
(append x
(list (cons i
(aref totals i
))))))
2946 (setq x
(sort x
(lambda (a b
) (> (cdr a
) (cdr b
)))))
2947 (setq tot
(apply '+ (append totals nil
)))
2948 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
2952 (message "no values!")) ;; we return nil
2954 (message "only value is %d" (car (car x
)))
2955 (setq result
(car (car x
)))) ;; return single value
2956 ((> (cdr (car x
)) (/ tot
2))
2958 (message "basic-offset is probably %d" (car (car x
)))
2959 (setq result
(car (car x
)))) ;; again, return a single value
2960 ((>= (cdr (car x
)) (* 2 (cdr (car (cdr x
)))))
2961 ;; 1st is >= 2 * 2nd
2962 (message "basic-offset could be %d" (car (car x
)))
2963 (setq result
(car (car x
))))
2964 ((>= (+ (cdr (car x
))(cdr (car (cdr x
)))) (/ tot
2))
2965 ;; 1st & 2nd together >= 50% - return a list
2966 (setq p x sum
0 result nil
)
2968 (<= (setq sum
(+ sum
(cdr (car p
)))) (/ tot
2)))
2969 (setq result
(append result
(list (car (car p
)))))
2971 (message "Possible choices for sh-basic-offset: %s"
2972 (mapconcat 'int-to-string result
" ")))
2974 (message "No obvious value for sh-basic-offset. Perhaps %d"
2976 ;; result is nil here
2980 ;; ========================================================================
2982 ;; Styles -- a quick and dirty way of saving the indentation settings.
2984 (defvar sh-styles-alist nil
2985 "A list of all known shell indentation styles.")
2987 (defun sh-name-style (name &optional confirm-overwrite
)
2988 "Name the current indentation settings as a style called NAME.
2989 If this name exists, the command will prompt whether it should be
2991 - - it was called interactively with a prefix argument, or
2992 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
2993 ;; (interactive "sName for this style: ")
2996 (read-from-minibuffer "Name for this style? " )
2997 (not current-prefix-arg
)))
2998 (let ((slist (cons name
2999 (mapcar (lambda (var) (cons var
(symbol-value var
)))
3001 (style (assoc name sh-styles-alist
)))
3003 (if (and confirm-overwrite
3004 (not (y-or-n-p "This style exists. Overwrite it? ")))
3005 (message "Not changing style %s" name
)
3006 (message "Updating style %s" name
)
3007 (setcdr style
(cdr slist
)))
3008 (message "Creating new style %s" name
)
3009 (push slist sh-styles-alist
))))
3011 (defun sh-load-style (name)
3012 "Set shell indentation values for this buffer from those in style NAME."
3013 (interactive (list (completing-read
3014 "Which style to use for this buffer? "
3015 sh-styles-alist nil t
)))
3016 (let ((sl (assoc name sh-styles-alist
)))
3018 (error "sh-load-style - style %s not known" name
)
3019 (dolist (var (cdr sl
))
3020 (set (car var
) (cdr var
))))))
3022 (defun sh-save-styles-to-buffer (buff)
3023 "Save all current styles in elisp to buffer BUFF.
3024 This is always added to the end of the buffer."
3026 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3027 (with-current-buffer (get-buffer-create buff
)
3028 (goto-char (point-max))
3030 (pp `(setq sh-styles-alist
',sh-styles-alist
) (current-buffer))))
3034 ;; statement syntax-commands for various shells
3036 ;; You are welcome to add the syntax or even completely new statements as
3037 ;; appropriate for your favorite shell.
3039 (define-skeleton sh-case
3040 "Insert a case/switch statement. See `sh-feature'."
3042 "switch( " str
" )" \n
3043 > "case " (read-string "pattern: ") ?
: \n
3046 ( "other pattern, %s: "
3056 > "switch( " str
" ) {" \n
3057 > "case " (read-string "pattern: ") \n
3059 ( "other pattern, %s: "
3067 > "case " str
" in" \n
3068 > (read-string "pattern: ")
3069 (propertize ")" 'syntax-table sh-st-punc
)
3073 ( "other pattern, %s: "
3074 > str
(propertize ")" 'syntax-table sh-st-punc
) \n
3077 > "*" (propertize ")" 'syntax-table sh-st-punc
) \n
3082 (define-skeleton sh-for
3083 "Insert a for loop. See `sh-feature'."
3084 (csh eval sh-modify sh
3092 (es eval sh-modify rc
3094 (rc eval sh-modify sh
3098 (sh "Index variable: "
3099 > "for " str
" in " _
"; do" \n
3100 > _ | ?$
& (sh-remember-variable str
) \n
3105 (define-skeleton sh-indexed-loop
3106 "Insert an indexed loop from 1 to n. See `sh-feature'."
3107 (bash eval identity posix
)
3108 (csh "Index variable: "
3110 "while( $" str
" <= " (read-string "upper limit: ") " )" \n
3114 (es eval sh-modify rc
3116 (ksh88 "Index variable: "
3117 > "integer " str
"=0" \n
3118 > "while (( ( " str
" += 1 ) <= "
3119 (read-string "upper limit: ")
3121 > _ ?$
(sh-remember-variable str
) > \n
3123 (posix "Index variable: "
3125 "while [ $" str
" -le "
3126 (read-string "upper limit: ")
3129 str ?
= (sh-add (sh-remember-variable str
) 1) \n
3131 (rc "Index variable: "
3132 > "for( " str
" in" " `{awk 'BEGIN { for( i=1; i<="
3133 (read-string "upper limit: ")
3134 "; i++ ) print i }'`}) {" \n
3135 > _ ?$
(sh-remember-variable str
) \n
3137 (sh "Index variable: "
3138 > "for " str
" in `awk 'BEGIN { for( i=1; i<="
3139 (read-string "upper limit: ")
3140 "; i++ ) print i }'`; do" \n
3141 > _ ?$
(sh-remember-variable str
) \n
3145 (defun sh-shell-initialize-variables ()
3146 "Scan the buffer for variable assignments.
3147 Add these variables to `sh-shell-variables'."
3148 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3150 (goto-char (point-min))
3151 (setq sh-shell-variables-initialized t
)
3152 (while (search-forward "=" nil t
)
3154 (message "Scanning buffer `%s' for variable assignments...done"
3157 (defvar sh-add-buffer
)
3159 (defun sh-add-completer (string predicate code
)
3160 "Do completion using `sh-shell-variables', but initialize it first.
3161 This function is designed for use as the \"completion table\",
3162 so it takes three arguments:
3163 STRING, the current buffer contents;
3164 PREDICATE, the predicate for filtering possible matches;
3165 CODE, which says what kind of things to do.
3166 CODE can be nil, t or `lambda'.
3167 nil means to return the best completion of STRING, or nil if there is none.
3168 t means to return a list of all possible completions of STRING.
3169 `lambda' means to return t if STRING is a valid completion as it stands."
3170 (let ((sh-shell-variables
3172 (set-buffer sh-add-buffer
)
3173 (or sh-shell-variables-initialized
3174 (sh-shell-initialize-variables))
3175 (nconc (mapcar (lambda (var)
3177 (substring var
0 (string-match "=" var
))))
3179 process-environment
)
3180 sh-shell-variables
))))
3182 (try-completion string sh-shell-variables predicate
))
3184 (all-completions string sh-shell-variables predicate
))
3186 (assoc string sh-shell-variables
)))))
3188 (defun sh-add (var delta
)
3189 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3191 (let ((sh-add-buffer (current-buffer)))
3192 (list (completing-read "Variable: " 'sh-add-completer
)
3193 (prefix-numeric-value current-prefix-arg
))))
3194 (insert (sh-feature '((bash .
"$[ ")
3200 (sh-remember-variable var
)
3201 (if (< delta
0) " - " " + ")
3202 (number-to-string (abs delta
))
3203 (sh-feature '((bash .
" ]")
3212 (define-skeleton sh-function
3213 "Insert a function definition. See `sh-feature'."
3214 (bash eval sh-modify ksh88
3217 "function " str
" {" \n
3220 (rc eval sh-modify ksh88
3229 (define-skeleton sh-if
3230 "Insert an if statement. See `sh-feature'."
3232 "if( " str
" ) then" \n
3234 ( "other condition, %s: "
3235 < "else if( " str
" ) then" \n
3242 > "if { " str
" } {" \n
3244 ( "other condition, %s: "
3245 "} { " str
" } {" > \n
3252 > "if( " str
" ) {" \n
3254 ( "other condition, %s: "
3255 "} else if( " str
" ) {" > \n
3263 '(setq input
(sh-feature sh-test
))
3264 > "if " str
"; then" \n
3266 ( "other condition, %s: "
3267 > "elif " str
"; then" > \n
3276 (define-skeleton sh-repeat
3277 "Insert a repeat loop definition. See `sh-feature'."
3283 > "repeat " str
"; do" > \n
3287 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3291 (define-skeleton sh-select
3292 "Insert a select statement. See `sh-feature'."
3293 (ksh88 "Index variable: "
3294 > "select " str
" in " _
"; do" \n
3297 (bash eval sh-append ksh88
))
3298 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3302 (define-skeleton sh-tmp-file
3303 "Insert code to setup temporary file handling. See `sh-feature'."
3304 (bash eval identity ksh88
)
3305 (csh (file-name-nondirectory (buffer-file-name))
3306 "set tmp = /tmp/" str
".$$" \n
3308 (and (goto-char (point-max))
3312 "rm $tmp* >&/dev/null" >)
3313 (es (file-name-nondirectory (buffer-file-name))
3314 > "local( signals = $signals sighup sigint; tmp = /tmp/" str
3317 > "rm $tmp^* >[2]/dev/null" \n
3323 (ksh88 eval sh-modify sh
3325 (rc (file-name-nondirectory (buffer-file-name))
3326 > "tmp = /tmp/" str
".$pid" \n
3327 "fn sigexit { rm $tmp^* >[2]/dev/null }")
3328 (sh (file-name-nondirectory (buffer-file-name))
3329 > "TMP=${TMPDIR:-/tmp}/" str
".$$" \n
3330 "trap \"rm $TMP* 2>/dev/null\" " ?
0))
3334 (define-skeleton sh-until
3335 "Insert an until loop. See `sh-feature'."
3337 '(setq input
(sh-feature sh-test
))
3338 > "until " str
"; do" \n
3341 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3345 (define-skeleton sh-while
3346 "Insert a while loop. See `sh-feature'."
3347 (csh eval sh-modify sh
3353 (es eval sh-modify sh
3357 (rc eval sh-modify sh
3362 '(setq input
(sh-feature sh-test
))
3363 > "while " str
"; do" \n
3369 (define-skeleton sh-while-getopts
3370 "Insert a while getopts loop. See `sh-feature'.
3371 Prompts for an options string which consists of letters for each recognized
3372 option followed by a colon `:' if the option accepts an argument."
3373 (bash eval sh-modify sh
3377 > "switch( \"$1\" )" \n
3378 '(setq input
'("- x" .
2))
3381 < "case " '(eval str
)
3382 '(if (string-match " +" str
)
3383 (setq v1
(substring str
(match-end 0))
3384 str
(substring str
0 (match-beginning 0)))
3387 > "set " v1
& " = $2" | -
4 & _
\n
3388 (if v1
"shift") & \n
3398 (ksh88 eval sh-modify sh
3402 (posix eval sh-modify sh
3403 18 "$(basename $0)")
3405 > "while getopts :" str
" OPT; do" \n
3407 '(setq v1
(append (vconcat str
) nil
))
3408 ( (prog1 (if v1
(char-to-string (car v1
)))
3409 (if (eq (nth 1 v1
) ?
:)
3410 (setq v1
(nthcdr 2 v1
)
3414 > str
"|+" str
(propertize ")" 'syntax-table sh-st-punc
) \n
3417 > "*" (propertize ")" 'syntax-table sh-st-punc
) \n
3418 > "echo" " \"usage: " "`basename $0`"
3419 " [+-" '(setq v1
(point)) str
3421 (while (search-backward ":" v1 t
)
3422 (replace-match " ARG] [+-" t t
)))
3423 (if (eq (preceding-char) ?-
) -
5)
3424 (if (and (sequencep v1
) (length v1
)) "] " "} ")
3430 "shift " (sh-add "OPTIND" -
1)))
3434 (defun sh-assignment (arg)
3435 "Remember preceding identifier for future completion and do self-insert."
3437 (self-insert-command arg
)
3439 (sh-remember-variable
3441 (if (re-search-forward (sh-feature sh-assignment-regexp
)
3443 (beginning-of-line 1))
3445 (match-string 1))))))
3449 (defun sh-maybe-here-document (arg)
3450 "Insert self. Without prefix, following unquoted `<' inserts here document.
3451 The document is bounded by `sh-here-document-word'."
3453 (self-insert-command (prefix-numeric-value arg
))
3455 (not (eq (char-after (- (point) 2)) last-command-char
))
3460 (insert sh-here-document-word
)
3461 (or (eolp) (looking-at "[ \t]") (insert ?
))
3467 (save-excursion (insert ?
\n sh-here-document-word
)))))
3470 ;; various other commands
3472 (autoload 'comint-dynamic-complete
"comint"
3473 "Dynamically perform completion at point." t
)
3475 (autoload 'shell-dynamic-complete-command
"shell"
3476 "Dynamically complete the command at point." t
)
3478 (autoload 'comint-dynamic-complete-filename
"comint"
3479 "Dynamically complete the filename at point." t
)
3481 (autoload 'shell-dynamic-complete-environment-variable
"shell"
3482 "Dynamically complete the environment variable at point." t
)
3486 (defun sh-newline-and-indent ()
3487 "Strip unquoted whitespace, insert newline, and indent like current line."
3489 (indent-to (prog1 (current-indentation)
3490 (delete-region (point)
3492 (or (zerop (skip-chars-backward " \t"))
3498 (defun sh-beginning-of-command ()
3499 "Move point to successive beginnings of commands."
3501 (if (re-search-backward sh-beginning-of-command nil t
)
3502 (goto-char (match-beginning 2))))
3504 (defun sh-end-of-command ()
3505 "Move point to successive ends of commands."
3507 (if (re-search-forward sh-end-of-command nil t
)
3508 (goto-char (match-end 1))))
3510 (provide 'sh-script
)
3512 ;;; sh-script.el ends here