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