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