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