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