1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993, 94, 95, 96, 97, 1999, 2001, 2003
4 ;; Free Software Foundation, Inc.
6 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
9 ;; Keywords: languages, unix
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
30 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
31 ;; as various derivatives are supported and easily derived from. Structured
32 ;; statements can be inserted with one command or abbrev. Completion is
33 ;; available for filenames, variables known from the script, the shell and
34 ;; the environment as well as commands.
38 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
39 ;; - Variables in `"' strings aren't fontified because there's no way of
40 ;; syntactically distinguishing those from `'' strings.
44 ;; Indentation for rc and es modes is very limited, but for Bourne shells
45 ;; and its derivatives it is quite customizable.
47 ;; The following description applies to sh and derived shells (bash,
50 ;; There are various customization variables which allow tailoring to
51 ;; a wide variety of styles. Most of these variables are named
52 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
53 ;; sh-indent-after-if controls the indenting of a line following
54 ;; an if statement, and sh-indent-for-fi controls the indentation
55 ;; of the line containing the fi.
57 ;; You can set each to a numeric value, but it is often more convenient
58 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
59 ;; By changing this one variable you can increase or decrease how much
60 ;; indentation there is. Valid symbols:
62 ;; + Indent right by sh-basic-offset
63 ;; - Indent left by sh-basic-offset
64 ;; ++ Indent right twice sh-basic-offset
65 ;; -- Indent left twice sh-basic-offset
66 ;; * Indent right half sh-basic-offset
67 ;; / Indent left half sh-basic-offset.
69 ;; There are 4 commands to help set the indentation variables:
72 ;; This shows what variable controls the indentation of the current
73 ;; line and its value.
76 ;; This allows you to set the value of the variable controlling the
77 ;; current line's indentation. You can enter a number or one of a
78 ;; number of special symbols to denote the value of sh-basic-offset,
79 ;; or its negative, or half it, or twice it, etc. If you've used
80 ;; cc-mode this should be familiar. If you forget which symbols are
81 ;; valid simply press C-h at the prompt.
83 ;; `sh-learn-line-indent'
84 ;; Simply make the line look the way you want it, then invoke this
85 ;; command. It will set the variable to the value that makes the line
86 ;; indent like that. If called with a prefix argument then it will set
87 ;; the value to one of the symbols if applicable.
89 ;; `sh-learn-buffer-indent'
90 ;; This is the deluxe function! It "learns" the whole buffer (use
91 ;; narrowing if you want it to process only part). It outputs to a
92 ;; buffer *indent* any conflicts it finds, and all the variables it has
93 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
94 ;; easily find where something was set. It is popped to automatically
95 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
97 ;; `sh-indent-comment' will be set if all comments follow the same
98 ;; pattern; if they don't it will be set to nil.
99 ;; Whether `sh-basic-offset' is set is determined by variable
100 ;; `sh-learn-basic-offset'.
102 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
103 ;; (e.g. if there are large case statements). Perhaps it does not make
104 ;; sense to run it on large buffers: if lots of lines have different
105 ;; indentation styles it will produce a lot of diagnostics in the
106 ;; *indent* buffer; if there is a consistent style then running
107 ;; `sh-learn-buffer-indent' on a small region of the buffer should
110 ;; Saving indentation values
111 ;; -------------------------
112 ;; After you've learned the values in a buffer, how to you remember
113 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
114 ;; would make this unnecessary; simply learn the values when you visit
116 ;; You can do this automatically like this:
117 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
119 ;; However... `sh-learn-buffer-indent' is extremely slow,
120 ;; especially on large-ish buffer. Also, if there are conflicts the
121 ;; "last one wins" which may not produce the desired setting.
123 ;; So...There is a minimal way of being able to save indentation values and
124 ;; to reload them in another buffer or at another point in time.
126 ;; Use `sh-name-style' to give a name to the indentation settings of
127 ;; the current buffer.
128 ;; Use `sh-load-style' to load indentation settings for the current
129 ;; buffer from a specific style.
130 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
131 ;; in lisp code. You can then store it in a file and later use
132 ;; `load-file' to load it.
134 ;; Indentation variables - buffer local or global?
135 ;; ----------------------------------------------
136 ;; I think that often having them buffer-local makes sense,
137 ;; especially if one is using `sh-learn-buffer-indent'. However, if
138 ;; a user sets values using customization, these changes won't appear
139 ;; to work if the variables are already local!
141 ;; To get round this, there is a variable `sh-make-vars-local' and 2
142 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
144 ;; If `sh-make-vars-local' is non-nil, then these variables become
145 ;; buffer local when the mode is established.
146 ;; If this is nil, then the variables are global. At any time you
147 ;; can make them local with the command `sh-make-vars-local'.
148 ;; Conversely, to update with the global values you can use the
149 ;; command `sh-reset-indent-vars-to-global-values'.
151 ;; This may be awkward, but the intent is to cover all cases.
153 ;; Awkward things, pitfalls
154 ;; ------------------------
155 ;; Indentation for a sh script is complicated for a number of reasons:
157 ;; 1. You can't format by simply looking at symbols, you need to look
158 ;; at keywords. [This is not the case for rc and es shells.]
159 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
160 ;; as a stand-alone symbol (in a case alternative). This makes
161 ;; things quite tricky!
162 ;; 3. Here-documents in a script should be treated "as is", and when
163 ;; they terminate we want to revert to the indentation of the line
164 ;; containing the "<<" symbol.
165 ;; 4. A line may be continued using the "\".
166 ;; 5. The character "#" (outside a string) normally starts a comment,
167 ;; but it doesn't in the sequence "$#"!
169 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
170 ;; uses, that of a text's syntax property. This, however, has 2
172 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
173 ;; case alternative, to find any here documents, and handle "$#".
174 ;; 2. Setting the text property makes the buffer modified. If the
175 ;; buffer is read-only buffer we have to cheat and bypass the read-only
176 ;; status. This is for cases where the buffer started read-only buffer
177 ;; but the user issued `toggle-read-only'.
181 ;; - Indenting many lines is slow. It currently does each line
182 ;; independently, rather than saving state information.
184 ;; - `sh-learn-buffer-indent' is extremely slow.
186 ;; Richard Sharman <rsharman@pobox.com> June 1999.
190 ;; page 1: variables and settings
191 ;; page 2: indentation stuff
192 ;; page 3: mode-command and utility functions
193 ;; page 4: statement syntax-commands for various shells
194 ;; page 5: various other commands
200 (require 'executable
)
205 "Shell programming utilities"
209 (defgroup sh-script nil
215 (defcustom sh-ancestor-alist
234 "*Alist showing the direct ancestor of various shells.
235 This is the basis for `sh-feature'. See also `sh-alias-alist'.
236 By default we have the following three hierarchies:
239 jcsh C Shell with Job Control
241 itcsh ? Turbo C Shell
246 jsh Bourne Shell with Job Control
247 bash GNU Bourne Again Shell
250 dtksh CDE Desktop Korn Shell
251 pdksh Public Domain Korn Shell
252 wksh Window Korn Shell
254 oash SCO OA (curses) Shell
255 posix IEEE 1003.2 Shell Standard
257 :type
'(repeat (cons symbol symbol
))
261 (defcustom sh-alias-alist
262 (append (if (eq system-type
'gnu
/linux
)
265 ;; for the time being
269 "*Alist for transforming shell names to what they really are.
270 Use this where the name of the executable doesn't correspond to the type of
272 :type
'(repeat (cons symbol symbol
))
276 (defcustom sh-shell-file
278 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
279 ;; the executable extension, so comparisons with the list of
280 ;; known shells work.
281 (and (memq system-type
'(ms-dos windows-nt
))
282 (let* ((shell (getenv "SHELL"))
284 (and shell
(file-name-nondirectory shell
))))
285 ;; shell-script mode doesn't support DOS/Windows shells,
286 ;; so use the default instead.
288 (member (downcase shell-base
)
289 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
292 (file-name-sans-extension (downcase shell
)))))
295 "*The executable file name for the shell being programmed."
300 (defcustom sh-shell-arg
301 ;; bash does not need any options when run in a shell script,
305 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
307 ;; -p means don't initialize functions from the environment.
309 ;; Someone proposed -motif, but we don't want to encourage
310 ;; use of a non-free widget set.
312 ;; -f means don't run .zshrc.
314 "*Single argument string for the magic number. See `sh-feature'."
315 :type
'(repeat (cons (symbol :tag
"Shell")
316 (choice (const :tag
"No Arguments" nil
)
317 (string :tag
"Arguments")
318 (cons :format
"Evaluate: %v"
319 (const :format
"" eval
)
323 (defcustom sh-imenu-generic-expression
325 .
((nil "^\\s-*\\(function\\s-+\\)?\\([A-Za-z_][A-Za-z_0-9]+\\)\\s-*()" 2))))
326 "*Alist of regular expressions for recognizing shell function definitions.
327 See `sh-feature' and `imenu-generic-expression'."
328 :type
'(alist :key-type
(symbol :tag
"Shell")
329 :value-type
(alist :key-type
(choice :tag
"Title"
331 (const :tag
"None" nil
))
333 (repeat :tag
"Regexp, index..." sexp
)))
337 (defvar sh-shell-variables nil
338 "Alist of shell variable names that should be included in completion.
339 These are used for completion in addition to all the variables named
340 in `process-environment'. Each element looks like (VAR . VAR), where
341 the car and cdr are the same symbol.")
343 (defvar sh-shell-variables-initialized nil
344 "Non-nil if `sh-shell-variables' is initialized.")
346 (defun sh-canonicalize-shell (shell)
347 "Convert a shell name SHELL to the one we should handle it as."
348 (if (string-match "\\.exe\\'" shell
)
349 (setq shell
(substring shell
0 (match-beginning 0))))
351 (setq shell
(intern shell
)))
352 (or (cdr (assq shell sh-alias-alist
))
355 (defvar sh-shell
(sh-canonicalize-shell (file-name-nondirectory sh-shell-file
))
356 "The shell being programmed. This is set by \\[sh-set-shell].")
358 ;; I turned off this feature because it doesn't permit typing commands
359 ;; in the usual way without help.
361 ;; '((csh eval sh-abbrevs shell
363 ;; "getopts" 'sh-while-getopts)
365 ;; (es eval sh-abbrevs shell
366 ;; "function" 'sh-function)
368 ;; (ksh88 eval sh-abbrevs sh
369 ;; "select" 'sh-select)
371 ;; (rc eval sh-abbrevs shell
373 ;; "function" 'sh-function)
375 ;; (sh eval sh-abbrevs shell
377 ;; "function" 'sh-function
379 ;; "getopts" 'sh-while-getopts)
381 ;; ;; The next entry is only used for defining the others
382 ;; (shell "for" sh-for
383 ;; "loop" sh-indexed-loop
385 ;; "tmpfile" sh-tmp-file
388 ;; (zsh eval sh-abbrevs ksh88
389 ;; "repeat" 'sh-repeat))
390 ;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
391 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
392 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
396 (defvar sh-mode-syntax-table
397 '((sh eval sh-mode-syntax-table
()
411 (csh eval identity sh
)
412 (rc eval identity sh
))
414 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
417 (let ((map (make-sparse-keymap))
418 (menu-map (make-sparse-keymap "Insert")))
419 (define-key map
"\C-c(" 'sh-function
)
420 (define-key map
"\C-c\C-w" 'sh-while
)
421 (define-key map
"\C-c\C-u" 'sh-until
)
422 (define-key map
"\C-c\C-t" 'sh-tmp-file
)
423 (define-key map
"\C-c\C-s" 'sh-select
)
424 (define-key map
"\C-c\C-r" 'sh-repeat
)
425 (define-key map
"\C-c\C-o" 'sh-while-getopts
)
426 (define-key map
"\C-c\C-l" 'sh-indexed-loop
)
427 (define-key map
"\C-c\C-i" 'sh-if
)
428 (define-key map
"\C-c\C-f" 'sh-for
)
429 (define-key map
"\C-c\C-c" 'sh-case
)
430 (define-key map
"\C-c?" 'sh-show-indent
)
431 (define-key map
"\C-c=" 'sh-set-indent
)
432 (define-key map
"\C-c<" 'sh-learn-line-indent
)
433 (define-key map
"\C-c>" 'sh-learn-buffer-indent
)
435 (define-key map
"=" 'sh-assignment
)
436 (define-key map
"\C-c+" 'sh-add
)
437 (define-key map
"\C-\M-x" 'sh-execute-region
)
438 (define-key map
"\C-c\C-x" 'executable-interpret
)
439 (define-key map
"<" 'sh-maybe-here-document
)
440 (define-key map
"(" 'skeleton-pair-insert-maybe
)
441 (define-key map
"{" 'skeleton-pair-insert-maybe
)
442 (define-key map
"[" 'skeleton-pair-insert-maybe
)
443 (define-key map
"'" 'skeleton-pair-insert-maybe
)
444 (define-key map
"`" 'skeleton-pair-insert-maybe
)
445 (define-key map
"\"" 'skeleton-pair-insert-maybe
)
447 (define-key map
[remap complete-tag
] 'comint-dynamic-complete
)
448 (define-key map
[remap newline-and-indent
] 'sh-newline-and-indent
)
449 (define-key map
[remap delete-backward-char
]
450 'backward-delete-char-untabify
)
451 (define-key map
"\C-c:" 'sh-set-shell
)
452 (define-key map
[remap backward-sentence
] 'sh-beginning-of-command
)
453 (define-key map
[remap forward-sentence
] 'sh-end-of-command
)
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.
547 If the first character of this string is \"-\", this character will
548 be removed from the string when it is used to close the here document.
549 This convention is used by the Bash shell, for example, to indicate
550 that leading tabs inside the here document should be ignored.
551 Note that Emacs currently has no support for indenting inside here
552 documents - you must insert literal tabs by hand.")
557 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
560 ;; customized this out of sheer bravado. not for the faint of heart.
561 ;; but it *did* have an asterisk in the docstring!
562 (defcustom sh-builtins
563 '((bash eval sh-append posix
564 "alias" "bg" "bind" "builtin" "declare" "dirs" "enable" "fc" "fg"
565 "help" "history" "jobs" "kill" "let" "local" "popd" "pushd" "source"
566 "suspend" "typeset" "unalias")
568 ;; The next entry is only used for defining the others
569 (bourne eval sh-append shell
570 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
573 (csh eval sh-append shell
574 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
575 "setenv" "source" "time" "unalias" "unhash")
577 (dtksh eval identity wksh
)
579 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
580 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
582 (jsh eval sh-append sh
583 "bg" "fg" "jobs" "kill" "stop" "suspend")
585 (jcsh eval sh-append csh
586 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
588 (ksh88 eval sh-append bourne
589 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
590 "typeset" "unalias" "whence")
592 (oash eval sh-append sh
593 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
594 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
595 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
596 "wmtitle" "wrefresh")
598 (pdksh eval sh-append ksh88
601 (posix eval sh-append sh
604 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
607 (sh eval sh-append bourne
608 "hash" "test" "type")
610 ;; The next entry is only used for defining the others
611 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
613 (wksh eval sh-append ksh88
616 (zsh eval sh-append ksh88
617 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
618 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
619 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
620 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
621 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
623 "*List of all shell builtins for completing read and fontification.
624 Note that on some systems not all builtins are available or some are
625 implemented as aliases. See `sh-feature'."
626 :type
'(repeat (cons (symbol :tag
"Shell")
627 (choice (repeat string
)
628 (cons :format
"Evaluate: %v"
629 (const :format
"" eval
)
635 (defcustom sh-leading-keywords
638 (es "true" "unwind-protect" "whatis")
642 (sh "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
643 "*List of keywords that may be immediately followed by a builtin or keyword.
644 Given some confusion between keywords and builtins depending on shell and
645 system, the distinction here has been based on whether they influence the
646 flow of control or syntax. See `sh-feature'."
647 :type
'(repeat (cons (symbol :tag
"Shell")
648 (choice (repeat string
)
649 (cons :format
"Evaluate: %v"
650 (const :format
"" eval
)
655 (defcustom sh-other-keywords
656 '((bash eval sh-append bourne
657 "bye" "logout" "select")
659 ;; The next entry is only used for defining the others
660 (bourne eval sh-append sh
663 (csh eval sh-append shell
664 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
665 "if" "logout" "onintr" "repeat" "switch" "then" "while")
667 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
668 "return" "throw" "while")
670 (ksh88 eval sh-append bourne
673 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
676 (sh eval sh-append shell
677 "done" "esac" "fi" "for" "in" "return")
679 ;; The next entry is only used for defining the others
680 (shell "break" "case" "continue" "exec" "exit")
682 (zsh eval sh-append bash
684 "*List of keywords not in `sh-leading-keywords'.
686 :type
'(repeat (cons (symbol :tag
"Shell")
687 (choice (repeat string
)
688 (cons :format
"Evaluate: %v"
689 (const :format
"" eval
)
696 '((bash eval sh-append sh
697 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_VERSION"
698 "cdable_vars" "ENV" "EUID" "FCEDIT" "FIGNORE" "glob_dot_filenames"
699 "histchars" "HISTFILE" "HISTFILESIZE" "history_control" "HISTSIZE"
700 "hostname_completion_file" "HOSTTYPE" "IGNOREEOF" "ignoreeof"
701 "LINENO" "MAIL_WARNING" "noclobber" "nolinks" "notify"
702 "no_exit_on_failed_exec" "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "PPID"
703 "PROMPT_COMMAND" "PS4" "pushd_silent" "PWD" "RANDOM" "REPLY"
704 "SECONDS" "SHLVL" "TMOUT" "UID")
706 (csh eval sh-append shell
707 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
708 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
709 "shell" "status" "time" "verbose")
711 (es eval sh-append shell
712 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
713 "pid" "prompt" "signals")
715 (jcsh eval sh-append csh
718 (ksh88 eval sh-append sh
719 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
720 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
723 (oash eval sh-append sh
724 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
726 (rc eval sh-append shell
727 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
730 (sh eval sh-append shell
731 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
733 ;; The next entry is only used for defining the others
734 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
735 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
736 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
737 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
739 (tcsh eval sh-append csh
740 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
741 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
742 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
743 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
744 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
745 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
746 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
747 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
750 (zsh eval sh-append ksh88
751 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
752 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
753 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
754 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
755 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
756 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
757 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
758 "List of all shell variables available for completing read.
764 (defface sh-heredoc-face
767 (:foreground
"yellow" :weight bold
))
770 (:foreground
"tan" ))
773 "Face to show a here-document"
774 :group
'sh-indentation
)
775 (defvar sh-heredoc-face
'sh-heredoc-face
)
778 (defvar sh-font-lock-keywords
779 '((csh eval sh-append shell
780 '("\\${?[#?]?\\([A-Za-z_][A-Za-z0-9_]*\\|0\\)" 1
781 font-lock-variable-name-face
))
783 (es eval sh-append executable-font-lock-keywords
784 '("\\$#?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\)" 1
785 font-lock-variable-name-face
))
787 (rc eval identity es
)
789 (sh eval sh-append shell
791 '("\\$\\({#?\\)?\\([A-Za-z_][A-Za-z0-9_]*\\|[-#?@!]\\)" 2
792 font-lock-variable-name-face
)
794 '("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face
)
795 '("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
796 (1 font-lock-keyword-face
) (2 font-lock-function-name-face nil t
)))
798 ;; The next entry is only used for defining the others
799 (shell eval sh-append executable-font-lock-keywords
800 '("\\\\[^A-Za-z0-9]" 0 font-lock-string-face
)
801 '("\\${?\\([A-Za-z_][A-Za-z0-9_]*\\|[0-9]+\\|[$*_]\\)" 1
802 font-lock-variable-name-face
))
803 (rpm eval sh-append rpm2
804 '("%{?\\(\\sw+\\)" 1 font-lock-keyword-face
))
805 (rpm2 eval sh-append shell
806 '("^\\(\\sw+\\):" 1 font-lock-variable-name-face
)))
807 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
809 (defvar sh-font-lock-keywords-1
811 "Subdued level highlighting for Shell Script modes.")
813 (defvar sh-font-lock-keywords-2
()
814 "Gaudy level highlighting for Shell Script modes.")
816 ;; These are used for the syntax table stuff (derived from cperl-mode).
817 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
818 (defconst sh-st-punc
(string-to-syntax "."))
819 (defconst sh-st-symbol
(string-to-syntax "_"))
820 (defconst sh-here-doc-syntax
(string-to-syntax "|")) ;; generic string
822 (defconst sh-here-doc-open-re
"<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\|\\s_\\)+\\).*\\(\n\\)")
824 (defvar sh-here-doc-markers nil
)
825 (make-variable-buffer-local 'sh-here-doc-markers
)
826 (defvar sh-here-doc-re sh-here-doc-open-re
)
827 (make-variable-buffer-local 'sh-here-doc-re
)
829 (defun sh-font-lock-close-heredoc (bol eof indented
)
830 "Determine the syntax of the \\n after an EOF.
831 If non-nil INDENTED indicates that the EOF was indented."
832 (let* ((eof-re (if eof
(regexp-quote eof
) ""))
833 ;; A rough regexp that should find the opening <<EOF back.
834 (sre (concat "<<\\(-?\\)\\s-*['\"\\]?"
835 ;; Use \s| to cheaply check it's an open-heredoc.
836 eof-re
"['\"]?\\([ \t|;&)<>].*\\)?\\s|"))
837 ;; A regexp that will find other EOFs.
838 (ere (concat "^" (if indented
"[ \t]*") eof-re
"\n"))
839 (start (save-excursion
841 (re-search-backward (concat sre
"\\|" ere
) nil t
))))
842 ;; If subgroup 1 matched, we found an open-heredoc, otherwise we first
843 ;; found a close-heredoc which makes the current close-heredoc inoperant.
845 ((when (and start
(match-end 1)
846 (not (and indented
(= (match-beginning 1) (match-end 1))))
847 (not (sh-in-comment-or-string (match-beginning 0))))
848 ;; Make sure our `<<' is not the EOF1 of a `cat <<EOF1 <<EOF2'.
851 (setq start
(line-beginning-position 2))
854 (re-search-forward "<<") ; Skip ourselves.
855 (and (re-search-forward sh-here-doc-open-re start
'move
)
856 (goto-char (match-beginning 0))
857 (sh-in-comment-or-string (point)))))
858 ;; No <<EOF2 found after our <<.
861 ((not (or start
(save-excursion (re-search-forward sre nil t
))))
862 ;; There's no <<EOF either before or after us,
863 ;; so we should remove ourselves from font-lock's keywords.
864 (setq sh-here-doc-markers
(delete eof sh-here-doc-markers
))
866 (concat sh-here-doc-open-re
"\\|^\\([ \t]*\\)"
867 (regexp-opt sh-here-doc-markers t
) "\\(\n\\)"))
870 (defun sh-font-lock-open-heredoc (start string
)
871 "Determine the syntax of the \\n after a <<EOF.
872 START is the position of <<.
873 STRING is the actual word used as delimiter (f.ex. \"EOF\").
874 INDENTED is non-nil if the here document's content (and the EOF mark) can
875 be indented (i.e. a <<- was used rather than just <<)."
876 (unless (or (memq (char-before start
) '(?
< ?
>))
877 (sh-in-comment-or-string start
))
878 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
879 ;; font-lock keywords to detect the end of this here document.
880 (let ((str (replace-regexp-in-string "['\"]" "" string
)))
881 (unless (member str sh-here-doc-markers
)
882 (push str sh-here-doc-markers
)
884 (concat sh-here-doc-open-re
"\\|^\\([ \t]*\\)"
885 (regexp-opt sh-here-doc-markers t
) "\\(\n\\)"))))
888 (defun sh-font-lock-here-doc (limit)
889 "Search for a heredoc marker."
890 ;; This looks silly, but it's because `sh-here-doc-re' keeps changing.
891 (re-search-forward sh-here-doc-re limit t
))
893 (defun sh-is-quoted-p (pos)
894 (and (eq (char-before pos
) ?
\\)
895 (not (sh-is-quoted-p (1- pos
)))))
897 (defun sh-font-lock-paren (start)
900 ;; Skip through all patterns
903 (forward-comment (- (point-max)))
904 ;; Skip through one pattern
906 (or (/= 0 (skip-syntax-backward "w_"))
907 (/= 0 (skip-chars-backward "?[]*/\\"))
908 (and (sh-is-quoted-p (1- (point)))
909 (goto-char (- (point) 2)))
910 (when (memq (char-before) '(?
\" ?
\'))
911 (condition-case nil
(progn (backward-sexp 1) t
)
913 (forward-comment (- (point-max)))
914 (when (eq (char-before) ?|
)
915 (backward-char 1) t
)))
916 (when (save-excursion (backward-char 2) (looking-at ";;\\|in"))
919 (defconst sh-font-lock-syntactic-keywords
920 ;; A `#' begins a comment when it is unquoted and at the beginning of a
921 ;; word. In the shell, words are separated by metacharacters.
922 ;; The list of special chars is taken from the single-unix spec
923 ;; of the shell command language (under `quoting') but with `$' removed.
924 `(("[^|&;<>()`\\\"' \t\n]\\(#+\\)" 1 ,sh-st-symbol
)
925 ;; Find HEREDOC starters and add a corresponding rule for the ender.
926 (sh-font-lock-here-doc
927 (2 (sh-font-lock-open-heredoc
928 (match-beginning 0) (match-string 1)) nil t
)
929 (5 (sh-font-lock-close-heredoc
930 (match-beginning 0) (match-string 4)
931 (and (match-beginning 3) (/= (match-beginning 3) (match-end 3))))
933 ;; Distinguish the special close-paren in `case'.
934 (")" 0 (sh-font-lock-paren (match-beginning 0)))))
936 (defun sh-font-lock-syntactic-face-function (state)
938 (if (char-valid-p (nth 3 state
))
939 font-lock-string-face
941 font-lock-comment-face
))
943 (defgroup sh-indentation nil
944 "Variables controlling indentation in shell scripts.
946 Note: customizing these variables will not affect existing buffers if
947 `sh-make-vars-local' is no-nil. See the documentation for
948 variable `sh-make-vars-local', command `sh-make-vars-local'
949 and command `sh-reset-indent-vars-to-global-values'."
953 (defcustom sh-set-shell-hook nil
954 "*Hook run by `sh-set-shell'."
958 (defcustom sh-mode-hook nil
959 "*Hook run by `sh-mode'."
963 (defcustom sh-learn-basic-offset nil
964 "*When `sh-guess-basic-offset' should learn `sh-basic-offset'.
967 t means: only if there seems to be an obvious value.
968 Anything else means: whenever we have a \"good guess\" as to the value."
970 (const :tag
"Never" nil
)
971 (const :tag
"Only if sure" t
)
972 (const :tag
"If have a good guess" usually
))
973 :group
'sh-indentation
)
975 (defcustom sh-popup-occur-buffer nil
976 "*Controls when `sh-learn-buffer-indent' pops the *indent* buffer.
977 If t it is always shown. If nil, it is shown only when there
980 (const :tag
"Only when there are conflicts." nil
)
981 (const :tag
"Always" t
))
982 :group
'sh-indentation
)
984 (defcustom sh-blink t
985 "*If non-nil, `sh-show-indent' shows the line indentation is relative to.
986 The position on the line is not necessarily meaningful.
987 In some cases the line will be the matching keyword, but this is not
990 :group
'sh-indentation
)
992 (defcustom sh-first-lines-indent
0
993 "*The indentation of the first non-blank non-comment line.
994 Usually 0 meaning first column.
995 Can be set to a number, or to nil which means leave it as is."
997 (const :tag
"Leave as is" nil
)
998 (integer :tag
"Column number"
999 :menu-tag
"Indent to this col (0 means first col)" ))
1000 :group
'sh-indentation
)
1003 (defcustom sh-basic-offset
4
1004 "*The default indentation increment.
1005 This value is used for the + and - symbols in an indentation variable."
1007 :group
'sh-indentation
)
1009 (defcustom sh-indent-comment nil
1010 "*How a comment line is to be indented.
1011 nil means leave it as it is;
1012 t means indent it as a normal line, aligning it to previous non-blank
1014 a number means align to that column, e.g. 0 means fist column."
1016 (const :tag
"Leave as is." nil
)
1017 (const :tag
"Indent as a normal line." t
)
1018 (integer :menu-tag
"Indent to this col (0 means first col)."
1019 :tag
"Indent to column number.") )
1020 :group
'sh-indentation
)
1023 (defvar sh-debug nil
1024 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1027 ;; Uncomment this defun and comment the defmacro for debugging.
1028 ;; (defun sh-debug (&rest args)
1029 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1031 ;; (apply 'message args)))
1032 (defmacro sh-debug
(&rest args
))
1034 (defconst sh-symbol-list
1035 '((const :tag
"+ " :value
+
1036 :menu-tag
"+ Indent right by sh-basic-offset")
1037 (const :tag
"- " :value -
1038 :menu-tag
"- Indent left by sh-basic-offset")
1039 (const :tag
"++" :value
++
1040 :menu-tag
"++ Indent right twice sh-basic-offset")
1041 (const :tag
"--" :value --
1042 :menu-tag
"-- Indent left twice sh-basic-offset")
1043 (const :tag
"* " :value
*
1044 :menu-tag
"* Indent right half sh-basic-offset")
1045 (const :tag
"/ " :value
/
1046 :menu-tag
"/ Indent left half sh-basic-offset")))
1048 (defcustom sh-indent-for-else
0
1049 "*How much to indent an else relative to an if. Usually 0."
1051 (integer :menu-tag
"A number (positive=>indent right)"
1053 (const :tag
"--") ;; separator!
1056 :group
'sh-indentation
)
1058 (defconst sh-number-or-symbol-list
1059 (append '((integer :menu-tag
"A number (positive=>indent right)"
1061 (const :tag
"--")) ; separator
1064 (defcustom sh-indent-for-fi
0
1065 "*How much to indent a fi relative to an if. Usually 0."
1066 :type
`(choice ,@ sh-number-or-symbol-list
)
1067 :group
'sh-indentation
)
1069 (defcustom sh-indent-for-done
'0
1070 "*How much to indent a done relative to its matching stmt. Usually 0."
1071 :type
`(choice ,@ sh-number-or-symbol-list
)
1072 :group
'sh-indentation
)
1074 (defcustom sh-indent-after-else
'+
1075 "*How much to indent a statement after an else statement."
1076 :type
`(choice ,@ sh-number-or-symbol-list
)
1077 :group
'sh-indentation
)
1079 (defcustom sh-indent-after-if
'+
1080 "*How much to indent a statement after an if statement.
1081 This includes lines after else and elif statements, too, but
1082 does not affect then else elif or fi statements themselves."
1083 :type
`(choice ,@ sh-number-or-symbol-list
)
1084 :group
'sh-indentation
)
1086 (defcustom sh-indent-for-then
'+
1087 "*How much to indent a then relative to an if."
1088 :type
`(choice ,@ sh-number-or-symbol-list
)
1089 :group
'sh-indentation
)
1091 (defcustom sh-indent-for-do
'*
1092 "*How much to indent a do statement.
1093 This is relative to the statement before the do, i.e. the
1094 while until or for statement."
1095 :type
`(choice ,@ sh-number-or-symbol-list
)
1096 :group
'sh-indentation
)
1098 (defcustom sh-indent-after-do
'*
1099 "*How much to indent a line after a do statement.
1100 This is used when the do is the first word of the line.
1101 This is relative to the statement before the do, e.g. a
1102 while for repeat or select statement."
1103 :type
`(choice ,@ sh-number-or-symbol-list
)
1104 :group
'sh-indentation
)
1106 (defcustom sh-indent-after-loop-construct
'+
1107 "*How much to indent a statement after a loop construct.
1109 This variable is used when the keyword \"do\" is on the same line as the
1110 loop statement (e.g. \"until\", \"while\" or \"for\").
1111 If the do is on a line by itself, then `sh-indent-after-do' is used instead."
1112 :type
`(choice ,@ sh-number-or-symbol-list
)
1113 :group
'sh-indentation
)
1116 (defcustom sh-indent-after-done
0
1117 "*How much to indent a statement after a \"done\" keyword.
1118 Normally this is 0, which aligns the \"done\" to the matching
1119 looping construct line.
1120 Setting it non-zero allows you to have the \"do\" statement on a line
1121 by itself and align the done under to do."
1122 :type
`(choice ,@ sh-number-or-symbol-list
)
1123 :group
'sh-indentation
)
1125 (defcustom sh-indent-for-case-label
'+
1126 "*How much to indent a case label statement.
1127 This is relative to the line containing the case statement."
1128 :type
`(choice ,@ sh-number-or-symbol-list
)
1129 :group
'sh-indentation
)
1131 (defcustom sh-indent-for-case-alt
'++
1132 "*How much to indent statements after the case label.
1133 This is relative to the line containing the case statement."
1134 :type
`(choice ,@ sh-number-or-symbol-list
)
1135 :group
'sh-indentation
)
1138 (defcustom sh-indent-for-continuation
'+
1139 "*How much to indent for a continuation statement."
1140 :type
`(choice ,@ sh-number-or-symbol-list
)
1141 :group
'sh-indentation
)
1143 (defcustom sh-indent-after-open
'+
1144 "*How much to indent after a line with an opening parenthesis or brace.
1145 For an open paren after a function `sh-indent-after-function' is used."
1146 :type
`(choice ,@ sh-number-or-symbol-list
)
1147 :group
'sh-indentation
)
1149 (defcustom sh-indent-after-function
'+
1150 "*How much to indent after a function line."
1151 :type
`(choice ,@ sh-number-or-symbol-list
)
1152 :group
'sh-indentation
)
1154 ;; These 2 are for the rc shell:
1156 (defcustom sh-indent-after-switch
'+
1157 "*How much to indent a case statement relative to the switch statement.
1158 This is for the rc shell."
1159 :type
`(choice ,@ sh-number-or-symbol-list
)
1160 :group
'sh-indentation
)
1162 (defcustom sh-indent-after-case
'+
1163 "*How much to indent a statement relative to the case statement.
1164 This is for the rc shell."
1165 :type
`(choice ,@ sh-number-or-symbol-list
)
1166 :group
'sh-indentation
)
1168 ;; Internal use - not designed to be changed by the user:
1170 (defun sh-mkword-regexpr (word)
1171 "Make a regexp which matches WORD as a word.
1172 This specifically excludes an occurrence of WORD followed by
1173 punctuation characters like '-'."
1174 (concat word
"\\([^-a-z0-9_]\\|$\\)"))
1176 (defconst sh-re-done
(sh-mkword-regexpr "done"))
1179 (defconst sh-kws-for-done
1180 '((sh .
( "while" "until" "for" ) )
1181 (bash .
( "while" "until" "for" "select" ) )
1182 (ksh88 .
( "while" "until" "for" "select" ) )
1183 (zsh .
( "while" "until" "for" "repeat" "select" ) ) )
1184 "Which keywords can match the word `done' in this shell.")
1187 (defconst sh-indent-supported
1191 "Shell types that shell indenting can do something with.")
1193 (defvar sh-indent-supported-here nil
1194 "Non-nil if we support indentation for the current buffer's shell type.")
1196 (defconst sh-var-list
1198 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1199 sh-indent-after-do sh-indent-after-done
1200 sh-indent-after-else
1202 sh-indent-after-loop-construct
1203 sh-indent-after-open
1205 sh-indent-for-case-alt
1206 sh-indent-for-case-label
1207 sh-indent-for-continuation
1214 "A list of variables used by script mode to control indentation.
1215 This list is used when switching between buffer-local and global
1216 values of variables, and for the commands using indentation styles.")
1218 (defvar sh-make-vars-local t
1219 "*Controls whether indentation variables are local to the buffer.
1220 If non-nil, indentation variables are made local initially.
1221 If nil, you can later make the variables local by invoking
1222 command `sh-make-vars-local'.
1223 The default is t because I assume that in one Emacs session one is
1224 frequently editing existing scripts with different styles.")
1227 ;; mode-command and utility functions
1230 (put 'sh-mode
'mode-class
'special
)
1234 "Major mode for editing shell scripts.
1235 This mode works for many shells, since they all have roughly the same syntax,
1236 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1237 Unless the file's magic number indicates the shell, your usual shell is
1238 assumed. Since filenames rarely give a clue, they are not further analyzed.
1240 This mode adapts to the variations between shells (see `sh-set-shell') by
1241 means of an inheritance based feature lookup (see `sh-feature'). This
1242 mechanism applies to all variables (including skeletons) that pertain to
1243 shell-specific features.
1245 The default style of this mode is that of Rosenblatt's Korn shell book.
1246 The syntax of the statements varies with the shell being used. The
1247 following commands are available, based on the current shell's syntax:
1249 \\[sh-case] case statement
1251 \\[sh-function] function definition
1252 \\[sh-if] if statement
1253 \\[sh-indexed-loop] indexed loop from 1 to n
1254 \\[sh-while-getopts] while getopts loop
1255 \\[sh-repeat] repeat loop
1256 \\[sh-select] select loop
1257 \\[sh-until] until loop
1258 \\[sh-while] while loop
1260 For sh and rc shells indentation commands are:
1261 \\[sh-show-indent] Show the variable controlling this line's indentation.
1262 \\[sh-set-indent] Set then variable controlling this line's indentation.
1263 \\[sh-learn-line-indent] Change the indentation variable so this line
1264 would indent to the way it currently is.
1265 \\[sh-learn-buffer-indent] Set the indentation variables so the
1266 buffer indents as it currently is indented.
1269 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1270 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
1271 \\[sh-end-of-command] Go to end of successive commands.
1272 \\[sh-beginning-of-command] Go to beginning of successive commands.
1273 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1274 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1276 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
1278 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1280 If you generally program a shell different from your login shell you can
1281 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1282 indicate what shell it is use `sh-alias-alist' to translate.
1284 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1285 with your script for an edit-interpret-debug cycle."
1287 (kill-all-local-variables)
1288 (setq major-mode
'sh-mode
1289 mode-name
"Shell-script")
1290 (use-local-map sh-mode-map
)
1291 (make-local-variable 'skeleton-end-hook
)
1292 (make-local-variable 'paragraph-start
)
1293 (make-local-variable 'paragraph-separate
)
1294 (make-local-variable 'comment-start
)
1295 (make-local-variable 'comment-start-skip
)
1296 (make-local-variable 'require-final-newline
)
1297 (make-local-variable 'sh-header-marker
)
1298 (make-local-variable 'sh-shell-file
)
1299 (make-local-variable 'sh-shell
)
1300 (make-local-variable 'skeleton-pair-alist
)
1301 (make-local-variable 'skeleton-pair-filter
)
1302 (make-local-variable 'comint-dynamic-complete-functions
)
1303 (make-local-variable 'comint-prompt-regexp
)
1304 (make-local-variable 'font-lock-defaults
)
1305 (make-local-variable 'skeleton-filter
)
1306 (make-local-variable 'skeleton-newline-indent-rigidly
)
1307 (make-local-variable 'sh-shell-variables
)
1308 (make-local-variable 'sh-shell-variables-initialized
)
1309 (make-local-variable 'imenu-generic-expression
)
1310 (make-local-variable 'sh-indent-supported-here
)
1311 (setq skeleton-end-hook
(lambda ()
1312 (or (eolp) (newline) (indent-relative)))
1313 paragraph-start
(concat page-delimiter
"\\|$")
1314 paragraph-separate paragraph-start
1316 comint-dynamic-complete-functions sh-dynamic-complete-functions
1317 ;; we can't look if previous line ended with `\'
1318 comint-prompt-regexp
"^[ \t]*"
1320 `((sh-font-lock-keywords
1321 sh-font-lock-keywords-1 sh-font-lock-keywords-2
)
1323 ((?
/ .
"w") (?~ .
"w") (?. .
"w") (?- .
"w") (?_ .
"w")) nil
1324 (font-lock-syntactic-keywords . sh-font-lock-syntactic-keywords
)
1325 (font-lock-syntactic-face-function
1326 . sh-font-lock-syntactic-face-function
))
1327 skeleton-pair-alist
'((?
` _ ?
`))
1328 skeleton-pair-filter
'sh-quoted-p
1329 skeleton-further-elements
'((< '(- (min sh-indentation
1330 (current-column)))))
1331 skeleton-filter
'sh-feature
1332 skeleton-newline-indent-rigidly t
1333 sh-indent-supported-here nil
)
1334 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
1335 ;; Parse or insert magic number for exec, and set all variables depending
1336 ;; on the shell thus determined.
1339 (goto-char (point-min))
1340 (cond ((looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
1342 ((and buffer-file-name
1343 (string-match "\\.m?spec$" buffer-file-name
))
1345 (sh-set-shell (or interpreter sh-shell-file
) nil nil
))
1346 (run-hooks 'sh-mode-hook
))
1349 (defalias 'shell-script-mode
'sh-mode
)
1352 (defun sh-font-lock-keywords (&optional keywords
)
1353 "Function to get simple fontification based on `sh-font-lock-keywords'.
1354 This adds rules for comments and assignments."
1355 (sh-feature sh-font-lock-keywords
1356 (when (stringp (sh-feature sh-assignment-regexp
))
1358 `((,(sh-feature sh-assignment-regexp
)
1359 1 font-lock-variable-name-face
)
1363 (defun sh-font-lock-keywords-1 (&optional builtins
)
1364 "Function to get better fontification including keywords."
1365 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1366 (regexp-opt (sh-feature sh-leading-keywords
) t
)
1368 (regexp-opt (append (sh-feature sh-leading-keywords
)
1369 (sh-feature sh-other-keywords
))
1371 (sh-font-lock-keywords
1373 `((,(concat keywords
"[ \t]+\\)?"
1374 (regexp-opt (sh-feature sh-builtins
) t
)
1376 (2 font-lock-keyword-face nil t
)
1377 (6 font-lock-builtin-face
))
1378 ,@(sh-feature sh-font-lock-keywords-2
)))
1379 (,(concat keywords
"\\)\\>")
1380 2 font-lock-keyword-face
)
1381 ,@(sh-feature sh-font-lock-keywords-1
)))))
1383 (defun sh-font-lock-keywords-2 ()
1384 "Function to get better fontification including keywords and builtins."
1385 (sh-font-lock-keywords-1 t
))
1388 (defvar sh-regexp-for-done nil
1389 "A buffer-local regexp to match opening keyword for done.")
1391 (defvar sh-kw-alist nil
1392 "A buffer-local, since it is shell-type dependent, list of keywords.")
1394 ;; ( key-word first-on-this on-prev-line )
1395 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1396 ;; having 3 elements:
1398 ;; a rule to check when the keyword appears on "this" line
1399 ;; a rule to check when the keyword appears on "the previous" line
1400 ;; The keyword is usually a string and is the first word on a line.
1401 ;; If this keyword appears on the line whose indentation is to be
1402 ;; calculated, the rule in element 2 is called. If this returns
1403 ;; non-zero, the resulting point (which may be changed by the rule)
1404 ;; is used as the default indentation.
1405 ;; If it returned false or the keyword was not found in the table,
1406 ;; then the keyword from the previous line is looked up and the rule
1407 ;; in element 3 is called. In this case, however,
1408 ;; `sh-get-indent-info' does not stop but may keep going and test
1409 ;; other keywords against rules in element 3. This is because the
1410 ;; preceding line could have, for example, an opening "if" and an
1411 ;; opening "while" keyword and we need to add the indentation offsets
1416 ("if" nil sh-handle-prev-if
)
1417 ("elif" sh-handle-this-else sh-handle-prev-else
)
1418 ("else" sh-handle-this-else sh-handle-prev-else
)
1419 ("fi" sh-handle-this-fi sh-handle-prev-fi
)
1420 ("then" sh-handle-this-then sh-handle-prev-then
)
1421 ("(" nil sh-handle-prev-open
)
1422 ("{" nil sh-handle-prev-open
)
1423 ("[" nil sh-handle-prev-open
)
1424 ("}" sh-handle-this-close nil
)
1425 (")" sh-handle-this-close nil
)
1426 ("]" sh-handle-this-close nil
)
1427 ("case" nil sh-handle-prev-case
)
1428 ("esac" sh-handle-this-esac sh-handle-prev-esac
)
1429 (case-label nil sh-handle-after-case-label
) ;; ???
1430 (";;" nil sh-handle-prev-case-alt-end
) ;; ???
1431 ("done" sh-handle-this-done sh-handle-prev-done
)
1432 ("do" sh-handle-this-do sh-handle-prev-do
))
1434 ;; Note: we don't need specific stuff for bash and zsh shells;
1435 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1436 ;; these shells use.
1438 ("{" nil sh-handle-prev-open
)
1439 ("}" sh-handle-this-close nil
)
1440 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case
))))
1443 (defun sh-set-shell (shell &optional no-query-flag insert-flag
)
1444 "Set this buffer's shell to SHELL (a string).
1445 When used interactively, insert the proper starting #!-line,
1446 and make the visited file executable via `executable-set-magic',
1447 perhaps querying depending on the value of `executable-query'.
1449 When this function is called noninteractively, INSERT-FLAG (the third
1450 argument) controls whether to insert a #!-line and think about making
1451 the visited file executable, and NO-QUERY-FLAG (the second argument)
1452 controls whether to query about making the visited file executable.
1454 Calls the value of `sh-set-shell-hook' if set."
1455 (interactive (list (completing-read (format "Shell \(default %s\): "
1457 interpreter-mode-alist
1458 (lambda (x) (eq (cdr x
) 'sh-mode
))
1459 nil nil nil sh-shell-file
)
1460 (eq executable-query
'function
)
1462 (if (string-match "\\.exe\\'" shell
)
1463 (setq shell
(substring shell
0 (match-beginning 0))))
1464 (setq sh-shell
(intern (file-name-nondirectory shell
))
1465 sh-shell
(or (cdr (assq sh-shell sh-alias-alist
))
1469 (executable-set-magic shell
(sh-feature sh-shell-arg
)
1470 no-query-flag insert-flag
)))
1471 (setq require-final-newline
(sh-feature sh-require-final-newline
)
1472 ;;; local-abbrev-table (sh-feature sh-abbrevs)
1473 comment-start-skip
"#+[\t ]*"
1474 mode-line-process
(format "[%s]" sh-shell
)
1475 sh-shell-variables nil
1476 sh-shell-variables-initialized nil
1477 imenu-generic-expression
(sh-feature sh-imenu-generic-expression
)
1478 imenu-case-fold-search nil
)
1479 (set-syntax-table (or (sh-feature sh-mode-syntax-table
)
1480 (standard-syntax-table)))
1481 (dolist (var (sh-feature sh-variables
))
1482 (sh-remember-variable var
))
1483 (make-local-variable 'indent-line-function
)
1484 (if (setq sh-indent-supported-here
(sh-feature sh-indent-supported
))
1486 (message "Setting up indent for shell type %s" sh-shell
)
1487 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
1488 (set (make-local-variable 'sh-kw-alist
) (sh-feature sh-kw
))
1489 (let ((regexp (sh-feature sh-kws-for-done
)))
1491 (set (make-local-variable 'sh-regexp-for-done
)
1492 (sh-mkword-regexpr (regexp-opt regexp t
)))))
1493 (message "setting up indent stuff")
1494 ;; sh-mode has already made indent-line-function local
1495 ;; but do it in case this is called before that.
1496 (setq indent-line-function
'sh-indent-line
)
1497 (if sh-make-vars-local
1498 (sh-make-vars-local))
1499 (message "Indentation setup for shell type %s" sh-shell
))
1500 (message "No indentation for this shell type.")
1501 (setq indent-line-function
'sh-basic-indent-line
))
1502 (run-hooks 'sh-set-shell-hook
))
1506 (defun sh-feature (list &optional function
)
1507 "Index ALIST by the current shell.
1508 If ALIST isn't a list where every element is a cons, it is returned as is.
1509 Else indexing follows an inheritance logic which works in two ways:
1511 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1512 the alist contains no value for the current shell.
1513 The ultimate default is always `sh'.
1515 - If the value thus looked up is a list starting with `eval' its `cdr' is
1516 first evaluated. If that is also a list and the first argument is a
1517 symbol in ALIST it is not evaluated, but rather recursively looked up in
1518 ALIST to allow the function called to define the value for one shell to be
1519 derived from another shell. While calling the function, is the car of the
1520 alist element is the current shell.
1521 The value thus determined is physically replaced into the alist.
1523 Optional FUNCTION is applied to the determined value and the result is cached
1525 (or (if (consp list
)
1527 (while (and l
(consp (car l
)))
1531 (cdr (assoc (setq function
(cons sh-shell function
)) list
)))
1532 (let ((sh-shell sh-shell
)
1534 (while (and sh-shell
1535 (not (setq elt
(assq sh-shell list
))))
1536 (setq sh-shell
(cdr (assq sh-shell sh-ancestor-alist
))))
1537 ;; If the shell is not known, treat it as sh.
1539 (setq elt
(assq 'sh list
)))
1540 (if (and (consp (setq val
(cdr elt
)))
1541 (eq (car val
) 'eval
))
1544 (eval (if (consp (setq val
(cdr val
)))
1545 (let ((sh-shell (car (cdr val
))))
1546 (if (assq sh-shell list
)
1549 (sh-feature list
))))
1554 (list (cons function
1555 (setq sh-shell
(car function
)
1556 val
(funcall (cdr function
) val
))))))
1561 ;; I commented this out because nobody calls it -- rms.
1562 ;;(defun sh-abbrevs (ancestor &rest list)
1563 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
1564 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1565 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1566 ;;according to the remaining arguments NAMEi EXPANSIONi ...
1567 ;;EXPANSION may be either a string or a skeleton command."
1568 ;; (or (if (boundp sh-shell)
1569 ;; (symbol-value sh-shell))
1571 ;; (if (listp ancestor)
1572 ;; (nconc list ancestor))
1573 ;; (define-abbrev-table sh-shell ())
1574 ;; (if (vectorp ancestor)
1575 ;; (mapatoms (lambda (atom)
1577 ;; (define-abbrev (symbol-value sh-shell)
1578 ;; (symbol-name atom)
1579 ;; (symbol-value atom)
1580 ;; (symbol-function atom))))
1583 ;; (define-abbrev (symbol-value sh-shell)
1585 ;; (if (stringp (car (cdr list)))
1588 ;; (if (symbolp (car (cdr list)))
1589 ;; (car (cdr list))))
1590 ;; (setq list (cdr (cdr list)))))
1591 ;; (symbol-value sh-shell)))
1594 (defun sh-mode-syntax-table (table &rest list
)
1595 "Copy TABLE and set syntax for successive CHARs according to strings S."
1596 (setq table
(copy-syntax-table table
))
1598 (modify-syntax-entry (pop list
) (pop list
) table
))
1601 (defun sh-append (ancestor &rest list
)
1602 "Return list composed of first argument (a list) physically appended to rest."
1603 (nconc list ancestor
))
1606 (defun sh-modify (skeleton &rest list
)
1607 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1608 (setq skeleton
(copy-sequence skeleton
))
1610 (setcar (or (nthcdr (car list
) skeleton
)
1611 (error "Index %d out of bounds" (car list
)))
1613 (setq list
(nthcdr 2 list
)))
1617 (defun sh-basic-indent-line ()
1618 "Indent a line for Sh mode (shell script mode).
1619 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1620 Lines containing only comments are considered empty."
1622 (let ((previous (save-excursion
1623 (while (and (progn (beginning-of-line)
1627 (back-to-indentation)
1629 (eq (following-char) ?
#)))))
1633 (indent-to (if (eq this-command
'newline-and-indent
)
1635 (if (< (current-column)
1636 (setq current
(progn (back-to-indentation)
1638 (if (eolp) previous
0)
1639 (delete-region (point)
1640 (progn (beginning-of-line) (point)))
1642 (max previous
(* (1+ (/ current sh-indentation
))
1644 (* (1+ (/ current sh-indentation
)) sh-indentation
))))))
1645 (if (< (current-column) (current-indentation))
1646 (skip-chars-forward " \t"))))
1649 (defun sh-execute-region (start end
&optional flag
)
1650 "Pass optional header and region to a subshell for noninteractive execution.
1651 The working directory is that of the buffer, and only environment variables
1652 are already set which is why you can mark a header within the script.
1654 With a positive prefix ARG, instead of sending region, define header from
1655 beginning of buffer to point. With a negative prefix ARG, instead of sending
1656 region, clear header."
1657 (interactive "r\nP")
1659 (setq sh-header-marker
(if (> (prefix-numeric-value flag
) 0)
1661 (if sh-header-marker
1663 (let (buffer-undo-list)
1664 (goto-char sh-header-marker
)
1665 (append-to-buffer (current-buffer) start end
)
1666 (shell-command-on-region (point-min)
1667 (setq end
(+ sh-header-marker
1670 (delete-region sh-header-marker end
)))
1671 (shell-command-on-region start end
(concat sh-shell-file
" -")))))
1674 (defun sh-remember-variable (var)
1675 "Make VARIABLE available for future completing reads in this buffer."
1676 (or (< (length var
) sh-remember-variable-min
)
1678 (assoc var sh-shell-variables
)
1679 (push (cons var var
) sh-shell-variables
))
1684 (defun sh-quoted-p ()
1685 "Is point preceded by an odd number of backslashes?"
1686 (eq -
1 (%
(save-excursion (skip-chars-backward "\\\\")) 2)))
1688 ;; Indentation stuff.
1689 (defun sh-must-support-indent ()
1690 "*Signal an error if the shell type for this buffer is not supported.
1691 Also, the buffer must be in Shell-script mode."
1692 (unless sh-indent-supported-here
1693 (error "This buffer's shell does not support indentation through Emacs")))
1695 (defun sh-make-vars-local ()
1696 "Make the indentation variables local to this buffer.
1697 Normally they already are local. This command is provided in case
1698 variable `sh-make-vars-local' has been set to nil.
1700 To revert all these variables to the global values, use
1701 command `sh-reset-indent-vars-to-global-values'."
1703 (mapcar 'make-local-variable sh-var-list
)
1704 (message "Indentation variable are now local."))
1706 (defun sh-reset-indent-vars-to-global-values ()
1707 "Reset local indentation variables to the global values.
1708 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1710 (mapcar 'kill-local-variable sh-var-list
)
1711 (if sh-make-vars-local
1712 (mapcar 'make-local-variable sh-var-list
)))
1715 ;; Theoretically these are only needed in shell and derived modes.
1716 ;; However, the routines which use them are only called in those modes.
1717 (defconst sh-special-keywords
"then\\|do")
1719 (defun sh-help-string-for-variable (var)
1720 "Construct a string for `sh-read-variable' when changing variable VAR ."
1721 (let ((msg (documentation-property var
'variable-documentation
))
1723 (unless (memq var
'(sh-first-lines-indent sh-indent-comment
))
1726 You can enter a number (positive to increase indentation,
1727 negative to decrease indentation, zero for no change to indentation).
1729 Or, you can enter one of the following symbols which are relative to
1730 the value of variable `sh-basic-offset'
1731 which in this buffer is currently %s.
1735 (mapconcat (lambda (x)
1736 (nth (1- (length x
)) x
))
1737 sh-symbol-list
"\n\t"))))
1739 ;; The following shows the global not the local value!
1740 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1743 (defun sh-read-variable (var)
1744 "Read a new value for indentation variable VAR."
1745 (interactive "*variable? ") ;; to test
1746 (let ((minibuffer-help-form `(sh-help-string-for-variable
1749 (setq val
(read-from-minibuffer
1750 (format "New value for %s (press %s for help): "
1751 var
(single-key-description help-char
))
1752 (format "%s" (symbol-value var
))
1758 (defun sh-in-comment-or-string (start)
1759 "Return non-nil if START is in a comment or string."
1761 (let ((state (syntax-ppss start
)))
1762 (or (nth 3 state
) (nth 4 state
)))))
1764 (defun sh-goto-matching-if ()
1765 "Go to the matching if for a fi.
1766 This handles nested if..fi pairs."
1767 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1769 (goto-char found
))))
1772 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1773 ;; line whose indentation is being handled contain XXX;
1774 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
1776 (defun sh-handle-prev-if ()
1777 (list '(+ sh-indent-after-if
)))
1779 (defun sh-handle-this-else ()
1780 (if (sh-goto-matching-if)
1781 ;; (list "aligned to if")
1782 (list "aligned to if" '(+ sh-indent-for-else
))
1786 (defun sh-handle-prev-else ()
1787 (if (sh-goto-matching-if)
1788 (list '(+ sh-indent-after-if
))
1791 (defun sh-handle-this-fi ()
1792 (if (sh-goto-matching-if)
1793 (list "aligned to if" '(+ sh-indent-for-fi
))
1797 (defun sh-handle-prev-fi ()
1798 ;; Why do we have this rule? Because we must go back to the if
1799 ;; to get its indent. We may continue back from there.
1800 ;; We return nil because we don't have anything to add to result,
1801 ;; the side affect of setting align-point is all that matters.
1802 ;; we could return a comment (a string) but I can't think of a good one...
1803 (sh-goto-matching-if)
1806 (defun sh-handle-this-then ()
1807 (let ((p (sh-goto-matching-if)))
1809 (list '(+ sh-indent-for-then
))
1812 (defun sh-handle-prev-then ()
1813 (let ((p (sh-goto-matching-if)))
1815 (list '(+ sh-indent-after-if
))
1818 (defun sh-handle-prev-open ()
1820 (let ((x (sh-prev-stmt)))
1825 (looking-at "function\\b")
1826 (looking-at "\\s-*\\S-+\\s-*()")
1828 (list '(+ sh-indent-after-function
))
1829 (list '(+ sh-indent-after-open
)))
1832 (defun sh-handle-this-close ()
1833 (forward-char 1) ;; move over ")"
1834 (if (sh-safe-forward-sexp -
1)
1835 (list "aligned to opening paren")))
1837 (defun sh-goto-matching-case ()
1838 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
1839 (if found
(goto-char found
))))
1841 (defun sh-handle-prev-case ()
1842 ;; This is typically called when point is on same line as a case
1843 ;; we shouldn't -- and can't find prev-case
1844 (if (looking-at ".*\\<case\\>")
1845 (list '(+ sh-indent-for-case-label
))
1846 (error "We don't seem to be on a line with a case"))) ;; debug
1848 (defun sh-handle-this-esac ()
1849 (if (sh-goto-matching-case)
1850 (list "aligned to matching case")))
1852 (defun sh-handle-prev-esac ()
1853 (if (sh-goto-matching-case)
1854 (list "matching case")))
1856 (defun sh-handle-after-case-label ()
1857 (if (sh-goto-matching-case)
1858 (list '(+ sh-indent-for-case-alt
))))
1860 (defun sh-handle-prev-case-alt-end ()
1861 (if (sh-goto-matching-case)
1862 (list '(+ sh-indent-for-case-label
))))
1864 (defun sh-safe-forward-sexp (&optional arg
)
1865 "Try and do a `forward-sexp', but do not error.
1866 Return new point if successful, nil if an error occurred."
1869 (forward-sexp (or arg
1))
1870 (point)) ;; return point if successful
1872 (sh-debug "oops!(1) %d" (point))
1873 nil
))) ;; return nil if fail
1875 (defun sh-goto-match-for-done ()
1876 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done
1)))
1878 (goto-char found
))))
1880 (defun sh-handle-this-done ()
1881 (if (sh-goto-match-for-done)
1882 (list "aligned to do stmt" '(+ sh-indent-for-done
))))
1884 (defun sh-handle-prev-done ()
1885 (if (sh-goto-match-for-done)
1886 (list "previous done")))
1888 (defun sh-handle-this-do ()
1889 (if (sh-goto-match-for-done)
1890 (list '(+ sh-indent-for-do
))))
1892 (defun sh-handle-prev-do ()
1900 (sh-goto-match-for-done))
1901 (sh-debug "match for done found on THIS line")
1902 (list '(+ sh-indent-after-loop-construct
)))
1903 ((sh-goto-match-for-done)
1904 (sh-debug "match for done found on PREV line")
1905 (list '(+ sh-indent-after-do
)))
1907 (message "match for done NOT found")
1911 (defun sh-find-prev-switch ()
1912 "Find the line for the switch keyword matching this line's case keyword."
1913 (re-search-backward "\\<switch\\>" nil t
))
1915 (defun sh-handle-this-rc-case ()
1916 (if (sh-find-prev-switch)
1917 (list '(+ sh-indent-after-switch
))
1918 ;; (list '(+ sh-indent-for-case-label))
1921 (defun sh-handle-prev-rc-case ()
1922 (list '(+ sh-indent-after-case
)))
1924 (defun sh-check-rule (n thing
)
1925 (let ((rule (nth n
(assoc thing sh-kw-alist
)))
1929 (setq val
(funcall rule
))
1930 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
1931 n thing
(point) rule val
)))
1935 (defun sh-get-indent-info ()
1936 "Return indent-info for this line.
1937 This is a list. nil means the line is to be left as is.
1938 Otherwise it contains one or more of the following sublists:
1939 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
1940 relative to. If present, this is always the first of the
1941 sublists. The indentation of the line in question is
1942 derived from the indentation of this point, possibly
1943 modified by subsequent sublists.
1945 \(- VAR\) Get the value of variable VAR and add to or subtract from
1946 the indentation calculated so far.
1947 \(= VAR\) Get the value of variable VAR and *replace* the
1948 indentation with its value. This only occurs for
1949 special variables such as `sh-indent-comment'.
1950 STRING This is ignored for the purposes of calculating
1951 indentation, it is printed in certain cases to help show
1952 what the indentation is based on."
1953 ;; See comments before `sh-kw'.
1955 (let ((have-result nil
)
1963 ;; Note: setting result to t means we are done and will return nil.
1964 ;;(This function never returns just t.)
1966 ((or (and (boundp 'font-lock-string-face
) (not (bobp))
1967 (eq (get-text-property (1- (point)) 'face
)
1968 font-lock-string-face
))
1969 (eq (get-text-property (point) 'face
) sh-heredoc-face
))
1971 (setq have-result t
))
1972 ((looking-at "\\s-*#") ; was (equal this-kw "#")
1974 (setq result t
) ;; return nil if 1st line!
1975 (setq result
(list '(= sh-indent-comment
)))
1976 ;; we still need to get previous line in case
1977 ;; sh-indent-comment is t (indent as normal)
1978 (setq align-point
(sh-prev-line nil
))
1979 (setq have-result nil
)
1984 ;; Continuation lines are handled specially
1985 (if (sh-this-is-a-continuation)
1987 ;; We assume the line being continued is already
1988 ;; properly indented...
1989 ;; (setq prev-line-end (sh-prev-line))
1990 (setq align-point
(sh-prev-line nil
))
1991 (setq result
(list '(+ sh-indent-for-continuation
)))
1992 (setq have-result t
))
1994 (skip-chars-forward " \t")
1995 (setq this-kw
(sh-get-kw)))
1997 ;; Handle "this" keyword: first word on the line we're
1998 ;; calculating indentation info for.
2000 (if (setq val
(sh-check-rule 1 this-kw
))
2002 (setq align-point
(point))
2004 "this - setting align-point to %d" align-point
)
2005 (setq result
(append result val
))
2006 (setq have-result t
)
2007 ;; set prev-line to continue processing remainder
2008 ;; of this line as a previous line
2009 (setq prev-line-end
(point))
2013 (setq prev-line-end
(sh-prev-line 'end
)))
2017 ;; We start off at beginning of this line.
2018 ;; Scan previous statements while this is <=
2019 ;; start of previous line.
2020 (setq start
(point)) ;; for debug only
2021 (goto-char prev-line-end
)
2023 (while (and x
(setq x
(sh-prev-thing)))
2024 (sh-debug "at %d x is: %s result is: %s" (point) x result
)
2027 (equal (get-text-property (1- (point)) 'syntax-table
)
2029 (sh-debug "Case label) here")
2030 (setq x
'case-label
)
2031 (if (setq val
(sh-check-rule 2 x
))
2033 (setq result
(append result val
))
2034 (setq align-point
(point))))
2036 (skip-chars-forward "[a-z0-9]*?")
2038 ((string-match "[])}]" x
)
2039 (setq x
(sh-safe-forward-sexp -
1))
2042 (setq align-point
(point))
2043 (setq result
(append result
2044 (list "aligned to opening paren")))
2046 ((string-match "[[({]" x
)
2047 (sh-debug "Checking special thing: %s" x
)
2048 (if (setq val
(sh-check-rule 2 x
))
2049 (setq result
(append result val
)))
2051 (setq align-point
(point)))
2052 ((string-match "[\"'`]" x
)
2053 (sh-debug "Skipping back for %s" x
)
2055 (setq x
(sh-safe-forward-sexp -
1)))
2057 (sh-debug "Checking string %s at %s" x
(point))
2058 (if (setq val
(sh-check-rule 2 x
))
2059 ;; (or (eq t (car val))
2060 ;; (eq t (car (car val))))
2061 (setq result
(append result val
)))
2062 ;; not sure about this test Wed Jan 27 23:48:35 1999
2063 (setq align-point
(point))
2067 (error "Don't know what to do with %s" x
))
2070 (sh-debug "result is %s" result
)
2072 (sh-debug "No prev line!")
2073 (sh-debug "result: %s align-point: %s" result align-point
)
2077 ;; was: (setq result (append result (list (list t align-point))))
2078 (setq result
(append (list (list t align-point
)) result
))
2080 (sh-debug "result is now: %s" result
)
2084 (setq result
(list (list t prev-line-end
)))
2085 (setq result
(list (list '= 'sh-first-lines-indent
)))
2090 (sh-debug "result is: %s" result
)
2096 (defun sh-get-indent-var-for-line (&optional info
)
2097 "Return the variable controlling indentation for this line.
2098 If there is not [just] one such variable, return a string
2099 indicating the problem.
2100 If INFO is supplied it is used, else it is calculated."
2106 (setq info
(sh-get-indent-info)))
2108 (setq result
"this line to be left as is")
2109 (while (and info
(null result
))
2110 (setq elt
(car info
))
2116 (error "sh-get-indent-var-for-line invalid elt: %s" elt
))
2120 ((symbolp (setq sym
(nth 1 elt
)))
2121 ;; A bit of a kludge - when we see the sh-indent-comment
2122 ;; ignore other variables. Otherwise it is tricky to
2123 ;; "learn" the comment indentation.
2124 (if (eq var
'sh-indent-comment
)
2128 "this line is controlled by more than 1 variable.")
2131 (error "sh-get-indent-var-for-line invalid list elt: %s" elt
)))
2132 (setq info
(cdr info
))
2137 (setq result reason
))
2139 ;; e.g. just had (t POS)
2140 (setq result
"line has default indentation"))
2145 ;; Finding the previous line isn't trivial.
2146 ;; We must *always* go back one more and see if that is a continuation
2147 ;; line -- it is the PREVIOUS line which is continued, not the one
2149 ;; Also, we want to treat a whole "here document" as one big line,
2150 ;; because we may want to a align to the beginning of it.
2153 ;; - go back to previous non-empty line
2154 ;; - if this is in a here-document, go to the beginning of it
2155 ;; - while previous line is continued, go back one line
2156 (defun sh-prev-line (&optional end
)
2157 "Back to end of previous non-comment non-empty line.
2158 Go to beginning of logical line unless END is non-nil, in which case
2159 we go to the end of the previous line and do not check for continuations."
2162 (forward-comment (- (point-max)))
2163 (unless end
(beginning-of-line))
2164 (when (and (not (bobp))
2165 (equal (get-text-property (1- (point)) 'face
)
2167 (let ((p1 (previous-single-property-change (1- (point)) 'face
)))
2172 (beginning-of-line)))))
2174 ;; we must check previous lines to see if they are continuation lines
2175 ;; if so, we must return position of first of them
2176 (while (and (sh-this-is-a-continuation)
2177 (>= 0 (forward-line -
1))))
2179 (skip-chars-forward " \t"))
2183 (defun sh-prev-stmt ()
2184 "Return the address of the previous stmt or nil."
2185 ;; This is used when we are trying to find a matching keyword.
2186 ;; Searching backward for the keyword would certainly be quicker, but
2187 ;; it is hard to remove "false matches" -- such as if the keyword
2188 ;; appears in a string or quote. This way is slower, but (I think) safer.
2195 (skip-chars-backward " \t;|&({[")
2196 (while (and (not found
)
2199 ;; Do a backward-sexp if possible, else backup bit by bit...
2200 (if (sh-safe-forward-sexp -
1)
2202 (if (looking-at sh-special-keywords
)
2207 ;; backward-sexp failed
2208 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2211 (let ((back (sh-prev-line nil
)))
2214 (setq going nil
)))))
2216 (skip-chars-backward " \t")
2217 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2218 (eq (char-before) ?\
;)
2219 (looking-at "\\s-*[|&]"))
2220 (setq found
(point)))))
2225 (skip-chars-forward " \t|&({[")
2226 (setq found
(point))))
2227 (if (>= (point) start
)
2229 (debug "We didn't move!")
2232 (sh-debug "Did not find prev stmt.")))
2236 (defun sh-get-word ()
2237 "Get a shell word skipping whitespace from point."
2239 (skip-chars-forward "\t ")
2240 (let ((start (point)))
2242 (if (looking-at "[\"'`]")
2243 (sh-safe-forward-sexp)
2244 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2245 (> (skip-chars-forward "-_a-zA-Z\$0-9") 0)
2247 (buffer-substring start
(point))
2250 (defun sh-prev-thing ()
2251 "Return the previous thing this logical line."
2252 ;; This is called when `sh-get-indent-info' is working backwards on
2253 ;; the previous line(s) finding what keywords may be relevant for
2254 ;; indenting. It moves over sexps if possible, and will stop
2255 ;; on a ; and at the beginning of a line if it is not a continuation
2258 ;; Added a kludge for ";;"
2259 ;; Possible return values:
2261 ;; a string - possibly a keyword
2269 (if (sh-this-is-a-continuation)
2270 (setq min-point
(sh-prev-line nil
))
2273 (setq min-point
(point))))
2275 (skip-chars-backward " \t;")
2276 (unless (looking-at "\\s-*;;")
2277 (skip-chars-backward "^)}];\"'`({[")
2278 (setq c
(char-before))))
2279 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2280 (point) c start min-point
)
2281 (if (< (point) min-point
)
2282 (error "point %d < min-point %d" (point) min-point
))
2284 ((looking-at "\\s-*;;")
2285 ;; (message "Found ;; !")
2291 ;; skip forward over white space newline and \ at eol
2292 (skip-chars-forward " \t\n\\\\")
2293 (sh-debug "Now at %d start=%d" (point) start
)
2294 (if (>= (point) start
)
2296 (sh-debug "point: %d >= start: %d" (point) start
)
2301 ;; c -- return a string
2307 (defun sh-this-is-a-continuation ()
2308 "Return non-nil if current line is a continuation of previous line."
2310 (and (zerop (forward-line -
1))
2311 (looking-at ".*\\\\$")
2312 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2315 (defun sh-get-kw (&optional where and-move
)
2316 "Return first word of line from WHERE.
2317 If AND-MOVE is non-nil then move to end of word."
2318 (let ((start (point)))
2322 (buffer-substring (point)
2323 (progn (skip-chars-forward "^ \t\n;")(point)))
2325 (goto-char start
)))))
2327 (defun sh-find-prev-matching (open close
&optional depth
)
2328 "Find a matching token for a set of opening and closing keywords.
2329 This takes into account that there may be nested open..close pairings.
2330 OPEN and CLOSE are regexps denoting the tokens to be matched.
2331 Optional parameter DEPTH (usually 1) says how many to look for."
2332 (let ((parse-sexp-ignore-comments t
)
2334 (setq depth
(or depth
1))
2340 (setq prev
(sh-prev-stmt)))
2343 (if (looking-at "\\\\\n")
2346 (skip-chars-forward " \t")))
2349 (setq depth
(1- depth
))
2350 (sh-debug "found open at %d - depth = %d" (point) depth
))
2352 (setq depth
(1+ depth
))
2353 (sh-debug "found close - depth = %d" depth
))
2363 (defun sh-var-value (var &optional ignore-error
)
2364 "Return the value of variable VAR, interpreting symbols.
2365 It can also return t or nil.
2366 If an illegal value is found, throw an error unless Optional argument
2367 IGNORE-ERROR is non-nil."
2368 (let ((val (symbol-value var
)))
2379 (- sh-basic-offset
))
2381 (* 2 sh-basic-offset
))
2383 (* 2 (- sh-basic-offset
)))
2385 (/ sh-basic-offset
2))
2387 (/ (- sh-basic-offset
) 2))
2391 (message "Don't know how to handle %s's value of %s" var val
)
2393 (error "Don't know how to handle %s's value of %s" var val
))
2396 (defun sh-set-var-value (var value
&optional no-symbol
)
2397 "Set variable VAR to VALUE.
2398 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2399 can be represented by a symbol then do so."
2403 ((= value sh-basic-offset
)
2405 ((= value
(- sh-basic-offset
))
2407 ((eq value
(* 2 sh-basic-offset
))
2409 ((eq value
(* 2 (- sh-basic-offset
)))
2411 ((eq value
(/ sh-basic-offset
2))
2413 ((eq value
(/ (- sh-basic-offset
) 2))
2420 (defun sh-calculate-indent (&optional info
)
2421 "Return the indentation for the current line.
2422 If INFO is supplied it is used, else it is calculated from current line."
2427 (setq info
(sh-get-indent-info)))
2430 (sh-debug "info: %s ofs=%s" info ofs
)
2431 (setq elt
(car info
))
2433 ((stringp elt
)) ;; do nothing?
2435 (setq a
(car (car info
)))
2436 (setq b
(nth 1 (car info
)))
2441 (setq val
(current-indentation)))
2442 (setq base-value val
))
2444 (setq val
(sh-var-value b
))
2450 ;; set info to nil so we stop immediately
2451 (setq base-value nil ofs nil info nil
))
2452 ((eq val t
) (setq ofs
0)) ;; indent as normal line
2454 ;; The following assume the (t POS) come first!
2455 (setq ofs val base-value
0)
2456 (setq info nil
)))) ;; ? stop now
2457 ((eq a
'+) (setq ofs
(+ ofs val
)))
2458 ((eq a
'-
) (setq ofs
(- ofs val
)))
2460 (error "sh-calculate-indent invalid a a=%s b=%s" a b
))))
2462 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b
))))
2464 (error "sh-calculate-indent invalid elt %s" elt
)))
2465 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2466 a b val base-value ofs
)
2467 (setq info
(cdr info
)))
2469 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs
)
2472 ((or (null base-value
)(null ofs
))
2474 ((and (numberp base-value
)(numberp ofs
))
2475 (sh-debug "base (%d) + ofs (%d) = %d"
2476 base-value ofs
(+ base-value ofs
))
2477 (+ base-value ofs
)) ;; return value
2479 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2484 (defun sh-indent-line ()
2485 "Indent the current line."
2487 (let ((indent (sh-calculate-indent))
2488 (pos (- (point-max) (point))))
2491 (skip-chars-forward " \t")
2492 (indent-line-to indent
)
2493 ;; If initial point was within line's indentation,
2494 ;; position after the indentation. Else stay at same point in text.
2495 (if (> (- (point-max) pos
) (point))
2496 (goto-char (- (point-max) pos
))))))
2499 (defun sh-blink (blinkpos &optional msg
)
2500 "Move cursor momentarily to BLINKPOS and display MSG."
2501 ;; We can get here without it being a number on first line
2502 (if (numberp blinkpos
)
2504 (goto-char blinkpos
)
2506 (sit-for blink-matching-delay
))
2509 (defun sh-show-indent (arg)
2510 "Show the how the currently line would be indented.
2511 This tells you which variable, if any, controls the indentation of
2513 If optional arg ARG is non-null (called interactively with a prefix),
2514 a pop up window describes this variable.
2515 If variable `sh-blink' is non-nil then momentarily go to the line
2516 we are indenting relative to, if applicable."
2518 (sh-must-support-indent)
2519 (let* ((info (sh-get-indent-info))
2520 (var (sh-get-indent-var-for-line info
))
2521 (curr-indent (current-indentation))
2524 (message (setq msg var
))
2525 (setq val
(sh-calculate-indent info
))
2527 (if (eq curr-indent val
)
2528 (setq msg
(format "%s is %s" var
(symbol-value var
)))
2531 (format "%s (%s) would change indent from %d to: %d"
2532 var
(symbol-value var
) curr-indent val
)
2533 (format "%s (%s) would leave line as is"
2534 var
(symbol-value var
)))
2537 (describe-variable var
)))
2539 (let ((info (sh-get-indent-info)))
2540 (if (and info
(listp (car info
))
2541 (eq (car (car info
)) t
))
2542 (sh-blink (nth 1 (car info
)) msg
)
2547 (defun sh-set-indent ()
2548 "Set the indentation for the current line.
2549 If the current line is controlled by an indentation variable, prompt
2550 for a new value for it."
2552 (sh-must-support-indent)
2553 (let* ((info (sh-get-indent-info))
2554 (var (sh-get-indent-var-for-line info
))
2555 val old-val indent-val
)
2557 (message (format "Cannot set indent - %s" var
))
2558 (setq old-val
(symbol-value var
))
2559 (setq val
(sh-read-variable var
))
2563 (setq indent-val
(sh-calculate-indent info
))
2565 (message "Variable: %s Value: %s would indent to: %d"
2566 var
(symbol-value var
) indent-val
)
2567 (message "Variable: %s Value: %s would leave line as is."
2568 var
(symbol-value var
)))
2569 ;; I'm not sure about this, indenting it now?
2570 ;; No. Because it would give the impression that an undo would
2571 ;; restore thing, but the value has been altered.
2576 (message "Bad value for %s, restoring to previous value %s"
2583 (defun sh-learn-line-indent (arg)
2584 "Learn how to indent a line as it currently is indented.
2586 If there is an indentation variable which controls this line's indentation,
2587 then set it to a value which would indent the line the way it
2590 If the value can be represented by one of the symbols then do so
2591 unless optional argument ARG (the prefix when interactive) is non-nil."
2593 (sh-must-support-indent)
2594 ;; I'm not sure if we show allow learning on an empty line.
2595 ;; Though it might occasionally be useful I think it usually
2596 ;; would just be confusing.
2599 (looking-at "\\s-*$"))
2600 (message "sh-learn-line-indent ignores empty lines.")
2601 (let* ((info (sh-get-indent-info))
2602 (var (sh-get-indent-var-for-line info
))
2603 ival sval diff new-val
2605 (curr-indent (current-indentation)))
2608 (message (format "Cannot learn line - %s" var
)))
2609 ((eq var
'sh-indent-comment
)
2610 ;; This is arbitrary...
2611 ;; - if curr-indent is 0, set to curr-indent
2612 ;; - else if it has the indentation of a "normal" line,
2614 ;; - else set to curr-indent.
2615 (setq sh-indent-comment
2616 (if (= curr-indent
0)
2618 (let* ((sh-indent-comment t
)
2619 (val2 (sh-calculate-indent info
)))
2620 (if (= val2 curr-indent
)
2623 (message "%s set to %s" var
(symbol-value var
))
2625 ((numberp (setq sval
(sh-var-value var
)))
2626 (setq ival
(sh-calculate-indent info
))
2627 (setq diff
(- curr-indent ival
))
2629 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2630 curr-indent ival diff var sval
)
2631 (setq new-val
(+ sval diff
))
2632 ;;; I commented out this because someone might want to replace
2633 ;;; a value of `+' with the current value of sh-basic-offset
2636 ;;; (message "No change needed!")
2637 (sh-set-var-value var new-val no-symbol
)
2638 (message "%s set to %s" var
(symbol-value var
))
2642 (message "Cannot change %s" var
))))))
2646 (defun sh-mark-init (buffer)
2647 "Initialize a BUFFER to be used by `sh-mark-line'."
2649 (set-buffer (get-buffer-create buffer
))
2655 (defun sh-mark-line (message point buffer
&optional add-linenum occur-point
)
2656 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2657 Buffer BUFFER is in `occur-mode'.
2658 If ADD-LINENUM is non-nil the message is preceded by the line number.
2659 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2660 so that `occur-next' and `occur-prev' will work."
2661 (let ((m1 (make-marker))
2665 (set-marker m1 point
(current-buffer))
2667 (setq line
(format "%d: " (1+ (count-lines 1 point
))))))
2669 (if (get-buffer buffer
)
2670 (set-buffer (get-buffer buffer
))
2671 (set-buffer (get-buffer-create buffer
))
2674 (goto-char (point-max))
2675 (setq start
(point))
2678 (setq occur-point
(point)))
2681 (add-text-properties
2683 '(mouse-face highlight
2684 help-echo
"mouse-2: go to the line where I learned this")))
2688 (put-text-property start
(point) 'occur-target m1
)
2690 (put-text-property start occur-point
2697 ;; Is this really worth having?
2698 (defvar sh-learned-buffer-hook nil
2699 "*An abnormal hook, called with an alist of learned variables.")
2700 ;; Example of how to use sh-learned-buffer-hook
2702 ;; (defun what-i-learned (list)
2705 ;; (set-buffer "*scratch*")
2706 ;; (goto-char (point-max))
2707 ;; (insert "(setq\n")
2709 ;; (insert (format " %s %s \n"
2710 ;; (nth 0 (car p)) (nth 1 (car p))))
2711 ;; (setq p (cdr p)))
2715 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2718 ;; Originally this was sh-learn-region-indent (beg end)
2719 ;; However, in practice this was awkward so I changed it to
2720 ;; use the whole buffer. Use narrowing if needbe.
2721 (defun sh-learn-buffer-indent (&optional arg
)
2722 "Learn how to indent the buffer the way it currently is.
2724 Output in buffer \"*indent*\" shows any lines which have conflicting
2725 values of a variable, and the final value of all variables learned.
2726 This buffer is popped to automatically if there are any discrepancies.
2728 If no prefix ARG is given, then variables are set to numbers.
2729 If a prefix arg is given, then variables are set to symbols when
2730 applicable -- e.g. to symbol `+' if the value is that of the
2732 If a positive numerical prefix is given, then `sh-basic-offset'
2733 is set to the prefix's numerical value.
2734 Otherwise, sh-basic-offset may or may not be changed, according
2735 to the value of variable `sh-learn-basic-offset'.
2737 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2738 function completes. The function is abnormal because it is called
2739 with an alist of variables learned. This feature may be changed or
2740 removed in the future.
2742 This command can often take a long time to run."
2744 (sh-must-support-indent)
2746 (goto-char (point-min))
2747 (let ((learned-var-list nil
)
2748 (out-buffer "*indent*")
2754 (comment-col nil
) ;; number if all same, t if seen diff values
2755 (comments-always-default t
) ;; nil if we see one not default
2757 (specified-basic-offset (and arg
(numberp arg
)
2761 (setq vec
(make-vector max
0))
2762 (sh-mark-init out-buffer
)
2764 (if specified-basic-offset
2766 (setq sh-basic-offset arg
)
2768 (format "Using specified sh-basic-offset of %d"
2771 (format "Initial value of sh-basic-offset: %s"
2774 (while (< (point) (point-max))
2775 (setq linenum
(1+ linenum
))
2776 ;; (if (zerop (% linenum 10))
2777 (message "line %d" linenum
)
2779 (unless (looking-at "\\s-*$") ;; ignore empty lines!
2780 (let* ((sh-indent-comment t
) ;; info must return default indent
2781 (info (sh-get-indent-info))
2782 (var (sh-get-indent-var-for-line info
))
2783 sval ival diff new-val
2784 (curr-indent (current-indentation)))
2790 ((numberp (setq sval
(sh-var-value var
'no-error
)))
2791 ;; the numberp excludes comments since sval will be t.
2792 (setq ival
(sh-calculate-indent))
2793 (setq diff
(- curr-indent ival
))
2794 (setq new-val
(+ sval diff
))
2795 (sh-set-var-value var new-val
'no-symbol
)
2796 (unless (looking-at "\\s-*#") ;; don't learn from comments
2797 (if (setq previous-set-info
(assoc var learned-var-list
))
2799 ;; it was already there, is it same value ?
2800 (unless (eq (symbol-value var
)
2801 (nth 1 previous-set-info
))
2803 (format "Variable %s was set to %s"
2804 var
(symbol-value var
))
2805 (point) out-buffer t t
)
2807 (format " but was previously set to %s"
2808 (nth 1 previous-set-info
))
2809 (nth 2 previous-set-info
) out-buffer t
)
2810 (setq num-diffs
(1+ num-diffs
))
2811 ;; (delete previous-set-info learned-var-list)
2812 (setcdr previous-set-info
2813 (list (symbol-value var
) (point)))
2816 (setq learned-var-list
2817 (append (list (list var
(symbol-value var
)
2820 (if (numberp new-val
)
2823 "This line's indent value: %d" new-val
)
2825 (setq new-val
(- new-val
)))
2827 (aset vec new-val
(1+ (aref vec new-val
))))))
2829 ((eq var
'sh-indent-comment
)
2830 (unless (= curr-indent
(sh-calculate-indent info
))
2831 ;; this is not the default indentation
2832 (setq comments-always-default nil
)
2833 (if comment-col
;; then we have see one before
2834 (or (eq comment-col curr-indent
)
2835 (setq comment-col t
)) ;; seen a different one
2836 (setq comment-col curr-indent
))
2839 (sh-debug "Cannot learn this line!!!")
2842 "at %s learned-var-list is %s" (point) learned-var-list
)
2849 "comment-col = %s comments-always-default = %s"
2850 comment-col comments-always-default
))
2852 (sh-mark-line msg nil out-buffer
)))
2855 (setq msg
"\nComments are all in 1st column.\n"))
2856 (comments-always-default
2857 (setq msg
"\nComments follow default indentation.\n")
2858 (setq comment-col t
))
2859 ((numberp comment-col
)
2860 (setq msg
(format "\nComments are in col %d." comment-col
)))
2862 (setq msg
"\nComments seem to be mixed, leaving them as is.\n")
2863 (setq comment-col nil
)
2866 (sh-mark-line msg nil out-buffer
)
2868 (sh-mark-line initial-msg nil out-buffer t t
)
2870 (setq suggested
(sh-guess-basic-offset vec
))
2872 (if (and suggested
(not specified-basic-offset
))
2875 ;; t => set it if we have a single value as a number
2876 ((and (eq sh-learn-basic-offset t
) (numberp suggested
))
2878 ;; other non-nil => set it if only one value was found
2879 (sh-learn-basic-offset
2880 (if (numberp suggested
)
2882 (if (= (length suggested
) 1)
2888 (setq learned-var-list
2889 (append (list (list 'sh-basic-offset
2890 (setq sh-basic-offset new-value
)
2893 ;; Not sure if we need to put this line in, since
2894 ;; it will appear in the "Learned variable settings".
2896 (format "Changed sh-basic-offset to: %d" sh-basic-offset
)
2899 (if (listp suggested
)
2900 (format "Possible value(s) for sh-basic-offset: %s"
2901 (mapconcat 'int-to-string suggested
" "))
2902 (format "Suggested sh-basic-offset: %d" suggested
))
2906 (setq learned-var-list
2907 (append (list (list 'sh-indent-comment comment-col
(point-max)))
2909 (setq sh-indent-comment comment-col
)
2910 (let ((name (buffer-name)))
2911 (sh-mark-line "\nLearned variable settings:" nil out-buffer
)
2913 ;; Set learned variables to symbolic rather than numeric
2914 ;; values where possible.
2915 (dolist (learned-var (reverse learned-var-list
))
2916 (let ((var (car learned-var
))
2917 (val (nth 1 learned-var
)))
2918 (when (and (not (eq var
'sh-basic-offset
))
2920 (sh-set-var-value var val
)))))
2921 (dolist (learned-var (reverse learned-var-list
))
2922 (let ((var (car learned-var
)))
2923 (sh-mark-line (format " %s %s" var
(symbol-value var
))
2924 (nth 2 learned-var
) out-buffer
)))
2926 (set-buffer out-buffer
)
2927 (goto-char (point-min))
2929 (format "Indentation values for buffer %s.\n" name
)
2930 (format "%d indentation variable%s different values%s\n\n"
2934 (if (zerop num-diffs
)
2937 ;; Are abnormal hooks considered bad form?
2938 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list
)
2939 (if (or sh-popup-occur-buffer
(> num-diffs
0))
2940 (pop-to-buffer out-buffer
))
2943 (defun sh-guess-basic-offset (vec)
2944 "See if we can determine a reasonable value for `sh-basic-offset'.
2945 This is experimental, heuristic and arbitrary!
2946 Argument VEC is a vector of information collected by
2947 `sh-learn-buffer-indent'.
2949 number - there appears to be a good single value
2950 list of numbers - no obvious one, here is a list of one or more
2952 nil - we couldn't find a reasonable one."
2953 (let* ((max (1- (length vec
)))
2955 (totals (make-vector max
0)))
2957 (aset totals i
(+ (aref totals i
) (* 4 (aref vec i
))))
2959 (aset totals i
(+ (aref totals i
) (aref vec
(/ i
2)))))
2961 (aset totals i
(+ (aref totals i
) (aref vec
(* i
2)))))
2969 (if (/= (aref totals i
) 0)
2970 (setq x
(append x
(list (cons i
(aref totals i
))))))
2973 (setq x
(sort x
(lambda (a b
) (> (cdr a
) (cdr b
)))))
2974 (setq tot
(apply '+ (append totals nil
)))
2975 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
2979 (message "no values!")) ;; we return nil
2981 (message "only value is %d" (car (car x
)))
2982 (setq result
(car (car x
)))) ;; return single value
2983 ((> (cdr (car x
)) (/ tot
2))
2985 (message "basic-offset is probably %d" (car (car x
)))
2986 (setq result
(car (car x
)))) ;; again, return a single value
2987 ((>= (cdr (car x
)) (* 2 (cdr (car (cdr x
)))))
2988 ;; 1st is >= 2 * 2nd
2989 (message "basic-offset could be %d" (car (car x
)))
2990 (setq result
(car (car x
))))
2991 ((>= (+ (cdr (car x
))(cdr (car (cdr x
)))) (/ tot
2))
2992 ;; 1st & 2nd together >= 50% - return a list
2993 (setq p x sum
0 result nil
)
2995 (<= (setq sum
(+ sum
(cdr (car p
)))) (/ tot
2)))
2996 (setq result
(append result
(list (car (car p
)))))
2998 (message "Possible choices for sh-basic-offset: %s"
2999 (mapconcat 'int-to-string result
" ")))
3001 (message "No obvious value for sh-basic-offset. Perhaps %d"
3003 ;; result is nil here
3007 ;; ========================================================================
3009 ;; Styles -- a quick and dirty way of saving the indentation settings.
3011 (defvar sh-styles-alist nil
3012 "A list of all known shell indentation styles.")
3014 (defun sh-name-style (name &optional confirm-overwrite
)
3015 "Name the current indentation settings as a style called NAME.
3016 If this name exists, the command will prompt whether it should be
3018 - - it was called interactively with a prefix argument, or
3019 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3020 ;; (interactive "sName for this style: ")
3023 (read-from-minibuffer "Name for this style? " )
3024 (not current-prefix-arg
)))
3025 (let ((slist (cons name
3026 (mapcar (lambda (var) (cons var
(symbol-value var
)))
3028 (style (assoc name sh-styles-alist
)))
3030 (if (and confirm-overwrite
3031 (not (y-or-n-p "This style exists. Overwrite it? ")))
3032 (message "Not changing style %s" name
)
3033 (message "Updating style %s" name
)
3034 (setcdr style
(cdr slist
)))
3035 (message "Creating new style %s" name
)
3036 (push slist sh-styles-alist
))))
3038 (defun sh-load-style (name)
3039 "Set shell indentation values for this buffer from those in style NAME."
3040 (interactive (list (completing-read
3041 "Which style to use for this buffer? "
3042 sh-styles-alist nil t
)))
3043 (let ((sl (assoc name sh-styles-alist
)))
3045 (error "sh-load-style - style %s not known" name
)
3046 (dolist (var (cdr sl
))
3047 (set (car var
) (cdr var
))))))
3049 (defun sh-save-styles-to-buffer (buff)
3050 "Save all current styles in elisp to buffer BUFF.
3051 This is always added to the end of the buffer."
3053 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3054 (with-current-buffer (get-buffer-create buff
)
3055 (goto-char (point-max))
3057 (pp `(setq sh-styles-alist
',sh-styles-alist
) (current-buffer))))
3061 ;; statement syntax-commands for various shells
3063 ;; You are welcome to add the syntax or even completely new statements as
3064 ;; appropriate for your favorite shell.
3066 (defconst sh-non-closing-paren
3067 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3068 ;; that inherits this property, which then confuses the indentation.
3069 (propertize ")" 'syntax-table sh-st-punc
'rear-nonsticky t
))
3071 (define-skeleton sh-case
3072 "Insert a case/switch statement. See `sh-feature'."
3074 "switch( " str
" )" \n
3075 > "case " (read-string "pattern: ") ?
: \n
3078 ( "other pattern, %s: "
3088 > "switch( " str
" ) {" \n
3089 > "case " (read-string "pattern: ") \n
3091 ( "other pattern, %s: "
3099 > "case " str
" in" \n
3101 > str sh-non-closing-paren
\n
3104 > "*" sh-non-closing-paren
\n
3109 (define-skeleton sh-for
3110 "Insert a for loop. See `sh-feature'."
3111 (csh eval sh-modify sh
3118 (es eval sh-modify rc
3120 (rc eval sh-modify sh
3124 (sh "Index variable: "
3125 > "for " str
" in " _
"; do" \n
3126 > _ | ?$
& (sh-remember-variable str
) \n
3131 (define-skeleton sh-indexed-loop
3132 "Insert an indexed loop from 1 to n. See `sh-feature'."
3133 (bash eval identity posix
)
3134 (csh "Index variable: "
3136 "while( $" str
" <= " (read-string "upper limit: ") " )" \n
3140 (es eval sh-modify rc
3142 (ksh88 "Index variable: "
3143 > "integer " str
"=0" \n
3144 > "while (( ( " str
" += 1 ) <= "
3145 (read-string "upper limit: ")
3147 > _ ?$
(sh-remember-variable str
) > \n
3149 (posix "Index variable: "
3151 "while [ $" str
" -le "
3152 (read-string "upper limit: ")
3155 str ?
= (sh-add (sh-remember-variable str
) 1) \n
3157 (rc "Index variable: "
3158 > "for( " str
" in" " `{awk 'BEGIN { for( i=1; i<="
3159 (read-string "upper limit: ")
3160 "; i++ ) print i }'`}) {" \n
3161 > _ ?$
(sh-remember-variable str
) \n
3163 (sh "Index variable: "
3164 > "for " str
" in `awk 'BEGIN { for( i=1; i<="
3165 (read-string "upper limit: ")
3166 "; i++ ) print i }'`; do" \n
3167 > _ ?$
(sh-remember-variable str
) \n
3171 (defun sh-shell-initialize-variables ()
3172 "Scan the buffer for variable assignments.
3173 Add these variables to `sh-shell-variables'."
3174 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3176 (goto-char (point-min))
3177 (setq sh-shell-variables-initialized t
)
3178 (while (search-forward "=" nil t
)
3180 (message "Scanning buffer `%s' for variable assignments...done"
3183 (defvar sh-add-buffer
)
3185 (defun sh-add-completer (string predicate code
)
3186 "Do completion using `sh-shell-variables', but initialize it first.
3187 This function is designed for use as the \"completion table\",
3188 so it takes three arguments:
3189 STRING, the current buffer contents;
3190 PREDICATE, the predicate for filtering possible matches;
3191 CODE, which says what kind of things to do.
3192 CODE can be nil, t or `lambda'.
3193 nil means to return the best completion of STRING, or nil if there is none.
3194 t means to return a list of all possible completions of STRING.
3195 `lambda' means to return t if STRING is a valid completion as it stands."
3196 (let ((sh-shell-variables
3198 (set-buffer sh-add-buffer
)
3199 (or sh-shell-variables-initialized
3200 (sh-shell-initialize-variables))
3201 (nconc (mapcar (lambda (var)
3203 (substring var
0 (string-match "=" var
))))
3205 process-environment
)
3206 sh-shell-variables
))))
3208 (nil (try-completion string sh-shell-variables predicate
))
3209 (lambda (test-completion string sh-shell-variables predicate
))
3210 (t (all-completions string sh-shell-variables predicate
)))))
3212 (defun sh-add (var delta
)
3213 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3215 (let ((sh-add-buffer (current-buffer)))
3216 (list (completing-read "Variable: " 'sh-add-completer
)
3217 (prefix-numeric-value current-prefix-arg
))))
3218 (insert (sh-feature '((bash .
"$[ ")
3224 (sh-remember-variable var
)
3225 (if (< delta
0) " - " " + ")
3226 (number-to-string (abs delta
))
3227 (sh-feature '((bash .
" ]")
3236 (define-skeleton sh-function
3237 "Insert a function definition. See `sh-feature'."
3238 (bash eval sh-modify ksh88
3241 "function " str
" {" \n
3244 (rc eval sh-modify ksh88
3253 (define-skeleton sh-if
3254 "Insert an if statement. See `sh-feature'."
3256 "if( " str
" ) then" \n
3258 ( "other condition, %s: "
3259 < "else if( " str
" ) then" \n
3266 > "if { " str
" } {" \n
3268 ( "other condition, %s: "
3269 "} { " str
" } {" > \n
3276 > "if( " str
" ) {" \n
3278 ( "other condition, %s: "
3279 "} else if( " str
" ) {" > \n
3286 '(setq input
(sh-feature sh-test
))
3287 > "if " str
"; then" \n
3289 ( "other condition, %s: "
3290 > "elif " str
"; then" > \n
3299 (define-skeleton sh-repeat
3300 "Insert a repeat loop definition. See `sh-feature'."
3306 > "repeat " str
"; do" > \n
3310 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3314 (define-skeleton sh-select
3315 "Insert a select statement. See `sh-feature'."
3316 (ksh88 "Index variable: "
3317 > "select " str
" in " _
"; do" \n
3320 (bash eval sh-append ksh88
))
3321 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3325 (define-skeleton sh-tmp-file
3326 "Insert code to setup temporary file handling. See `sh-feature'."
3327 (bash eval identity ksh88
)
3328 (csh (file-name-nondirectory (buffer-file-name))
3329 "set tmp = /tmp/" str
".$$" \n
3331 (and (goto-char (point-max))
3335 "rm $tmp* >&/dev/null" > \n)
3336 (es (file-name-nondirectory (buffer-file-name))
3337 > "local( signals = $signals sighup sigint; tmp = /tmp/" str
3340 > "rm $tmp^* >[2]/dev/null" \n
3346 (ksh88 eval sh-modify sh
3348 (rc (file-name-nondirectory (buffer-file-name))
3349 > "tmp = /tmp/" str
".$pid" \n
3350 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
3351 (sh (file-name-nondirectory (buffer-file-name))
3352 > "TMP=${TMPDIR:-/tmp}/" str
".$$" \n
3353 "trap \"rm $TMP* 2>/dev/null\" " ?
0 \n))
3357 (define-skeleton sh-until
3358 "Insert an until loop. See `sh-feature'."
3360 '(setq input
(sh-feature sh-test
))
3361 > "until " str
"; do" \n
3364 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3368 (define-skeleton sh-while
3369 "Insert a while loop. See `sh-feature'."
3370 (csh eval sh-modify sh
3376 (es eval sh-modify sh
3380 (rc eval sh-modify sh
3385 '(setq input
(sh-feature sh-test
))
3386 > "while " str
"; do" \n
3392 (define-skeleton sh-while-getopts
3393 "Insert a while getopts loop. See `sh-feature'.
3394 Prompts for an options string which consists of letters for each recognized
3395 option followed by a colon `:' if the option accepts an argument."
3396 (bash eval sh-modify sh
3400 > "switch( \"$1\" )" \n
3401 '(setq input
'("- x" .
2))
3404 < "case " '(eval str
)
3405 '(if (string-match " +" str
)
3406 (setq v1
(substring str
(match-end 0))
3407 str
(substring str
0 (match-beginning 0)))
3410 > "set " v1
& " = $2" | -
4 & _
\n
3411 (if v1
"shift") & \n
3421 (ksh88 eval sh-modify sh
3425 (posix eval sh-modify sh
3426 18 "$(basename $0)")
3428 > "while getopts :" str
" OPT; do" \n
3430 '(setq v1
(append (vconcat str
) nil
))
3431 ( (prog1 (if v1
(char-to-string (car v1
)))
3432 (if (eq (nth 1 v1
) ?
:)
3433 (setq v1
(nthcdr 2 v1
)
3437 > str
"|+" str sh-non-closing-paren
\n
3440 > "*" sh-non-closing-paren
\n
3441 > "echo" " \"usage: " "`basename $0`"
3442 " [+-" '(setq v1
(point)) str
3444 (while (search-backward ":" v1 t
)
3445 (replace-match " ARG] [+-" t t
)))
3446 (if (eq (preceding-char) ?-
) -
5)
3447 (if (and (sequencep v1
) (length v1
)) "] " "} ")
3453 "shift " (sh-add "OPTIND" -
1) \n))
3457 (defun sh-assignment (arg)
3458 "Remember preceding identifier for future completion and do self-insert."
3460 (self-insert-command arg
)
3462 (sh-remember-variable
3464 (if (re-search-forward (sh-feature sh-assignment-regexp
)
3466 (beginning-of-line 1))
3468 (match-string 1))))))
3472 (defun sh-maybe-here-document (arg)
3473 "Insert self. Without prefix, following unquoted `<' inserts here document.
3474 The document is bounded by `sh-here-document-word'."
3476 (self-insert-command (prefix-numeric-value arg
))
3478 (not (eq (char-after (- (point) 2)) last-command-char
))
3483 (insert sh-here-document-word
)
3484 (or (eolp) (looking-at "[ \t]") (insert ?
))
3491 (insert ?
\n (substring
3492 sh-here-document-word
3493 (if (string-match "^-" sh-here-document-word
) 1 0)))))))
3496 ;; various other commands
3498 (autoload 'comint-dynamic-complete
"comint"
3499 "Dynamically perform completion at point." t
)
3501 (autoload 'shell-dynamic-complete-command
"shell"
3502 "Dynamically complete the command at point." t
)
3504 (autoload 'comint-dynamic-complete-filename
"comint"
3505 "Dynamically complete the filename at point." t
)
3507 (autoload 'shell-dynamic-complete-environment-variable
"shell"
3508 "Dynamically complete the environment variable at point." t
)
3512 (defun sh-newline-and-indent ()
3513 "Strip unquoted whitespace, insert newline, and indent like current line."
3515 (indent-to (prog1 (current-indentation)
3516 (delete-region (point)
3518 (or (zerop (skip-chars-backward " \t"))
3524 (defun sh-beginning-of-command ()
3525 "Move point to successive beginnings of commands."
3527 (if (re-search-backward sh-beginning-of-command nil t
)
3528 (goto-char (match-beginning 2))))
3530 (defun sh-end-of-command ()
3531 "Move point to successive ends of commands."
3533 (if (re-search-forward sh-end-of-command nil t
)
3534 (goto-char (match-end 1))))
3536 (provide 'sh-script
)
3538 ;;; sh-script.el ends here