(calendar-other-dates): New function.
[emacs.git] / lisp / progmodes / sh-script.el
blob1fae4ef98c7ee237ea869c967f35901ddd1dd2a7
1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993, 1994, 1995, 1996, 1997, 1999, 2001, 2002,
4 ;; 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
7 ;; Version: 2.0f
8 ;; Maintainer: FSF
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 3, or (at your option)
16 ;; any later version.
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., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
28 ;;; Commentary:
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.
36 ;;; Known Bugs:
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.
42 ;; Indentation
43 ;; ===========
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,
48 ;; zsh, ...).
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:
71 ;; `sh-show-indent'
72 ;; This shows what variable controls the indentation of the current
73 ;; line and its value.
75 ;; `sh-set-indent'
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
96 ;; non-nil.
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
108 ;; suffice.
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
115 ;; the buffer.
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
171 ;; disadvantages:
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 "$#".
175 ;; Bugs
176 ;; ----
177 ;; - Indenting many lines is slow. It currently does each line
178 ;; independently, rather than saving state information.
180 ;; - `sh-learn-buffer-indent' is extremely slow.
182 ;; - "case $x in y) echo ;; esac)" the last ) is mis-identified as being
183 ;; part of a case-pattern. You need to add a semi-colon after "esac" to
184 ;; coerce sh-script into doing the right thing.
186 ;; - "echo $z in ps | head)" the last ) is mis-identified as being part of
187 ;; a case-pattern. You need to put the "in" between quotes to coerce
188 ;; sh-script into doing the right thing.
190 ;; - A line starting with "}>foo" is not indented like "} >foo".
192 ;; Richard Sharman <rsharman@pobox.com> June 1999.
194 ;;; Code:
196 ;; page 1: variables and settings
197 ;; page 2: indentation stuff
198 ;; page 3: mode-command and utility functions
199 ;; page 4: statement syntax-commands for various shells
200 ;; page 5: various other commands
202 (eval-when-compile
203 (require 'skeleton)
204 (require 'cl)
205 (require 'comint))
206 (require 'executable)
208 (defvar font-lock-comment-face)
209 (defvar font-lock-set-defaults)
210 (defvar font-lock-string-face)
213 (defgroup sh nil
214 "Shell programming utilities."
215 :group 'languages)
217 (defgroup sh-script nil
218 "Shell script mode."
219 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
220 :group 'sh
221 :prefix "sh-")
224 (defcustom sh-ancestor-alist
225 '((ash . sh)
226 (bash . jsh)
227 (bash2 . jsh)
228 (dtksh . ksh)
229 (es . rc)
230 (itcsh . tcsh)
231 (jcsh . csh)
232 (jsh . sh)
233 (ksh . ksh88)
234 (ksh88 . jsh)
235 (oash . sh)
236 (pdksh . ksh88)
237 (posix . sh)
238 (tcsh . csh)
239 (wksh . ksh88)
240 (wsh . sh)
241 (zsh . ksh88)
242 (rpm . sh))
243 "Alist showing the direct ancestor of various shells.
244 This is the basis for `sh-feature'. See also `sh-alias-alist'.
245 By default we have the following three hierarchies:
247 csh C Shell
248 jcsh C Shell with Job Control
249 tcsh Turbo C Shell
250 itcsh ? Turbo C Shell
251 rc Plan 9 Shell
252 es Extensible Shell
253 sh Bourne Shell
254 ash ? Shell
255 jsh Bourne Shell with Job Control
256 bash GNU Bourne Again Shell
257 ksh88 Korn Shell '88
258 ksh Korn Shell '93
259 dtksh CDE Desktop Korn Shell
260 pdksh Public Domain Korn Shell
261 wksh Window Korn Shell
262 zsh Z Shell
263 oash SCO OA (curses) Shell
264 posix IEEE 1003.2 Shell Standard
265 wsh ? Shell"
266 :type '(repeat (cons symbol symbol))
267 :group 'sh-script)
270 (defcustom sh-alias-alist
271 (append (if (eq system-type 'gnu/linux)
272 '((csh . tcsh)
273 (ksh . pdksh)))
274 ;; for the time being
275 '((ksh . ksh88)
276 (bash2 . bash)
277 (sh5 . sh)))
278 "Alist for transforming shell names to what they really are.
279 Use this where the name of the executable doesn't correspond to the type of
280 shell it really is."
281 :type '(repeat (cons symbol symbol))
282 :group 'sh-script)
285 (defcustom sh-shell-file
287 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
288 ;; the executable extension, so comparisons with the list of
289 ;; known shells work.
290 (and (memq system-type '(ms-dos windows-nt))
291 (let* ((shell (getenv "SHELL"))
292 (shell-base
293 (and shell (file-name-nondirectory shell))))
294 ;; shell-script mode doesn't support DOS/Windows shells,
295 ;; so use the default instead.
296 (if (or (null shell)
297 (member (downcase shell-base)
298 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
299 "cmdproxy.exe")))
300 "/bin/sh"
301 (file-name-sans-extension (downcase shell)))))
302 (getenv "SHELL")
303 "/bin/sh")
304 "The executable file name for the shell being programmed."
305 :type 'string
306 :group 'sh-script)
309 (defcustom sh-shell-arg
310 ;; bash does not need any options when run in a shell script,
311 '((bash)
312 (csh . "-f")
313 (pdksh)
314 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
315 (ksh88)
316 ;; -p means don't initialize functions from the environment.
317 (rc . "-p")
318 ;; Someone proposed -motif, but we don't want to encourage
319 ;; use of a non-free widget set.
320 (wksh)
321 ;; -f means don't run .zshrc.
322 (zsh . "-f"))
323 "Single argument string for the magic number. See `sh-feature'."
324 :type '(repeat (cons (symbol :tag "Shell")
325 (choice (const :tag "No Arguments" nil)
326 (string :tag "Arguments")
327 (sexp :format "Evaluate: %v"))))
328 :group 'sh-script)
330 (defcustom sh-imenu-generic-expression
331 `((sh
332 . ((nil "^\\s-*\\(function\\s-+\\)?\\([[:alpha:]_][[:alnum:]_]+\\)\\s-*()" 2))))
333 "Alist of regular expressions for recognizing shell function definitions.
334 See `sh-feature' and `imenu-generic-expression'."
335 :type '(alist :key-type (symbol :tag "Shell")
336 :value-type (alist :key-type (choice :tag "Title"
337 string
338 (const :tag "None" nil))
339 :value-type
340 (repeat :tag "Regexp, index..." sexp)))
341 :group 'sh-script
342 :version "20.4")
344 (defvar sh-shell-variables nil
345 "Alist of shell variable names that should be included in completion.
346 These are used for completion in addition to all the variables named
347 in `process-environment'. Each element looks like (VAR . VAR), where
348 the car and cdr are the same symbol.")
350 (defvar sh-shell-variables-initialized nil
351 "Non-nil if `sh-shell-variables' is initialized.")
353 (defun sh-canonicalize-shell (shell)
354 "Convert a shell name SHELL to the one we should handle it as."
355 (if (string-match "\\.exe\\'" shell)
356 (setq shell (substring shell 0 (match-beginning 0))))
357 (or (symbolp shell)
358 (setq shell (intern shell)))
359 (or (cdr (assq shell sh-alias-alist))
360 shell))
362 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
363 "The shell being programmed. This is set by \\[sh-set-shell].")
364 ;;;###autoload(put 'sh-shell 'safe-local-variable 'symbolp)
366 (defvar sh-mode-abbrev-table nil)
368 (define-abbrev-table 'sh-mode-abbrev-table ())
371 ;; I turned off this feature because it doesn't permit typing commands
372 ;; in the usual way without help.
373 ;;(defvar sh-abbrevs
374 ;; '((csh sh-abbrevs shell
375 ;; "switch" 'sh-case
376 ;; "getopts" 'sh-while-getopts)
378 ;; (es sh-abbrevs shell
379 ;; "function" 'sh-function)
381 ;; (ksh88 sh-abbrevs sh
382 ;; "select" 'sh-select)
384 ;; (rc sh-abbrevs shell
385 ;; "case" 'sh-case
386 ;; "function" 'sh-function)
388 ;; (sh sh-abbrevs shell
389 ;; "case" 'sh-case
390 ;; "function" 'sh-function
391 ;; "until" 'sh-until
392 ;; "getopts" 'sh-while-getopts)
394 ;; ;; The next entry is only used for defining the others
395 ;; (shell "for" sh-for
396 ;; "loop" sh-indexed-loop
397 ;; "if" sh-if
398 ;; "tmpfile" sh-tmp-file
399 ;; "while" sh-while)
401 ;; (zsh sh-abbrevs ksh88
402 ;; "repeat" 'sh-repeat))
403 ;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
404 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
405 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
409 (defun sh-mode-syntax-table (table &rest list)
410 "Copy TABLE and set syntax for successive CHARs according to strings S."
411 (setq table (copy-syntax-table table))
412 (while list
413 (modify-syntax-entry (pop list) (pop list) table))
414 table)
416 (defvar sh-mode-syntax-table nil
417 "The syntax table to use for Shell-Script mode.
418 This is buffer-local in every such buffer.")
420 (defvar sh-mode-default-syntax-table
421 (sh-mode-syntax-table ()
422 ?\# "<"
423 ?\n ">#"
424 ?\" "\"\""
425 ?\' "\"'"
426 ?\` "\"`"
427 ;; ?$ might also have a ". p" syntax. Both "'" and ". p" seem
428 ;; to work fine. This is needed so that dabbrev-expand
429 ;; $VARNAME works.
430 ?$ "'"
431 ?! "_"
432 ?% "_"
433 ?: "_"
434 ?. "_"
435 ?^ "_"
436 ?~ "_"
437 ?, "_"
438 ?= "."
439 ?< "."
440 ?> ".")
441 "Default syntax table for shell mode.")
443 (defvar sh-mode-syntax-table-input
444 '((sh . nil))
445 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
447 (defvar sh-mode-map
448 (let ((map (make-sparse-keymap))
449 (menu-map (make-sparse-keymap "Insert")))
450 (define-key map "\C-c(" 'sh-function)
451 (define-key map "\C-c\C-w" 'sh-while)
452 (define-key map "\C-c\C-u" 'sh-until)
453 (define-key map "\C-c\C-t" 'sh-tmp-file)
454 (define-key map "\C-c\C-s" 'sh-select)
455 (define-key map "\C-c\C-r" 'sh-repeat)
456 (define-key map "\C-c\C-o" 'sh-while-getopts)
457 (define-key map "\C-c\C-l" 'sh-indexed-loop)
458 (define-key map "\C-c\C-i" 'sh-if)
459 (define-key map "\C-c\C-f" 'sh-for)
460 (define-key map "\C-c\C-c" 'sh-case)
461 (define-key map "\C-c?" 'sh-show-indent)
462 (define-key map "\C-c=" 'sh-set-indent)
463 (define-key map "\C-c<" 'sh-learn-line-indent)
464 (define-key map "\C-c>" 'sh-learn-buffer-indent)
465 (define-key map "\C-c\C-\\" 'sh-backslash-region)
467 (define-key map "=" 'sh-assignment)
468 (define-key map "\C-c+" 'sh-add)
469 (define-key map "\C-\M-x" 'sh-execute-region)
470 (define-key map "\C-c\C-x" 'executable-interpret)
471 (define-key map "<" 'sh-maybe-here-document)
472 (define-key map "(" 'skeleton-pair-insert-maybe)
473 (define-key map "{" 'skeleton-pair-insert-maybe)
474 (define-key map "[" 'skeleton-pair-insert-maybe)
475 (define-key map "'" 'skeleton-pair-insert-maybe)
476 (define-key map "`" 'skeleton-pair-insert-maybe)
477 (define-key map "\"" 'skeleton-pair-insert-maybe)
479 (define-key map [remap complete-tag] 'comint-dynamic-complete)
480 (define-key map [remap newline-and-indent] 'sh-newline-and-indent)
481 (define-key map [remap delete-backward-char]
482 'backward-delete-char-untabify)
483 (define-key map "\C-c:" 'sh-set-shell)
484 (define-key map [remap backward-sentence] 'sh-beginning-of-command)
485 (define-key map [remap forward-sentence] 'sh-end-of-command)
486 (define-key map [menu-bar insert] (cons "Insert" menu-map))
487 (define-key menu-map [sh-while] '("While Loop" . sh-while))
488 (define-key menu-map [sh-until] '("Until Loop" . sh-until))
489 (define-key menu-map [sh-tmp-file] '("Temporary File" . sh-tmp-file))
490 (define-key menu-map [sh-select] '("Select Statement" . sh-select))
491 (define-key menu-map [sh-repeat] '("Repeat Loop" . sh-repeat))
492 (define-key menu-map [sh-getopts] '("Options Loop" . sh-while-getopts))
493 (define-key menu-map [sh-indexed-loop] '("Indexed Loop" . sh-indexed-loop))
494 (define-key menu-map [sh-if] '("If Statement" . sh-if))
495 (define-key menu-map [sh-for] '("For Loop" . sh-for))
496 (define-key menu-map [sh-case] '("Case Statement" . sh-case))
497 map)
498 "Keymap used in Shell-Script mode.")
500 (defvar sh-skeleton-pair-default-alist '((?( _ ?)) (?\))
501 (?[ ?\s _ ?\s ?]) (?\])
502 (?{ _ ?}) (?\}))
503 "Value to use for `skeleton-pair-default-alist' in Shell-Script mode.")
505 (defcustom sh-dynamic-complete-functions
506 '(shell-dynamic-complete-environment-variable
507 shell-dynamic-complete-command
508 comint-dynamic-complete-filename)
509 "Functions for doing TAB dynamic completion."
510 :type '(repeat function)
511 :group 'sh-script)
514 (defcustom sh-require-final-newline
515 '((csh . t)
516 (pdksh . t))
517 "Value of `require-final-newline' in Shell-Script mode buffers.
518 \(SHELL . t) means use the value of `mode-require-final-newline' for SHELL.
519 See `sh-feature'."
520 :type '(repeat (cons (symbol :tag "Shell")
521 (choice (const :tag "require" t)
522 (sexp :format "Evaluate: %v"))))
523 :group 'sh-script)
526 (defcustom sh-assignment-regexp
527 '((csh . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
528 ;; actually spaces are only supported in let/(( ... ))
529 (ksh88 . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
530 (rc . "\\<\\([[:alnum:]_*]+\\)[ \t]*=")
531 (sh . "\\<\\([[:alnum:]_]+\\)="))
532 "Regexp for the variable name and what may follow in an assignment.
533 First grouping matches the variable name. This is upto and including the `='
534 sign. See `sh-feature'."
535 :type '(repeat (cons (symbol :tag "Shell")
536 (choice regexp
537 (sexp :format "Evaluate: %v"))))
538 :group 'sh-script)
541 (defcustom sh-indentation 4
542 "The width for further indentation in Shell-Script mode."
543 :type 'integer
544 :group 'sh-script)
545 (put 'sh-indentation 'safe-local-variable 'integerp)
547 (defcustom sh-remember-variable-min 3
548 "Don't remember variables less than this length for completing reads."
549 :type 'integer
550 :group 'sh-script)
553 (defvar sh-header-marker nil
554 "When non-nil is the end of header for prepending by \\[sh-execute-region].
555 That command is also used for setting this variable.")
558 (defcustom sh-beginning-of-command
559 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~[:alnum:]:]\\)"
560 "Regexp to determine the beginning of a shell command.
561 The actual command starts at the beginning of the second \\(grouping\\)."
562 :type 'regexp
563 :group 'sh-script)
566 (defcustom sh-end-of-command
567 "\\([/~[:alnum:]:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
568 "Regexp to determine the end of a shell command.
569 The actual command ends at the end of the first \\(grouping\\)."
570 :type 'regexp
571 :group 'sh-script)
575 (defcustom sh-here-document-word "EOF"
576 "Word to delimit here documents.
577 If the first character of this string is \"-\", this is taken as
578 part of the redirection operator, rather than part of the
579 word (that is, \"<<-\" instead of \"<<\"). This is a feature
580 used by some shells (for example Bash) to indicate that leading
581 tabs inside the here document should be ignored. In this case,
582 Emacs indents the initial body and end of the here document with
583 tabs, to the same level as the start (note that apart from this
584 there is no support for indentation of here documents). This
585 will only work correctly if `sh-basic-offset' is a multiple of
586 `tab-width'.
588 Any quote characters or leading whitespace in the word are
589 removed when closing the here document."
590 :type 'string
591 :group 'sh-script)
594 (defvar sh-test
595 '((sh "[ ]" . 3)
596 (ksh88 "[[ ]]" . 4))
597 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
600 ;; customized this out of sheer bravado. not for the faint of heart.
601 ;; but it *did* have an asterisk in the docstring!
602 (defcustom sh-builtins
603 '((bash sh-append posix
604 "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
605 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
606 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
607 "source" "suspend" "typeset" "unalias")
609 ;; The next entry is only used for defining the others
610 (bourne sh-append shell
611 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
612 "times" "ulimit")
614 (csh sh-append shell
615 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
616 "setenv" "source" "time" "unalias" "unhash")
618 (dtksh sh-append wksh)
620 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
621 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
623 (jsh sh-append sh
624 "bg" "fg" "jobs" "kill" "stop" "suspend")
626 (jcsh sh-append csh
627 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
629 (ksh88 sh-append bourne
630 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
631 "typeset" "unalias" "whence")
633 (oash sh-append sh
634 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
635 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
636 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
637 "wmtitle" "wrefresh")
639 (pdksh sh-append ksh88
640 "bind")
642 (posix sh-append sh
643 "command")
645 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
646 "whatis")
648 (sh sh-append bourne
649 "hash" "test" "type")
651 ;; The next entry is only used for defining the others
652 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
654 (wksh sh-append ksh88
655 ;; FIXME: This looks too much like a regexp. --Stef
656 "Xt[A-Z][A-Za-z]*")
658 (zsh sh-append ksh88
659 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
660 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
661 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
662 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
663 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
664 "which"))
665 "List of all shell builtins for completing read and fontification.
666 Note that on some systems not all builtins are available or some are
667 implemented as aliases. See `sh-feature'."
668 :type '(repeat (cons (symbol :tag "Shell")
669 (choice (repeat string)
670 (sexp :format "Evaluate: %v"))))
671 :group 'sh-script)
675 (defcustom sh-leading-keywords
676 '((bash sh-append sh
677 "time")
679 (csh "else")
681 (es "true" "unwind-protect" "whatis")
683 (rc "else")
685 (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
686 "List of keywords that may be immediately followed by a builtin or keyword.
687 Given some confusion between keywords and builtins depending on shell and
688 system, the distinction here has been based on whether they influence the
689 flow of control or syntax. See `sh-feature'."
690 :type '(repeat (cons (symbol :tag "Shell")
691 (choice (repeat string)
692 (sexp :format "Evaluate: %v"))))
693 :group 'sh-script)
696 (defcustom sh-other-keywords
697 '((bash sh-append bourne
698 "bye" "logout" "select")
700 ;; The next entry is only used for defining the others
701 (bourne sh-append sh
702 "function")
704 (csh sh-append shell
705 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
706 "if" "logout" "onintr" "repeat" "switch" "then" "while")
708 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
709 "return" "throw" "while")
711 (ksh88 sh-append bourne
712 "select")
714 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
715 "while")
717 (sh sh-append shell
718 "done" "esac" "fi" "for" "in" "return")
720 ;; The next entry is only used for defining the others
721 (shell "break" "case" "continue" "exec" "exit")
723 (zsh sh-append bash
724 "select"))
725 "List of keywords not in `sh-leading-keywords'.
726 See `sh-feature'."
727 :type '(repeat (cons (symbol :tag "Shell")
728 (choice (repeat string)
729 (sexp :format "Evaluate: %v"))))
730 :group 'sh-script)
734 (defvar sh-variables
735 '((bash sh-append sh
736 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
737 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
738 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
739 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
740 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
741 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
742 "HISTIGNORE" "history_control" "HISTSIZE"
743 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
744 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
745 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
746 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
747 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
748 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
749 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
751 (csh sh-append shell
752 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
753 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
754 "shell" "status" "time" "verbose")
756 (es sh-append shell
757 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
758 "pid" "prompt" "signals")
760 (jcsh sh-append csh
761 "notify")
763 (ksh88 sh-append sh
764 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
765 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
766 "TMOUT")
768 (oash sh-append sh
769 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
771 (rc sh-append shell
772 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
773 "prompt" "status")
775 (sh sh-append shell
776 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
778 ;; The next entry is only used for defining the others
779 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
780 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
781 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
782 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
784 (tcsh sh-append csh
785 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
786 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
787 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
788 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
789 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
790 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
791 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
792 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
793 "wordchars")
795 (zsh sh-append ksh88
796 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
797 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
798 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
799 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
800 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
801 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
802 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
803 "List of all shell variables available for completing read.
804 See `sh-feature'.")
807 ;; Font-Lock support
809 (defface sh-heredoc
810 '((((min-colors 88) (class color)
811 (background dark))
812 (:foreground "yellow1" :weight bold))
813 (((class color)
814 (background dark))
815 (:foreground "yellow" :weight bold))
816 (((class color)
817 (background light))
818 (:foreground "tan" ))
820 (:weight bold)))
821 "Face to show a here-document"
822 :group 'sh-indentation)
824 ;; These colours are probably icky. It's just a placeholder though.
825 (defface sh-quoted-exec
826 '((((class color) (background dark))
827 (:foreground "salmon"))
828 (((class color) (background light))
829 (:foreground "magenta"))
831 (:weight bold)))
832 "Face to show quoted execs like ``"
833 :group 'sh-indentation)
835 ;; backward-compatibility alias
836 (put 'sh-heredoc-face 'face-alias 'sh-heredoc)
837 (defvar sh-heredoc-face 'sh-heredoc)
839 (defface sh-escaped-newline '((t :inherit font-lock-string-face))
840 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
841 :group 'sh-script
842 :version "22.1")
844 (defvar sh-font-lock-keywords-var
845 '((csh sh-append shell
846 ("\\${?[#?]?\\([[:alpha:]_][[:alnum:]_]*\\|0\\)" 1
847 font-lock-variable-name-face))
849 (es sh-append executable-font-lock-keywords
850 ("\\$#?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\)" 1
851 font-lock-variable-name-face))
853 (rc sh-append es)
854 (bash sh-append shell ("\\$(\\(\\sw+\\)" (1 'sh-quoted-exec t) ))
855 (sh sh-append shell
856 ;; Variable names.
857 ("\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?@!]\\)" 2
858 font-lock-variable-name-face)
859 ;; Function names.
860 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
861 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
862 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
863 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
864 1 font-lock-negation-char-face))
866 ;; The next entry is only used for defining the others
867 (shell
868 ;; Using font-lock-string-face here confuses sh-get-indent-info.
869 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline)
870 ("\\\\[^[:alnum:]]" 0 font-lock-string-face)
871 ("\\${?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\|[$*_]\\)" 1
872 font-lock-variable-name-face))
873 (rpm sh-append rpm2
874 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face))
875 (rpm2 sh-append shell
876 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face)))
877 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
879 (defvar sh-font-lock-keywords-var-1
880 '((sh "[ \t]in\\>"))
881 "Subdued level highlighting for Shell Script modes.")
883 (defvar sh-font-lock-keywords-var-2 ()
884 "Gaudy level highlighting for Shell Script modes.")
886 ;; These are used for the syntax table stuff (derived from cperl-mode).
887 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
888 (defconst sh-st-punc (string-to-syntax "."))
889 (defconst sh-st-symbol (string-to-syntax "_"))
890 (defconst sh-here-doc-syntax (string-to-syntax "|")) ;; generic string
892 (defconst sh-escaped-line-re
893 ;; Should match until the real end-of-continued-line, but if that is not
894 ;; possible (because we bump into EOB or the search bound), then we should
895 ;; match until the search bound.
896 "\\(?:\\(?:.*[^\\\n]\\)?\\(?:\\\\\\\\\\)*\\\\\n\\)*.*")
898 (defconst sh-here-doc-open-re
899 (concat "<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\)+\\)"
900 sh-escaped-line-re "\\(\n\\)"))
902 (defvar sh-here-doc-markers nil)
903 (make-variable-buffer-local 'sh-here-doc-markers)
904 (defvar sh-here-doc-re sh-here-doc-open-re)
905 (make-variable-buffer-local 'sh-here-doc-re)
907 (defun sh-font-lock-close-heredoc (bol eof indented)
908 "Determine the syntax of the \\n after an EOF.
909 If non-nil INDENTED indicates that the EOF was indented."
910 (let* ((eof-re (if eof (regexp-quote eof) ""))
911 ;; A rough regexp that should find the opening <<EOF back.
912 (sre (concat "<<\\(-?\\)\\s-*['\"\\]?"
913 ;; Use \s| to cheaply check it's an open-heredoc.
914 eof-re "['\"]?\\([ \t|;&)<>]"
915 sh-escaped-line-re
916 "\\)?\\s|"))
917 ;; A regexp that will find other EOFs.
918 (ere (concat "^" (if indented "[ \t]*") eof-re "\n"))
919 (start (save-excursion
920 (goto-char bol)
921 (re-search-backward (concat sre "\\|" ere) nil t))))
922 ;; If subgroup 1 matched, we found an open-heredoc, otherwise we first
923 ;; found a close-heredoc which makes the current close-heredoc inoperant.
924 (cond
925 ((when (and start (match-end 1)
926 (not (and indented (= (match-beginning 1) (match-end 1))))
927 (not (sh-in-comment-or-string (match-beginning 0))))
928 ;; Make sure our `<<' is not the EOF1 of a `cat <<EOF1 <<EOF2'.
929 (save-excursion
930 (goto-char start)
931 (setq start (line-beginning-position 2))
932 (while
933 (progn
934 (re-search-forward "<<") ; Skip ourselves.
935 (and (re-search-forward sh-here-doc-open-re start 'move)
936 (goto-char (match-beginning 0))
937 (sh-in-comment-or-string (point)))))
938 ;; No <<EOF2 found after our <<.
939 (= (point) start)))
940 sh-here-doc-syntax)
941 ((not (or start (save-excursion (re-search-forward sre nil t))))
942 ;; There's no <<EOF either before or after us,
943 ;; so we should remove ourselves from font-lock's keywords.
944 (setq sh-here-doc-markers (delete eof sh-here-doc-markers))
945 (setq sh-here-doc-re
946 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
947 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))
948 nil))))
950 (defun sh-font-lock-open-heredoc (start string)
951 "Determine the syntax of the \\n after a <<EOF.
952 START is the position of <<.
953 STRING is the actual word used as delimiter (f.ex. \"EOF\").
954 INDENTED is non-nil if the here document's content (and the EOF mark) can
955 be indented (i.e. a <<- was used rather than just <<).
956 Point is at the beginning of the next line."
957 (unless (or (memq (char-before start) '(?< ?>))
958 (sh-in-comment-or-string start))
959 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
960 ;; font-lock keywords to detect the end of this here document.
961 (let ((str (replace-regexp-in-string "['\"]" "" string)))
962 (unless (member str sh-here-doc-markers)
963 (push str sh-here-doc-markers)
964 (setq sh-here-doc-re
965 (concat sh-here-doc-open-re "\\|^\\([ \t]*\\)"
966 (regexp-opt sh-here-doc-markers t) "\\(\n\\)"))))
967 (let ((ppss (save-excursion (syntax-ppss (1- (point))))))
968 (if (nth 4 ppss)
969 ;; The \n not only starts the heredoc but also closes a comment.
970 ;; Let's close the comment just before the \n.
971 (put-text-property (1- (point)) (point) 'syntax-table '(12))) ;">"
972 (if (or (nth 5 ppss) (> (count-lines start (point)) 1))
973 ;; If the sh-escaped-line-re part of sh-here-doc-re has matched
974 ;; several lines, make sure we refontify them together.
975 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
976 ;; escaped), it means the right \n is actually further down.
977 ;; Don't bother fixing it now, but place a multiline property so
978 ;; that when jit-lock-context-* refontifies the rest of the
979 ;; buffer, it also refontifies the current line with it.
980 (put-text-property start (point) 'font-lock-multiline t)))
981 sh-here-doc-syntax))
983 (defun sh-font-lock-here-doc (limit)
984 "Search for a heredoc marker."
985 ;; This looks silly, but it's because `sh-here-doc-re' keeps changing.
986 (re-search-forward sh-here-doc-re limit t))
988 (defun sh-font-lock-quoted-subshell (limit)
989 "Search for a subshell embedded in a string.
990 Find all the unescaped \" characters within said subshell, remembering that
991 subshells can nest."
992 ;; FIXME: This can (and often does) match multiple lines, yet it makes no
993 ;; effort to handle multiline cases correctly, so it ends up being
994 ;; rather flakey.
995 (when (and (re-search-forward "\"\\(?:\\(?:.\\|\n\\)*?[^\\]\\(?:\\\\\\\\\\)*\\)??\\(\\$(\\|`\\)" limit t)
996 ;; Make sure the " we matched is an opening quote.
997 (eq ?\" (nth 3 (syntax-ppss))))
998 ;; bingo we have a $( or a ` inside a ""
999 (let ((char (char-after (point)))
1000 ;; `state' can be: double-quote, backquote, code.
1001 (state (if (eq (char-before) ?`) 'backquote 'code))
1002 ;; Stacked states in the context.
1003 (states '(double-quote)))
1004 (while (and state (progn (skip-chars-forward "^'\\\\\"`$()" limit)
1005 (< (point) limit)))
1006 ;; unescape " inside a $( ... ) construct.
1007 (case (char-after)
1008 (?\' (forward-char 1) (skip-chars-forward "^'" limit))
1009 (?\\ (forward-char 1))
1010 (?\" (case state
1011 (double-quote (setq state (pop states)))
1012 (t (push state states) (setq state 'double-quote)))
1013 (if state (put-text-property (point) (1+ (point))
1014 'syntax-table '(1))))
1015 (?\` (case state
1016 (backquote (setq state (pop states)))
1017 (t (push state states) (setq state 'backquote))))
1018 (?\$ (if (not (eq (char-after (1+ (point))) ?\())
1020 (forward-char 1)
1021 (case state
1022 (t (push state states) (setq state 'code)))))
1023 (?\( (case state
1024 (double-quote nil)
1025 (t (push state states) (setq state 'code))))
1026 (?\) (case state
1027 (double-quote nil)
1028 (t (setq state (pop states)))))
1029 (t (error "Internal error in sh-font-lock-quoted-subshell")))
1030 (forward-char 1)))
1034 (defun sh-is-quoted-p (pos)
1035 (and (eq (char-before pos) ?\\)
1036 (not (sh-is-quoted-p (1- pos)))))
1038 (defun sh-font-lock-paren (start)
1039 (save-excursion
1040 (goto-char start)
1041 ;; Skip through all patterns
1042 (while
1043 (progn
1044 (forward-comment (- (point-max)))
1045 ;; Skip through one pattern
1046 (while
1047 (or (/= 0 (skip-syntax-backward "w_"))
1048 (/= 0 (skip-chars-backward "?[]*@/\\"))
1049 (and (sh-is-quoted-p (1- (point)))
1050 (goto-char (- (point) 2)))
1051 (when (memq (char-before) '(?\" ?\'))
1052 (condition-case nil (progn (backward-sexp 1) t)
1053 (error nil)))))
1054 (while (progn
1055 (forward-comment (- (point-max)))
1056 ;; Maybe we've bumped into an escaped newline.
1057 (sh-is-quoted-p (point)))
1058 (backward-char 1))
1059 (when (eq (char-before) ?|)
1060 (backward-char 1) t)))
1061 ;; FIXME: ";; esac )" is a case that looks like a case-pattern but it's
1062 ;; really just a close paren after a case statement. I.e. if we skipped
1063 ;; over `esac' just now, we're not looking at a case-pattern.
1064 (when (progn (backward-char 2)
1065 (if (> start (line-end-position))
1066 (put-text-property (point) (1+ start)
1067 'font-lock-multiline t))
1068 ;; FIXME: The `in' may just be a random argument to
1069 ;; a normal command rather than the real `in' keyword.
1070 ;; I.e. we should look back to try and find the
1071 ;; corresponding `case'.
1072 (looking-at ";;\\|in"))
1073 sh-st-punc)))
1075 (defun sh-font-lock-backslash-quote ()
1076 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?\')
1077 ;; In a '...' the backslash is not escaping.
1078 sh-st-punc
1079 nil))
1081 (defun sh-font-lock-flush-syntax-ppss-cache (limit)
1082 ;; This should probably be a standard function provided by font-lock.el
1083 ;; (or syntax.el).
1084 (syntax-ppss-flush-cache (point))
1085 (goto-char limit)
1086 nil)
1088 (defconst sh-font-lock-syntactic-keywords
1089 ;; A `#' begins a comment when it is unquoted and at the beginning of a
1090 ;; word. In the shell, words are separated by metacharacters.
1091 ;; The list of special chars is taken from the single-unix spec
1092 ;; of the shell command language (under `quoting') but with `$' removed.
1093 `(("[^|&;<>()`\\\"' \t\n]\\(#+\\)" 1 ,sh-st-symbol)
1094 ;; In a '...' the backslash is not escaping.
1095 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1096 ;; The previous rule uses syntax-ppss, but the subsequent rules may
1097 ;; change the syntax, so we have to tell syntax-ppss that the states it
1098 ;; has just computed will need to be recomputed.
1099 (sh-font-lock-flush-syntax-ppss-cache)
1100 ;; Make sure $@ and $? are correctly recognized as sexps.
1101 ("\\$\\([?@]\\)" 1 ,sh-st-symbol)
1102 ;; Find HEREDOC starters and add a corresponding rule for the ender.
1103 (sh-font-lock-here-doc
1104 (2 (sh-font-lock-open-heredoc
1105 (match-beginning 0) (match-string 1)) nil t)
1106 (5 (sh-font-lock-close-heredoc
1107 (match-beginning 0) (match-string 4)
1108 (and (match-beginning 3) (/= (match-beginning 3) (match-end 3))))
1109 nil t))
1110 ;; Distinguish the special close-paren in `case'.
1111 (")" 0 (sh-font-lock-paren (match-beginning 0)))
1112 ;; highlight (possibly nested) subshells inside "" quoted regions correctly.
1113 ;; This should be at the very end because it uses syntax-ppss.
1114 (sh-font-lock-quoted-subshell)))
1116 (defun sh-font-lock-syntactic-face-function (state)
1117 (let ((q (nth 3 state)))
1118 (if q
1119 (if (characterp q)
1120 (if (eq q ?\`) 'sh-quoted-exec font-lock-string-face)
1121 sh-heredoc-face)
1122 font-lock-comment-face)))
1124 (defgroup sh-indentation nil
1125 "Variables controlling indentation in shell scripts.
1127 Note: customizing these variables will not affect existing buffers if
1128 `sh-make-vars-local' is no-nil. See the documentation for
1129 variable `sh-make-vars-local', command `sh-make-vars-local'
1130 and command `sh-reset-indent-vars-to-global-values'."
1131 :group 'sh-script)
1134 (defcustom sh-set-shell-hook nil
1135 "Hook run by `sh-set-shell'."
1136 :type 'hook
1137 :group 'sh-script)
1139 (defcustom sh-mode-hook nil
1140 "Hook run by `sh-mode'."
1141 :type 'hook
1142 :group 'sh-script)
1144 (defcustom sh-learn-basic-offset nil
1145 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1147 nil mean: never.
1148 t means: only if there seems to be an obvious value.
1149 Anything else means: whenever we have a \"good guess\" as to the value."
1150 :type '(choice
1151 (const :tag "Never" nil)
1152 (const :tag "Only if sure" t)
1153 (const :tag "If have a good guess" usually))
1154 :group 'sh-indentation)
1156 (defcustom sh-popup-occur-buffer nil
1157 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1158 If t it is always shown. If nil, it is shown only when there
1159 are conflicts."
1160 :type '(choice
1161 (const :tag "Only when there are conflicts." nil)
1162 (const :tag "Always" t))
1163 :group 'sh-indentation)
1165 (defcustom sh-blink t
1166 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
1167 The position on the line is not necessarily meaningful.
1168 In some cases the line will be the matching keyword, but this is not
1169 always the case."
1170 :type 'boolean
1171 :group 'sh-indentation)
1173 (defcustom sh-first-lines-indent 0
1174 "The indentation of the first non-blank non-comment line.
1175 Usually 0 meaning first column.
1176 Can be set to a number, or to nil which means leave it as is."
1177 :type '(choice
1178 (const :tag "Leave as is" nil)
1179 (integer :tag "Column number"
1180 :menu-tag "Indent to this col (0 means first col)" ))
1181 :group 'sh-indentation)
1184 (defcustom sh-basic-offset 4
1185 "The default indentation increment.
1186 This value is used for the `+' and `-' symbols in an indentation variable."
1187 :type 'integer
1188 :group 'sh-indentation)
1189 (put 'sh-basic-offset 'safe-local-variable 'integerp)
1191 (defcustom sh-indent-comment nil
1192 "How a comment line is to be indented.
1193 nil means leave it as it is;
1194 t means indent it as a normal line, aligning it to previous non-blank
1195 non-comment line;
1196 a number means align to that column, e.g. 0 means first column."
1197 :type '(choice
1198 (const :tag "Leave as is." nil)
1199 (const :tag "Indent as a normal line." t)
1200 (integer :menu-tag "Indent to this col (0 means first col)."
1201 :tag "Indent to column number.") )
1202 :group 'sh-indentation)
1205 (defvar sh-debug nil
1206 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1209 ;; Uncomment this defun and comment the defmacro for debugging.
1210 ;; (defun sh-debug (&rest args)
1211 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1212 ;; (if sh-debug
1213 ;; (apply 'message args)))
1214 (defmacro sh-debug (&rest args))
1216 (defconst sh-symbol-list
1217 '((const :tag "+ " :value +
1218 :menu-tag "+ Indent right by sh-basic-offset")
1219 (const :tag "- " :value -
1220 :menu-tag "- Indent left by sh-basic-offset")
1221 (const :tag "++" :value ++
1222 :menu-tag "++ Indent right twice sh-basic-offset")
1223 (const :tag "--" :value --
1224 :menu-tag "-- Indent left twice sh-basic-offset")
1225 (const :tag "* " :value *
1226 :menu-tag "* Indent right half sh-basic-offset")
1227 (const :tag "/ " :value /
1228 :menu-tag "/ Indent left half sh-basic-offset")))
1230 (defcustom sh-indent-for-else 0
1231 "How much to indent an `else' relative to its `if'. Usually 0."
1232 :type `(choice
1233 (integer :menu-tag "A number (positive=>indent right)"
1234 :tag "A number")
1235 (const :tag "--") ;; separator!
1236 ,@ sh-symbol-list
1238 :group 'sh-indentation)
1240 (defconst sh-number-or-symbol-list
1241 (append '((integer :menu-tag "A number (positive=>indent right)"
1242 :tag "A number")
1243 (const :tag "--")) ; separator
1244 sh-symbol-list))
1246 (defcustom sh-indent-for-fi 0
1247 "How much to indent a `fi' relative to its `if'. Usually 0."
1248 :type `(choice ,@ sh-number-or-symbol-list )
1249 :group 'sh-indentation)
1251 (defcustom sh-indent-for-done 0
1252 "How much to indent a `done' relative to its matching stmt. Usually 0."
1253 :type `(choice ,@ sh-number-or-symbol-list )
1254 :group 'sh-indentation)
1256 (defcustom sh-indent-after-else '+
1257 "How much to indent a statement after an `else' statement."
1258 :type `(choice ,@ sh-number-or-symbol-list )
1259 :group 'sh-indentation)
1261 (defcustom sh-indent-after-if '+
1262 "How much to indent a statement after an `if' statement.
1263 This includes lines after `else' and `elif' statements, too, but
1264 does not affect the `else', `elif' or `fi' statements themselves."
1265 :type `(choice ,@ sh-number-or-symbol-list )
1266 :group 'sh-indentation)
1268 (defcustom sh-indent-for-then 0
1269 "How much to indent a `then' relative to its `if'."
1270 :type `(choice ,@ sh-number-or-symbol-list )
1271 :group 'sh-indentation)
1273 (defcustom sh-indent-for-do 0
1274 "How much to indent a `do' statement.
1275 This is relative to the statement before the `do', typically a
1276 `while', `until', `for', `repeat' or `select' statement."
1277 :type `(choice ,@ sh-number-or-symbol-list)
1278 :group 'sh-indentation)
1280 (defcustom sh-indent-after-do '+
1281 "How much to indent a line after a `do' statement.
1282 This is used when the `do' is the first word of the line.
1283 This is relative to the statement before the `do', typically a
1284 `while', `until', `for', `repeat' or `select' statement."
1285 :type `(choice ,@ sh-number-or-symbol-list)
1286 :group 'sh-indentation)
1288 (defcustom sh-indent-after-loop-construct '+
1289 "How much to indent a statement after a loop construct.
1291 This variable is used when the keyword `do' is on the same line as the
1292 loop statement (e.g., `until', `while' or `for').
1293 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1294 :type `(choice ,@ sh-number-or-symbol-list)
1295 :group 'sh-indentation)
1298 (defcustom sh-indent-after-done 0
1299 "How much to indent a statement after a `done' keyword.
1300 Normally this is 0, which aligns the `done' to the matching
1301 looping construct line.
1302 Setting it non-zero allows you to have the `do' statement on a line
1303 by itself and align the done under to do."
1304 :type `(choice ,@ sh-number-or-symbol-list)
1305 :group 'sh-indentation)
1307 (defcustom sh-indent-for-case-label '+
1308 "How much to indent a case label statement.
1309 This is relative to the line containing the `case' statement."
1310 :type `(choice ,@ sh-number-or-symbol-list)
1311 :group 'sh-indentation)
1313 (defcustom sh-indent-for-case-alt '++
1314 "How much to indent statements after the case label.
1315 This is relative to the line containing the `case' statement."
1316 :type `(choice ,@ sh-number-or-symbol-list)
1317 :group 'sh-indentation)
1320 (defcustom sh-indent-for-continuation '+
1321 "How much to indent for a continuation statement."
1322 :type `(choice ,@ sh-number-or-symbol-list)
1323 :group 'sh-indentation)
1325 (defcustom sh-indent-after-open '+
1326 "How much to indent after a line with an opening parenthesis or brace.
1327 For an open paren after a function, `sh-indent-after-function' is used."
1328 :type `(choice ,@ sh-number-or-symbol-list)
1329 :group 'sh-indentation)
1331 (defcustom sh-indent-after-function '+
1332 "How much to indent after a function line."
1333 :type `(choice ,@ sh-number-or-symbol-list)
1334 :group 'sh-indentation)
1336 ;; These 2 are for the rc shell:
1338 (defcustom sh-indent-after-switch '+
1339 "How much to indent a `case' statement relative to the `switch' statement.
1340 This is for the rc shell."
1341 :type `(choice ,@ sh-number-or-symbol-list)
1342 :group 'sh-indentation)
1344 (defcustom sh-indent-after-case '+
1345 "How much to indent a statement relative to the `case' statement.
1346 This is for the rc shell."
1347 :type `(choice ,@ sh-number-or-symbol-list)
1348 :group 'sh-indentation)
1350 (defcustom sh-backslash-column 48
1351 "Column in which `sh-backslash-region' inserts backslashes."
1352 :type 'integer
1353 :group 'sh)
1355 (defcustom sh-backslash-align t
1356 "If non-nil, `sh-backslash-region' will align backslashes."
1357 :type 'boolean
1358 :group 'sh)
1360 ;; Internal use - not designed to be changed by the user:
1362 (defun sh-mkword-regexpr (word)
1363 "Make a regexp which matches WORD as a word.
1364 This specifically excludes an occurrence of WORD followed by
1365 punctuation characters like '-'."
1366 (concat word "\\([^-[:alnum:]_]\\|$\\)"))
1368 (defconst sh-re-done (sh-mkword-regexpr "done"))
1371 (defconst sh-kws-for-done
1372 '((sh . ( "while" "until" "for" ) )
1373 (bash . ( "while" "until" "for" "select" ) )
1374 (ksh88 . ( "while" "until" "for" "select" ) )
1375 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1376 "Which keywords can match the word `done' in this shell.")
1379 (defconst sh-indent-supported
1380 '((sh . t)
1381 (csh . nil)
1382 (rc . t))
1383 "Shell types that shell indenting can do something with.")
1385 (defvar sh-indent-supported-here nil
1386 "Non-nil if we support indentation for the current buffer's shell type.")
1388 (defconst sh-var-list
1390 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1391 sh-indent-after-do sh-indent-after-done
1392 sh-indent-after-else
1393 sh-indent-after-if
1394 sh-indent-after-loop-construct
1395 sh-indent-after-open
1396 sh-indent-comment
1397 sh-indent-for-case-alt
1398 sh-indent-for-case-label
1399 sh-indent-for-continuation
1400 sh-indent-for-do
1401 sh-indent-for-done
1402 sh-indent-for-else
1403 sh-indent-for-fi
1404 sh-indent-for-then
1406 "A list of variables used by script mode to control indentation.
1407 This list is used when switching between buffer-local and global
1408 values of variables, and for the commands using indentation styles.")
1410 (defvar sh-make-vars-local t
1411 "*Controls whether indentation variables are local to the buffer.
1412 If non-nil, indentation variables are made local initially.
1413 If nil, you can later make the variables local by invoking
1414 command `sh-make-vars-local'.
1415 The default is t because I assume that in one Emacs session one is
1416 frequently editing existing scripts with different styles.")
1419 ;; mode-command and utility functions
1421 ;;;###autoload
1422 (defun sh-mode ()
1423 "Major mode for editing shell scripts.
1424 This mode works for many shells, since they all have roughly the same syntax,
1425 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1426 Unless the file's magic number indicates the shell, your usual shell is
1427 assumed. Since filenames rarely give a clue, they are not further analyzed.
1429 This mode adapts to the variations between shells (see `sh-set-shell') by
1430 means of an inheritance based feature lookup (see `sh-feature'). This
1431 mechanism applies to all variables (including skeletons) that pertain to
1432 shell-specific features.
1434 The default style of this mode is that of Rosenblatt's Korn shell book.
1435 The syntax of the statements varies with the shell being used. The
1436 following commands are available, based on the current shell's syntax:
1437 \\<sh-mode-map>
1438 \\[sh-case] case statement
1439 \\[sh-for] for loop
1440 \\[sh-function] function definition
1441 \\[sh-if] if statement
1442 \\[sh-indexed-loop] indexed loop from 1 to n
1443 \\[sh-while-getopts] while getopts loop
1444 \\[sh-repeat] repeat loop
1445 \\[sh-select] select loop
1446 \\[sh-until] until loop
1447 \\[sh-while] while loop
1449 For sh and rc shells indentation commands are:
1450 \\[sh-show-indent] Show the variable controlling this line's indentation.
1451 \\[sh-set-indent] Set then variable controlling this line's indentation.
1452 \\[sh-learn-line-indent] Change the indentation variable so this line
1453 would indent to the way it currently is.
1454 \\[sh-learn-buffer-indent] Set the indentation variables so the
1455 buffer indents as it currently is indented.
1458 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1459 \\[sh-newline-and-indent] Delete unquoted space and indent new line same as this one.
1460 \\[sh-end-of-command] Go to end of successive commands.
1461 \\[sh-beginning-of-command] Go to beginning of successive commands.
1462 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1463 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1465 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
1466 \{, (, [, ', \", `
1467 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1469 If you generally program a shell different from your login shell you can
1470 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1471 indicate what shell it is use `sh-alias-alist' to translate.
1473 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1474 with your script for an edit-interpret-debug cycle."
1475 (interactive)
1476 (kill-all-local-variables)
1477 (setq major-mode 'sh-mode
1478 mode-name "Shell-script")
1479 (use-local-map sh-mode-map)
1480 (make-local-variable 'skeleton-end-hook)
1481 (make-local-variable 'paragraph-start)
1482 (make-local-variable 'paragraph-separate)
1483 (make-local-variable 'comment-start)
1484 (make-local-variable 'comment-start-skip)
1485 (make-local-variable 'require-final-newline)
1486 (make-local-variable 'sh-header-marker)
1487 (make-local-variable 'sh-shell-file)
1488 (make-local-variable 'sh-shell)
1489 (make-local-variable 'skeleton-pair-alist)
1490 (make-local-variable 'skeleton-pair-filter-function)
1491 (make-local-variable 'comint-dynamic-complete-functions)
1492 (make-local-variable 'comint-prompt-regexp)
1493 (make-local-variable 'font-lock-defaults)
1494 (make-local-variable 'skeleton-filter-function)
1495 (make-local-variable 'skeleton-newline-indent-rigidly)
1496 (make-local-variable 'sh-shell-variables)
1497 (make-local-variable 'sh-shell-variables-initialized)
1498 (make-local-variable 'imenu-generic-expression)
1499 (make-local-variable 'sh-indent-supported-here)
1500 (make-local-variable 'skeleton-pair-default-alist)
1501 (setq skeleton-pair-default-alist sh-skeleton-pair-default-alist)
1502 (setq skeleton-end-hook (lambda ()
1503 (or (eolp) (newline) (indent-relative)))
1504 paragraph-start (concat page-delimiter "\\|$")
1505 paragraph-separate paragraph-start
1506 comment-start "# "
1507 comment-start-skip "#+[\t ]*"
1508 local-abbrev-table sh-mode-abbrev-table
1509 comint-dynamic-complete-functions sh-dynamic-complete-functions
1510 ;; we can't look if previous line ended with `\'
1511 comint-prompt-regexp "^[ \t]*"
1512 imenu-case-fold-search nil
1513 font-lock-defaults
1514 `((sh-font-lock-keywords
1515 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1516 nil nil
1517 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1518 (font-lock-syntactic-keywords . sh-font-lock-syntactic-keywords)
1519 (font-lock-syntactic-face-function
1520 . sh-font-lock-syntactic-face-function))
1521 skeleton-pair-alist '((?` _ ?`))
1522 skeleton-pair-filter-function 'sh-quoted-p
1523 skeleton-further-elements '((< '(- (min sh-indentation
1524 (current-column)))))
1525 skeleton-filter-function 'sh-feature
1526 skeleton-newline-indent-rigidly t
1527 sh-indent-supported-here nil)
1528 (set (make-local-variable 'defun-prompt-regexp)
1529 (concat "^\\(function[ \t]\\|[[:alnum:]]+[ \t]+()[ \t]+\\)"))
1530 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1531 ;; Parse or insert magic number for exec, and set all variables depending
1532 ;; on the shell thus determined.
1533 (sh-set-shell
1534 (cond ((save-excursion
1535 (goto-char (point-min))
1536 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1537 (match-string 2))
1538 ((not buffer-file-name)
1539 sh-shell-file)
1540 ;; Checks that use `buffer-file-name' follow.
1541 ((string-match "\\.m?spec\\'" buffer-file-name)
1542 "rpm")
1543 ((string-match "[.]sh\\>" buffer-file-name)
1544 "sh")
1545 ((string-match "[.]bash\\>" buffer-file-name)
1546 "bash")
1547 ((string-match "[.]ksh\\>" buffer-file-name)
1548 "ksh")
1549 ((string-match "[.]csh\\>" buffer-file-name)
1550 "csh")
1551 ((equal (file-name-nondirectory buffer-file-name) ".profile")
1552 "sh")
1554 sh-shell-file))
1555 nil nil)
1556 (run-mode-hooks 'sh-mode-hook))
1558 ;;;###autoload
1559 (defalias 'shell-script-mode 'sh-mode)
1562 (defun sh-font-lock-keywords (&optional keywords)
1563 "Function to get simple fontification based on `sh-font-lock-keywords'.
1564 This adds rules for comments and assignments."
1565 (sh-feature sh-font-lock-keywords-var
1566 (when (stringp (sh-feature sh-assignment-regexp))
1567 (lambda (list)
1568 `((,(sh-feature sh-assignment-regexp)
1569 1 font-lock-variable-name-face)
1570 ,@keywords
1571 ,@list
1572 ,@executable-font-lock-keywords)))))
1574 (defun sh-font-lock-keywords-1 (&optional builtins)
1575 "Function to get better fontification including keywords."
1576 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1577 (regexp-opt (sh-feature sh-leading-keywords) t)
1578 "[ \t]+\\)?"
1579 (regexp-opt (append (sh-feature sh-leading-keywords)
1580 (sh-feature sh-other-keywords))
1581 t))))
1582 (sh-font-lock-keywords
1583 `(,@(if builtins
1584 `((,(concat keywords "[ \t]+\\)?"
1585 (regexp-opt (sh-feature sh-builtins) t)
1586 "\\>")
1587 (2 font-lock-keyword-face nil t)
1588 (6 font-lock-builtin-face))
1589 ,@(sh-feature sh-font-lock-keywords-var-2)))
1590 (,(concat keywords "\\)\\>")
1591 2 font-lock-keyword-face)
1592 ,@(sh-feature sh-font-lock-keywords-var-1)))))
1594 (defun sh-font-lock-keywords-2 ()
1595 "Function to get better fontification including keywords and builtins."
1596 (sh-font-lock-keywords-1 t))
1599 (defvar sh-regexp-for-done nil
1600 "A buffer-local regexp to match opening keyword for done.")
1602 (defvar sh-kw-alist nil
1603 "A buffer-local, since it is shell-type dependent, list of keywords.")
1605 ;; ( key-word first-on-this on-prev-line )
1606 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1607 ;; having 3 elements:
1608 ;; a keyword
1609 ;; a rule to check when the keyword appears on "this" line
1610 ;; a rule to check when the keyword appears on "the previous" line
1611 ;; The keyword is usually a string and is the first word on a line.
1612 ;; If this keyword appears on the line whose indentation is to be
1613 ;; calculated, the rule in element 2 is called. If this returns
1614 ;; non-zero, the resulting point (which may be changed by the rule)
1615 ;; is used as the default indentation.
1616 ;; If it returned false or the keyword was not found in the table,
1617 ;; then the keyword from the previous line is looked up and the rule
1618 ;; in element 3 is called. In this case, however,
1619 ;; `sh-get-indent-info' does not stop but may keep going and test
1620 ;; other keywords against rules in element 3. This is because the
1621 ;; preceding line could have, for example, an opening "if" and an
1622 ;; opening "while" keyword and we need to add the indentation offsets
1623 ;; for both.
1625 (defconst sh-kw
1626 '((sh
1627 ("if" nil sh-handle-prev-if)
1628 ("elif" sh-handle-this-else sh-handle-prev-else)
1629 ("else" sh-handle-this-else sh-handle-prev-else)
1630 ("fi" sh-handle-this-fi sh-handle-prev-fi)
1631 ("then" sh-handle-this-then sh-handle-prev-then)
1632 ("(" nil sh-handle-prev-open)
1633 ("{" nil sh-handle-prev-open)
1634 ("[" nil sh-handle-prev-open)
1635 ("}" sh-handle-this-close nil)
1636 (")" sh-handle-this-close nil)
1637 ("]" sh-handle-this-close nil)
1638 ("case" nil sh-handle-prev-case)
1639 ("esac" sh-handle-this-esac sh-handle-prev-esac)
1640 (case-label nil sh-handle-after-case-label) ;; ???
1641 (";;" nil sh-handle-prev-case-alt-end) ;; ???
1642 ("done" sh-handle-this-done sh-handle-prev-done)
1643 ("do" sh-handle-this-do sh-handle-prev-do))
1645 ;; Note: we don't need specific stuff for bash and zsh shells;
1646 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1647 ;; these shells use.
1649 ("{" nil sh-handle-prev-open)
1650 ("}" sh-handle-this-close nil)
1651 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
1655 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
1656 "Set this buffer's shell to SHELL (a string).
1657 When used interactively, insert the proper starting #!-line,
1658 and make the visited file executable via `executable-set-magic',
1659 perhaps querying depending on the value of `executable-query'.
1661 When this function is called noninteractively, INSERT-FLAG (the third
1662 argument) controls whether to insert a #!-line and think about making
1663 the visited file executable, and NO-QUERY-FLAG (the second argument)
1664 controls whether to query about making the visited file executable.
1666 Calls the value of `sh-set-shell-hook' if set."
1667 (interactive (list (completing-read (format "Shell \(default %s\): "
1668 sh-shell-file)
1669 interpreter-mode-alist
1670 (lambda (x) (eq (cdr x) 'sh-mode))
1671 nil nil nil sh-shell-file)
1672 (eq executable-query 'function)
1674 (if (string-match "\\.exe\\'" shell)
1675 (setq shell (substring shell 0 (match-beginning 0))))
1676 (setq sh-shell (intern (file-name-nondirectory shell))
1677 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
1678 sh-shell))
1679 (if insert-flag
1680 (setq sh-shell-file
1681 (executable-set-magic shell (sh-feature sh-shell-arg)
1682 no-query-flag insert-flag)))
1683 (let ((tem (sh-feature sh-require-final-newline)))
1684 (if (eq tem t)
1685 (setq require-final-newline mode-require-final-newline)))
1686 (setq
1687 mode-line-process (format "[%s]" sh-shell)
1688 sh-shell-variables nil
1689 sh-shell-variables-initialized nil
1690 imenu-generic-expression (sh-feature sh-imenu-generic-expression))
1691 (make-local-variable 'sh-mode-syntax-table)
1692 (let ((tem (sh-feature sh-mode-syntax-table-input)))
1693 (setq sh-mode-syntax-table
1694 (if tem (apply 'sh-mode-syntax-table tem)
1695 sh-mode-default-syntax-table)))
1696 (set-syntax-table sh-mode-syntax-table)
1697 (dolist (var (sh-feature sh-variables))
1698 (sh-remember-variable var))
1699 (make-local-variable 'indent-line-function)
1700 (if (setq sh-indent-supported-here (sh-feature sh-indent-supported))
1701 (progn
1702 (message "Setting up indent for shell type %s" sh-shell)
1703 (set (make-local-variable 'parse-sexp-lookup-properties) t)
1704 (set (make-local-variable 'sh-kw-alist) (sh-feature sh-kw))
1705 (let ((regexp (sh-feature sh-kws-for-done)))
1706 (if regexp
1707 (set (make-local-variable 'sh-regexp-for-done)
1708 (sh-mkword-regexpr (regexp-opt regexp t)))))
1709 (message "setting up indent stuff")
1710 ;; sh-mode has already made indent-line-function local
1711 ;; but do it in case this is called before that.
1712 (setq indent-line-function 'sh-indent-line)
1713 (if sh-make-vars-local
1714 (sh-make-vars-local))
1715 (message "Indentation setup for shell type %s" sh-shell))
1716 (message "No indentation for this shell type.")
1717 (setq indent-line-function 'sh-basic-indent-line))
1718 (when font-lock-mode
1719 (setq font-lock-set-defaults nil)
1720 (font-lock-set-defaults)
1721 (font-lock-fontify-buffer))
1722 (run-hooks 'sh-set-shell-hook))
1725 (defun sh-feature (alist &optional function)
1726 "Index ALIST by the current shell.
1727 If ALIST isn't a list where every element is a cons, it is returned as is.
1728 Else indexing follows an inheritance logic which works in two ways:
1730 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1731 the alist contains no value for the current shell.
1732 The ultimate default is always `sh'.
1734 - If the value thus looked up is a list starting with `sh-append',
1735 we call the function `sh-append' with the rest of the list as
1736 arguments, and use the value. However, the next element of the
1737 list is not used as-is; instead, we look it up recursively
1738 in ALIST to allow the function called to define the value for
1739 one shell to be derived from another shell.
1740 The value thus determined is physically replaced into the alist.
1742 If FUNCTION is non-nil, it is called with one argument,
1743 the value thus obtained, and the result is used instead."
1744 (or (if (consp alist)
1745 ;; Check for something that isn't a valid alist.
1746 (let ((l alist))
1747 (while (and l (consp (car l)))
1748 (setq l (cdr l)))
1749 (if l alist)))
1751 (let ((orig-sh-shell sh-shell))
1752 (let ((sh-shell sh-shell)
1753 elt val)
1754 (while (and sh-shell
1755 (not (setq elt (assq sh-shell alist))))
1756 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
1757 ;; If the shell is not known, treat it as sh.
1758 (unless elt
1759 (setq elt (assq 'sh alist)))
1760 (setq val (cdr elt))
1761 (if (and (consp val)
1762 (memq (car val) '(sh-append sh-modify)))
1763 (setq val
1764 (apply (car val)
1765 ;; Refer to the value for a different shell,
1766 ;; as a kind of inheritance.
1767 (let ((sh-shell (car (cdr val))))
1768 (sh-feature alist))
1769 (cddr val))))
1770 (if function
1771 (setq sh-shell orig-sh-shell
1772 val (funcall function val)))
1773 val))))
1777 ;; I commented this out because nobody calls it -- rms.
1778 ;;(defun sh-abbrevs (ancestor &rest list)
1779 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
1780 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1781 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1782 ;;according to the remaining arguments NAMEi EXPANSIONi ...
1783 ;;EXPANSION may be either a string or a skeleton command."
1784 ;; (or (if (boundp sh-shell)
1785 ;; (symbol-value sh-shell))
1786 ;; (progn
1787 ;; (if (listp ancestor)
1788 ;; (nconc list ancestor))
1789 ;; (define-abbrev-table sh-shell ())
1790 ;; (if (vectorp ancestor)
1791 ;; (mapatoms (lambda (atom)
1792 ;; (or (eq atom 0)
1793 ;; (define-abbrev (symbol-value sh-shell)
1794 ;; (symbol-name atom)
1795 ;; (symbol-value atom)
1796 ;; (symbol-function atom))))
1797 ;; ancestor))
1798 ;; (while list
1799 ;; (define-abbrev (symbol-value sh-shell)
1800 ;; (car list)
1801 ;; (if (stringp (car (cdr list)))
1802 ;; (car (cdr list))
1803 ;; "")
1804 ;; (if (symbolp (car (cdr list)))
1805 ;; (car (cdr list))))
1806 ;; (setq list (cdr (cdr list)))))
1807 ;; (symbol-value sh-shell)))
1810 (defun sh-append (ancestor &rest list)
1811 "Return list composed of first argument (a list) physically appended to rest."
1812 (nconc list ancestor))
1815 (defun sh-modify (skeleton &rest list)
1816 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1817 (setq skeleton (copy-sequence skeleton))
1818 (while list
1819 (setcar (or (nthcdr (car list) skeleton)
1820 (error "Index %d out of bounds" (car list)))
1821 (car (cdr list)))
1822 (setq list (nthcdr 2 list)))
1823 skeleton)
1826 (defun sh-basic-indent-line ()
1827 "Indent a line for Sh mode (shell script mode).
1828 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1829 Lines containing only comments are considered empty."
1830 (interactive)
1831 (let ((previous (save-excursion
1832 (while (and (progn (beginning-of-line)
1833 (not (bobp)))
1834 (progn
1835 (forward-line -1)
1836 (back-to-indentation)
1837 (or (eolp)
1838 (eq (following-char) ?#)))))
1839 (current-column)))
1840 current)
1841 (save-excursion
1842 (indent-to (if (eq this-command 'newline-and-indent)
1843 previous
1844 (if (< (current-column)
1845 (setq current (progn (back-to-indentation)
1846 (current-column))))
1847 (if (eolp) previous 0)
1848 (delete-region (point)
1849 (progn (beginning-of-line) (point)))
1850 (if (eolp)
1851 (max previous (* (1+ (/ current sh-indentation))
1852 sh-indentation))
1853 (* (1+ (/ current sh-indentation)) sh-indentation))))))
1854 (if (< (current-column) (current-indentation))
1855 (skip-chars-forward " \t"))))
1858 (defun sh-execute-region (start end &optional flag)
1859 "Pass optional header and region to a subshell for noninteractive execution.
1860 The working directory is that of the buffer, and only environment variables
1861 are already set which is why you can mark a header within the script.
1863 With a positive prefix ARG, instead of sending region, define header from
1864 beginning of buffer to point. With a negative prefix ARG, instead of sending
1865 region, clear header."
1866 (interactive "r\nP")
1867 (if flag
1868 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
1869 (point-marker)))
1870 (if sh-header-marker
1871 (save-excursion
1872 (let (buffer-undo-list)
1873 (goto-char sh-header-marker)
1874 (append-to-buffer (current-buffer) start end)
1875 (shell-command-on-region (point-min)
1876 (setq end (+ sh-header-marker
1877 (- end start)))
1878 sh-shell-file)
1879 (delete-region sh-header-marker end)))
1880 (shell-command-on-region start end (concat sh-shell-file " -")))))
1883 (defun sh-remember-variable (var)
1884 "Make VARIABLE available for future completing reads in this buffer."
1885 (or (< (length var) sh-remember-variable-min)
1886 (getenv var)
1887 (assoc var sh-shell-variables)
1888 (push (cons var var) sh-shell-variables))
1889 var)
1893 (defun sh-quoted-p ()
1894 "Is point preceded by an odd number of backslashes?"
1895 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
1897 ;; Indentation stuff.
1898 (defun sh-must-support-indent ()
1899 "*Signal an error if the shell type for this buffer is not supported.
1900 Also, the buffer must be in Shell-script mode."
1901 (unless sh-indent-supported-here
1902 (error "This buffer's shell does not support indentation through Emacs")))
1904 (defun sh-make-vars-local ()
1905 "Make the indentation variables local to this buffer.
1906 Normally they already are local. This command is provided in case
1907 variable `sh-make-vars-local' has been set to nil.
1909 To revert all these variables to the global values, use
1910 command `sh-reset-indent-vars-to-global-values'."
1911 (interactive)
1912 (mapc 'make-local-variable sh-var-list)
1913 (message "Indentation variables are now local."))
1915 (defun sh-reset-indent-vars-to-global-values ()
1916 "Reset local indentation variables to the global values.
1917 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1918 (interactive)
1919 (mapc 'kill-local-variable sh-var-list)
1920 (if sh-make-vars-local
1921 (mapcar 'make-local-variable sh-var-list)))
1924 ;; Theoretically these are only needed in shell and derived modes.
1925 ;; However, the routines which use them are only called in those modes.
1926 (defconst sh-special-keywords "then\\|do")
1928 (defun sh-help-string-for-variable (var)
1929 "Construct a string for `sh-read-variable' when changing variable VAR ."
1930 (let ((msg (documentation-property var 'variable-documentation))
1931 (msg2 ""))
1932 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
1933 (setq msg2
1934 (format "\n
1935 You can enter a number (positive to increase indentation,
1936 negative to decrease indentation, zero for no change to indentation).
1938 Or, you can enter one of the following symbols which are relative to
1939 the value of variable `sh-basic-offset'
1940 which in this buffer is currently %s.
1942 \t%s."
1943 sh-basic-offset
1944 (mapconcat (lambda (x)
1945 (nth (1- (length x)) x))
1946 sh-symbol-list "\n\t"))))
1947 (concat
1948 ;; The following shows the global not the local value!
1949 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1950 msg msg2)))
1952 (defun sh-read-variable (var)
1953 "Read a new value for indentation variable VAR."
1954 (interactive "*variable? ") ;; to test
1955 (let ((minibuffer-help-form `(sh-help-string-for-variable
1956 (quote ,var)))
1957 val)
1958 (setq val (read-from-minibuffer
1959 (format "New value for %s (press %s for help): "
1960 var (single-key-description help-char))
1961 (format "%s" (symbol-value var))
1962 nil t))
1963 val))
1967 (defun sh-in-comment-or-string (start)
1968 "Return non-nil if START is in a comment or string."
1969 (save-excursion
1970 (let ((state (syntax-ppss start)))
1971 (or (nth 3 state) (nth 4 state)))))
1973 (defun sh-goto-matching-if ()
1974 "Go to the matching if for a fi.
1975 This handles nested if..fi pairs."
1976 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1977 (if found
1978 (goto-char found))))
1981 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1982 ;; line whose indentation is being handled contain XXX;
1983 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
1985 (defun sh-handle-prev-if ()
1986 (list '(+ sh-indent-after-if)))
1988 (defun sh-handle-this-else ()
1989 (if (sh-goto-matching-if)
1990 ;; (list "aligned to if")
1991 (list "aligned to if" '(+ sh-indent-for-else))
1995 (defun sh-handle-prev-else ()
1996 (if (sh-goto-matching-if)
1997 (list '(+ sh-indent-after-if))
2000 (defun sh-handle-this-fi ()
2001 (if (sh-goto-matching-if)
2002 (list "aligned to if" '(+ sh-indent-for-fi))
2006 (defun sh-handle-prev-fi ()
2007 ;; Why do we have this rule? Because we must go back to the if
2008 ;; to get its indent. We may continue back from there.
2009 ;; We return nil because we don't have anything to add to result,
2010 ;; the side affect of setting align-point is all that matters.
2011 ;; we could return a comment (a string) but I can't think of a good one...
2012 (sh-goto-matching-if)
2013 nil)
2015 (defun sh-handle-this-then ()
2016 (let ((p (sh-goto-matching-if)))
2017 (if p
2018 (list '(+ sh-indent-for-then))
2021 (defun sh-handle-prev-then ()
2022 (let ((p (sh-goto-matching-if)))
2023 (if p
2024 (list '(+ sh-indent-after-if))
2027 (defun sh-handle-prev-open ()
2028 (save-excursion
2029 (let ((x (sh-prev-stmt)))
2030 (if (and x
2031 (progn
2032 (goto-char x)
2034 (looking-at "function\\b")
2035 (looking-at "\\s-*\\S-+\\s-*()")
2037 (list '(+ sh-indent-after-function))
2038 (list '(+ sh-indent-after-open)))
2041 (defun sh-handle-this-close ()
2042 (forward-char 1) ;; move over ")"
2043 (if (sh-safe-forward-sexp -1)
2044 (list "aligned to opening paren")))
2046 (defun sh-goto-matching-case ()
2047 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2048 (if found (goto-char found))))
2050 (defun sh-handle-prev-case ()
2051 ;; This is typically called when point is on same line as a case
2052 ;; we shouldn't -- and can't find prev-case
2053 (if (looking-at ".*\\<case\\>")
2054 (list '(+ sh-indent-for-case-label))
2055 (error "We don't seem to be on a line with a case"))) ;; debug
2057 (defun sh-handle-this-esac ()
2058 (if (sh-goto-matching-case)
2059 (list "aligned to matching case")))
2061 (defun sh-handle-prev-esac ()
2062 (if (sh-goto-matching-case)
2063 (list "matching case")))
2065 (defun sh-handle-after-case-label ()
2066 (if (sh-goto-matching-case)
2067 (list '(+ sh-indent-for-case-alt))))
2069 (defun sh-handle-prev-case-alt-end ()
2070 (if (sh-goto-matching-case)
2071 (list '(+ sh-indent-for-case-label))))
2073 (defun sh-safe-forward-sexp (&optional arg)
2074 "Try and do a `forward-sexp', but do not error.
2075 Return new point if successful, nil if an error occurred."
2076 (condition-case nil
2077 (progn
2078 (forward-sexp (or arg 1))
2079 (point)) ;; return point if successful
2080 (error
2081 (sh-debug "oops!(1) %d" (point))
2082 nil))) ;; return nil if fail
2084 (defun sh-goto-match-for-done ()
2085 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2086 (if found
2087 (goto-char found))))
2089 (defun sh-handle-this-done ()
2090 (if (sh-goto-match-for-done)
2091 (list "aligned to do stmt" '(+ sh-indent-for-done))))
2093 (defun sh-handle-prev-done ()
2094 (if (sh-goto-match-for-done)
2095 (list "previous done")))
2097 (defun sh-handle-this-do ()
2098 (if (sh-goto-match-for-done)
2099 (list '(+ sh-indent-for-do))))
2101 (defun sh-handle-prev-do ()
2102 (cond
2103 ((save-restriction
2104 (narrow-to-region
2105 (point)
2106 (save-excursion
2107 (beginning-of-line)
2108 (point)))
2109 (sh-goto-match-for-done))
2110 (sh-debug "match for done found on THIS line")
2111 (list '(+ sh-indent-after-loop-construct)))
2112 ((sh-goto-match-for-done)
2113 (sh-debug "match for done found on PREV line")
2114 (list '(+ sh-indent-after-do)))
2116 (message "match for done NOT found")
2117 nil)))
2119 ;; for rc:
2120 (defun sh-find-prev-switch ()
2121 "Find the line for the switch keyword matching this line's case keyword."
2122 (re-search-backward "\\<switch\\>" nil t))
2124 (defun sh-handle-this-rc-case ()
2125 (if (sh-find-prev-switch)
2126 (list '(+ sh-indent-after-switch))
2127 ;; (list '(+ sh-indent-for-case-label))
2128 nil))
2130 (defun sh-handle-prev-rc-case ()
2131 (list '(+ sh-indent-after-case)))
2133 (defun sh-check-rule (n thing)
2134 (let ((rule (nth n (assoc thing sh-kw-alist)))
2135 (val nil))
2136 (if rule
2137 (progn
2138 (setq val (funcall rule))
2139 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2140 n thing (point) rule val)))
2141 val))
2144 (defun sh-get-indent-info ()
2145 "Return indent-info for this line.
2146 This is a list. nil means the line is to be left as is.
2147 Otherwise it contains one or more of the following sublists:
2148 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2149 relative to. If present, this is always the first of the
2150 sublists. The indentation of the line in question is
2151 derived from the indentation of this point, possibly
2152 modified by subsequent sublists.
2153 \(+ VAR\)
2154 \(- VAR\) Get the value of variable VAR and add to or subtract from
2155 the indentation calculated so far.
2156 \(= VAR\) Get the value of variable VAR and *replace* the
2157 indentation with its value. This only occurs for
2158 special variables such as `sh-indent-comment'.
2159 STRING This is ignored for the purposes of calculating
2160 indentation, it is printed in certain cases to help show
2161 what the indentation is based on."
2162 ;; See comments before `sh-kw'.
2163 (save-excursion
2164 (let ((have-result nil)
2165 this-kw
2166 start
2168 (result nil)
2169 (align-point nil)
2170 prev-line-end x)
2171 (beginning-of-line)
2172 ;; Note: setting result to t means we are done and will return nil.
2173 ;;(This function never returns just t.)
2174 (cond
2175 ((or (and (boundp 'font-lock-string-face) (not (bobp))
2176 (eq (get-text-property (1- (point)) 'face)
2177 font-lock-string-face))
2178 (eq (get-text-property (point) 'face) sh-heredoc-face))
2179 (setq result t)
2180 (setq have-result t))
2181 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2182 (if (bobp)
2183 (setq result t) ;; return nil if 1st line!
2184 (setq result (list '(= sh-indent-comment)))
2185 ;; we still need to get previous line in case
2186 ;; sh-indent-comment is t (indent as normal)
2187 (setq align-point (sh-prev-line nil))
2188 (setq have-result nil)
2190 ) ;; cond
2192 (unless have-result
2193 ;; Continuation lines are handled specially
2194 (if (sh-this-is-a-continuation)
2195 (progn
2196 (setq result
2197 (if (save-excursion
2198 (beginning-of-line)
2199 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2200 ;; By convention, if the continuation \ is not
2201 ;; preceded by a SPC or a TAB it means that the line
2202 ;; is cut at a place where spaces cannot be freely
2203 ;; added/removed. I.e. do not indent the line.
2204 (list '(= nil))
2205 ;; We assume the line being continued is already
2206 ;; properly indented...
2207 ;; (setq prev-line-end (sh-prev-line))
2208 (setq align-point (sh-prev-line nil))
2209 (list '(+ sh-indent-for-continuation))))
2210 (setq have-result t))
2211 (beginning-of-line)
2212 (skip-chars-forward " \t")
2213 (setq this-kw (sh-get-kw)))
2215 ;; Handle "this" keyword: first word on the line we're
2216 ;; calculating indentation info for.
2217 (if this-kw
2218 (if (setq val (sh-check-rule 1 this-kw))
2219 (progn
2220 (setq align-point (point))
2221 (sh-debug
2222 "this - setting align-point to %d" align-point)
2223 (setq result (append result val))
2224 (setq have-result t)
2225 ;; set prev-line to continue processing remainder
2226 ;; of this line as a previous line
2227 (setq prev-line-end (point))
2228 ))))
2230 (unless have-result
2231 (setq prev-line-end (sh-prev-line 'end)))
2233 (if prev-line-end
2234 (save-excursion
2235 ;; We start off at beginning of this line.
2236 ;; Scan previous statements while this is <=
2237 ;; start of previous line.
2238 (setq start (point)) ;; for debug only
2239 (goto-char prev-line-end)
2240 (setq x t)
2241 (while (and x (setq x (sh-prev-thing)))
2242 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2243 (cond
2244 ((and (equal x ")")
2245 (equal (get-text-property (1- (point)) 'syntax-table)
2246 sh-st-punc))
2247 (sh-debug "Case label) here")
2248 (setq x 'case-label)
2249 (if (setq val (sh-check-rule 2 x))
2250 (progn
2251 (setq result (append result val))
2252 (setq align-point (point))))
2253 (or (bobp)
2254 (forward-char -1))
2255 ;; FIXME: This charset looks too much like a regexp. --Stef
2256 (skip-chars-forward "[a-z0-9]*?")
2258 ((string-match "[])}]" x)
2259 (setq x (sh-safe-forward-sexp -1))
2260 (if x
2261 (progn
2262 (setq align-point (point))
2263 (setq result (append result
2264 (list "aligned to opening paren")))
2266 ((string-match "[[({]" x)
2267 (sh-debug "Checking special thing: %s" x)
2268 (if (setq val (sh-check-rule 2 x))
2269 (setq result (append result val)))
2270 (forward-char -1)
2271 (setq align-point (point)))
2272 ((string-match "[\"'`]" x)
2273 (sh-debug "Skipping back for %s" x)
2274 ;; this was oops-2
2275 (setq x (sh-safe-forward-sexp -1)))
2276 ((stringp x)
2277 (sh-debug "Checking string %s at %s" x (point))
2278 (if (setq val (sh-check-rule 2 x))
2279 ;; (or (eq t (car val))
2280 ;; (eq t (car (car val))))
2281 (setq result (append result val)))
2282 ;; not sure about this test Wed Jan 27 23:48:35 1999
2283 (setq align-point (point))
2284 (unless (bolp)
2285 (forward-char -1)))
2287 (error "Don't know what to do with %s" x))
2289 ) ;; while
2290 (sh-debug "result is %s" result)
2292 (sh-debug "No prev line!")
2293 (sh-debug "result: %s align-point: %s" result align-point)
2296 (if align-point
2297 ;; was: (setq result (append result (list (list t align-point))))
2298 (setq result (append (list (list t align-point)) result))
2300 (sh-debug "result is now: %s" result)
2302 (or result
2303 (setq result (list (if prev-line-end
2304 (list t prev-line-end)
2305 (list '= 'sh-first-lines-indent)))))
2307 (if (eq result t)
2308 (setq result nil))
2309 (sh-debug "result is: %s" result)
2310 result
2311 ) ;; let
2315 (defun sh-get-indent-var-for-line (&optional info)
2316 "Return the variable controlling indentation for this line.
2317 If there is not [just] one such variable, return a string
2318 indicating the problem.
2319 If INFO is supplied it is used, else it is calculated."
2320 (let ((var nil)
2321 (result nil)
2322 (reason nil)
2323 sym elt)
2324 (or info
2325 (setq info (sh-get-indent-info)))
2326 (if (null info)
2327 (setq result "this line to be left as is")
2328 (while (and info (null result))
2329 (setq elt (car info))
2330 (cond
2331 ((stringp elt)
2332 (setq reason elt)
2334 ((not (listp elt))
2335 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2336 ;; so it is a list
2337 ((eq t (car elt))
2338 ) ;; nothing
2339 ((symbolp (setq sym (nth 1 elt)))
2340 ;; A bit of a kludge - when we see the sh-indent-comment
2341 ;; ignore other variables. Otherwise it is tricky to
2342 ;; "learn" the comment indentation.
2343 (if (eq var 'sh-indent-comment)
2344 (setq result var)
2345 (if var
2346 (setq result
2347 "this line is controlled by more than 1 variable.")
2348 (setq var sym))))
2350 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2351 (setq info (cdr info))
2353 (or result
2354 (setq result var))
2355 (or result
2356 (setq result reason))
2357 (if (null result)
2358 ;; e.g. just had (t POS)
2359 (setq result "line has default indentation"))
2360 result))
2364 ;; Finding the previous line isn't trivial.
2365 ;; We must *always* go back one more and see if that is a continuation
2366 ;; line -- it is the PREVIOUS line which is continued, not the one
2367 ;; we are going to!
2368 ;; Also, we want to treat a whole "here document" as one big line,
2369 ;; because we may want to a align to the beginning of it.
2371 ;; What we do:
2372 ;; - go back to previous non-empty line
2373 ;; - if this is in a here-document, go to the beginning of it
2374 ;; - while previous line is continued, go back one line
2375 (defun sh-prev-line (&optional end)
2376 "Back to end of previous non-comment non-empty line.
2377 Go to beginning of logical line unless END is non-nil, in which case
2378 we go to the end of the previous line and do not check for continuations."
2379 (save-excursion
2380 (beginning-of-line)
2381 (forward-comment (- (point-max)))
2382 (unless end (beginning-of-line))
2383 (when (and (not (bobp))
2384 (equal (get-text-property (1- (point)) 'face)
2385 sh-heredoc-face))
2386 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
2387 (when p1
2388 (goto-char p1)
2389 (if end
2390 (end-of-line)
2391 (beginning-of-line)))))
2392 (unless end
2393 ;; we must check previous lines to see if they are continuation lines
2394 ;; if so, we must return position of first of them
2395 (while (and (sh-this-is-a-continuation)
2396 (>= 0 (forward-line -1))))
2397 (beginning-of-line)
2398 (skip-chars-forward " \t"))
2399 (point)))
2402 (defun sh-prev-stmt ()
2403 "Return the address of the previous stmt or nil."
2404 ;; This is used when we are trying to find a matching keyword.
2405 ;; Searching backward for the keyword would certainly be quicker, but
2406 ;; it is hard to remove "false matches" -- such as if the keyword
2407 ;; appears in a string or quote. This way is slower, but (I think) safer.
2408 (interactive)
2409 (save-excursion
2410 (let ((going t)
2411 (start (point))
2412 (found nil)
2413 (prev nil))
2414 (skip-chars-backward " \t;|&({[")
2415 (while (and (not found)
2416 (not (bobp))
2417 going)
2418 ;; Do a backward-sexp if possible, else backup bit by bit...
2419 (if (sh-safe-forward-sexp -1)
2420 (progn
2421 (if (looking-at sh-special-keywords)
2422 (progn
2423 (setq found prev))
2424 (setq prev (point))
2426 ;; backward-sexp failed
2427 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2428 (forward-char -1))
2429 (if (bolp)
2430 (let ((back (sh-prev-line nil)))
2431 (if back
2432 (goto-char back)
2433 (setq going nil)))))
2434 (unless found
2435 (skip-chars-backward " \t")
2436 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2437 (eq (char-before) ?\;)
2438 (looking-at "\\s-*[|&]"))
2439 (setq found (point)))))
2440 (if found
2441 (goto-char found))
2442 (if found
2443 (progn
2444 (skip-chars-forward " \t|&({[")
2445 (setq found (point))))
2446 (if (>= (point) start)
2447 (progn
2448 (debug "We didn't move!")
2449 (setq found nil))
2450 (or found
2451 (sh-debug "Did not find prev stmt.")))
2452 found)))
2455 (defun sh-get-word ()
2456 "Get a shell word skipping whitespace from point."
2457 (interactive)
2458 (skip-chars-forward "\t ")
2459 (let ((start (point)))
2460 (while
2461 (if (looking-at "[\"'`]")
2462 (sh-safe-forward-sexp)
2463 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2464 (> (skip-chars-forward "-_$[:alnum:]") 0)
2466 (buffer-substring start (point))
2469 (defun sh-prev-thing ()
2470 "Return the previous thing this logical line."
2471 ;; This is called when `sh-get-indent-info' is working backwards on
2472 ;; the previous line(s) finding what keywords may be relevant for
2473 ;; indenting. It moves over sexps if possible, and will stop
2474 ;; on a ; and at the beginning of a line if it is not a continuation
2475 ;; line.
2477 ;; Added a kludge for ";;"
2478 ;; Possible return values:
2479 ;; nil - nothing
2480 ;; a string - possibly a keyword
2482 (if (bolp)
2484 (let ((start (point))
2485 (min-point (if (sh-this-is-a-continuation)
2486 (sh-prev-line nil)
2487 (line-beginning-position))))
2488 (skip-chars-backward " \t;" min-point)
2489 (if (looking-at "\\s-*;;")
2490 ;; (message "Found ;; !")
2491 ";;"
2492 (skip-chars-backward "^)}];\"'`({[" min-point)
2493 (let ((c (if (> (point) min-point) (char-before))))
2494 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2495 (point) c start min-point)
2496 (if (not (memq c '(?\n nil ?\;)))
2497 ;; c -- return a string
2498 (char-to-string c)
2499 ;; Return the leading keyword of the "command" we supposedly
2500 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
2501 ;; `then' that precedes the actual command), so check whether
2502 ;; we're looking at such a keyword and if so, move back forward.
2503 (let ((boundary (point))
2504 kwd next)
2505 (while
2506 (progn
2507 ;; Skip forward over white space newline and \ at eol.
2508 (skip-chars-forward " \t\n\\\\" start)
2509 (if (>= (point) start)
2510 (progn
2511 (sh-debug "point: %d >= start: %d" (point) start)
2512 nil)
2513 (if next (setq boundary next))
2514 (sh-debug "Now at %d start=%d" (point) start)
2515 (setq kwd (sh-get-word))
2516 (if (member kwd (sh-feature sh-leading-keywords))
2517 (progn
2518 (setq next (point))
2520 nil))))
2521 (goto-char boundary)
2522 kwd)))))))
2525 (defun sh-this-is-a-continuation ()
2526 "Return non-nil if current line is a continuation of previous line."
2527 (save-excursion
2528 (and (zerop (forward-line -1))
2529 (looking-at ".*\\\\$")
2530 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2531 nil nil nil t))))))
2533 (defun sh-get-kw (&optional where and-move)
2534 "Return first word of line from WHERE.
2535 If AND-MOVE is non-nil then move to end of word."
2536 (let ((start (point)))
2537 (if where
2538 (goto-char where))
2539 (prog1
2540 (buffer-substring (point)
2541 (progn (skip-chars-forward "^ \t\n;&|()")(point)))
2542 (unless and-move
2543 (goto-char start)))))
2545 (defun sh-find-prev-matching (open close &optional depth)
2546 "Find a matching token for a set of opening and closing keywords.
2547 This takes into account that there may be nested open..close pairings.
2548 OPEN and CLOSE are regexps denoting the tokens to be matched.
2549 Optional parameter DEPTH (usually 1) says how many to look for."
2550 (let ((parse-sexp-ignore-comments t)
2551 prev)
2552 (setq depth (or depth 1))
2553 (save-excursion
2554 (condition-case nil
2555 (while (and
2556 (/= 0 depth)
2557 (not (bobp))
2558 (setq prev (sh-prev-stmt)))
2559 (goto-char prev)
2560 (save-excursion
2561 (if (looking-at "\\\\\n")
2562 (progn
2563 (forward-char 2)
2564 (skip-chars-forward " \t")))
2565 (cond
2566 ((looking-at open)
2567 (setq depth (1- depth))
2568 (sh-debug "found open at %d - depth = %d" (point) depth))
2569 ((looking-at close)
2570 (setq depth (1+ depth))
2571 (sh-debug "found close - depth = %d" depth))
2573 ))))
2574 (error nil))
2575 (if (eq depth 0)
2576 prev ;; (point)
2577 nil)
2581 (defun sh-var-value (var &optional ignore-error)
2582 "Return the value of variable VAR, interpreting symbols.
2583 It can also return t or nil.
2584 If an invalid value is found, throw an error unless Optional argument
2585 IGNORE-ERROR is non-nil."
2586 (let ((val (symbol-value var)))
2587 (cond
2588 ((numberp val)
2589 val)
2590 ((eq val t)
2591 val)
2592 ((null val)
2593 val)
2594 ((eq val '+)
2595 sh-basic-offset)
2596 ((eq val '-)
2597 (- sh-basic-offset))
2598 ((eq val '++)
2599 (* 2 sh-basic-offset))
2600 ((eq val '--)
2601 (* 2 (- sh-basic-offset)))
2602 ((eq val '*)
2603 (/ sh-basic-offset 2))
2604 ((eq val '/)
2605 (/ (- sh-basic-offset) 2))
2607 (if ignore-error
2608 (progn
2609 (message "Don't know how to handle %s's value of %s" var val)
2611 (error "Don't know how to handle %s's value of %s" var val))
2612 ))))
2614 (defun sh-set-var-value (var value &optional no-symbol)
2615 "Set variable VAR to VALUE.
2616 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2617 can be represented by a symbol then do so."
2618 (cond
2619 (no-symbol
2620 (set var value))
2621 ((= value sh-basic-offset)
2622 (set var '+))
2623 ((= value (- sh-basic-offset))
2624 (set var '-))
2625 ((eq value (* 2 sh-basic-offset))
2626 (set var '++))
2627 ((eq value (* 2 (- sh-basic-offset)))
2628 (set var '--))
2629 ((eq value (/ sh-basic-offset 2))
2630 (set var '*))
2631 ((eq value (/ (- sh-basic-offset) 2))
2632 (set var '/))
2634 (set var value)))
2638 (defun sh-calculate-indent (&optional info)
2639 "Return the indentation for the current line.
2640 If INFO is supplied it is used, else it is calculated from current line."
2641 (let ((ofs 0)
2642 (base-value 0)
2643 elt a b var val)
2644 (or info
2645 (setq info (sh-get-indent-info)))
2646 (when info
2647 (while info
2648 (sh-debug "info: %s ofs=%s" info ofs)
2649 (setq elt (car info))
2650 (cond
2651 ((stringp elt)) ;; do nothing?
2652 ((listp elt)
2653 (setq a (car (car info)))
2654 (setq b (nth 1 (car info)))
2655 (cond
2656 ((eq a t)
2657 (save-excursion
2658 (goto-char b)
2659 (setq val (current-indentation)))
2660 (setq base-value val))
2661 ((symbolp b)
2662 (setq val (sh-var-value b))
2663 (cond
2664 ((eq a '=)
2665 (cond
2666 ((null val)
2667 ;; no indentation
2668 ;; set info to nil so we stop immediately
2669 (setq base-value nil ofs nil info nil))
2670 ((eq val t) (setq ofs 0)) ;; indent as normal line
2672 ;; The following assume the (t POS) come first!
2673 (setq ofs val base-value 0)
2674 (setq info nil)))) ;; ? stop now
2675 ((eq a '+) (setq ofs (+ ofs val)))
2676 ((eq a '-) (setq ofs (- ofs val)))
2678 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
2680 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
2682 (error "sh-calculate-indent invalid elt %s" elt)))
2683 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2684 a b val base-value ofs)
2685 (setq info (cdr info)))
2686 ;; return value:
2687 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
2689 (cond
2690 ((or (null base-value)(null ofs))
2691 nil)
2692 ((and (numberp base-value)(numberp ofs))
2693 (sh-debug "base (%d) + ofs (%d) = %d"
2694 base-value ofs (+ base-value ofs))
2695 (+ base-value ofs)) ;; return value
2697 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2698 base-value ofs)
2699 nil)))))
2702 (defun sh-indent-line ()
2703 "Indent the current line."
2704 (interactive)
2705 (let ((indent (sh-calculate-indent))
2706 (pos (- (point-max) (point))))
2707 (when indent
2708 (beginning-of-line)
2709 (skip-chars-forward " \t")
2710 (indent-line-to indent)
2711 ;; If initial point was within line's indentation,
2712 ;; position after the indentation. Else stay at same point in text.
2713 (if (> (- (point-max) pos) (point))
2714 (goto-char (- (point-max) pos))))))
2717 (defun sh-blink (blinkpos &optional msg)
2718 "Move cursor momentarily to BLINKPOS and display MSG."
2719 ;; We can get here without it being a number on first line
2720 (if (numberp blinkpos)
2721 (save-excursion
2722 (goto-char blinkpos)
2723 (if msg (message "%s" msg) (message nil))
2724 (sit-for blink-matching-delay))
2725 (if msg (message "%s" msg) (message nil))))
2727 (defun sh-show-indent (arg)
2728 "Show the how the currently line would be indented.
2729 This tells you which variable, if any, controls the indentation of
2730 this line.
2731 If optional arg ARG is non-null (called interactively with a prefix),
2732 a pop up window describes this variable.
2733 If variable `sh-blink' is non-nil then momentarily go to the line
2734 we are indenting relative to, if applicable."
2735 (interactive "P")
2736 (sh-must-support-indent)
2737 (let* ((info (sh-get-indent-info))
2738 (var (sh-get-indent-var-for-line info))
2739 (curr-indent (current-indentation))
2740 val msg)
2741 (if (stringp var)
2742 (message "%s" (setq msg var))
2743 (setq val (sh-calculate-indent info))
2745 (if (eq curr-indent val)
2746 (setq msg (format "%s is %s" var (symbol-value var)))
2747 (setq msg
2748 (if val
2749 (format "%s (%s) would change indent from %d to: %d"
2750 var (symbol-value var) curr-indent val)
2751 (format "%s (%s) would leave line as is"
2752 var (symbol-value var)))
2754 (if (and arg var)
2755 (describe-variable var)))
2756 (if sh-blink
2757 (let ((info (sh-get-indent-info)))
2758 (if (and info (listp (car info))
2759 (eq (car (car info)) t))
2760 (sh-blink (nth 1 (car info)) msg)
2761 (message "%s" msg)))
2762 (message "%s" msg))
2765 (defun sh-set-indent ()
2766 "Set the indentation for the current line.
2767 If the current line is controlled by an indentation variable, prompt
2768 for a new value for it."
2769 (interactive)
2770 (sh-must-support-indent)
2771 (let* ((info (sh-get-indent-info))
2772 (var (sh-get-indent-var-for-line info))
2773 val old-val indent-val)
2774 (if (stringp var)
2775 (message "Cannot set indent - %s" var)
2776 (setq old-val (symbol-value var))
2777 (setq val (sh-read-variable var))
2778 (condition-case nil
2779 (progn
2780 (set var val)
2781 (setq indent-val (sh-calculate-indent info))
2782 (if indent-val
2783 (message "Variable: %s Value: %s would indent to: %d"
2784 var (symbol-value var) indent-val)
2785 (message "Variable: %s Value: %s would leave line as is."
2786 var (symbol-value var)))
2787 ;; I'm not sure about this, indenting it now?
2788 ;; No. Because it would give the impression that an undo would
2789 ;; restore thing, but the value has been altered.
2790 ;; (sh-indent-line)
2792 (error
2793 (set var old-val)
2794 (message "Bad value for %s, restoring to previous value %s"
2795 var old-val)
2796 (sit-for 1)
2797 nil))
2801 (defun sh-learn-line-indent (arg)
2802 "Learn how to indent a line as it currently is indented.
2804 If there is an indentation variable which controls this line's indentation,
2805 then set it to a value which would indent the line the way it
2806 presently is.
2808 If the value can be represented by one of the symbols then do so
2809 unless optional argument ARG (the prefix when interactive) is non-nil."
2810 (interactive "*P")
2811 (sh-must-support-indent)
2812 ;; I'm not sure if we show allow learning on an empty line.
2813 ;; Though it might occasionally be useful I think it usually
2814 ;; would just be confusing.
2815 (if (save-excursion
2816 (beginning-of-line)
2817 (looking-at "\\s-*$"))
2818 (message "sh-learn-line-indent ignores empty lines.")
2819 (let* ((info (sh-get-indent-info))
2820 (var (sh-get-indent-var-for-line info))
2821 ival sval diff new-val
2822 (no-symbol arg)
2823 (curr-indent (current-indentation)))
2824 (cond
2825 ((stringp var)
2826 (message "Cannot learn line - %s" var))
2827 ((eq var 'sh-indent-comment)
2828 ;; This is arbitrary...
2829 ;; - if curr-indent is 0, set to curr-indent
2830 ;; - else if it has the indentation of a "normal" line,
2831 ;; then set to t
2832 ;; - else set to curr-indent.
2833 (setq sh-indent-comment
2834 (if (= curr-indent 0)
2836 (let* ((sh-indent-comment t)
2837 (val2 (sh-calculate-indent info)))
2838 (if (= val2 curr-indent)
2840 curr-indent))))
2841 (message "%s set to %s" var (symbol-value var))
2843 ((numberp (setq sval (sh-var-value var)))
2844 (setq ival (sh-calculate-indent info))
2845 (setq diff (- curr-indent ival))
2847 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2848 curr-indent ival diff var sval)
2849 (setq new-val (+ sval diff))
2850 ;;; I commented out this because someone might want to replace
2851 ;;; a value of `+' with the current value of sh-basic-offset
2852 ;;; or vice-versa.
2853 ;;; (if (= 0 diff)
2854 ;;; (message "No change needed!")
2855 (sh-set-var-value var new-val no-symbol)
2856 (message "%s set to %s" var (symbol-value var))
2859 (debug)
2860 (message "Cannot change %s" var))))))
2864 (defun sh-mark-init (buffer)
2865 "Initialize a BUFFER to be used by `sh-mark-line'."
2866 (with-current-buffer (get-buffer-create buffer)
2867 (erase-buffer)
2868 (occur-mode)))
2871 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
2872 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2873 Buffer BUFFER is in `occur-mode'.
2874 If ADD-LINENUM is non-nil the message is preceded by the line number.
2875 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2876 so that `occur-next' and `occur-prev' will work."
2877 (let ((m1 (make-marker))
2878 start
2879 (line ""))
2880 (when point
2881 (set-marker m1 point (current-buffer))
2882 (if add-linenum
2883 (setq line (format "%d: " (1+ (count-lines 1 point))))))
2884 (save-excursion
2885 (if (get-buffer buffer)
2886 (set-buffer (get-buffer buffer))
2887 (set-buffer (get-buffer-create buffer))
2888 (occur-mode)
2890 (goto-char (point-max))
2891 (setq start (point))
2892 (insert line)
2893 (if occur-point
2894 (setq occur-point (point)))
2895 (insert message)
2896 (if point
2897 (add-text-properties
2898 start (point)
2899 '(mouse-face highlight
2900 help-echo "mouse-2: go to the line where I learned this")))
2901 (insert "\n")
2902 (if point
2903 (progn
2904 (put-text-property start (point) 'occur-target m1)
2905 (if occur-point
2906 (put-text-property start occur-point
2907 'occur-match t))
2913 ;; Is this really worth having?
2914 (defvar sh-learned-buffer-hook nil
2915 "*An abnormal hook, called with an alist of learned variables.")
2916 ;; Example of how to use sh-learned-buffer-hook
2918 ;; (defun what-i-learned (list)
2919 ;; (let ((p list))
2920 ;; (save-excursion
2921 ;; (set-buffer "*scratch*")
2922 ;; (goto-char (point-max))
2923 ;; (insert "(setq\n")
2924 ;; (while p
2925 ;; (insert (format " %s %s \n"
2926 ;; (nth 0 (car p)) (nth 1 (car p))))
2927 ;; (setq p (cdr p)))
2928 ;; (insert ")\n")
2929 ;; )))
2931 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2934 ;; Originally this was sh-learn-region-indent (beg end)
2935 ;; However, in practice this was awkward so I changed it to
2936 ;; use the whole buffer. Use narrowing if needbe.
2937 (defun sh-learn-buffer-indent (&optional arg)
2938 "Learn how to indent the buffer the way it currently is.
2940 Output in buffer \"*indent*\" shows any lines which have conflicting
2941 values of a variable, and the final value of all variables learned.
2942 This buffer is popped to automatically if there are any discrepancies.
2944 If no prefix ARG is given, then variables are set to numbers.
2945 If a prefix arg is given, then variables are set to symbols when
2946 applicable -- e.g. to symbol `+' if the value is that of the
2947 basic indent.
2948 If a positive numerical prefix is given, then `sh-basic-offset'
2949 is set to the prefix's numerical value.
2950 Otherwise, sh-basic-offset may or may not be changed, according
2951 to the value of variable `sh-learn-basic-offset'.
2953 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2954 function completes. The function is abnormal because it is called
2955 with an alist of variables learned. This feature may be changed or
2956 removed in the future.
2958 This command can often take a long time to run."
2959 (interactive "P")
2960 (sh-must-support-indent)
2961 (save-excursion
2962 (goto-char (point-min))
2963 (let ((learned-var-list nil)
2964 (out-buffer "*indent*")
2965 (num-diffs 0)
2966 previous-set-info
2967 (max 17)
2970 (comment-col nil) ;; number if all same, t if seen diff values
2971 (comments-always-default t) ;; nil if we see one not default
2972 initial-msg
2973 (specified-basic-offset (and arg (numberp arg)
2974 (> arg 0)))
2975 (linenum 0)
2976 suggested)
2977 (setq vec (make-vector max 0))
2978 (sh-mark-init out-buffer)
2980 (if specified-basic-offset
2981 (progn
2982 (setq sh-basic-offset arg)
2983 (setq initial-msg
2984 (format "Using specified sh-basic-offset of %d"
2985 sh-basic-offset)))
2986 (setq initial-msg
2987 (format "Initial value of sh-basic-offset: %s"
2988 sh-basic-offset)))
2990 (while (< (point) (point-max))
2991 (setq linenum (1+ linenum))
2992 ;; (if (zerop (% linenum 10))
2993 (message "line %d" linenum)
2994 ;; )
2995 (unless (looking-at "\\s-*$") ;; ignore empty lines!
2996 (let* ((sh-indent-comment t) ;; info must return default indent
2997 (info (sh-get-indent-info))
2998 (var (sh-get-indent-var-for-line info))
2999 sval ival diff new-val
3000 (curr-indent (current-indentation)))
3001 (cond
3002 ((null var)
3003 nil)
3004 ((stringp var)
3005 nil)
3006 ((numberp (setq sval (sh-var-value var 'no-error)))
3007 ;; the numberp excludes comments since sval will be t.
3008 (setq ival (sh-calculate-indent))
3009 (setq diff (- curr-indent ival))
3010 (setq new-val (+ sval diff))
3011 (sh-set-var-value var new-val 'no-symbol)
3012 (unless (looking-at "\\s-*#") ;; don't learn from comments
3013 (if (setq previous-set-info (assoc var learned-var-list))
3014 (progn
3015 ;; it was already there, is it same value ?
3016 (unless (eq (symbol-value var)
3017 (nth 1 previous-set-info))
3018 (sh-mark-line
3019 (format "Variable %s was set to %s"
3020 var (symbol-value var))
3021 (point) out-buffer t t)
3022 (sh-mark-line
3023 (format " but was previously set to %s"
3024 (nth 1 previous-set-info))
3025 (nth 2 previous-set-info) out-buffer t)
3026 (setq num-diffs (1+ num-diffs))
3027 ;; (delete previous-set-info learned-var-list)
3028 (setcdr previous-set-info
3029 (list (symbol-value var) (point)))
3032 (setq learned-var-list
3033 (append (list (list var (symbol-value var)
3034 (point)))
3035 learned-var-list)))
3036 (if (numberp new-val)
3037 (progn
3038 (sh-debug
3039 "This line's indent value: %d" new-val)
3040 (if (< new-val 0)
3041 (setq new-val (- new-val)))
3042 (if (< new-val max)
3043 (aset vec new-val (1+ (aref vec new-val))))))
3045 ((eq var 'sh-indent-comment)
3046 (unless (= curr-indent (sh-calculate-indent info))
3047 ;; this is not the default indentation
3048 (setq comments-always-default nil)
3049 (if comment-col ;; then we have see one before
3050 (or (eq comment-col curr-indent)
3051 (setq comment-col t)) ;; seen a different one
3052 (setq comment-col curr-indent))
3055 (sh-debug "Cannot learn this line!!!")
3057 (sh-debug
3058 "at %s learned-var-list is %s" (point) learned-var-list)
3060 (forward-line 1)
3061 ) ;; while
3062 (if sh-debug
3063 (progn
3064 (setq msg (format
3065 "comment-col = %s comments-always-default = %s"
3066 comment-col comments-always-default))
3067 ;; (message msg)
3068 (sh-mark-line msg nil out-buffer)))
3069 (cond
3070 ((eq comment-col 0)
3071 (setq msg "\nComments are all in 1st column.\n"))
3072 (comments-always-default
3073 (setq msg "\nComments follow default indentation.\n")
3074 (setq comment-col t))
3075 ((numberp comment-col)
3076 (setq msg (format "\nComments are in col %d." comment-col)))
3078 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3079 (setq comment-col nil)
3081 (sh-debug msg)
3082 (sh-mark-line msg nil out-buffer)
3084 (sh-mark-line initial-msg nil out-buffer t t)
3086 (setq suggested (sh-guess-basic-offset vec))
3088 (if (and suggested (not specified-basic-offset))
3089 (let ((new-value
3090 (cond
3091 ;; t => set it if we have a single value as a number
3092 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3093 suggested)
3094 ;; other non-nil => set it if only one value was found
3095 (sh-learn-basic-offset
3096 (if (numberp suggested)
3097 suggested
3098 (if (= (length suggested) 1)
3099 (car suggested))))
3101 nil))))
3102 (if new-value
3103 (progn
3104 (setq learned-var-list
3105 (append (list (list 'sh-basic-offset
3106 (setq sh-basic-offset new-value)
3107 (point-max)))
3108 learned-var-list))
3109 ;; Not sure if we need to put this line in, since
3110 ;; it will appear in the "Learned variable settings".
3111 (sh-mark-line
3112 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3113 nil out-buffer))
3114 (sh-mark-line
3115 (if (listp suggested)
3116 (format "Possible value(s) for sh-basic-offset: %s"
3117 (mapconcat 'int-to-string suggested " "))
3118 (format "Suggested sh-basic-offset: %d" suggested))
3119 nil out-buffer))))
3122 (setq learned-var-list
3123 (append (list (list 'sh-indent-comment comment-col (point-max)))
3124 learned-var-list))
3125 (setq sh-indent-comment comment-col)
3126 (let ((name (buffer-name)))
3127 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3128 (if arg
3129 ;; Set learned variables to symbolic rather than numeric
3130 ;; values where possible.
3131 (dolist (learned-var (reverse learned-var-list))
3132 (let ((var (car learned-var))
3133 (val (nth 1 learned-var)))
3134 (when (and (not (eq var 'sh-basic-offset))
3135 (numberp val))
3136 (sh-set-var-value var val)))))
3137 (dolist (learned-var (reverse learned-var-list))
3138 (let ((var (car learned-var)))
3139 (sh-mark-line (format " %s %s" var (symbol-value var))
3140 (nth 2 learned-var) out-buffer)))
3141 (with-current-buffer out-buffer
3142 (goto-char (point-min))
3143 (insert
3144 (format "Indentation values for buffer %s.\n" name)
3145 (format "%d indentation variable%s different values%s\n\n"
3146 num-diffs
3147 (if (= num-diffs 1)
3148 " has" "s have")
3149 (if (zerop num-diffs)
3150 "." ":"))
3152 ;; Are abnormal hooks considered bad form?
3153 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3154 (if (or sh-popup-occur-buffer (> num-diffs 0))
3155 (pop-to-buffer out-buffer))
3158 (defun sh-guess-basic-offset (vec)
3159 "See if we can determine a reasonable value for `sh-basic-offset'.
3160 This is experimental, heuristic and arbitrary!
3161 Argument VEC is a vector of information collected by
3162 `sh-learn-buffer-indent'.
3163 Return values:
3164 number - there appears to be a good single value
3165 list of numbers - no obvious one, here is a list of one or more
3166 reasonable choices
3167 nil - we couldn't find a reasonable one."
3168 (let* ((max (1- (length vec)))
3169 (i 1)
3170 (totals (make-vector max 0)))
3171 (while (< i max)
3172 (aset totals i (+ (aref totals i) (* 4 (aref vec i))))
3173 (if (zerop (% i 2))
3174 (aset totals i (+ (aref totals i) (aref vec (/ i 2)))))
3175 (if (< (* i 2) max)
3176 (aset totals i (+ (aref totals i) (aref vec (* i 2)))))
3177 (setq i (1+ i)))
3179 (let ((x nil)
3180 (result nil)
3181 tot sum p)
3182 (setq i 1)
3183 (while (< i max)
3184 (if (/= (aref totals i) 0)
3185 (setq x (append x (list (cons i (aref totals i))))))
3186 (setq i (1+ i)))
3188 (setq x (sort x (lambda (a b) (> (cdr a) (cdr b)))))
3189 (setq tot (apply '+ (append totals nil)))
3190 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3191 vec totals tot))
3192 (cond
3193 ((zerop (length x))
3194 (message "no values!")) ;; we return nil
3195 ((= (length x) 1)
3196 (message "only value is %d" (car (car x)))
3197 (setq result (car (car x)))) ;; return single value
3198 ((> (cdr (car x)) (/ tot 2))
3199 ;; 1st is > 50%
3200 (message "basic-offset is probably %d" (car (car x)))
3201 (setq result (car (car x)))) ;; again, return a single value
3202 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3203 ;; 1st is >= 2 * 2nd
3204 (message "basic-offset could be %d" (car (car x)))
3205 (setq result (car (car x))))
3206 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3207 ;; 1st & 2nd together >= 50% - return a list
3208 (setq p x sum 0 result nil)
3209 (while (and p
3210 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3211 (setq result (append result (list (car (car p)))))
3212 (setq p (cdr p)))
3213 (message "Possible choices for sh-basic-offset: %s"
3214 (mapconcat 'int-to-string result " ")))
3216 (message "No obvious value for sh-basic-offset. Perhaps %d"
3217 (car (car x)))
3218 ;; result is nil here
3220 result)))
3222 ;; ========================================================================
3224 ;; Styles -- a quick and dirty way of saving the indentation settings.
3226 (defvar sh-styles-alist nil
3227 "A list of all known shell indentation styles.")
3229 (defun sh-name-style (name &optional confirm-overwrite)
3230 "Name the current indentation settings as a style called NAME.
3231 If this name exists, the command will prompt whether it should be
3232 overwritten if
3233 - - it was called interactively with a prefix argument, or
3234 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3235 ;; (interactive "sName for this style: ")
3236 (interactive
3237 (list
3238 (read-from-minibuffer "Name for this style? " )
3239 (not current-prefix-arg)))
3240 (let ((slist (cons name
3241 (mapcar (lambda (var) (cons var (symbol-value var)))
3242 sh-var-list)))
3243 (style (assoc name sh-styles-alist)))
3244 (if style
3245 (if (and confirm-overwrite
3246 (not (y-or-n-p "This style exists. Overwrite it? ")))
3247 (message "Not changing style %s" name)
3248 (message "Updating style %s" name)
3249 (setcdr style (cdr slist)))
3250 (message "Creating new style %s" name)
3251 (push slist sh-styles-alist))))
3253 (defun sh-load-style (name)
3254 "Set shell indentation values for this buffer from those in style NAME."
3255 (interactive (list (completing-read
3256 "Which style to use for this buffer? "
3257 sh-styles-alist nil t)))
3258 (let ((sl (assoc name sh-styles-alist)))
3259 (if (null sl)
3260 (error "sh-load-style - style %s not known" name)
3261 (dolist (var (cdr sl))
3262 (set (car var) (cdr var))))))
3264 (defun sh-save-styles-to-buffer (buff)
3265 "Save all current styles in elisp to buffer BUFF.
3266 This is always added to the end of the buffer."
3267 (interactive (list
3268 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3269 (with-current-buffer (get-buffer-create buff)
3270 (goto-char (point-max))
3271 (insert "\n")
3272 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3276 ;; statement syntax-commands for various shells
3278 ;; You are welcome to add the syntax or even completely new statements as
3279 ;; appropriate for your favorite shell.
3281 (defconst sh-non-closing-paren
3282 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3283 ;; that inherits this property, which then confuses the indentation.
3284 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3286 (define-skeleton sh-case
3287 "Insert a case/switch statement. See `sh-feature'."
3288 (csh "expression: "
3289 "switch( " str " )" \n
3290 > "case " (read-string "pattern: ") ?: \n
3291 > _ \n
3292 "breaksw" \n
3293 ( "other pattern, %s: "
3294 < "case " str ?: \n
3295 > _ \n
3296 "breaksw" \n)
3297 < "default:" \n
3298 > _ \n
3299 resume:
3300 < < "endsw" \n)
3301 (es)
3302 (rc "expression: "
3303 > "switch( " str " ) {" \n
3304 > "case " (read-string "pattern: ") \n
3305 > _ \n
3306 ( "other pattern, %s: "
3307 "case " str > \n
3308 > _ \n)
3309 "case *" > \n
3310 > _ \n
3311 resume:
3312 ?\} > \n)
3313 (sh "expression: "
3314 > "case " str " in" \n
3315 ( "pattern, %s: "
3316 > str sh-non-closing-paren \n
3317 > _ \n
3318 ";;" \n)
3319 > "*" sh-non-closing-paren \n
3320 > _ \n
3321 resume:
3322 "esac" > \n))
3324 (define-skeleton sh-for
3325 "Insert a for loop. See `sh-feature'."
3326 (csh sh-modify sh
3327 1 ""
3328 2 "foreach "
3329 4 " ( "
3330 6 " )"
3331 15 '<
3332 16 "end")
3333 (es sh-modify rc
3334 4 " = ")
3335 (rc sh-modify sh
3336 2 "for( "
3337 6 " ) {"
3338 15 ?\} )
3339 (sh "Index variable: "
3340 > "for " str " in " _ "; do" \n
3341 > _ | ?$ & (sh-remember-variable str) \n
3342 "done" > \n))
3346 (define-skeleton sh-indexed-loop
3347 "Insert an indexed loop from 1 to n. See `sh-feature'."
3348 (bash sh-modify posix)
3349 (csh "Index variable: "
3350 "@ " str " = 1" \n
3351 "while( $" str " <= " (read-string "upper limit: ") " )" \n
3352 > _ ?$ str \n
3353 "@ " str "++" \n
3354 < "end" \n)
3355 (es sh-modify rc
3356 4 " =")
3357 (ksh88 "Index variable: "
3358 > "integer " str "=0" \n
3359 > "while (( ( " str " += 1 ) <= "
3360 (read-string "upper limit: ")
3361 " )); do" \n
3362 > _ ?$ (sh-remember-variable str) > \n
3363 "done" > \n)
3364 (posix "Index variable: "
3365 > str "=1" \n
3366 "while [ $" str " -le "
3367 (read-string "upper limit: ")
3368 " ]; do" \n
3369 > _ ?$ str \n
3370 str ?= (sh-add (sh-remember-variable str) 1) \n
3371 "done" > \n)
3372 (rc "Index variable: "
3373 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
3374 (read-string "upper limit: ")
3375 "; i++ ) print i }'`}) {" \n
3376 > _ ?$ (sh-remember-variable str) \n
3377 ?\} > \n)
3378 (sh "Index variable: "
3379 > "for " str " in `awk 'BEGIN { for( i=1; i<="
3380 (read-string "upper limit: ")
3381 "; i++ ) print i }'`; do" \n
3382 > _ ?$ (sh-remember-variable str) \n
3383 "done" > \n))
3386 (defun sh-shell-initialize-variables ()
3387 "Scan the buffer for variable assignments.
3388 Add these variables to `sh-shell-variables'."
3389 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3390 (save-excursion
3391 (goto-char (point-min))
3392 (setq sh-shell-variables-initialized t)
3393 (while (search-forward "=" nil t)
3394 (sh-assignment 0)))
3395 (message "Scanning buffer `%s' for variable assignments...done"
3396 (buffer-name)))
3398 (defvar sh-add-buffer)
3400 (defun sh-add-completer (string predicate code)
3401 "Do completion using `sh-shell-variables', but initialize it first.
3402 This function is designed for use as the \"completion table\",
3403 so it takes three arguments:
3404 STRING, the current buffer contents;
3405 PREDICATE, the predicate for filtering possible matches;
3406 CODE, which says what kind of things to do.
3407 CODE can be nil, t or `lambda'.
3408 nil means to return the best completion of STRING, or nil if there is none.
3409 t means to return a list of all possible completions of STRING.
3410 `lambda' means to return t if STRING is a valid completion as it stands."
3411 (let ((sh-shell-variables
3412 (with-current-buffer sh-add-buffer
3413 (or sh-shell-variables-initialized
3414 (sh-shell-initialize-variables))
3415 (nconc (mapcar (lambda (var)
3416 (let ((name
3417 (substring var 0 (string-match "=" var))))
3418 (cons name name)))
3419 process-environment)
3420 sh-shell-variables))))
3421 (case code
3422 ((nil) (try-completion string sh-shell-variables predicate))
3423 (lambda (test-completion string sh-shell-variables predicate))
3424 (t (all-completions string sh-shell-variables predicate)))))
3426 (defun sh-add (var delta)
3427 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3428 (interactive
3429 (let ((sh-add-buffer (current-buffer)))
3430 (list (completing-read "Variable: " 'sh-add-completer)
3431 (prefix-numeric-value current-prefix-arg))))
3432 (insert (sh-feature '((bash . "$(( ")
3433 (ksh88 . "$(( ")
3434 (posix . "$(( ")
3435 (rc . "`{expr $")
3436 (sh . "`expr $")
3437 (zsh . "$[ ")))
3438 (sh-remember-variable var)
3439 (if (< delta 0) " - " " + ")
3440 (number-to-string (abs delta))
3441 (sh-feature '((bash . " ))")
3442 (ksh88 . " ))")
3443 (posix . " ))")
3444 (rc . "}")
3445 (sh . "`")
3446 (zsh . " ]")))))
3450 (define-skeleton sh-function
3451 "Insert a function definition. See `sh-feature'."
3452 (bash sh-modify ksh88
3453 3 "() {")
3454 (ksh88 "name: "
3455 "function " str " {" \n
3456 > _ \n
3457 < "}" \n)
3458 (rc sh-modify ksh88
3459 1 "fn ")
3460 (sh ()
3461 "() {" \n
3462 > _ \n
3463 < "}" \n))
3467 (define-skeleton sh-if
3468 "Insert an if statement. See `sh-feature'."
3469 (csh "condition: "
3470 "if( " str " ) then" \n
3471 > _ \n
3472 ( "other condition, %s: "
3473 < "else if( " str " ) then" \n
3474 > _ \n)
3475 < "else" \n
3476 > _ \n
3477 resume:
3478 < "endif" \n)
3479 (es "condition: "
3480 > "if { " str " } {" \n
3481 > _ \n
3482 ( "other condition, %s: "
3483 "} { " str " } {" > \n
3484 > _ \n)
3485 "} {" > \n
3486 > _ \n
3487 resume:
3488 ?\} > \n)
3489 (rc "condition: "
3490 > "if( " str " ) {" \n
3491 > _ \n
3492 ( "other condition, %s: "
3493 "} else if( " str " ) {" > \n
3494 > _ \n)
3495 "} else {" > \n
3496 > _ \n
3497 resume:
3498 ?\} > \n)
3499 (sh "condition: "
3500 '(setq input (sh-feature sh-test))
3501 > "if " str "; then" \n
3502 > _ \n
3503 ( "other condition, %s: "
3504 > "elif " str "; then" > \n
3505 > \n)
3506 "else" > \n
3507 > \n
3508 resume:
3509 "fi" > \n))
3513 (define-skeleton sh-repeat
3514 "Insert a repeat loop definition. See `sh-feature'."
3515 (es nil
3516 > "forever {" \n
3517 > _ \n
3518 ?\} > \n)
3519 (zsh "factor: "
3520 > "repeat " str "; do" > \n
3521 > \n
3522 "done" > \n))
3524 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3528 (define-skeleton sh-select
3529 "Insert a select statement. See `sh-feature'."
3530 (ksh88 "Index variable: "
3531 > "select " str " in " _ "; do" \n
3532 > ?$ str \n
3533 "done" > \n)
3534 (bash sh-append ksh88))
3535 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3539 (define-skeleton sh-tmp-file
3540 "Insert code to setup temporary file handling. See `sh-feature'."
3541 (bash sh-append ksh88)
3542 (csh (file-name-nondirectory (buffer-file-name))
3543 "set tmp = `mktemp -t " str ".XXXXXX`" \n
3544 "onintr exit" \n _
3545 (and (goto-char (point-max))
3546 (not (bolp))
3547 ?\n)
3548 "exit:\n"
3549 "rm $tmp* >&/dev/null" > \n)
3550 (es (file-name-nondirectory (buffer-file-name))
3551 > "local( signals = $signals sighup sigint;" \n
3552 > "tmp = `{ mktemp -t " str ".XXXXXX } ) {" \n
3553 > "catch @ e {" \n
3554 > "rm $tmp^* >[2]/dev/null" \n
3555 "throw $e" \n
3556 "} {" > \n
3557 _ \n
3558 ?\} > \n
3559 ?\} > \n)
3560 (ksh88 sh-modify sh
3561 7 "EXIT")
3562 (rc (file-name-nondirectory (buffer-file-name))
3563 > "tmp = `{ mktemp -t " str ".XXXXXX }" \n
3564 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
3565 (sh (file-name-nondirectory (buffer-file-name))
3566 > "TMP=`mktemp -t " str ".XXXXXX`" \n
3567 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
3571 (define-skeleton sh-until
3572 "Insert an until loop. See `sh-feature'."
3573 (sh "condition: "
3574 '(setq input (sh-feature sh-test))
3575 > "until " str "; do" \n
3576 > _ \n
3577 "done" > \n))
3578 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3582 (define-skeleton sh-while
3583 "Insert a while loop. See `sh-feature'."
3584 (csh sh-modify sh
3585 2 ""
3586 3 "while( "
3587 5 " )"
3588 10 '<
3589 11 "end")
3590 (es sh-modify sh
3591 3 "while { "
3592 5 " } {"
3593 10 ?\} )
3594 (rc sh-modify sh
3595 3 "while( "
3596 5 " ) {"
3597 10 ?\} )
3598 (sh "condition: "
3599 '(setq input (sh-feature sh-test))
3600 > "while " str "; do" \n
3601 > _ \n
3602 "done" > \n))
3606 (define-skeleton sh-while-getopts
3607 "Insert a while getopts loop. See `sh-feature'.
3608 Prompts for an options string which consists of letters for each recognized
3609 option followed by a colon `:' if the option accepts an argument."
3610 (bash sh-modify sh
3611 18 "${0##*/}")
3612 (csh nil
3613 "while( 1 )" \n
3614 > "switch( \"$1\" )" \n
3615 '(setq input '("- x" . 2))
3617 ( "option, %s: "
3618 < "case " '(eval str)
3619 '(if (string-match " +" str)
3620 (setq v1 (substring str (match-end 0))
3621 str (substring str 0 (match-beginning 0)))
3622 (setq v1 nil))
3623 str ?: \n
3624 > "set " v1 & " = $2" | -4 & _ \n
3625 (if v1 "shift") & \n
3626 "breaksw" \n)
3627 < "case --:" \n
3628 > "shift" \n
3629 < "default:" \n
3630 > "break" \n
3631 resume:
3632 < < "endsw" \n
3633 "shift" \n
3634 < "end" \n)
3635 (ksh88 sh-modify sh
3636 16 "print"
3637 18 "${0##*/}"
3638 37 "OPTIND-1")
3639 (posix sh-modify sh
3640 18 "$(basename $0)")
3641 (sh "optstring: "
3642 > "while getopts :" str " OPT; do" \n
3643 > "case $OPT in" \n
3644 '(setq v1 (append (vconcat str) nil))
3645 ( (prog1 (if v1 (char-to-string (car v1)))
3646 (if (eq (nth 1 v1) ?:)
3647 (setq v1 (nthcdr 2 v1)
3648 v2 "\"$OPTARG\"")
3649 (setq v1 (cdr v1)
3650 v2 nil)))
3651 > str "|+" str sh-non-closing-paren \n
3652 > _ v2 \n
3653 > ";;" \n)
3654 > "*" sh-non-closing-paren \n
3655 > "echo" " \"usage: " "`basename $0`"
3656 " [+-" '(setq v1 (point)) str
3657 '(save-excursion
3658 (while (search-backward ":" v1 t)
3659 (replace-match " ARG] [+-" t t)))
3660 (if (eq (preceding-char) ?-) -5)
3661 (if (and (sequencep v1) (length v1)) "] " "} ")
3662 "[--] ARGS...\"" \n
3663 "exit 2" > \n
3664 "esac" >
3665 \n "done"
3666 > \n
3667 "shift " (sh-add "OPTIND" -1) \n
3668 "OPTIND=1" \n))
3672 (defun sh-assignment (arg)
3673 "Remember preceding identifier for future completion and do self-insert."
3674 (interactive "p")
3675 (self-insert-command arg)
3676 (if (<= arg 1)
3677 (sh-remember-variable
3678 (save-excursion
3679 (if (re-search-forward (sh-feature sh-assignment-regexp)
3680 (prog1 (point)
3681 (beginning-of-line 1))
3683 (match-string 1))))))
3686 (defun sh-maybe-here-document (arg)
3687 "Insert self. Without prefix, following unquoted `<' inserts here document.
3688 The document is bounded by `sh-here-document-word'."
3689 (interactive "*P")
3690 (self-insert-command (prefix-numeric-value arg))
3691 (or arg
3692 (not (eq (char-after (- (point) 2)) last-command-char))
3693 (save-excursion
3694 (backward-char 2)
3695 (sh-quoted-p))
3696 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
3697 (make-string (/ (current-indentation) tab-width) ?\t)
3698 ""))
3699 (delim (replace-regexp-in-string "['\"]" ""
3700 sh-here-document-word)))
3701 (insert sh-here-document-word)
3702 (or (eolp) (looking-at "[ \t]") (insert ?\s))
3703 (end-of-line 1)
3704 (while
3705 (sh-quoted-p)
3706 (end-of-line 2))
3707 (insert ?\n tabs)
3708 (save-excursion
3709 (insert ?\n tabs (replace-regexp-in-string
3710 "\\`-?[ \t]*" "" delim))))))
3713 ;; various other commands
3715 (autoload 'comint-dynamic-complete "comint"
3716 "Dynamically perform completion at point." t)
3718 (autoload 'shell-dynamic-complete-command "shell"
3719 "Dynamically complete the command at point." t)
3721 (autoload 'comint-dynamic-complete-filename "comint"
3722 "Dynamically complete the filename at point." t)
3724 (autoload 'shell-dynamic-complete-environment-variable "shell"
3725 "Dynamically complete the environment variable at point." t)
3729 (defun sh-newline-and-indent ()
3730 "Strip unquoted whitespace, insert newline, and indent like current line."
3731 (interactive "*")
3732 (indent-to (prog1 (current-indentation)
3733 (delete-region (point)
3734 (progn
3735 (or (zerop (skip-chars-backward " \t"))
3736 (if (sh-quoted-p)
3737 (forward-char)))
3738 (point)))
3739 (newline))))
3741 (defun sh-beginning-of-command ()
3742 "Move point to successive beginnings of commands."
3743 (interactive)
3744 (if (re-search-backward sh-beginning-of-command nil t)
3745 (goto-char (match-beginning 2))))
3747 (defun sh-end-of-command ()
3748 "Move point to successive ends of commands."
3749 (interactive)
3750 (if (re-search-forward sh-end-of-command nil t)
3751 (goto-char (match-end 1))))
3753 ;; Backslashification. Stolen from make-mode.el.
3755 (defun sh-backslash-region (from to delete-flag)
3756 "Insert, align, or delete end-of-line backslashes on the lines in the region.
3757 With no argument, inserts backslashes and aligns existing backslashes.
3758 With an argument, deletes the backslashes.
3760 This function does not modify the last line of the region if the region ends
3761 right at the start of the following line; it does not modify blank lines
3762 at the start of the region. So you can put the region around an entire
3763 shell command and conveniently use this command."
3764 (interactive "r\nP")
3765 (save-excursion
3766 (goto-char from)
3767 (let ((column sh-backslash-column)
3768 (endmark (make-marker)))
3769 (move-marker endmark to)
3770 ;; Compute the smallest column number past the ends of all the lines.
3771 (if sh-backslash-align
3772 (progn
3773 (if (not delete-flag)
3774 (while (< (point) to)
3775 (end-of-line)
3776 (if (= (preceding-char) ?\\)
3777 (progn (forward-char -1)
3778 (skip-chars-backward " \t")))
3779 (setq column (max column (1+ (current-column))))
3780 (forward-line 1)))
3781 ;; Adjust upward to a tab column, if that doesn't push
3782 ;; past the margin.
3783 (if (> (% column tab-width) 0)
3784 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
3785 tab-width)))
3786 (if (< adjusted (window-width))
3787 (setq column adjusted))))))
3788 ;; Don't modify blank lines at start of region.
3789 (goto-char from)
3790 (while (and (< (point) endmark) (eolp))
3791 (forward-line 1))
3792 ;; Add or remove backslashes on all the lines.
3793 (while (and (< (point) endmark)
3794 ;; Don't backslashify the last line
3795 ;; if the region ends right at the start of the next line.
3796 (save-excursion
3797 (forward-line 1)
3798 (< (point) endmark)))
3799 (if (not delete-flag)
3800 (sh-append-backslash column)
3801 (sh-delete-backslash))
3802 (forward-line 1))
3803 (move-marker endmark nil))))
3805 (defun sh-append-backslash (column)
3806 (end-of-line)
3807 ;; Note that "\\\\" is needed to get one backslash.
3808 (if (= (preceding-char) ?\\)
3809 (progn (forward-char -1)
3810 (delete-horizontal-space)
3811 (indent-to column (if sh-backslash-align nil 1)))
3812 (indent-to column (if sh-backslash-align nil 1))
3813 (insert "\\")))
3815 (defun sh-delete-backslash ()
3816 (end-of-line)
3817 (or (bolp)
3818 (progn
3819 (forward-char -1)
3820 (if (looking-at "\\\\")
3821 (delete-region (1+ (point))
3822 (progn (skip-chars-backward " \t") (point)))))))
3824 (provide 'sh-script)
3826 ;; arch-tag: eccd8b72-f337-4fc2-ae86-18155a69d937
3827 ;;; sh-script.el ends here