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