Merge changes from emacs-23 branch
[emacs.git] / lisp / progmodes / sh-script.el
blob7b84cc89d08ad611b0974e2fe1c9ed086e9b10d2
1 ;;; sh-script.el --- shell-script editing commands for Emacs
3 ;; Copyright (C) 1993-1997, 1999, 2001-2011 Free Software Foundation, Inc.
5 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
6 ;; Version: 2.0f
7 ;; Maintainer: FSF
8 ;; Keywords: languages, unix
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Major mode for editing shell scripts. Bourne, C and rc shells as well
28 ;; as various derivatives are supported and easily derived from. Structured
29 ;; statements can be inserted with one command or abbrev. Completion is
30 ;; available for filenames, variables known from the script, the shell and
31 ;; the environment as well as commands.
33 ;;; Known Bugs:
35 ;; - In Bourne the keyword `in' is not anchored to case, for, select ...
36 ;; - Variables in `"' strings aren't fontified because there's no way of
37 ;; syntactically distinguishing those from `'' strings.
39 ;; Indentation
40 ;; ===========
41 ;; Indentation for rc and es modes is very limited, but for Bourne shells
42 ;; and its derivatives it is quite customizable.
44 ;; The following description applies to sh and derived shells (bash,
45 ;; zsh, ...).
47 ;; There are various customization variables which allow tailoring to
48 ;; a wide variety of styles. Most of these variables are named
49 ;; sh-indent-for-XXX and sh-indent-after-XXX. For example.
50 ;; sh-indent-after-if controls the indenting of a line following
51 ;; an if statement, and sh-indent-for-fi controls the indentation
52 ;; of the line containing the fi.
54 ;; You can set each to a numeric value, but it is often more convenient
55 ;; to a symbol such as `+' which uses the value of variable `sh-basic-offset'.
56 ;; By changing this one variable you can increase or decrease how much
57 ;; indentation there is. Valid symbols:
59 ;; + Indent right by sh-basic-offset
60 ;; - Indent left by sh-basic-offset
61 ;; ++ Indent right twice sh-basic-offset
62 ;; -- Indent left twice sh-basic-offset
63 ;; * Indent right half sh-basic-offset
64 ;; / Indent left half sh-basic-offset.
66 ;; There are 4 commands to help set the indentation variables:
68 ;; `sh-show-indent'
69 ;; This shows what variable controls the indentation of the current
70 ;; line and its value.
72 ;; `sh-set-indent'
73 ;; This allows you to set the value of the variable controlling the
74 ;; current line's indentation. You can enter a number or one of a
75 ;; number of special symbols to denote the value of sh-basic-offset,
76 ;; or its negative, or half it, or twice it, etc. If you've used
77 ;; cc-mode this should be familiar. If you forget which symbols are
78 ;; valid simply press C-h at the prompt.
80 ;; `sh-learn-line-indent'
81 ;; Simply make the line look the way you want it, then invoke this
82 ;; command. It will set the variable to the value that makes the line
83 ;; indent like that. If called with a prefix argument then it will set
84 ;; the value to one of the symbols if applicable.
86 ;; `sh-learn-buffer-indent'
87 ;; This is the deluxe function! It "learns" the whole buffer (use
88 ;; narrowing if you want it to process only part). It outputs to a
89 ;; buffer *indent* any conflicts it finds, and all the variables it has
90 ;; learned. This buffer is a sort of Occur mode buffer, allowing you to
91 ;; easily find where something was set. It is popped to automatically
92 ;; if there are any conflicts found or if `sh-popup-occur-buffer' is
93 ;; non-nil.
94 ;; `sh-indent-comment' will be set if all comments follow the same
95 ;; pattern; if they don't it will be set to nil.
96 ;; Whether `sh-basic-offset' is set is determined by variable
97 ;; `sh-learn-basic-offset'.
99 ;; Unfortunately, `sh-learn-buffer-indent' can take a long time to run
100 ;; (e.g. if there are large case statements). Perhaps it does not make
101 ;; sense to run it on large buffers: if lots of lines have different
102 ;; indentation styles it will produce a lot of diagnostics in the
103 ;; *indent* buffer; if there is a consistent style then running
104 ;; `sh-learn-buffer-indent' on a small region of the buffer should
105 ;; suffice.
107 ;; Saving indentation values
108 ;; -------------------------
109 ;; After you've learned the values in a buffer, how to you remember
110 ;; them? Originally I had hoped that `sh-learn-buffer-indent'
111 ;; would make this unnecessary; simply learn the values when you visit
112 ;; the buffer.
113 ;; You can do this automatically like this:
114 ;; (add-hook 'sh-set-shell-hook 'sh-learn-buffer-indent)
116 ;; However... `sh-learn-buffer-indent' is extremely slow,
117 ;; especially on large-ish buffer. Also, if there are conflicts the
118 ;; "last one wins" which may not produce the desired setting.
120 ;; So...There is a minimal way of being able to save indentation values and
121 ;; to reload them in another buffer or at another point in time.
123 ;; Use `sh-name-style' to give a name to the indentation settings of
124 ;; the current buffer.
125 ;; Use `sh-load-style' to load indentation settings for the current
126 ;; buffer from a specific style.
127 ;; Use `sh-save-styles-to-buffer' to write all the styles to a buffer
128 ;; in lisp code. You can then store it in a file and later use
129 ;; `load-file' to load it.
131 ;; Indentation variables - buffer local or global?
132 ;; ----------------------------------------------
133 ;; I think that often having them buffer-local makes sense,
134 ;; especially if one is using `sh-learn-buffer-indent'. However, if
135 ;; a user sets values using customization, these changes won't appear
136 ;; to work if the variables are already local!
138 ;; To get round this, there is a variable `sh-make-vars-local' and 2
139 ;; functions: `sh-make-vars-local' and `sh-reset-indent-vars-to-global-values'.
141 ;; If `sh-make-vars-local' is non-nil, then these variables become
142 ;; buffer local when the mode is established.
143 ;; If this is nil, then the variables are global. At any time you
144 ;; can make them local with the command `sh-make-vars-local'.
145 ;; Conversely, to update with the global values you can use the
146 ;; command `sh-reset-indent-vars-to-global-values'.
148 ;; This may be awkward, but the intent is to cover all cases.
150 ;; Awkward things, pitfalls
151 ;; ------------------------
152 ;; Indentation for a sh script is complicated for a number of reasons:
154 ;; 1. You can't format by simply looking at symbols, you need to look
155 ;; at keywords. [This is not the case for rc and es shells.]
156 ;; 2. The character ")" is used both as a matched pair "(" ... ")" and
157 ;; as a stand-alone symbol (in a case alternative). This makes
158 ;; things quite tricky!
159 ;; 3. Here-documents in a script should be treated "as is", and when
160 ;; they terminate we want to revert to the indentation of the line
161 ;; containing the "<<" symbol.
162 ;; 4. A line may be continued using the "\".
163 ;; 5. The character "#" (outside a string) normally starts a comment,
164 ;; but it doesn't in the sequence "$#"!
166 ;; To try and address points 2 3 and 5 I used a feature that cperl mode
167 ;; uses, that of a text's syntax property. This, however, has 2
168 ;; disadvantages:
169 ;; 1. We need to scan the buffer to find which ")" symbols belong to a
170 ;; case alternative, to find any here documents, and handle "$#".
172 ;; Bugs
173 ;; ----
174 ;; - Indenting many lines is slow. It currently does each line
175 ;; independently, rather than saving state information.
177 ;; - `sh-learn-buffer-indent' is extremely slow.
179 ;; - "case $x in y) echo ;; esac)" the last ) is mis-identified as being
180 ;; part of a case-pattern. You need to add a semi-colon after "esac" to
181 ;; coerce sh-script into doing the right thing.
183 ;; - "echo $z in ps | head)" the last ) is mis-identified as being part of
184 ;; a case-pattern. You need to put the "in" between quotes to coerce
185 ;; sh-script into doing the right thing.
187 ;; - A line starting with "}>foo" is not indented like "} >foo".
189 ;; Richard Sharman <rsharman@pobox.com> June 1999.
191 ;;; Code:
193 ;; page 1: variables and settings
194 ;; page 2: indentation stuff
195 ;; page 3: mode-command and utility functions
196 ;; page 4: statement syntax-commands for various shells
197 ;; page 5: various other commands
199 (eval-when-compile
200 (require 'skeleton)
201 (require 'cl)
202 (require 'comint))
203 (require 'executable)
205 (defvar font-lock-comment-face)
206 (defvar font-lock-set-defaults)
207 (defvar font-lock-string-face)
210 (defgroup sh nil
211 "Shell programming utilities."
212 :group 'languages)
214 (defgroup sh-script nil
215 "Shell script mode."
216 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
217 :group 'sh
218 :prefix "sh-")
221 (defcustom sh-ancestor-alist
222 '((ash . sh)
223 (bash . jsh)
224 (bash2 . jsh)
225 (dtksh . ksh)
226 (es . rc)
227 (itcsh . tcsh)
228 (jcsh . csh)
229 (jsh . sh)
230 (ksh . ksh88)
231 (ksh88 . jsh)
232 (oash . sh)
233 (pdksh . ksh88)
234 (posix . sh)
235 (tcsh . csh)
236 (wksh . ksh88)
237 (wsh . sh)
238 (zsh . ksh88)
239 (rpm . sh))
240 "Alist showing the direct ancestor of various shells.
241 This is the basis for `sh-feature'. See also `sh-alias-alist'.
242 By default we have the following three hierarchies:
244 csh C Shell
245 jcsh C Shell with Job Control
246 tcsh TENEX C Shell
247 itcsh Ian's TENEX C Shell
248 rc Plan 9 Shell
249 es Extensible Shell
250 sh Bourne Shell
251 ash Almquist Shell
252 jsh Bourne Shell with Job Control
253 bash GNU Bourne Again Shell
254 ksh88 Korn Shell '88
255 ksh Korn Shell '93
256 dtksh CDE Desktop Korn Shell
257 pdksh Public Domain Korn Shell
258 wksh Window Korn Shell
259 zsh Z Shell
260 oash SCO OA (curses) Shell
261 posix IEEE 1003.2 Shell Standard
262 wsh ? Shell"
263 :type '(repeat (cons symbol symbol))
264 :group 'sh-script)
267 (defcustom sh-alias-alist
268 (append (if (eq system-type 'gnu/linux)
269 '((csh . tcsh)
270 (ksh . pdksh)))
271 ;; for the time being
272 '((ksh . ksh88)
273 (bash2 . bash)
274 (sh5 . sh)))
275 "Alist for transforming shell names to what they really are.
276 Use this where the name of the executable doesn't correspond to the type of
277 shell it really is."
278 :type '(repeat (cons symbol symbol))
279 :group 'sh-script)
282 (defcustom sh-shell-file
284 ;; On MSDOS and Windows, collapse $SHELL to lower-case and remove
285 ;; the executable extension, so comparisons with the list of
286 ;; known shells work.
287 (and (memq system-type '(ms-dos windows-nt))
288 (let* ((shell (getenv "SHELL"))
289 (shell-base
290 (and shell (file-name-nondirectory shell))))
291 ;; shell-script mode doesn't support DOS/Windows shells,
292 ;; so use the default instead.
293 (if (or (null shell)
294 (member (downcase shell-base)
295 '("command.com" "cmd.exe" "4dos.com" "ndos.com"
296 "cmdproxy.exe")))
297 "/bin/sh"
298 (file-name-sans-extension (downcase shell)))))
299 (getenv "SHELL")
300 "/bin/sh")
301 "The executable file name for the shell being programmed."
302 :type 'string
303 :group 'sh-script)
306 (defcustom sh-shell-arg
307 ;; bash does not need any options when run in a shell script,
308 '((bash)
309 (csh . "-f")
310 (pdksh)
311 ;; Bill_Mann@praxisint.com says -p with ksh can do harm.
312 (ksh88)
313 ;; -p means don't initialize functions from the environment.
314 (rc . "-p")
315 ;; Someone proposed -motif, but we don't want to encourage
316 ;; use of a non-free widget set.
317 (wksh)
318 ;; -f means don't run .zshrc.
319 (zsh . "-f"))
320 "Single argument string for the magic number. See `sh-feature'."
321 :type '(repeat (cons (symbol :tag "Shell")
322 (choice (const :tag "No Arguments" nil)
323 (string :tag "Arguments")
324 (sexp :format "Evaluate: %v"))))
325 :group 'sh-script)
327 (defcustom sh-imenu-generic-expression
328 `((sh
329 . ((nil "^\\s-*\\(function\\s-+\\)?\\([[:alpha:]_][[:alnum:]_]+\\)\\s-*()" 2))))
330 "Alist of regular expressions for recognizing shell function definitions.
331 See `sh-feature' and `imenu-generic-expression'."
332 :type '(alist :key-type (symbol :tag "Shell")
333 :value-type (alist :key-type (choice :tag "Title"
334 string
335 (const :tag "None" nil))
336 :value-type
337 (repeat :tag "Regexp, index..." sexp)))
338 :group 'sh-script
339 :version "20.4")
341 (defvar sh-shell-variables nil
342 "Alist of shell variable names that should be included in completion.
343 These are used for completion in addition to all the variables named
344 in `process-environment'. Each element looks like (VAR . VAR), where
345 the car and cdr are the same symbol.")
347 (defvar sh-shell-variables-initialized nil
348 "Non-nil if `sh-shell-variables' is initialized.")
350 (defun sh-canonicalize-shell (shell)
351 "Convert a shell name SHELL to the one we should handle it as."
352 (if (string-match "\\.exe\\'" shell)
353 (setq shell (substring shell 0 (match-beginning 0))))
354 (or (symbolp shell)
355 (setq shell (intern shell)))
356 (or (cdr (assq shell sh-alias-alist))
357 shell))
359 (defvar sh-shell (sh-canonicalize-shell (file-name-nondirectory sh-shell-file))
360 "The shell being programmed. This is set by \\[sh-set-shell].")
361 ;;;###autoload(put 'sh-shell 'safe-local-variable 'symbolp)
363 (define-abbrev-table 'sh-mode-abbrev-table ())
366 ;; I turned off this feature because it doesn't permit typing commands
367 ;; in the usual way without help.
368 ;;(defvar sh-abbrevs
369 ;; '((csh sh-abbrevs shell
370 ;; "switch" 'sh-case
371 ;; "getopts" 'sh-while-getopts)
373 ;; (es sh-abbrevs shell
374 ;; "function" 'sh-function)
376 ;; (ksh88 sh-abbrevs sh
377 ;; "select" 'sh-select)
379 ;; (rc sh-abbrevs shell
380 ;; "case" 'sh-case
381 ;; "function" 'sh-function)
383 ;; (sh sh-abbrevs shell
384 ;; "case" 'sh-case
385 ;; "function" 'sh-function
386 ;; "until" 'sh-until
387 ;; "getopts" 'sh-while-getopts)
389 ;; ;; The next entry is only used for defining the others
390 ;; (shell "for" sh-for
391 ;; "loop" sh-indexed-loop
392 ;; "if" sh-if
393 ;; "tmpfile" sh-tmp-file
394 ;; "while" sh-while)
396 ;; (zsh sh-abbrevs ksh88
397 ;; "repeat" 'sh-repeat))
398 ;; "Abbrev-table used in Shell-Script mode. See `sh-feature'.
399 ;;;Due to the internal workings of abbrev tables, the shell name symbol is
400 ;;;actually defined as the table for the like of \\[edit-abbrevs].")
404 (defun sh-mode-syntax-table (table &rest list)
405 "Copy TABLE and set syntax for successive CHARs according to strings S."
406 (setq table (copy-syntax-table table))
407 (while list
408 (modify-syntax-entry (pop list) (pop list) table))
409 table)
411 (defvar sh-mode-syntax-table
412 (sh-mode-syntax-table ()
413 ?\# "<"
414 ?\n ">#"
415 ?\" "\"\""
416 ?\' "\"'"
417 ?\` "\"`"
418 ;; ?$ might also have a ". p" syntax. Both "'" and ". p" seem
419 ;; to work fine. This is needed so that dabbrev-expand
420 ;; $VARNAME works.
421 ?$ "'"
422 ?! "_"
423 ?% "_"
424 ?: "_"
425 ?. "_"
426 ?^ "_"
427 ?~ "_"
428 ?, "_"
429 ?= "."
430 ?< "."
431 ?> ".")
432 "The syntax table to use for Shell-Script mode.
433 This is buffer-local in every such buffer.")
435 (defvar sh-mode-syntax-table-input
436 '((sh . nil))
437 "Syntax-table used in Shell-Script mode. See `sh-feature'.")
439 (defvar sh-mode-map
440 (let ((map (make-sparse-keymap))
441 (menu-map (make-sparse-keymap)))
442 (define-key map "\C-c(" 'sh-function)
443 (define-key map "\C-c\C-w" 'sh-while)
444 (define-key map "\C-c\C-u" 'sh-until)
445 (define-key map "\C-c\C-t" 'sh-tmp-file)
446 (define-key map "\C-c\C-s" 'sh-select)
447 (define-key map "\C-c\C-r" 'sh-repeat)
448 (define-key map "\C-c\C-o" 'sh-while-getopts)
449 (define-key map "\C-c\C-l" 'sh-indexed-loop)
450 (define-key map "\C-c\C-i" 'sh-if)
451 (define-key map "\C-c\C-f" 'sh-for)
452 (define-key map "\C-c\C-c" 'sh-case)
453 (define-key map "\C-c?" 'sh-show-indent)
454 (define-key map "\C-c=" 'sh-set-indent)
455 (define-key map "\C-c<" 'sh-learn-line-indent)
456 (define-key map "\C-c>" 'sh-learn-buffer-indent)
457 (define-key map "\C-c\C-\\" 'sh-backslash-region)
459 (define-key map "=" 'sh-assignment)
460 (define-key map "\C-c+" 'sh-add)
461 (define-key map "\C-\M-x" 'sh-execute-region)
462 (define-key map "\C-c\C-x" 'executable-interpret)
463 (define-key map "<" 'sh-maybe-here-document)
464 (define-key map "(" 'skeleton-pair-insert-maybe)
465 (define-key map "{" 'skeleton-pair-insert-maybe)
466 (define-key map "[" 'skeleton-pair-insert-maybe)
467 (define-key map "'" 'skeleton-pair-insert-maybe)
468 (define-key map "`" 'skeleton-pair-insert-maybe)
469 (define-key map "\"" 'skeleton-pair-insert-maybe)
471 (define-key map [remap complete-tag] 'comint-dynamic-complete)
472 (define-key map [remap delete-backward-char]
473 'backward-delete-char-untabify)
474 (define-key map "\C-c:" 'sh-set-shell)
475 (define-key map [remap backward-sentence] 'sh-beginning-of-command)
476 (define-key map [remap forward-sentence] 'sh-end-of-command)
477 (define-key map [menu-bar sh-script] (cons "Sh-Script" menu-map))
478 (define-key menu-map [sh-learn-buffer-indent]
479 '(menu-item "Learn buffer indentation" sh-learn-buffer-indent
480 :help "Learn how to indent the buffer the way it currently is."))
481 (define-key menu-map [sh-learn-line-indent]
482 '(menu-item "Learn line indentation" sh-learn-line-indent
483 :help "Learn how to indent a line as it currently is indented"))
484 (define-key menu-map [sh-show-indent]
485 '(menu-item "Show indentation" sh-show-indent
486 :help "Show the how the current line would be indented"))
487 (define-key menu-map [sh-set-indent]
488 '(menu-item "Set indentation" sh-set-indent
489 :help "Set the indentation for the current line"))
491 (define-key menu-map [sh-pair]
492 '(menu-item "Insert braces and quotes in pairs"
493 (lambda ()
494 (interactive)
495 (require 'skeleton)
496 (setq skeleton-pair (not skeleton-pair)))
497 :button (:toggle . (and (boundp 'skeleton-pair)
498 skeleton-pair))
499 :help "Inserting a brace or quote automatically inserts the matching pair"))
501 (define-key menu-map [sh-s0] '("--"))
502 ;; Insert
503 (define-key menu-map [sh-function]
504 '(menu-item "Function..." sh-function
505 :help "Insert a function definition"))
506 (define-key menu-map [sh-add]
507 '(menu-item "Addition..." sh-add
508 :help "Insert an addition of VAR and prefix DELTA for Bourne (type) shell"))
509 (define-key menu-map [sh-until]
510 '(menu-item "Until Loop" sh-until
511 :help "Insert an until loop"))
512 (define-key menu-map [sh-repeat]
513 '(menu-item "Repeat Loop" sh-repeat
514 :help "Insert a repeat loop definition"))
515 (define-key menu-map [sh-while]
516 '(menu-item "While Loop" sh-while
517 :help "Insert a while loop"))
518 (define-key menu-map [sh-getopts]
519 '(menu-item "Options Loop" sh-while-getopts
520 :help "Insert a while getopts loop."))
521 (define-key menu-map [sh-indexed-loop]
522 '(menu-item "Indexed Loop" sh-indexed-loop
523 :help "Insert an indexed loop from 1 to n."))
524 (define-key menu-map [sh-select]
525 '(menu-item "Select Statement" sh-select
526 :help "Insert a select statement "))
527 (define-key menu-map [sh-if]
528 '(menu-item "If Statement" sh-if
529 :help "Insert an if statement"))
530 (define-key menu-map [sh-for]
531 '(menu-item "For Loop" sh-for
532 :help "Insert a for loop"))
533 (define-key menu-map [sh-case]
534 '(menu-item "Case Statement" sh-case
535 :help "Insert a case/switch statement"))
536 (define-key menu-map [sh-s1] '("--"))
537 (define-key menu-map [sh-exec]
538 '(menu-item "Execute region" sh-execute-region
539 :help "Pass optional header and region to a subshell for noninteractive execution"))
540 (define-key menu-map [sh-exec-interpret]
541 '(menu-item "Execute script..." executable-interpret
542 :help "Run script with user-specified args, and collect output in a buffer"))
543 (define-key menu-map [sh-set-shell]
544 '(menu-item "Set shell type..." sh-set-shell
545 :help "Set this buffer's shell to SHELL (a string)"))
546 (define-key menu-map [sh-backslash-region]
547 '(menu-item "Backslash region" sh-backslash-region
548 :help "Insert, align, or delete end-of-line backslashes on the lines in the region."))
549 map)
550 "Keymap used in Shell-Script mode.")
552 (defvar sh-skeleton-pair-default-alist '((?( _ ?)) (?\))
553 (?[ ?\s _ ?\s ?]) (?\])
554 (?{ _ ?}) (?\}))
555 "Value to use for `skeleton-pair-default-alist' in Shell-Script mode.")
557 (defcustom sh-dynamic-complete-functions
558 '(shell-dynamic-complete-environment-variable
559 shell-dynamic-complete-command
560 comint-dynamic-complete-filename)
561 "Functions for doing TAB dynamic completion."
562 :type '(repeat function)
563 :group 'sh-script)
565 (defcustom sh-assignment-regexp
566 '((csh . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*[-+*/%^]?=")
567 ;; actually spaces are only supported in let/(( ... ))
568 (ksh88 . "\\<\\([[:alnum:]_]+\\)\\(\\[.+\\]\\)?[ \t]*\\([-+*/%&|~^]\\|<<\\|>>\\)?=")
569 (rc . "\\<\\([[:alnum:]_*]+\\)[ \t]*=")
570 (sh . "\\<\\([[:alnum:]_]+\\)="))
571 "Regexp for the variable name and what may follow in an assignment.
572 First grouping matches the variable name. This is upto and including the `='
573 sign. See `sh-feature'."
574 :type '(repeat (cons (symbol :tag "Shell")
575 (choice regexp
576 (sexp :format "Evaluate: %v"))))
577 :group 'sh-script)
580 (defcustom sh-indentation 4
581 "The width for further indentation in Shell-Script mode."
582 :type 'integer
583 :group 'sh-script)
584 (put 'sh-indentation 'safe-local-variable 'integerp)
586 (defcustom sh-remember-variable-min 3
587 "Don't remember variables less than this length for completing reads."
588 :type 'integer
589 :group 'sh-script)
592 (defvar sh-header-marker nil
593 "When non-nil is the end of header for prepending by \\[sh-execute-region].
594 That command is also used for setting this variable.")
595 (make-variable-buffer-local 'sh-header-marker)
597 (defcustom sh-beginning-of-command
598 "\\([;({`|&]\\|\\`\\|[^\\]\n\\)[ \t]*\\([/~[:alnum:]:]\\)"
599 "Regexp to determine the beginning of a shell command.
600 The actual command starts at the beginning of the second \\(grouping\\)."
601 :type 'regexp
602 :group 'sh-script)
605 (defcustom sh-end-of-command
606 "\\([/~[:alnum:]:]\\)[ \t]*\\([;#)}`|&]\\|$\\)"
607 "Regexp to determine the end of a shell command.
608 The actual command ends at the end of the first \\(grouping\\)."
609 :type 'regexp
610 :group 'sh-script)
614 (defcustom sh-here-document-word "EOF"
615 "Word to delimit here documents.
616 If the first character of this string is \"-\", this is taken as
617 part of the redirection operator, rather than part of the
618 word (that is, \"<<-\" instead of \"<<\"). This is a feature
619 used by some shells (for example Bash) to indicate that leading
620 tabs inside the here document should be ignored. In this case,
621 Emacs indents the initial body and end of the here document with
622 tabs, to the same level as the start (note that apart from this
623 there is no support for indentation of here documents). This
624 will only work correctly if `sh-basic-offset' is a multiple of
625 `tab-width'.
627 Any quote characters or leading whitespace in the word are
628 removed when closing the here document."
629 :type 'string
630 :group 'sh-script)
633 (defvar sh-test
634 '((sh "[ ]" . 3)
635 (ksh88 "[[ ]]" . 4))
636 "Initial input in Bourne if, while and until skeletons. See `sh-feature'.")
639 ;; customized this out of sheer bravado. not for the faint of heart.
640 ;; but it *did* have an asterisk in the docstring!
641 (defcustom sh-builtins
642 '((bash sh-append posix
643 "." "alias" "bg" "bind" "builtin" "caller" "compgen" "complete"
644 "declare" "dirs" "disown" "enable" "fc" "fg" "help" "history"
645 "jobs" "kill" "let" "local" "popd" "printf" "pushd" "shopt"
646 "source" "suspend" "typeset" "unalias")
648 ;; The next entry is only used for defining the others
649 (bourne sh-append shell
650 "eval" "export" "getopts" "newgrp" "pwd" "read" "readonly"
651 "times" "ulimit")
653 (csh sh-append shell
654 "alias" "chdir" "glob" "history" "limit" "nice" "nohup" "rehash"
655 "setenv" "source" "time" "unalias" "unhash")
657 (dtksh sh-append wksh)
659 (es "access" "apids" "cd" "echo" "eval" "false" "let" "limit" "local"
660 "newpgrp" "result" "time" "umask" "var" "vars" "wait" "whatis")
662 (jsh sh-append sh
663 "bg" "fg" "jobs" "kill" "stop" "suspend")
665 (jcsh sh-append csh
666 "bg" "fg" "jobs" "kill" "notify" "stop" "suspend")
668 (ksh88 sh-append bourne
669 "alias" "bg" "false" "fc" "fg" "jobs" "kill" "let" "print" "time"
670 "typeset" "unalias" "whence")
672 (oash sh-append sh
673 "checkwin" "dateline" "error" "form" "menu" "newwin" "oadeinit"
674 "oaed" "oahelp" "oainit" "pp" "ppfile" "scan" "scrollok" "wattr"
675 "wclear" "werase" "win" "wmclose" "wmmessage" "wmopen" "wmove"
676 "wmtitle" "wrefresh")
678 (pdksh sh-append ksh88
679 "bind")
681 (posix sh-append sh
682 "command")
684 (rc "builtin" "cd" "echo" "eval" "limit" "newpgrp" "shift" "umask" "wait"
685 "whatis")
687 (sh sh-append bourne
688 "hash" "test" "type")
690 ;; The next entry is only used for defining the others
691 (shell "cd" "echo" "eval" "set" "shift" "umask" "unset" "wait")
693 (wksh sh-append ksh88
694 ;; FIXME: This looks too much like a regexp. --Stef
695 "Xt[A-Z][A-Za-z]*")
697 (zsh sh-append ksh88
698 "autoload" "bindkey" "builtin" "chdir" "compctl" "declare" "dirs"
699 "disable" "disown" "echotc" "enable" "functions" "getln" "hash"
700 "history" "integer" "limit" "local" "log" "popd" "pushd" "r"
701 "readonly" "rehash" "sched" "setopt" "source" "suspend" "true"
702 "ttyctl" "type" "unfunction" "unhash" "unlimit" "unsetopt" "vared"
703 "which"))
704 "List of all shell builtins for completing read and fontification.
705 Note that on some systems not all builtins are available or some are
706 implemented as aliases. See `sh-feature'."
707 :type '(repeat (cons (symbol :tag "Shell")
708 (choice (repeat string)
709 (sexp :format "Evaluate: %v"))))
710 :group 'sh-script)
714 (defcustom sh-leading-keywords
715 '((bash sh-append sh
716 "time")
718 (csh "else")
720 (es "true" "unwind-protect" "whatis")
722 (rc "else")
724 (sh "!" "do" "elif" "else" "if" "then" "trap" "type" "until" "while"))
725 "List of keywords that may be immediately followed by a builtin or keyword.
726 Given some confusion between keywords and builtins depending on shell and
727 system, the distinction here has been based on whether they influence the
728 flow of control or syntax. See `sh-feature'."
729 :type '(repeat (cons (symbol :tag "Shell")
730 (choice (repeat string)
731 (sexp :format "Evaluate: %v"))))
732 :group 'sh-script)
735 (defcustom sh-other-keywords
736 '((bash sh-append bourne
737 "bye" "logout" "select")
739 ;; The next entry is only used for defining the others
740 (bourne sh-append sh
741 "function")
743 (csh sh-append shell
744 "breaksw" "default" "end" "endif" "endsw" "foreach" "goto"
745 "if" "logout" "onintr" "repeat" "switch" "then" "while")
747 (es "break" "catch" "exec" "exit" "fn" "for" "forever" "fork" "if"
748 "return" "throw" "while")
750 (ksh88 sh-append bourne
751 "select")
753 (rc "break" "case" "exec" "exit" "fn" "for" "if" "in" "return" "switch"
754 "while")
756 (sh sh-append shell
757 "done" "esac" "fi" "for" "in" "return")
759 ;; The next entry is only used for defining the others
760 (shell "break" "case" "continue" "exec" "exit")
762 (zsh sh-append bash
763 "select" "foreach"))
764 "List of keywords not in `sh-leading-keywords'.
765 See `sh-feature'."
766 :type '(repeat (cons (symbol :tag "Shell")
767 (choice (repeat string)
768 (sexp :format "Evaluate: %v"))))
769 :group 'sh-script)
773 (defvar sh-variables
774 '((bash sh-append sh
775 "allow_null_glob_expansion" "auto_resume" "BASH" "BASH_ENV"
776 "BASH_VERSINFO" "BASH_VERSION" "cdable_vars" "COMP_CWORD"
777 "COMP_LINE" "COMP_POINT" "COMP_WORDS" "COMPREPLY" "DIRSTACK"
778 "ENV" "EUID" "FCEDIT" "FIGNORE" "FUNCNAME"
779 "glob_dot_filenames" "GLOBIGNORE" "GROUPS" "histchars"
780 "HISTCMD" "HISTCONTROL" "HISTFILE" "HISTFILESIZE"
781 "HISTIGNORE" "history_control" "HISTSIZE"
782 "hostname_completion_file" "HOSTFILE" "HOSTTYPE" "IGNOREEOF"
783 "ignoreeof" "INPUTRC" "LINENO" "MACHTYPE" "MAIL_WARNING"
784 "noclobber" "nolinks" "notify" "no_exit_on_failed_exec"
785 "NO_PROMPT_VARS" "OLDPWD" "OPTERR" "OSTYPE" "PIPESTATUS"
786 "PPID" "POSIXLY_CORRECT" "PROMPT_COMMAND" "PS3" "PS4"
787 "pushd_silent" "PWD" "RANDOM" "REPLY" "SECONDS" "SHELLOPTS"
788 "SHLVL" "TIMEFORMAT" "TMOUT" "UID")
790 (csh sh-append shell
791 "argv" "cdpath" "child" "echo" "histchars" "history" "home"
792 "ignoreeof" "mail" "noclobber" "noglob" "nonomatch" "path" "prompt"
793 "shell" "status" "time" "verbose")
795 (es sh-append shell
796 "apid" "cdpath" "CDPATH" "history" "home" "ifs" "noexport" "path"
797 "pid" "prompt" "signals")
799 (jcsh sh-append csh
800 "notify")
802 (ksh88 sh-append sh
803 "ENV" "ERRNO" "FCEDIT" "FPATH" "HISTFILE" "HISTSIZE" "LINENO"
804 "OLDPWD" "PPID" "PS3" "PS4" "PWD" "RANDOM" "REPLY" "SECONDS"
805 "TMOUT")
807 (oash sh-append sh
808 "FIELD" "FIELD_MAX" "LAST_KEY" "OALIB" "PP_ITEM" "PP_NUM")
810 (rc sh-append shell
811 "apid" "apids" "cdpath" "CDPATH" "history" "home" "ifs" "path" "pid"
812 "prompt" "status")
814 (sh sh-append shell
815 "CDPATH" "IFS" "OPTARG" "OPTIND" "PS1" "PS2")
817 ;; The next entry is only used for defining the others
818 (shell "COLUMNS" "EDITOR" "HOME" "HUSHLOGIN" "LANG" "LC_COLLATE"
819 "LC_CTYPE" "LC_MESSAGES" "LC_MONETARY" "LC_NUMERIC" "LC_TIME"
820 "LINES" "LOGNAME" "MAIL" "MAILCHECK" "MAILPATH" "PAGER" "PATH"
821 "SHELL" "TERM" "TERMCAP" "TERMINFO" "VISUAL")
823 (tcsh sh-append csh
824 "addsuffix" "ampm" "autocorrect" "autoexpand" "autolist"
825 "autologout" "chase_symlinks" "correct" "dextract" "edit" "el"
826 "fignore" "gid" "histlit" "HOST" "HOSTTYPE" "HPATH"
827 "ignore_symlinks" "listjobs" "listlinks" "listmax" "matchbeep"
828 "nobeep" "NOREBIND" "oid" "printexitvalue" "prompt2" "prompt3"
829 "pushdsilent" "pushdtohome" "recexact" "recognize_only_executables"
830 "rmstar" "savehist" "SHLVL" "showdots" "sl" "SYSTYPE" "tcsh" "term"
831 "tperiod" "tty" "uid" "version" "visiblebell" "watch" "who"
832 "wordchars")
834 (zsh sh-append ksh88
835 "BAUD" "bindcmds" "cdpath" "DIRSTACKSIZE" "fignore" "FIGNORE" "fpath"
836 "HISTCHARS" "hostcmds" "hosts" "HOSTS" "LISTMAX" "LITHISTSIZE"
837 "LOGCHECK" "mailpath" "manpath" "NULLCMD" "optcmds" "path" "POSTEDIT"
838 "prompt" "PROMPT" "PROMPT2" "PROMPT3" "PROMPT4" "psvar" "PSVAR"
839 "READNULLCMD" "REPORTTIME" "RPROMPT" "RPS1" "SAVEHIST" "SPROMPT"
840 "STTY" "TIMEFMT" "TMOUT" "TMPPREFIX" "varcmds" "watch" "WATCH"
841 "WATCHFMT" "WORDCHARS" "ZDOTDIR"))
842 "List of all shell variables available for completing read.
843 See `sh-feature'.")
846 ;; Font-Lock support
848 (defface sh-heredoc
849 '((((min-colors 88) (class color)
850 (background dark))
851 (:foreground "yellow1" :weight bold))
852 (((class color)
853 (background dark))
854 (:foreground "yellow" :weight bold))
855 (((class color)
856 (background light))
857 (:foreground "tan1" ))
859 (:weight bold)))
860 "Face to show a here-document"
861 :group 'sh-indentation)
863 ;; These colors are probably icky. It's just a placeholder though.
864 (defface sh-quoted-exec
865 '((((class color) (background dark))
866 (:foreground "salmon"))
867 (((class color) (background light))
868 (:foreground "magenta"))
870 (:weight bold)))
871 "Face to show quoted execs like ``"
872 :group 'sh-indentation)
873 (define-obsolete-face-alias 'sh-heredoc-face 'sh-heredoc "22.1")
874 (defvar sh-heredoc-face 'sh-heredoc)
876 (defface sh-escaped-newline '((t :inherit font-lock-string-face))
877 "Face used for (non-escaped) backslash at end of a line in Shell-script mode."
878 :group 'sh-script
879 :version "22.1")
881 (defvar sh-font-lock-keywords-var
882 '((csh sh-append shell
883 ("\\${?[#?]?\\([[:alpha:]_][[:alnum:]_]*\\|0\\)" 1
884 font-lock-variable-name-face))
886 (es sh-append executable-font-lock-keywords
887 ("\\$#?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\)" 1
888 font-lock-variable-name-face))
890 (rc sh-append es)
891 (bash sh-append shell ("\\$(\\(\\sw+\\)" (1 'sh-quoted-exec t) ))
892 (sh sh-append shell
893 ;; Variable names.
894 ("\\$\\({#?\\)?\\([[:alpha:]_][[:alnum:]_]*\\|[-#?@!]\\)" 2
895 font-lock-variable-name-face)
896 ;; Function names.
897 ("^\\(\\sw+\\)[ \t]*(" 1 font-lock-function-name-face)
898 ("\\<\\(function\\)\\>[ \t]*\\(\\sw+\\)?"
899 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
900 ("\\(?:^\\s *\\|[[();&|]\\s *\\|\\(?:\\s +-[ao]\\|if\\|else\\|then\\|while\\|do\\)\\s +\\)\\(!\\)"
901 1 font-lock-negation-char-face))
903 ;; The next entry is only used for defining the others
904 (shell
905 ;; Using font-lock-string-face here confuses sh-get-indent-info.
906 ("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'sh-escaped-newline)
907 ("\\\\[^[:alnum:]]" 0 font-lock-string-face)
908 ("\\${?\\([[:alpha:]_][[:alnum:]_]*\\|[0-9]+\\|[$*_]\\)" 1
909 font-lock-variable-name-face))
910 (rpm sh-append rpm2
911 ("%{?\\(\\sw+\\)" 1 font-lock-keyword-face))
912 (rpm2 sh-append shell
913 ("^\\(\\sw+\\):" 1 font-lock-variable-name-face)))
914 "Default expressions to highlight in Shell Script modes. See `sh-feature'.")
916 (defvar sh-font-lock-keywords-var-1
917 '((sh "[ \t]in\\>"))
918 "Subdued level highlighting for Shell Script modes.")
920 (defvar sh-font-lock-keywords-var-2 ()
921 "Gaudy level highlighting for Shell Script modes.")
923 ;; These are used for the syntax table stuff (derived from cperl-mode).
924 ;; Note: parse-sexp-lookup-properties must be set to t for it to work.
925 (defconst sh-st-punc (string-to-syntax "."))
926 (defconst sh-here-doc-syntax (string-to-syntax "|")) ;; generic string
928 (eval-and-compile
929 (defconst sh-escaped-line-re
930 ;; Should match until the real end-of-continued-line, but if that is not
931 ;; possible (because we bump into EOB or the search bound), then we should
932 ;; match until the search bound.
933 "\\(?:\\(?:.*[^\\\n]\\)?\\(?:\\\\\\\\\\)*\\\\\n\\)*.*")
935 (defconst sh-here-doc-open-re
936 (concat "<<-?\\s-*\\\\?\\(\\(?:['\"][^'\"]+['\"]\\|\\sw\\|[-/~._]\\)+\\)"
937 sh-escaped-line-re "\\(\n\\)")))
939 (defun sh-font-lock-open-heredoc (start string eol)
940 "Determine the syntax of the \\n after a <<EOF.
941 START is the position of <<.
942 STRING is the actual word used as delimiter (e.g. \"EOF\").
943 INDENTED is non-nil if the here document's content (and the EOF mark) can
944 be indented (i.e. a <<- was used rather than just <<).
945 Point is at the beginning of the next line."
946 (unless (or (memq (char-before start) '(?< ?>))
947 (sh-in-comment-or-string start))
948 ;; We're looking at <<STRING, so we add "^STRING$" to the syntactic
949 ;; font-lock keywords to detect the end of this here document.
950 (let ((str (replace-regexp-in-string "['\"]" "" string))
951 (ppss (save-excursion (syntax-ppss eol))))
952 (if (nth 4 ppss)
953 ;; The \n not only starts the heredoc but also closes a comment.
954 ;; Let's close the comment just before the \n.
955 (put-text-property (1- eol) eol 'syntax-table '(12))) ;">"
956 (if (or (nth 5 ppss) (> (count-lines start eol) 1))
957 ;; If the sh-escaped-line-re part of sh-here-doc-open-re has matched
958 ;; several lines, make sure we refontify them together.
959 ;; Furthermore, if (nth 5 ppss) is non-nil (i.e. the \n is
960 ;; escaped), it means the right \n is actually further down.
961 ;; Don't bother fixing it now, but place a multiline property so
962 ;; that when jit-lock-context-* refontifies the rest of the
963 ;; buffer, it also refontifies the current line with it.
964 (put-text-property start (1+ eol) 'syntax-multiline t))
965 (put-text-property eol (1+ eol) 'sh-here-doc-marker str)
966 (prog1 sh-here-doc-syntax
967 (goto-char (+ 2 start))))))
969 (defun sh-syntax-propertize-here-doc (end)
970 (let ((ppss (syntax-ppss)))
971 (when (eq t (nth 3 ppss))
972 (let ((key (get-text-property (nth 8 ppss) 'sh-here-doc-marker))
973 (case-fold-search nil))
974 (when (re-search-forward
975 (concat "^\\([ \t]*\\)" (regexp-quote key) "\\(\n\\)")
976 end 'move)
977 (let ((eol (match-beginning 2)))
978 (put-text-property eol (1+ eol)
979 'syntax-table sh-here-doc-syntax)))))))
981 (defun sh-font-lock-quoted-subshell (limit)
982 "Search for a subshell embedded in a string.
983 Find all the unescaped \" characters within said subshell, remembering that
984 subshells can nest."
985 ;; FIXME: This can (and often does) match multiple lines, yet it makes no
986 ;; effort to handle multiline cases correctly, so it ends up being
987 ;; rather flakey.
988 (when (eq ?\" (nth 3 (syntax-ppss))) ; Check we matched an opening quote.
989 ;; bingo we have a $( or a ` inside a ""
990 (let ((char (char-after (point)))
991 ;; `state' can be: double-quote, backquote, code.
992 (state (if (eq (char-before) ?`) 'backquote 'code))
993 ;; Stacked states in the context.
994 (states '(double-quote)))
995 (while (and state (progn (skip-chars-forward "^'\\\\\"`$()" limit)
996 (< (point) limit)))
997 ;; unescape " inside a $( ... ) construct.
998 (case (char-after)
999 (?\' (case state
1000 (double-quote nil)
1001 (t (forward-char 1) (skip-chars-forward "^'" limit))))
1002 (?\\ (forward-char 1))
1003 (?\" (case state
1004 (double-quote (setq state (pop states)))
1005 (t (push state states) (setq state 'double-quote)))
1006 (if state (put-text-property (point) (1+ (point))
1007 'syntax-table '(1))))
1008 (?\` (case state
1009 (backquote (setq state (pop states)))
1010 (t (push state states) (setq state 'backquote))))
1011 (?\$ (if (not (eq (char-after (1+ (point))) ?\())
1013 (forward-char 1)
1014 (case state
1015 (t (push state states) (setq state 'code)))))
1016 (?\( (case state
1017 (double-quote nil)
1018 (t (push state states) (setq state 'code))))
1019 (?\) (case state
1020 (double-quote nil)
1021 (t (setq state (pop states)))))
1022 (t (error "Internal error in sh-font-lock-quoted-subshell")))
1023 (forward-char 1)))))
1026 (defun sh-is-quoted-p (pos)
1027 (and (eq (char-before pos) ?\\)
1028 (not (sh-is-quoted-p (1- pos)))))
1030 (defun sh-font-lock-paren (start)
1031 (unless (nth 8 (syntax-ppss))
1032 (save-excursion
1033 (goto-char start)
1034 ;; Skip through all patterns
1035 (while
1036 (progn
1037 (while
1038 (progn
1039 (forward-comment (- (point-max)))
1040 (when (and (eolp) (sh-is-quoted-p (point)))
1041 (forward-char -1)
1042 t)))
1043 ;; Skip through one pattern
1044 (while
1045 (or (/= 0 (skip-syntax-backward "w_"))
1046 (/= 0 (skip-chars-backward "-$=?[]*@/\\\\"))
1047 (and (sh-is-quoted-p (1- (point)))
1048 (goto-char (- (point) 2)))
1049 (when (memq (char-before) '(?\" ?\' ?\}))
1050 (condition-case nil (progn (backward-sexp 1) t)
1051 (error nil)))))
1052 ;; Patterns can be preceded by an open-paren (Bug#1320).
1053 (if (eq (char-before (point)) ?\()
1054 (backward-char 1))
1055 (while (progn
1056 (forward-comment (- (point-max)))
1057 ;; Maybe we've bumped into an escaped newline.
1058 (sh-is-quoted-p (point)))
1059 (backward-char 1))
1060 (when (eq (char-before) ?|)
1061 (backward-char 1) t)))
1062 (when (progn (backward-char 2)
1063 (if (> start (line-end-position))
1064 (put-text-property (point) (1+ start)
1065 'syntax-multiline t))
1066 ;; FIXME: The `in' may just be a random argument to
1067 ;; a normal command rather than the real `in' keyword.
1068 ;; I.e. we should look back to try and find the
1069 ;; corresponding `case'.
1070 (and (looking-at ";[;&]\\|in")
1071 ;; ";; esac )" is a case that looks like a case-pattern
1072 ;; but it's really just a close paren after a case
1073 ;; statement. I.e. if we skipped over `esac' just now,
1074 ;; we're not looking at a case-pattern.
1075 (not (looking-at "..[ \t\n]+esac[^[:word:]_]"))))
1076 sh-st-punc))))
1078 (defun sh-font-lock-backslash-quote ()
1079 (if (eq (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) ?\')
1080 ;; In a '...' the backslash is not escaping.
1081 sh-st-punc
1082 nil))
1084 (defun sh-syntax-propertize-function (start end)
1085 (goto-char start)
1086 (sh-syntax-propertize-here-doc end)
1087 (funcall
1088 (syntax-propertize-rules
1089 (sh-here-doc-open-re
1090 (2 (sh-font-lock-open-heredoc
1091 (match-beginning 0) (match-string 1) (match-beginning 2))))
1092 ("\\s|" (0 (prog1 nil (sh-syntax-propertize-here-doc end))))
1093 ;; A `#' begins a comment when it is unquoted and at the
1094 ;; beginning of a word. In the shell, words are separated by
1095 ;; metacharacters. The list of special chars is taken from
1096 ;; the single-unix spec of the shell command language (under
1097 ;; `quoting') but with `$' removed.
1098 ("[^|&;<>()`\\\"' \t\n]\\(#+\\)" (1 "_"))
1099 ;; In a '...' the backslash is not escaping.
1100 ("\\(\\\\\\)'" (1 (sh-font-lock-backslash-quote)))
1101 ;; Make sure $@ and $? are correctly recognized as sexps.
1102 ("\\$\\([?@]\\)" (1 "_"))
1103 ;; Distinguish the special close-paren in `case'.
1104 (")" (0 (sh-font-lock-paren (match-beginning 0))))
1105 ;; Highlight (possibly nested) subshells inside "" quoted
1106 ;; regions correctly.
1107 ("\"\\(?:\\(?:[^\\\"]\\|\\)*?[^\\]\\(?:\\\\\\\\\\)*\\)??\\(\\$(\\|`\\)"
1108 (1 (ignore
1109 ;; Save excursion because we want to also apply other
1110 ;; syntax-propertize rules within the affected region.
1111 (if (nth 8 (syntax-ppss))
1112 (goto-char (1+ (match-beginning 0)))
1113 (save-excursion
1114 (sh-font-lock-quoted-subshell end)))))))
1115 (point) end))
1117 (defun sh-font-lock-syntactic-face-function (state)
1118 (let ((q (nth 3 state)))
1119 (if q
1120 (if (characterp q)
1121 (if (eq q ?\`) 'sh-quoted-exec font-lock-string-face)
1122 sh-heredoc-face)
1123 font-lock-comment-face)))
1125 (defgroup sh-indentation nil
1126 "Variables controlling indentation in shell scripts.
1128 Note: customizing these variables will not affect existing buffers if
1129 `sh-make-vars-local' is non-nil. See the documentation for
1130 variable `sh-make-vars-local', command `sh-make-vars-local'
1131 and command `sh-reset-indent-vars-to-global-values'."
1132 :group 'sh-script)
1135 (defcustom sh-set-shell-hook nil
1136 "Hook run by `sh-set-shell'."
1137 :type 'hook
1138 :group 'sh-script)
1140 (defcustom sh-mode-hook nil
1141 "Hook run by `sh-mode'."
1142 :type 'hook
1143 :group 'sh-script)
1145 (defcustom sh-learn-basic-offset nil
1146 "When `sh-guess-basic-offset' should learn `sh-basic-offset'.
1148 nil mean: never.
1149 t means: only if there seems to be an obvious value.
1150 Anything else means: whenever we have a \"good guess\" as to the value."
1151 :type '(choice
1152 (const :tag "Never" nil)
1153 (const :tag "Only if sure" t)
1154 (const :tag "If have a good guess" usually))
1155 :group 'sh-indentation)
1157 (defcustom sh-popup-occur-buffer nil
1158 "Controls when `sh-learn-buffer-indent' pops the `*indent*' buffer.
1159 If t it is always shown. If nil, it is shown only when there
1160 are conflicts."
1161 :type '(choice
1162 (const :tag "Only when there are conflicts." nil)
1163 (const :tag "Always" t))
1164 :group 'sh-indentation)
1166 (defcustom sh-blink t
1167 "If non-nil, `sh-show-indent' shows the line indentation is relative to.
1168 The position on the line is not necessarily meaningful.
1169 In some cases the line will be the matching keyword, but this is not
1170 always the case."
1171 :type 'boolean
1172 :group 'sh-indentation)
1174 (defcustom sh-first-lines-indent 0
1175 "The indentation of the first non-blank non-comment line.
1176 Usually 0 meaning first column.
1177 Can be set to a number, or to nil which means leave it as is."
1178 :type '(choice
1179 (const :tag "Leave as is" nil)
1180 (integer :tag "Column number"
1181 :menu-tag "Indent to this col (0 means first col)" ))
1182 :group 'sh-indentation)
1185 (defcustom sh-basic-offset 4
1186 "The default indentation increment.
1187 This value is used for the `+' and `-' symbols in an indentation variable."
1188 :type 'integer
1189 :group 'sh-indentation)
1190 (put 'sh-basic-offset 'safe-local-variable 'integerp)
1192 (defcustom sh-indent-comment nil
1193 "How a comment line is to be indented.
1194 nil means leave it as it is;
1195 t means indent it as a normal line, aligning it to previous non-blank
1196 non-comment line;
1197 a number means align to that column, e.g. 0 means first column."
1198 :type '(choice
1199 (const :tag "Leave as is." nil)
1200 (const :tag "Indent as a normal line." t)
1201 (integer :menu-tag "Indent to this col (0 means first col)."
1202 :tag "Indent to column number.") )
1203 :group 'sh-indentation)
1206 (defvar sh-debug nil
1207 "Enable lots of debug messages - if function `sh-debug' is enabled.")
1210 ;; Uncomment this defun and comment the defmacro for debugging.
1211 ;; (defun sh-debug (&rest args)
1212 ;; "For debugging: display message ARGS if variable SH-DEBUG is non-nil."
1213 ;; (if sh-debug
1214 ;; (apply 'message args)))
1215 (defmacro sh-debug (&rest args))
1217 (defconst sh-symbol-list
1218 '((const :tag "+ " :value +
1219 :menu-tag "+ Indent right by sh-basic-offset")
1220 (const :tag "- " :value -
1221 :menu-tag "- Indent left by sh-basic-offset")
1222 (const :tag "++" :value ++
1223 :menu-tag "++ Indent right twice sh-basic-offset")
1224 (const :tag "--" :value --
1225 :menu-tag "-- Indent left twice sh-basic-offset")
1226 (const :tag "* " :value *
1227 :menu-tag "* Indent right half sh-basic-offset")
1228 (const :tag "/ " :value /
1229 :menu-tag "/ Indent left half sh-basic-offset")))
1231 (defcustom sh-indent-for-else 0
1232 "How much to indent an `else' relative to its `if'. Usually 0."
1233 :type `(choice
1234 (integer :menu-tag "A number (positive=>indent right)"
1235 :tag "A number")
1236 (const :tag "--") ;; separator!
1237 ,@ sh-symbol-list
1239 :group 'sh-indentation)
1241 (defconst sh-number-or-symbol-list
1242 (append '((integer :menu-tag "A number (positive=>indent right)"
1243 :tag "A number")
1244 (const :tag "--")) ; separator
1245 sh-symbol-list))
1247 (defcustom sh-indent-for-fi 0
1248 "How much to indent a `fi' relative to its `if'. Usually 0."
1249 :type `(choice ,@ sh-number-or-symbol-list )
1250 :group 'sh-indentation)
1252 (defcustom sh-indent-for-done 0
1253 "How much to indent a `done' relative to its matching stmt. Usually 0."
1254 :type `(choice ,@ sh-number-or-symbol-list )
1255 :group 'sh-indentation)
1257 (defcustom sh-indent-after-else '+
1258 "How much to indent a statement after an `else' statement."
1259 :type `(choice ,@ sh-number-or-symbol-list )
1260 :group 'sh-indentation)
1262 (defcustom sh-indent-after-if '+
1263 "How much to indent a statement after an `if' statement.
1264 This includes lines after `else' and `elif' statements, too, but
1265 does not affect the `else', `elif' or `fi' statements themselves."
1266 :type `(choice ,@ sh-number-or-symbol-list )
1267 :group 'sh-indentation)
1269 (defcustom sh-indent-for-then 0
1270 "How much to indent a `then' relative to its `if'."
1271 :type `(choice ,@ sh-number-or-symbol-list )
1272 :group 'sh-indentation)
1274 (defcustom sh-indent-for-do 0
1275 "How much to indent a `do' statement.
1276 This is relative to the statement before the `do', typically a
1277 `while', `until', `for', `repeat' or `select' statement."
1278 :type `(choice ,@ sh-number-or-symbol-list)
1279 :group 'sh-indentation)
1281 (defcustom sh-indent-after-do '+
1282 "How much to indent a line after a `do' statement.
1283 This is used when the `do' is the first word of the line.
1284 This is relative to the statement before the `do', typically a
1285 `while', `until', `for', `repeat' or `select' statement."
1286 :type `(choice ,@ sh-number-or-symbol-list)
1287 :group 'sh-indentation)
1289 (defcustom sh-indent-after-loop-construct '+
1290 "How much to indent a statement after a loop construct.
1292 This variable is used when the keyword `do' is on the same line as the
1293 loop statement (e.g., `until', `while' or `for').
1294 If the `do' is on a line by itself, then `sh-indent-after-do' is used instead."
1295 :type `(choice ,@ sh-number-or-symbol-list)
1296 :group 'sh-indentation)
1299 (defcustom sh-indent-after-done 0
1300 "How much to indent a statement after a `done' keyword.
1301 Normally this is 0, which aligns the `done' to the matching
1302 looping construct line.
1303 Setting it non-zero allows you to have the `do' statement on a line
1304 by itself and align the done under to do."
1305 :type `(choice ,@ sh-number-or-symbol-list)
1306 :group 'sh-indentation)
1308 (defcustom sh-indent-for-case-label '+
1309 "How much to indent a case label statement.
1310 This is relative to the line containing the `case' statement."
1311 :type `(choice ,@ sh-number-or-symbol-list)
1312 :group 'sh-indentation)
1314 (defcustom sh-indent-for-case-alt '++
1315 "How much to indent statements after the case label.
1316 This is relative to the line containing the `case' statement."
1317 :type `(choice ,@ sh-number-or-symbol-list)
1318 :group 'sh-indentation)
1321 (defcustom sh-indent-for-continuation '+
1322 "How much to indent for a continuation statement."
1323 :type `(choice ,@ sh-number-or-symbol-list)
1324 :group 'sh-indentation)
1326 (defcustom sh-indent-after-open '+
1327 "How much to indent after a line with an opening parenthesis or brace.
1328 For an open paren after a function, `sh-indent-after-function' is used."
1329 :type `(choice ,@ sh-number-or-symbol-list)
1330 :group 'sh-indentation)
1332 (defcustom sh-indent-after-function '+
1333 "How much to indent after a function line."
1334 :type `(choice ,@ sh-number-or-symbol-list)
1335 :group 'sh-indentation)
1337 ;; These 2 are for the rc shell:
1339 (defcustom sh-indent-after-switch '+
1340 "How much to indent a `case' statement relative to the `switch' statement.
1341 This is for the rc shell."
1342 :type `(choice ,@ sh-number-or-symbol-list)
1343 :group 'sh-indentation)
1345 (defcustom sh-indent-after-case '+
1346 "How much to indent a statement relative to the `case' statement.
1347 This is for the rc shell."
1348 :type `(choice ,@ sh-number-or-symbol-list)
1349 :group 'sh-indentation)
1351 (defcustom sh-backslash-column 48
1352 "Column in which `sh-backslash-region' inserts backslashes."
1353 :type 'integer
1354 :group 'sh)
1356 (defcustom sh-backslash-align t
1357 "If non-nil, `sh-backslash-region' will align backslashes."
1358 :type 'boolean
1359 :group 'sh)
1361 ;; Internal use - not designed to be changed by the user:
1363 (defun sh-mkword-regexpr (word)
1364 "Make a regexp which matches WORD as a word.
1365 This specifically excludes an occurrence of WORD followed by
1366 punctuation characters like '-'."
1367 (concat word "\\([^-[:alnum:]_]\\|$\\)"))
1369 (defconst sh-re-done (sh-mkword-regexpr "done"))
1372 (defconst sh-kws-for-done
1373 '((sh . ( "while" "until" "for" ) )
1374 (bash . ( "while" "until" "for" "select" ) )
1375 (ksh88 . ( "while" "until" "for" "select" ) )
1376 (zsh . ( "while" "until" "for" "repeat" "select" ) ) )
1377 "Which keywords can match the word `done' in this shell.")
1380 (defconst sh-indent-supported
1381 '((sh . t)
1382 (csh . nil)
1383 (rc . t))
1384 "Shell types that shell indenting can do something with.")
1386 (defvar sh-indent-supported-here nil
1387 "Non-nil if we support indentation for the current buffer's shell type.")
1389 (defconst sh-var-list
1391 sh-basic-offset sh-first-lines-indent sh-indent-after-case
1392 sh-indent-after-do sh-indent-after-done
1393 sh-indent-after-else
1394 sh-indent-after-if
1395 sh-indent-after-loop-construct
1396 sh-indent-after-open
1397 sh-indent-comment
1398 sh-indent-for-case-alt
1399 sh-indent-for-case-label
1400 sh-indent-for-continuation
1401 sh-indent-for-do
1402 sh-indent-for-done
1403 sh-indent-for-else
1404 sh-indent-for-fi
1405 sh-indent-for-then
1407 "A list of variables used by script mode to control indentation.
1408 This list is used when switching between buffer-local and global
1409 values of variables, and for the commands using indentation styles.")
1411 (defvar sh-make-vars-local t
1412 "*Controls whether indentation variables are local to the buffer.
1413 If non-nil, indentation variables are made local initially.
1414 If nil, you can later make the variables local by invoking
1415 command `sh-make-vars-local'.
1416 The default is t because I assume that in one Emacs session one is
1417 frequently editing existing scripts with different styles.")
1420 ;; mode-command and utility functions
1422 ;;;###autoload
1423 (define-derived-mode sh-mode prog-mode "Shell-script"
1424 "Major mode for editing shell scripts.
1425 This mode works for many shells, since they all have roughly the same syntax,
1426 as far as commands, arguments, variables, pipes, comments etc. are concerned.
1427 Unless the file's magic number indicates the shell, your usual shell is
1428 assumed. Since filenames rarely give a clue, they are not further analyzed.
1430 This mode adapts to the variations between shells (see `sh-set-shell') by
1431 means of an inheritance based feature lookup (see `sh-feature'). This
1432 mechanism applies to all variables (including skeletons) that pertain to
1433 shell-specific features.
1435 The default style of this mode is that of Rosenblatt's Korn shell book.
1436 The syntax of the statements varies with the shell being used. The
1437 following commands are available, based on the current shell's syntax:
1438 \\<sh-mode-map>
1439 \\[sh-case] case statement
1440 \\[sh-for] for loop
1441 \\[sh-function] function definition
1442 \\[sh-if] if statement
1443 \\[sh-indexed-loop] indexed loop from 1 to n
1444 \\[sh-while-getopts] while getopts loop
1445 \\[sh-repeat] repeat loop
1446 \\[sh-select] select loop
1447 \\[sh-until] until loop
1448 \\[sh-while] while loop
1450 For sh and rc shells indentation commands are:
1451 \\[sh-show-indent] Show the variable controlling this line's indentation.
1452 \\[sh-set-indent] Set then variable controlling this line's indentation.
1453 \\[sh-learn-line-indent] Change the indentation variable so this line
1454 would indent to the way it currently is.
1455 \\[sh-learn-buffer-indent] Set the indentation variables so the
1456 buffer indents as it currently is indented.
1459 \\[backward-delete-char-untabify] Delete backward one position, even if it was a tab.
1460 \\[newline-and-indent] Delete unquoted space and indent new line same as this one.
1461 \\[sh-end-of-command] Go to end of successive commands.
1462 \\[sh-beginning-of-command] Go to beginning of successive commands.
1463 \\[sh-set-shell] Set this buffer's shell, and maybe its magic number.
1464 \\[sh-execute-region] Have optional header and region be executed in a subshell.
1466 \\[sh-maybe-here-document] Without prefix, following an unquoted < inserts here document.
1467 \{, (, [, ', \", `
1468 Unless quoted with \\, insert the pairs {}, (), [], or '', \"\", ``.
1470 If you generally program a shell different from your login shell you can
1471 set `sh-shell-file' accordingly. If your shell's file name doesn't correctly
1472 indicate what shell it is use `sh-alias-alist' to translate.
1474 If your shell gives error messages with line numbers, you can use \\[executable-interpret]
1475 with your script for an edit-interpret-debug cycle."
1476 (make-local-variable 'sh-shell-file)
1477 (make-local-variable 'sh-shell)
1479 (set (make-local-variable 'skeleton-pair-default-alist)
1480 sh-skeleton-pair-default-alist)
1481 (set (make-local-variable 'skeleton-end-hook)
1482 (lambda () (or (eolp) (newline) (indent-relative))))
1484 (set (make-local-variable 'paragraph-start) (concat page-delimiter "\\|$"))
1485 (set (make-local-variable 'paragraph-separate) paragraph-start)
1486 (set (make-local-variable 'comment-start) "# ")
1487 (set (make-local-variable 'comment-start-skip) "#+[\t ]*")
1488 (set (make-local-variable 'local-abbrev-table) sh-mode-abbrev-table)
1489 (set (make-local-variable 'comint-dynamic-complete-functions)
1490 sh-dynamic-complete-functions)
1491 ;; we can't look if previous line ended with `\'
1492 (set (make-local-variable 'comint-prompt-regexp) "^[ \t]*")
1493 (set (make-local-variable 'imenu-case-fold-search) nil)
1494 (set (make-local-variable 'font-lock-defaults)
1495 `((sh-font-lock-keywords
1496 sh-font-lock-keywords-1 sh-font-lock-keywords-2)
1497 nil nil
1498 ((?/ . "w") (?~ . "w") (?. . "w") (?- . "w") (?_ . "w")) nil
1499 (font-lock-syntactic-face-function
1500 . sh-font-lock-syntactic-face-function)))
1501 (set (make-local-variable 'syntax-propertize-function)
1502 #'sh-syntax-propertize-function)
1503 (add-hook 'syntax-propertize-extend-region-functions
1504 #'syntax-propertize-multiline 'append 'local)
1505 (set (make-local-variable 'skeleton-pair-alist) '((?` _ ?`)))
1506 (set (make-local-variable 'skeleton-pair-filter-function) 'sh-quoted-p)
1507 (set (make-local-variable 'skeleton-further-elements)
1508 '((< '(- (min sh-indentation (current-column))))))
1509 (set (make-local-variable 'skeleton-filter-function) 'sh-feature)
1510 (set (make-local-variable 'skeleton-newline-indent-rigidly) t)
1511 (set (make-local-variable 'sh-indent-supported-here) nil)
1512 (set (make-local-variable 'defun-prompt-regexp)
1513 (concat "^\\(function[ \t]\\|[[:alnum:]]+[ \t]+()[ \t]+\\)"))
1514 ;; Parse or insert magic number for exec, and set all variables depending
1515 ;; on the shell thus determined.
1516 (sh-set-shell
1517 (cond ((save-excursion
1518 (goto-char (point-min))
1519 (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1520 (match-string 2))
1521 ((not buffer-file-name)
1522 sh-shell-file)
1523 ;; Checks that use `buffer-file-name' follow.
1524 ((string-match "\\.m?spec\\'" buffer-file-name)
1525 "rpm")
1526 ((string-match "[.]sh\\>" buffer-file-name)
1527 "sh")
1528 ((string-match "[.]bash\\>" buffer-file-name)
1529 "bash")
1530 ((string-match "[.]ksh\\>" buffer-file-name)
1531 "ksh")
1532 ((string-match "[.]csh\\>" buffer-file-name)
1533 "csh")
1534 ((equal (file-name-nondirectory buffer-file-name) ".profile")
1535 "sh")
1537 sh-shell-file))
1538 nil nil))
1540 ;;;###autoload
1541 (defalias 'shell-script-mode 'sh-mode)
1544 (defun sh-font-lock-keywords (&optional keywords)
1545 "Function to get simple fontification based on `sh-font-lock-keywords'.
1546 This adds rules for comments and assignments."
1547 (sh-feature sh-font-lock-keywords-var
1548 (when (stringp (sh-feature sh-assignment-regexp))
1549 (lambda (list)
1550 `((,(sh-feature sh-assignment-regexp)
1551 1 font-lock-variable-name-face)
1552 ,@keywords
1553 ,@list
1554 ,@executable-font-lock-keywords)))))
1556 (defun sh-font-lock-keywords-1 (&optional builtins)
1557 "Function to get better fontification including keywords."
1558 (let ((keywords (concat "\\([;(){}`|&]\\|^\\)[ \t]*\\(\\("
1559 (regexp-opt (sh-feature sh-leading-keywords) t)
1560 "[ \t]+\\)?"
1561 (regexp-opt (append (sh-feature sh-leading-keywords)
1562 (sh-feature sh-other-keywords))
1563 t))))
1564 (sh-font-lock-keywords
1565 `(,@(if builtins
1566 `((,(concat keywords "[ \t]+\\)?"
1567 (regexp-opt (sh-feature sh-builtins) t)
1568 "\\>")
1569 (2 font-lock-keyword-face nil t)
1570 (6 font-lock-builtin-face))
1571 ,@(sh-feature sh-font-lock-keywords-var-2)))
1572 (,(concat keywords "\\)\\>")
1573 2 font-lock-keyword-face)
1574 ,@(sh-feature sh-font-lock-keywords-var-1)))))
1576 (defun sh-font-lock-keywords-2 ()
1577 "Function to get better fontification including keywords and builtins."
1578 (sh-font-lock-keywords-1 t))
1581 (defvar sh-regexp-for-done nil
1582 "A buffer-local regexp to match opening keyword for done.")
1584 (defvar sh-kw-alist nil
1585 "A buffer-local, since it is shell-type dependent, list of keywords.")
1587 ;; ( key-word first-on-this on-prev-line )
1588 ;; This is used to set `sh-kw-alist' which is a list of sublists each
1589 ;; having 3 elements:
1590 ;; a keyword
1591 ;; a rule to check when the keyword appears on "this" line
1592 ;; a rule to check when the keyword appears on "the previous" line
1593 ;; The keyword is usually a string and is the first word on a line.
1594 ;; If this keyword appears on the line whose indentation is to be
1595 ;; calculated, the rule in element 2 is called. If this returns
1596 ;; non-zero, the resulting point (which may be changed by the rule)
1597 ;; is used as the default indentation.
1598 ;; If it returned false or the keyword was not found in the table,
1599 ;; then the keyword from the previous line is looked up and the rule
1600 ;; in element 3 is called. In this case, however,
1601 ;; `sh-get-indent-info' does not stop but may keep going and test
1602 ;; other keywords against rules in element 3. This is because the
1603 ;; preceding line could have, for example, an opening "if" and an
1604 ;; opening "while" keyword and we need to add the indentation offsets
1605 ;; for both.
1607 (defconst sh-kw
1608 '((sh
1609 ("if" nil sh-handle-prev-if)
1610 ("elif" sh-handle-this-else sh-handle-prev-else)
1611 ("else" sh-handle-this-else sh-handle-prev-else)
1612 ("fi" sh-handle-this-fi sh-handle-prev-fi)
1613 ("then" sh-handle-this-then sh-handle-prev-then)
1614 ("(" nil sh-handle-prev-open)
1615 ("{" nil sh-handle-prev-open)
1616 ("[" nil sh-handle-prev-open)
1617 ("}" sh-handle-this-close nil)
1618 (")" sh-handle-this-close nil)
1619 ("]" sh-handle-this-close nil)
1620 ("case" nil sh-handle-prev-case)
1621 ("esac" sh-handle-this-esac sh-handle-prev-esac)
1622 (case-label nil sh-handle-after-case-label) ;; ???
1623 (";;" nil sh-handle-prev-case-alt-end) ;; ???
1624 (";;&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
1625 (";&" nil sh-handle-prev-case-alt-end) ;Like ";;" with diff semantics.
1626 ("done" sh-handle-this-done sh-handle-prev-done)
1627 ("do" sh-handle-this-do sh-handle-prev-do))
1629 ;; Note: we don't need specific stuff for bash and zsh shells;
1630 ;; the regexp `sh-regexp-for-done' handles the extra keywords
1631 ;; these shells use.
1633 ("{" nil sh-handle-prev-open)
1634 ("}" sh-handle-this-close nil)
1635 ("case" sh-handle-this-rc-case sh-handle-prev-rc-case))))
1639 (defun sh-set-shell (shell &optional no-query-flag insert-flag)
1640 "Set this buffer's shell to SHELL (a string).
1641 When used interactively, insert the proper starting #!-line,
1642 and make the visited file executable via `executable-set-magic',
1643 perhaps querying depending on the value of `executable-query'.
1645 When this function is called noninteractively, INSERT-FLAG (the third
1646 argument) controls whether to insert a #!-line and think about making
1647 the visited file executable, and NO-QUERY-FLAG (the second argument)
1648 controls whether to query about making the visited file executable.
1650 Calls the value of `sh-set-shell-hook' if set."
1651 (interactive (list (completing-read (format "Shell \(default %s\): "
1652 sh-shell-file)
1653 interpreter-mode-alist
1654 (lambda (x) (eq (cdr x) 'sh-mode))
1655 nil nil nil sh-shell-file)
1656 (eq executable-query 'function)
1658 (if (string-match "\\.exe\\'" shell)
1659 (setq shell (substring shell 0 (match-beginning 0))))
1660 (setq sh-shell (intern (file-name-nondirectory shell))
1661 sh-shell (or (cdr (assq sh-shell sh-alias-alist))
1662 sh-shell))
1663 (if insert-flag
1664 (setq sh-shell-file
1665 (executable-set-magic shell (sh-feature sh-shell-arg)
1666 no-query-flag insert-flag)))
1667 (setq mode-line-process (format "[%s]" sh-shell))
1668 (set (make-local-variable 'sh-shell-variables) nil)
1669 (set (make-local-variable 'sh-shell-variables-initialized) nil)
1670 (set (make-local-variable 'imenu-generic-expression)
1671 (sh-feature sh-imenu-generic-expression))
1672 (let ((tem (sh-feature sh-mode-syntax-table-input)))
1673 (when tem
1674 (set (make-local-variable 'sh-mode-syntax-table)
1675 (apply 'sh-mode-syntax-table tem))
1676 (set-syntax-table sh-mode-syntax-table)))
1677 (dolist (var (sh-feature sh-variables))
1678 (sh-remember-variable var))
1679 (if (setq sh-indent-supported-here (sh-feature sh-indent-supported))
1680 (progn
1681 (message "Setting up indent for shell type %s" sh-shell)
1682 (set (make-local-variable 'parse-sexp-lookup-properties) t)
1683 (set (make-local-variable 'sh-kw-alist) (sh-feature sh-kw))
1684 (let ((regexp (sh-feature sh-kws-for-done)))
1685 (if regexp
1686 (set (make-local-variable 'sh-regexp-for-done)
1687 (sh-mkword-regexpr (regexp-opt regexp t)))))
1688 (message "setting up indent stuff")
1689 ;; sh-mode has already made indent-line-function local
1690 ;; but do it in case this is called before that.
1691 (set (make-local-variable 'indent-line-function) 'sh-indent-line)
1692 (if sh-make-vars-local
1693 (sh-make-vars-local))
1694 (message "Indentation setup for shell type %s" sh-shell))
1695 (message "No indentation for this shell type.")
1696 (setq indent-line-function 'sh-basic-indent-line))
1697 (when font-lock-mode
1698 (setq font-lock-set-defaults nil)
1699 (font-lock-set-defaults)
1700 (font-lock-fontify-buffer))
1701 (run-hooks 'sh-set-shell-hook))
1704 (defun sh-feature (alist &optional function)
1705 "Index ALIST by the current shell.
1706 If ALIST isn't a list where every element is a cons, it is returned as is.
1707 Else indexing follows an inheritance logic which works in two ways:
1709 - Fall back on successive ancestors (see `sh-ancestor-alist') as long as
1710 the alist contains no value for the current shell.
1711 The ultimate default is always `sh'.
1713 - If the value thus looked up is a list starting with `sh-append',
1714 we call the function `sh-append' with the rest of the list as
1715 arguments, and use the value. However, the next element of the
1716 list is not used as-is; instead, we look it up recursively
1717 in ALIST to allow the function called to define the value for
1718 one shell to be derived from another shell.
1719 The value thus determined is physically replaced into the alist.
1721 If FUNCTION is non-nil, it is called with one argument,
1722 the value thus obtained, and the result is used instead."
1723 (or (if (consp alist)
1724 ;; Check for something that isn't a valid alist.
1725 (let ((l alist))
1726 (while (and l (consp (car l)))
1727 (setq l (cdr l)))
1728 (if l alist)))
1730 (let ((orig-sh-shell sh-shell))
1731 (let ((sh-shell sh-shell)
1732 elt val)
1733 (while (and sh-shell
1734 (not (setq elt (assq sh-shell alist))))
1735 (setq sh-shell (cdr (assq sh-shell sh-ancestor-alist))))
1736 ;; If the shell is not known, treat it as sh.
1737 (unless elt
1738 (setq elt (assq 'sh alist)))
1739 (setq val (cdr elt))
1740 (if (and (consp val)
1741 (memq (car val) '(sh-append sh-modify)))
1742 (setq val
1743 (apply (car val)
1744 ;; Refer to the value for a different shell,
1745 ;; as a kind of inheritance.
1746 (let ((sh-shell (car (cdr val))))
1747 (sh-feature alist))
1748 (cddr val))))
1749 (if function
1750 (setq sh-shell orig-sh-shell
1751 val (funcall function val)))
1752 val))))
1756 ;; I commented this out because nobody calls it -- rms.
1757 ;;(defun sh-abbrevs (ancestor &rest list)
1758 ;; "Iff it isn't, define the current shell as abbrev table and fill that.
1759 ;;Abbrev table will inherit all abbrevs from ANCESTOR, which is either an abbrev
1760 ;;table or a list of (NAME1 EXPANSION1 ...). In addition it will define abbrevs
1761 ;;according to the remaining arguments NAMEi EXPANSIONi ...
1762 ;;EXPANSION may be either a string or a skeleton command."
1763 ;; (or (if (boundp sh-shell)
1764 ;; (symbol-value sh-shell))
1765 ;; (progn
1766 ;; (if (listp ancestor)
1767 ;; (nconc list ancestor))
1768 ;; (define-abbrev-table sh-shell ())
1769 ;; (if (vectorp ancestor)
1770 ;; (mapatoms (lambda (atom)
1771 ;; (or (eq atom 0)
1772 ;; (define-abbrev (symbol-value sh-shell)
1773 ;; (symbol-name atom)
1774 ;; (symbol-value atom)
1775 ;; (symbol-function atom))))
1776 ;; ancestor))
1777 ;; (while list
1778 ;; (define-abbrev (symbol-value sh-shell)
1779 ;; (car list)
1780 ;; (if (stringp (car (cdr list)))
1781 ;; (car (cdr list))
1782 ;; "")
1783 ;; (if (symbolp (car (cdr list)))
1784 ;; (car (cdr list))))
1785 ;; (setq list (cdr (cdr list)))))
1786 ;; (symbol-value sh-shell)))
1789 (defun sh-append (ancestor &rest list)
1790 "Return list composed of first argument (a list) physically appended to rest."
1791 (nconc list ancestor))
1794 (defun sh-modify (skeleton &rest list)
1795 "Modify a copy of SKELETON by replacing I1 with REPL1, I2 with REPL2 ..."
1796 (setq skeleton (copy-sequence skeleton))
1797 (while list
1798 (setcar (or (nthcdr (car list) skeleton)
1799 (error "Index %d out of bounds" (car list)))
1800 (car (cdr list)))
1801 (setq list (nthcdr 2 list)))
1802 skeleton)
1805 (defun sh-basic-indent-line ()
1806 "Indent a line for Sh mode (shell script mode).
1807 Indent as far as preceding non-empty line, then by steps of `sh-indentation'.
1808 Lines containing only comments are considered empty."
1809 (interactive)
1810 (let ((previous (save-excursion
1811 (while (and (progn (beginning-of-line)
1812 (not (bobp)))
1813 (progn
1814 (forward-line -1)
1815 (back-to-indentation)
1816 (or (eolp)
1817 (eq (following-char) ?#)))))
1818 (current-column)))
1819 current)
1820 (save-excursion
1821 (indent-to (if (eq this-command 'newline-and-indent)
1822 previous
1823 (if (< (current-column)
1824 (setq current (progn (back-to-indentation)
1825 (current-column))))
1826 (if (eolp) previous 0)
1827 (delete-region (point)
1828 (progn (beginning-of-line) (point)))
1829 (if (eolp)
1830 (max previous (* (1+ (/ current sh-indentation))
1831 sh-indentation))
1832 (* (1+ (/ current sh-indentation)) sh-indentation))))))
1833 (if (< (current-column) (current-indentation))
1834 (skip-chars-forward " \t"))))
1837 (defun sh-execute-region (start end &optional flag)
1838 "Pass optional header and region to a subshell for noninteractive execution.
1839 The working directory is that of the buffer, and only environment variables
1840 are already set which is why you can mark a header within the script.
1842 With a positive prefix ARG, instead of sending region, define header from
1843 beginning of buffer to point. With a negative prefix ARG, instead of sending
1844 region, clear header."
1845 (interactive "r\nP")
1846 (if flag
1847 (setq sh-header-marker (if (> (prefix-numeric-value flag) 0)
1848 (point-marker)))
1849 (if sh-header-marker
1850 (save-excursion
1851 (let (buffer-undo-list)
1852 (goto-char sh-header-marker)
1853 (append-to-buffer (current-buffer) start end)
1854 (shell-command-on-region (point-min)
1855 (setq end (+ sh-header-marker
1856 (- end start)))
1857 sh-shell-file)
1858 (delete-region sh-header-marker end)))
1859 (shell-command-on-region start end (concat sh-shell-file " -")))))
1862 (defun sh-remember-variable (var)
1863 "Make VARIABLE available for future completing reads in this buffer."
1864 (or (< (length var) sh-remember-variable-min)
1865 (getenv var)
1866 (assoc var sh-shell-variables)
1867 (push (cons var var) sh-shell-variables))
1868 var)
1872 (defun sh-quoted-p ()
1873 "Is point preceded by an odd number of backslashes?"
1874 (eq -1 (% (save-excursion (skip-chars-backward "\\\\")) 2)))
1876 ;; Indentation stuff.
1877 (defun sh-must-support-indent ()
1878 "*Signal an error if the shell type for this buffer is not supported.
1879 Also, the buffer must be in Shell-script mode."
1880 (unless sh-indent-supported-here
1881 (error "This buffer's shell does not support indentation through Emacs")))
1883 (defun sh-make-vars-local ()
1884 "Make the indentation variables local to this buffer.
1885 Normally they already are local. This command is provided in case
1886 variable `sh-make-vars-local' has been set to nil.
1888 To revert all these variables to the global values, use
1889 command `sh-reset-indent-vars-to-global-values'."
1890 (interactive)
1891 (mapc 'make-local-variable sh-var-list)
1892 (message "Indentation variables are now local."))
1894 (defun sh-reset-indent-vars-to-global-values ()
1895 "Reset local indentation variables to the global values.
1896 Then, if variable `sh-make-vars-local' is non-nil, make them local."
1897 (interactive)
1898 (mapc 'kill-local-variable sh-var-list)
1899 (if sh-make-vars-local
1900 (mapcar 'make-local-variable sh-var-list)))
1903 ;; Theoretically these are only needed in shell and derived modes.
1904 ;; However, the routines which use them are only called in those modes.
1905 (defconst sh-special-keywords "then\\|do")
1907 (defun sh-help-string-for-variable (var)
1908 "Construct a string for `sh-read-variable' when changing variable VAR ."
1909 (let ((msg (documentation-property var 'variable-documentation))
1910 (msg2 ""))
1911 (unless (memq var '(sh-first-lines-indent sh-indent-comment))
1912 (setq msg2
1913 (format "\n
1914 You can enter a number (positive to increase indentation,
1915 negative to decrease indentation, zero for no change to indentation).
1917 Or, you can enter one of the following symbols which are relative to
1918 the value of variable `sh-basic-offset'
1919 which in this buffer is currently %s.
1921 \t%s."
1922 sh-basic-offset
1923 (mapconcat (lambda (x)
1924 (nth (1- (length x)) x))
1925 sh-symbol-list "\n\t"))))
1926 (concat
1927 ;; The following shows the global not the local value!
1928 ;; (format "Current value of %s is %s\n\n" var (symbol-value var))
1929 msg msg2)))
1931 (defun sh-read-variable (var)
1932 "Read a new value for indentation variable VAR."
1933 (interactive "*variable? ") ;; to test
1934 (let ((minibuffer-help-form `(sh-help-string-for-variable
1935 (quote ,var)))
1936 val)
1937 (setq val (read-from-minibuffer
1938 (format "New value for %s (press %s for help): "
1939 var (single-key-description help-char))
1940 (format "%s" (symbol-value var))
1941 nil t))
1942 val))
1946 (defun sh-in-comment-or-string (start)
1947 "Return non-nil if START is in a comment or string."
1948 (save-excursion
1949 (let ((state (syntax-ppss start)))
1950 (or (nth 3 state) (nth 4 state)))))
1952 (defun sh-goto-matching-if ()
1953 "Go to the matching if for a fi.
1954 This handles nested if..fi pairs."
1955 (let ((found (sh-find-prev-matching "\\bif\\b" "\\bfi\\b" 1)))
1956 (if found
1957 (goto-char found))))
1960 ;; Functions named sh-handle-this-XXX are called when the keyword on the
1961 ;; line whose indentation is being handled contain XXX;
1962 ;; those named sh-handle-prev-XXX are when XXX appears on the previous line.
1964 (defun sh-handle-prev-if ()
1965 (list '(+ sh-indent-after-if)))
1967 (defun sh-handle-this-else ()
1968 (if (sh-goto-matching-if)
1969 ;; (list "aligned to if")
1970 (list "aligned to if" '(+ sh-indent-for-else))
1974 (defun sh-handle-prev-else ()
1975 (if (sh-goto-matching-if)
1976 (list '(+ sh-indent-after-if))
1979 (defun sh-handle-this-fi ()
1980 (if (sh-goto-matching-if)
1981 (list "aligned to if" '(+ sh-indent-for-fi))
1985 (defun sh-handle-prev-fi ()
1986 ;; Why do we have this rule? Because we must go back to the if
1987 ;; to get its indent. We may continue back from there.
1988 ;; We return nil because we don't have anything to add to result,
1989 ;; the side affect of setting align-point is all that matters.
1990 ;; we could return a comment (a string) but I can't think of a good one...
1991 (sh-goto-matching-if)
1992 nil)
1994 (defun sh-handle-this-then ()
1995 (let ((p (sh-goto-matching-if)))
1996 (if p
1997 (list '(+ sh-indent-for-then))
2000 (defun sh-handle-prev-then ()
2001 (let ((p (sh-goto-matching-if)))
2002 (if p
2003 (list '(+ sh-indent-after-if))
2006 (defun sh-handle-prev-open ()
2007 (save-excursion
2008 (let ((x (sh-prev-stmt)))
2009 (if (and x
2010 (progn
2011 (goto-char x)
2013 (looking-at "function\\b")
2014 (looking-at "\\s-*\\S-+\\s-*()")
2016 (list '(+ sh-indent-after-function))
2017 (list '(+ sh-indent-after-open)))
2020 (defun sh-handle-this-close ()
2021 (forward-char 1) ;; move over ")"
2022 (if (sh-safe-forward-sexp -1)
2023 (list "aligned to opening paren")))
2025 (defun sh-goto-matching-case ()
2026 (let ((found (sh-find-prev-matching "\\bcase\\b" "\\besac\\b" 1)))
2027 (if found (goto-char found))))
2029 (defun sh-handle-prev-case ()
2030 ;; This is typically called when point is on same line as a case
2031 ;; we shouldn't -- and can't find prev-case
2032 (if (looking-at ".*\\<case\\>")
2033 (list '(+ sh-indent-for-case-label))
2034 (error "We don't seem to be on a line with a case"))) ;; debug
2036 (defun sh-handle-this-esac ()
2037 (if (sh-goto-matching-case)
2038 (list "aligned to matching case")))
2040 (defun sh-handle-prev-esac ()
2041 (if (sh-goto-matching-case)
2042 (list "matching case")))
2044 (defun sh-handle-after-case-label ()
2045 (if (sh-goto-matching-case)
2046 (list '(+ sh-indent-for-case-alt))))
2048 (defun sh-handle-prev-case-alt-end ()
2049 (if (sh-goto-matching-case)
2050 (list '(+ sh-indent-for-case-label))))
2052 (defun sh-safe-forward-sexp (&optional arg)
2053 "Try and do a `forward-sexp', but do not error.
2054 Return new point if successful, nil if an error occurred."
2055 (condition-case nil
2056 (progn
2057 (forward-sexp (or arg 1))
2058 (point)) ;; return point if successful
2059 (error
2060 (sh-debug "oops!(1) %d" (point))
2061 nil))) ;; return nil if fail
2063 (defun sh-goto-match-for-done ()
2064 (let ((found (sh-find-prev-matching sh-regexp-for-done sh-re-done 1)))
2065 (if found
2066 (goto-char found))))
2068 (defun sh-handle-this-done ()
2069 (if (sh-goto-match-for-done)
2070 (list "aligned to do stmt" '(+ sh-indent-for-done))))
2072 (defun sh-handle-prev-done ()
2073 (if (sh-goto-match-for-done)
2074 (list "previous done")))
2076 (defun sh-handle-this-do ()
2077 (if (sh-goto-match-for-done)
2078 (list '(+ sh-indent-for-do))))
2080 (defun sh-handle-prev-do ()
2081 (cond
2082 ((save-restriction
2083 (narrow-to-region (point) (line-beginning-position))
2084 (sh-goto-match-for-done))
2085 (sh-debug "match for done found on THIS line")
2086 (list '(+ sh-indent-after-loop-construct)))
2087 ((sh-goto-match-for-done)
2088 (sh-debug "match for done found on PREV line")
2089 (list '(+ sh-indent-after-do)))
2091 (message "match for done NOT found")
2092 nil)))
2094 ;; for rc:
2095 (defun sh-find-prev-switch ()
2096 "Find the line for the switch keyword matching this line's case keyword."
2097 (re-search-backward "\\<switch\\>" nil t))
2099 (defun sh-handle-this-rc-case ()
2100 (if (sh-find-prev-switch)
2101 (list '(+ sh-indent-after-switch))
2102 ;; (list '(+ sh-indent-for-case-label))
2103 nil))
2105 (defun sh-handle-prev-rc-case ()
2106 (list '(+ sh-indent-after-case)))
2108 (defun sh-check-rule (n thing)
2109 (let ((rule (nth n (assoc thing sh-kw-alist)))
2110 (val nil))
2111 (if rule
2112 (progn
2113 (setq val (funcall rule))
2114 (sh-debug "rule (%d) for %s at %d is %s\n-> returned %s"
2115 n thing (point) rule val)))
2116 val))
2119 (defun sh-get-indent-info ()
2120 "Return indent-info for this line.
2121 This is a list. nil means the line is to be left as is.
2122 Otherwise it contains one or more of the following sublists:
2123 \(t NUMBER\) NUMBER is the base location in the buffer that indentation is
2124 relative to. If present, this is always the first of the
2125 sublists. The indentation of the line in question is
2126 derived from the indentation of this point, possibly
2127 modified by subsequent sublists.
2128 \(+ VAR\)
2129 \(- VAR\) Get the value of variable VAR and add to or subtract from
2130 the indentation calculated so far.
2131 \(= VAR\) Get the value of variable VAR and *replace* the
2132 indentation with its value. This only occurs for
2133 special variables such as `sh-indent-comment'.
2134 STRING This is ignored for the purposes of calculating
2135 indentation, it is printed in certain cases to help show
2136 what the indentation is based on."
2137 ;; See comments before `sh-kw'.
2138 (save-excursion
2139 (let ((have-result nil)
2140 this-kw
2141 start
2143 (result nil)
2144 (align-point nil)
2145 prev-line-end x)
2146 (beginning-of-line)
2147 ;; Note: setting result to t means we are done and will return nil.
2148 ;;(This function never returns just t.)
2149 (cond
2150 ((or (nth 3 (syntax-ppss (point)))
2151 (eq (get-text-property (point) 'face) sh-heredoc-face))
2152 ;; String continuation -- don't indent
2153 (setq result t)
2154 (setq have-result t))
2155 ((looking-at "\\s-*#") ; was (equal this-kw "#")
2156 (if (bobp)
2157 (setq result t) ;; return nil if 1st line!
2158 (setq result (list '(= sh-indent-comment)))
2159 ;; we still need to get previous line in case
2160 ;; sh-indent-comment is t (indent as normal)
2161 (setq align-point (sh-prev-line nil))
2162 (setq have-result nil)
2164 ) ;; cond
2166 (unless have-result
2167 ;; Continuation lines are handled specially
2168 (if (sh-this-is-a-continuation)
2169 (progn
2170 (setq result
2171 (if (save-excursion
2172 (beginning-of-line)
2173 (not (memq (char-before (- (point) 2)) '(?\s ?\t))))
2174 ;; By convention, if the continuation \ is not
2175 ;; preceded by a SPC or a TAB it means that the line
2176 ;; is cut at a place where spaces cannot be freely
2177 ;; added/removed. I.e. do not indent the line.
2178 (list '(= nil))
2179 ;; We assume the line being continued is already
2180 ;; properly indented...
2181 ;; (setq prev-line-end (sh-prev-line))
2182 (setq align-point (sh-prev-line nil))
2183 (list '(+ sh-indent-for-continuation))))
2184 (setq have-result t))
2185 (beginning-of-line)
2186 (skip-chars-forward " \t")
2187 (setq this-kw (sh-get-kw)))
2189 ;; Handle "this" keyword: first word on the line we're
2190 ;; calculating indentation info for.
2191 (if this-kw
2192 (if (setq val (sh-check-rule 1 this-kw))
2193 (progn
2194 (setq align-point (point))
2195 (sh-debug
2196 "this - setting align-point to %d" align-point)
2197 (setq result (append result val))
2198 (setq have-result t)
2199 ;; set prev-line to continue processing remainder
2200 ;; of this line as a previous line
2201 (setq prev-line-end (point))
2202 ))))
2204 (unless have-result
2205 (setq prev-line-end (sh-prev-line 'end)))
2207 (if prev-line-end
2208 (save-excursion
2209 ;; We start off at beginning of this line.
2210 ;; Scan previous statements while this is <=
2211 ;; start of previous line.
2212 (setq start (point)) ;; for debug only
2213 (goto-char prev-line-end)
2214 (setq x t)
2215 (while (and x (setq x (sh-prev-thing)))
2216 (sh-debug "at %d x is: %s result is: %s" (point) x result)
2217 (cond
2218 ((and (equal x ")")
2219 (equal (get-text-property (1- (point)) 'syntax-table)
2220 sh-st-punc))
2221 (sh-debug "Case label) here")
2222 (setq x 'case-label)
2223 (if (setq val (sh-check-rule 2 x))
2224 (progn
2225 (setq result (append result val))
2226 (setq align-point (point))))
2227 (or (bobp)
2228 (forward-char -1))
2229 ;; FIXME: This charset looks too much like a regexp. --Stef
2230 (skip-chars-forward "[a-z0-9]*?")
2232 ((string-match "[])}]" x)
2233 (setq x (sh-safe-forward-sexp -1))
2234 (if x
2235 (progn
2236 (setq align-point (point))
2237 (setq result (append result
2238 (list "aligned to opening paren")))
2240 ((string-match "[[({]" x)
2241 (sh-debug "Checking special thing: %s" x)
2242 (if (setq val (sh-check-rule 2 x))
2243 (setq result (append result val)))
2244 (forward-char -1)
2245 (setq align-point (point)))
2246 ((string-match "[\"'`]" x)
2247 (sh-debug "Skipping back for %s" x)
2248 ;; this was oops-2
2249 (setq x (sh-safe-forward-sexp -1)))
2250 ((stringp x)
2251 (sh-debug "Checking string %s at %s" x (point))
2252 (if (setq val (sh-check-rule 2 x))
2253 ;; (or (eq t (car val))
2254 ;; (eq t (car (car val))))
2255 (setq result (append result val)))
2256 ;; not sure about this test Wed Jan 27 23:48:35 1999
2257 (setq align-point (point))
2258 (unless (bolp)
2259 (forward-char -1)))
2261 (error "Don't know what to do with %s" x))
2263 ) ;; while
2264 (sh-debug "result is %s" result)
2266 (sh-debug "No prev line!")
2267 (sh-debug "result: %s align-point: %s" result align-point)
2270 (if align-point
2271 ;; was: (setq result (append result (list (list t align-point))))
2272 (setq result (append (list (list t align-point)) result))
2274 (sh-debug "result is now: %s" result)
2276 (or result
2277 (setq result (list (if prev-line-end
2278 (list t prev-line-end)
2279 (list '= 'sh-first-lines-indent)))))
2281 (if (eq result t)
2282 (setq result nil))
2283 (sh-debug "result is: %s" result)
2284 result
2285 ) ;; let
2289 (defun sh-get-indent-var-for-line (&optional info)
2290 "Return the variable controlling indentation for this line.
2291 If there is not [just] one such variable, return a string
2292 indicating the problem.
2293 If INFO is supplied it is used, else it is calculated."
2294 (let ((var nil)
2295 (result nil)
2296 (reason nil)
2297 sym elt)
2298 (or info
2299 (setq info (sh-get-indent-info)))
2300 (if (null info)
2301 (setq result "this line to be left as is")
2302 (while (and info (null result))
2303 (setq elt (car info))
2304 (cond
2305 ((stringp elt)
2306 (setq reason elt)
2308 ((not (listp elt))
2309 (error "sh-get-indent-var-for-line invalid elt: %s" elt))
2310 ;; so it is a list
2311 ((eq t (car elt))
2312 ) ;; nothing
2313 ((symbolp (setq sym (nth 1 elt)))
2314 ;; A bit of a kludge - when we see the sh-indent-comment
2315 ;; ignore other variables. Otherwise it is tricky to
2316 ;; "learn" the comment indentation.
2317 (if (eq var 'sh-indent-comment)
2318 (setq result var)
2319 (if var
2320 (setq result
2321 "this line is controlled by more than 1 variable.")
2322 (setq var sym))))
2324 (error "sh-get-indent-var-for-line invalid list elt: %s" elt)))
2325 (setq info (cdr info))
2327 (or result
2328 (setq result var))
2329 (or result
2330 (setq result reason))
2331 (if (null result)
2332 ;; e.g. just had (t POS)
2333 (setq result "line has default indentation"))
2334 result))
2338 ;; Finding the previous line isn't trivial.
2339 ;; We must *always* go back one more and see if that is a continuation
2340 ;; line -- it is the PREVIOUS line which is continued, not the one
2341 ;; we are going to!
2342 ;; Also, we want to treat a whole "here document" as one big line,
2343 ;; because we may want to a align to the beginning of it.
2345 ;; What we do:
2346 ;; - go back to previous non-empty line
2347 ;; - if this is in a here-document, go to the beginning of it
2348 ;; - while previous line is continued, go back one line
2349 (defun sh-prev-line (&optional end)
2350 "Back to end of previous non-comment non-empty line.
2351 Go to beginning of logical line unless END is non-nil, in which case
2352 we go to the end of the previous line and do not check for continuations."
2353 (save-excursion
2354 (beginning-of-line)
2355 (forward-comment (- (point-max)))
2356 (unless end (beginning-of-line))
2357 (when (and (not (bobp))
2358 (equal (get-text-property (1- (point)) 'face)
2359 sh-heredoc-face))
2360 (let ((p1 (previous-single-property-change (1- (point)) 'face)))
2361 (when p1
2362 (goto-char p1)
2363 (if end
2364 (end-of-line)
2365 (beginning-of-line)))))
2366 (unless end
2367 ;; we must check previous lines to see if they are continuation lines
2368 ;; if so, we must return position of first of them
2369 (while (and (sh-this-is-a-continuation)
2370 (>= 0 (forward-line -1))))
2371 (beginning-of-line)
2372 (skip-chars-forward " \t"))
2373 (point)))
2376 (defun sh-prev-stmt ()
2377 "Return the address of the previous stmt or nil."
2378 ;; This is used when we are trying to find a matching keyword.
2379 ;; Searching backward for the keyword would certainly be quicker, but
2380 ;; it is hard to remove "false matches" -- such as if the keyword
2381 ;; appears in a string or quote. This way is slower, but (I think) safer.
2382 (interactive)
2383 (save-excursion
2384 (let ((going t)
2385 (start (point))
2386 (found nil)
2387 (prev nil))
2388 (skip-chars-backward " \t;|&({[")
2389 (while (and (not found)
2390 (not (bobp))
2391 going)
2392 ;; Do a backward-sexp if possible, else backup bit by bit...
2393 (if (sh-safe-forward-sexp -1)
2394 (progn
2395 (if (looking-at sh-special-keywords)
2396 (progn
2397 (setq found prev))
2398 (setq prev (point))
2400 ;; backward-sexp failed
2401 (if (zerop (skip-chars-backward " \t()[\]{};`'"))
2402 (forward-char -1))
2403 (if (bolp)
2404 (let ((back (sh-prev-line nil)))
2405 (if back
2406 (goto-char back)
2407 (setq going nil)))))
2408 (unless found
2409 (skip-chars-backward " \t")
2410 (if (or (and (bolp) (not (sh-this-is-a-continuation)))
2411 (eq (char-before) ?\;)
2412 (looking-at "\\s-*[|&]"))
2413 (setq found (point)))))
2414 (if found
2415 (goto-char found))
2416 (if found
2417 (progn
2418 (skip-chars-forward " \t|&({[")
2419 (setq found (point))))
2420 (if (>= (point) start)
2421 (progn
2422 (debug "We didn't move!")
2423 (setq found nil))
2424 (or found
2425 (sh-debug "Did not find prev stmt.")))
2426 found)))
2429 (defun sh-get-word ()
2430 "Get a shell word skipping whitespace from point."
2431 (interactive)
2432 (skip-chars-forward "\t ")
2433 (let ((start (point)))
2434 (while
2435 (if (looking-at "[\"'`]")
2436 (sh-safe-forward-sexp)
2437 ;; (> (skip-chars-forward "^ \t\n\"'`") 0)
2438 (> (skip-chars-forward "-_$[:alnum:]") 0)
2440 (buffer-substring start (point))
2443 (defun sh-prev-thing ()
2444 "Return the previous thing this logical line."
2445 ;; This is called when `sh-get-indent-info' is working backwards on
2446 ;; the previous line(s) finding what keywords may be relevant for
2447 ;; indenting. It moves over sexps if possible, and will stop
2448 ;; on a ; and at the beginning of a line if it is not a continuation
2449 ;; line.
2451 ;; Added a kludge for ";;"
2452 ;; Possible return values:
2453 ;; nil - nothing
2454 ;; a string - possibly a keyword
2456 (if (bolp)
2458 (let ((start (point))
2459 (min-point (if (sh-this-is-a-continuation)
2460 (sh-prev-line nil)
2461 (line-beginning-position))))
2462 (skip-chars-backward " \t;" min-point)
2463 (if (looking-at "\\s-*;[;&]")
2464 ;; (message "Found ;; !")
2465 ";;"
2466 (skip-chars-backward "^)}];\"'`({[" min-point)
2467 (let ((c (if (> (point) min-point) (char-before))))
2468 (sh-debug "stopping at %d c is %s start=%d min-point=%d"
2469 (point) c start min-point)
2470 (if (not (memq c '(?\n nil ?\;)))
2471 ;; c -- return a string
2472 (char-to-string c)
2473 ;; Return the leading keyword of the "command" we supposedly
2474 ;; skipped over. Maybe we skipped too far (e.g. past a `do' or
2475 ;; `then' that precedes the actual command), so check whether
2476 ;; we're looking at such a keyword and if so, move back forward.
2477 (let ((boundary (point))
2478 kwd next)
2479 (while
2480 (progn
2481 ;; Skip forward over white space newline and \ at eol.
2482 (skip-chars-forward " \t\n\\\\" start)
2483 (if (>= (point) start)
2484 (progn
2485 (sh-debug "point: %d >= start: %d" (point) start)
2486 nil)
2487 (if next (setq boundary next))
2488 (sh-debug "Now at %d start=%d" (point) start)
2489 (setq kwd (sh-get-word))
2490 (if (member kwd (sh-feature sh-leading-keywords))
2491 (progn
2492 (setq next (point))
2494 nil))))
2495 (goto-char boundary)
2496 kwd)))))))
2499 (defun sh-this-is-a-continuation ()
2500 "Return non-nil if current line is a continuation of previous line."
2501 (save-excursion
2502 (and (zerop (forward-line -1))
2503 (looking-at ".*\\\\$")
2504 (not (nth 4 (parse-partial-sexp (match-beginning 0) (match-end 0)
2505 nil nil nil t))))))
2507 (defun sh-get-kw (&optional where and-move)
2508 "Return first word of line from WHERE.
2509 If AND-MOVE is non-nil then move to end of word."
2510 (let ((start (point)))
2511 (if where
2512 (goto-char where))
2513 (prog1
2514 (buffer-substring (point)
2515 (progn (skip-chars-forward "^ \t\n;&|")(point)))
2516 (unless and-move
2517 (goto-char start)))))
2519 (defun sh-find-prev-matching (open close &optional depth)
2520 "Find a matching token for a set of opening and closing keywords.
2521 This takes into account that there may be nested open..close pairings.
2522 OPEN and CLOSE are regexps denoting the tokens to be matched.
2523 Optional parameter DEPTH (usually 1) says how many to look for."
2524 (let ((parse-sexp-ignore-comments t)
2525 prev)
2526 (setq depth (or depth 1))
2527 (save-excursion
2528 (condition-case nil
2529 (while (and
2530 (/= 0 depth)
2531 (not (bobp))
2532 (setq prev (sh-prev-stmt)))
2533 (goto-char prev)
2534 (save-excursion
2535 (if (looking-at "\\\\\n")
2536 (progn
2537 (forward-char 2)
2538 (skip-chars-forward " \t")))
2539 (cond
2540 ((looking-at open)
2541 (setq depth (1- depth))
2542 (sh-debug "found open at %d - depth = %d" (point) depth))
2543 ((looking-at close)
2544 (setq depth (1+ depth))
2545 (sh-debug "found close - depth = %d" depth))
2547 ))))
2548 (error nil))
2549 (if (eq depth 0)
2550 prev ;; (point)
2551 nil)
2555 (defun sh-var-value (var &optional ignore-error)
2556 "Return the value of variable VAR, interpreting symbols.
2557 It can also return t or nil.
2558 If an invalid value is found, throw an error unless Optional argument
2559 IGNORE-ERROR is non-nil."
2560 (let ((val (symbol-value var)))
2561 (cond
2562 ((numberp val)
2563 val)
2564 ((eq val t)
2565 val)
2566 ((null val)
2567 val)
2568 ((eq val '+)
2569 sh-basic-offset)
2570 ((eq val '-)
2571 (- sh-basic-offset))
2572 ((eq val '++)
2573 (* 2 sh-basic-offset))
2574 ((eq val '--)
2575 (* 2 (- sh-basic-offset)))
2576 ((eq val '*)
2577 (/ sh-basic-offset 2))
2578 ((eq val '/)
2579 (/ (- sh-basic-offset) 2))
2581 (if ignore-error
2582 (progn
2583 (message "Don't know how to handle %s's value of %s" var val)
2585 (error "Don't know how to handle %s's value of %s" var val))
2586 ))))
2588 (defun sh-set-var-value (var value &optional no-symbol)
2589 "Set variable VAR to VALUE.
2590 Unless optional argument NO-SYMBOL is non-nil, then if VALUE is
2591 can be represented by a symbol then do so."
2592 (cond
2593 (no-symbol
2594 (set var value))
2595 ((= value sh-basic-offset)
2596 (set var '+))
2597 ((= value (- sh-basic-offset))
2598 (set var '-))
2599 ((eq value (* 2 sh-basic-offset))
2600 (set var '++))
2601 ((eq value (* 2 (- sh-basic-offset)))
2602 (set var '--))
2603 ((eq value (/ sh-basic-offset 2))
2604 (set var '*))
2605 ((eq value (/ (- sh-basic-offset) 2))
2606 (set var '/))
2608 (set var value)))
2612 (defun sh-calculate-indent (&optional info)
2613 "Return the indentation for the current line.
2614 If INFO is supplied it is used, else it is calculated from current line."
2615 (let ((ofs 0)
2616 (base-value 0)
2617 elt a b var val)
2618 (or info
2619 (setq info (sh-get-indent-info)))
2620 (when info
2621 (while info
2622 (sh-debug "info: %s ofs=%s" info ofs)
2623 (setq elt (car info))
2624 (cond
2625 ((stringp elt)) ;; do nothing?
2626 ((listp elt)
2627 (setq a (car (car info)))
2628 (setq b (nth 1 (car info)))
2629 (cond
2630 ((eq a t)
2631 (save-excursion
2632 (goto-char b)
2633 (setq val (current-indentation)))
2634 (setq base-value val))
2635 ((symbolp b)
2636 (setq val (sh-var-value b))
2637 (cond
2638 ((eq a '=)
2639 (cond
2640 ((null val)
2641 ;; no indentation
2642 ;; set info to nil so we stop immediately
2643 (setq base-value nil ofs nil info nil))
2644 ((eq val t) (setq ofs 0)) ;; indent as normal line
2646 ;; The following assume the (t POS) come first!
2647 (setq ofs val base-value 0)
2648 (setq info nil)))) ;; ? stop now
2649 ((eq a '+) (setq ofs (+ ofs val)))
2650 ((eq a '-) (setq ofs (- ofs val)))
2652 (error "sh-calculate-indent invalid a a=%s b=%s" a b))))
2654 (error "sh-calculate-indent invalid elt: a=%s b=%s" a b))))
2656 (error "sh-calculate-indent invalid elt %s" elt)))
2657 (sh-debug "a=%s b=%s val=%s base-value=%s ofs=%s"
2658 a b val base-value ofs)
2659 (setq info (cdr info)))
2660 ;; return value:
2661 (sh-debug "at end: base-value: %s ofs: %s" base-value ofs)
2663 (cond
2664 ((or (null base-value)(null ofs))
2665 nil)
2666 ((and (numberp base-value)(numberp ofs))
2667 (sh-debug "base (%d) + ofs (%d) = %d"
2668 base-value ofs (+ base-value ofs))
2669 (+ base-value ofs)) ;; return value
2671 (error "sh-calculate-indent: Help. base-value=%s ofs=%s"
2672 base-value ofs)
2673 nil)))))
2676 (defun sh-indent-line ()
2677 "Indent the current line."
2678 (interactive)
2679 (let ((indent (sh-calculate-indent))
2680 (pos (- (point-max) (point))))
2681 (when indent
2682 (beginning-of-line)
2683 (skip-chars-forward " \t")
2684 (indent-line-to indent)
2685 ;; If initial point was within line's indentation,
2686 ;; position after the indentation. Else stay at same point in text.
2687 (if (> (- (point-max) pos) (point))
2688 (goto-char (- (point-max) pos))))))
2691 (defun sh-blink (blinkpos &optional msg)
2692 "Move cursor momentarily to BLINKPOS and display MSG."
2693 ;; We can get here without it being a number on first line
2694 (if (numberp blinkpos)
2695 (save-excursion
2696 (goto-char blinkpos)
2697 (if msg (message "%s" msg) (message nil))
2698 (sit-for blink-matching-delay))
2699 (if msg (message "%s" msg) (message nil))))
2701 (defun sh-show-indent (arg)
2702 "Show the how the current line would be indented.
2703 This tells you which variable, if any, controls the indentation of
2704 this line.
2705 If optional arg ARG is non-null (called interactively with a prefix),
2706 a pop up window describes this variable.
2707 If variable `sh-blink' is non-nil then momentarily go to the line
2708 we are indenting relative to, if applicable."
2709 (interactive "P")
2710 (sh-must-support-indent)
2711 (let* ((info (sh-get-indent-info))
2712 (var (sh-get-indent-var-for-line info))
2713 (curr-indent (current-indentation))
2714 val msg)
2715 (if (stringp var)
2716 (message "%s" (setq msg var))
2717 (setq val (sh-calculate-indent info))
2719 (if (eq curr-indent val)
2720 (setq msg (format "%s is %s" var (symbol-value var)))
2721 (setq msg
2722 (if val
2723 (format "%s (%s) would change indent from %d to: %d"
2724 var (symbol-value var) curr-indent val)
2725 (format "%s (%s) would leave line as is"
2726 var (symbol-value var)))
2728 (if (and arg var)
2729 (describe-variable var)))
2730 (if sh-blink
2731 (let ((info (sh-get-indent-info)))
2732 (if (and info (listp (car info))
2733 (eq (car (car info)) t))
2734 (sh-blink (nth 1 (car info)) msg)
2735 (message "%s" msg)))
2736 (message "%s" msg))
2739 (defun sh-set-indent ()
2740 "Set the indentation for the current line.
2741 If the current line is controlled by an indentation variable, prompt
2742 for a new value for it."
2743 (interactive)
2744 (sh-must-support-indent)
2745 (let* ((info (sh-get-indent-info))
2746 (var (sh-get-indent-var-for-line info))
2747 val old-val indent-val)
2748 (if (stringp var)
2749 (message "Cannot set indent - %s" var)
2750 (setq old-val (symbol-value var))
2751 (setq val (sh-read-variable var))
2752 (condition-case nil
2753 (progn
2754 (set var val)
2755 (setq indent-val (sh-calculate-indent info))
2756 (if indent-val
2757 (message "Variable: %s Value: %s would indent to: %d"
2758 var (symbol-value var) indent-val)
2759 (message "Variable: %s Value: %s would leave line as is."
2760 var (symbol-value var)))
2761 ;; I'm not sure about this, indenting it now?
2762 ;; No. Because it would give the impression that an undo would
2763 ;; restore thing, but the value has been altered.
2764 ;; (sh-indent-line)
2766 (error
2767 (set var old-val)
2768 (message "Bad value for %s, restoring to previous value %s"
2769 var old-val)
2770 (sit-for 1)
2771 nil))
2775 (defun sh-learn-line-indent (arg)
2776 "Learn how to indent a line as it currently is indented.
2778 If there is an indentation variable which controls this line's indentation,
2779 then set it to a value which would indent the line the way it
2780 presently is.
2782 If the value can be represented by one of the symbols then do so
2783 unless optional argument ARG (the prefix when interactive) is non-nil."
2784 (interactive "*P")
2785 (sh-must-support-indent)
2786 ;; I'm not sure if we show allow learning on an empty line.
2787 ;; Though it might occasionally be useful I think it usually
2788 ;; would just be confusing.
2789 (if (save-excursion
2790 (beginning-of-line)
2791 (looking-at "\\s-*$"))
2792 (message "sh-learn-line-indent ignores empty lines.")
2793 (let* ((info (sh-get-indent-info))
2794 (var (sh-get-indent-var-for-line info))
2795 ival sval diff new-val
2796 (no-symbol arg)
2797 (curr-indent (current-indentation)))
2798 (cond
2799 ((stringp var)
2800 (message "Cannot learn line - %s" var))
2801 ((eq var 'sh-indent-comment)
2802 ;; This is arbitrary...
2803 ;; - if curr-indent is 0, set to curr-indent
2804 ;; - else if it has the indentation of a "normal" line,
2805 ;; then set to t
2806 ;; - else set to curr-indent.
2807 (setq sh-indent-comment
2808 (if (= curr-indent 0)
2810 (let* ((sh-indent-comment t)
2811 (val2 (sh-calculate-indent info)))
2812 (if (= val2 curr-indent)
2814 curr-indent))))
2815 (message "%s set to %s" var (symbol-value var))
2817 ((numberp (setq sval (sh-var-value var)))
2818 (setq ival (sh-calculate-indent info))
2819 (setq diff (- curr-indent ival))
2821 (sh-debug "curr-indent: %d ival: %d diff: %d var:%s sval %s"
2822 curr-indent ival diff var sval)
2823 (setq new-val (+ sval diff))
2824 ;;; I commented out this because someone might want to replace
2825 ;;; a value of `+' with the current value of sh-basic-offset
2826 ;;; or vice-versa.
2827 ;;; (if (= 0 diff)
2828 ;;; (message "No change needed!")
2829 (sh-set-var-value var new-val no-symbol)
2830 (message "%s set to %s" var (symbol-value var))
2833 (debug)
2834 (message "Cannot change %s" var))))))
2838 (defun sh-mark-init (buffer)
2839 "Initialize a BUFFER to be used by `sh-mark-line'."
2840 (with-current-buffer (get-buffer-create buffer)
2841 (erase-buffer)
2842 (occur-mode)))
2845 (defun sh-mark-line (message point buffer &optional add-linenum occur-point)
2846 "Insert MESSAGE referring to location POINT in current buffer into BUFFER.
2847 Buffer BUFFER is in `occur-mode'.
2848 If ADD-LINENUM is non-nil the message is preceded by the line number.
2849 If OCCUR-POINT is non-nil then the line is marked as a new occurrence
2850 so that `occur-next' and `occur-prev' will work."
2851 (let ((m1 (make-marker))
2852 start
2853 (line ""))
2854 (when point
2855 (set-marker m1 point (current-buffer))
2856 (if add-linenum
2857 (setq line (format "%d: " (1+ (count-lines 1 point))))))
2858 (save-excursion
2859 (if (get-buffer buffer)
2860 (set-buffer (get-buffer buffer))
2861 (set-buffer (get-buffer-create buffer))
2862 (occur-mode)
2864 (goto-char (point-max))
2865 (setq start (point))
2866 (insert line)
2867 (if occur-point
2868 (setq occur-point (point)))
2869 (insert message)
2870 (if point
2871 (add-text-properties
2872 start (point)
2873 '(mouse-face highlight
2874 help-echo "mouse-2: go to the line where I learned this")))
2875 (insert "\n")
2876 (if point
2877 (progn
2878 (put-text-property start (point) 'occur-target m1)
2879 (if occur-point
2880 (put-text-property start occur-point
2881 'occur-match t))
2887 ;; Is this really worth having?
2888 (defvar sh-learned-buffer-hook nil
2889 "*An abnormal hook, called with an alist of learned variables.")
2890 ;; Example of how to use sh-learned-buffer-hook
2892 ;; (defun what-i-learned (list)
2893 ;; (let ((p list))
2894 ;; (with-current-buffer "*scratch*"
2895 ;; (goto-char (point-max))
2896 ;; (insert "(setq\n")
2897 ;; (while p
2898 ;; (insert (format " %s %s \n"
2899 ;; (nth 0 (car p)) (nth 1 (car p))))
2900 ;; (setq p (cdr p)))
2901 ;; (insert ")\n")
2902 ;; )))
2904 ;; (add-hook 'sh-learned-buffer-hook 'what-i-learned)
2907 ;; Originally this was sh-learn-region-indent (beg end)
2908 ;; However, in practice this was awkward so I changed it to
2909 ;; use the whole buffer. Use narrowing if needbe.
2910 (defun sh-learn-buffer-indent (&optional arg)
2911 "Learn how to indent the buffer the way it currently is.
2913 Output in buffer \"*indent*\" shows any lines which have conflicting
2914 values of a variable, and the final value of all variables learned.
2915 When called interactively, pop to this buffer automatically if
2916 there are any discrepancies.
2918 If no prefix ARG is given, then variables are set to numbers.
2919 If a prefix arg is given, then variables are set to symbols when
2920 applicable -- e.g. to symbol `+' if the value is that of the
2921 basic indent.
2922 If a positive numerical prefix is given, then `sh-basic-offset'
2923 is set to the prefix's numerical value.
2924 Otherwise, sh-basic-offset may or may not be changed, according
2925 to the value of variable `sh-learn-basic-offset'.
2927 Abnormal hook `sh-learned-buffer-hook' if non-nil is called when the
2928 function completes. The function is abnormal because it is called
2929 with an alist of variables learned. This feature may be changed or
2930 removed in the future.
2932 This command can often take a long time to run."
2933 (interactive "P")
2934 (sh-must-support-indent)
2935 (save-excursion
2936 (goto-char (point-min))
2937 (let ((learned-var-list nil)
2938 (out-buffer "*indent*")
2939 (num-diffs 0)
2940 previous-set-info
2941 (max 17)
2944 (comment-col nil) ;; number if all same, t if seen diff values
2945 (comments-always-default t) ;; nil if we see one not default
2946 initial-msg
2947 (specified-basic-offset (and arg (numberp arg)
2948 (> arg 0)))
2949 (linenum 0)
2950 suggested)
2951 (setq vec (make-vector max 0))
2952 (sh-mark-init out-buffer)
2954 (if specified-basic-offset
2955 (progn
2956 (setq sh-basic-offset arg)
2957 (setq initial-msg
2958 (format "Using specified sh-basic-offset of %d"
2959 sh-basic-offset)))
2960 (setq initial-msg
2961 (format "Initial value of sh-basic-offset: %s"
2962 sh-basic-offset)))
2964 (while (< (point) (point-max))
2965 (setq linenum (1+ linenum))
2966 ;; (if (zerop (% linenum 10))
2967 (message "line %d" linenum)
2968 ;; )
2969 (unless (looking-at "\\s-*$") ;; ignore empty lines!
2970 (let* ((sh-indent-comment t) ;; info must return default indent
2971 (info (sh-get-indent-info))
2972 (var (sh-get-indent-var-for-line info))
2973 sval ival diff new-val
2974 (curr-indent (current-indentation)))
2975 (cond
2976 ((null var)
2977 nil)
2978 ((stringp var)
2979 nil)
2980 ((numberp (setq sval (sh-var-value var 'no-error)))
2981 ;; the numberp excludes comments since sval will be t.
2982 (setq ival (sh-calculate-indent))
2983 (setq diff (- curr-indent ival))
2984 (setq new-val (+ sval diff))
2985 (sh-set-var-value var new-val 'no-symbol)
2986 (unless (looking-at "\\s-*#") ;; don't learn from comments
2987 (if (setq previous-set-info (assoc var learned-var-list))
2988 (progn
2989 ;; it was already there, is it same value ?
2990 (unless (eq (symbol-value var)
2991 (nth 1 previous-set-info))
2992 (sh-mark-line
2993 (format "Variable %s was set to %s"
2994 var (symbol-value var))
2995 (point) out-buffer t t)
2996 (sh-mark-line
2997 (format " but was previously set to %s"
2998 (nth 1 previous-set-info))
2999 (nth 2 previous-set-info) out-buffer t)
3000 (setq num-diffs (1+ num-diffs))
3001 ;; (delete previous-set-info learned-var-list)
3002 (setcdr previous-set-info
3003 (list (symbol-value var) (point)))
3006 (setq learned-var-list
3007 (append (list (list var (symbol-value var)
3008 (point)))
3009 learned-var-list)))
3010 (if (numberp new-val)
3011 (progn
3012 (sh-debug
3013 "This line's indent value: %d" new-val)
3014 (if (< new-val 0)
3015 (setq new-val (- new-val)))
3016 (if (< new-val max)
3017 (aset vec new-val (1+ (aref vec new-val))))))
3019 ((eq var 'sh-indent-comment)
3020 (unless (= curr-indent (sh-calculate-indent info))
3021 ;; this is not the default indentation
3022 (setq comments-always-default nil)
3023 (if comment-col ;; then we have see one before
3024 (or (eq comment-col curr-indent)
3025 (setq comment-col t)) ;; seen a different one
3026 (setq comment-col curr-indent))
3029 (sh-debug "Cannot learn this line!!!")
3031 (sh-debug
3032 "at %s learned-var-list is %s" (point) learned-var-list)
3034 (forward-line 1)
3035 ) ;; while
3036 (if sh-debug
3037 (progn
3038 (setq msg (format
3039 "comment-col = %s comments-always-default = %s"
3040 comment-col comments-always-default))
3041 ;; (message msg)
3042 (sh-mark-line msg nil out-buffer)))
3043 (cond
3044 ((eq comment-col 0)
3045 (setq msg "\nComments are all in 1st column.\n"))
3046 (comments-always-default
3047 (setq msg "\nComments follow default indentation.\n")
3048 (setq comment-col t))
3049 ((numberp comment-col)
3050 (setq msg (format "\nComments are in col %d." comment-col)))
3052 (setq msg "\nComments seem to be mixed, leaving them as is.\n")
3053 (setq comment-col nil)
3055 (sh-debug msg)
3056 (sh-mark-line msg nil out-buffer)
3058 (sh-mark-line initial-msg nil out-buffer t t)
3060 (setq suggested (sh-guess-basic-offset vec))
3062 (if (and suggested (not specified-basic-offset))
3063 (let ((new-value
3064 (cond
3065 ;; t => set it if we have a single value as a number
3066 ((and (eq sh-learn-basic-offset t) (numberp suggested))
3067 suggested)
3068 ;; other non-nil => set it if only one value was found
3069 (sh-learn-basic-offset
3070 (if (numberp suggested)
3071 suggested
3072 (if (= (length suggested) 1)
3073 (car suggested))))
3075 nil))))
3076 (if new-value
3077 (progn
3078 (setq learned-var-list
3079 (append (list (list 'sh-basic-offset
3080 (setq sh-basic-offset new-value)
3081 (point-max)))
3082 learned-var-list))
3083 ;; Not sure if we need to put this line in, since
3084 ;; it will appear in the "Learned variable settings".
3085 (sh-mark-line
3086 (format "Changed sh-basic-offset to: %d" sh-basic-offset)
3087 nil out-buffer))
3088 (sh-mark-line
3089 (if (listp suggested)
3090 (format "Possible value(s) for sh-basic-offset: %s"
3091 (mapconcat 'int-to-string suggested " "))
3092 (format "Suggested sh-basic-offset: %d" suggested))
3093 nil out-buffer))))
3096 (setq learned-var-list
3097 (append (list (list 'sh-indent-comment comment-col (point-max)))
3098 learned-var-list))
3099 (setq sh-indent-comment comment-col)
3100 (let ((name (buffer-name)))
3101 (sh-mark-line "\nLearned variable settings:" nil out-buffer)
3102 (if arg
3103 ;; Set learned variables to symbolic rather than numeric
3104 ;; values where possible.
3105 (dolist (learned-var (reverse learned-var-list))
3106 (let ((var (car learned-var))
3107 (val (nth 1 learned-var)))
3108 (when (and (not (eq var 'sh-basic-offset))
3109 (numberp val))
3110 (sh-set-var-value var val)))))
3111 (dolist (learned-var (reverse learned-var-list))
3112 (let ((var (car learned-var)))
3113 (sh-mark-line (format " %s %s" var (symbol-value var))
3114 (nth 2 learned-var) out-buffer)))
3115 (with-current-buffer out-buffer
3116 (goto-char (point-min))
3117 (insert
3118 (format "Indentation values for buffer %s.\n" name)
3119 (format "%d indentation variable%s different values%s\n\n"
3120 num-diffs
3121 (if (= num-diffs 1)
3122 " has" "s have")
3123 (if (zerop num-diffs)
3124 "." ":"))
3126 ;; Are abnormal hooks considered bad form?
3127 (run-hook-with-args 'sh-learned-buffer-hook learned-var-list)
3128 (and (called-interactively-p 'any)
3129 (or sh-popup-occur-buffer (> num-diffs 0))
3130 (pop-to-buffer out-buffer)))))
3132 (defun sh-guess-basic-offset (vec)
3133 "See if we can determine a reasonable value for `sh-basic-offset'.
3134 This is experimental, heuristic and arbitrary!
3135 Argument VEC is a vector of information collected by
3136 `sh-learn-buffer-indent'.
3137 Return values:
3138 number - there appears to be a good single value
3139 list of numbers - no obvious one, here is a list of one or more
3140 reasonable choices
3141 nil - we couldn't find a reasonable one."
3142 (let* ((max (1- (length vec)))
3143 (i 1)
3144 (totals (make-vector max 0)))
3145 (while (< i max)
3146 (aset totals i (+ (aref totals i) (* 4 (aref vec i))))
3147 (if (zerop (% i 2))
3148 (aset totals i (+ (aref totals i) (aref vec (/ i 2)))))
3149 (if (< (* i 2) max)
3150 (aset totals i (+ (aref totals i) (aref vec (* i 2)))))
3151 (setq i (1+ i)))
3153 (let ((x nil)
3154 (result nil)
3155 tot sum p)
3156 (setq i 1)
3157 (while (< i max)
3158 (if (/= (aref totals i) 0)
3159 (setq x (append x (list (cons i (aref totals i))))))
3160 (setq i (1+ i)))
3162 (setq x (sort x (lambda (a b) (> (cdr a) (cdr b)))))
3163 (setq tot (apply '+ (append totals nil)))
3164 (sh-debug (format "vec: %s\ntotals: %s\ntot: %d"
3165 vec totals tot))
3166 (cond
3167 ((zerop (length x))
3168 (message "no values!")) ;; we return nil
3169 ((= (length x) 1)
3170 (message "only value is %d" (car (car x)))
3171 (setq result (car (car x)))) ;; return single value
3172 ((> (cdr (car x)) (/ tot 2))
3173 ;; 1st is > 50%
3174 (message "basic-offset is probably %d" (car (car x)))
3175 (setq result (car (car x)))) ;; again, return a single value
3176 ((>= (cdr (car x)) (* 2 (cdr (car (cdr x)))))
3177 ;; 1st is >= 2 * 2nd
3178 (message "basic-offset could be %d" (car (car x)))
3179 (setq result (car (car x))))
3180 ((>= (+ (cdr (car x))(cdr (car (cdr x)))) (/ tot 2))
3181 ;; 1st & 2nd together >= 50% - return a list
3182 (setq p x sum 0 result nil)
3183 (while (and p
3184 (<= (setq sum (+ sum (cdr (car p)))) (/ tot 2)))
3185 (setq result (append result (list (car (car p)))))
3186 (setq p (cdr p)))
3187 (message "Possible choices for sh-basic-offset: %s"
3188 (mapconcat 'int-to-string result " ")))
3190 (message "No obvious value for sh-basic-offset. Perhaps %d"
3191 (car (car x)))
3192 ;; result is nil here
3194 result)))
3196 ;; ========================================================================
3198 ;; Styles -- a quick and dirty way of saving the indentation settings.
3200 (defvar sh-styles-alist nil
3201 "A list of all known shell indentation styles.")
3203 (defun sh-name-style (name &optional confirm-overwrite)
3204 "Name the current indentation settings as a style called NAME.
3205 If this name exists, the command will prompt whether it should be
3206 overwritten if
3207 - - it was called interactively with a prefix argument, or
3208 - - called non-interactively with optional CONFIRM-OVERWRITE non-nil."
3209 ;; (interactive "sName for this style: ")
3210 (interactive
3211 (list
3212 (read-from-minibuffer "Name for this style? " )
3213 (not current-prefix-arg)))
3214 (let ((slist (cons name
3215 (mapcar (lambda (var) (cons var (symbol-value var)))
3216 sh-var-list)))
3217 (style (assoc name sh-styles-alist)))
3218 (if style
3219 (if (and confirm-overwrite
3220 (not (y-or-n-p "This style exists. Overwrite it? ")))
3221 (message "Not changing style %s" name)
3222 (message "Updating style %s" name)
3223 (setcdr style (cdr slist)))
3224 (message "Creating new style %s" name)
3225 (push slist sh-styles-alist))))
3227 (defun sh-load-style (name)
3228 "Set shell indentation values for this buffer from those in style NAME."
3229 (interactive (list (completing-read
3230 "Which style to use for this buffer? "
3231 sh-styles-alist nil t)))
3232 (let ((sl (assoc name sh-styles-alist)))
3233 (if (null sl)
3234 (error "sh-load-style - style %s not known" name)
3235 (dolist (var (cdr sl))
3236 (set (car var) (cdr var))))))
3238 (defun sh-save-styles-to-buffer (buff)
3239 "Save all current styles in elisp to buffer BUFF.
3240 This is always added to the end of the buffer."
3241 (interactive (list
3242 (read-from-minibuffer "Buffer to save styles in? " "*scratch*")))
3243 (with-current-buffer (get-buffer-create buff)
3244 (goto-char (point-max))
3245 (insert "\n")
3246 (pp `(setq sh-styles-alist ',sh-styles-alist) (current-buffer))))
3250 ;; statement syntax-commands for various shells
3252 ;; You are welcome to add the syntax or even completely new statements as
3253 ;; appropriate for your favorite shell.
3255 (defconst sh-non-closing-paren
3256 ;; If we leave it rear-sticky, calling `newline' ends up inserting a \n
3257 ;; that inherits this property, which then confuses the indentation.
3258 (propertize ")" 'syntax-table sh-st-punc 'rear-nonsticky t))
3260 (define-skeleton sh-case
3261 "Insert a case/switch statement. See `sh-feature'."
3262 (csh "expression: "
3263 "switch( " str " )" \n
3264 > "case " (read-string "pattern: ") ?: \n
3265 > _ \n
3266 "breaksw" \n
3267 ( "other pattern, %s: "
3268 < "case " str ?: \n
3269 > _ \n
3270 "breaksw" \n)
3271 < "default:" \n
3272 > _ \n
3273 resume:
3274 < < "endsw" \n)
3275 (es)
3276 (rc "expression: "
3277 > "switch( " str " ) {" \n
3278 > "case " (read-string "pattern: ") \n
3279 > _ \n
3280 ( "other pattern, %s: "
3281 "case " str > \n
3282 > _ \n)
3283 "case *" > \n
3284 > _ \n
3285 resume:
3286 ?\} > \n)
3287 (sh "expression: "
3288 > "case " str " in" \n
3289 ( "pattern, %s: "
3290 > str sh-non-closing-paren \n
3291 > _ \n
3292 ";;" \n)
3293 > "*" sh-non-closing-paren \n
3294 > _ \n
3295 resume:
3296 "esac" > \n))
3298 (define-skeleton sh-for
3299 "Insert a for loop. See `sh-feature'."
3300 (csh sh-modify sh
3301 1 ""
3302 2 "foreach "
3303 4 " ( "
3304 6 " )"
3305 15 '<
3306 16 "end")
3307 (es sh-modify rc
3308 4 " = ")
3309 (rc sh-modify sh
3310 2 "for( "
3311 6 " ) {"
3312 15 ?\} )
3313 (sh "Index variable: "
3314 > "for " str " in " _ "; do" \n
3315 > _ | ?$ & (sh-remember-variable str) \n
3316 "done" > \n))
3320 (define-skeleton sh-indexed-loop
3321 "Insert an indexed loop from 1 to n. See `sh-feature'."
3322 (bash sh-modify posix)
3323 (csh "Index variable: "
3324 "@ " str " = 1" \n
3325 "while( $" str " <= " (read-string "upper limit: ") " )" \n
3326 > _ ?$ str \n
3327 "@ " str "++" \n
3328 < "end" \n)
3329 (es sh-modify rc
3330 4 " =")
3331 (ksh88 "Index variable: "
3332 > "integer " str "=0" \n
3333 > "while (( ( " str " += 1 ) <= "
3334 (read-string "upper limit: ")
3335 " )); do" \n
3336 > _ ?$ (sh-remember-variable str) > \n
3337 "done" > \n)
3338 (posix "Index variable: "
3339 > str "=1" \n
3340 "while [ $" str " -le "
3341 (read-string "upper limit: ")
3342 " ]; do" \n
3343 > _ ?$ str \n
3344 str ?= (sh-add (sh-remember-variable str) 1) \n
3345 "done" > \n)
3346 (rc "Index variable: "
3347 > "for( " str " in" " `{awk 'BEGIN { for( i=1; i<="
3348 (read-string "upper limit: ")
3349 "; i++ ) print i }'`}) {" \n
3350 > _ ?$ (sh-remember-variable str) \n
3351 ?\} > \n)
3352 (sh "Index variable: "
3353 > "for " str " in `awk 'BEGIN { for( i=1; i<="
3354 (read-string "upper limit: ")
3355 "; i++ ) print i }'`; do" \n
3356 > _ ?$ (sh-remember-variable str) \n
3357 "done" > \n))
3360 (defun sh-shell-initialize-variables ()
3361 "Scan the buffer for variable assignments.
3362 Add these variables to `sh-shell-variables'."
3363 (message "Scanning buffer `%s' for variable assignments..." (buffer-name))
3364 (save-excursion
3365 (goto-char (point-min))
3366 (setq sh-shell-variables-initialized t)
3367 (while (search-forward "=" nil t)
3368 (sh-assignment 0)))
3369 (message "Scanning buffer `%s' for variable assignments...done"
3370 (buffer-name)))
3372 (defvar sh-add-buffer)
3374 (defun sh-add-completer (string predicate code)
3375 "Do completion using `sh-shell-variables', but initialize it first.
3376 This function is designed for use as the \"completion table\",
3377 so it takes three arguments:
3378 STRING, the current buffer contents;
3379 PREDICATE, the predicate for filtering possible matches;
3380 CODE, which says what kind of things to do.
3381 CODE can be nil, t or `lambda'.
3382 nil means to return the best completion of STRING, or nil if there is none.
3383 t means to return a list of all possible completions of STRING.
3384 `lambda' means to return t if STRING is a valid completion as it stands."
3385 (let ((vars
3386 (with-current-buffer sh-add-buffer
3387 (or sh-shell-variables-initialized
3388 (sh-shell-initialize-variables))
3389 (nconc (mapcar (lambda (var)
3390 (substring var 0 (string-match "=" var)))
3391 process-environment)
3392 sh-shell-variables))))
3393 (complete-with-action code vars string predicate)))
3395 (defun sh-add (var delta)
3396 "Insert an addition of VAR and prefix DELTA for Bourne (type) shell."
3397 (interactive
3398 (let ((sh-add-buffer (current-buffer)))
3399 (list (completing-read "Variable: " 'sh-add-completer)
3400 (prefix-numeric-value current-prefix-arg))))
3401 (insert (sh-feature '((bash . "$(( ")
3402 (ksh88 . "$(( ")
3403 (posix . "$(( ")
3404 (rc . "`{expr $")
3405 (sh . "`expr $")
3406 (zsh . "$[ ")))
3407 (sh-remember-variable var)
3408 (if (< delta 0) " - " " + ")
3409 (number-to-string (abs delta))
3410 (sh-feature '((bash . " ))")
3411 (ksh88 . " ))")
3412 (posix . " ))")
3413 (rc . "}")
3414 (sh . "`")
3415 (zsh . " ]")))))
3419 (define-skeleton sh-function
3420 "Insert a function definition. See `sh-feature'."
3421 (bash sh-modify ksh88
3422 3 "() {")
3423 (ksh88 "name: "
3424 "function " str " {" \n
3425 > _ \n
3426 < "}" \n)
3427 (rc sh-modify ksh88
3428 1 "fn ")
3429 (sh ()
3430 "() {" \n
3431 > _ \n
3432 < "}" \n))
3436 (define-skeleton sh-if
3437 "Insert an if statement. See `sh-feature'."
3438 (csh "condition: "
3439 "if( " str " ) then" \n
3440 > _ \n
3441 ( "other condition, %s: "
3442 < "else if( " str " ) then" \n
3443 > _ \n)
3444 < "else" \n
3445 > _ \n
3446 resume:
3447 < "endif" \n)
3448 (es "condition: "
3449 > "if { " str " } {" \n
3450 > _ \n
3451 ( "other condition, %s: "
3452 "} { " str " } {" > \n
3453 > _ \n)
3454 "} {" > \n
3455 > _ \n
3456 resume:
3457 ?\} > \n)
3458 (rc "condition: "
3459 > "if( " str " ) {" \n
3460 > _ \n
3461 ( "other condition, %s: "
3462 "} else if( " str " ) {" > \n
3463 > _ \n)
3464 "} else {" > \n
3465 > _ \n
3466 resume:
3467 ?\} > \n)
3468 (sh "condition: "
3469 '(setq input (sh-feature sh-test))
3470 > "if " str "; then" \n
3471 > _ \n
3472 ( "other condition, %s: "
3473 > "elif " str "; then" > \n
3474 > \n)
3475 "else" > \n
3476 > \n
3477 resume:
3478 "fi" > \n))
3482 (define-skeleton sh-repeat
3483 "Insert a repeat loop definition. See `sh-feature'."
3484 (es nil
3485 > "forever {" \n
3486 > _ \n
3487 ?\} > \n)
3488 (zsh "factor: "
3489 > "repeat " str "; do" > \n
3490 > \n
3491 "done" > \n))
3493 ;;;(put 'sh-repeat 'menu-enable '(sh-feature sh-repeat))
3497 (define-skeleton sh-select
3498 "Insert a select statement. See `sh-feature'."
3499 (ksh88 "Index variable: "
3500 > "select " str " in " _ "; do" \n
3501 > ?$ str \n
3502 "done" > \n)
3503 (bash sh-append ksh88))
3504 ;;;(put 'sh-select 'menu-enable '(sh-feature sh-select))
3508 (define-skeleton sh-tmp-file
3509 "Insert code to setup temporary file handling. See `sh-feature'."
3510 (bash sh-append ksh88)
3511 (csh (file-name-nondirectory (buffer-file-name))
3512 "set tmp = `mktemp -t " str ".XXXXXX`" \n
3513 "onintr exit" \n _
3514 (and (goto-char (point-max))
3515 (not (bolp))
3516 ?\n)
3517 "exit:\n"
3518 "rm $tmp* >&/dev/null" > \n)
3519 (es (file-name-nondirectory (buffer-file-name))
3520 > "local( signals = $signals sighup sigint;" \n
3521 > "tmp = `{ mktemp -t " str ".XXXXXX } ) {" \n
3522 > "catch @ e {" \n
3523 > "rm $tmp^* >[2]/dev/null" \n
3524 "throw $e" \n
3525 "} {" > \n
3526 _ \n
3527 ?\} > \n
3528 ?\} > \n)
3529 (ksh88 sh-modify sh
3530 7 "EXIT")
3531 (rc (file-name-nondirectory (buffer-file-name))
3532 > "tmp = `{ mktemp -t " str ".XXXXXX }" \n
3533 "fn sigexit { rm $tmp^* >[2]/dev/null }" \n)
3534 (sh (file-name-nondirectory (buffer-file-name))
3535 > "TMP=`mktemp -t " str ".XXXXXX`" \n
3536 "trap \"rm $TMP* 2>/dev/null\" " ?0 \n))
3540 (define-skeleton sh-until
3541 "Insert an until loop. See `sh-feature'."
3542 (sh "condition: "
3543 '(setq input (sh-feature sh-test))
3544 > "until " str "; do" \n
3545 > _ \n
3546 "done" > \n))
3547 ;;;(put 'sh-until 'menu-enable '(sh-feature sh-until))
3551 (define-skeleton sh-while
3552 "Insert a while loop. See `sh-feature'."
3553 (csh sh-modify sh
3554 2 ""
3555 3 "while( "
3556 5 " )"
3557 10 '<
3558 11 "end")
3559 (es sh-modify sh
3560 3 "while { "
3561 5 " } {"
3562 10 ?\} )
3563 (rc sh-modify sh
3564 3 "while( "
3565 5 " ) {"
3566 10 ?\} )
3567 (sh "condition: "
3568 '(setq input (sh-feature sh-test))
3569 > "while " str "; do" \n
3570 > _ \n
3571 "done" > \n))
3575 (define-skeleton sh-while-getopts
3576 "Insert a while getopts loop. See `sh-feature'.
3577 Prompts for an options string which consists of letters for each recognized
3578 option followed by a colon `:' if the option accepts an argument."
3579 (bash sh-modify sh
3580 18 "${0##*/}")
3581 (csh nil
3582 "while( 1 )" \n
3583 > "switch( \"$1\" )" \n
3584 '(setq input '("- x" . 2))
3586 ( "option, %s: "
3587 < "case " '(eval str)
3588 '(if (string-match " +" str)
3589 (setq v1 (substring str (match-end 0))
3590 str (substring str 0 (match-beginning 0)))
3591 (setq v1 nil))
3592 str ?: \n
3593 > "set " v1 & " = $2" | -4 & _ \n
3594 (if v1 "shift") & \n
3595 "breaksw" \n)
3596 < "case --:" \n
3597 > "shift" \n
3598 < "default:" \n
3599 > "break" \n
3600 resume:
3601 < < "endsw" \n
3602 "shift" \n
3603 < "end" \n)
3604 (ksh88 sh-modify sh
3605 16 "print"
3606 18 "${0##*/}"
3607 37 "OPTIND-1")
3608 (posix sh-modify sh
3609 18 "$(basename $0)")
3610 (sh "optstring: "
3611 > "while getopts :" str " OPT; do" \n
3612 > "case $OPT in" \n
3613 '(setq v1 (append (vconcat str) nil))
3614 ( (prog1 (if v1 (char-to-string (car v1)))
3615 (if (eq (nth 1 v1) ?:)
3616 (setq v1 (nthcdr 2 v1)
3617 v2 "\"$OPTARG\"")
3618 (setq v1 (cdr v1)
3619 v2 nil)))
3620 > str "|+" str sh-non-closing-paren \n
3621 > _ v2 \n
3622 > ";;" \n)
3623 > "*" sh-non-closing-paren \n
3624 > "echo" " \"usage: " "`basename $0`"
3625 " [+-" '(setq v1 (point)) str
3626 '(save-excursion
3627 (while (search-backward ":" v1 t)
3628 (replace-match " ARG] [+-" t t)))
3629 (if (eq (preceding-char) ?-) -5)
3630 (if (and (sequencep v1) (length v1)) "] " "} ")
3631 "[--] ARGS...\"" \n
3632 "exit 2" > \n
3633 "esac" >
3634 \n "done"
3635 > \n
3636 "shift " (sh-add "OPTIND" -1) \n
3637 "OPTIND=1" \n))
3641 (defun sh-assignment (arg)
3642 "Remember preceding identifier for future completion and do self-insert."
3643 (interactive "p")
3644 (self-insert-command arg)
3645 (if (<= arg 1)
3646 (sh-remember-variable
3647 (save-excursion
3648 (if (re-search-forward (sh-feature sh-assignment-regexp)
3649 (prog1 (point)
3650 (beginning-of-line 1))
3652 (match-string 1))))))
3655 (defun sh-maybe-here-document (arg)
3656 "Insert self. Without prefix, following unquoted `<' inserts here document.
3657 The document is bounded by `sh-here-document-word'."
3658 (interactive "*P")
3659 (self-insert-command (prefix-numeric-value arg))
3660 (or arg
3661 (not (looking-back "[^<]<<"))
3662 (save-excursion
3663 (backward-char 2)
3664 (sh-quoted-p))
3665 (let ((tabs (if (string-match "\\`-" sh-here-document-word)
3666 (make-string (/ (current-indentation) tab-width) ?\t)
3667 ""))
3668 (delim (replace-regexp-in-string "['\"]" ""
3669 sh-here-document-word)))
3670 (insert sh-here-document-word)
3671 (or (eolp) (looking-at "[ \t]") (insert ?\s))
3672 (end-of-line 1)
3673 (while
3674 (sh-quoted-p)
3675 (end-of-line 2))
3676 (insert ?\n tabs)
3677 (save-excursion
3678 (insert ?\n tabs (replace-regexp-in-string
3679 "\\`-?[ \t]*" "" delim))))))
3682 ;; various other commands
3684 (autoload 'comint-dynamic-complete "comint"
3685 "Dynamically perform completion at point." t)
3687 (autoload 'shell-dynamic-complete-command "shell"
3688 "Dynamically complete the command at point." t)
3690 (autoload 'comint-dynamic-complete-filename "comint"
3691 "Dynamically complete the filename at point." t)
3693 (autoload 'shell-dynamic-complete-environment-variable "shell"
3694 "Dynamically complete the environment variable at point." t)
3698 (defun sh-beginning-of-command ()
3699 "Move point to successive beginnings of commands."
3700 (interactive)
3701 (if (re-search-backward sh-beginning-of-command nil t)
3702 (goto-char (match-beginning 2))))
3704 (defun sh-end-of-command ()
3705 "Move point to successive ends of commands."
3706 (interactive)
3707 (if (re-search-forward sh-end-of-command nil t)
3708 (goto-char (match-end 1))))
3710 ;; Backslashification. Stolen from make-mode.el.
3712 (defun sh-backslash-region (from to delete-flag)
3713 "Insert, align, or delete end-of-line backslashes on the lines in the region.
3714 With no argument, inserts backslashes and aligns existing backslashes.
3715 With an argument, deletes the backslashes.
3717 This function does not modify the last line of the region if the region ends
3718 right at the start of the following line; it does not modify blank lines
3719 at the start of the region. So you can put the region around an entire
3720 shell command and conveniently use this command."
3721 (interactive "r\nP")
3722 (save-excursion
3723 (goto-char from)
3724 (let ((column sh-backslash-column)
3725 (endmark (make-marker)))
3726 (move-marker endmark to)
3727 ;; Compute the smallest column number past the ends of all the lines.
3728 (if sh-backslash-align
3729 (progn
3730 (if (not delete-flag)
3731 (while (< (point) to)
3732 (end-of-line)
3733 (if (= (preceding-char) ?\\)
3734 (progn (forward-char -1)
3735 (skip-chars-backward " \t")))
3736 (setq column (max column (1+ (current-column))))
3737 (forward-line 1)))
3738 ;; Adjust upward to a tab column, if that doesn't push
3739 ;; past the margin.
3740 (if (> (% column tab-width) 0)
3741 (let ((adjusted (* (/ (+ column tab-width -1) tab-width)
3742 tab-width)))
3743 (if (< adjusted (window-width))
3744 (setq column adjusted))))))
3745 ;; Don't modify blank lines at start of region.
3746 (goto-char from)
3747 (while (and (< (point) endmark) (eolp))
3748 (forward-line 1))
3749 ;; Add or remove backslashes on all the lines.
3750 (while (and (< (point) endmark)
3751 ;; Don't backslashify the last line
3752 ;; if the region ends right at the start of the next line.
3753 (save-excursion
3754 (forward-line 1)
3755 (< (point) endmark)))
3756 (if (not delete-flag)
3757 (sh-append-backslash column)
3758 (sh-delete-backslash))
3759 (forward-line 1))
3760 (move-marker endmark nil))))
3762 (defun sh-append-backslash (column)
3763 (end-of-line)
3764 ;; Note that "\\\\" is needed to get one backslash.
3765 (if (= (preceding-char) ?\\)
3766 (progn (forward-char -1)
3767 (delete-horizontal-space)
3768 (indent-to column (if sh-backslash-align nil 1)))
3769 (indent-to column (if sh-backslash-align nil 1))
3770 (insert "\\")))
3772 (defun sh-delete-backslash ()
3773 (end-of-line)
3774 (or (bolp)
3775 (progn
3776 (forward-char -1)
3777 (if (looking-at "\\\\")
3778 (delete-region (1+ (point))
3779 (progn (skip-chars-backward " \t") (point)))))))
3781 (provide 'sh-script)
3783 ;;; sh-script.el ends here