diff --git a/contrib/tcsh/Fixes b/contrib/tcsh/Fixes index e539c8241a86..76fdede0c4b7 100644 --- a/contrib/tcsh/Fixes +++ b/contrib/tcsh/Fixes @@ -1,2197 +1,2198 @@ + 15. V6.22.04 - 20210426 14. Don't crash with 'bindkey "^0" clear-screen' (Karl Jeacle) 13. Fix $x:q:h and $x:q:t return the whole string for strings not containing / 12. V6.22.03 - 20201118 11. Fix $x:q:h and $x:q:t to not crash (alzwded) with strings containing / 10. Block SIGHUP while writing history/directory stack (Brett Frankenberger) 9. Fixed reversed test that broke history merging (Brett Frankenberger) 8. Prevent recursive entry for writing history (Brett Frankenberger) 7. alxwded@github, keep track of the :g and :a modifiers per modifier they affect. 6. alzwded@github, fix infinite loop with :gas variable modifier 5. PR/88: Add a Q: modifier that preserves empty arguments leaving :q alone. 4. V6.22.02 - 20191204 3. Fix version in configure.ac 2. V6.22.01 - 20191201 1. undo PR/88: Preserve empty arguments in :q, since it breaks $ set x="" $ alias test "echo "\""$x:q"\"" is working." $ alias test echo " 6. V6.22.00 - 20191128 5. PR/113: Sobomax: avoid infinite loops for -c commands when stdout is not a tty. 4. Avoid infinite loops during history loads when merging, print a better error for errors during history load. 3. PR/88: Preserve empty arguments in :q 2. PR/94: Small apple issues (SAVESIGVEC, HOSTTYPE) 1. PR/81: Fix range matching issue where we were comparing with the range character instead of the start of range. [l-z]* would match foo 12. V6.21.00 - 20190508 11. Abort history loading on words and lines too long https://bugzilla.redhat.com/show_bug.cgi?id=1598502 10. PR/37: Introduce GetCmdChar() to avoid open coding array access. 9. make closem() not close sockets so as not to affect nss_ldap. tcsh never creates sockets so that's ok (Miloslav Trmac) 8. PR/597: Make rmstar work with aliased rm 7. convert match() from recursive to backtracking. 6. Handle 8 bit characters in bindkey (Werner Fink) 5. Look for tgetent in libtinfo as well (Werner Fink) 4. Don't play pointer tricks that are undefined in modern c (Brooks Davis) 3. Fix out of bounds read (Brooks Davis) 2. Fix type of read in prompt confirmation (eg. rmstar) (David Kaspar) 1. PR/471: Delay arginp parsing 20. V6.20.00 - 20161124 19. Don't resize the screen if it did not change size. 18. V6.19.01 - 20161025 17. restore file description when cleaning up after eval: repeat 99 time 16. PR/572: Fix $SHLVL issue when exec'ing subshells. 15. PR/403: Fix backquote expansion for multi-byte character sets. 14. Fix drawing issu with multi-line prompt (Kensuke Iwahashi/David Kaspar) 13. always send prusage to stdout. 12. PR/526: Fix double \\ printing from previous fix in history expansion. 11. Android updates from Corinna Vinschen 10. PR/526: Quote backslashes properly so they can be preserved in `` expansions 9. Fix memory leak for paraml 8. Add notempty and ask values for the noclobber setting (Martin Tournoij) 7. more correct $wordchars for vimode (Luke Mewburn) 6. expose VImode in $vimode (Luke Mewburn) 5. display what the compiled in editor is in bindkey -d (Luke Mewburn) 4. run-fg-editor improvements and documentation (Luke Mewburn) 3. Fix parsing of 'if (cond)then' (Fridolin Pokorny) 2. PR/437: Fix handling of invalid unicode characters. 1. PR/451: Fix error messages containing %c to be always '%c' 41. V6.19.00 - 20150521 40. V6.18.05 - 20150510 39. fix reseting when interrupted inside an eval "eval sleep 10^C" (paulo.cesar.pereira.de.andrade) 38. rename handle_intr -> handle_interrupt as originally intended. 37. fix input tests that need stdin on a tty 36. V6.18.04 - 20150504 35. revert fix echo "\1", it is incorrect. 34. revert fix to PR/437, breaks short strings. 33. V6.18.03 - 20150503 32. PR/437: Nakajima Akira: Fix segmentation fault reading input files 31. PR/291: Print job status messages to stderr. 30. Fridolin Pokorny NUL in `` does not mean EOF. 29. Pavel Raiskup fix hang with: while (1) ( date & ; wait ) end 28. Add cdtohome special variable (Martin Tournoij) 27. Fix root prompt char for windows (Corinna Vinschen) 26. For "next" completion matches only consider exact matches of the previous word (Jamie Landeg-Jones) 25. Fix echo "\1" for echo_style=both where the first character was not processed properly (Gary Duzan) 24. V6.18.02 - 20140618 23. fix ls-F /non printing exit value twice. 22. rename configure.in to configure.ac, add aclocal.m4 to CVS 21. set foo="aabaabaa"; echo $foo:as/a// should produce bb 20. Add locked merge history support (Marcin Konarski) 19. Support more resource limits from various BSD's 18. Cache history count to speed up thing 17. PR/240: minix support 16. revert fix for 15. Causes extra quoting, for example (foo is a program that prints its arguments): $ ./foo 'abc' * '\a\b\c' 15. fix globbing for ``, stripping backslashes. Example: cat << _EOF > huh echo 'hello\;world' _EOF echo `./huh 0` echo `./huh $?` 14. fix for `` that causes hang. Example: cat << _EOF > huh #!/bin/sh echo "[$@]" echo "I am running" echo "I am running ($$)" >> huh.out _EOF cat << _EOF > huh.tcsh #!/bin/tcsh -f ./huh \ `#comment blah blah blah` \ parameter a \ `#comment blah blah blah` \ parameter b \ `#comment blah blah blah` \ parameter c echo ok _EOF 13. remove AsciiOnly fix now that the real issue has been fixed (Roman Kollar) 12. define utmp file for aix (Laurence Darby) 11. fix if history in loops 10. make ls-F print to stderr and set the exit code 9. make rmstar interruptible on linux 8. Get rid of pret_t and make the printf functions return the number of characters printed as the system ones do. 7. Parse a FreeBSD compat $LSCOLORS. What to do when both LSCOLORS and LS_COLORS are set. I am not documenting this until we decide. 6. V6.18.01 - 20120214 5. fix interruptible wait again 4. ignore bogus compiler overflow message 3. cleanup ifdefs in utmp code, and provide default array entries 2. Ignore #machine entries in host.defs 1. Detect missing ) in gethost.c (Corinna Vinschen) 104. V6.18.00 - 20120114 103. remove unused variables. 102. Make gethost use definitions for x __x__ and __x automatically. 101. More utmp fixes 100. V6.17.10 - 20120105 99. Add more FreeBSD/NetBSD machines 98. Add portability wrapper for gencat 97. Fix warning for write in SYSMALLOC systems. 96. V6.17.09 - 20120102 95. revert gencat handling to pre-cygwin fixes (without the env settings) 94. remove stray endutent() 93. V6.17.08 - 20111230 92. Remove - from gencat 91. Provide support for malloc_usable_size() so that linux works again without SYSMALLOC 90. Add support for FreeBSD's utmpx. 89. V6.17.07 - 20111227 88. Fix debian bug #645238: tcsh segfaults when prompt includes %j and there are more than 10 jobs. 87. PR/155: Default $anyerror to set for backward compatibility 86. PR/149: Don't print -1 in %j (Vojtech Vitek) 85. handle -- on chdir commands as the end of options processing so that they can process a directory like -x without resorting to ./-x (Andrew Stevenson) 84. Handle write(2) returning ENOENT from SoFS, thanks ++HAL (Robert Byrnes) 83. PR/38: Null check for jobs (Kurt Miller) 82. Fix spelling correction correcting ./foo -> ../foo2 (jean-luc leger) 81. PR/120: string0 in filetest does not have enough space. 80. V6.17.06 - 20110415 79. PR/110: Add $anyerror to select behavior. Default to the new one. 78. Don't try to spell commands that are correct (Rouben Rostamian) [./tcsh -f; set path=($path 2); mkdir foo2; cd foo2; touch foo; chmod +x foo; set correct=cmd; ./foo -> ../foo] 77. Don't push the syntax struct on the cleanup stack, because on foo;bar if foo fails, we will free bar prematurely (Ben Miller) 76. Avoid infinite loop while trying to print the pid of a dying process to a closed file (Bob Arendt) 75. Handle completion of ${ variables (Anthony Mallet) 74. Add --disable-nls-catalogs (Corinna Vinschen) 73. convert message catalogs to UTF-8 (Werner Fink) 72. check that the NLS path works before setting $NLSPATH. 71. use SYSMALLOC for GLIBC (Werner Fink) 70. use mallinfo for SYSMALLOC (Corinna Vinschen) 69. V6.17.05 - 20110201 68. Use mkstemp() if there for here docs (Werner Fink) 67. Fix handling of errors and exit values in builtins (Werner Fink) 66. Better pty name detection (Werner Fink) 65. Enable NLS catalogs on Cygwin (Corinna Vinschen) 64. NLSPATH handling fixes (Corinna Vinschen) 63. Avoid infrequent exit when tcsh cd's into a non-existent directory https://bugzilla.novell.com/show_bug.cgi?id=293395 (Werner Fink) 62. Don't try to spell check full path binaries that are correct because they can cause hangs when other nfs partitions are hung. (Werner Fink) 61. Avoid nested interrupts when exiting causing history writing to fail https://bugzilla.novell.com/show_bug.cgi?id=331627 (Werner Fink) 60. Instead of giving an error or ignoring lines with missing eol at eof, process them. 59. Avoid leaking fd's in mail check (Werner Fink) 58. Add cygwin_xcrypt() (Corinna Vinschen) 57. Recognize i686 (Corinna Vinschen) 56. Rename cygwin32 to cygwin and bring it up-to-date with modern cygwin settings (Corinna Vinschen) 55. Avoid double slashes in cdpath (Corinna Vinschen) 54. V6.17.04 - 20110118 53. Revert PR/110, breaks the test suite. 52. V6.17.03 - 20110117 51. PR/102: Complain on input files with missing trailing \n 50. PR/104: If atime == mtime we don't have new mail. 49. PR/113: Don't allow illegal variable names to be set. 48. PR/112: don't set $REMOTEHOST on the local machine. 47. PR/110: exit status of the pipeline should be the status of the last command. 46. Android support (Corinna Vinschen) 45. Add AUTOSET_KANJI which works around the Shift-JIS encoding that translates unshifted 7 bit ASCII (Werner Fink) 44. Handle mb{r,}towc() returning 0 by setting the return value to NUL (Jean-Luc Leger) 43. PR/109: make wait interruptible (Vojtech Vitek) 42. resource limit fixes: signed vs. unsigned, megabyte issue, doc issues (Robert Byrnes) 41. remove .bat and .cmd handling for executables on cygwin (Corinna Vinschen) 40. Don't echo history while history -L or history -M 39. Check for EOS before ** from Greg Dionne 38. Don't fork in backeval from Bryan Mason 37. Better globstar support from Greg Dionne 36. Error out when processing the last incomplete line instead of silently ignoring it (Anders Kaseorg) 35. Fix SEGV from echo `` 34. Better fixes for histchars and promptchars (nargs) 33. Fix win32 issue calling fmalloc/ffree from non-thread-safe context. (Fabio Fabbri) 32. V6.17.02 - 20100512 31. PR/79: nargs: Better handling for promptchars. 30. PR/97: Add parseoctal to retain compatibility with previous versions (Jim Zajkowski) 29. PR/84: Performance fixes for large history merges (add hashtable (Ted Anderson) 28. Revert previous #23; people should use $histlit if they want this feature. 27. Don't kill "hup" background jobs when a child of the shell exits. From Debian. 26. Ignore \r\n in the command line options for OS's that don't strip these from #!; from Debian 25. Fix enhanced missing patch (Greg Dionne) 24. Callers of rt_mbtowc don't grok -2 as a return. Return -1 for now. (Corinna Vinschen) 23. Turn HistLit on while recording history to avoid \!\! losing its \. From Debian 22. set autoexpand; set histchars="";\n crash. From Debian 21. V6.17.01 - 20100506 20. unset verbose while we are reading the history file to avoid echoing to the terminal. (Jeffrey Bastian) 19. globstar addition, Enhance addition, euid, euser, gid variables (Greg Dionne) 18. Make 'e' in vi mode work like 'b' - use wordchars (Alistair Crooks) 17. Handle UTF-16 surrogates (Corinna Vinschen) 16. Make tcsh work on systems where sizeof(wchar_t) == 2 (Corinna Vinschen) 15. Better support for Solaris >= 2.9 (Thomas Uhle) 14. Change internal expression calculations to long long so that we can deal with > 32 bit time, inodes, uids, file sizes etc. 13. Add new linux resource limits. 12. Don't print 'Exit X' when printexitvalue is set in `` expressions (Jeff Bastian) 11. Add more LS_COLORS vars (M.H. Anderson) 10. Reduce whitespace in Makefile (Don Estabrook) 9. Manual page fixes (Alan R. S. Bueno) 8. Remove history in loops bug from the documentation (Holger Weiss) 7. Add autorehash (Holger Weiss) 6. Add history.at (Ted Anderson) 5. Better NLSPATH handling (Norm Jacobs) 4. Fix hostname building from utmp (Cyrus Rahman) 3. Handle pending signals before flush so that the the history file does not get truncated. (Ted Anderson) 2. Fix AsciiOnly setting that broke 8 bit input. (Juergen Keil) 1. remember to closedir in mailchk (from Werner Fink, reported by David Binderman) 21. V6.17.00 - 20090710 20. Fix dataroot autoconf issue. 19. Fix directory stuff for unit tests. 18. Fix small bug in history in loops. 17. Provide newer config.{guess,sub} 16. Fix gcc 4 warnings. 15. Fix memory trashing bug introduced in 10. 14. V6.16.01 - 20090624 13. add missing sigemptyset in goodbye() 12. add rlimit swapsize from FreeBSD. 11. restore behavior where a[n-] never prints an error. 10. always save the whole command, not just the first 80 chars of it. 9. fix short2str/short2qstr length adjustment in wide chars (Vitezslav Crhonek) 8. set histfile=/tmp/history.temp; set savehist=(100 merge); alias precmd history -S. After that justpr is not restored and commands don't execute. (Andriy Gapon) 7. Fix "as" $ modifier from corrupting memory. set t=demfonsftraftionf; echo $t:as/f// 6. Make $% work with environment variable (Ron Johnston) 5. Dragonfly script support (Matthias Schmidt, m65) 4. Add autoexpand=onlyhistory (Don Estabrook, m66) 3. Add history in loops (Laurence Darby, m48) 2. Add missing colorls "rs" variable (Shlomi Fish, m70) 1. Fix pts detection issue (Ruslan Ermilov) 33. V6.16.00 - 20080930 32. longjmp clobbered variable fixes. 31. __GNX__ addition 30. Windows fork fixes 28. V6.15.02 - 20080830 27. Fix an eval free'ing botch (Per Hedeland) 26. /bin/echo "`" coredumped because stderror() calls longjmp corrupting the stack (Mark Davies). We should vet the code for all stderror() calls that cleanup local stack variables. 25. foo > ${undef} caused coredumps because of vfork() child corrupting the state of the parent stack. 24. $x[A-B] did not complain for A out of range. (Cai Xianchao) 23. rename setp -> tcsh_setp to avoid conflict with mach (Javier Vasquez) 22. Fix degree handling by defining __XPG4_CHAR_CLASS__ for solaris (Mike Sullivan) 21. Change 'od' to 'od -c' in tests so that they work on big endian machines. (Martin Kraemer) 20. Add environment variable COMMAND_LINE to be available in completions (Marcin Konarski) 19. V6.15.01 - 20070928 18. Evaluate expressions in the proper order (Li Zefan), controlled by compat_expr. 17. Don't need to flush() if we are silent. Prevents recursive error issue. (joshua stein) 16. Don't execute the jobcmd if the output is not a tty (Charles Ross) 15. Quote the history in the examples (Johann 'Myrkraverk' Oskarsson) 14. Mismatch clarification patch (Per Hedeland) 13. Fix 'repeat n cmd &' abort() (Mike Sullivan) 12. Fix octal parsing (Li Zefan) 11. Fix pty detection for autologout setting (Kris Kennaway, Giorgos Keramidas) 10. kill `foo` got stuck because sigchld was disabled too soon (Mark Peek) 9. Avoid null pointer dereference in proc cwd (Kurt Miller) 8. eval "foreach a b c" exits (Anthony Menasse) 7. Quoting was broken in substitutions (Joe Wells) 6. QNX patches via pkgsrc 5. cd - twice from a directory that contained a glob pattern, expands the glob twice (Mark Santcroos) 4. MidnightBsd support (Lucas Holt) 3. Fix history substitution core-dump with no history entries 2. Merge two character tables that are the same (Martin Kraemer) 1. On ancient 7 bit locales, punctuation characters are used to denote special characters such as umlaut, adiaresis, etc. These characters return true for isalpha/isalnum. Ignore them because they break parsing (Martin Kraemer) 74. V6.15.00 - 20070303 73. fix extension eating windows code (christos) 72. fix loop in %R history expansion (christos) 71. sched +X source file disables interrupts (Mike Sullivan) 70. One off copying macro buffers (Jean-Luc Leger) 69. Avoid infinite loops in :ga modifiers when the LHS is a substring of the RHS. 68. Automatically disable WIDE_STRINGS with --disable-nls (Miloslav Trmac) 67. V6.14.07 - 20060825 66. rename set to setv to avoid clashes (christos) 65. Eliminate sighold/sigrelse (christos) 64. Compilation cleanups. (Martin Kraemer) 63. Don't rebuild needlessly when generated files are unchanged (Martin Kraemer) 62. Fix confusion between Char and eChar (Martin Kraemer) 61. V6.14.06 - 20060824 60. set PROGRAM_ENVIRONMENT for OSD_POSIX (Martin Kraemer) 59. EBCDIC patch (Martin Kraemer) 58. Remove globbing support in history rearches (Ryan Barrett) 57. Highlighting patch (Ryan Barrett) 56. Mark-Cursor exchange emacs editing fix (Martin Kraemer) 55. V6.14.05 - 20060304 54. don't limit termcap strings to 1K (Alan Ferrency) 53. protect against null path. 52. Be more conservative in wide_read PR#29 51. remove HAVE_STRCOLL; not needed anymore (Miloslav Trmac) 50. remove imake support and make nls configurable by configure (Miloslav Trmac) 49. V6.14.04 - 20060214 48. Fixes build failure with !SHORT_STRINGS (Miloslav Trmac) 47. Fixes constness warnings with !SHORT_STRINGS: short2str is "strip()", which modifies its argument. Rather than verify this is safe in all callers, I have added caching_strip() to mirror the behavior of other modes. (Miloslav Trmac) 46. Fixes some constness warnings with SHORT_STRINGS; this is orthogonal to both build errors with SHORT_STRINGS in 6.14.03, and short_strings.patch. (Miloslav Trmac) 45. config-catalogs.patch: Autodetect catalog support (#14). (Miloslav Trmac) 44. auth.patch: Handle false positives in getauthid() detection, IIRC on FreeBSD. (Miloslav Trmac) 43. crypt.patch: Autodetect whether is available. (Miloslav Trmac) 42. sigint.patch: Block SIGINT while waiting on children. This is necessary, but I'll still have to look on the older releases to find out why it was not necessary before ("before" = 6.13 on Linux). (Miloslav Trmac) 41. config-package.patch: Readd package version to configure.in, the testsuite uses it. (TODO: a better integration with package.h) (Miloslav Trmac) 40. item_len.patch: Truncate item.len when truncating the string, just to be sure. (Miloslav Trmac) 39. va_list.patch: Add missing va_end(). (Miloslav Trmac) 38. Use va_copy in xvasprintf(); emulate va_copy as suggested in Autoconf manual if it is not available. (Miloslav Trmac) 37. declarations.patch: Replace some #ifdef nests by autodetecting whether the guarded declaration is necessary. I'm only guessing this is the intent of the #ifdefs, though. Declare environ unconditionally, it is a bit hard to detect and the declaration is correct for Linux, anyway. (Miloslav Trmac) 36. warning.patch: Fix a const warning. 35. More color-ls variables (Jean-Luc Leger) 34. V6.14.03 - 20060212 33. Signal related changes (Miloslav Trmac) 32. Misc cast cleanups and code clarification (Miloslav Trmac) 31. Use dynamically allocated buffers everywhere (Miloslav Trmac) 30. Fix reading of invalid byte sequences (Miloslav Trmac) 29. read should only increment count when it succeeds (Miloslav Trmac) 28. testsuiteadditions (Miloslav Trmac) 27. -n fixes (Miloslav Trmac) 26. signness warnings (Miloslav Trmac) 25. Prevent infinite recursion in catclose (Gerhard Niklasch) 24. Add Dragonfly (Joerg Sonnenberger) 23. Check for wcwidth returning a negative number (TOMITA Yoshinori) 22. recognize "li" and "co" in echotc (Martin Kraemer) [PR/7] 21. Don't use T_Cols for wrapping purposes; use TermH consistently (Martin Kraemer) [PR/8] 20. Don't display duplicate utmp records (Miloslav Trmac) [PR/17] 19. Clarify hashing and -f sections of man page (Volker Quetschke) [PR/20] 18. Dave Yearke: configure did not recognize solaris 10 [PR/18] 17. CYGWIN: Don't lowercase commands and allow foo.exe on command line. (Corinna Vinschen) [PR/19] 16. CYGWIN: cd /foo && cd .. ends up erroneously in // for systems that HAVE_SLASHSLASH [PR/21] 15. %j was broken (Peter Kruse) 14. Extend // handling in pathnames from being apollo specific to also cygwin (Corinna Vinschen) 13. Fix uppercase/lowercase transformations (Jean-Luc Leger) 12. Fix symlink expansion (revert from 6.10.00) (Jean-Luc Leger and Christos) 11. Fix literal sequence in prompt (Miloslav Trmac) 10. V6.14.02 - 20050412 9. Prototype fixes (Miloslav Trmac and Jean-Luc Leger) 8. V6.14.01 - 20050411 7. Make =- refer to $owd (H.Merijn Brand) 6. Use prototypes (almost) everywhere (Miloslav Trmac) (issue #5) 5. Fix doc path in Cygwin installation (Corinna Vinschen) 4. Fix column size calculation (Martin Kraemer) 3. Implement newline-and-hold and newline-and-down-history (Per Hedeland) 2. Messages fixes for the ja (Japanese) locale (NAKAMURA Takeshi) (issue #4) 1. Enable charset conversion in nls (Miloslav Trmac) (issue #3) 76. V6.14.00 - 20050325 75. Additional messages for the ja (Japanese) locale (NAKAMURA Takeshi) 74. V6.13.10 - 20050321 73. Implement --help (Tom Warzeka) 72. Clamp solaris autologout time 71. Add support for "limit heapsize" (Martin Kraemer) 70. Improved autoconf for utmp/utmpx (Miloslav Trmac) 69. V6.13.09 - 20050303 68. Autoconf additions (Miloslav Trmac and Jean-Luc Leger) 67. Fix erroneous sign extension when printing huge numbers (Martin Kraemer) 66. Handle delay in termcap entries (Martin Kraemer) 65. EBCDIC and BS2000 fixes (Martin Kraemer) 64. Avoid the SCCS percent-S-percent sequence differently (Kimmo Suominen) 63. Mark position update fixes (Martin Kraemer) 62. Define BSDLIMIT and BSDTIMES for Cygwin (Corinna Vinschen) 61. Fix NLSFrom prototype (Martin Kraemer) 60. V6.13.08 - 20050303 59. Add test for socklen_t in autoconf 58. Fix problems with NLSFrom prototype 57. Deal with AIX's utmpx lossage 56. V6.13.07 - 20050118 55. constifications, XXX: duplicate prototype on setpgrp(). 54. iconv fixes (Miloslav Trmac) 53. literal code cleanups (Miloslav Trmac) 52. move intptr_t definition to sh.h and include both stdint.h and inttypes.h 51. Fix dup2() issues, and introduce FSAFE as the highest file descriptor to be left untouched. This is to avoid closing hesiod/nis etc file descriptors behind their backs. I need to really fix file descriptor handling one day. 50. forward<->reverse char conversion verification (Miloslav Trmac) 49. japanese locale additions (Yoshiyuki Sakakibara) 48. wide character/utf 8 cleanups (Michael Schroeder) 47. V6.13.06 - 20050105 46. autoconf cleanup (Miloslav Trmac) 45. Fix literal refresh code (Michael Schroeder) 44. Fix history printing bug with WIDE_STRINGS 43. V6.13.05 - 20041121 42. deal with not having intptr_t 41. get rid of bool. 40. Protect HAVE_ICONV with NLS_CATALOGS 39. Deal with wchar_t being unsigned. 38. If we HAVEUTMPX redefine some utmp functions in terms of utmpx ones. 37. V6.13.04 - 20041120 36. Fix display problems with two-column characters when using WIDE_STRINGS. (Miloslav Trmac) 35. Change charset declarations for some of the translations. (Miloslav Trmac) 34. Set O_LARGEFILE properly (Miloslav Trmac) 33. Use libc functions to access utmp data (Miloslav Trmac) 32. t_pmatch() was not really case-insensitive when cs == 8 (Miloslav Trmac) 31. Fix escaping of "control" bytes 0x80..0x9F when they are actually parts of UTF-8 character representation. (Miloslav Trmac) 30. V6.13.03 - 20041120 29. More close_on_exec fixes (Miloslav Trmac) 28. SUSE dspmbyte fixes (via Harald) 27. Newline handling in command substitution controlled by csubstnonl (Miloslav Trmac) 26. Fix UNC prompt expansion (WIN32) (Yasuhiro Matsumoto) 25. Fix incorrect xprintf() usage (Miloslav Trmac) 24. Additional architectures support for $HOSTTYPE and $MACHTYPE (Miloslav Trmac) 23. Use nl_langinfo(CODESET) to determine $dspmbyte (Miloslav Trmac) 22. Complete arguments that contant a # (Steven Grady) 21. Set close-on-exec in subshells 20. Compilation fixes (Miloslav Trmac) 19. V6.13.02 - 20040804 18. de-register, de-extern, de-shadow, and const poison. 17. WIDE_STRINGS support (Miloslav Trmac) 16. warning cleanups (Miloslav Trmac) 15. nlsclose() arg passing, exp2 is now a gcc builtin (Mark Peek) 14. iconv malloc portability fix. 13. make automatic dspmbyte determination case insensitive 12. V6.13.01 - 20040724 11. bug fix in automatic dspmbyte setting (Miloslav Trmac) 10. iconv patches (Miloslav Trmac) 9. cygwin signal fixes; only init 32 signals, don't set bit flag on error; breaks SIGHUP. (Corinna Vinschen) 8. Make sure terminal size change takes effect immediately. 7. Obey $printexitvalue for builtins. 6. FreeBSD PR/66420: Allow history parsing to be special so that it can handle inline # characters (Oliver Eikemeier) 5. new termname builtin from (Andrew Stevenson) 4. if ($var =~ *[^0-9]*) echo not numeric, fix (Andrew Stevenson) 3. completion fix to avoid dup hosts from ssh_known_hosts (Eric D. Hendrickson) 2. vc++ 7.1 compilation fix (Steve Schockley) 1. UTF-8 handling for both single and double width characters, but no combining character support. (Michael Schroeder) 36. V6.13.00 - 20040519 35. V6.12.03 - 20040322 34. turn on kanji and dspmbyte by default; add check for utf8 locales, and turn parsing of that automatically based on $LANG. 33. Fix compilation issue under Windows/NT and charset incorrect patch (Yoshiyuki Sakakibara) 32. completion additions (Tom Warzeka) 31. compilation fix (Martin Kraemer) 30. V6.12.02 - 20040221 29. Glob completion listing addition (Tom Warzeka) 28. BS2000 bs2cmd builtin. (Martin Kraemer) 27. Fix interrupt resetting code when /etc startup scripts have syntax errors (Mark A. Grondona) 26. Clarification of kill-ring commands (Per Hedeland) 25. Debian completion additions (Martin Godisch) 24. Japanese character set fixes (Juehiro-san) from debian 23. NLS charset fixes; disabled since they only work with gnu gencat (Martin Godisch) 22. Fix HPUX >= 11 resource (Jack Cummings) 21. Handle breaksw that jumps out of loops. 20. Revert #16. It causes worse problems. 19. Avoid using execl() because the last NULL does not always promoted to a pointer because the function is variadic (Harti Brandt) 18. revert ignoreeof to the 6.11.00 behavior and document it (Martin Godisch) 17. do a case insensitive comparison for the multibyte vars (Martin Godisch) 16. don't sigsuspend() for an already exited job 15. glob all arguments in source (Martin Godisch) 14. various debian fixes (Martin Godisch) 13. setenv syntax check revert (Satoshi I. Nozawa) 12. EAGAIN typo (dan harkless) 11. filec compilation issue on hpux (beebe) 10. win32 compilation fixes for O_LARGEFILE (amol) 9. Don't go into an infinite loop when tcgetpgrp() returns an error. 8. Cygwin fixes (Corinna Vinschen) 7. NLS catclose() bug avoidance (KAJIMOTO Masato) 6. V6.12.01 - 20030208 5. Misc NT cleanup. No more GPL code (amol) 4. use strtol() to detect errors in builtin kill (Peter Jeremy) 3. Recognize linux systems on mips* (Maciej W. Rozycki) 2. Enable complete=igncase on unix (Stephen Krauth) 1. Eliminate maxitems (Todd Miller) 58. V6.12.00 - 20020732 57. misc cleanups. 56. V6.11.05 - 20020712 55. We should have socklen_t in the INET6 case, but we leave int otherwise. 54. Fixed for Darwin/Rhapsody (Mark Peek) 53. provide new config.sub and config.guess from ftp://ftp.gnu.org/gnu/config/ (Nelson Beebe) 52. V6.11.04 - 20020709 51. Dissallow setting of environment variables that do not contain alphanumeric names (Ton Voon) 50. Don't expand path components that don't resolve to path names (Jonathan Chen) 49. Make $ignoreeof agree with the man page (Matias Moreno Meringer) 48. Fix argument passing in tc.prompt.c expdollar (Nelson Beebe) 47. Completion fixes from FreeBSD (Mark Peek) 46. FreeBSD's sbsize limit (Mark Peek) 45. Fix repeat 3 repeat 2 echo foo 44. Fix I/O redirection in scripts (Ian D Allen) 43. Fix ` \\\n ` evaluation (Jean-Luc Leger) 42. add --version (Nelson Beebe) 41. portability fixes for sed (Nelson Beebe) 40. undef sv_handler for AIX's benefit. (Nelson Beebe) 39. Add a test for ss_family that disables IPV6 (linux/ppc, osf/1 have problems) (Nelson Beebe) 38. Disable ipv6 for Apple (Nelson Beebe) 37. Fix darwin configure entry (Nelson Beebe) 36. V6.11.03 - 20020701 35. Add Ian D. Allen's bug list. 34. If we are invoked as csh, default to bsd echo (Matej Vela) 33. Don't close file descriptors too early because setuid scripts fail. (Jill Pryse-Davies) 32. Completion updates (Tom Warzeka) 31. Fix compilation issue on SunOS4 with _POSIX_VDISABLE (Tom Warzeka) 30. ukrainian update (Olexander Kunytsa) 29. DSPMBYTE=utf8 patch (Jean-Luc Leger) 28. fix ipv4 only compilation, remove extra sigsetmask() call (Takayuki Nakao) 27. window change can cause free to be re-entered causing abort (Mark Peek) 26. vp->vec vetting, suggested by Ian Dall. 25. V6.11.02 - 20020516 24. Fix prompt bugs in $var and %c0n (TAKAI Kousuke) 23. Add Cray SV2 config (Rafal Maszkowski) 22. Add pdf manual page (Warren Ferguson) 21. Fix REMOTEHOST lossage in with AF_LOCAL sockets (Tom Mander) 20. Fix win32 break because of TIOCSTI (Amol) 19. Fix TIOCSTI for hpux 11 (Igor Schein) 18. Avoid collapsing paths that refer to non-existent components (Martin Kraemer) 17. Make -shell invocations always treated as a login shell. 16. V6.11.01 - 20020308 15. Fixes to polish nls locale (Paweł Niewiadomski) 14. russian locale fixes (Alexey Dokuchaev) 13. document door support (Shaen) 12. tcsh euc handling extensions (Alexey Zelkin) 11. Make sure that jobcmd does not clobber the current job (Rob McMahon) 10. Make sure that the output of verbose and echo do not end up in the command output (Victor I. Pasko) 9. Add %j in prompt [needs more work; is not right the first time after proclist changes] (Hr. Peter Kruse) 8. `` commands with embedded newlines would ignore commands following the new line (Victor I. Pasko) 7. Re-initialize nls if NLSPATH is changed (Naoki Wakamatsu) 6. Fix 64 bit compilation with linux and resource limits. 5. Avoid double globbing when ls-F needs to fork (Joe Townsend) 4. put back csh filec compatible support. 3. add support for quads in xprintf in the presence of gcc. 2. unlimit should set rlim.rlim_max to rlim.rlim_cur if max < cur. 1. Make ~user work again when the home directory is '/'. 40. V6.11.00 - 20010902 39. Completion fixes (Tom Warzeka) 38. make c_insert not static so that it can be used from win32 (amol) 37. Fix rmstar not to corrupt memory when we say no. (Mark Peek) 36. V6.10.02 - 20010806 35. polish nls locale (Paweł Niewiadomski)) 34. Fix a tcsetattr race running background jobs as the last line on an xterm window (Andrew Brown) 33. jobcmd alias (Greg Parker) 32. hpux11 support (Joshua Weage) 31. Fix SHORT_STRINGS compilation (Daniel Trinkle) 30. Add kill -s (Mark Peek) 29. Don't recognize all mips as dec (Bjorn Knutsson) 28. Fix GLOB_QUOTE problem (noted by Per) I introduced in 6.10.01. 27. Port to concurrent's powermaxos (Matt Majka) 26. New builtin srcfile (Amol) 25. Fix bindkey "\\" cmd (reported by Ismail H. Tuncer) 24. %0Xc was broken in the prompt if the user's home directory was '/'. (reported by Edward Glowacki) 23. V6.10.01 - 20010426 22. LARGEFILE support on Linux. 21. Add big5 multibyte support (Yen-Ming Lee) 20. Check the return value of setpriority (Dima Dorfman) 19. Avoid constructing paths with // on DomainOS (Nickolai Zeldovich) 18. Russian translation (Ilmar S. Habibulin) 17. Fix hostdefs for alpha support in FreeBSD (Andrey A. Chernov) 16. Add door support in colorls (Shaen) 15. Add BSD_STYLE_COLORLS for FreeBSD (Anand) 14. MAXHOSTNAMELEN needs to be 256 (Kris Kennaway) 13. Document stty -tabs problems on compaq (Nelson H. F. Beebe) 12. Fix broken comment, and new versions of config.guess and config.sub (H.Merijn Brand) 11. fix redrawing in the recognize case (Andrew Brown) 10. don't call qsort with 0 items. (Luke Mewburn) 9. fix echo;echo;echo; not outputing anything (Andrey A. Chernov) 8. Fix shell word parsing in dabbrev-expand (Per Hedeland) 7. hpux fixes (Chienting Lin) 6. Implement kill ring (Per Hedeland) 5. Avoid core-dumping when a very long $HOME gets passed in (Kris Kennaway) 4. Add rlimit_vmem for linux based on rlimit_as (N KomaZaki) 3. back out symlink=expand path check. 2. Add Estonian translation (Toomas Soome) 1. Accept empty $savedirs to mean infinity. 57. V6.10.00 - 20001119 56. Completion fixes (Tom Warzeka) 55. add missing linux kanji define (Tsuyoshi Kawabe) 54. More WINNT_NATIVE fixes (amol) 53. Fix compile error on winnt (Yoshiyuki Sakakibara) 52. nonstopux configure and makefile fixes (Tom Bates) 51. V6.09.04 - 20001111 50. Order of initialization for multibyte display was wrong (HyunChul Kim) 49. Follow the guideline for linux for japanese locale: http://www.linux.or.jp/JF/JFdocs/Japanese-Locale-Policy.txt (Tomohiro KUBOTA) 48. Ukrainian nls map (Olexander Kunytsa) 47. exit immeditiately if we get an error while we are setting up (Michael Shalayeff) 46. (unset path; unsetenv PATH; rehash) -> crash (Kent Vander Velden) 45. change winnt to winnt_native (Randolph Fritz) 44. Support home/end in the editor (Andrey A. Chernov) 43. Typo s/gycwin/cygwin/ in tc.os.h (Andreas Schott) 42. Alpha ev6 addition (Karen R. McArthur) 41. DSPMBYTE patch from (Issei Suzuki) 40. Security fix for here-doc tmp files (proton@ENERGYMECH.NET) 39. Fix resource limit rounding *again* (Johannes Gross) 38. Fix $ expansion in prompt (Takashi Sumiyoshi) 37. V6.09.03 - 20000715 36. cygwin port fixes (Arihiro Yoshida) 35. Add a new "catalog" variable that specifies which NLS catalog to be used (Issei Suzuki) 34. cleanup and addition of page up/down (amol) 33. fix vfork compile problem. 32. use inet_addr instead of inet_aton for portability. 31. V6.09.02 - 20000704 30. lots more completions (George Cox) 29. change FILSIZ to BUFSIZE [now that BUFSIZE >> MAXPATHLEN] and avoid a potential buffer overflow in sh.dir.c (Volker Schmidt) 28. _MINIX_VMD port (Martijn van Buul) 27. inet6 handling for remotehost and configure (Hajimu UMEMOTO) 26. aix-4 does not need gethostname (Darren Reed) 25. IBM OS/390 Unix Systems Services support (Peter Prymmer) 24. Fix prompt formatting (Andrey A. Chernov) 23. Use HostType from Imakefile correctly (Kjetil Torgrim Homme) 22. Handle long and expanded history lines better (Boleslaw Ciesielski) 21. With symlinks=expand expand valid paths only (Martin Kraemer) 20. Make one-byte charsets work with KANJI (Andrey A. Chernov) 19. NT-specific executable detection moved to NT code (amol) 18. New "complete module" (Dan Nicolaescu) 17. Correctly display scaling string in limit error messages (Nathan Ahlstrom) 16. Don't display "unset watch" message when not appropriate (kim) 15. V6.09.01 - 20000114 14. Circumvent IRIX4D ESTALE bug by exiting. 13. IRIS4D de-linting. 12. Finnish nls catalogs (Jukka A. Ukkonen) 11. Even more multibyte fixes (Taga Nayuta) 10. Patches to statically link tcsh under solaris-2.6 (John Hawkinson) 9. Manual page typos (R. Bernstein) 8. HP/UX-11 (9000/800) HP/UX-10.20 (9000/820) (Haflidi Sigtryggur Magnusson) 7. Color-ls fixes (Luis Francisco Gonzalez) 6. Don't re-use time0 to compare to stat's st_mtime, cause it could be the value returned from times(2) which is the ticks since system startup (Frank van der Linden) 5. Time percentage wrap fix (Simon Burge) 4. EUCKR support (HyunChul Kim) 3. Grammar and typo fixes for tcsh.man (Steve Kelem) 2. More multibyte fixes (Rodney Ruddock) 1. Change 6.08 -> 6.09 where I missed it; update for utlrix 4.5 (Simon Burge) 65. V6.09.00 - 19990816 64. Add csh emacs mode (Dan Harkless) 63. Make sure the the glob buffer matches the word buffer size (Brian Biswas) 62. Fix periodic to work without tperiod set (Kenny McCormack) 61. V6.08.07 - 19990813 60. Fix e_dabbrev_expand (Bjorn Knutsson) 59. Make \builtin work again (by calling the command not the builtin) 58. Add NLS_BUGS for OS's that keep file descriptors open for NLS (Ian Dowse) 57. Make NONLSREBIND work after tcsh starts up. 56. Fix AIX stupid exit bug. (Dan Harkless) 55. More irix fixes (Kaveh) 54. V6.08.06 - 19990701 53. module command completion (Dan Nicolaescu) 52. Man command completion enhancement (Tom) 51. Fixes for irix configuration (Kaveh) 50. Support \a and \e in echo command. From (Keith Thompson) 49. Alpha configure nit from Kaveh 48. V6.08.05 - 19990511 47. In some system, when a builtin fails immediately after we start tcsh and before we print any messages, NLS messages fail (some descriptor might be closed) [FreeBSD, HP/UX?]. So we force reading the NLS catalogs in errinit() (Yoshiyuki Sakakibara) 46. typos in ja/set1 and ja/set29 (Yoshiyuki Sakakibara) 45. "dspmbyte autoset trap" support to HP-UX 10.20. (Yoshiyuki Sakakibara) 44. misnumbered NLS message in tw.help.c (Yoshiyuki Sakakibara) 43. colorcat variable for NLS color messages (Yoshiyuki Sakakibara) 42. autoconf fixes from Kaveh (and if it broke, me) 41. SGI irix fixes from Glenn Coombs. 40. Don't spin writing the history file when quota is exceeded (Rob McMahon) 39. V6.08.04 - 19990419 38. complete additions (John Gotts) 37. Port to amiga with geek gadgets (Arto Huusko) 36. Ignore case in setenv for windows (amol) 35. Bug fixes for NT unc stuff (amol) 34. Hash spell check (amol) 33. V6.08.03 - 19990211 32. Helpcommand documentation (Vladimir Alexiev) 31. small Y2K fix [%y in prompt would be formatted as 10 not 00 at year 2000], and new Itoa() code (Chris Torek) 30. OpenBSD m68k patches (Paul DuBois) 29. Avoid redefinition of getpeername on Solaris-2.7 28. fix problems with savedups=erase, savehist=merge (Randy Gobbel) 27. Don't set $shell to csh, if we were invoked as tcsh (Tomas Persson) 26. added $_ 25. added postcmd 24. V6.08.02 - 19981124 23. document continue and continue_args 22. wrong test in slowexec made NT optimization a noop (Amol) 21. Rhapsody fixes + separate CFLAGS/CPPFLAGS (Wilfredo Sanchez) 20. literals in both prompt at rprompt did not work properly (Taga Nayuta) 19. multibyte deletion fixes (Yoshiyuki.Sakakibara) 18. clean up key binding stuff for NT by moving the nt dependent code to the NT source (amol) 17. dspmbyte fixes for AIX, typos in man page and nls (Yoshiyuki Sakakibara) 16. Convex fixes (Ron Echeverri) 15. V6.08.01 - 19981025 14. SX4 port; this adds many casts for machines where ptrdiff_t is 64 bits. (Andreas Schott) 13. U/Win port; does not work properly with U/Win 1.6, wait for the next version (Chris Jones) 12. Sgi does not need gethostname prototype (John Bogan) 11. Logic in sh.dir.c was wrong for NT (Amol) 10. HP_CXD_SPP stat64 fixes (Scott Garee) 9. Documentation spelling fixes (Keith Thompson) 8. Documentation fix for savedirs (Amol) 7. Siemens OSD_POSIX fixes (Martin Kraemer) 6. include for all the BSD's (Trevor Johnson) 5. Multibyte display fixes for gnu ls (Taga Nayuta) 4. Configure/Makefile hesiod and bindir fixes (Dan Winship) 3. Use winnt not win32 in tc.os.h (Amol) 2. Cygwin32 port (Raj Menon) 1. Ported Fixes (Tom) 95. V6.08.00 - 19981002 94. where builtin nt fix (Amol) 93. V6.07.13 - 19980926 96. NT multibyte fixes (Amol) 95. NeXT needs getcwd. 94. fix new bug introduced by strncpy'fication in sh.dir.c (Taga Nayuta) 93. V6.07.12 - 19980918 92. add cray in configure script (Tom) 91. nls fixes 90. Avoid buffer overflows in directory code (kim) 89. Add multibyte character display support (Yoshiyuki Sakakibara) 88. Make tcsh use getcwd instead of getwd and supply a getcwd. 87. Fix remotehost again (kim) 86. V6.07.11 - 19980913 85. Leave remotehost ip addresses alone (don't try to resolve them) (Kim) 84. Read vs. force_read fixes (Amol) 83. Make colorls if color is set before the first LS_COLORS setenv (Taga Nayuta) 82. Use _PATH_DEFPATH on BSD4_4 systems. (Jim Bernard) 81. Cursor bounds checks (Michael Schroeder) 80. Syntax error nits (Michael Schroeder) 79. configure fixes (Michael Schroeder) 78. V6.07.10 - 19980904 77. Off by one error in NO_ERRORS... 76. Japanese NLS messages (Yoshiyuki Sakakibara) 75. Add ENXIO and EBADF in the test for write failures for Irix Zombies (Ralf W. Grosse-Kunstleve) 74. Missed a test for NOSTRCOLL in glob.c (Michael Liepelt) 73. Another ABSOLUTEP change (Amol) 72. Italian NLS messages (Massimo Bertozzi) 71. WIN32 fixes for ntslowexec and color_ls literal printing in prompt (Amol) 70. a few missed WIN32 merges (Amol) 69. defined YPBUGS for sgi (Kaveh) 68. V6.07.09 - 19980707 67. Separate the nt builtins (Amol) 66. completion fixes (Tom) 65. color ls fixes (Taga Nayuta) 64. V6.07.08 - 19980629 63. add config.h.in (Kaveh) 62. win32 updates (Amol) 61. warning and portability cleanups on the new changes (Kaveh) 60. V6.07.07 - 19980628 59. Fast execute by-pass for win32 (Amol Deshpande) 58. Clean up const usage a bit, and fix gcc 2.8.1 warnings. 57. Use @bindir@ for DESTBIN in Makefile.in (Edgar Hoch) 56. Avoid overflow in time builtin computation (Nobue Adachi) 55. Color ls additions (Taga Nayuta) 54. unsigned char vs. char warning fixes (Kaveh) 53. Solaris 64 bit fixes (fix directory offset bug) (Thomas-Martin Kruel) 52. More win32 patches (Amol) 51. autoconf lossage from (Kaveh) 50. V6.07.06 - 04/08/98 49. Collation fix for globbing (Andrey A. Chernov) 48. We might have NLS_CATALOGS and not LC_MESSAGES (Andrey A. Chernov) 47. 4.4BSD header fixes (Andrey A. Chernov) 46. Signed char prompt fixes (Andrey A. Chernov) 45. Pattern match fix for directory searches (Mike Patnode) 44. Pentium DGUX fixes (Miko Nahum) 43. Spanish nls message catalogs (Luis Francisco Gonzalez) 42. Fix trailing whitespace parsing in HASHBANG code (Martin Kraemer) 41. Remove stray debuggin message from unmatched substitutions. (from Amol Deshpande) 40. Fix reversed arguments in Usagae message. (from Amol Deshpande) 39. Fix bug introduced at tcsh-7.06.03 [expdollar] that affected %.n prompt format. 38. Fix typos introduced in last batch of changes. 37. Fix interrupted script using onintr, exiting parent shell problem. 36. Cleanup prototypes. 35. V6.07.05 - 10/28/97 34. Integrate Amol Deshpande's WINNT fixes to the tcsh source. Note that this is not complete yet; we are missing the NT glue code and the message catalogs. 33. Fix ^T at the first character in the line (Chuck Silvers) 32. Eliminate xsprintf and xvsprintf 31. Qmail patch from (Matthew Zahorik) 30. Added missing linux signals (Vadim Vygonets) 29. fixed problem where complete complete 'p/*/t:*.txt/' would not honor the pattern. 28. Port to an EBCDIC machine: BS2000 by Siemens Nixdorf that has an IBM/390 compatible processor (Martin.Kraemer) 27. Detect when we have errors writing to stdout (Vadim Vygonets) 26. Ignore quotes in the comparisons for builtins, so that \builtin works (Amol Deshpande). 25. HPUX, portability fixes; make sure that we have the right config file (Jonathan Kamens) 24. Don't do lookups for x displays and figure out ttys properly (Leonard N. Zubkoff) 23. make print_by_columns print in a single column when the output is not a tty 22. use rlim_t for Solaris2 (Casper Dik) 21. V6.07.04 - 05/04/97 20. set -f -l patch (Michael Veksler) 19. SGI patches (Tomasz J. Cholewo). Also fix completion code to take into account aliases that start with a period. 18. SCO patches (Boyd Lynn Gerber) 17. Fujitsu patches (Toshiaki Nomura) 16. autoconf patches (Kaveh Ghazi) 15. BSDI patches (Paul Vixie) 14. %Q formatting character addition. 13. Fix set=#123; echo $i:s/#// (Quoting problem) 12. V6.07.03 - 02/23/97 11. Understand %$variable in the prompt. 10. Quote directory names properly in .cshdirs 9. USE_ACCESS and autoconfig patches from (Larry Schwimmer) 8. Pyramid att config file (Andrew Lister) 7. $rprompt code (Luke Mewburn) 6. Kanji patches (Huw Rogers) 5. Cray T3E port (Jorn Amundsen) 4. Avoid html redirects in tcsh.man2html (from Kimmo) 3. HP/UX 10.0 fix for filesize resource limit; don't scale by 512 anymore. 2. Workaround for TIOCSTAT for NetBSD from lukem@netbsd.org 1. Return exit status from 0..255 not -128...127, as POSIX mandates. V6.07.02, 10/27/96 58. More configure fixes from Kaveh. 57. Fix histdup=erase again: Don't renumber events, or access uninitialized storage. 56. 6.07.01 - 10/19/96 55. Fix histdup=erase, where after some repetitions, we would get negative history events (kim@gw.com) 54. NLS fixes and typo in sh.err.c (Martin.Kraemer@deejai.mch.sni.de) 53. Output history in raw format in the history file (mveksler@VNET.IBM.COM) 52. Fix possible core dump when !: in autoexpand mode (rbrown@ERA.COM) 51. 6.07.00 - 10/11/96 50. Avoid stdio.h inclusion problem in SCO (gethost.c). 49. A bit of housekeeping in host.defs 48. 6.06.04 - 10/05/96 47. Fix tellmewhat() code to return true if found. 46. Change register foo to register int foo to avoid compiler warnings. 45. Fix problem with sticky non editing mode from Casper Dik. 44. history lex fix from Martin Kraemer; history events that ended with 0 were not properly parsed. 43. SNI fixes from Martin Kraemer. 42. SGI fixes from Ralf W. Grosse-Kunstleve. 41. BSDI2.1 fixes from Paul Vixie. 40. 6.06.03 - 09/24/96 39. undef TIOCGLTC for HP/UX 10.0 from Michael Shroeder 38. Sinix fixes 37. 6.06.02 - 06/22/96 36. Added implicitcd 35. Added configure.in and Makefile.in from Kaveh. 34. unset path, unsetenv PATH, ./foo did not work. 33. Add VAR_NOGLOB, and use it to avoid globbing directory names when cd'ing into them. 32. Fix bug introduced in the new tty parsing code. 31. Avoid pushing string back to the parsing string in ${ errors. 30. Patches for the manual page from Dave. 29. 6.06.01 - 05/24/96 28. Use sysconf to get NCARGS if available Robert Daniel Kennedy 27. Grab the program name and use that instead of tcsh in error messages. 26. Fix histdup, so that it does not leave gaps in the event sequence. 25. HP/UX v10.0 fixes: Don't use bsdtty.h and avoid clobbering memory since SIGRT??? is defined as -1. 24. Avoid coredumps when $TERMCAP exceeds 1024 characters Michael Schroeder 23. Fix memory clobbering when SHORT_STRINGS is not defined. Todd J Derr 22. Only restart stopped editors. Robert Webb 21. Recognize pts sysv ptys when checking to set autologout Bob Myers 20. Magic space incomplete modified core dump fix. Chris Metcalf , Bradley White 19. Linux nls fixes Rik Faith 18. SGI RS8000, Ported notes. Ralf W. Grosse-Kunstleve 17. Greek nls messages. Aggelos P. Varvitsiotis 16. Imakefile linux and libcrypt fixes. Jonathan Kamens 15. FreeBSD fixes Jukka Ukkonen 14. Expand the environment space for path Steve Kelem 13. Don't overwrite the environment randomly Steve Kelem 12. Don't turn the editor on when we have dumb or unknown terminals. This breaks emacs when compiled with terminfo Jonathan Kamens 11. Fix F- parsing in tc.bind.c (Bob Meyers) 10. Added -T option in history to force timestamp printing. -h alone does not print timestamps anymore for compatibility with csh. 9. Typo in tc.bind.c [with -DOBSOLETE] (misplaced parenthesis) 8. Recognize convex models properly. 7. suppress the DING! option using the noding variable. 6. negative nice values did not work. 5. Harris CX/UX 7.x support. 4. ERR_DMMODE was used on the crays but not defined. I changed the error messages in tc.os.c to use ERR_STRING instead, and fixed a missing error message in the catalogs. Someone will need to retranslate #30 and #31 in set23. 3. Bug setting listflags... Workaround: set listflags=(A /bin/ls) 2. Typo in Imakefile (# comment instead of c comment) 1. Typo in ma.setp.c (missing parenthesis) V6.06.00, 05/13/95 88. Cleanup off-by-one error ed.defns.c. 87. 6.05.09 - 05/06/95 86. Small memory leak in dosetenv() 85. Make sure that the number of editing functions defined is correct and abort otherwise. 84. Completion Fixes from Tom 83. Don't add yp stuff in the tilde cache [names that start with + or -] 82. Don't let children catclose() in xexit(), because the parent will lose access to the nls catalogs. From Michael. 81. 6.05.08 - 04/29/95 80. Update to the newest csh sh.file.c 79. More completions from Tom. 78. Fix the Imakefile to use XCOMM 77. Update for AIX 3.2. 76. French catalog from J.M.Vansteene@frcl.bull.fr (fwd Michael Schmidt) 75. Nls fixes and small typos from Michael 74. PDP11 BSD type fixes. 73. More manual page fixes. 72. 6.05.07 - 04/19/95 71. More NLS catalog fixes. 70. Bruce's jumbo patch. 69. 6.05.06 - 03/15/95 68. make clean does not clobber config.h if Makefile.std is used. make veryclean does. 67. New config define NISPLUS. Reportedly fixes vanishing output of ~expansion on solaris 2.4. 66. showdots has been removed; use listflags instead. [handles -x too] 65. more nls catalog fixes. 64. set histchars=,. did not have any effect in .cshrc 63. fix "-c command" new core dump. 62. more completions from Tom 61. call catclose() before exiting, so that svr4 cleans up the symlinks before exiting. 60. Per's fix for insert-last-word 59. Per's emacs abbreviation mode. 58. Makefile fixes for catalog stuff. 57. fixed again complete-word-raw and list-word-raw 56. 6.05.05 - 03/11/95 55. Made %?str work again 54. IRIX sigalarm problem should be fixed 53. complete-word-raw and list-word-raw should work 52. nls catalogs complete reworking. 51. sh.init.c: Signal complete rewrite. 50. Signal fixes from Bruce. 49. Added promptchars, like histchars; affect %# in the prompt. The first char is for the user and the second is for root. 48. 6.05.04 - 03/03/95 47. Add NODOT config, $command [that holds the command passed with -c] $GROUP and $group 46. AFS fixes from Larry Schwimmer 45. Real NLS catalogs from Michael Schmidt 44. patch to allow ^? binding. 43. completion patch from Paul DuBois. 42. Don't spell check in here docs. 41. Incorrect normalization of usec in sh.time.c 40. directory printing and option parsing fixes [from Paul DuBois] 39. realloc_searchlen should be static to avoid conflicts with OS's that use the same malloc package. 38. LOGINFIRST now applies to /etc/csh.login 37. Fixes in bind compatibility code to bindkey. 36. 6.05.03 - 01/17/95 35. Don't print the whole watchlist on startup. One can use explicitly the log builtin for that. 34. Don't display the $watch value in the log command. 33. Don't delete the unmatched portion if we try to complete a spelling error. 32. Solaris 2.4 workaround for isprint('\t') lossage (From Casper) 31. Fixed csh bug: [Reported by Jaap] set test="one\ two\ three" echo "$test:q" 30. Fixed the lossage in setting the looking mode in tw.parse.c before calling t_search; $x/$y will not append the right suffix. 29. Another attempt at the gethost timeout code. 28. Cray dmmode and filetests -m -k [need documentation!] 27. More manual patches. 26. Don't glob the path; security problem and core-dump. [from beto] 25. Avoid waiting for jobs that failed to restart, thus hanging the shell. eg, run job in background, attach to debugger; kill it inside the debugger. Get out of the debugger and you are stuck if you fg that job. 24. 6.05.02 - 09/04/94 23. remhost code could pass the wrong length to getpeername() 22. too eager sed'ing broke convex getwarpbyvalue() to getwarpbyvarval() 21. Fixed new bindings bug. 20. Fixed bug in newgrp code; execv was called incorrectly. 19. Take into account programmable completion hints when spell checking. 18. Unconditionally change stty modes in Rawmode() 17. Change date in $version to be ISO 8601 per Keith's suggestion 16. Fixed portability problems in the new counted-strings codes (From Kaveh) 15. Fixed binding problem with the new counted-strings code [all key bindings ended up in the extended map] 14. 6.05.01 - 07/08/94 13. Changed key bindings to use counted strings instead of Null terminated strings, so that binding ^@ works. 12. Fix parsing bug, where words that contained keywords caused incorrect word breaks: switch (iftagd) case iftagd: echo It works breaksw default: echo It is broken. endsw 11. Fix sh.c for systems with no job control. [the new hup builtin sends SIGCONT]. 10. Don't add the suffix character when all completions fail, from michael 9. Added histdup=erase, that deletes the oldest duplicate instead of the newest. 8. Don't call .logout recursively if we receive more than one hup, and don't process hangups when we execute the .logout. 7. $logout was set to a static string. 6. Non printable binding listing was broken. 5. Recursive sourced scripts would get mangled up because of input buffer confusion (thanks michael) 4. M-space should not be counted as a space. Leads to infinite loop in word splitting. 3. Pyramid fixes. 2. Fixed '\' in sysv echo (from Mika) 1. Missed fix_yp_bugs() when setting REMOTEHOST (From Casper) V6.05.00, 06/19/94 113. 6.04.17 06/18/94 112. Realloc debug fix from John. 111. Completion fixes from Bruce. 110. Added -b option to bind. 109. Added tcsh.man2html from Dave. Looks great! 108. 6.04.16 06/06/94 107. Allow multi word glob in "`foo`" expressions. > if ("`ls`" == "a b c") then 106. Michaels lex() buffer patch version 2. the previous version core-dumped with > sleep | echo 105. Fix seg fault in find_cmd, when path is unset. 104. 6.04.15 05/28/94 103. the previous =~ fix, was a bit broken. 102. 6.04.14 05/25/94 101. expression parser fix for !~ and =~. if (foo =~ *) echo ok the * was taken for a multiply and parsed as 0 * 0 returning 0. and asked to match "foo" with "0" 100. Michael's lex() buffer patch. 99. Bruce's Jumbo cleanup 98. fixed Imakefile for X11R6 97. fixed argument parsing in source command. 96. added $sched to format scheduled events. 95. 6.04.13 05/07/94 94. added expand-command 93. Alpha OSF-2.0 fixes 92. 6.04.12 04/28/94 91. Ignoreeof patch from Bruce. 90. Dan's completion fix. 89. 6.04.11 04/12/94 88. Don't source .logout when killed with -HUP unless we are a login shell. [ actually $loginsh controls the behavior now ] 87. ISC-4.0 posix exec() bug workaround (from Jonathan Broome ) 86. Dan's patch for complete=enhance 85. Kaveh's patches for memset, host.defs, _{U,G}ID_T 84. 6.04.10 03/29/94 83. Pathname completion bug fixes... 82. Completion pathname(p) changes: Completion 'C' -> 'X'. Replaced 'p' with 'F' and added D,T,C. 81. Next NLS fixes (From Paul Nevai ) 80. make spelling correction obey the current histchars setting. 79. Fix rounding in limits so that 0 is a true 0. (From Ken Lalonde ) 78. 6.04.09 03/12/94 77. Alarm race with remotehost. 76. If you have in your .cshrc set savehist=(100 merge) and execute #!./tcsh exec ps you get no output; [fixed] 75. setenv SHLVL -1; tcsh = Segmentation fault [fixed] 74. 6.04.08 02/10/94 73. new machtype, ostype, vendor 72. execute .logout on hangup. 71. more man page fixes. 70. 6.04.07 02/04/94 69. Dynamic hash changes, globbing for which command from Michael. 68. INBUFSIZE fixes for history. 67. printenv returns 1 when a variable is not found, like the non builtin one 66. Add quotes to the mismatch array so that: > touch foo > mail "oo bar" does not get corrected. The right fix would be to do correct parsing and quote the space... 65. NULL terminate mismatch[] array in ed.inputl.c, since it is used in Strchr(). 64. renamed stat to filetest 63. Afs and Hesiod patches. 62. More manual page patches. 61. 6.04.06 12/19/93 60. Alarm for resolver timeouts (untested) 59. Fixes for Henry Spenser's regex in the Makefiles 58. Modifiers now work with $< and $< does not do :q by default. [incompatibility with csh] and $< can be interrupted. 57. Added $histdup. 56. source /etc/.login for Solaris 2.x 55. don't remove trailing spaces in history searches. 54. dirs -L and dirs -S spurious warning elimination. 53. man page fixes from David. 52. Kimmo's patch [makefile, gcc warning, netdb.h include] 51. 6.04.05 12/12/93 50. rewrote srcunit() to use st_save and st_restore. The code was too messy to be useful before. 49. recdirs and rechist patches again! 48. Harris hck port, and ISC imake update 47. Eliminate the x windows :display.screen before looking for the hostname in REMOTEHOST 46. Patch for CDF filetype() recognition (hpux) 45. 6.04.04 11/12/93 44. Made =x obey nonomatch. 43. Fixed rechist and recdirs not to depend on savehist and savedirs 42. Removed aliases, bind, linedit builtins [ifdef'ed out as OBSOLETE] 41. change REMHOST to REMOTEHOST for compatibility with SGI. 40. $owd was not working correctly. 39. Debugging printf elimination (from Kimmo) 38. Typos in the new hup code in sh.c (from Matt) 37. Imakefile fix for sequent (from Jaap) 36. 6.04.03, 10/30/93 35. New manual page in place. 34. Fixed Makefile sed RE to work with gnu sed. 33. Added hup builtin. 32. Added $REMHOST in config_f.h 31. Fixed random parsing bug in sh.exp.c in isa(). It checked cp[1] without checking cp[0] first... (should propagate to 4.4BSD) 30. More sh.exp.c fixes from Bruce 29. Always exit when the user types exit. cat | tcsh -f -s exit ls 28. savedirs fix and readlink() null termination fix from Peter. 27. Added -p flag (force dirs printing in all directory functions and $owd variable 26. Let $dirstack work by default without needing to be set. 25. Fixed history -h to work with other history flags. 24. Renamed ed-functions more consistently (dcs) 23. Added missing filetests (dcs) 22. Added NEWGRP define in config_f.h (dcs) 21. More fixes for non blocking io recovery from Bruce 20. 6.04.02, 10/08/93 19. changed default prompt to %# 18. New group 'g' completion. 17. removed IIASA defs. 16. fix for history -SL and dirs -SL to work when savedirs and savehist are not set. 15. fix magic-space to understand :p 14. make :u,:l work for history. 13. Fixes for non-blocking i/o recovery. trap all non blocking styles under sunos. 12. 6.04.01, 08/10/93 11. Vi mode word moves [they work like vi and don't obey wordchars anymore]. 10. New file operators and stat builtin 9. David's FIONREAD patch for SVR4 8. Bruce's ignoreeof=n patch 7. Dan's complete/correct enhancement 6. Abort corrections patch. 5. Print_by_columns, now does not use the rightmost column. 4. Renamed config/config.$i to $i to avoid once and for all filename length problems. 3. bbn butterfly config 2. Beto's proc fixes 1. Bruce's bug fix for ed.chared.c, signals V6.04.00, 07/03/93 92. Alpha prototypes, for gcc -Wall clean compile. 91. Fixed alpha hashing. Did not work for directories > 31, Thanks to Dan Mosedale for all the help! 90. Added USE(a) for unused parameters, to avoid compiler warnings. 89. 6.03.10, 06/25/93 88. Makefile and lint patches from Bruce. 87. Posixsig patch from Peter for svr4 86. 6.03.09, 06/11/93 85. signal handling broke with the last job control patch... > (does-not-compute;) would hang. 84. don't quit after the first modifier fails: > set i=aabbcc > echo $i:s/a/A/:s/b/B/ AaBbcc > echo $i:s/x/A/:s/b/B/ aabbcc 83. Imakefile fixes for sequents from Jaap. 82. Move past the bottom of input when we hit ^C, so that multi-line input commands don't get trashed. 81. Look only at the first word in ${EDITOR,VISUAL} to determine the editor name. 80. Last patch broke listmax. 79. Remove extra sandbagging in exitstat(). Not needed anymore as value() will never return NULL. 78. Save $status before calling aliasrun() otherwise: > alias precmd 'cd .' > true > echo $status 0 > false > echo $status 0 77. 6.03.08, 06/07/93 76. missing prototypes/unused variables under SYSV4. 75. savedirs should glob the filename argument. 74. 6.03.07, 06/05/93 73. Changed _Q, _Q1 macros in sh.lex.c, sh.dol.c, sh.char.? to _QF and _QB because today 4.4BSD defined _Q to be ``Phonetics'' 72. listmaxrows variable. 71. set -r would not make existing variables readonly. 70. print usernames with ~user where possible in dirs and job cwd's 69. Mika's fixes (missing args in sh.c set(), linux Makefile, SIGCHLD) 68. FIONREAD argument is int everywhere except on SunOS where it is long. Tcsh used to think that it was long, and so it broke on the alpha where sizeof(int) != sizeof(long) 67. 6.03.06 05/16/93 66. Pipeline fixes. This should get rid of the dreaded Stopped tty output message. 65. Michael's fix for history buffer cleanup: > alias foo 'echo \!:1:h' > foo a/b a > ^P [nothing happens] 64. Unsigned long rlimit type for 64 bit machines (alpha) 63. Fixed Imakefile for alpha 62. tilde expansion now obeys $nonomatch 61. readonly veriables. 'set -r x=3' will set x to a very sticky 3... 60. Fixed bug in the new tab'ed completion that interfered with old listing. 59. Fixed entry -> item in tw.parse.c 58. Added -f option to unlimit 57. Define __STDC__ in Imakefile for Irix 56. Static redeclarations in tw.parse.c 55. 6.03.05 04/26/93 54. Don't echo history expansion in loops: > alias junk 'foreach i (\!:2*) \ foreach? echo \!:1 $i; \ foreach? end' > junk a b c d echo a $i ; a b echo a $i ; a c echo a $i ; a d 53. Added complete-word-fwd and complete-word-back that scroll through the list of possible completions... Neat addition from jfink@csugrad.cs.vt.edu (Jeff "$DOTDIR" Fink) 52. Workaround hpux9.01 broken optimizer in sh.glob.c where 'ls *' breaks. 51. Michael's editor fix. With "magic margins" and 80 char width, try: > set prompt= 20aa76bac 50. Reverted fix that does not glob the expanded back-quote text again. 49. > cd /., echo $cwd /. Eliminate the . in this case... 48. Matt's optimization in glob.c [retracted] 47. Fixed bug with -S 46. Renamed Makefile Makefile.std, and fixed the readme file 45. 6.03.04 04/07/93 44. Changed -s == !-z and -S == socket 43. Fixed typo in sh.c, in phup [shpgrp != pr->pgrp] 42. Multi-line aliases are not entered into the history when executed. 41. Changed f_seek to a union to avoid gcc warnings on 4.4BSD 40. Fixed 'unset home; dirs' bug 39. fixed $HOME->$home memory problem. 38. $?0 returns false now on interactive shells for csh compatibility. 37. Default watch inteval was 10 hours not 10 minutes as advertized in the manual! 36. Fixed clobbered veriable warning from gcc-1.39 in tw.parse.c 35. Fixed typo with INVPTR in sh.lex.c 34. 6.03.03 03/04/93 33. Eliminate 'Reset tty pgrp error message'. It is normal for the walking process group stuff. Check about the killpg() above? 32. More portability for 64 bit machines. 31. Improved completion error messages. 30. Fix bug with double globbing expansion on mirrored variables: > setenv TERM '?vt100' 29. Avoid hanging when writing to pipes etc. (From Paul Close) 28. Typo in the $HOME->$home mirroring. 27. %p %P 'p'recise time formats that include seconds for prompt strings. 26. Signal list fixes from Paul Close. nsig is now a variable. 25. 6.03.02 02/12/93 24. NEC SX3 "entry" is a reserved word!, changed entry to item... [this is as bad as cray typedefining "word" to int. Next thing I know, I'll have to prefix all the variables with tcsh_!] 23. xxx 22. Protected all include files to avoid warnings from lcc. 21. Finally resolved the job control problems with linux and ISC (from Beto) 20. More HUP,XFSZ,XCPU fixes. (with Beto) 19. Dcanon would not canonicalize correctly in case where dnormalize() failed to find a directory, but the directory existed when not crossing the symbolic link. 18. sh.init.c fixes; give 65 signals for all POSIX machines. 17. AMS mail fixes and cmu wm handling. 16. Setenv would not ignore trim quoted names... > alias foo 'setenv "\!:1" bar' > setenv FOO 123 > foo FOO > printenv ... FOO=123 FOO=bar ... 15. 6.03.01 08/01/93 14. #undef SHORT_STRINGS gcc warning fixes... 13. csh bug fix in foreach [quoteing problem] > foreach i ("*") > echo $i:q > end Should print * 12. ls-F obeys showdots... 11. After scheduled commands get executed, the editor could stay disabled until the first enter. 10. sigset() bug in ed.init.c; ^C could get disabled sometimes. 9. Don't glob in dowhich(); otherwise \pat does not work if pat is aliased. 8. When completion patterns are used $ and ~ expansion did not work right. 7. Printenv builtin and long backquote expansion fix from Harald. 6. $:-1, $:-0 enhancement from Paul and Michael. 5. Lynx/OS patches 4. Apollo bugs [Setenv -> tsetenv, typedef in pid_t] 3. ^@ did not work correctly in bindkey. 2. Fix vms/posix ifdefs in tc.alloc.c 1. Elide gcc-2.3.1 warnings V6.03.00, 11/20/92 102. Solaris2 patches, renamed sunosX to sosX to fit in 14 character filenames. 101. 6.02.12 11/12/92 100. Decreased BUFSIZE to 1K... 99. Don't use sbrk() in tc.alloc.c on VMS 98. EINTR error handling from Michael 97. Overwrite mode takes effect immediately, not delayed by a command. 96. Emx fixes. 95. SIGHUP gain... 94. Coherent times()/ fixes. 93. 6.02.11 10/27/92 92. Mach setpath fixes. 91. Which now globs its arguments 90. Again POSIX SIGHUP fixes... Maybe we got it right this time... 89. Increased BUFSIZE to 4K. Smaller machines may want to decrease this. [ Now one can edit up to 4K of buffer! ]. From Harald. 88. : is now a true builtin that does nothing, instead of being treated like the last character of a label. This is so it can take args. From Harald. 87. More fixes for hpux limits from Harald. 86. Login shell if ppid == 1 and argc == 1 for VMS. 85. Typo in sh.exec.c from Harry. 84. Per's editor fixes. 83. 6.02.10 10/17/92 82. Don't free STRNULL in freelex(). Update linked list in copylex() to do the same insert as in lex(). 81. Fixed spurious tilde printing in %c prompt. 80. Fixed dumb wild free in AddXKey... (thanks Harald for the complex bindings! :-) > bindkey "\e10z" expand-line # Any editor command will do > bindkey -[cs] "\e10z" "foo" # Any string or command will do Free(%x) .... 79. coherent additions. 78. fixes for hpux8 resource limits [Thanks Harald] 77. 6.02.09 10/10/92 76. More vms cleanups. 75. Removed #include CONFIGH from sh.h. There was no way to make it work under VMS/POSIX 74. Added t completion (Gray Watson) 73. Memory leaks in sh.dir.c and sh.glob.c [thanks purify :-)] 72. IRIX 5.0 patches (from Paul Close) 71. BSD resource limits for hpux8.0 (From Andreas Stolcke) 70. NGROUPS_MAX fixes (from Matt Day) 69. 6.02.08 10/04/92 68. VMS port additions. 67. Added $%var, which == strlen(var) 66. Added ^X^I and ^X^D to override programmable listing+completion 65. Added case insensitive globbing for OS/2 64. FIOCLEX and FIONCLEX are only used if we don't have FD_CLOEXEC. 63. Added emx termio support, and emx pathsep support; emx compiles and runs: needs job-debugging and finishing touches. 62. Horrible bug with the lex linked list; from Loic Grenie, grenie@ens.fr > echo a !# echoed 'echo a echo a echo'! 61. Shell -w,-x were incompatible with the same for test [POSIX] (beto) 60. builtin newgrp did not accept the - argument. 59. FIOCLEX for the masses (POSIX FD_CLOEXEC addition) 58. Old style csh completion bug fix [not used] (beto) 57. A background process waiting for input from tty blocks when being foregrounded doesn't read its input and doesn't get and signals. It can only be killed from another session. (beto) > cat > foo #!/bin/csh -f echo ">>>>>>" set x = $< echo $x ^D > chmod +x foo > foo & > fg ^Z,^C # Nothing happens 56. history > 1000 fix (beto) 55. 6.02.07 9/18/92 54. Added e_stuff_char() to put back a character in cooked mode in the input stream... Useful for status (^T) 53. $? == $status and $# == $#argv like in the bourne shell. 52. Added $dirstack. Problems: off by one since =0 == $cwd, but $dirstack[1] == $cwd... Suggestions welcome. 51. Leading spaces would confuse the run-help function. 50. Don't expand imported environment variables: > setenv HOME \* > tcsh > echo "$home" > echo "$HOME" 49. %C0n displays the number of directories omitted as /usr/local/bin /<2>bin/ 48. Added POSIXSIGS as a configuration option. 47. Per's fixes for history format and arrow key binding. 46. Expand-variables expands array variables too 45. 6.02.06 8/14/92 44. Separated limit stuff from BSDTIMES and added BSDLIMIT 43. History searching inconsistent with HistLit: > echo foo foo > ^foo^bar bar > ec[M-p] echo foo 42. 6.02.05 8/8/92 41. sourcing a script that contains 'onintr -; onintr' would disable interrupts on the command line 40. cd ../... with symlinks=ignore would work !@#!@ 39. No more BACKPIPE for POSIX machines... 38. SUNOS NLS bug workarounds... 37. New HASHBANG define for #! emulation... even 386BSD does not have it yet... 36. Added new -b -c file operators from SGI csh. 35. 6.02.04 7/23/92 34. Walking process group fixes. 33. $0 contains now argv[0] when we are not executing a shell script. 32. New Getwd() was broken. 31. 6.02.03 7/17/92 30. We kill our last foreground process group on HUP, for POSIX systems. 29. Walking process group fix. 28. $shlvl gets reset to 1 for login shells. 27. Macros can now involve multiple commands, i.e. bindkey -s "^[OP" "ls\n^P" 26. 6.02.02 7/6/92 25. nostat accepts now a list shell patterns. 24. Avoid print_exit_value in if ( { foo } ) 23. Symbolic key names for bindkey [arrow keys]. 22. Smarter getwd() that avoids some of the NFS hangs... 21. Use memmove() where possible. 20. 6.02.01 6/16/92 19. Fix automatic correction to work with the new completion. 18. Globbing bug with brace expansion, when arguments need to be realloced... e.g. echo 134{6,7}{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9} 17. shift and left operators update variables correcly ('shift path' did not work) 16. apollo fixes for cd. 15. STRNULL <-> NULL bug fixes. 14. %S in xprintf for short strings. 13. history -LSc, dirs -LSc additions, builtins builtin [oxymoron] 12. history formatting string, who formatting string, prompt formatting all use tprintf() now. 11. $history accepts a second formatting argument.. 10. History timestamps preserved in .history 9. Backquotes were broken: echo hi | cat > `echo foo` 8. SGI -t operator problem. 7. Dnix fixes. 6. Fix history file writing bug when autologout. 5. Change from TCSETA to TCSETAW, since we affect the output. 4. Per's fixes for display margin bugs. 3. Linux fixes. 2. Collapse adjacent stars in glob.c to avoid exponential behavior. 1. Fixed parseescape to put ^ literally if not followed by alpha. V6.02.00, 5/15/92 94. Default echo_style was not being set correctly. 93. $< did not work correctly with NLS chars. 92. 6.01.15 (5/11/92) 91. Minor cleanups in refresh code. 90. 6.01.14 (5/8/92) 89. Print \n in the right margin always to be consistent. 88. Linux patches. 87. 6.01.13 (5/2/92) 86. Fixes in listing and completion of non-unique commands. 85. Fix =stack entries > 9... from Bill Petro 84. Fix for last character at margin. [on terminals that have am & xm move the cursor manually to the next line] 83. Fix for complete completions 82. small typo in tc.alloc.c from Mark Moraes. 81. small typo in tw.parse.c from Richard. 80. Man page fixes from Per. 79. 6.01.12 (4/24/92) [release version for 6.02] 78. Autosuffix was not getting reset all the time. 77. Don't limit completion patterns to 1K. 76. Naming changes in ed.screen.c from Justin. 75. 6.01.11 (4/10/92) 74. Fixed magic-space ! expand bug: > echo a b123 45.{6,7} > echo !:2!:3[magic-space] 73. Work-around for apollo optimizer in tc.bind.c 72. Problem with setjmp in tw.parse.c 71. symlinks=expand from Yumin. 70. tenematch() fixes from Michael; 69. 6.01.10 (4/3/92) 68. Fixed Gnmatch. 67. Removed ignore_symlinks and chase_symlinks. Replaced by symlinks variable. 66. Backquote from completion was broken for machines with no dup2() 65. No $printexitvalue for `` jobs. 64. Added ultrix stuff for PW_AUTH [from Mike Potter mpotter@lampf.lanl.gov] 63. Fixed bug in Gnmatch(), added 'N' command 'x' completion. 62. Fixed fg_proc_entry() so autologout gets disabled when a process is foregrounded. 61. 6.01.09 (3/26/92) 60. source builtin takes arguments now that are passed in the script e.g.: > ./tcsh -i a b c > cat test echo $argv > echo $argv a b c > source test 1 2 3 1 2 3 > echo $argv a b c 59. Eliminate $margin_bug, add more intelligent margin code [from Justin] 58. expand_symlinks variable Urgh... 57. SGI CONTROL() fixes... 56. new dnormalize(), expand_symlinks flag. 55. interrupting completion restores the current line. [from Marc] 54. 6.01.08 (3/20/92) 53. inputmode affects the first line too. 52. Searches in vi do not destroy the current line. 51. -drwX test enhancement. 50. Generalized completion syntax and added more completion builtins. 49. Don't print '\n' on the right margin if we can avoid it. 48. 6.01.07 (3/9/92) 47. New completion style. [[[ ]],=] 46. 6.01.06 (3/7/92) 45. complete styles are ignored after shell metachars eg. > complete mail =u > mail christos < [tab] completes filenames. 44. $echo_style is initialized to the default style of the machine. 43. SGI 4.0 CTRL() macro is busted. So we ignore it. 42. Fixed bug with the new margin code (thanks justin) 41. Fixed mirroring of variables. Now set and setenv affect HOME, TERM, PATH, SHLVL, USER and their csh counterparts. Unset affects affects only the csh copies of the variables, and unsetenv only the environment variables. 40. Fixed gcc-2.0 warnings in sh.sem.c (needed for vfork() -O2 optimization) 39. 6.01.05 (2/21/92) 38. signal masking for BSD machines was still wrong in tw.init.c 37. Added $margin_bug, and now the editor outputs on the rightmost column by default. This should fix the xterm cut-n-paste problem. 36. AU/X 2.0 and SGI compiles with POSIX as a default now. 35. sysv_echo is gone too. Now we have a variable called echo_style which can be set to "none", "bsd", "sysv", "both" that defines the builtin echo_style. The default is "bsd" for systems with SYSVREL == 0, "sysv" otherwise. This can be overriden in config.h by defining ECHO_STYLE ro be BSD_ECHO, SYSV_ECHO, BOTH_ECHO, or NONE_ECHO. 34. asynchronous notification in run-fg-editor would try to change the tty settings and print an extra prompt. > set notify > sleep 10 & > vi^Z > ^[^Z 33. alias x /bin/true x? reported .//bin/true instead of /bin/true 32. 6.01.04 (2/12/92) 31. fixed vi_substitute_line 30. binding completion addition. 29. showdots=-A addition 28. sysv_echo addition; deleted bsd_echo which is now the default. 27. dunique could crash. 26. Don't clear lines after an asynchronous notification, because it might erase the message. 25. 6.01.03 (1/29/92) 24. `` were not working correctly when tcsh is started with 0,1,2 closed. 23. Correction was picking up the wrong thing in cases like .rhosts hosts 22. Correction with names with quoted spaces was broken. 21. Added sysv_echo and bsd_echo. 20. Added and documented the complete builtin. 19. Added dunique and cd -. 18. Per's fix for alarm functions. Things would break if time went backwards. 17. Realloc bug fix (copy min of old and new size) 16. Fix for csh compatible braces. 15. Brace globbing and negation globbing for Gmatch. 14. 6.01.02 (1/16/92) 13. Completion builtin, new tw* files. 12. 6.01.01 (1/6/92) 11. Changed w_ fields in tc.who.c to who_ to avoid redefinitions in in some os's. 10. Setting savehist to an empty string makes savehist use the value in $history. 9. echotc did not use the internal termcap descriptions. 8. echotc did not work right for single argument termcap strings. 7. DGUX needs SAVESIGVEC, updated type protection, and disabled CSWTCH. 6. Changed SVID to SYSVREL, since there is no SVID == 4 (yet). 5. Typo in tc.sig.h: UNRELSIGS was not getting defined. 4. Globbing bug fix. tglob() should ignore globbing characters inside backquotes otherwise things get expanded twice: % echo 'bar?' > 'foo?' % echo `cat foo\?` echo: No match. 3. Mach setpath fix. 2. Alliant process group fix. 1. Xenix fixes for broken vi and help path with no suffixes. V6.01.00, 12/19/91 [for comp.sources.unix] 22. Restore the original prompt in automatic correction when the user asks to re-edit the command. 21. Better error for unreadable files in tw.parse.c 20. Sequent patches. 19. (V6.00.08 beta 12/14/91) 18. Filenames containing # were spelled/expanded incorrectly. 17. Stellar/stellix port. 16. Hpux 8.0 has SIGWINDOW but we cannot get the window size. Protect against window changes updating $LINES and $COLUMNS. 15. Mach setpath did not work right. 14. Mach does not need setenv in lib; in fact that does not work right. 13. shell level gets decremented when we exec. 12. restart_fg_editor picked the wrong editor if arg contained a slash. e.g vi ~/.cshrc 11. (V6.00.07 beta 12/08/91) 10. Allow use of vfork() on systems that do not have job control. 9. Avoid NUMCC from being defined twice. 8. (V6.00.06 beta 12/05/91) 7. SunOS3's FIOCLEX dups... 6. Yet another globbing bug fix from Michael (echo .[^.]) 5. Ultrix now wants __ before cpp symbols. 4. Workaround sun's header files inconsistency so tcsh can be compiled with #undef POSIX 3. Fixed limit stuff so that large values don't cause errors. 2. Fixed =1 and ~user error messages (Per) 1. (beta-5 6.00.04 == 6.00.05) $#* $#* New numbering scheme (The last 2 digits are reserved for beta releases $#* from now on. So we start at 6.00.06 which is 6.00.04 beta 6, and we are $#* going to release 6.01.00... $#* V6.00.04, (never released) 34. (beta-5 11/25/91) 33. Simplify code in BindArrowKeys() 32. Get rid of the PNULL's 31. Support for shadow password in locking code. (From Kimmo) 30. Normalize-path editor function. 29. (beta-4 11/21/91) 28. minix additions 27. bindkey fixes (-c addition, casting cleanups) 26. (beta-3 11/16/91) 25. Prompt length checking. 24. Michael's fixes for the watching code. Tcsh could core dump when using a corrupted utmp. 23. overwrite mode flag, and autologout locking code. 22. overwrite mode would still insert digits! 21. Get the value of _POSIX_VDISABLE from pathconf... 20. Hpux 8.0 fixes. Sigstack botches with shared libraries. Ansi mode static initialization of structures with prototyped function pointers gives spurious warnings... 19. Onintr in /etc rc files is disabled. 18. (beta-2 11/03/91) 17. Multi-line aliases with `` bug fix. 16. Sticky emacs overwrite mode. 15. Autolist option. 14. Fix for redirection with wildcard filanames. 13. No error correction for multi-line commands. 12. Esix-4 re-defines p_pid. Argh... 11. (beta-1 10/28/91) 10. Foreach loops were broken again. 9. SUNOS localtime() bug does not only happen on the 8th byte. [Michael] 8. sh.dir.c, memory corruption in dinit(). Thanks Michael. 7. uts broken work-around, and has a wait3() 6. SGI (-t filename) extension, returns true when filename is a tty. 5. 'default:' addition in all switch() statements. 4. oflag was not being updated correctly in Rawmode() 3. missing 'break;' in prompt code '%y'. 2. infinite loop in :a code. 1. hashstat was not reporting hits+misses V6.00.03, 10/21/91 31. watch code now accepts shell patterns. 30. new hashing code portability fixes. 29. $foo:gs/:/ / fix and 'a' modifier addition. 28. Added $! (the pid of the last background job forked) 27. exec does not kill the shell when it fails. 26. Irix4.0 decls. 25. SVR4 uthost fixes from Kimmo Suominen 24. Imake addition from marc 23. New i-search from Per. 22. ibmesa fixes 21. convex fixes. 20. t command for vi. 19. SVR4 fixes (reverse pipeline and sigaction()) from David Dawes. 18. New hashing from Marc 17. Added : to the ~name separators so ~foo:~bar works. 16. New ed.init.c. Added ed.term.c 15. Still can't get the history exactly csh-like... !-2$ was broken... 14. vi character searches. 13. -Dvar=name command line option for the apollos. 12. Prompt format changes for date/directory. 11. Vi searches. 10. Emacs i-search. [currently not bound] 9. Vi additions ([dc]-{w,$,f},Undo) 8. tcsh -n parses now builtin structures. 7. seek to the end on errors in loops. 6. echotc -s was broken 5. Better !event parsing. !foo;!bar was broken. 4. foreach loops and if statements in aliases. 3. .cshdirs would corrupt the heap if some directories were not there. 2. System V echo was broken with \ 1. Fixed echo '!-1', history would eat the quote. V6.00.02, 08/05/91 [For comp.sources.unix] 8. tcsh will always set $LOGNAME and $USER if not already set in the environment. 7. added $histfile. 6. echo `echo` * and echo ~ {} were broken 5. setty builtin addition 4. Multiple : modifiers [experimental, disabled with -DCOMPAT] 3. 7 bit fixes, and hp9000s500. 2. #undef DEBUG in tc.alloc.c, so we continue if we get a bad free() 1. getn() is now protected against NULL strings. V6.00.01, 07/16/91 17. added beepcmd, and fixed small tenematch bugs. 16. Renamed DUP2 flag to HAVEDUP2 cause AIXPS2 defines DUP2 already. 15. More ANSI fixes, and mit additions (load-average) 14. don't clear ECHOE, background programs might need it. 13. Refresh bug fix... 12. getpwent() should not be interrupted (yellow pages), cause it might leave dangling pointers, that endpwent() will trash. 11. ChangeSize is now responsible to set the screen size to something sane, but it should not affect the environment if the information it received is not valid 10. Find out if we are running under emacs using $TERM. It is more reliable. 9. tcsh was broken if SHORT_STRINGS was not defined (glob() problem) 8. If GetSize() fails it should always return reasonable screen sizes. 7. globbing should not fail if one or more patterns match. 6. increased the number of aliases in the loop detection code. 5. DGUX has size_t and pid_t defined now... 4. ESIX does not have EWOULDBLOCK or EAGAIN & POSIX... That was not handled correctly. 3. rs6000 needs BSDWAIT. 2. Hpux susp key could not be changed. 1. Apollo fixes. V6.00.00, 07/04/91 45. Fixed quoting of VSTART/VSTOP on termios 44. Memory leak every time you pipe in or out. 43. echo {foo bar.[ch]}. Did not check for end of word. 42. ANSI prototypes 41. dmove() would leave the source descriptor open when using dup2() e.g. while (1) echo foo >>! bar end runs out of file descriptors 40. recursive `` expanded via aliases would abort. 39. set home=../relative-path-name was broken. e.g. set home=../..; cd ..; 38. Incorrect error when changing to directory: e.g. mkdir not-in-cd-path; chmod -x not-in-cd-path; cd not-in-cd-path; echoed: not-in-cd-path: No such file or directory. it should have said not-in-cd-path: Permission denied. 37. if ( \! =~ [\!] ) echo ok, did not echo ok. Quoting inside [] pattern. 36. More than 127 jobs caused job # to go negative 35. unsetenv ... Added support for more than one pattern. 34. More background process status report fixes. 33. Apollo builtin support. 32. Glob fix. echo '*' * was not handled properly. 31. Glob fix. setenv FOO `sleep 1` would either cause a segmentation fault. or print ambiguous. 30. Glob fix. Quoted characters inside [] were not handled properly. 29. Removed TELL and VMUNIX defines. I think we cannot compile on V6 anyway 28. Overflow check for expansions. 27. Added matchbeep, shell pattern history searching. 26. Added code to handle /dev/std{in,out,err} 25. Fixed POSIX speed handling in raw mode. 24. Fixed a flushing bug in the filec code in sh.file.c 23. Compiled and added hp9000s700 to the list of hosts. 22. Fixed horrible bug in gmatch() switch (4) case [a-z]: echo bug; breaksw; case 4: echo ok; breaksw; endsw 21. Fixes for _SEQUENT_ ut_host. 20. FLUSHO added 19. mkdir foo\`bar; cd foo\`bar; was broken 18. EWOULDBLOCK == EAGAIN on RENO check for that too. 17. Dword() simplified and removed the gotos. 16. Hpux now compiles with POSIX. Moved the local chars modes in ed.init.c after the tty modes. 15. Process group fixes for POSIX 14. We need on the suns for FIOCLEX!!! We did not close our file descriptors before... 13. A/UX fixes. 12. History events that start with a number are not necessarily numeric: > !3d 3d: Event not fount 11. History loop detection added. > alias a \!# > b; a 10. Alias loop detection code was ineffective on eager optimizers. 9. All errors should now go through our table. Next step we should add nls error messages. 8. Unsetenv now globs its arguments! Before it did not... 7. Added tilde cache and -l flag. 6. Added autocorrect 5. Fixed for so that background jobs in scripts get process groups 4. Fixed amazing memory leak in setenv()... 3. Added short2qstr() so that we can form quoted strings to be used with glob() 2. str2short and short2str allocate space dynamically. 1. Fixed bug related to the is*() routines called with shorts. [only if NLS and SHORT_STRINGS are defined]. (The _ctype_ was getting indexed with shorts...) 0. Complete overhaul. Brought in the 4.4 csh stuff. Separated most tcsh and csh code except where I would have to add more global variables. Compiled correctly with both lint and gcc -Wall on a sparc running 4.1 V5.20.03, 03/20/91. - Never released 25. Kanji, SXA additions. 24. (exec foo) should not fail if they are suspended jobs. 23. Support kernel paging stuff on aix 370. 22. Now we handle correctly the environment variables LINES, COLUMNS, TERMCAP for window size changes... 21. Tcsh 5.18c+ had broken NULL chars on scripts. > cat > foo #!/usr/local/bin/tcsh -f echo "foo" echo "^V^@" echo "bar" ^D > chmod +x foo; foo foo 20. Posix has EAGAIN and not EWOULDBLOCK 19. Don't set ECHOK; makes kill ^U ugly. 18. $shell is SHELLPATH and not $SHELL any more. 17. Added -n flag to cd, pushd, popd and dirs. Documented -l and -v flags. 16. Documented and fixed chase_symlinks and ignore_symlinks. 15. Call endpwent() when you get interrupted... cd ~chri^C cd ~christos/ 14. Exec when you have suspended jobs asks for verification. 13. Variable length fixes: >set abcdefghijklmnopqrstuvwxyz=1 >echo $abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrs: Undefined variable Now we have better messages too... 12. Icon fixes... 11. Quote expanded glob and history chars too. 10. If someone sets SHIN to O_NDELAY we died... Now we set it back... 9. unset path; unsetenv PATH; ls-F; (poof) fixed... 8. Patches for masscomp, and ${var123} lexical analysis fix... 7. Patch for sunview bug: A partially covered suntool sends SIGWINCH every time the text is scrolled, causing annoying redraw effects. Now tcsh checks if the size really changed before doing anything. 6. Interrupt in the middle of cwdcmd, and periodic does not remove the aliases. 5. prompt2 and prompt3 fixes: Prompt2 now prints the status of the parser by default. Prompt3 can now have the standard prompt escape sequences. 4. eval file descriptor re-direction fix. >set p='w | tail +3' >eval $p (originally | tail +3 was ignored) 3. $edit != emacs anymore; it was misleading, 'set edit' enables editing 'unset edit' disables it. 2. PERROR define fix. 1. irix3.3.1 line discipline fix. V5.20.02, 12/15/90. 32. /etc/Logout added and merged with /etc/Login flag. 31. Fixed tty chars in ed.init.c. Some of them were not handled correctly. 30. Command execution does not leak memory any more, and doing ~ four times does not core-dump. 29. Fixed the notorious csh 'if(' bug (part of the convex fixes) 28. Intelligent getwd() on startup, and canonicalization. 27. Intelligent directory stack. Gets updated when $HOME changes. 26. Directory stack/save-restore additions 25. Convex Fixes. 24. Fixed onlret, and echonl getting stuck on svid. 23. Shouldn't leave tty in raw mode at auto-logout (e.g. when su'ing from a csh, this is annoying). 22. Some users had environment EMACS set to something, and with my bad fix at pl 1 found that they didn't have echo... (of course, even before my "fix", they didn't have editing...). Anyway, refined the check to be for EMACS=t, which is what emacs sets when running a subshell. 21. kill -CONT %job, would not update the status of the job, but it would just restart it. 20. Sequent fixes. 19. AIX370 signal and TCF fixes. 18. fixed ls-F -l, SIGINT problem. 17. aix on the ps2 does not have strcoll() either. 16. Bind [A - [D and OA to OD in vi mode to the arrow key functions so that they work from insert mode. 15. %~ was not working correctly for /home/news and /home/newsbin... 14. Removed Rcs Log 13. ISC unix fixes. 12. sunos3.x wants not 11. Remove precmd's, cwdcmd's and periodic cmds that had errors. 10. Compile sunos4.1 using termio. 9. Rs6000 line discipline fixes. 8. T_Tabs was wrong for termio machines. 7. Don't bind single keystroke arrow keys, when they are already bound! 6. Test for newline and tab before deciding not to send shell scripts to the bourne shell. 5. Added LITERAL prompt stuff. 4. Fixed gethostname() in sh.rest.c to return the nodename. 3. Do not quote spell checked stuff. This is not very intelligent but works better than before. 2. Fixes for relative path components. (paths that start with a .) 1. Fixed so that Rawmode() is not called when we are not editing (breaks running under emacs) V5.20.01, 11/15/90. 12. Recognize environment variables too. 11. Always start in Rawmode() 10. don't try to execute binary files using the bourne shell. 9. Vi change to end of line updates correctly now. 8. Prompt in continuation lines. 7. Prompt in if statements fix. 6. System V ^C works right now. 5. ^Z works correctly in bindings 4. Better error messages for variables. 3. dinit() now is more robust. 2. Added aux2.0 patches. 1. Fixed bug with arrow key bindings in ed.screen.c. All the keys were bound to up-history! V5.20.00, 11/10/90. 26. Fixed system V and POSIX time reporting. 25. Fixed ed.screen.c so that it does not use malloc(). 24. Fixed SIGWINCH on the iris 23. Fixed ed.screen.c, so that settc works correcly. It used to set the termcap with a string that was allocated from the stack! 22. Fixed listing of commands, where the last command was not checked. 21. Fixed which command. It did not work for \, if command was aliased. 20. Eliminated CSH4.3 define. You've had enough time to upgrade from 4.2 19. Fixed GotTermCaps to be called only once. 18. Added bindkey -r 17. Attributes were not getting reset correctly. 16. history -t does not print the time-stamp. 15. AddXkey, works now for single character xkeys. 14. filetype() knows better about symlinks. 13. ls-F works with filenames that have metachars 12. Completion/spelling works with quoted things. 11. Fixed refresh bug. Repeat by: On an intelligent terminal that has insert and delete chars (xterm) > orphan > vi orphan.c > ^P^P 10. Fixed so that if we don't have a tty on stdin editing is disabled. 9. Check for nested process forking, to avoid loops such as: > alias foo 'set bar=`foo`' > foo 8. Fix setting of AsciiOnly (Per) 7. tw.spell.c, defined F_OK for systems that don't have it. 6. ourwait.h had typo in ifdef. 5. BSD compilers need a cast to int for enums used in switches (Matthew Day) 4. Found the cause for the core-dump in long backquote expansions (Mark Davies) 3. Some externs in ed.h needed to be truly externs... reported by Mark Davies, bug appeared only on hp9000s800. 2. Changed $tcsh, and $version strings. 1. Added internal sprintf function, renamed putchar to CSHputchar, printf to CSHprintf, sprintf to CSHsprintf. V5.19.02, 10/23/90. 36. Added /etc/cshrc for the SGI irises. 35. Added expand-variables function. 34. Documented $time in tcsh.man 33. Shell variables are now 'recognized' when expanding/listing things. 32. ls-F does not eat the last slash on the / directory! 31. Strings bound to keys are printed inside double quotes. 30. History now remembers the exact line, not just an unparsed version of the tokens. 29. Renamed itoa to Itoa(), so things in libc that use itoa() don't break. 28. Ported to IBM aix/ps2. 27. Fixed eval so that it forks when the output is piped Repeat by: > who | grep $user > eval who | grep $user 26. Fixed so that 'nice ' does not nice or fork. Consider doing: nice cd /tmp && rm *.c (don't try it!!!) [what actually happens is that nice has to fork, then the child executes chdir, and the parent stays where it was] 25. Added Dan's patches (nls, builtin bindkey, fixes to the editor). 24. Added aix370, migrate, getspath, getspath, getxvers, setxvers 23. Added builtin echotc, removed sl and el. 22. Ported to 4.4 BSD. This involved changing the way lots of flags worked, cleanup of the SVID stuff, and addition of more compilation flags. Now POSIX can work whed BSD is defined... 21. Fixed so that el, sl work. Actually they are to be removed soon and be replaced with echotc. 20. Avoid the Quoted Space hack for alias when printing jobs! [aliases to the same name avoid further alias expansion, by inserting a quoted space in front of the command. In SHORT_STRINGS QUOTE is the 15th bit so print ignores it thinking it is the end of the string. So we just skip the Quoted Space....] Repeat by: > set notify > alias ls ls -F > (ls) & Prints Exit 0 ( Should print: Exit 0 ( ls -F ) 19. Fixed so that "", '', ``, all produce ': Command not found', and not the spurious messages. Repeat by: > set path = (/bin /usr/bin .... .) > "" /some/path/name/: Command not found 18. Enable the use of macros if they exist and NLS is defined. NLS code is not ready yet. 17. Fixed rmstar and continue_jobs code, so that they are not compile options, but shell variables. Now you need to 'set rmstar' to get enable rmstar. 16. Fixed SIGWINCH, SIGWINDOW, and setting of li, co, that broke suntools, and others. Repeat by: Start a shelltool of size other than 80x34 > telltc > stty -a do not report the same number of lines and columns. 15. More fixes to tw.parse.c, and tw.spell.c. 14. More fixes to sh.char.c. 13. Fixed coredump caused by ``. 12. Fixed spell-line code.. 11. Trapped SIGCHLD in sh.sem.c, while forking. Still there is a small race, but the probability of happening is smaller! 10. Fixed sh.char.c to be ISO compliant. 9. Added expand-glob 8. Fixed ourwait.h for little endians. 7. Fixed that foreach i (^D expands correctly. 6. Fixed so that listmax is ignored in ls-F. 5. Fixed spelling correction so that single letter words and words that contain globbing chars do not get spell checked. 4. Changed NeXT HOSTTYPE to next, since all HOSTTYPE's are lower case. 3. Fixed symmetry, and changed symmetry HOSTTYPE from sequent to symmetry. 2. Added boldfacing, underlining chars. 1. Added IRIX3.3.1 support. V5.19.01, 9/26/90. 7. Brought the README file up-to-date, and changed the bug report address to point to me. 6. sh.lex.c. In addla(), overflow computation was wrong. 5. Fixed SHELLPATH, to be set correctly when $SHELL is not set. 4. Fixed print statement in sh.proc.c that contained \215. 3. Fixed the Makefile and MAKEDIFFS so that a tahoe diff can be made. 2. RS6000: hacked around execv bug, and ed.init.c warning. 1. Editor should not be enabled when we don't have a tty. diff --git a/contrib/tcsh/ed.chared.c b/contrib/tcsh/ed.chared.c index 2b4a63c8ca6e..2a8689713399 100644 --- a/contrib/tcsh/ed.chared.c +++ b/contrib/tcsh/ed.chared.c @@ -1,3893 +1,3893 @@ /* * ed.chared.c: Character editing functions. */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* Bjorn Knutsson @ Thu Jun 24 19:02:17 1999 e_dabbrev_expand() did not do proper completion if quoted spaces were present in the string being completed. Exemple: # echo hello\ world hello world # echo h # echo hello\ Correct behavior is: # echo h # echo hello\ world The same problem occured if spaces were present in a string withing quotation marks. Example: # echo "hello world" hello world # echo "h # echo "hello - + The former problem could be solved with minor modifications of c_preword() and c_endword(). The latter, however, required a significant rewrite of c_preword(), since quoted strings must be parsed from start to end to determine if a given character is inside or outside the quotation marks. Compare the following two strings: # echo \"" 'foo \' bar\" " 'foo \' bar\ # echo '\"" 'foo \' bar\" \"" foo ' bar" The only difference between the two echo lines is in the first character after the echo command. The result is either one or three arguments. */ #include "sh.h" #include "ed.h" #include "tw.h" #include "ed.defns.h" /* #define SDEBUG */ #define TCSHOP_NOP 0x00 #define TCSHOP_DELETE 0x01 #define TCSHOP_INSERT 0x02 #define TCSHOP_CHANGE 0x04 #define CHAR_FWD 0 #define CHAR_BACK 1 /* * vi word treatment * from: Gert-Jan Vons */ #define C_CLASS_WHITE 1 #define C_CLASS_WORD 2 #define C_CLASS_OTHER 3 static Char *InsertPos = InputBuf; /* Where insertion starts */ static Char *ActionPos = 0; /* Where action begins */ static int ActionFlag = TCSHOP_NOP; /* What delayed action to take */ /* * Word search state */ static int searchdir = F_UP_SEARCH_HIST; /* Direction of last search */ static struct Strbuf patbuf; /* = Strbuf_INIT; Search target */ /* * Char search state */ static int srch_dir = CHAR_FWD; /* Direction of last search */ static Char srch_char = 0; /* Search target */ /* all routines that start with c_ are private to this set of routines */ static void c_alternativ_key_map (int); void c_insert (int); void c_delafter (int); void c_delbefore (int); static int c_to_class (Char); static Char *c_prev_word (Char *, Char *, int); static Char *c_next_word (Char *, Char *, int); static Char *c_number (Char *, int *, int); static Char *c_expand (Char *); static int c_excl (Char *); static int c_substitute (void); static void c_delfini (void); static int c_hmatch (Char *); static void c_hsetpat (void); #ifdef COMMENT static void c_get_word (Char **, Char **); #endif static Char *c_preword (Char *, Char *, int, Char *); static Char *c_nexword (Char *, Char *, int); static Char *c_endword (Char *, Char *, int, Char *); static Char *c_eword (Char *, Char *, int); static void c_push_kill (Char *, Char *); static void c_save_inputbuf (void); static CCRETVAL c_search_line (Char *, int); static CCRETVAL v_repeat_srch (int); static CCRETVAL e_inc_search (int); #ifdef notyet static CCRETVAL e_insert_str (Char *); #endif static CCRETVAL v_search (int); static CCRETVAL v_csearch_fwd (Char, int, int); static CCRETVAL v_action (int); static CCRETVAL v_csearch_back (Char, int, int); static void c_alternativ_key_map(int state) { switch (state) { case 0: CurrentKeyMap = CcKeyMap; break; case 1: CurrentKeyMap = CcAltMap; break; default: return; } AltKeyMap = (Char) state; } void c_insert(int num) { Char *cp; if (LastChar + num >= InputLim) return; /* can't go past end of buffer */ if (Cursor < LastChar) { /* if I must move chars */ for (cp = LastChar; cp >= Cursor; cp--) cp[num] = *cp; if (Mark && Mark > Cursor) Mark += num; } LastChar += num; } void c_delafter(int num) { Char *cp, *kp = NULL; if (num > LastChar - Cursor) num = (int) (LastChar - Cursor); /* bounds check */ if (num > 0) { /* if I can delete anything */ if (VImode) { kp = UndoBuf; /* Set Up for VI undo command */ UndoAction = TCSHOP_INSERT; UndoSize = num; UndoPtr = Cursor; for (cp = Cursor; cp <= LastChar; cp++) { *kp++ = *cp; /* Save deleted chars into undobuf */ *cp = cp[num]; } } else for (cp = Cursor; cp + num <= LastChar; cp++) *cp = cp[num]; LastChar -= num; /* Mark was within the range of the deleted word? */ if (Mark && Mark > Cursor && Mark <= Cursor+num) Mark = Cursor; /* Mark after the deleted word? */ else if (Mark && Mark > Cursor) Mark -= num; } #ifdef notdef else { - /* + /* * XXX: We don't want to do that. In emacs mode overwrite should be - * sticky. I am not sure how that affects vi mode + * sticky. I am not sure how that affects vi mode */ inputmode = MODE_INSERT; } #endif /* notdef */ } void c_delbefore(int num) /* delete before dot, with bounds checking */ { Char *cp, *kp = NULL; if (num > Cursor - InputBuf) num = (int) (Cursor - InputBuf); /* bounds check */ if (num > 0) { /* if I can delete anything */ if (VImode) { kp = UndoBuf; /* Set Up for VI undo command */ UndoAction = TCSHOP_INSERT; UndoSize = num; UndoPtr = Cursor - num; for (cp = Cursor - num; cp <= LastChar; cp++) { *kp++ = *cp; *cp = cp[num]; } } else for (cp = Cursor - num; cp + num <= LastChar; cp++) *cp = cp[num]; LastChar -= num; Cursor -= num; /* Mark was within the range of the deleted word? */ if (Mark && Mark > Cursor && Mark <= Cursor+num) Mark = Cursor; /* Mark after the deleted word? */ else if (Mark && Mark > Cursor) Mark -= num; } } static Char * c_preword(Char *p, Char *low, int n, Char *delim) { while (n--) { Char *prev = low; Char *new; while (prev < p) { /* Skip initial non-word chars */ if (!Strchr(delim, *prev) || (prev > low && prev[-1] == (Char)'\\')) break; prev++; } new = prev; while (new < p) { prev = new; new = c_endword(prev-1, p, 1, delim); /* Skip to next non-word char */ new++; /* Step away from end of word */ while (new <= p) { /* Skip trailing non-word chars */ - if (!Strchr(delim, *new) || new > prev && new[-1] == (Char)'\\') + if (!Strchr(delim, *new) || (new > prev && new[-1] == (Char)'\\')) break; new++; } } p = prev; /* Set to previous word start */ } if (p < low) p = low; return (p); } /* * c_to_class() returns the class of the given character. * * This is used to make the c_prev_word(), c_next_word() and c_eword() functions * work like vi's, which classify characters. A word is a sequence of * characters belonging to the same class, classes being defined as * follows: * * 1/ whitespace * 2/ alphanumeric chars, + underscore * 3/ others */ static int c_to_class(Char ch) { if (Isspace(ch)) return C_CLASS_WHITE; if (isword(ch)) return C_CLASS_WORD; return C_CLASS_OTHER; } static Char * c_prev_word(Char *p, Char *low, int n) { p--; if (!VImode) { while (n--) { - while ((p >= low) && !isword(*p)) + while ((p >= low) && !isword(*p)) p--; - while ((p >= low) && isword(*p)) + while ((p >= low) && isword(*p)) p--; } - + /* cp now points to one character before the word */ p++; if (p < low) p = low; /* cp now points where we want it */ return(p); } - + while (n--) { int c_class; if (p < low) break; /* scan until beginning of current word (may be all whitespace!) */ c_class = c_to_class(*p); while ((p >= low) && c_class == c_to_class(*p)) p--; /* if this was a non_whitespace word, we're ready */ if (c_class != C_CLASS_WHITE) continue; /* otherwise, move back to beginning of the word just found */ c_class = c_to_class(*p); while ((p >= low) && c_class == c_to_class(*p)) p--; } p++; /* correct overshoot */ return (p); } static Char * c_next_word(Char *p, Char *high, int n) { if (!VImode) { while (n--) { - while ((p < high) && !isword(*p)) + while ((p < high) && !isword(*p)) p++; - while ((p < high) && isword(*p)) + while ((p < high) && isword(*p)) p++; } if (p > high) p = high; /* p now points where we want it */ return(p); } while (n--) { int c_class; if (p >= high) break; /* scan until end of current word (may be all whitespace!) */ c_class = c_to_class(*p); while ((p < high) && c_class == c_to_class(*p)) p++; /* if this was all whitespace, we're ready */ if (c_class == C_CLASS_WHITE) continue; /* if we've found white-space at the end of the word, skip it */ while ((p < high) && c_to_class(*p) == C_CLASS_WHITE) p++; } p--; /* correct overshoot */ return (p); } static Char * c_nexword(Char *p, Char *high, int n) { while (n--) { - while ((p < high) && !Isspace(*p)) + while ((p < high) && !Isspace(*p)) p++; - while ((p < high) && Isspace(*p)) + while ((p < high) && Isspace(*p)) p++; } if (p > high) p = high; /* p now points where we want it */ return(p); } /* * Expand-History (originally "Magic-Space") code added by * Ray Moody * this is a neat, but odd, addition. */ /* * c_number: Ignore character p points to, return number appearing after that. * A '$' by itself means a big number; "$-" is for negative; '^' means 1. * Return p pointing to last char used. */ /* * dval is the number to subtract from for things like $-3 */ static Char * c_number(Char *p, int *num, int dval) { int i; int sign = 1; if (*++p == '^') { *num = 1; return(p); } if (*p == '$') { if (*++p != '-') { *num = INT_MAX; /* Handle $ */ return(--p); } sign = -1; /* Handle $- */ ++p; } for (i = 0; *p >= '0' && *p <= '9'; i = 10 * i + *p++ - '0') continue; *num = (sign < 0 ? dval - i : i); return(--p); } /* * excl_expand: There is an excl to be expanded to p -- do the right thing * with it and return a version of p advanced over the expanded stuff. Also, * update tsh_cur and related things as appropriate... */ static Char * c_expand(Char *p) { Char *q; struct Hist *h = Histlist.Hnext; struct wordent *l; int i, from, to, dval; int all_dig; int been_once = 0; Char *op = p; Char *buf; size_t buf_len; Char *modbuf; buf = NULL; if (!h) goto excl_err; excl_sw: switch (*(q = p + 1)) { case '^': buf = expand_lex(&h->Hlex, 1, 1); break; case '$': if ((l = (h->Hlex).prev) != 0) buf = expand_lex(l->prev->prev, 0, 0); break; case '*': buf = expand_lex(&h->Hlex, 1, INT_MAX); break; default: if (been_once) { /* unknown argument */ /* assume it's a modifier, e.g. !foo:h, and get whole cmd */ buf = expand_lex(&h->Hlex, 0, INT_MAX); q -= 2; break; } been_once = 1; if (*q == ':') /* short form: !:arg */ --q; if (HIST != '\0' && *q != HIST) { /* * Search for a space, tab, or colon. See if we have a number (as * in !1234:xyz). Remember the number. */ - for (i = 0, all_dig = 1; + for (i = 0, all_dig = 1; *q != ' ' && *q != '\t' && *q != ':' && q < Cursor; q++) { /* * PWP: !-4 is a valid history argument too, therefore the test * is if not a digit, or not a - as the first character. */ if ((*q < '0' || *q > '9') && (*q != '-' || q != p + 1)) all_dig = 0; else if (*q == '-') all_dig = 2;/* we are sneeky about this */ else i = 10 * i + *q - '0'; } --q; /* * If we have a number, search for event i. Otherwise, search for * a named event (as in !foo). (In this case, I is the length of * the named event). */ if (all_dig) { if (all_dig == 2) i = -i; /* make it negitive */ if (i < 0) /* if !-4 (for example) */ i = eventno + 1 + i; /* remember: i is < 0 */ for (; h; h = h->Hnext) { if (h->Hnum == i) break; } } else { for (i = (int) (q - p); h; h = h->Hnext) { if ((l = &h->Hlex) != 0) { if (!Strncmp(p + 1, l->next->word, (size_t) i)) break; } } } } if (!h) goto excl_err; if (q[1] == ':' || q[1] == '-' || q[1] == '*' || q[1] == '$' || q[1] == '^') { /* get some args */ p = q[1] == ':' ? ++q : q; /* * Go handle !foo:* */ if ((q[1] < '0' || q[1] > '9') && q[1] != '-' && q[1] != '$' && q[1] != '^') goto excl_sw; /* * Go handle !foo:$ */ if (q[1] == '$' && (q[2] != '-' || q[3] < '0' || q[3] > '9')) goto excl_sw; /* * Count up the number of words in this event. Store it in dval. * Dval will be fed to number. */ dval = 0; if ((l = h->Hlex.prev) != 0) { for (l = l->prev; l != h->Hlex.next; l = l->prev, dval++) continue; } if (!dval) goto excl_err; if (q[1] == '-') from = 0; else q = c_number(q, &from, dval); if (q[1] == '-') { ++q; if ((q[1] < '0' || q[1] > '9') && q[1] != '$') to = dval - 1; else q = c_number(q, &to, dval); } else if (q[1] == '*') { ++q; to = INT_MAX; } else { to = from; } if (from < 0 || to < from) goto excl_err; buf = expand_lex(&h->Hlex, from, to); } else /* get whole cmd */ buf = expand_lex(&h->Hlex, 0, INT_MAX); break; } if (buf == NULL) buf = SAVE(""); /* * Apply modifiers, if any. */ if (q[1] == ':') { modbuf = buf; while (q[1] == ':' && modbuf != NULL) { switch (q[2]) { case 'r': case 'e': case 'h': case 't': case 'q': case 'x': case 'u': case 'l': if ((modbuf = domod(buf, (int) q[2])) != NULL) { xfree(buf); buf = modbuf; } ++q; break; case 'a': case 'g': /* Not implemented; this needs to be done before expanding * lex. We don't have the words available to us anymore. */ ++q; break; case 'p': /* Ok */ ++q; break; case '\0': break; default: ++q; break; } if (q[1]) ++q; } } buf_len = Strlen(buf); /* * Now replace the text from op to q inclusive with the text from buf. */ q++; /* * Now replace text non-inclusively like a real CS major! */ if (LastChar + buf_len - (q - op) >= InputLim) goto excl_err; (void) memmove(op + buf_len, q, (LastChar - q) * sizeof(Char)); LastChar += buf_len - (q - op); Cursor += buf_len - (q - op); (void) memcpy(op, buf, buf_len * sizeof(Char)); *LastChar = '\0'; xfree(buf); return op + buf_len; excl_err: xfree(buf); SoundBeep(); return(op + 1); } /* * c_excl: An excl has been found at point p -- back up and find some white * space (or the beginning of the buffer) and properly expand all the excl's * from there up to the current cursor position. We also avoid (trying to) * expanding '>!' * Returns number of expansions attempted (doesn't matter whether they succeeded * or not). */ static int c_excl(Char *p) { int i; Char *q; int nr_exp; /* * if />[SPC TAB]*![SPC TAB]/, back up p to just after the >. otherwise, * back p up to just before the current word. */ if ((p[1] == ' ' || p[1] == '\t') && (p[-1] == ' ' || p[-1] == '\t' || p[-1] == '>')) { for (q = p - 1; q > InputBuf && (*q == ' ' || *q == '\t'); --q) continue; if (*q == '>') ++p; } else { while (*p != ' ' && *p != '\t' && p > InputBuf) --p; } /* * Forever: Look for history char. (Stop looking when we find the cursor.) * Count backslashes. If odd, skip history char. Expand if even number of * backslashes. */ nr_exp = 0; for (;;) { if (HIST != '\0') while (*p != HIST && p < Cursor) ++p; for (i = 1; (p - i) >= InputBuf && p[-i] == '\\'; i++) continue; if (i % 2 == 0) ++p; if (p >= Cursor) /* all done */ return nr_exp; if (i % 2 == 1) { p = c_expand(p); ++nr_exp; } } } static int c_substitute(void) { Char *p; int nr_exp; /* * Start p out one character before the cursor. Move it backwards looking * for white space, the beginning of the line, or a history character. */ - for (p = Cursor - 1; + for (p = Cursor - 1; p > InputBuf && *p != ' ' && *p != '\t' && *p && *p != HIST; --p) continue; /* * If we found a history character, go expand it. */ if (p >= InputBuf && HIST != '\0' && *p == HIST) nr_exp = c_excl(p); else nr_exp = 0; Refresh(); return nr_exp; } static void c_delfini(void) /* Finish up delete action */ { int Size; if (ActionFlag & TCSHOP_INSERT) c_alternativ_key_map(0); ActionFlag = TCSHOP_NOP; - if (ActionPos == 0) + if (ActionPos == 0) return; UndoAction = TCSHOP_INSERT; if (Cursor > ActionPos) { Size = (int) (Cursor-ActionPos); - c_delbefore(Size); + c_delbefore(Size); RefCursor(); } else if (Cursor < ActionPos) { Size = (int)(ActionPos-Cursor); c_delafter(Size); } else { Size = 1; c_delafter(Size); } UndoPtr = Cursor; UndoSize = Size; } static Char * c_endword(Char *p, Char *high, int n, Char *delim) { Char inquote = 0; p++; while (n--) { while (p < high) { /* Skip non-word chars */ if (!Strchr(delim, *p) || p[-1] == (Char)'\\') break; p++; } while (p < high) { /* Skip string */ if ((*p == (Char)'\'' || *p == (Char)'"')) { /* Quotation marks? */ if (inquote || p[-1] != (Char)'\\') { /* Should it be honored? */ if (inquote == 0) inquote = *p; else if (inquote == *p) inquote = 0; } } /* Break if unquoted non-word char */ if (!inquote && Strchr(delim, *p) && p[-1] != (Char)'\\') break; p++; } } p--; return(p); } static Char * c_eword(Char *p, Char *high, int n) { p++; while (n--) { int c_class; if (p >= high) break; /* scan until end of current word (may be all whitespace!) */ c_class = c_to_class(*p); while ((p < high) && c_class == c_to_class(*p)) p++; /* if this was a non_whitespace word, we're ready */ if (c_class != C_CLASS_WHITE) continue; /* otherwise, move to the end of the word just found */ c_class = c_to_class(*p); while ((p < high) && c_class == c_to_class(*p)) p++; } p--; return(p); } /* Set the max length of the kill ring */ void SetKillRing(int max) { CStr *new; int count, i, j; if (max < 1) max = 1; /* no ring, but always one buffer */ if (max == KillRingMax) return; new = xcalloc(max, sizeof(CStr)); if (KillRing != NULL) { if (KillRingLen != 0) { if (max >= KillRingLen) { count = KillRingLen; j = KillPos; } else { count = max; j = (KillPos - count + KillRingLen) % KillRingLen; } for (i = 0; i < KillRingLen; i++) { if (i < count) /* copy latest */ new[i] = KillRing[j]; else /* free the others */ xfree(KillRing[j].buf); j = (j + 1) % KillRingLen; } KillRingLen = count; KillPos = count % max; YankPos = count - 1; } xfree(KillRing); } KillRing = new; KillRingMax = max; } /* Push string from start upto (but not including) end onto kill ring */ static void c_push_kill(Char *start, Char *end) { CStr save, *pos; Char *dp, *cp, *kp; int len = end - start, i, j, k; /* Check for duplicates? */ if (KillRingLen > 0 && (dp = varval(STRkilldup)) != STRNULL) { YankPos = (KillPos - 1 + KillRingLen) % KillRingLen; if (eq(dp, STRerase)) { /* erase earlier one (actually move up) */ j = YankPos; for (i = 0; i < KillRingLen; i++) { if (Strncmp(KillRing[j].buf, start, (size_t) len) == 0 && KillRing[j].buf[len] == '\0') { save = KillRing[j]; for ( ; i > 0; i--) { k = j; j = (j + 1) % KillRingLen; KillRing[k] = KillRing[j]; } KillRing[j] = save; return; } j = (j - 1 + KillRingLen) % KillRingLen; } } else if (eq(dp, STRall)) { /* skip if any earlier */ for (i = 0; i < KillRingLen; i++) if (Strncmp(KillRing[i].buf, start, (size_t) len) == 0 && KillRing[i].buf[len] == '\0') return; } else if (eq(dp, STRprev)) { /* skip if immediately previous */ j = YankPos; if (Strncmp(KillRing[j].buf, start, (size_t) len) == 0 && KillRing[j].buf[len] == '\0') return; } } /* No duplicate, go ahead and push */ len++; /* need space for '\0' */ YankPos = KillPos; if (KillRingLen < KillRingMax) KillRingLen++; pos = &KillRing[KillPos]; KillPos = (KillPos + 1) % KillRingMax; if (pos->len < len) { pos->buf = xrealloc(pos->buf, len * sizeof(Char)); pos->len = len; } cp = start; kp = pos->buf; while (cp < end) *kp++ = *cp++; *kp = '\0'; } /* Save InputBuf etc in SavedBuf etc for restore after cmd exec */ static void c_save_inputbuf(void) { SavedBuf.len = 0; Strbuf_append(&SavedBuf, InputBuf); Strbuf_terminate(&SavedBuf); LastSaved = LastChar - InputBuf; CursSaved = Cursor - InputBuf; HistSaved = Hist_num; RestoreSaved = 1; } CCRETVAL GetHistLine(void) { struct Hist *hp; int h; if (Hist_num == 0) { /* if really the current line */ if (HistBuf.s != NULL) copyn(InputBuf, HistBuf.s, INBUFSIZE);/*FIXBUF*/ else *InputBuf = '\0'; LastChar = InputBuf + HistBuf.len; #ifdef KSHVI if (VImode) Cursor = InputBuf; else #endif /* KSHVI */ Cursor = LastChar; return(CC_REFRESH); } hp = Histlist.Hnext; if (hp == NULL) return(CC_ERROR); for (h = 1; h < Hist_num; h++) { if ((hp->Hnext) == NULL) { Hist_num = h; return(CC_ERROR); } hp = hp->Hnext; } if (HistLit && hp->histline) { copyn(InputBuf, hp->histline, INBUFSIZE);/*FIXBUF*/ CurrentHistLit = 1; } else { Char *p; p = sprlex(&hp->Hlex); copyn(InputBuf, p, sizeof(InputBuf) / sizeof(Char));/*FIXBUF*/ xfree(p); CurrentHistLit = 0; } LastChar = Strend(InputBuf); if (LastChar > InputBuf) { if (LastChar[-1] == '\n') LastChar--; #if 0 if (LastChar[-1] == ' ') LastChar--; #endif if (LastChar < InputBuf) LastChar = InputBuf; } - + #ifdef KSHVI if (VImode) Cursor = InputBuf; else #endif /* KSHVI */ Cursor = LastChar; return(CC_REFRESH); } static CCRETVAL c_search_line(Char *pattern, int dir) { Char *cp; size_t len; len = Strlen(pattern); if (dir == F_UP_SEARCH_HIST) { for (cp = Cursor; cp >= InputBuf; cp--) if (Strncmp(cp, pattern, len) == 0 || Gmatch(cp, pattern)) { Cursor = cp; return(CC_NORM); } return(CC_ERROR); } else { for (cp = Cursor; *cp != '\0' && cp < InputLim; cp++) if (Strncmp(cp, pattern, len) == 0 || Gmatch(cp, pattern)) { Cursor = cp; return(CC_NORM); } return(CC_ERROR); } } static CCRETVAL e_inc_search(int dir) { static const Char STRfwd[] = { 'f', 'w', 'd', '\0' }, STRbck[] = { 'b', 'c', 'k', '\0' }; static Char pchar = ':'; /* ':' = normal, '?' = failed */ static Char endcmd[2]; const Char *cp; Char ch, *oldCursor = Cursor, oldpchar = pchar; CCRETVAL ret = CC_NORM; int oldHist_num = Hist_num, oldpatlen = patbuf.len, newdir = dir, done, redo; if (LastChar + sizeof(STRfwd)/sizeof(Char) + 2 + patbuf.len >= InputLim) return(CC_ERROR); for (;;) { if (patbuf.len == 0) { /* first round */ pchar = ':'; Strbuf_append1(&patbuf, '*'); } done = redo = 0; *LastChar++ = '\n'; - for (cp = newdir == F_UP_SEARCH_HIST ? STRbck : STRfwd; + for (cp = newdir == F_UP_SEARCH_HIST ? STRbck : STRfwd; *cp; *LastChar++ = *cp++) continue; *LastChar++ = pchar; for (cp = &patbuf.s[1]; cp < &patbuf.s[patbuf.len]; *LastChar++ = *cp++) continue; *LastChar = '\0'; if (adrof(STRhighlight) && pchar == ':') { /* if the no-glob-search patch is applied, remove the - 1 below */ IncMatchLen = patbuf.len - 1; ClearLines(); ClearDisp(); } Refresh(); if (GetNextChar(&ch) != 1) return(e_send_eof(0)); switch (GetCmdChar(ch)) { case F_INSERT: case F_DIGIT: case F_MAGIC_SPACE: if (LastChar + 1 >= InputLim) /*FIXBUF*/ SoundBeep(); else { Strbuf_append1(&patbuf, ch); *LastChar++ = ch; *LastChar = '\0'; Refresh(); } break; case F_INC_FWD: newdir = F_DOWN_SEARCH_HIST; redo++; break; case F_INC_BACK: newdir = F_UP_SEARCH_HIST; redo++; break; case F_DELPREV: if (patbuf.len > 1) done++; - else + else SoundBeep(); break; default: switch (ASC(ch)) { case 0007: /* ^G: Abort */ ret = CC_ERROR; done++; break; case 0027: /* ^W: Append word */ /* No can do if globbing characters in pattern */ for (cp = &patbuf.s[1]; ; cp++) if (cp >= &patbuf.s[patbuf.len]) { Cursor += patbuf.len - 1; cp = c_next_word(Cursor, LastChar, 1); while (Cursor < cp && *Cursor != '\n') { if (LastChar + 1 >= InputLim) {/*FIXBUF*/ SoundBeep(); break; } Strbuf_append1(&patbuf, *Cursor); *LastChar++ = *Cursor++; } Cursor = oldCursor; *LastChar = '\0'; Refresh(); break; } else if (isglob(*cp)) { SoundBeep(); break; } break; - + default: /* Terminate and execute cmd */ endcmd[0] = ch; PushMacro(endcmd); /*FALLTHROUGH*/ case 0033: /* ESC: Terminate */ ret = CC_REFRESH; done++; break; } break; } while (LastChar > InputBuf && *LastChar != '\n') *LastChar-- = '\0'; *LastChar = '\0'; if (!done) { /* Can't search if unmatched '[' */ for (cp = &patbuf.s[patbuf.len - 1], ch = ']'; cp > patbuf.s; cp--) if (*cp == '[' || *cp == ']') { ch = *cp; break; } if (patbuf.len > 1 && ch != '[') { if (redo && newdir == dir) { if (pchar == '?') { /* wrap around */ Hist_num = newdir == F_UP_SEARCH_HIST ? 0 : INT_MAX; if (GetHistLine() == CC_ERROR) /* Hist_num was fixed by first call */ (void) GetHistLine(); Cursor = newdir == F_UP_SEARCH_HIST ? LastChar : InputBuf; } else Cursor += newdir == F_UP_SEARCH_HIST ? -1 : 1; } Strbuf_append1(&patbuf, '*'); Strbuf_terminate(&patbuf); if (Cursor < InputBuf || Cursor > LastChar || (ret = c_search_line(&patbuf.s[1], newdir)) == CC_ERROR) { LastCmd = (KEYCMD) newdir; /* avoid c_hsetpat */ ret = newdir == F_UP_SEARCH_HIST ? e_up_search_hist(0) : e_down_search_hist(0); if (ret != CC_ERROR) { Cursor = newdir == F_UP_SEARCH_HIST ? LastChar : InputBuf; (void) c_search_line(&patbuf.s[1], newdir); } } patbuf.s[--patbuf.len] = '\0'; if (ret == CC_ERROR) { SoundBeep(); if (Hist_num != oldHist_num) { Hist_num = oldHist_num; if (GetHistLine() == CC_ERROR) return(CC_ERROR); } Cursor = oldCursor; pchar = '?'; } else { pchar = ':'; } } ret = e_inc_search(newdir); if (ret == CC_ERROR && pchar == '?' && oldpchar == ':') { /* break abort of failed search at last non-failed */ ret = CC_NORM; } } if (ret == CC_NORM || (ret == CC_ERROR && oldpatlen == 0)) { /* restore on normal return or error exit */ pchar = oldpchar; patbuf.len = oldpatlen; if (Hist_num != oldHist_num) { Hist_num = oldHist_num; if (GetHistLine() == CC_ERROR) return(CC_ERROR); } Cursor = oldCursor; if (ret == CC_ERROR) Refresh(); } if (done || ret != CC_NORM) return(ret); - + } } static CCRETVAL v_search(int dir) { struct Strbuf tmpbuf = Strbuf_INIT; Char ch; Char *oldbuf; Char *oldlc, *oldc; cleanup_push(&tmpbuf, Strbuf_cleanup); oldbuf = Strsave(InputBuf); cleanup_push(oldbuf, xfree); oldlc = LastChar; oldc = Cursor; Strbuf_append1(&tmpbuf, '*'); InputBuf[0] = '\0'; LastChar = InputBuf; Cursor = InputBuf; searchdir = dir; c_insert(2); /* prompt + '\n' */ *Cursor++ = '\n'; *Cursor++ = dir == F_UP_SEARCH_HIST ? '?' : '/'; Refresh(); for (ch = 0;ch == 0;) { if (GetNextChar(&ch) != 1) { cleanup_until(&tmpbuf); return(e_send_eof(0)); } switch (ASC(ch)) { case 0010: /* Delete and backspace */ case 0177: if (tmpbuf.len > 1) { *Cursor-- = '\0'; LastChar = Cursor; tmpbuf.len--; } else { copyn(InputBuf, oldbuf, INBUFSIZE);/*FIXBUF*/ LastChar = oldlc; Cursor = oldc; cleanup_until(&tmpbuf); return(CC_REFRESH); } Refresh(); ch = 0; break; case 0033: /* ESC */ #ifdef IS_ASCII case '\r': /* Newline */ case '\n': #else case '\012': /* ASCII Line feed */ case '\015': /* ASCII (or EBCDIC) Return */ #endif break; default: Strbuf_append1(&tmpbuf, ch); *Cursor++ = ch; LastChar = Cursor; Refresh(); ch = 0; break; } } cleanup_until(oldbuf); if (tmpbuf.len == 1) { /* * Use the old pattern, but wild-card it. */ if (patbuf.len == 0) { InputBuf[0] = '\0'; LastChar = InputBuf; Cursor = InputBuf; Refresh(); cleanup_until(&tmpbuf); return(CC_ERROR); } if (patbuf.s[0] != '*') { oldbuf = Strsave(patbuf.s); patbuf.len = 0; Strbuf_append1(&patbuf, '*'); Strbuf_append(&patbuf, oldbuf); xfree(oldbuf); Strbuf_append1(&patbuf, '*'); Strbuf_terminate(&patbuf); } } else { Strbuf_append1(&tmpbuf, '*'); Strbuf_terminate(&tmpbuf); patbuf.len = 0; Strbuf_append(&patbuf, tmpbuf.s); Strbuf_terminate(&patbuf); } cleanup_until(&tmpbuf); LastCmd = (KEYCMD) dir; /* avoid c_hsetpat */ Cursor = LastChar = InputBuf; - if ((dir == F_UP_SEARCH_HIST ? e_up_search_hist(0) : + if ((dir == F_UP_SEARCH_HIST ? e_up_search_hist(0) : e_down_search_hist(0)) == CC_ERROR) { Refresh(); return(CC_ERROR); } else { if (ASC(ch) == 0033) { Refresh(); *LastChar++ = '\n'; *LastChar = '\0'; PastBottom(); return(CC_NEWLINE); } else return(CC_REFRESH); } } /* * semi-PUBLIC routines. Any routine that is of type CCRETVAL is an * entry point, called from the CcKeyMap indirected into the * CcFuncTbl array. */ /*ARGSUSED*/ CCRETVAL v_cmd_mode(Char c) { USE(c); InsertPos = 0; ActionFlag = TCSHOP_NOP; /* [Esc] cancels pending action */ ActionPos = 0; DoingArg = 0; if (UndoPtr > Cursor) UndoSize = (int)(UndoPtr - Cursor); else UndoSize = (int)(Cursor - UndoPtr); inputmode = MODE_INSERT; c_alternativ_key_map(1); #ifdef notdef /* * We don't want to move the cursor, because all the editing * commands don't include the character under the cursor. */ if (Cursor > InputBuf) Cursor--; #endif RefCursor(); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_unassigned(Char c) { /* bound to keys that arn't really assigned */ USE(c); SoundBeep(); flush(); return(CC_NORM); } #ifdef notyet static CCRETVAL e_insert_str(Char *c) { int i, n; n = Strlen(c); if (LastChar + Argument * n >= InputLim) return(CC_ERROR); /* end of buffer space */ if (inputmode != MODE_INSERT) { c_delafter(Argument * Strlen(c)); } c_insert(Argument * n); while (Argument--) { for (i = 0; i < n; i++) *Cursor++ = c[i]; } Refresh(); return(CC_NORM); } #endif CCRETVAL e_insert(Char c) { #ifndef SHORT_STRINGS c &= ASCII; /* no meta chars ever */ #endif if (!c) return(CC_ERROR); /* no NULs in the input ever!! */ if (LastChar + Argument >= InputLim) return(CC_ERROR); /* end of buffer space */ if (Argument == 1) { /* How was this optimized ???? */ if (inputmode != MODE_INSERT) { UndoBuf[UndoSize++] = *Cursor; UndoBuf[UndoSize] = '\0'; c_delafter(1); /* Do NOT use the saving ONE */ } c_insert(1); *Cursor++ = (Char) c; DoingArg = 0; /* just in case */ RefPlusOne(1); /* fast refresh for one char. */ } else { if (inputmode != MODE_INSERT) { int i; - for (i = 0; i < Argument; i++) + for (i = 0; i < Argument; i++) UndoBuf[UndoSize++] = Cursor[i]; UndoBuf[UndoSize] = '\0'; c_delafter(Argument); /* Do NOT use the saving ONE */ } c_insert(Argument); while (Argument--) *Cursor++ = (Char) c; Refresh(); } if (inputmode == MODE_REPLACE_1) (void) v_cmd_mode(0); return(CC_NORM); } int InsertStr(Char *s) /* insert ASCIZ s at cursor (for complete) */ { int len; if ((len = (int) Strlen(s)) <= 0) return -1; if (LastChar + len >= InputLim) return -1; /* end of buffer space */ c_insert(len); while (len--) *Cursor++ = *s++; return 0; } void DeleteBack(int n) /* delete the n characters before . */ { if (n <= 0) return; if (Cursor >= &InputBuf[n]) { c_delbefore(n); /* delete before dot */ } } CCRETVAL e_digit(Char c) /* gray magic here */ { if (!Isdigit(c)) return(CC_ERROR); /* no NULs in the input ever!! */ if (DoingArg) { /* if doing an arg, add this in... */ if (LastCmd == F_ARGFOUR) /* if last command was ^U */ Argument = c - '0'; else { if (Argument > 1000000) return CC_ERROR; Argument = (Argument * 10) + (c - '0'); } return(CC_ARGHACK); } else { if (LastChar + 1 >= InputLim) return CC_ERROR; /* end of buffer space */ if (inputmode != MODE_INSERT) { UndoBuf[UndoSize++] = *Cursor; UndoBuf[UndoSize] = '\0'; c_delafter(1); /* Do NOT use the saving ONE */ } c_insert(1); *Cursor++ = (Char) c; DoingArg = 0; /* just in case */ RefPlusOne(1); /* fast refresh for one char. */ } return(CC_NORM); } CCRETVAL e_argdigit(Char c) /* for ESC-n */ { #ifdef IS_ASCII c &= ASCII; #else c = CTL_ESC(ASC(c) & ASCII); /* stripping for EBCDIC done the ASCII way */ #endif if (!Isdigit(c)) return(CC_ERROR); /* no NULs in the input ever!! */ if (DoingArg) { /* if doing an arg, add this in... */ if (Argument > 1000000) return CC_ERROR; Argument = (Argument * 10) + (c - '0'); } else { /* else starting an argument */ Argument = c - '0'; DoingArg = 1; } return(CC_ARGHACK); } CCRETVAL v_zero(Char c) /* command mode 0 for vi */ { if (DoingArg) { /* if doing an arg, add this in... */ if (Argument > 1000000) return CC_ERROR; Argument = (Argument * 10) + (c - '0'); return(CC_ARGHACK); } else { /* else starting an argument */ Cursor = InputBuf; if (ActionFlag & TCSHOP_DELETE) { c_delfini(); return(CC_REFRESH); } RefCursor(); /* move the cursor */ return(CC_NORM); } } /*ARGSUSED*/ CCRETVAL e_newline(Char c) { /* always ignore argument */ USE(c); if (adrof(STRhighlight) && MarkIsSet) { MarkIsSet = 0; ClearLines(); ClearDisp(); Refresh(); } MarkIsSet = 0; /* PastBottom(); NOW done in ed.inputl.c */ *LastChar++ = '\n'; /* for the benefit of CSH */ *LastChar = '\0'; /* just in case */ if (VImode) InsertPos = InputBuf; /* Reset editing position */ return(CC_NEWLINE); } /*ARGSUSED*/ CCRETVAL e_newline_hold(Char c) { USE(c); c_save_inputbuf(); HistSaved = 0; *LastChar++ = '\n'; /* for the benefit of CSH */ *LastChar = '\0'; /* just in case */ return(CC_NEWLINE); } /*ARGSUSED*/ CCRETVAL e_newline_down_hist(Char c) { USE(c); if (Hist_num > 1) { HistSaved = Hist_num; } *LastChar++ = '\n'; /* for the benefit of CSH */ *LastChar = '\0'; /* just in case */ return(CC_NEWLINE); } /*ARGSUSED*/ CCRETVAL e_send_eof(Char c) { /* for when ^D is ONLY send-eof */ USE(c); PastBottom(); *LastChar = '\0'; /* just in case */ return(CC_EOF); } /*ARGSUSED*/ CCRETVAL e_complete(Char c) { USE(c); *LastChar = '\0'; /* just in case */ return(CC_COMPLETE); } /*ARGSUSED*/ CCRETVAL e_complete_back(Char c) { USE(c); *LastChar = '\0'; /* just in case */ return(CC_COMPLETE_BACK); } /*ARGSUSED*/ CCRETVAL e_complete_fwd(Char c) { USE(c); *LastChar = '\0'; /* just in case */ return(CC_COMPLETE_FWD); } /*ARGSUSED*/ CCRETVAL e_complete_all(Char c) { USE(c); *LastChar = '\0'; /* just in case */ return(CC_COMPLETE_ALL); } /*ARGSUSED*/ CCRETVAL v_cm_complete(Char c) { USE(c); if (Cursor < LastChar) Cursor++; *LastChar = '\0'; /* just in case */ return(CC_COMPLETE); } /*ARGSUSED*/ CCRETVAL e_toggle_hist(Char c) { struct Hist *hp; int h; USE(c); *LastChar = '\0'; /* just in case */ if (Hist_num <= 0) { return CC_ERROR; } hp = Histlist.Hnext; if (hp == NULL) { /* this is only if no history */ return(CC_ERROR); } for (h = 1; h < Hist_num; h++) hp = hp->Hnext; if (!CurrentHistLit) { if (hp->histline) { copyn(InputBuf, hp->histline, INBUFSIZE);/*FIXBUF*/ CurrentHistLit = 1; } else { return CC_ERROR; } } else { Char *p; p = sprlex(&hp->Hlex); copyn(InputBuf, p, sizeof(InputBuf) / sizeof(Char));/*FIXBUF*/ xfree(p); CurrentHistLit = 0; } LastChar = Strend(InputBuf); if (LastChar > InputBuf) { if (LastChar[-1] == '\n') LastChar--; if (LastChar[-1] == ' ') LastChar--; if (LastChar < InputBuf) LastChar = InputBuf; } #ifdef KSHVI if (VImode) Cursor = InputBuf; else #endif /* KSHVI */ Cursor = LastChar; return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_up_hist(Char c) { Char beep = 0; USE(c); UndoAction = TCSHOP_NOP; *LastChar = '\0'; /* just in case */ if (Hist_num == 0) { /* save the current buffer away */ HistBuf.len = 0; Strbuf_append(&HistBuf, InputBuf); Strbuf_terminate(&HistBuf); } Hist_num += Argument; if (GetHistLine() == CC_ERROR) { beep = 1; (void) GetHistLine(); /* Hist_num was fixed by first call */ } Refresh(); if (beep) return(CC_ERROR); else return(CC_NORM); /* was CC_UP_HIST */ } /*ARGSUSED*/ CCRETVAL e_down_hist(Char c) { USE(c); UndoAction = TCSHOP_NOP; *LastChar = '\0'; /* just in case */ Hist_num -= Argument; if (Hist_num < 0) { Hist_num = 0; return(CC_ERROR); /* make it beep */ } return(GetHistLine()); } /* * c_hmatch() return True if the pattern matches the prefix */ static int c_hmatch(Char *str) { if (Strncmp(patbuf.s, str, patbuf.len) == 0) return 1; return Gmatch(str, patbuf.s); } /* * c_hsetpat(): Set the history seatch pattern */ static void c_hsetpat(void) { if (LastCmd != F_UP_SEARCH_HIST && LastCmd != F_DOWN_SEARCH_HIST) { patbuf.len = 0; Strbuf_appendn(&patbuf, InputBuf, Cursor - InputBuf); Strbuf_terminate(&patbuf); } #ifdef SDEBUG xprintf("\nHist_num = %d\n", Hist_num); xprintf("patlen = %d\n", (int)patbuf.len); xprintf("patbuf = \"%S\"\n", patbuf.s); xprintf("Cursor %d LastChar %d\n", Cursor - InputBuf, LastChar - InputBuf); #endif } /*ARGSUSED*/ CCRETVAL e_up_search_hist(Char c) { struct Hist *hp; int h; int found = 0; USE(c); ActionFlag = TCSHOP_NOP; UndoAction = TCSHOP_NOP; *LastChar = '\0'; /* just in case */ if (Hist_num < 0) { #ifdef DEBUG_EDIT xprintf("%s: e_up_search_hist(): Hist_num < 0; resetting.\n", progname); #endif Hist_num = 0; return(CC_ERROR); } if (Hist_num == 0) { HistBuf.len = 0; Strbuf_append(&HistBuf, InputBuf); Strbuf_terminate(&HistBuf); } hp = Histlist.Hnext; if (hp == NULL) return(CC_ERROR); c_hsetpat(); /* Set search pattern !! */ for (h = 1; h <= Hist_num; h++) hp = hp->Hnext; while (hp != NULL) { Char *hl; int matched; if (hp->histline == NULL) hp->histline = sprlex(&hp->Hlex); if (HistLit) hl = hp->histline; else { hl = sprlex(&hp->Hlex); cleanup_push(hl, xfree); } #ifdef SDEBUG xprintf("Comparing with \"%S\"\n", hl); #endif matched = (Strncmp(hl, InputBuf, (size_t) (LastChar - InputBuf)) || hl[LastChar-InputBuf]) && c_hmatch(hl); if (!HistLit) cleanup_until(hl); if (matched) { found++; break; } h++; hp = hp->Hnext; } if (!found) { #ifdef SDEBUG xprintf("not found\n"); #endif return(CC_ERROR); } Hist_num = h; return(GetHistLine()); } /*ARGSUSED*/ CCRETVAL e_down_search_hist(Char c) { struct Hist *hp; int h; int found = 0; USE(c); ActionFlag = TCSHOP_NOP; UndoAction = TCSHOP_NOP; *LastChar = '\0'; /* just in case */ if (Hist_num == 0) return(CC_ERROR); hp = Histlist.Hnext; if (hp == 0) return(CC_ERROR); c_hsetpat(); /* Set search pattern !! */ for (h = 1; h < Hist_num && hp; h++) { Char *hl; if (hp->histline == NULL) hp->histline = sprlex(&hp->Hlex); if (HistLit) hl = hp->histline; else { hl = sprlex(&hp->Hlex); cleanup_push(hl, xfree); } #ifdef SDEBUG xprintf("Comparing with \"%S\"\n", hl); #endif - if ((Strncmp(hl, InputBuf, (size_t) (LastChar - InputBuf)) || + if ((Strncmp(hl, InputBuf, (size_t) (LastChar - InputBuf)) || hl[LastChar-InputBuf]) && c_hmatch(hl)) found = h; if (!HistLit) cleanup_until(hl); hp = hp->Hnext; } if (!found) { /* is it the current history number? */ if (!c_hmatch(HistBuf.s)) { #ifdef SDEBUG xprintf("not found\n"); #endif return(CC_ERROR); } } Hist_num = found; return(GetHistLine()); } /*ARGSUSED*/ CCRETVAL e_helpme(Char c) { USE(c); PastBottom(); *LastChar = '\0'; /* just in case */ return(CC_HELPME); } /*ARGSUSED*/ CCRETVAL e_correct(Char c) { USE(c); *LastChar = '\0'; /* just in case */ return(CC_CORRECT); } /*ARGSUSED*/ CCRETVAL e_correctl(Char c) { USE(c); *LastChar = '\0'; /* just in case */ return(CC_CORRECT_L); } /*ARGSUSED*/ CCRETVAL e_run_fg_editor(Char c) { struct process *pp; USE(c); if ((pp = find_stop_ed()) != NULL) { /* save our editor state so we can restore it */ c_save_inputbuf(); Hist_num = 0; /* for the history commands */ /* put the tty in a sane mode */ PastBottom(); (void) Cookedmode(); /* make sure the tty is set up correctly */ /* do it! */ fg_proc_entry(pp); (void) Rawmode(); /* go on */ Refresh(); RestoreSaved = 0; HistSaved = 0; } return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_list_choices(Char c) { USE(c); PastBottom(); *LastChar = '\0'; /* just in case */ return(CC_LIST_CHOICES); } /*ARGSUSED*/ CCRETVAL e_list_all(Char c) { USE(c); PastBottom(); *LastChar = '\0'; /* just in case */ return(CC_LIST_ALL); } /*ARGSUSED*/ CCRETVAL e_list_glob(Char c) { USE(c); PastBottom(); *LastChar = '\0'; /* just in case */ return(CC_LIST_GLOB); } /*ARGSUSED*/ CCRETVAL e_expand_glob(Char c) { USE(c); *LastChar = '\0'; /* just in case */ return(CC_EXPAND_GLOB); } /*ARGSUSED*/ CCRETVAL e_normalize_path(Char c) { USE(c); *LastChar = '\0'; /* just in case */ return(CC_NORMALIZE_PATH); } /*ARGSUSED*/ CCRETVAL e_normalize_command(Char c) { USE(c); *LastChar = '\0'; /* just in case */ return(CC_NORMALIZE_COMMAND); } /*ARGSUSED*/ CCRETVAL e_expand_vars(Char c) { USE(c); *LastChar = '\0'; /* just in case */ return(CC_EXPAND_VARS); } /*ARGSUSED*/ CCRETVAL e_which(Char c) { /* do a fast command line which(1) */ USE(c); c_save_inputbuf(); Hist_num = 0; /* for the history commands */ PastBottom(); *LastChar = '\0'; /* just in case */ return(CC_WHICH); } /*ARGSUSED*/ CCRETVAL e_last_item(Char c) { /* insert the last element of the prev. cmd */ struct Hist *hp; struct wordent *wp, *firstp; int i; Char *expanded; USE(c); if (Argument <= 0) return(CC_ERROR); hp = Histlist.Hnext; if (hp == NULL) { /* this is only if no history */ return(CC_ERROR); } wp = (hp->Hlex).prev; if (wp->prev == (struct wordent *) NULL) return(CC_ERROR); /* an empty history entry */ firstp = (hp->Hlex).next; /* back up arg words in lex */ for (i = 0; i < Argument && wp != firstp; i++) { wp = wp->prev; } expanded = expand_lex(wp->prev, 0, i - 1); if (InsertStr(expanded)) { xfree(expanded); return(CC_ERROR); } xfree(expanded); return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_dabbrev_expand(Char c) { /* expand to preceding word matching prefix */ Char *cp, *ncp, *bp; struct Hist *hp; int arg = 0, i; size_t len = 0; int found = 0; Char *hbuf; static int oldevent, hist, word; static Char *start, *oldcursor; USE(c); if (Argument <= 0) return(CC_ERROR); cp = c_preword(Cursor, InputBuf, 1, STRshwordsep); if (cp == Cursor || Isspace(*cp)) return(CC_ERROR); hbuf = NULL; hp = Histlist.Hnext; bp = InputBuf; if (Argument == 1 && eventno == oldevent && cp == start && Cursor == oldcursor && patbuf.len > 0 && Strncmp(patbuf.s, cp, patbuf.len) == 0){ /* continue previous search - go to last match (hist/word) */ if (hist != 0) { /* need to move up history */ for (i = 1; i < hist && hp != NULL; i++) hp = hp->Hnext; if (hp == NULL) /* "can't happen" */ goto err_hbuf; hbuf = expand_lex(&hp->Hlex, 0, INT_MAX); cp = Strend(hbuf); bp = hbuf; hp = hp->Hnext; } cp = c_preword(cp, bp, word, STRshwordsep); } else { /* starting new search */ oldevent = eventno; start = cp; patbuf.len = 0; Strbuf_appendn(&patbuf, cp, Cursor - cp); hist = 0; word = 0; } while (!found) { ncp = c_preword(cp, bp, 1, STRshwordsep); if (ncp == cp || Isspace(*ncp)) { /* beginning of line */ hist++; word = 0; if (hp == NULL) goto err_hbuf; hbuf = expand_lex(&hp->Hlex, 0, INT_MAX); cp = Strend(hbuf); bp = hbuf; hp = hp->Hnext; continue; } else { word++; len = c_endword(ncp-1, cp, 1, STRshwordsep) - ncp + 1; cp = ncp; } if (len > patbuf.len && Strncmp(cp, patbuf.s, patbuf.len) == 0) { /* We don't fully check distinct matches as Gnuemacs does: */ if (Argument > 1) { /* just count matches */ if (++arg >= Argument) found++; } else { /* match if distinct from previous */ if (len != (size_t)(Cursor - start) || Strncmp(cp, start, len) != 0) found++; } } } if (LastChar + len - (Cursor - start) >= InputLim) goto err_hbuf; /* no room */ DeleteBack(Cursor - start); c_insert(len); while (len--) *Cursor++ = *cp++; oldcursor = Cursor; xfree(hbuf); return(CC_REFRESH); err_hbuf: xfree(hbuf); return CC_ERROR; } /*ARGSUSED*/ CCRETVAL e_yank_kill(Char c) { /* almost like GnuEmacs */ int len; Char *kp, *cp; USE(c); if (KillRingLen == 0) /* nothing killed */ return(CC_ERROR); len = Strlen(KillRing[YankPos].buf); if (LastChar + len >= InputLim) return(CC_ERROR); /* end of buffer space */ /* else */ cp = Cursor; /* for speed */ c_insert(len); /* open the space, */ for (kp = KillRing[YankPos].buf; *kp; kp++) /* copy the chars */ *cp++ = *kp; if (Argument == 1) { /* if no arg */ Mark = Cursor; /* mark at beginning, cursor at end */ Cursor = cp; } else { Mark = cp; /* else cursor at beginning, mark at end */ } if (adrof(STRhighlight) && MarkIsSet) { ClearLines(); ClearDisp(); } MarkIsSet = 0; return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_yank_pop(Char c) { /* almost like GnuEmacs */ int m_bef_c, del_len, ins_len; Char *kp, *cp; USE(c); #if 0 /* XXX This "should" be here, but doesn't work, since LastCmd gets set on CC_ERROR and CC_ARGHACK, which it shouldn't(?). (But what about F_ARGFOUR?) I.e. if you hit M-y twice the second one will "succeed" even if the first one wasn't preceded by a yank, and giving an argument is impossible. Now we "succeed" regardless of previous command, which is wrong too of course. */ if (LastCmd != F_YANK_KILL && LastCmd != F_YANK_POP) return(CC_ERROR); #endif if (KillRingLen == 0) /* nothing killed */ return(CC_ERROR); YankPos -= Argument; while (YankPos < 0) YankPos += KillRingLen; YankPos %= KillRingLen; if (Cursor > Mark) { del_len = Cursor - Mark; m_bef_c = 1; } else { del_len = Mark - Cursor; m_bef_c = 0; } ins_len = Strlen(KillRing[YankPos].buf); if (LastChar + ins_len - del_len >= InputLim) return(CC_ERROR); /* end of buffer space */ if (m_bef_c) { c_delbefore(del_len); } else { c_delafter(del_len); } cp = Cursor; /* for speed */ c_insert(ins_len); /* open the space, */ for (kp = KillRing[YankPos].buf; *kp; kp++) /* copy the chars */ *cp++ = *kp; if (m_bef_c) { Mark = Cursor; /* mark at beginning, cursor at end */ Cursor = cp; } else { Mark = cp; /* else cursor at beginning, mark at end */ } if (adrof(STRhighlight) && MarkIsSet) { ClearLines(); ClearDisp(); } MarkIsSet = 0; return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL v_delprev(Char c) /* Backspace key in insert mode */ { int rc; USE(c); rc = CC_ERROR; if (InsertPos != 0) { if (Argument <= Cursor - InsertPos) { c_delbefore(Argument); /* delete before */ rc = CC_REFRESH; } } return(rc); } /* v_delprev */ /*ARGSUSED*/ CCRETVAL e_delprev(Char c) { USE(c); if (Cursor > InputBuf) { c_delbefore(Argument); /* delete before dot */ return(CC_REFRESH); } else { return(CC_ERROR); } } /*ARGSUSED*/ CCRETVAL e_delwordprev(Char c) { Char *cp; USE(c); if (Cursor == InputBuf) return(CC_ERROR); /* else */ cp = c_prev_word(Cursor, InputBuf, Argument); c_push_kill(cp, Cursor); /* save the text */ c_delbefore((int)(Cursor - cp)); /* delete before dot */ return(CC_REFRESH); } /* DCS , 9 Oct 93 * * Changed the names of some of the ^D family of editor functions to * correspond to what they actually do and created new e_delnext_list * for completeness. - * + * * Old names: New names: - * + * * delete-char delete-char-or-eof * F_DELNEXT F_DELNEXT_EOF * e_delnext e_delnext_eof * edelnxt edelnxteof - * delete-char-or-eof delete-char + * delete-char-or-eof delete-char * F_DELNEXT_EOF F_DELNEXT * e_delnext_eof e_delnext * edelnxteof edelnxt * delete-char-or-list delete-char-or-list-or-eof * F_LIST_DELNEXT F_DELNEXT_LIST_EOF * e_list_delnext e_delnext_list_eof * edellsteof * (no old equivalent) delete-char-or-list * F_DELNEXT_LIST * e_delnext_list * e_delnxtlst */ /* added by mtk@ari.ncl.omron.co.jp (920818) */ /* rename e_delnext() -> e_delnext_eof() */ /*ARGSUSED*/ CCRETVAL e_delnext(Char c) { USE(c); if (Cursor == LastChar) {/* if I'm at the end */ if (!VImode) { return(CC_ERROR); } else { if (Cursor != InputBuf) Cursor--; else return(CC_ERROR); } } c_delafter(Argument); /* delete after dot */ if (Cursor > LastChar) Cursor = LastChar; /* bounds check */ return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_delnext_eof(Char c) { USE(c); if (Cursor == LastChar) {/* if I'm at the end */ if (!VImode) { - if (Cursor == InputBuf) { + if (Cursor == InputBuf) { /* if I'm also at the beginning */ so_write(STReof, 4);/* then do a EOF */ flush(); return(CC_EOF); } - else + else return(CC_ERROR); } else { if (Cursor != InputBuf) Cursor--; else return(CC_ERROR); } } c_delafter(Argument); /* delete after dot */ if (Cursor > LastChar) Cursor = LastChar; /* bounds check */ return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_delnext_list(Char c) { USE(c); if (Cursor == LastChar) { /* if I'm at the end */ PastBottom(); *LastChar = '\0'; /* just in case */ return(CC_LIST_CHOICES); } else { c_delafter(Argument); /* delete after dot */ if (Cursor > LastChar) Cursor = LastChar; /* bounds check */ return(CC_REFRESH); } } /*ARGSUSED*/ CCRETVAL e_delnext_list_eof(Char c) { USE(c); if (Cursor == LastChar) { /* if I'm at the end */ if (Cursor == InputBuf) { /* if I'm also at the beginning */ so_write(STReof, 4);/* then do a EOF */ flush(); return(CC_EOF); } else { PastBottom(); *LastChar = '\0'; /* just in case */ return(CC_LIST_CHOICES); } } else { c_delafter(Argument); /* delete after dot */ if (Cursor > LastChar) Cursor = LastChar; /* bounds check */ return(CC_REFRESH); } } /*ARGSUSED*/ CCRETVAL e_list_eof(Char c) { CCRETVAL rv; USE(c); if (Cursor == LastChar && Cursor == InputBuf) { so_write(STReof, 4); /* then do a EOF */ flush(); rv = CC_EOF; } else { PastBottom(); *LastChar = '\0'; /* just in case */ rv = CC_LIST_CHOICES; } return rv; } /*ARGSUSED*/ CCRETVAL e_delwordnext(Char c) { Char *cp; USE(c); if (Cursor == LastChar) return(CC_ERROR); /* else */ cp = c_next_word(Cursor, LastChar, Argument); c_push_kill(Cursor, cp); /* save the text */ c_delafter((int)(cp - Cursor)); /* delete after dot */ if (Cursor > LastChar) Cursor = LastChar; /* bounds check */ return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_toend(Char c) { USE(c); Cursor = LastChar; if (VImode) if (ActionFlag & TCSHOP_DELETE) { c_delfini(); return(CC_REFRESH); } RefCursor(); /* move the cursor */ return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_tobeg(Char c) { USE(c); Cursor = InputBuf; if (VImode) { - while (Isspace(*Cursor)) /* We want FIRST non space character */ - Cursor++; + while (Isspace(*Cursor)) /* We want FIRST non space character */ + Cursor++; if (ActionFlag & TCSHOP_DELETE) { c_delfini(); return(CC_REFRESH); } } RefCursor(); /* move the cursor */ return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_killend(Char c) { USE(c); c_push_kill(Cursor, LastChar); /* copy it */ LastChar = Cursor; /* zap! -- delete to end */ if (Mark > Cursor) Mark = Cursor; MarkIsSet = 0; return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_killbeg(Char c) { USE(c); c_push_kill(InputBuf, Cursor); /* copy it */ c_delbefore((int)(Cursor - InputBuf)); if (Mark && Mark > Cursor) Mark -= Cursor-InputBuf; return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_killall(Char c) { USE(c); c_push_kill(InputBuf, LastChar); /* copy it */ Cursor = Mark = LastChar = InputBuf; /* zap! -- delete all of it */ MarkIsSet = 0; return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_killregion(Char c) { USE(c); if (!Mark) return(CC_ERROR); if (Mark > Cursor) { c_push_kill(Cursor, Mark); /* copy it */ c_delafter((int)(Mark - Cursor)); /* delete it - UNUSED BY VI mode */ Mark = Cursor; } else { /* mark is before cursor */ c_push_kill(Mark, Cursor); /* copy it */ c_delbefore((int)(Cursor - Mark)); } if (adrof(STRhighlight) && MarkIsSet) { ClearLines(); ClearDisp(); } MarkIsSet = 0; return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_copyregion(Char c) { USE(c); if (!Mark) return(CC_ERROR); if (Mark > Cursor) { c_push_kill(Cursor, Mark); /* copy it */ } else { /* mark is before cursor */ c_push_kill(Mark, Cursor); /* copy it */ } return(CC_NORM); /* don't even need to Refresh() */ } /*ARGSUSED*/ CCRETVAL e_charswitch(Char cc) { Char c; USE(cc); /* do nothing if we are at beginning of line or have only one char */ if (Cursor == &InputBuf[0] || LastChar == &InputBuf[1]) { return(CC_ERROR); } if (Cursor < LastChar) { Cursor++; } c = Cursor[-2]; Cursor[-2] = Cursor[-1]; Cursor[-1] = c; return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_gcharswitch(Char cc) { /* gosmacs style ^T */ Char c; USE(cc); if (Cursor > &InputBuf[1]) {/* must have at least two chars entered */ c = Cursor[-2]; Cursor[-2] = Cursor[-1]; Cursor[-1] = c; return(CC_REFRESH); } else { return(CC_ERROR); } } /*ARGSUSED*/ CCRETVAL e_charback(Char c) { USE(c); if (Cursor > InputBuf) { if (Argument > Cursor - InputBuf) Cursor = InputBuf; else Cursor -= Argument; if (VImode) if (ActionFlag & TCSHOP_DELETE) { c_delfini(); return(CC_REFRESH); } RefCursor(); return(CC_NORM); } else { return(CC_ERROR); } } /*ARGSUSED*/ CCRETVAL v_wordback(Char c) { USE(c); if (Cursor == InputBuf) return(CC_ERROR); /* else */ Cursor = c_preword(Cursor, InputBuf, Argument, STRshwspace); /* bounds check */ if (ActionFlag & TCSHOP_DELETE) { c_delfini(); return(CC_REFRESH); } RefCursor(); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_wordback(Char c) { USE(c); if (Cursor == InputBuf) return(CC_ERROR); /* else */ Cursor = c_prev_word(Cursor, InputBuf, Argument); /* bounds check */ - if (VImode) + if (VImode) if (ActionFlag & TCSHOP_DELETE) { c_delfini(); return(CC_REFRESH); } RefCursor(); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_charfwd(Char c) { USE(c); if (Cursor < LastChar) { Cursor += Argument; if (Cursor > LastChar) Cursor = LastChar; if (VImode) if (ActionFlag & TCSHOP_DELETE) { c_delfini(); return(CC_REFRESH); } RefCursor(); return(CC_NORM); } else { return(CC_ERROR); } } /*ARGSUSED*/ CCRETVAL e_wordfwd(Char c) { USE(c); if (Cursor == LastChar) return(CC_ERROR); /* else */ Cursor = c_next_word(Cursor, LastChar, Argument); if (VImode) if (ActionFlag & TCSHOP_DELETE) { c_delfini(); return(CC_REFRESH); } RefCursor(); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL v_wordfwd(Char c) { USE(c); if (Cursor == LastChar) return(CC_ERROR); /* else */ Cursor = c_nexword(Cursor, LastChar, Argument); if (VImode) if (ActionFlag & TCSHOP_DELETE) { c_delfini(); return(CC_REFRESH); } RefCursor(); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL v_wordbegnext(Char c) { USE(c); if (Cursor == LastChar) return(CC_ERROR); /* else */ Cursor = c_next_word(Cursor, LastChar, Argument); if (Cursor < LastChar) Cursor++; if (VImode) if (ActionFlag & TCSHOP_DELETE) { c_delfini(); return(CC_REFRESH); } RefCursor(); return(CC_NORM); } /*ARGSUSED*/ static CCRETVAL v_repeat_srch(int c) { CCRETVAL rv = CC_ERROR; #ifdef SDEBUG xprintf("dir %d patlen %d patbuf %S\n", c, (int)patbuf.len, patbuf.s); #endif LastCmd = (KEYCMD) c; /* Hack to stop c_hsetpat */ LastChar = InputBuf; switch (c) { case F_DOWN_SEARCH_HIST: rv = e_down_search_hist(0); break; case F_UP_SEARCH_HIST: rv = e_up_search_hist(0); break; default: break; } return rv; } static CCRETVAL v_csearch_back(Char ch, int count, int tflag) { Char *cp; cp = Cursor; while (count--) { - if (*cp == ch) + if (*cp == ch) cp--; - while (cp > InputBuf && *cp != ch) + while (cp > InputBuf && *cp != ch) cp--; } if (cp < InputBuf || (cp == InputBuf && *cp != ch)) return(CC_ERROR); if (*cp == ch && tflag) cp++; Cursor = cp; if (ActionFlag & TCSHOP_DELETE) { Cursor++; c_delfini(); return(CC_REFRESH); } RefCursor(); return(CC_NORM); } static CCRETVAL v_csearch_fwd(Char ch, int count, int tflag) { Char *cp; cp = Cursor; while (count--) { - if (*cp == ch) + if (*cp == ch) cp++; - while (cp < LastChar && *cp != ch) + while (cp < LastChar && *cp != ch) cp++; } if (cp >= LastChar) return(CC_ERROR); if (*cp == ch && tflag) cp--; Cursor = cp; if (ActionFlag & TCSHOP_DELETE) { Cursor++; c_delfini(); return(CC_REFRESH); } RefCursor(); return(CC_NORM); } /*ARGSUSED*/ static CCRETVAL v_action(int c) { Char *cp, *kp; if (ActionFlag == TCSHOP_DELETE) { ActionFlag = TCSHOP_NOP; ActionPos = 0; - + UndoSize = 0; kp = UndoBuf; for (cp = InputBuf; cp < LastChar; cp++) { *kp++ = *cp; UndoSize++; } - + UndoAction = TCSHOP_INSERT; UndoPtr = InputBuf; LastChar = InputBuf; Cursor = InputBuf; if (c & TCSHOP_INSERT) c_alternativ_key_map(0); - + return(CC_REFRESH); } #ifdef notdef else if (ActionFlag == TCSHOP_NOP) { #endif ActionPos = Cursor; ActionFlag = c; return(CC_ARGHACK); /* Do NOT clear out argument */ #ifdef notdef } else { ActionFlag = 0; ActionPos = 0; return(CC_ERROR); } #endif } #ifdef COMMENT /* by: Brian Allison */ static void c_get_word(Char **begin, Char **end) { Char *cp; cp = &Cursor[0]; while (Argument--) { while ((cp <= LastChar) && (isword(*cp))) cp++; *end = --cp; while ((cp >= InputBuf) && (isword(*cp))) cp--; *begin = ++cp; } } #endif /* COMMENT */ /*ARGSUSED*/ CCRETVAL e_uppercase(Char c) { Char *cp, *end; USE(c); end = c_next_word(Cursor, LastChar, Argument); for (cp = Cursor; cp < end; cp++) /* PWP: was cp=begin */ if (Islower(*cp)) *cp = Toupper(*cp); Cursor = end; if (Cursor > LastChar) Cursor = LastChar; return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_capitalcase(Char c) { Char *cp, *end; USE(c); end = c_next_word(Cursor, LastChar, Argument); cp = Cursor; for (; cp < end; cp++) { if (Isalpha(*cp)) { if (Islower(*cp)) *cp = Toupper(*cp); cp++; break; } } for (; cp < end; cp++) if (Isupper(*cp)) *cp = Tolower(*cp); Cursor = end; if (Cursor > LastChar) Cursor = LastChar; return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_lowercase(Char c) { Char *cp, *end; USE(c); end = c_next_word(Cursor, LastChar, Argument); for (cp = Cursor; cp < end; cp++) if (Isupper(*cp)) *cp = Tolower(*cp); Cursor = end; if (Cursor > LastChar) Cursor = LastChar; return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_set_mark(Char c) { USE(c); if (adrof(STRhighlight) && MarkIsSet && Mark != Cursor) { ClearLines(); ClearDisp(); Refresh(); } Mark = Cursor; MarkIsSet = 1; return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_exchange_mark(Char c) { Char *cp; USE(c); cp = Cursor; Cursor = Mark; Mark = cp; RefCursor(); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_argfour(Char c) { /* multiply current argument by 4 */ USE(c); if (Argument > 1000000) return CC_ERROR; DoingArg = 1; Argument *= 4; return(CC_ARGHACK); } static void quote_mode_cleanup(void *unused) { USE(unused); QuoteModeOff(); } /*ARGSUSED*/ CCRETVAL e_quote(Char c) { Char ch; int num; USE(c); QuoteModeOn(); cleanup_push(&c, quote_mode_cleanup); /* Using &c just as a mark */ num = GetNextChar(&ch); cleanup_until(&c); if (num == 1) return e_insert(ch); else return e_send_eof(0); } /*ARGSUSED*/ CCRETVAL e_metanext(Char c) { USE(c); MetaNext = 1; return(CC_ARGHACK); /* preserve argument */ } #ifdef notdef /*ARGSUSED*/ CCRETVAL e_extendnext(Char c) { CurrentKeyMap = CcAltMap; return(CC_ARGHACK); /* preserve argument */ } #endif /*ARGSUSED*/ CCRETVAL v_insbeg(Char c) { /* move to beginning of line and start vi * insert mode */ USE(c); Cursor = InputBuf; InsertPos = Cursor; UndoPtr = Cursor; UndoAction = TCSHOP_DELETE; RefCursor(); /* move the cursor */ c_alternativ_key_map(0); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL v_replone(Char c) { /* vi mode overwrite one character */ USE(c); c_alternativ_key_map(0); inputmode = MODE_REPLACE_1; UndoAction = TCSHOP_CHANGE; /* Set Up for VI undo command */ UndoPtr = Cursor; UndoSize = 0; return(CC_NORM); } /*ARGSUSED*/ CCRETVAL v_replmode(Char c) { /* vi mode start overwriting */ USE(c); c_alternativ_key_map(0); inputmode = MODE_REPLACE; UndoAction = TCSHOP_CHANGE; /* Set Up for VI undo command */ UndoPtr = Cursor; UndoSize = 0; return(CC_NORM); } /*ARGSUSED*/ CCRETVAL v_substchar(Char c) { /* vi mode substitute for one char */ USE(c); c_delafter(Argument); c_alternativ_key_map(0); return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL v_substline(Char c) { /* vi mode replace whole line */ USE(c); (void) e_killall(0); c_alternativ_key_map(0); return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL v_chgtoend(Char c) { /* vi mode change to end of line */ USE(c); (void) e_killend(0); c_alternativ_key_map(0); return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL v_insert(Char c) { /* vi mode start inserting */ USE(c); c_alternativ_key_map(0); InsertPos = Cursor; UndoPtr = Cursor; UndoAction = TCSHOP_DELETE; return(CC_NORM); } /*ARGSUSED*/ CCRETVAL v_add(Char c) { /* vi mode start adding */ USE(c); c_alternativ_key_map(0); if (Cursor < LastChar) { Cursor++; if (Cursor > LastChar) Cursor = LastChar; RefCursor(); } InsertPos = Cursor; UndoPtr = Cursor; UndoAction = TCSHOP_DELETE; return(CC_NORM); } /*ARGSUSED*/ CCRETVAL v_addend(Char c) { /* vi mode to add at end of line */ USE(c); c_alternativ_key_map(0); Cursor = LastChar; InsertPos = LastChar; /* Mark where insertion begins */ UndoPtr = LastChar; UndoAction = TCSHOP_DELETE; RefCursor(); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL v_change_case(Char cc) { Char c; USE(cc); if (Cursor < LastChar) { #ifndef WINNT_NATIVE c = *Cursor; #else c = CHAR & *Cursor; #endif /* WINNT_NATIVE */ if (Isupper(c)) *Cursor++ = Tolower(c); else if (Islower(c)) *Cursor++ = Toupper(c); else Cursor++; RefPlusOne(1); /* fast refresh for one char */ return(CC_NORM); } return(CC_ERROR); } /*ARGSUSED*/ CCRETVAL e_expand(Char c) { Char *p; USE(c); for (p = InputBuf; Isspace(*p); p++) continue; if (p == LastChar) return(CC_ERROR); justpr++; Expand++; return(e_newline(0)); } /*ARGSUSED*/ CCRETVAL e_startover(Char c) { /* erase all of current line, start again */ USE(c); ResetInLine(0); /* reset the input pointers */ return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_redisp(Char c) { USE(c); ClearLines(); ClearDisp(); return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_cleardisp(Char c) { USE(c); ClearScreen(); /* clear the whole real screen */ ClearDisp(); /* reset everything */ return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_tty_int(Char c) -{ +{ USE(c); #if defined(_MINIX) || defined(WINNT_NATIVE) /* SAK PATCH: erase all of current line, start again */ ResetInLine(0); /* reset the input pointers */ xputchar('\n'); ClearDisp(); return (CC_REFRESH); #else /* !_MINIX && !WINNT_NATIVE */ /* do no editing */ return (CC_NORM); #endif /* _MINIX || WINNT_NATIVE */ } /* * From: ghazi@cesl.rutgers.edu (Kaveh R. Ghazi) * Function to send a character back to the input stream in cooked * mode. Only works if we have TIOCSTI */ /*ARGSUSED*/ CCRETVAL e_stuff_char(Char c) { #ifdef TIOCSTI int was_raw = Tty_raw_mode; char buf[MB_LEN_MAX]; size_t i, len; if (was_raw) (void) Cookedmode(); (void) xwrite(SHIN, "\n", 1); len = one_wctomb(buf, c); for (i = 0; i < len; i++) (void) ioctl(SHIN, TIOCSTI, (ioctl_t) &buf[i]); if (was_raw) (void) Rawmode(); return(e_redisp(c)); -#else /* !TIOCSTI */ +#else /* !TIOCSTI */ return(CC_ERROR); -#endif /* !TIOCSTI */ +#endif /* !TIOCSTI */ } /*ARGSUSED*/ CCRETVAL e_insovr(Char c) { USE(c); inputmode = (inputmode == MODE_INSERT ? MODE_REPLACE : MODE_INSERT); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_tty_dsusp(Char c) { USE(c); /* do no editing */ return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_tty_flusho(Char c) { USE(c); /* do no editing */ return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_tty_quit(Char c) { USE(c); /* do no editing */ return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_tty_tsusp(Char c) { USE(c); /* do no editing */ return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_tty_stopo(Char c) { USE(c); /* do no editing */ return(CC_NORM); } /* returns the number of (attempted) expansions */ int ExpandHistory(void) { *LastChar = '\0'; /* just in case */ return c_substitute(); } /*ARGSUSED*/ CCRETVAL e_expand_history(Char c) { USE(c); (void)ExpandHistory(); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_magic_space(Char c) { USE(c); *LastChar = '\0'; /* just in case */ (void)c_substitute(); return(e_insert(' ')); } /*ARGSUSED*/ CCRETVAL e_inc_fwd(Char c) { CCRETVAL ret; USE(c); patbuf.len = 0; MarkIsSet = 0; ret = e_inc_search(F_DOWN_SEARCH_HIST); if (adrof(STRhighlight) && IncMatchLen) { IncMatchLen = 0; ClearLines(); ClearDisp(); Refresh(); } IncMatchLen = 0; return ret; } /*ARGSUSED*/ CCRETVAL e_inc_back(Char c) { CCRETVAL ret; USE(c); patbuf.len = 0; MarkIsSet = 0; ret = e_inc_search(F_UP_SEARCH_HIST); if (adrof(STRhighlight) && IncMatchLen) { IncMatchLen = 0; ClearLines(); ClearDisp(); Refresh(); } IncMatchLen = 0; return ret; } /*ARGSUSED*/ CCRETVAL e_copyprev(Char c) { Char *cp, *oldc, *dp; USE(c); if (Cursor == InputBuf) return(CC_ERROR); /* else */ oldc = Cursor; /* does a bounds check */ - cp = c_prev_word(Cursor, InputBuf, Argument); + cp = c_prev_word(Cursor, InputBuf, Argument); c_insert((int)(oldc - cp)); for (dp = oldc; cp < oldc && dp < LastChar; cp++) *dp++ = *cp; Cursor = dp; /* put cursor at end */ return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL e_tty_starto(Char c) { USE(c); /* do no editing */ return(CC_NORM); } /*ARGSUSED*/ CCRETVAL e_load_average(Char c) { USE(c); PastBottom(); #ifdef TIOCSTAT /* * Here we pass &c to the ioctl because some os's (NetBSD) expect it * there even if they don't use it. (lukem@netbsd.org) */ - if (ioctl(SHIN, TIOCSTAT, (ioctl_t) &c) < 0) + if (ioctl(SHIN, TIOCSTAT, (ioctl_t) &c) < 0) #endif xprintf("%s", CGETS(5, 1, "Load average unavailable\n")); return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL v_chgmeta(Char c) { USE(c); /* * Delete with insert == change: first we delete and then we leave in * insert mode. */ return(v_action(TCSHOP_DELETE|TCSHOP_INSERT)); } /*ARGSUSED*/ CCRETVAL v_delmeta(Char c) { USE(c); return(v_action(TCSHOP_DELETE)); } /*ARGSUSED*/ CCRETVAL v_endword(Char c) { USE(c); if (Cursor == LastChar) return(CC_ERROR); /* else */ Cursor = c_endword(Cursor, LastChar, Argument, STRshwspace); if (ActionFlag & TCSHOP_DELETE) { Cursor++; c_delfini(); return(CC_REFRESH); } RefCursor(); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL v_eword(Char c) { USE(c); if (Cursor == LastChar) return(CC_ERROR); /* else */ Cursor = c_eword(Cursor, LastChar, Argument); if (ActionFlag & TCSHOP_DELETE) { Cursor++; c_delfini(); return(CC_REFRESH); } RefCursor(); return(CC_NORM); } /*ARGSUSED*/ CCRETVAL v_char_fwd(Char c) { Char ch; USE(c); if (GetNextChar(&ch) != 1) return e_send_eof(0); srch_dir = CHAR_FWD; srch_char = ch; return v_csearch_fwd(ch, Argument, 0); } /*ARGSUSED*/ CCRETVAL v_char_back(Char c) { Char ch; USE(c); if (GetNextChar(&ch) != 1) return e_send_eof(0); srch_dir = CHAR_BACK; srch_char = ch; return v_csearch_back(ch, Argument, 0); } /*ARGSUSED*/ CCRETVAL v_charto_fwd(Char c) { Char ch; USE(c); if (GetNextChar(&ch) != 1) return e_send_eof(0); return v_csearch_fwd(ch, Argument, 1); } /*ARGSUSED*/ CCRETVAL v_charto_back(Char c) { Char ch; USE(c); if (GetNextChar(&ch) != 1) return e_send_eof(0); return v_csearch_back(ch, Argument, 1); } /*ARGSUSED*/ CCRETVAL v_rchar_fwd(Char c) { USE(c); if (srch_char == 0) return CC_ERROR; - return srch_dir == CHAR_FWD ? v_csearch_fwd(srch_char, Argument, 0) : + return srch_dir == CHAR_FWD ? v_csearch_fwd(srch_char, Argument, 0) : v_csearch_back(srch_char, Argument, 0); } /*ARGSUSED*/ CCRETVAL v_rchar_back(Char c) { USE(c); if (srch_char == 0) return CC_ERROR; - return srch_dir == CHAR_BACK ? v_csearch_fwd(srch_char, Argument, 0) : + return srch_dir == CHAR_BACK ? v_csearch_fwd(srch_char, Argument, 0) : v_csearch_back(srch_char, Argument, 0); } /*ARGSUSED*/ CCRETVAL v_undo(Char c) { int loop; Char *kp, *cp; Char temp; int size; USE(c); switch (UndoAction) { case TCSHOP_DELETE|TCSHOP_INSERT: case TCSHOP_DELETE: if (UndoSize == 0) return(CC_NORM); cp = UndoPtr; kp = UndoBuf; for (loop=0; loop < UndoSize; loop++) /* copy the chars */ *kp++ = *cp++; /* into UndoBuf */ for (cp = UndoPtr; cp <= LastChar; cp++) *cp = cp[UndoSize]; LastChar -= UndoSize; Cursor = UndoPtr; - + UndoAction = TCSHOP_INSERT; break; case TCSHOP_INSERT: if (UndoSize == 0) return(CC_NORM); cp = UndoPtr; Cursor = UndoPtr; kp = UndoBuf; c_insert(UndoSize); /* open the space, */ for (loop = 0; loop < UndoSize; loop++) /* copy the chars */ *cp++ = *kp++; UndoAction = TCSHOP_DELETE; break; case TCSHOP_CHANGE: if (UndoSize == 0) return(CC_NORM); cp = UndoPtr; Cursor = UndoPtr; kp = UndoBuf; size = (int)(Cursor-LastChar); /* NOT NSL independant */ if (size < UndoSize) size = UndoSize; for (loop = 0; loop < size; loop++) { temp = *kp; *kp++ = *cp; *cp++ = temp; } break; default: return(CC_ERROR); } return(CC_REFRESH); } /*ARGSUSED*/ CCRETVAL v_ush_meta(Char c) { USE(c); return v_search(F_UP_SEARCH_HIST); } /*ARGSUSED*/ CCRETVAL v_dsh_meta(Char c) { USE(c); return v_search(F_DOWN_SEARCH_HIST); } /*ARGSUSED*/ CCRETVAL v_rsrch_fwd(Char c) { USE(c); if (patbuf.len == 0) return(CC_ERROR); return(v_repeat_srch(searchdir)); } /*ARGSUSED*/ CCRETVAL v_rsrch_back(Char c) { USE(c); if (patbuf.len == 0) return(CC_ERROR); - return(v_repeat_srch(searchdir == F_UP_SEARCH_HIST ? + return(v_repeat_srch(searchdir == F_UP_SEARCH_HIST ? F_DOWN_SEARCH_HIST : F_UP_SEARCH_HIST)); } #ifndef WINNT_NATIVE -/* Since ed.defns.h is generated from ed.defns.c, these empty +/* Since ed.defns.h is generated from ed.defns.c, these empty functions will keep the F_NUM_FNS consistent */ CCRETVAL e_copy_to_clipboard(Char c) { USE(c); return CC_ERROR; } CCRETVAL e_paste_from_clipboard(Char c) { USE(c); return (CC_ERROR); } CCRETVAL e_dosify_next(Char c) { USE(c); return (CC_ERROR); } CCRETVAL e_dosify_prev(Char c) { USE(c); return (CC_ERROR); } CCRETVAL e_page_up(Char c) { USE(c); return (CC_ERROR); } CCRETVAL e_page_down(Char c) { USE(c); return (CC_ERROR); } #endif /* !WINNT_NATIVE */ #ifdef notdef void MoveCursor(int n) /* move cursor + right - left char */ { Cursor = Cursor + n; if (Cursor < InputBuf) Cursor = InputBuf; if (Cursor > LastChar) Cursor = LastChar; return; } Char * GetCursor(void) { return(Cursor); } int PutCursor(Char *p) { if (p < InputBuf || p > LastChar) return 1; /* Error */ Cursor = p; return 0; } #endif diff --git a/contrib/tcsh/ed.defns.c b/contrib/tcsh/ed.defns.c index 02ae764510af..f4030b530f6d 100644 --- a/contrib/tcsh/ed.defns.c +++ b/contrib/tcsh/ed.defns.c @@ -1,1971 +1,1971 @@ /* * ed.defns.c: Editor function definitions and initialization */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" static void ed_InitMetaBindings (void); PFCmd CcFuncTbl[] = { /* table of available commands */ e_unassigned, /* no #define here -- this is a dummy to detect initing of the key map */ e_unassigned, #define F_UNASSIGNED 1 e_insert, #define F_INSERT 2 e_newline, #define F_NEWLINE 3 e_delprev, #define F_DELPREV 4 e_delnext, #define F_DELNEXT 5 e_toend, #define F_TOEND 6 e_tobeg, #define F_TOBEG 7 e_charback, #define F_CHARBACK 8 e_charfwd, #define F_CHARFWD 9 e_quote, #define F_QUOTE 10 e_startover, #define F_STARTOVER 11 e_redisp, #define F_REDISP 12 e_tty_int, #define F_TTY_INT 13 e_wordback, #define F_WORDBACK 14 e_wordfwd, #define F_WORDFWD 15 e_cleardisp, #define F_CLEARDISP 16 e_complete, #define F_COMPLETE 17 e_correct, #define F_CORRECT 18 e_up_hist, #define F_UP_HIST 19 e_down_hist, #define F_DOWN_HIST 20 e_up_search_hist, #define F_UP_SEARCH_HIST 21 e_down_search_hist, #define F_DOWN_SEARCH_HIST 22 e_helpme, #define F_HELPME 23 e_list_choices, #define F_LIST_CHOICES 24 e_delwordprev, #define F_DELWORDPREV 25 e_delwordnext, #define F_DELWORDNEXT 26 e_digit, #define F_DIGIT 27 e_killend, #define F_KILLEND 28 e_killbeg, #define F_KILLBEG 29 e_metanext, #define F_METANEXT 30 e_send_eof, #define F_SEND_EOF 31 e_charswitch, #define F_CHARSWITCH 32 e_which, #define F_WHICH 33 e_yank_kill, #define F_YANK_KILL 34 e_tty_dsusp, #define F_TTY_DSUSP 35 e_tty_flusho, #define F_TTY_FLUSHO 36 e_tty_quit, #define F_TTY_QUIT 37 e_tty_tsusp, #define F_TTY_TSUSP 38 e_tty_stopo, #define F_TTY_STOPO 39 e_tty_starto, #define F_TTY_STARTO 40 e_argfour, #define F_ARGFOUR 41 e_set_mark, #define F_SET_MARK 42 e_exchange_mark, #define F_EXCHANGE_MARK 43 e_last_item, #define F_LAST_ITEM 44 e_delnext_list_eof, #define F_DELNEXT_LIST_EOF 45 v_cmd_mode, #define V_CMD_MODE 46 v_insert, #define V_INSERT 47 e_argdigit, #define F_ARGDIGIT 48 e_killregion, #define F_KILLREGION 49 e_copyregion, #define F_COPYREGION 50 e_gcharswitch, #define F_GCHARSWITCH 51 e_run_fg_editor, #define F_RUN_FG_EDITOR 52 e_unassigned, /* place holder for sequence lead in character */ #define F_XKEY 53 e_uppercase, #define F_CASEUPPER 54 e_lowercase, #define F_CASELOWER 55 e_capitalcase, #define F_CASECAPITAL 56 v_zero, #define V_ZERO 57 v_add, #define V_ADD 58 v_addend, #define V_ADDEND 59 v_wordbegnext, #define V_WORDBEGNEXT 60 e_killall, #define F_KILLALL 61 e_unassigned, /* F_EXTENDNEXT removed */ v_insbeg, #define V_INSBEG 63 v_replmode, #define V_REPLMODE 64 v_replone, #define V_REPLONE 65 v_substline, #define V_SUBSTLINE 66 v_substchar, #define V_SUBSTCHAR 67 v_chgtoend, #define V_CHGTOEND 68 e_list_eof, #define F_LIST_EOF 69 e_list_glob, #define F_LIST_GLOB 70 e_expand_history, #define F_EXPAND_HISTORY 71 e_magic_space, #define F_MAGIC_SPACE 72 e_insovr, #define F_INSOVR 73 v_cm_complete, #define V_CM_COMPLETE 74 e_copyprev, #define F_COPYPREV 75 e_correctl, #define F_CORRECT_L 76 e_expand_glob, #define F_EXPAND_GLOB 77 e_expand_vars, #define F_EXPAND_VARS 78 e_toggle_hist, #define F_TOGGLE_HIST 79 v_change_case, #define V_CHGCASE 80 e_expand, #define F_EXPAND 81 e_load_average, #define F_LOAD_AVERAGE 82 v_delprev, #define V_DELPREV 83 v_delmeta, #define V_DELMETA 84 v_wordfwd, #define V_WORDFWD 85 v_wordback, #define V_WORDBACK 86 v_endword, #define V_ENDWORD 87 v_eword, #define V_EWORD 88 v_undo, #define V_UNDO 89 v_ush_meta, #define V_USH_META 90 v_dsh_meta, #define V_DSH_META 91 v_rsrch_fwd, #define V_RSRCH_FWD 92 v_rsrch_back, #define V_RSRCH_BACK 93 v_char_fwd, #define V_CHAR_FWD 94 v_char_back, #define V_CHAR_BACK 95 v_chgmeta, #define V_CHGMETA 96 e_inc_fwd, #define F_INC_FWD 97 e_inc_back, #define F_INC_BACK 98 v_rchar_fwd, #define V_RCHAR_FWD 99 v_rchar_back, #define V_RCHAR_BACK 100 v_charto_fwd, #define V_CHARTO_FWD 101 v_charto_back, #define V_CHARTO_BACK 102 e_normalize_path, #define F_PATH_NORM 103 e_delnext_eof, /* added by mtk@ari.ncl.omron.co.jp (920818) */ #define F_DELNEXT_EOF 104 - e_stuff_char, + e_stuff_char, #define F_STUFF_CHAR 105 e_complete_all, #define F_COMPLETE_ALL 106 e_list_all, #define F_LIST_ALL 107 e_complete_fwd, #define F_COMPLETE_FWD 108 e_complete_back, #define F_COMPLETE_BACK 109 e_delnext_list, #define F_DELNEXT_LIST 110 e_normalize_command, #define F_COMMAND_NORM 111 e_dabbrev_expand, #define F_DABBREV_EXPAND 112 e_dosify_next, #define F_DOSIFY_NEXT 113 e_dosify_prev, #define F_DOSIFY_PREV 114 e_page_up, #define F_PAGE_UP 115 e_page_down, #define F_PAGE_DOWN 116 e_yank_pop, #define F_YANK_POP 117 e_newline_hold, #define F_NEWLINE_HOLD 118 e_newline_down_hist, #define F_NEWLINE_DOWN_HIST 119 0 /* DUMMY VALUE */ #define F_NUM_FNS 120 }; KEYCMD NumFuns = F_NUM_FNS; KEYCMD CcKeyMap[NT_NUM_KEYS]; /* the real key map */ KEYCMD CcAltMap[NT_NUM_KEYS]; /* the alternative key map */ #define F_NUM_FUNCNAMES (F_NUM_FNS + 2) struct KeyFuncs FuncNames[F_NUM_FUNCNAMES]; #ifdef WINNT_NATIVE extern KEYCMD CcEmacsMap[]; extern KEYCMD CcViMap[]; extern KEYCMD CcViCmdMap[]; #else /* !WINNT_NATIVE*/ KEYCMD CcEmacsMap[] = { /* keymap table, each index into above tbl; should be 256*sizeof(KEYCMD) bytes long */ F_SET_MARK, /* ^@ */ F_TOBEG, /* ^A */ F_CHARBACK, /* ^B */ F_TTY_INT, /* ^C */ F_DELNEXT_LIST_EOF, /* ^D */ F_TOEND, /* ^E */ F_CHARFWD, /* ^F */ F_UNASSIGNED, /* ^G */ F_DELPREV, /* ^H */ F_COMPLETE, /* ^I */ F_NEWLINE, /* ^J */ F_KILLEND, /* ^K */ F_CLEARDISP, /* ^L */ F_NEWLINE, /* ^M */ F_DOWN_HIST, /* ^N */ F_TTY_FLUSHO, /* ^O */ F_UP_HIST, /* ^P */ F_TTY_STARTO, /* ^Q */ F_REDISP, /* ^R */ F_TTY_STOPO, /* ^S */ F_CHARSWITCH, /* ^T */ F_KILLALL, /* ^U */ F_QUOTE, /* ^V */ F_KILLREGION, /* ^W */ F_XKEY, /* ^X */ F_YANK_KILL, /* ^Y */ F_TTY_TSUSP, /* ^Z */ F_METANEXT, /* ^[ */ F_TTY_QUIT, /* ^\ */ F_TTY_DSUSP, /* ^] */ F_UNASSIGNED, /* ^^ */ F_UNASSIGNED, /* ^_ */ F_INSERT, /* SPACE */ F_INSERT, /* ! */ F_INSERT, /* " */ F_INSERT, /* # */ F_INSERT, /* $ */ F_INSERT, /* % */ F_INSERT, /* & */ F_INSERT, /* ' */ F_INSERT, /* ( */ F_INSERT, /* ) */ F_INSERT, /* * */ F_INSERT, /* + */ F_INSERT, /* , */ F_INSERT, /* - */ F_INSERT, /* . */ F_INSERT, /* / */ F_DIGIT, /* 0 */ F_DIGIT, /* 1 */ F_DIGIT, /* 2 */ F_DIGIT, /* 3 */ F_DIGIT, /* 4 */ F_DIGIT, /* 5 */ F_DIGIT, /* 6 */ F_DIGIT, /* 7 */ F_DIGIT, /* 8 */ F_DIGIT, /* 9 */ F_INSERT, /* : */ F_INSERT, /* ; */ F_INSERT, /* < */ F_INSERT, /* = */ F_INSERT, /* > */ F_INSERT, /* ? */ F_INSERT, /* @ */ F_INSERT, /* A */ F_INSERT, /* B */ F_INSERT, /* C */ F_INSERT, /* D */ F_INSERT, /* E */ F_INSERT, /* F */ F_INSERT, /* G */ F_INSERT, /* H */ F_INSERT, /* I */ F_INSERT, /* J */ F_INSERT, /* K */ F_INSERT, /* L */ F_INSERT, /* M */ F_INSERT, /* N */ F_INSERT, /* O */ F_INSERT, /* P */ F_INSERT, /* Q */ F_INSERT, /* R */ F_INSERT, /* S */ F_INSERT, /* T */ F_INSERT, /* U */ F_INSERT, /* V */ F_INSERT, /* W */ F_INSERT, /* X */ F_INSERT, /* Y */ F_INSERT, /* Z */ F_INSERT, /* [ */ F_INSERT, /* \ */ F_INSERT, /* ] */ F_INSERT, /* ^ */ F_INSERT, /* _ */ F_INSERT, /* ` */ F_INSERT, /* a */ F_INSERT, /* b */ F_INSERT, /* c */ F_INSERT, /* d */ F_INSERT, /* e */ F_INSERT, /* f */ F_INSERT, /* g */ F_INSERT, /* h */ F_INSERT, /* i */ F_INSERT, /* j */ F_INSERT, /* k */ F_INSERT, /* l */ F_INSERT, /* m */ F_INSERT, /* n */ F_INSERT, /* o */ F_INSERT, /* p */ F_INSERT, /* q */ F_INSERT, /* r */ F_INSERT, /* s */ F_INSERT, /* t */ F_INSERT, /* u */ F_INSERT, /* v */ F_INSERT, /* w */ F_INSERT, /* x */ F_INSERT, /* y */ F_INSERT, /* z */ F_INSERT, /* { */ F_INSERT, /* | */ F_INSERT, /* } */ F_INSERT, /* ~ */ F_DELPREV, /* ^? */ F_UNASSIGNED, /* M-^@ */ F_UNASSIGNED, /* M-^A */ F_UNASSIGNED, /* M-^B */ F_UNASSIGNED, /* M-^C */ F_LIST_CHOICES, /* M-^D */ F_UNASSIGNED, /* M-^E */ F_UNASSIGNED, /* M-^F */ F_UNASSIGNED, /* M-^G */ F_DELWORDPREV, /* M-^H */ F_COMPLETE, /* M-^I */ F_UNASSIGNED, /* M-^J */ F_UNASSIGNED, /* M-^K */ F_CLEARDISP, /* M-^L */ F_UNASSIGNED, /* M-^M */ F_UNASSIGNED, /* M-^N */ F_UNASSIGNED, /* M-^O */ F_UNASSIGNED, /* M-^P */ F_UNASSIGNED, /* M-^Q */ F_UNASSIGNED, /* M-^R */ F_UNASSIGNED, /* M-^S */ F_UNASSIGNED, /* M-^T */ F_UNASSIGNED, /* M-^U */ F_UNASSIGNED, /* M-^V */ F_UNASSIGNED, /* M-^W */ F_UNASSIGNED, /* M-^X */ F_UNASSIGNED, /* M-^Y */ F_RUN_FG_EDITOR, /* M-^Z */ F_COMPLETE, /* M-^[ */ F_UNASSIGNED, /* M-^\ */ F_UNASSIGNED, /* M-^] */ F_UNASSIGNED, /* M-^^ */ F_COPYPREV, /* M-^_ */ F_EXPAND_HISTORY, /* M-SPACE */ F_EXPAND_HISTORY, /* M-! */ F_UNASSIGNED, /* M-" */ F_UNASSIGNED, /* M-# */ F_CORRECT_L, /* M-$ */ F_UNASSIGNED, /* M-% */ F_UNASSIGNED, /* M-& */ F_UNASSIGNED, /* M-' */ F_UNASSIGNED, /* M-( */ F_UNASSIGNED, /* M-) */ F_UNASSIGNED, /* M-* */ F_UNASSIGNED, /* M-+ */ F_UNASSIGNED, /* M-, */ F_UNASSIGNED, /* M-- */ F_UNASSIGNED, /* M-. */ F_DABBREV_EXPAND, /* M-/ */ F_ARGDIGIT, /* M-0 */ F_ARGDIGIT, /* M-1 */ F_ARGDIGIT, /* M-2 */ F_ARGDIGIT, /* M-3 */ F_ARGDIGIT, /* M-4 */ F_ARGDIGIT, /* M-5 */ F_ARGDIGIT, /* M-6 */ F_ARGDIGIT, /* M-7 */ F_ARGDIGIT, /* M-8 */ F_ARGDIGIT, /* M-9 */ F_UNASSIGNED, /* M-: */ F_UNASSIGNED, /* M-; */ F_UNASSIGNED, /* M-< */ F_UNASSIGNED, /* M-= */ F_UNASSIGNED, /* M-> */ F_WHICH, /* M-? */ F_UNASSIGNED, /* M-@ */ F_NEWLINE_HOLD, /* M-A */ F_WORDBACK, /* M-B */ F_CASECAPITAL, /* M-C */ F_DELWORDNEXT, /* M-D */ F_UNASSIGNED, /* M-E */ F_WORDFWD, /* M-F */ F_UNASSIGNED, /* M-G */ F_HELPME, /* M-H */ F_UNASSIGNED, /* M-I */ F_UNASSIGNED, /* M-J */ F_UNASSIGNED, /* M-K */ F_CASELOWER, /* M-L */ F_UNASSIGNED, /* M-M */ F_DOWN_SEARCH_HIST, /* M-N */ F_XKEY, /* M-O *//* extended key esc PWP Mar 88 */ F_UP_SEARCH_HIST, /* M-P */ F_UNASSIGNED, /* M-Q */ F_TOGGLE_HIST, /* M-R */ F_CORRECT, /* M-S */ F_UNASSIGNED, /* M-T */ F_CASEUPPER, /* M-U */ F_UNASSIGNED, /* M-V */ F_COPYREGION, /* M-W */ F_UNASSIGNED, /* M-X */ F_YANK_POP, /* M-Y */ F_UNASSIGNED, /* M-Z */ F_XKEY, /* M-[ *//* extended key esc -mf Oct 87 */ F_UNASSIGNED, /* M-\ */ F_UNASSIGNED, /* M-] */ F_UNASSIGNED, /* M-^ */ F_LAST_ITEM, /* M-_ */ F_UNASSIGNED, /* M-` */ F_NEWLINE_HOLD, /* M-a */ F_WORDBACK, /* M-b */ F_CASECAPITAL, /* M-c */ F_DELWORDNEXT, /* M-d */ F_UNASSIGNED, /* M-e */ F_WORDFWD, /* M-f */ F_UNASSIGNED, /* M-g */ F_HELPME, /* M-h */ F_UNASSIGNED, /* M-i */ F_UNASSIGNED, /* M-j */ F_UNASSIGNED, /* M-k */ F_CASELOWER, /* M-l */ F_UNASSIGNED, /* M-m */ F_DOWN_SEARCH_HIST, /* M-n */ F_UNASSIGNED, /* M-o */ F_UP_SEARCH_HIST, /* M-p */ F_UNASSIGNED, /* M-q */ F_TOGGLE_HIST, /* M-r */ F_CORRECT, /* M-s */ F_UNASSIGNED, /* M-t */ F_CASEUPPER, /* M-u */ F_UNASSIGNED, /* M-v */ F_COPYREGION, /* M-w */ F_UNASSIGNED, /* M-x */ F_YANK_POP, /* M-y */ F_UNASSIGNED, /* M-z */ F_UNASSIGNED, /* M-{ */ F_UNASSIGNED, /* M-| */ F_UNASSIGNED, /* M-} */ F_UNASSIGNED, /* M-~ */ F_DELWORDPREV /* M-^? */ }; /* * keymap table for vi. Each index into above tbl; should be * 256 entries long. Vi mode uses a sticky-extend to do command mode: * insert mode characters are in the normal keymap, and command mode * in the extended keymap. */ static KEYCMD CcViMap[] = { #ifdef KSHVI F_UNASSIGNED, /* ^@ */ F_INSERT, /* ^A */ F_INSERT, /* ^B */ F_INSERT, /* ^C */ F_INSERT, /* ^D */ F_INSERT, /* ^E */ F_INSERT, /* ^F */ F_INSERT, /* ^G */ V_DELPREV, /* ^H */ /* BackSpace key */ F_COMPLETE, /* ^I */ /* Tab Key */ F_NEWLINE, /* ^J */ F_INSERT, /* ^K */ F_INSERT, /* ^L */ F_NEWLINE, /* ^M */ F_INSERT, /* ^N */ F_INSERT, /* ^O */ F_INSERT, /* ^P */ F_TTY_STARTO, /* ^Q */ F_INSERT, /* ^R */ F_INSERT, /* ^S */ F_INSERT, /* ^T */ F_INSERT, /* ^U */ F_QUOTE, /* ^V */ F_DELWORDPREV, /* ^W */ /* Only until start edit pos */ F_INSERT, /* ^X */ F_INSERT, /* ^Y */ F_INSERT, /* ^Z */ V_CMD_MODE, /* ^[ */ /* [ Esc ] key */ F_TTY_QUIT, /* ^\ */ F_INSERT, /* ^] */ F_INSERT, /* ^^ */ F_INSERT, /* ^_ */ #else /* !KSHVI */ F_UNASSIGNED, /* ^@ */ /* NOTE: These mapping do NOT */ F_TOBEG, /* ^A */ /* Correspond well to the KSH */ F_CHARBACK, /* ^B */ /* VI editting assignments */ F_TTY_INT, /* ^C */ /* On the other hand they are */ F_LIST_EOF, /* ^D */ /* convenient any many people */ F_TOEND, /* ^E */ /* have gotten used to them */ F_CHARFWD, /* ^F */ F_LIST_GLOB, /* ^G */ F_DELPREV, /* ^H */ /* BackSpace key */ F_COMPLETE, /* ^I */ /* Tab Key */ F_NEWLINE, /* ^J */ F_KILLEND, /* ^K */ F_CLEARDISP, /* ^L */ F_NEWLINE, /* ^M */ F_DOWN_HIST, /* ^N */ F_TTY_FLUSHO, /* ^O */ F_UP_HIST, /* ^P */ F_TTY_STARTO, /* ^Q */ F_REDISP, /* ^R */ F_TTY_STOPO, /* ^S */ F_CHARSWITCH, /* ^T */ F_KILLBEG, /* ^U */ F_QUOTE, /* ^V */ F_DELWORDPREV, /* ^W */ F_EXPAND, /* ^X */ F_TTY_DSUSP, /* ^Y */ F_TTY_TSUSP, /* ^Z */ V_CMD_MODE, /* ^[ */ F_TTY_QUIT, /* ^\ */ F_UNASSIGNED, /* ^] */ F_UNASSIGNED, /* ^^ */ F_UNASSIGNED, /* ^_ */ #endif /* KSHVI */ F_INSERT, /* SPACE */ F_INSERT, /* ! */ F_INSERT, /* " */ F_INSERT, /* # */ F_INSERT, /* $ */ F_INSERT, /* % */ F_INSERT, /* & */ F_INSERT, /* ' */ F_INSERT, /* ( */ F_INSERT, /* ) */ F_INSERT, /* * */ F_INSERT, /* + */ F_INSERT, /* , */ F_INSERT, /* - */ F_INSERT, /* . */ F_INSERT, /* / */ F_INSERT, /* 0 */ F_INSERT, /* 1 */ F_INSERT, /* 2 */ F_INSERT, /* 3 */ F_INSERT, /* 4 */ F_INSERT, /* 5 */ F_INSERT, /* 6 */ F_INSERT, /* 7 */ F_INSERT, /* 8 */ F_INSERT, /* 9 */ F_INSERT, /* : */ F_INSERT, /* ; */ F_INSERT, /* < */ F_INSERT, /* = */ F_INSERT, /* > */ F_INSERT, /* ? */ F_INSERT, /* @ */ F_INSERT, /* A */ F_INSERT, /* B */ F_INSERT, /* C */ F_INSERT, /* D */ F_INSERT, /* E */ F_INSERT, /* F */ F_INSERT, /* G */ F_INSERT, /* H */ F_INSERT, /* I */ F_INSERT, /* J */ F_INSERT, /* K */ F_INSERT, /* L */ F_INSERT, /* M */ F_INSERT, /* N */ F_INSERT, /* O */ F_INSERT, /* P */ F_INSERT, /* Q */ F_INSERT, /* R */ F_INSERT, /* S */ F_INSERT, /* T */ F_INSERT, /* U */ F_INSERT, /* V */ F_INSERT, /* W */ F_INSERT, /* X */ F_INSERT, /* Y */ F_INSERT, /* Z */ F_INSERT, /* [ */ F_INSERT, /* \ */ F_INSERT, /* ] */ F_INSERT, /* ^ */ F_INSERT, /* _ */ F_INSERT, /* ` */ F_INSERT, /* a */ F_INSERT, /* b */ F_INSERT, /* c */ F_INSERT, /* d */ F_INSERT, /* e */ F_INSERT, /* f */ F_INSERT, /* g */ F_INSERT, /* h */ F_INSERT, /* i */ F_INSERT, /* j */ F_INSERT, /* k */ F_INSERT, /* l */ F_INSERT, /* m */ F_INSERT, /* n */ F_INSERT, /* o */ F_INSERT, /* p */ F_INSERT, /* q */ F_INSERT, /* r */ F_INSERT, /* s */ F_INSERT, /* t */ F_INSERT, /* u */ F_INSERT, /* v */ F_INSERT, /* w */ F_INSERT, /* x */ F_INSERT, /* y */ F_INSERT, /* z */ F_INSERT, /* { */ F_INSERT, /* | */ F_INSERT, /* } */ F_INSERT, /* ~ */ F_DELPREV, /* ^? */ F_UNASSIGNED, /* M-^@ */ F_UNASSIGNED, /* M-^A */ F_UNASSIGNED, /* M-^B */ F_UNASSIGNED, /* M-^C */ F_UNASSIGNED, /* M-^D */ F_UNASSIGNED, /* M-^E */ F_UNASSIGNED, /* M-^F */ F_UNASSIGNED, /* M-^G */ F_UNASSIGNED, /* M-^H */ F_UNASSIGNED, /* M-^I */ F_UNASSIGNED, /* M-^J */ F_UNASSIGNED, /* M-^K */ F_UNASSIGNED, /* M-^L */ F_UNASSIGNED, /* M-^M */ F_UNASSIGNED, /* M-^N */ F_UNASSIGNED, /* M-^O */ F_UNASSIGNED, /* M-^P */ F_UNASSIGNED, /* M-^Q */ F_UNASSIGNED, /* M-^R */ F_UNASSIGNED, /* M-^S */ F_UNASSIGNED, /* M-^T */ F_UNASSIGNED, /* M-^U */ F_UNASSIGNED, /* M-^V */ F_UNASSIGNED, /* M-^W */ F_UNASSIGNED, /* M-^X */ F_UNASSIGNED, /* M-^Y */ F_UNASSIGNED, /* M-^Z */ F_UNASSIGNED, /* M-^[ */ F_UNASSIGNED, /* M-^\ */ F_UNASSIGNED, /* M-^] */ F_UNASSIGNED, /* M-^^ */ F_UNASSIGNED, /* M-^_ */ F_UNASSIGNED, /* M-SPACE */ F_UNASSIGNED, /* M-! */ F_UNASSIGNED, /* M-" */ F_UNASSIGNED, /* M-# */ F_UNASSIGNED, /* M-$ */ F_UNASSIGNED, /* M-% */ F_UNASSIGNED, /* M-& */ F_UNASSIGNED, /* M-' */ F_UNASSIGNED, /* M-( */ F_UNASSIGNED, /* M-) */ F_UNASSIGNED, /* M-* */ F_UNASSIGNED, /* M-+ */ F_UNASSIGNED, /* M-, */ F_UNASSIGNED, /* M-- */ F_UNASSIGNED, /* M-. */ F_UNASSIGNED, /* M-/ */ F_UNASSIGNED, /* M-0 */ F_UNASSIGNED, /* M-1 */ F_UNASSIGNED, /* M-2 */ F_UNASSIGNED, /* M-3 */ F_UNASSIGNED, /* M-4 */ F_UNASSIGNED, /* M-5 */ F_UNASSIGNED, /* M-6 */ F_UNASSIGNED, /* M-7 */ F_UNASSIGNED, /* M-8 */ F_UNASSIGNED, /* M-9 */ F_UNASSIGNED, /* M-: */ F_UNASSIGNED, /* M-; */ F_UNASSIGNED, /* M-< */ F_UNASSIGNED, /* M-= */ F_UNASSIGNED, /* M-> */ F_UNASSIGNED, /* M-? */ F_UNASSIGNED, /* M-@ */ F_UNASSIGNED, /* M-A */ F_UNASSIGNED, /* M-B */ F_UNASSIGNED, /* M-C */ F_UNASSIGNED, /* M-D */ F_UNASSIGNED, /* M-E */ F_UNASSIGNED, /* M-F */ F_UNASSIGNED, /* M-G */ F_UNASSIGNED, /* M-H */ F_UNASSIGNED, /* M-I */ F_UNASSIGNED, /* M-J */ F_UNASSIGNED, /* M-K */ F_UNASSIGNED, /* M-L */ F_UNASSIGNED, /* M-M */ F_UNASSIGNED, /* M-N */ F_UNASSIGNED, /* M-O */ F_UNASSIGNED, /* M-P */ F_UNASSIGNED, /* M-Q */ F_UNASSIGNED, /* M-R */ F_UNASSIGNED, /* M-S */ F_UNASSIGNED, /* M-T */ F_UNASSIGNED, /* M-U */ F_UNASSIGNED, /* M-V */ F_UNASSIGNED, /* M-W */ F_UNASSIGNED, /* M-X */ F_UNASSIGNED, /* M-Y */ F_UNASSIGNED, /* M-Z */ F_UNASSIGNED, /* M-[ */ F_UNASSIGNED, /* M-\ */ F_UNASSIGNED, /* M-] */ F_UNASSIGNED, /* M-^ */ F_UNASSIGNED, /* M-_ */ F_UNASSIGNED, /* M-` */ F_UNASSIGNED, /* M-a */ F_UNASSIGNED, /* M-b */ F_UNASSIGNED, /* M-c */ F_UNASSIGNED, /* M-d */ F_UNASSIGNED, /* M-e */ F_UNASSIGNED, /* M-f */ F_UNASSIGNED, /* M-g */ F_UNASSIGNED, /* M-h */ F_UNASSIGNED, /* M-i */ F_UNASSIGNED, /* M-j */ F_UNASSIGNED, /* M-k */ F_UNASSIGNED, /* M-l */ F_UNASSIGNED, /* M-m */ F_UNASSIGNED, /* M-n */ F_UNASSIGNED, /* M-o */ F_UNASSIGNED, /* M-p */ F_UNASSIGNED, /* M-q */ F_UNASSIGNED, /* M-r */ F_UNASSIGNED, /* M-s */ F_UNASSIGNED, /* M-t */ F_UNASSIGNED, /* M-u */ F_UNASSIGNED, /* M-v */ F_UNASSIGNED, /* M-w */ F_UNASSIGNED, /* M-x */ F_UNASSIGNED, /* M-y */ F_UNASSIGNED, /* M-z */ F_UNASSIGNED, /* M-{ */ F_UNASSIGNED, /* M-| */ F_UNASSIGNED, /* M-} */ F_UNASSIGNED, /* M-~ */ F_UNASSIGNED /* M-^? */ }; KEYCMD CcViCmdMap[] = { F_UNASSIGNED, /* ^@ */ F_TOBEG, /* ^A */ F_UNASSIGNED, /* ^B */ F_TTY_INT, /* ^C */ F_LIST_CHOICES, /* ^D */ F_TOEND, /* ^E */ F_UNASSIGNED, /* ^F */ F_LIST_GLOB, /* ^G */ F_CHARBACK, /* ^H */ V_CM_COMPLETE, /* ^I */ F_NEWLINE, /* ^J */ F_KILLEND, /* ^K */ F_CLEARDISP, /* ^L */ F_NEWLINE, /* ^M */ F_DOWN_HIST, /* ^N */ F_TTY_FLUSHO, /* ^O */ F_UP_HIST, /* ^P */ F_TTY_STARTO, /* ^Q */ F_REDISP, /* ^R */ F_TTY_STOPO, /* ^S */ F_UNASSIGNED, /* ^T */ F_KILLBEG, /* ^U */ F_UNASSIGNED, /* ^V */ F_DELWORDPREV, /* ^W */ F_EXPAND, /* ^X */ F_UNASSIGNED, /* ^Y */ F_UNASSIGNED, /* ^Z */ F_METANEXT, /* ^[ */ F_TTY_QUIT, /* ^\ */ F_UNASSIGNED, /* ^] */ F_UNASSIGNED, /* ^^ */ F_UNASSIGNED, /* ^_ */ F_CHARFWD, /* SPACE */ F_EXPAND_HISTORY, /* ! */ F_UNASSIGNED, /* " */ F_UNASSIGNED, /* # */ F_TOEND, /* $ */ F_UNASSIGNED, /* % */ F_UNASSIGNED, /* & */ F_UNASSIGNED, /* ' */ F_UNASSIGNED, /* ( */ F_UNASSIGNED, /* ) */ F_EXPAND_GLOB, /* * */ F_DOWN_HIST, /* + */ - V_RCHAR_BACK, /* , */ - F_UP_HIST, /* - */ + V_RCHAR_BACK, /* , */ + F_UP_HIST, /* - */ F_UNASSIGNED, /* . */ V_DSH_META, /* / */ V_ZERO, /* 0 */ F_ARGDIGIT, /* 1 */ F_ARGDIGIT, /* 2 */ F_ARGDIGIT, /* 3 */ F_ARGDIGIT, /* 4 */ F_ARGDIGIT, /* 5 */ F_ARGDIGIT, /* 6 */ F_ARGDIGIT, /* 7 */ F_ARGDIGIT, /* 8 */ F_ARGDIGIT, /* 9 */ F_UNASSIGNED, /* : */ V_RCHAR_FWD, /* ; */ F_UNASSIGNED, /* < */ F_UNASSIGNED, /* = */ F_UNASSIGNED, /* > */ V_USH_META, /* ? */ F_UNASSIGNED, /* @ */ V_ADDEND, /* A */ V_WORDBACK, /* B */ V_CHGTOEND, /* C */ F_KILLEND, /* D */ V_ENDWORD, /* E */ V_CHAR_BACK, /* F */ F_UNASSIGNED, /* G */ F_UNASSIGNED, /* H */ V_INSBEG, /* I */ F_DOWN_SEARCH_HIST, /* J */ F_UP_SEARCH_HIST, /* K */ F_UNASSIGNED, /* L */ F_UNASSIGNED, /* M */ V_RSRCH_BACK, /* N */ F_XKEY, /* O */ F_UNASSIGNED, /* P */ F_UNASSIGNED, /* Q */ V_REPLMODE, /* R */ V_SUBSTLINE, /* S */ V_CHARTO_BACK, /* T */ F_UNASSIGNED, /* U */ F_EXPAND_VARS, /* V */ V_WORDFWD, /* W */ F_DELPREV, /* X */ F_UNASSIGNED, /* Y */ F_UNASSIGNED, /* Z */ F_XKEY, /* [ */ F_UNASSIGNED, /* \ */ F_UNASSIGNED, /* ] */ F_TOBEG, /* ^ */ F_UNASSIGNED, /* _ */ F_UNASSIGNED, /* ` */ V_ADD, /* a */ F_WORDBACK, /* b */ V_CHGMETA, /* c */ V_DELMETA, /* d */ V_EWORD, /* e */ V_CHAR_FWD, /* f */ F_UNASSIGNED, /* g */ F_CHARBACK, /* h */ V_INSERT, /* i */ F_DOWN_HIST, /* j */ F_UP_HIST, /* k */ F_CHARFWD, /* l */ F_UNASSIGNED, /* m */ V_RSRCH_FWD, /* n */ F_UNASSIGNED, /* o */ F_UNASSIGNED, /* p */ F_UNASSIGNED, /* q */ V_REPLONE, /* r */ V_SUBSTCHAR, /* s */ V_CHARTO_FWD, /* t */ V_UNDO, /* u */ F_EXPAND_VARS, /* v */ V_WORDBEGNEXT, /* w */ F_DELNEXT_EOF, /* x */ F_UNASSIGNED, /* y */ F_UNASSIGNED, /* z */ F_UNASSIGNED, /* { */ F_UNASSIGNED, /* | */ F_UNASSIGNED, /* } */ V_CHGCASE, /* ~ */ F_DELPREV, /* ^? */ F_UNASSIGNED, /* M-^@ */ F_UNASSIGNED, /* M-^A */ F_UNASSIGNED, /* M-^B */ F_UNASSIGNED, /* M-^C */ F_UNASSIGNED, /* M-^D */ F_UNASSIGNED, /* M-^E */ F_UNASSIGNED, /* M-^F */ F_UNASSIGNED, /* M-^G */ F_UNASSIGNED, /* M-^H */ F_UNASSIGNED, /* M-^I */ F_UNASSIGNED, /* M-^J */ F_UNASSIGNED, /* M-^K */ F_UNASSIGNED, /* M-^L */ F_UNASSIGNED, /* M-^M */ F_UNASSIGNED, /* M-^N */ F_UNASSIGNED, /* M-^O */ F_UNASSIGNED, /* M-^P */ F_UNASSIGNED, /* M-^Q */ F_UNASSIGNED, /* M-^R */ F_UNASSIGNED, /* M-^S */ F_UNASSIGNED, /* M-^T */ F_UNASSIGNED, /* M-^U */ F_UNASSIGNED, /* M-^V */ F_UNASSIGNED, /* M-^W */ F_UNASSIGNED, /* M-^X */ F_UNASSIGNED, /* M-^Y */ F_UNASSIGNED, /* M-^Z */ F_UNASSIGNED, /* M-^[ */ F_UNASSIGNED, /* M-^\ */ F_UNASSIGNED, /* M-^] */ F_UNASSIGNED, /* M-^^ */ F_UNASSIGNED, /* M-^_ */ F_UNASSIGNED, /* M-SPACE */ F_UNASSIGNED, /* M-! */ F_UNASSIGNED, /* M-" */ F_UNASSIGNED, /* M-# */ F_UNASSIGNED, /* M-$ */ F_UNASSIGNED, /* M-% */ F_UNASSIGNED, /* M-& */ F_UNASSIGNED, /* M-' */ F_UNASSIGNED, /* M-( */ F_UNASSIGNED, /* M-) */ F_UNASSIGNED, /* M-* */ F_UNASSIGNED, /* M-+ */ F_UNASSIGNED, /* M-, */ F_UNASSIGNED, /* M-- */ F_UNASSIGNED, /* M-. */ F_UNASSIGNED, /* M-/ */ F_UNASSIGNED, /* M-0 */ F_UNASSIGNED, /* M-1 */ F_UNASSIGNED, /* M-2 */ F_UNASSIGNED, /* M-3 */ F_UNASSIGNED, /* M-4 */ F_UNASSIGNED, /* M-5 */ F_UNASSIGNED, /* M-6 */ F_UNASSIGNED, /* M-7 */ F_UNASSIGNED, /* M-8 */ F_UNASSIGNED, /* M-9 */ F_UNASSIGNED, /* M-: */ F_UNASSIGNED, /* M-; */ F_UNASSIGNED, /* M-< */ F_UNASSIGNED, /* M-= */ F_UNASSIGNED, /* M-> */ F_HELPME, /* M-? */ F_UNASSIGNED, /* M-@ */ F_UNASSIGNED, /* M-A */ F_UNASSIGNED, /* M-B */ F_UNASSIGNED, /* M-C */ F_UNASSIGNED, /* M-D */ F_UNASSIGNED, /* M-E */ F_UNASSIGNED, /* M-F */ F_UNASSIGNED, /* M-G */ F_UNASSIGNED, /* M-H */ F_UNASSIGNED, /* M-I */ F_UNASSIGNED, /* M-J */ F_UNASSIGNED, /* M-K */ F_UNASSIGNED, /* M-L */ F_UNASSIGNED, /* M-M */ F_UNASSIGNED, /* M-N */ F_XKEY, /* M-O *//* extended key esc PWP Mar 88 */ F_UNASSIGNED, /* M-P */ F_UNASSIGNED, /* M-Q */ F_UNASSIGNED, /* M-R */ F_UNASSIGNED, /* M-S */ F_UNASSIGNED, /* M-T */ F_UNASSIGNED, /* M-U */ F_UNASSIGNED, /* M-V */ F_UNASSIGNED, /* M-W */ F_UNASSIGNED, /* M-X */ F_UNASSIGNED, /* M-Y */ F_UNASSIGNED, /* M-Z */ F_XKEY, /* M-[ *//* extended key esc -mf Oct 87 */ F_UNASSIGNED, /* M-\ */ F_UNASSIGNED, /* M-] */ F_UNASSIGNED, /* M-^ */ F_UNASSIGNED, /* M-_ */ F_UNASSIGNED, /* M-` */ F_UNASSIGNED, /* M-a */ F_UNASSIGNED, /* M-b */ F_UNASSIGNED, /* M-c */ F_UNASSIGNED, /* M-d */ F_UNASSIGNED, /* M-e */ F_UNASSIGNED, /* M-f */ F_UNASSIGNED, /* M-g */ F_UNASSIGNED, /* M-h */ F_UNASSIGNED, /* M-i */ F_UNASSIGNED, /* M-j */ F_UNASSIGNED, /* M-k */ F_UNASSIGNED, /* M-l */ F_UNASSIGNED, /* M-m */ F_UNASSIGNED, /* M-n */ F_UNASSIGNED, /* M-o */ F_UNASSIGNED, /* M-p */ F_UNASSIGNED, /* M-q */ F_UNASSIGNED, /* M-r */ F_UNASSIGNED, /* M-s */ F_UNASSIGNED, /* M-t */ F_UNASSIGNED, /* M-u */ F_UNASSIGNED, /* M-v */ F_UNASSIGNED, /* M-w */ F_UNASSIGNED, /* M-x */ F_UNASSIGNED, /* M-y */ F_UNASSIGNED, /* M-z */ F_UNASSIGNED, /* M-{ */ F_UNASSIGNED, /* M-| */ F_UNASSIGNED, /* M-} */ F_UNASSIGNED, /* M-~ */ F_UNASSIGNED /* M-^? */ }; #endif /* WINNT_NATIVE */ void editinit(void) { struct KeyFuncs *f; #if defined(NLS_CATALOGS) || defined(WINNT_NATIVE) int i; for (i = 0; i < F_NUM_FUNCNAMES; i++) xfree((ptr_t)(intptr_t)FuncNames[i].desc); #endif f = FuncNames; f->name = "backward-char"; f->func = F_CHARBACK; f->desc = CSAVS(3, 1, "Move back a character"); f++; f->name = "backward-delete-char"; f->func = F_DELPREV; f->desc = CSAVS(3, 2, "Delete the character behind cursor"); f++; f->name = "backward-delete-word"; f->func = F_DELWORDPREV; f->desc = CSAVS(3, 3, "Cut from beginning of current word to cursor - saved in cut buffer"); f++; f->name = "backward-kill-line"; f->func = F_KILLBEG; f->desc = CSAVS(3, 4, "Cut from beginning of line to cursor - save in cut buffer"); f++; f->name = "backward-word"; f->func = F_WORDBACK; f->desc = CSAVS(3, 5, "Move to beginning of current word"); f++; f->name = "beginning-of-line"; f->func = F_TOBEG; f->desc = CSAVS(3, 6, "Move to beginning of line"); f++; f->name = "capitalize-word"; f->func = F_CASECAPITAL; f->desc = CSAVS(3, 7, "Capitalize the characters from cursor to end of current word"); f++; f->name = "change-case"; f->func = V_CHGCASE; f->desc = CSAVS(3, 8, "Vi change case of character under cursor and advance one character"); f++; f->name = "change-till-end-of-line"; f->func = V_CHGTOEND; /* backward compat. */ f->desc = CSAVS(3, 9, "Vi change to end of line"); f++; f->name = "clear-screen"; f->func = F_CLEARDISP; f->desc = CSAVS(3, 10, "Clear screen leaving current line on top"); f++; f->name = "complete-word"; f->func = F_COMPLETE; f->desc = CSAVS(3, 11, "Complete current word"); f++; f->name = "complete-word-fwd"; f->func = F_COMPLETE_FWD; f->desc = CSAVS(3, 12, "Tab forward through files"); f++; f->name = "complete-word-back"; f->func = F_COMPLETE_BACK; f->desc = CSAVS(3, 13, "Tab backward through files"); f++; f->name = "complete-word-raw"; f->func = F_COMPLETE_ALL; f->desc = CSAVS(3, 14, "Complete current word ignoring programmable completions"); f++; f->name = "copy-prev-word"; f->func = F_COPYPREV; f->desc = CSAVS(3, 15, "Copy current word to cursor"); f++; f->name = "copy-region-as-kill"; f->func = F_COPYREGION; f->desc = CSAVS(3, 16, "Copy area between mark and cursor to cut buffer"); f++; f->name = "dabbrev-expand"; f->func = F_DABBREV_EXPAND; f->desc = CSAVS(3, 17, "Expand to preceding word for which this is a prefix"); f++; f->name = "delete-char"; f->func = F_DELNEXT; f->desc = CSAVS(3, 18, "Delete character under cursor"); f++; f->name = "delete-char-or-eof"; f->func = F_DELNEXT_EOF; f->desc = CSAVS(3, 19, "Delete character under cursor or signal end of file on an empty line"); f++; f->name = "delete-char-or-list"; f->func = F_DELNEXT_LIST; f->desc = CSAVS(3, 20, "Delete character under cursor or list completions if at end of line"); f++; f->name = "delete-char-or-list-or-eof"; f->func = F_DELNEXT_LIST_EOF; f->desc = CSAVS(3, 21, "Delete character under cursor, list completions or signal end of file"); f++; f->name = "delete-word"; f->func = F_DELWORDNEXT; f->desc = CSAVS(3, 22, "Cut from cursor to end of current word - save in cut buffer"); f++; f->name = "digit"; f->func = F_DIGIT; f->desc = CSAVS(3, 23, "Adds to argument if started or enters digit"); f++; f->name = "digit-argument"; f->func = F_ARGDIGIT; f->desc = CSAVS(3, 24, "Digit that starts argument"); f++; f->name = "down-history"; f->func = F_DOWN_HIST; f->desc = CSAVS(3, 25, "Move to next history line"); f++; f->name = "downcase-word"; f->func = F_CASELOWER; f->desc = CSAVS(3, 26, "Lowercase the characters from cursor to end of current word"); f++; f->name = "end-of-file"; f->func = F_SEND_EOF; f->desc = CSAVS(3, 27, "Indicate end of file"); f++; f->name = "end-of-line"; f->func = F_TOEND; f->desc = CSAVS(3, 28, "Move cursor to end of line"); f++; f->name = "exchange-point-and-mark"; f->func = F_EXCHANGE_MARK; f->desc = CSAVS(3, 29, "Exchange the cursor and mark"); f++; f->name = "expand-glob"; f->func = F_EXPAND_GLOB; f->desc = CSAVS(3, 30, "Expand file name wildcards"); f++; f->name = "expand-history"; f->func = F_EXPAND_HISTORY; f->desc = CSAVS(3, 31, "Expand history escapes"); f++; f->name = "expand-line"; f->func = F_EXPAND; f->desc = CSAVS(3, 32, "Expand the history escapes in a line"); f++; f->name = "expand-variables"; f->func = F_EXPAND_VARS; f->desc = CSAVS(3, 33, "Expand variables"); f++; f->name = "forward-char"; f->func = F_CHARFWD; f->desc = CSAVS(3, 34, "Move forward one character"); f++; f->name = "forward-word"; f->func = F_WORDFWD; f->desc = CSAVS(3, 35, "Move forward to end of current word"); f++; f->name = "gosmacs-transpose-chars"; f->func = F_GCHARSWITCH; f->desc = CSAVS(3, 36, "Exchange the two characters before the cursor"); f++; f->name = "history-search-backward"; f->func = F_UP_SEARCH_HIST; f->desc = CSAVS(3, 37, "Search in history backward for line beginning as current"); f++; f->name = "history-search-forward"; f->func = F_DOWN_SEARCH_HIST; f->desc = CSAVS(3, 38, "Search in history forward for line beginning as current"); f++; f->name = "insert-last-word"; f->func = F_LAST_ITEM; f->desc = CSAVS(3, 39, "Insert last item of previous command"); f++; f->name = "i-search-fwd"; f->func = F_INC_FWD; f->desc = CSAVS(3, 40, "Incremental search forward"); f++; f->name = "i-search-back"; f->func = F_INC_BACK; f->desc = CSAVS(3, 41, "Incremental search backward"); f++; f->name = "keyboard-quit"; f->func = F_STARTOVER; f->desc = CSAVS(3, 42, "Clear line"); f++; f->name = "kill-line"; f->func = F_KILLEND; f->desc = CSAVS(3, 43, "Cut to end of line and save in cut buffer"); f++; f->name = "kill-region"; f->func = F_KILLREGION; f->desc = CSAVS(3, 44, "Cut area between mark and cursor and save in cut buffer"); f++; f->name = "kill-whole-line"; f->func = F_KILLALL; f->desc = CSAVS(3, 45, "Cut the entire line and save in cut buffer"); f++; f->name = "list-choices"; f->func = F_LIST_CHOICES; f->desc = CSAVS(3, 46, "List choices for completion"); f++; f->name = "list-choices-raw"; f->func = F_LIST_ALL; f->desc = CSAVS(3, 47, "List choices for completion overriding programmable completion"); f++; f->name = "list-glob"; f->func = F_LIST_GLOB; f->desc = CSAVS(3, 48, "List file name wildcard matches"); f++; f->name = "list-or-eof"; f->func = F_LIST_EOF; f->desc = CSAVS(3, 49, "List choices for completion or indicate end of file if empty line"); f++; f->name = "load-average"; f->func = F_LOAD_AVERAGE; f->desc = CSAVS(3, 50, "Display load average and current process status"); f++; f->name = "magic-space"; f->func = F_MAGIC_SPACE; f->desc = CSAVS(3, 51, "Expand history escapes and insert a space"); f++; f->name = "newline"; f->func = F_NEWLINE; f->desc = CSAVS(3, 52, "Execute command"); f++; f->name = "newline-and-hold"; f->func = F_NEWLINE_HOLD; f->desc = CSAVS(3, 122, "Execute command and keep current line"); f++; f->name = "newline-and-down-history"; f->func = F_NEWLINE_DOWN_HIST; f->desc = CSAVS(3, 123, "Execute command and move to next history line"); f++; f->name = "normalize-path"; f->func = F_PATH_NORM; - f->desc = CSAVS(3, 53, + f->desc = CSAVS(3, 53, "Expand pathnames, eliminating leading .'s and ..'s"); f++; f->name = "normalize-command"; f->func = F_COMMAND_NORM; - f->desc = CSAVS(3, 54, + f->desc = CSAVS(3, 54, "Expand commands to the resulting pathname or alias"); f++; f->name = "overwrite-mode"; f->func = F_INSOVR; f->desc = CSAVS(3, 55, "Switch from insert to overwrite mode or vice versa"); f++; f->name = "prefix-meta"; f->func = F_METANEXT; f->desc = CSAVS(3, 56, "Add 8th bit to next character typed"); f++; f->name = "quoted-insert"; f->func = F_QUOTE; f->desc = CSAVS(3, 57, "Add the next character typed to the line verbatim"); f++; f->name = "redisplay"; f->func = F_REDISP; f->desc = CSAVS(3, 58, "Redisplay everything"); f++; f->name = "run-fg-editor"; f->func = F_RUN_FG_EDITOR; f->desc = CSAVS(3, 59, "Restart stopped editor"); f++; f->name = "run-help"; f->func = F_HELPME; f->desc = CSAVS(3, 60, "Look for help on current command"); f++; f->name = "self-insert-command"; f->func = F_INSERT; f->desc = CSAVS(3, 61, "This character is added to the line"); f++; f->name = "sequence-lead-in"; f->func = F_XKEY; f->desc = CSAVS(3, 62, "This character is the first in a character sequence"); f++; f->name = "set-mark-command"; f->func = F_SET_MARK; f->desc = CSAVS(3, 63, "Set the mark at cursor"); f++; f->name = "spell-word"; f->func = F_CORRECT; f->desc = CSAVS(3, 64, "Correct the spelling of current word"); f++; f->name = "spell-line"; f->func = F_CORRECT_L; f->desc = CSAVS(3, 65, "Correct the spelling of entire line"); f++; f->name = "stuff-char"; f->func = F_STUFF_CHAR; f->desc = CSAVS(3, 66, "Send character to tty in cooked mode"); f++; f->name = "toggle-literal-history"; f->func = F_TOGGLE_HIST; f->desc = CSAVS(3, 67, "Toggle between literal and lexical current history line"); f++; f->name = "transpose-chars"; f->func = F_CHARSWITCH; f->desc = CSAVS(3, 68, "Exchange the character to the left of the cursor with the one under"); f++; f->name = "transpose-gosling"; f->func = F_GCHARSWITCH; f->desc = CSAVS(3, 69, "Exchange the two characters before the cursor"); f++; f->name = "tty-dsusp"; f->func = F_TTY_DSUSP; f->desc = CSAVS(3, 70, "Tty delayed suspend character"); f++; f->name = "tty-flush-output"; f->func = F_TTY_FLUSHO; f->desc = CSAVS(3, 71, "Tty flush output character"); f++; f->name = "tty-sigintr"; f->func = F_TTY_INT; f->desc = CSAVS(3, 72, "Tty interrupt character"); f++; f->name = "tty-sigquit"; f->func = F_TTY_QUIT; f->desc = CSAVS(3, 73, "Tty quit character"); f++; f->name = "tty-sigtsusp"; f->func = F_TTY_TSUSP; f->desc = CSAVS(3, 74, "Tty suspend character"); f++; f->name = "tty-start-output"; f->func = F_TTY_STARTO; f->desc = CSAVS(3, 75, "Tty allow output character"); f++; f->name = "tty-stop-output"; f->func = F_TTY_STOPO; f->desc = CSAVS(3, 76, "Tty disallow output character"); f++; f->name = "undefined-key"; f->func = F_UNASSIGNED; f->desc = CSAVS(3, 77, "Indicates unbound character"); f++; f->name = "universal-argument"; f->func = F_ARGFOUR; f->desc = CSAVS(3, 78, "Emacs universal argument (argument times 4)"); f++; f->name = "up-history"; f->func = F_UP_HIST; f->desc = CSAVS(3, 79, "Move to previous history line"); f++; f->name = "upcase-word"; f->func = F_CASEUPPER; f->desc = CSAVS(3, 80, "Uppercase the characters from cursor to end of current word"); f++; f->name = "vi-beginning-of-next-word"; f->func = V_WORDBEGNEXT; f->desc = CSAVS(3, 81, "Vi goto the beginning of next word"); f++; f->name = "vi-add"; f->func = V_ADD; f->desc = CSAVS(3, 82, "Vi enter insert mode after the cursor"); f++; f->name = "vi-add-at-eol"; f->func = V_ADDEND; f->desc = CSAVS(3, 83, "Vi enter insert mode at end of line"); f++; f->name = "vi-chg-case"; f->func = V_CHGCASE; f->desc = CSAVS(3, 84, "Vi change case of character under cursor and advance one character"); f++; f->name = "vi-chg-meta"; f->func = V_CHGMETA; f->desc = CSAVS(3, 85, "Vi change prefix command"); f++; f->name = "vi-chg-to-eol"; f->func = V_CHGTOEND; f->desc = CSAVS(3, 86, "Vi change to end of line"); f++; f->name = "vi-cmd-mode"; f->func = V_CMD_MODE; f->desc = CSAVS(3, 87, "Enter vi command mode (use alternative key bindings)"); f++; f->name = "vi-cmd-mode-complete"; f->func = V_CM_COMPLETE; f->desc = CSAVS(3, 88, "Vi command mode complete current word"); f++; f->name = "vi-delprev"; f->func = V_DELPREV; f->desc = CSAVS(3, 89, "Vi move to previous character (backspace)"); f++; f->name = "vi-delmeta"; f->func = V_DELMETA; f->desc = CSAVS(3, 90, "Vi delete prefix command"); f++; f->name = "vi-endword"; f->func = V_ENDWORD; f->desc = CSAVS(3, 91, "Vi move to the end of the current space delimited word"); f++; f->name = "vi-eword"; f->func = V_EWORD; f->desc = CSAVS(3, 92, "Vi move to the end of the current word"); f++; f->name = "vi-char-back"; f->func = V_CHAR_BACK; f->desc = CSAVS(3, 93, "Vi move to the character specified backward"); f++; f->name = "vi-char-fwd"; f->func = V_CHAR_FWD; f->desc = CSAVS(3, 94, "Vi move to the character specified forward"); f++; f->name = "vi-charto-back"; f->func = V_CHARTO_BACK; f->desc = CSAVS(3, 95, "Vi move up to the character specified backward"); f++; f->name = "vi-charto-fwd"; f->func = V_CHARTO_FWD; f->desc = CSAVS(3, 96, "Vi move up to the character specified forward"); f++; f->name = "vi-insert"; f->func = V_INSERT; f->desc = CSAVS(3, 97, "Enter vi insert mode"); f++; f->name = "vi-insert-at-bol"; f->func = V_INSBEG; f->desc = CSAVS(3, 98, "Enter vi insert mode at beginning of line"); f++; f->name = "vi-repeat-char-fwd"; f->func = V_RCHAR_FWD; f->desc = CSAVS(3, 99, "Vi repeat current character search in the same search direction"); f++; f->name = "vi-repeat-char-back"; f->func = V_RCHAR_BACK; f->desc = CSAVS(3, 100, "Vi repeat current character search in the opposite search direction"); f++; f->name = "vi-repeat-search-fwd"; f->func = V_RSRCH_FWD; f->desc = CSAVS(3, 101, "Vi repeat current search in the same search direction"); f++; f->name = "vi-repeat-search-back"; f->func = V_RSRCH_BACK; f->desc = CSAVS(3, 102, "Vi repeat current search in the opposite search direction"); f++; f->name = "vi-replace-char"; f->func = V_REPLONE; f->desc = CSAVS(3, 103, "Vi replace character under the cursor with the next character typed"); f++; f->name = "vi-replace-mode"; f->func = V_REPLMODE; f->desc = CSAVS(3, 104, "Vi replace mode"); f++; f->name = "vi-search-back"; f->func = V_USH_META; f->desc = CSAVS(3, 105, "Vi search history backward"); f++; f->name = "vi-search-fwd"; f->func = V_DSH_META; f->desc = CSAVS(3, 106, "Vi search history forward"); f++; f->name = "vi-substitute-char"; f->func = V_SUBSTCHAR; f->desc = CSAVS(3, 107, "Vi replace character under the cursor and enter insert mode"); f++; f->name = "vi-substitute-line"; f->func = V_SUBSTLINE; f->desc = CSAVS(3, 108, "Vi replace entire line"); f++; f->name = "vi-word-back"; f->func = V_WORDBACK; f->desc = CSAVS(3, 109, "Vi move to the previous word"); f++; f->name = "vi-word-fwd"; f->func = V_WORDFWD; f->desc = CSAVS(3, 110, "Vi move to the next word"); f++; f->name = "vi-undo"; f->func = V_UNDO; f->desc = CSAVS(3, 111, "Vi undo last change"); f++; f->name = "vi-zero"; f->func = V_ZERO; f->desc = CSAVS(3, 112, "Vi goto the beginning of line"); f++; f->name = "which-command"; f->func = F_WHICH; f->desc = CSAVS(3, 113, "Perform which of current command"); f++; f->name = "yank"; f->func = F_YANK_KILL; f->desc = CSAVS(3, 114, "Paste cut buffer at cursor position"); f++; f->name = "yank-pop"; f->func = F_YANK_POP; f->desc = CSAVS(3, 115, "Replace just-yanked text with yank from earlier kill"); f++; f->name = "e_dosify_next"; f->func = F_DOSIFY_NEXT; f->desc = CSAVS(3, 118, "(WIN32 only) Convert each '/' in next word to '\\\\'"); f++; f->name = "e_dosify_prev"; f->func = F_DOSIFY_PREV; f->desc = CSAVS(3, 119, "(WIN32 only) Convert each '/' in previous word to '\\\\'"); f++; f->name = "e_page_up"; f->func = F_PAGE_UP; f->desc = CSAVS(3, 120, "(WIN32 only) Page visible console window up"); f++; f->name = "e_page_down"; f->func = F_PAGE_DOWN; f->desc = CSAVS(3, 121, "(WIN32 only) Page visible console window down"); f++; f->name = NULL; f->func = 0; f->desc = NULL; f++; if (f - FuncNames != F_NUM_FUNCNAMES) abort(); } #ifdef DEBUG_EDIT void CheckMaps(void) { /* check the size of the key maps */ size_t c1 = NT_NUM_KEYS * sizeof(KEYCMD); if (sizeof(CcKeyMap) != c1) xprintf("CcKeyMap should be %u entries, but is %zu.\r\n", NT_NUM_KEYS, sizeof(CcKeyMap) / sizeof(KEYCMD)); if (sizeof(CcAltMap) != c1) xprintf("CcAltMap should be %u entries, but is %zu.\r\n", NT_NUM_KEYS, sizeof(CcAltMap) / sizeof(KEYCMD)); if (sizeof(CcEmacsMap) != c1) xprintf("CcEmacsMap should be %u entries, but is %zu.\r\n", NT_NUM_KEYS, sizeof(CcEmacsMap) / sizeof(KEYCMD)); if (sizeof(CcViMap) != c1) xprintf("CcViMap should be %u entries, but is %zu.\r\n", NT_NUM_KEYS, sizeof(CcViMap) / sizeof(KEYCMD)); if (sizeof(CcViCmdMap) != c1) xprintf("CcViCmdMap should be %u entries, but is %zu.\r\n", NT_NUM_KEYS, sizeof(CcViCmdMap) / sizeof(KEYCMD)); } #endif int MapsAreInited = 0; int NLSMapsAreInited = 0; int NoNLSRebind; void ed_InitNLSMaps(void) { int i; if (AsciiOnly) return; if (NoNLSRebind) return; for (i = 0200; i <= 0377; i++) { if (Isprint(CTL_ESC(i))) { CcKeyMap[CTL_ESC(i)] = F_INSERT; } } NLSMapsAreInited = 1; } static void ed_InitMetaBindings(void) { Char buf[3]; int i; CStr cstr; KEYCMD *map; map = CcKeyMap; for (i = 0; i <= 0377 && CcKeyMap[CTL_ESC(i)] != F_METANEXT; i++) continue; if (i > 0377) { for (i = 0; i <= 0377 && CcAltMap[CTL_ESC(i)] != F_METANEXT; i++) continue; if (i > 0377) { i = '\033'; if (VImode) map = CcAltMap; } else { map = CcAltMap; } } buf[0] = (Char)CTL_ESC(i); buf[2] = 0; cstr.buf = buf; cstr.len = 2; for (i = 0200; i <= 0377; i++) { if (map[CTL_ESC(i)] != F_INSERT && map[CTL_ESC(i)] != F_UNASSIGNED && map[CTL_ESC(i)] != F_XKEY) { buf[1] = CTL_ESC(i & ASCII); AddXkey(&cstr, XmapCmd((int) map[CTL_ESC(i)]), XK_CMD); } } map[buf[0]] = F_XKEY; } void ed_InitVIMaps(void) { int i; VImode = 1; setNS(STRvimode); update_wordchars(); ResetXmap(); for (i = 0; i < NT_NUM_KEYS; i++) { CcKeyMap[i] = CcViMap[i]; CcAltMap[i] = CcViCmdMap[i]; } ed_InitMetaBindings(); ed_InitNLSMaps(); ResetArrowKeys(); BindArrowKeys(); } void ed_InitEmacsMaps(void) { int i; Char buf[3]; CStr cstr; cstr.buf = buf; cstr.len = 2; VImode = 0; if (adrof(STRvimode)) unsetv(STRvimode); update_wordchars(); ResetXmap(); for (i = 0; i < NT_NUM_KEYS; i++) { CcKeyMap[i] = CcEmacsMap[i]; CcAltMap[i] = F_UNASSIGNED; } ed_InitMetaBindings(); ed_InitNLSMaps(); buf[0] = CTL_ESC('\030'); buf[2] = 0; buf[1] = CTL_ESC('\030'); AddXkey(&cstr, XmapCmd(F_EXCHANGE_MARK), XK_CMD); buf[1] = '*'; AddXkey(&cstr, XmapCmd(F_EXPAND_GLOB), XK_CMD); buf[1] = '$'; AddXkey(&cstr, XmapCmd(F_EXPAND_VARS), XK_CMD); buf[1] = 'G'; AddXkey(&cstr, XmapCmd(F_LIST_GLOB), XK_CMD); buf[1] = 'g'; AddXkey(&cstr, XmapCmd(F_LIST_GLOB), XK_CMD); buf[1] = 'n'; AddXkey(&cstr, XmapCmd(F_PATH_NORM), XK_CMD); buf[1] = 'N'; AddXkey(&cstr, XmapCmd(F_PATH_NORM), XK_CMD); buf[1] = '?'; AddXkey(&cstr, XmapCmd(F_COMMAND_NORM), XK_CMD); buf[1] = '\t'; AddXkey(&cstr, XmapCmd(F_COMPLETE_ALL), XK_CMD); buf[1] = CTL_ESC('\004'); /* ^D */ AddXkey(&cstr, XmapCmd(F_LIST_ALL), XK_CMD); ResetArrowKeys(); BindArrowKeys(); } void ed_InitMaps(void) { if (MapsAreInited) return; #ifndef IS_ASCII /* This machine has an EBCDIC charset. The assumptions made for the * initialized keymaps therefore don't hold, since they are based on * ASCII (or ISO8859-1). * Here, we do a one-time transformation to EBCDIC environment * for the key initializations. */ { KEYCMD temp[NT_NUM_KEYS]; static KEYCMD *const list[3] = { CcEmacsMap, CcViMap, CcViCmdMap }; int i, table; for (table=0; table<3; ++table) { /* copy ASCII ordered map to temp table */ for (i = 0; i < NT_NUM_KEYS; i++) { temp[i] = list[table][i]; } /* write back as EBCDIC ordered map */ for (i = 0; i < NT_NUM_KEYS; i++) { list[table][_toebcdic[i]] = temp[i]; } } } #endif /* !IS_ASCII */ #ifdef VIDEFAULT ed_InitVIMaps(); #else ed_InitEmacsMaps(); #endif MapsAreInited = 1; } diff --git a/contrib/tcsh/ed.h b/contrib/tcsh/ed.h index 60d061a80bda..50990dee92b6 100644 --- a/contrib/tcsh/ed.h +++ b/contrib/tcsh/ed.h @@ -1,254 +1,258 @@ /* * ed.h: Editor declarations and globals */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _h_ed #define _h_ed #ifndef EXTERN # define EXTERN extern #endif #define MAXMACROLEVELS 10 /* max number of nested kbd macros */ #ifndef WINNT_NATIVE # define NT_NUM_KEYS 256 #endif /* WINNT_NATIVE */ #ifdef __QNXNTO__ #undef min #undef max #endif /****************************************************************************/ /* stuff for the different states returned by the character editor routines */ /****************************************************************************/ #define CCRETVAL char /* size needed for the different char editor */ /* return values */ #define KEYCMD unsigned char /* size needed to index into CcFuncTbl */ /* Must be unsigned */ typedef CCRETVAL(*PFCmd) (Char); /* pointer to function returning CCRETVAL */ struct KeyFuncs { /* for the "bind" shell command */ const char *name; /* function name for bind command */ int func; /* function numeric value */ const char *desc; /* description of function */ }; extern PFCmd CcFuncTbl[]; /* table of available commands */ extern KEYCMD CcKeyMap[]; /* keymap table, each index into above tbl */ extern KEYCMD CcAltMap[]; /* Alt keymap table */ extern KEYCMD CcEmacsMap[]; /* keymap table for Emacs default bindings */ extern KEYCMD CcViCmdMap[]; /* for Vi command mode defaults */ extern struct KeyFuncs FuncNames[]; /* string names vs. CcFuncTbl indices */ extern KEYCMD NumFuns; /* number of KEYCMDs in above table */ #define CC_ERROR 100 /* there should NOT be 100 different... */ #define CC_FATAL 101 /* fatal error: inconsistant, must * reset */ #define CC_NORM 0 #define CC_NEWLINE 1 #define CC_EOF 2 #define CC_COMPLETE 3 #define CC_LIST_CHOICES 4 #define CC_LIST_GLOB 5 #define CC_EXPAND_GLOB 6 #define CC_HELPME 9 #define CC_CORRECT 10 #define CC_WHICH 11 #define CC_ARGHACK 12 #define CC_CORRECT_L 13 #define CC_REFRESH 14 #define CC_EXPAND_VARS 15 #define CC_NORMALIZE_PATH 16 #define CC_LIST_ALL 17 #define CC_COMPLETE_ALL 18 #define CC_COMPLETE_FWD 19 #define CC_COMPLETE_BACK 20 #define CC_NORMALIZE_COMMAND 21 typedef struct { Char *buf; int len; } CStr; typedef union { /* value passed to the Xkey routines */ KEYCMD cmd; CStr str; } XmapVal; #define XK_NOD -1 /* Internal tree node */ #define XK_CMD 0 /* X-key was an editor command */ #define XK_STR 1 /* X-key was a string macro */ #define XK_EXE 2 /* X-key was a unix command */ /****************************/ /* Editor state and buffers */ /****************************/ EXTERN KEYCMD *CurrentKeyMap; /* current command key map */ EXTERN int inputmode; /* insert, replace, replace1 mode */ EXTERN Char GettingInput; /* true if getting an input line (mostly) */ EXTERN Char NeedsRedraw; /* for editor and twenex error messages */ EXTERN Char InputBuf[INBUFSIZE]; /* the real input data *//*FIXBUF*/ EXTERN Char *LastChar, *Cursor; /* point to the next open space */ EXTERN Char *InputLim; /* limit of size of InputBuf */ EXTERN Char MetaNext; /* flags for ^V and ^[ functions */ EXTERN Char AltKeyMap; /* Using alternative command map (for vi mode) */ EXTERN Char VImode; /* true if running in vi mode (PWP 6-27-88) */ EXTERN Char *Mark; /* the emacs "mark" (dot is Cursor) */ EXTERN char MarkIsSet; /* true if the mark has been set explicitly */ EXTERN Char DoingArg; /* true if we have an argument */ EXTERN int Argument; /* "universal" argument value */ EXTERN KEYCMD LastCmd; /* previous command executed */ EXTERN CStr *KillRing; /* kill ring */ EXTERN int KillRingMax; /* max length of kill ring */ EXTERN int KillRingLen; /* current length of kill ring */ EXTERN int KillPos; /* points to next kill */ EXTERN int YankPos; /* points to next yank */ EXTERN Char UndoBuf[INBUFSIZE];/*FIXBUF*/ EXTERN Char *UndoPtr; EXTERN int UndoSize; EXTERN int UndoAction; EXTERN struct Strbuf HistBuf; /* = Strbuf_INIT; history buffer */ EXTERN int Hist_num; /* what point up the history we are at now. */ /* buffer for which command and others */ EXTERN struct Strbuf SavedBuf; /* = Strbuf_INIT; */ EXTERN size_t LastSaved; /* points to end of saved buffer */ EXTERN size_t CursSaved; /* points to the cursor point in saved buf */ EXTERN int HistSaved; /* Hist_num is saved in this */ EXTERN char RestoreSaved; /* true if SavedBuf should be restored */ EXTERN int IncMatchLen; /* current match length during incremental search */ EXTERN char Expand; /* true if we are expanding a line */ extern Char HistLit; /* true if history lines are shown literal */ EXTERN Char CurrentHistLit; /* Literal status of current show history line */ extern int Tty_raw_mode; /* * These are truly extern */ extern int MacroLvl; extern Char *litptr; /* Entries start at offsets divisible by LIT_FACTOR */ #define LIT_FACTOR 4 extern int didsetty; EXTERN Char *KeyMacro[MAXMACROLEVELS]; /* CHAR_DBWIDTH in Display and Vdisplay means the non-first column of a character that is wider than one "regular" position. The cursor should never point in the middle of a multiple-column character. */ EXTERN Char **Display; /* display buffer seed vector */ EXTERN int CursorV, /* real cursor vertical (line) */ CursorH, /* real cursor horisontal (column) */ TermV, /* number of real screen lines * (sizeof(DisplayBuf) / width */ TermH; /* screen width */ EXTERN Char **Vdisplay; /* new buffer */ /* Variables that describe terminal ability */ EXTERN int T_Lines, T_Cols; /* Rows and Cols of the terminal */ EXTERN Char T_CanIns; /* true if I can insert characters */ EXTERN Char T_CanDel; /* dito for delete characters */ EXTERN char T_Tabs; /* true if tty interface is passing tabs */ EXTERN char T_Margin; #define MARGIN_AUTO 1 /* term has auto margins */ #define MARGIN_MAGIC 2 /* concept glitch */ EXTERN speed_t T_Speed; /* Tty input Baud rate */ EXTERN Char T_CanCEOL; /* true if we can clear to end of line */ EXTERN Char T_CanUP; /* true if this term can do reverse linefeen */ EXTERN char T_HasMeta; /* true if we have a meta key */ /* note the extra characters in the Strchr() call in this macro */ #define isword(c) (Isalpha(c)||Isdigit(c)||Strchr(word_chars,c)) #define min(x,y) (((x)<(y))?(x):(y)) #define max(x,y) (((x)>(y))?(x):(y)) #define MODE_INSERT 0 #define MODE_REPLACE 1 #define MODE_REPLACE_1 2 #define EX_IO 0 /* while we are executing */ #define ED_IO 1 /* while we are editing */ #define TS_IO 2 /* new mode from terminal */ #define QU_IO 2 /* used only for quoted chars */ #define NN_IO 3 /* The number of entries */ #if defined(POSIX) || defined(TERMIO) # define M_INPUT 0 # define M_OUTPUT 1 # define M_CONTROL 2 # define M_LINED 3 # define M_CHAR 4 # define M_NN 5 #else /* GSTTY */ # define M_CONTROL 0 # define M_LOCAL 1 # define M_CHAR 2 # define M_NN 3 #endif /* TERMIO */ -typedef struct { +typedef struct { const char *t_name; unsigned int t_setmask; unsigned int t_clrmask; } ttyperm_t[NN_IO][M_NN]; extern ttyperm_t ttylist; #include "ed.term.h" #include "ed.decls.h" #ifndef POSIX /* * We don't prototype these, cause some systems have them wrong! */ extern int tgetent (); extern char *tgetstr (); extern int tgetflag (); extern int tgetnum (); extern char *tgoto (); # define PUTPURE putpure # define PUTRAW putraw #else extern int tgetent (char *, const char *); extern char *tgetstr (const char *, char **); extern int tgetflag (const char *); extern int tgetnum (const char *); extern char *tgoto (const char *, int, int); extern void tputs (const char *, int, void (*)(int)); -# define PUTPURE ((void (*)(int)) putpure) -# define PUTRAW ((void (*)(int)) putraw) +static __inline void PUTPURE(int c) { + (void)putpure(c); +} +static __inline void PUTRAW(int c) { + (void)putraw(c); +} #endif #endif /* _h_ed */ diff --git a/contrib/tcsh/ed.init.c b/contrib/tcsh/ed.init.c index f90028499f53..4781f15a5ea5 100644 --- a/contrib/tcsh/ed.init.c +++ b/contrib/tcsh/ed.init.c @@ -1,704 +1,704 @@ /* * ed.init.c: Editor initializations */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTS_ION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include "tc.h" #include "ed.defns.h" /* ed.init.c -- init routines for the line editor */ /* #define DEBUG_TTY */ int Tty_raw_mode = 0; /* Last tty change was to raw mode */ int MacroLvl = -1; /* pointer to current macro nesting level; */ /* (-1 == none) */ static int Tty_quote_mode = 0; /* Last tty change was to quote mode */ -static unsigned char vdisable; /* The value of _POSIX_VDISABLE from +static unsigned char vdisable; /* The value of _POSIX_VDISABLE from * pathconf(2) */ int Tty_eight_bit = -1; /* does the tty handle eight bits */ extern int GotTermCaps; static ttydata_t extty, edtty, tstty; #define qutty tstty #define SHTTY (insource ? OLDSTD : SHIN) #define uc unsigned char static unsigned char ttychars[NN_IO][C_NCC] = { { - (uc)CINTR, (uc)CQUIT, (uc)CERASE, (uc)CKILL, - (uc)CEOF, (uc)CEOL, (uc)CEOL2, (uc)CSWTCH, + (uc)CINTR, (uc)CQUIT, (uc)CERASE, (uc)CKILL, + (uc)CEOF, (uc)CEOL, (uc)CEOL2, (uc)CSWTCH, (uc)CDSWTCH, (uc)CERASE2, (uc)CSTART, (uc)CSTOP, (uc)CWERASE, (uc)CSUSP, (uc)CDSUSP, (uc)CREPRINT, (uc)CDISCARD, (uc)CLNEXT, (uc)CSTATUS, (uc)CPAGE, (uc)CPGOFF, (uc)CKILL2, (uc)CBRK, (uc)CMIN, (uc)CTIME }, { - CINTR, CQUIT, CERASE, CKILL, - _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, - _POSIX_VDISABLE, CERASE2, CSTART, CSTOP, - _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, - CDISCARD, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, + CINTR, CQUIT, CERASE, CKILL, + _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, + _POSIX_VDISABLE, CERASE2, CSTART, CSTOP, + _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, + CDISCARD, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, _POSIX_VDISABLE, 1, 0 }, - { + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; #ifdef SIG_WINDOW void check_window_size(int force) { int lins, cols; /* don't want to confuse things here */ pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); /* * From: bret@shark.agps.lanl.gov (Bret Thaeler) Avoid sunview bug, where a * partially hidden window gets a SIG_WINDOW every time the text is * scrolled */ if (GetSize(&lins, &cols) || force) { if (GettingInput) { ClearLines(); ClearDisp(); MoveToLine(0); MoveToChar(0); ChangeSize(lins, cols); Refresh(); } else ChangeSize(lins, cols); } windowchg = 0; cleanup_until(&pintr_disabled); /* can change it again */ } void /*ARGSUSED*/ window_change(int snum) { USE(snum); windowchg = 1; } #endif /* SIG_WINDOW */ void ed_set_tty_eight_bit(void) { if (tty_getty(SHTTY, &extty) == -1) { #ifdef DEBUG_TTY xprintf("ed_set_tty_eight_bit: tty_getty: %s\n", strerror(errno)); #endif /* DEBUG_TTY */ return; } Tty_eight_bit = tty_geteightbit(&extty); } - + int ed_Setup(int rst) { static int havesetup = 0; struct varent *imode; if (havesetup) /* if we have never been called */ return(0); #if defined(POSIX) && defined(_PC_VDISABLE) && !defined(BSD4_4) && \ !defined(WINNT_NATIVE) - { + { long pcret; if ((pcret = fpathconf(SHTTY, _PC_VDISABLE)) == -1L) vdisable = (unsigned char) _POSIX_VDISABLE; - else + else vdisable = (unsigned char) pcret; if (vdisable != (unsigned char) _POSIX_VDISABLE && rst != 0) for (rst = 0; rst < C_NCC; rst++) { if (ttychars[ED_IO][rst] == (unsigned char) _POSIX_VDISABLE) ttychars[ED_IO][rst] = vdisable; if (ttychars[EX_IO][rst] == (unsigned char) _POSIX_VDISABLE) ttychars[EX_IO][rst] = vdisable; } } #else /* ! POSIX || !_PC_VDISABLE || BSD4_4 || WINNT_NATIVE */ vdisable = (unsigned char) _POSIX_VDISABLE; #endif /* POSIX && _PC_VDISABLE && !BSD4_4 && !WINNT_NATIVE */ - + if ((imode = adrof(STRinputmode)) != NULL && imode->vec != NULL) { if (!Strcmp(*(imode->vec), STRinsert)) inputmode = MODE_INSERT; else if (!Strcmp(*(imode->vec), STRoverwrite)) inputmode = MODE_REPLACE; } else inputmode = MODE_INSERT; ed_InitMaps(); Hist_num = 0; Expand = 0; SetKillRing(getn(varval(STRkillring))); #ifndef WINNT_NATIVE if (tty_getty(SHTTY, &extty) == -1) { # ifdef DEBUG_TTY xprintf("ed_Setup: tty_getty: %s\n", strerror(errno)); # endif /* DEBUG_TTY */ return(-1); } tstty = edtty = extty; T_Speed = tty_getspeed(&extty); T_Tabs = tty_gettabs(&extty); Tty_eight_bit = tty_geteightbit(&extty); # if defined(POSIX) || defined(TERMIO) extty.d_t.c_iflag &= ~ttylist[EX_IO][M_INPUT].t_clrmask; extty.d_t.c_iflag |= ttylist[EX_IO][M_INPUT].t_setmask; extty.d_t.c_oflag &= ~ttylist[EX_IO][M_OUTPUT].t_clrmask; extty.d_t.c_oflag |= ttylist[EX_IO][M_OUTPUT].t_setmask; extty.d_t.c_cflag &= ~ttylist[EX_IO][M_CONTROL].t_clrmask; extty.d_t.c_cflag |= ttylist[EX_IO][M_CONTROL].t_setmask; extty.d_t.c_lflag &= ~ttylist[EX_IO][M_LINED].t_clrmask; extty.d_t.c_lflag |= ttylist[EX_IO][M_LINED].t_setmask; # if defined(IRIX3_3) && SYSVREL < 4 extty.d_t.c_line = NTTYDISC; # endif /* IRIX3_3 && SYSVREL < 4 */ # else /* GSTTY */ /* V7, Berkeley style tty */ if (T_Tabs) { /* order of &= and |= is important to XTABS */ extty.d_t.sg_flags &= ~(ttylist[EX_IO][M_CONTROL].t_clrmask|XTABS); extty.d_t.sg_flags |= ttylist[EX_IO][M_CONTROL].t_setmask; } else { extty.d_t.sg_flags &= ~ttylist[EX_IO][M_CONTROL].t_clrmask; extty.d_t.sg_flags |= (ttylist[EX_IO][M_CONTROL].t_setmask|XTABS); } extty.d_lb &= ~ttylist[EX_IO][M_LOCAL].t_clrmask; extty.d_lb |= ttylist[EX_IO][M_LOCAL].t_setmask; # endif /* GSTTY */ /* * Reset the tty chars to reasonable defaults * If they are disabled, then enable them. */ if (rst) { if (tty_cooked_mode(&tstty)) { tty_getchar(&tstty, ttychars[TS_IO]); /* * Don't affect CMIN and CTIME for the editor mode */ - for (rst = 0; rst < C_NCC - 2; rst++) + for (rst = 0; rst < C_NCC - 2; rst++) if (ttychars[TS_IO][rst] != vdisable && ttychars[ED_IO][rst] != vdisable) ttychars[ED_IO][rst] = ttychars[TS_IO][rst]; - for (rst = 0; rst < C_NCC; rst++) + for (rst = 0; rst < C_NCC; rst++) if (ttychars[TS_IO][rst] != vdisable && ttychars[EX_IO][rst] != vdisable) ttychars[EX_IO][rst] = ttychars[TS_IO][rst]; } tty_setchar(&extty, ttychars[EX_IO]); if (tty_setty(SHTTY, &extty) == -1) { # ifdef DEBUG_TTY xprintf("ed_Setup: tty_setty: %s\n", strerror(errno)); # endif /* DEBUG_TTY */ return(-1); } } else tty_setchar(&extty, ttychars[EX_IO]); # ifdef SIG_WINDOW { sigset_t set; (void)signal(SIG_WINDOW, window_change); /* for window systems */ sigemptyset(&set); sigaddset(&set, SIG_WINDOW); (void)sigprocmask(SIG_UNBLOCK, &set, NULL); } # endif #else /* WINNT_NATIVE */ # ifdef DEBUG if (rst) xprintf("rst received in ed_Setup() %d\n", rst); # endif #endif /* WINNT_NATIVE */ havesetup = 1; return(0); } void ed_Init(void) { ResetInLine(1); /* reset the input pointers */ GettingInput = 0; /* just in case */ #ifdef notdef /* XXX This code was here before the kill ring: LastKill = KillBuf; / * no kill buffer * / If there was any reason for that other than to make sure LastKill was initialized, the code below should go in here instead - but it doesn't seem reasonable to lose the entire kill ring (which is "self-initializing") just because you set $term or whatever, so presumably this whole '#ifdef notdef' should just be taken out. */ { /* no kill ring - why? */ int i; for (i = 0; i < KillRingMax; i++) { xfree(KillRing[i].buf); KillRing[i].buf = NULL; KillRing[i].len = 0; } YankPos = KillPos = 0; KillRingLen = 0; } #endif #ifdef DEBUG_EDIT CheckMaps(); /* do a little error checking on key maps */ -#endif +#endif if (ed_Setup(0) == -1) return; /* * if we have been called before but GotTermCaps isn't set, our TERM has * changed, so get new termcaps and try again */ if (!GotTermCaps) GetTermCaps(); /* does the obvious, but gets term type each * time */ #ifndef WINNT_NATIVE # if defined(TERMIO) || defined(POSIX) edtty.d_t.c_iflag &= ~ttylist[ED_IO][M_INPUT].t_clrmask; edtty.d_t.c_iflag |= ttylist[ED_IO][M_INPUT].t_setmask; edtty.d_t.c_oflag &= ~ttylist[ED_IO][M_OUTPUT].t_clrmask; edtty.d_t.c_oflag |= ttylist[ED_IO][M_OUTPUT].t_setmask; edtty.d_t.c_cflag &= ~ttylist[ED_IO][M_CONTROL].t_clrmask; edtty.d_t.c_cflag |= ttylist[ED_IO][M_CONTROL].t_setmask; edtty.d_t.c_lflag &= ~ttylist[ED_IO][M_LINED].t_clrmask; edtty.d_t.c_lflag |= ttylist[ED_IO][M_LINED].t_setmask; # if defined(IRIX3_3) && SYSVREL < 4 edtty.d_t.c_line = NTTYDISC; # endif /* IRIX3_3 && SYSVREL < 4 */ # else /* GSTTY */ if (T_Tabs) { /* order of &= and |= is important to XTABS */ edtty.d_t.sg_flags &= ~(ttylist[ED_IO][M_CONTROL].t_clrmask | XTABS); edtty.d_t.sg_flags |= ttylist[ED_IO][M_CONTROL].t_setmask; } else { edtty.d_t.sg_flags &= ~ttylist[ED_IO][M_CONTROL].t_clrmask; edtty.d_t.sg_flags |= (ttylist[ED_IO][M_CONTROL].t_setmask | XTABS); } edtty.d_lb &= ~ttylist[ED_IO][M_LOCAL].t_clrmask; edtty.d_lb |= ttylist[ED_IO][M_LOCAL].t_setmask; # endif /* POSIX || TERMIO */ tty_setchar(&edtty, ttychars[ED_IO]); #endif /* WINNT_NATIVE */ } -/* +/* * Check and re-init the line. set the terminal into 1 char at a time mode. */ int Rawmode(void) { if (Tty_raw_mode) return (0); #ifdef WINNT_NATIVE do_nt_raw_mode(); #else /* !WINNT_NATIVE */ # ifdef _IBMR2 tty_setdisc(SHTTY, ED_IO); # endif /* _IBMR2 */ if (tty_getty(SHTTY, &tstty) == -1) { # ifdef DEBUG_TTY xprintf("Rawmode: tty_getty: %s\n", strerror(errno)); # endif /* DEBUG_TTY */ return(-1); } /* * We always keep up with the eight bit setting and the speed of the * tty. But only we only believe changes that are made to cooked mode! */ # if defined(POSIX) || defined(TERMIO) Tty_eight_bit = tty_geteightbit(&tstty); T_Speed = tty_getspeed(&tstty); # ifdef POSIX /* * Fix from: Steven (Steve) B. Green * Speed was not being set up correctly under POSIX. */ if (tty_getspeed(&extty) != T_Speed || tty_getspeed(&edtty) != T_Speed) { (void) cfsetispeed(&extty.d_t, T_Speed); (void) cfsetospeed(&extty.d_t, T_Speed); (void) cfsetispeed(&edtty.d_t, T_Speed); (void) cfsetospeed(&edtty.d_t, T_Speed); } # endif /* POSIX */ # else /* GSTTY */ T_Speed = tty_getspeed(&tstty); Tty_eight_bit = tty_geteightbit(&tstty); if (extty.d_t.sg_ispeed != tstty.d_t.sg_ispeed) { extty.d_t.sg_ispeed = tstty.d_t.sg_ispeed; edtty.d_t.sg_ispeed = tstty.d_t.sg_ispeed; } if (extty.d_t.sg_ospeed != tstty.d_t.sg_ospeed) { extty.d_t.sg_ospeed = tstty.d_t.sg_ospeed; edtty.d_t.sg_ospeed = tstty.d_t.sg_ospeed; } # endif /* POSIX || TERMIO */ if (tty_cooked_mode(&tstty)) { /* - * re-test for some things here (like maybe the user typed + * re-test for some things here (like maybe the user typed * "stty -tabs" */ if (tty_gettabs(&tstty) == 0) T_Tabs = 0; - else + else T_Tabs = CanWeTab(); # if defined(POSIX) || defined(TERMIO) extty.d_t.c_cflag = tstty.d_t.c_cflag; extty.d_t.c_cflag &= ~ttylist[EX_IO][M_CONTROL].t_clrmask; extty.d_t.c_cflag |= ttylist[EX_IO][M_CONTROL].t_setmask; edtty.d_t.c_cflag = tstty.d_t.c_cflag; edtty.d_t.c_cflag &= ~ttylist[ED_IO][M_CONTROL].t_clrmask; edtty.d_t.c_cflag |= ttylist[ED_IO][M_CONTROL].t_setmask; extty.d_t.c_lflag = tstty.d_t.c_lflag; extty.d_t.c_lflag &= ~ttylist[EX_IO][M_LINED].t_clrmask; extty.d_t.c_lflag |= ttylist[EX_IO][M_LINED].t_setmask; edtty.d_t.c_lflag = tstty.d_t.c_lflag; edtty.d_t.c_lflag &= ~ttylist[ED_IO][M_LINED].t_clrmask; edtty.d_t.c_lflag |= ttylist[ED_IO][M_LINED].t_setmask; extty.d_t.c_iflag = tstty.d_t.c_iflag; extty.d_t.c_iflag &= ~ttylist[EX_IO][M_INPUT].t_clrmask; extty.d_t.c_iflag |= ttylist[EX_IO][M_INPUT].t_setmask; edtty.d_t.c_iflag = tstty.d_t.c_iflag; edtty.d_t.c_iflag &= ~ttylist[ED_IO][M_INPUT].t_clrmask; edtty.d_t.c_iflag |= ttylist[ED_IO][M_INPUT].t_setmask; extty.d_t.c_oflag = tstty.d_t.c_oflag; extty.d_t.c_oflag &= ~ttylist[EX_IO][M_OUTPUT].t_clrmask; extty.d_t.c_oflag |= ttylist[EX_IO][M_OUTPUT].t_setmask; edtty.d_t.c_oflag = tstty.d_t.c_oflag; edtty.d_t.c_oflag &= ~ttylist[ED_IO][M_OUTPUT].t_clrmask; edtty.d_t.c_oflag |= ttylist[ED_IO][M_OUTPUT].t_setmask; # else /* GSTTY */ extty.d_t.sg_flags = tstty.d_t.sg_flags; extty.d_t.sg_flags &= ~ttylist[EX_IO][M_CONTROL].t_clrmask; extty.d_t.sg_flags |= ttylist[EX_IO][M_CONTROL].t_setmask; if (T_Tabs) /* order of &= and |= is important to XTABS */ extty.d_t.sg_flags &= ~XTABS; - else + else extty.d_t.sg_flags |= XTABS; extty.d_lb = tstty.d_lb; extty.d_lb &= ~ttylist[EX_IO][M_LOCAL].t_clrmask; extty.d_lb |= ttylist[EX_IO][M_LOCAL].t_setmask; edtty.d_t.sg_flags = extty.d_t.sg_flags; if (T_Tabs) { /* order of &= and |= is important to XTABS */ - edtty.d_t.sg_flags &= + edtty.d_t.sg_flags &= ~(ttylist[ED_IO][M_CONTROL].t_clrmask|XTABS); edtty.d_t.sg_flags |= ttylist[ED_IO][M_CONTROL].t_setmask; } else { edtty.d_t.sg_flags &= ~ttylist[ED_IO][M_CONTROL].t_clrmask; - edtty.d_t.sg_flags |= + edtty.d_t.sg_flags |= (ttylist[ED_IO][M_CONTROL].t_setmask|XTABS); } edtty.d_lb = tstty.d_lb; edtty.d_lb &= ~ttylist[ED_IO][M_LOCAL].t_clrmask; edtty.d_lb |= ttylist[ED_IO][M_LOCAL].t_setmask; # endif /* TERMIO || POSIX */ { int i; tty_getchar(&tstty, ttychars[TS_IO]); /* * Check if the user made any changes. * If he did, then propagate the changes to the * edit and execute data structures. */ for (i = 0; i < C_NCC; i++) if (ttychars[TS_IO][i] != ttychars[EX_IO][i]) break; - + if (i != C_NCC || didsetty) { didsetty = 0; /* * Propagate changes only to the unprotected chars * that have been modified just now. */ for (i = 0; i < C_NCC; i++) { if (!((ttylist[ED_IO][M_CHAR].t_setmask & C_SH(i))) && (ttychars[TS_IO][i] != ttychars[EX_IO][i])) ttychars[ED_IO][i] = ttychars[TS_IO][i]; if (ttylist[ED_IO][M_CHAR].t_clrmask & C_SH(i)) ttychars[ED_IO][i] = vdisable; } tty_setchar(&edtty, ttychars[ED_IO]); for (i = 0; i < C_NCC; i++) { if (!((ttylist[EX_IO][M_CHAR].t_setmask & C_SH(i))) && (ttychars[TS_IO][i] != ttychars[EX_IO][i])) ttychars[EX_IO][i] = ttychars[TS_IO][i]; if (ttylist[EX_IO][M_CHAR].t_clrmask & C_SH(i)) ttychars[EX_IO][i] = vdisable; } tty_setchar(&extty, ttychars[EX_IO]); } } } if (tty_setty(SHTTY, &edtty) == -1) { # ifdef DEBUG_TTY xprintf("Rawmode: tty_setty: %s\n", strerror(errno)); # endif /* DEBUG_TTY */ return(-1); } #endif /* WINNT_NATIVE */ Tty_raw_mode = 1; flush(); /* flush any buffered output */ return (0); } int Cookedmode(void) { /* set tty in normal setup */ #ifdef WINNT_NATIVE do_nt_cooked_mode(); #else sigset_t set, oset; int res; # ifdef _IBMR2 tty_setdisc(SHTTY, EX_IO); # endif /* _IBMR2 */ if (!Tty_raw_mode) return (0); /* hold this for reseting tty */ sigemptyset(&set); sigaddset(&set, SIGINT); (void)sigprocmask(SIG_BLOCK, &set, &oset); cleanup_push(&oset, sigprocmask_cleanup); res = tty_setty(SHTTY, &extty); cleanup_until(&oset); if (res == -1) { # ifdef DEBUG_TTY xprintf("Cookedmode: tty_setty: %s\n", strerror(errno)); # endif /* DEBUG_TTY */ return -1; } #endif /* WINNT_NATIVE */ Tty_raw_mode = 0; return (0); } void ResetInLine(int macro) { Cursor = InputBuf; /* reset cursor */ LastChar = InputBuf; InputLim = &InputBuf[INBUFSIZE - 2];/*FIXBUF*/ Mark = InputBuf; MarkIsSet = 0; MetaNext = 0; CurrentKeyMap = CcKeyMap; AltKeyMap = 0; Hist_num = 0; DoingArg = 0; Argument = 1; LastCmd = F_UNASSIGNED; /* previous command executed */ IncMatchLen = 0; if (macro) MacroLvl = -1; /* no currently active macros */ } int Load_input_line(void) { static Char *Input_Line = NULL; #ifdef SUNOS4 long chrs = 0; #else /* !SUNOS4 */ - /* + /* * *Everyone* else has an int, but SunOS wants long! * This breaks where int != long (alpha) */ int chrs = 0; #endif /* SUNOS4 */ if (Input_Line) xfree(Input_Line); Input_Line = NULL; if (Tty_raw_mode) return 0; #if defined(FIONREAD) && !defined(OREO) (void) ioctl(SHIN, FIONREAD, (ioctl_t) &chrs); if (chrs > 0) { char buf[BUFSIZE]; chrs = xread(SHIN, buf, min(chrs, BUFSIZE - 1)); if (chrs > 0) { buf[chrs] = '\0'; Input_Line = Strsave(str2short(buf)); PushMacro(Input_Line); } #ifdef convex /* need to print errno message in case file is migrated */ if (chrs < 0) stderror(ERR_SYSTEM, progname, strerror(errno)); #endif } #endif /* FIONREAD && !OREO */ return chrs > 0; } /* * Bugfix (in Swedish) by: * Johan Widen * SICS, PO Box 1263, S-163 13 SPANGA, SWEDEN * {mcvax,munnari,cernvax,diku,inria,prlb2,penet,ukc,unido}!enea!sics.se!jw * Internet: jw@sics.se * * (via Hans J Albertsson (thanks)) */ void QuoteModeOn(void) { if (MacroLvl >= 0) return; #ifndef WINNT_NATIVE qutty = edtty; #if defined(TERMIO) || defined(POSIX) qutty.d_t.c_iflag &= ~ttylist[QU_IO][M_INPUT].t_clrmask; qutty.d_t.c_iflag |= ttylist[QU_IO][M_INPUT].t_setmask; qutty.d_t.c_oflag &= ~ttylist[QU_IO][M_OUTPUT].t_clrmask; qutty.d_t.c_oflag |= ttylist[QU_IO][M_OUTPUT].t_setmask; qutty.d_t.c_cflag &= ~ttylist[QU_IO][M_CONTROL].t_clrmask; qutty.d_t.c_cflag |= ttylist[QU_IO][M_CONTROL].t_setmask; qutty.d_t.c_lflag &= ~ttylist[QU_IO][M_LINED].t_clrmask; qutty.d_t.c_lflag |= ttylist[QU_IO][M_LINED].t_setmask; #else /* GSTTY */ qutty.d_t.sg_flags &= ~ttylist[QU_IO][M_CONTROL].t_clrmask; qutty.d_t.sg_flags |= ttylist[QU_IO][M_CONTROL].t_setmask; qutty.d_lb &= ~ttylist[QU_IO][M_LOCAL].t_clrmask; qutty.d_lb |= ttylist[QU_IO][M_LOCAL].t_setmask; #endif /* TERMIO || POSIX */ if (tty_setty(SHTTY, &qutty) == -1) { #ifdef DEBUG_TTY xprintf("QuoteModeOn: tty_setty: %s\n", strerror(errno)); #endif /* DEBUG_TTY */ return; } #endif /* !WINNT_NATIVE */ Tty_quote_mode = 1; return; } void QuoteModeOff(void) { if (!Tty_quote_mode) return; Tty_quote_mode = 0; if (tty_setty(SHTTY, &edtty) == -1) { #ifdef DEBUG_TTY xprintf("QuoteModeOff: tty_setty: %s\n", strerror(errno)); #endif /* DEBUG_TTY */ return; } return; } diff --git a/contrib/tcsh/ed.inputl.c b/contrib/tcsh/ed.inputl.c index 8d4c341631b0..35f21a4e95a8 100644 --- a/contrib/tcsh/ed.inputl.c +++ b/contrib/tcsh/ed.inputl.c @@ -1,955 +1,955 @@ /* * ed.inputl.c: Input line handling. */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include "ed.defns.h" /* for the function names */ #include "tw.h" /* for twenex stuff */ #define OKCMD INT_MAX /* ed.inputl -- routines to get a single line from the input. */ extern int MapsAreInited; /* mismatched first character */ static Char mismatch[] = { '\\', '-', '%', '\0' }; /* don't Strchr() for '\0', obey current history character settings */ #define MISMATCH(c) ((c) == '\0' || (c) == HIST || (c) == HISTSUB || \ Strchr(mismatch, (c))) static int Repair (void); static int GetNextCommand (KEYCMD *, Char *); static int SpellLine (int); static int CompleteLine (void); static void RunCommand (Char *); static void doeval1 (Char **); static int rotate = 0; static int Repair(void) { if (NeedsRedraw) { ClearLines(); ClearDisp(); NeedsRedraw = 0; } Refresh(); Argument = 1; DoingArg = 0; curchoice = -1; return (int) (LastChar - InputBuf); } /* CCRETVAL */ int Inputl(void) { CCRETVAL retval; KEYCMD cmdnum = 0; unsigned char tch; /* the place where read() goes */ Char ch; int num; /* how many chars we have read at NL */ int expnum; struct varent *crct = inheredoc ? NULL : adrof(STRcorrect); struct varent *autol = adrof(STRautolist); struct varent *matchbeep = adrof(STRmatchbeep); struct varent *imode = adrof(STRinputmode); Char *SaveChar, *CorrChar; int matchval; /* from tenematch() */ int nr_history_exp; /* number of (attempted) history expansions */ COMMAND fn; int curlen = 0; int newlen; int idx; Char *autoexpand; if (!MapsAreInited) /* double extra just in case */ ed_InitMaps(); ClearDisp(); /* reset the display stuff */ ResetInLine(0); /* reset the input pointers */ if (GettingInput) MacroLvl = -1; /* editor was interrupted during input */ if (imode && imode->vec != NULL) { if (!Strcmp(*(imode->vec), STRinsert)) inputmode = MODE_INSERT; else if (!Strcmp(*(imode->vec), STRoverwrite)) inputmode = MODE_REPLACE; } #if defined(FIONREAD) && !defined(OREO) if (!Tty_raw_mode && MacroLvl < 0) { # ifdef SUNOS4 long chrs = 0; # else /* !SUNOS4 */ - /* + /* * *Everyone* else has an int, but SunOS wants long! * This breaks where int != long (alpha) */ int chrs = 0; # endif /* SUNOS4 */ (void) ioctl(SHIN, FIONREAD, (ioctl_t) & chrs); if (chrs == 0) { if (Rawmode() < 0) return 0; } } #endif /* FIONREAD && !OREO */ GettingInput = 1; NeedsRedraw = 0; tellwhat = 0; if (RestoreSaved) { copyn(InputBuf, SavedBuf.s, INBUFSIZE);/*FIXBUF*/ LastChar = InputBuf + LastSaved; Cursor = InputBuf + CursSaved; Hist_num = HistSaved; HistSaved = 0; RestoreSaved = 0; } if (HistSaved) { Hist_num = HistSaved; GetHistLine(); HistSaved = 0; } if (Expand) { (void) e_up_hist(0); Expand = 0; } Refresh(); /* print the prompt */ for (num = OKCMD; num == OKCMD;) { /* while still editing this line */ #ifdef DEBUG_EDIT if (Cursor > LastChar) xprintf("Cursor > LastChar\r\n"); if (Cursor < InputBuf) xprintf("Cursor < InputBuf\r\n"); if (Cursor > InputLim) xprintf("Cursor > InputLim\r\n"); if (LastChar > InputLim) xprintf("LastChar > InputLim\r\n"); if (InputLim != &InputBuf[INBUFSIZE - 2])/*FIXBUF*/ xprintf("InputLim != &InputBuf[INBUFSIZE-2]\r\n"); if ((!DoingArg) && (Argument != 1)) xprintf("(!DoingArg) && (Argument != 1)\r\n"); if (CcKeyMap[0] == 0) xprintf("CcKeyMap[0] == 0 (maybe not inited)\r\n"); #endif /* if EOF or error */ if ((num = GetNextCommand(&cmdnum, &ch)) != OKCMD) { break; } if (cmdnum >= NumFuns) {/* BUG CHECK command */ #ifdef DEBUG_EDIT xprintf(CGETS(6, 1, "ERROR: illegal command from key 0%o\r\n"), ch); #endif continue; /* try again */ } /* now do the real command */ retval = (*CcFuncTbl[cmdnum]) (ch); /* save the last command here */ LastCmd = cmdnum; /* make sure fn is initialized */ fn = (retval == CC_COMPLETE_ALL) ? LIST_ALL : LIST; /* use any return value */ switch (retval) { case CC_REFRESH: Refresh(); /*FALLTHROUGH*/ case CC_NORM: /* normal char */ Argument = 1; DoingArg = 0; /*FALLTHROUGH*/ case CC_ARGHACK: /* Suggested by Rich Salz */ /* */ curchoice = -1; curlen = (int) (LastChar - InputBuf); break; /* keep going... */ case CC_EOF: /* end of file typed */ curchoice = -1; curlen = (int) (LastChar - InputBuf); num = 0; break; case CC_WHICH: /* tell what this command does */ tellwhat = 1; *LastChar++ = '\n'; /* for the benifit of CSH */ num = (int) (LastChar - InputBuf); /* number characters read */ break; case CC_NEWLINE: /* normal end of line */ curlen = 0; curchoice = -1; matchval = 1; if (crct && crct->vec != NULL && (!Strcmp(*(crct->vec), STRcmd) || !Strcmp(*(crct->vec), STRall))) { Char *Origin; PastBottom(); Origin = Strsave(InputBuf); cleanup_push(Origin, xfree); SaveChar = LastChar; if (SpellLine(!Strcmp(*(crct->vec), STRcmd)) == 1) { Char *Change; PastBottom(); Change = Strsave(InputBuf); cleanup_push(Change, xfree); *Strchr(Change, '\n') = '\0'; CorrChar = LastChar; /* Save the corrected end */ LastChar = InputBuf; /* Null the current line */ SoundBeep(); printprompt(2, short2str(Change)); cleanup_until(Change); Refresh(); if (xread(SHIN, &tch, 1) < 0) { #ifdef convex /* * need to print error message in case file * is migrated */ if (errno) stderror(ERR_SYSTEM, progname, strerror(errno)); #else cleanup_until(Origin); break; #endif } ch = tch; if (ch == 'y' || ch == ' ') { LastChar = CorrChar; /* Restore the corrected end */ xprintf("%s", CGETS(6, 2, "yes\n")); } else { Strcpy(InputBuf, Origin); LastChar = SaveChar; if (ch == 'e') { xprintf("%s", CGETS(6, 3, "edit\n")); *LastChar-- = '\0'; Cursor = LastChar; printprompt(3, NULL); ClearLines(); ClearDisp(); Refresh(); cleanup_until(Origin); break; } else if (ch == 'a') { xprintf("%s", CGETS(6, 4, "abort\n")); LastChar = InputBuf; /* Null the current line */ Cursor = LastChar; printprompt(0, NULL); Refresh(); cleanup_until(Origin); break; } xprintf("%s", CGETS(6, 5, "no\n")); } flush(); } cleanup_until(Origin); } else if (crct && crct->vec != NULL && !Strcmp(*(crct->vec), STRcomplete)) { if (LastChar > InputBuf && LastChar[-1] == '\n') { LastChar[-1] = '\0'; LastChar--; Cursor = LastChar; } match_unique_match = 1; /* match unique matches */ matchval = CompleteLine(); match_unique_match = 0; curlen = (int) (LastChar - InputBuf); if (matchval != 1) { PastBottom(); } if (matchval == 0) { xprintf("%s", CGETS(6, 6, "No matching command\n")); } else if (matchval == 2) { xprintf("%s", CGETS(6, 7, "Ambiguous command\n")); } if (NeedsRedraw) { ClearLines(); ClearDisp(); NeedsRedraw = 0; } Refresh(); Argument = 1; DoingArg = 0; if (matchval == 1) { PastBottom(); *LastChar++ = '\n'; *LastChar = '\0'; } curlen = (int) (LastChar - InputBuf); } else PastBottom(); if (matchval == 1) { tellwhat = 0; /* just in case */ Hist_num = 0; /* for the history commands */ /* return the number of chars read */ num = (int) (LastChar - InputBuf); /* * For continuation lines, we set the prompt to prompt 2 */ printprompt(1, NULL); } break; case CC_CORRECT: if (tenematch(InputBuf, Cursor - InputBuf, SPELL) < 0) SoundBeep(); /* Beep = No match/ambiguous */ curlen = Repair(); break; case CC_CORRECT_L: if (SpellLine(FALSE) < 0) SoundBeep(); /* Beep = No match/ambiguous */ curlen = Repair(); break; case CC_COMPLETE: case CC_COMPLETE_ALL: case CC_COMPLETE_FWD: case CC_COMPLETE_BACK: switch (retval) { case CC_COMPLETE: fn = RECOGNIZE; curlen = (int) (LastChar - InputBuf); curchoice = -1; rotate = 0; break; case CC_COMPLETE_ALL: fn = RECOGNIZE_ALL; curlen = (int) (LastChar - InputBuf); curchoice = -1; rotate = 0; break; case CC_COMPLETE_FWD: fn = RECOGNIZE_SCROLL; curchoice++; rotate = 1; break; case CC_COMPLETE_BACK: fn = RECOGNIZE_SCROLL; curchoice--; rotate = 1; break; default: abort(); } if (InputBuf[curlen] && rotate) { newlen = (int) (LastChar - InputBuf); - for (idx = (int) (Cursor - InputBuf); + for (idx = (int) (Cursor - InputBuf); idx <= newlen; idx++) InputBuf[idx - newlen + curlen] = InputBuf[idx]; LastChar = InputBuf + curlen; Cursor = Cursor - newlen + curlen; } curlen = (int) (LastChar - InputBuf); nr_history_exp = 0; autoexpand = varval(STRautoexpand); if (autoexpand != STRNULL) nr_history_exp += ExpandHistory(); /* try normal expansion only if no history references were found */ if (nr_history_exp == 0 || Strcmp(autoexpand, STRonlyhistory) != 0) { /* * Modified by Martin Boyer (gamin@ireq-robot.hydro.qc.ca): * A separate variable now controls beeping after * completion, independently of autolisting. */ expnum = (int) (Cursor - InputBuf); switch (matchval = tenematch(InputBuf, Cursor-InputBuf, fn)){ case 1: if (non_unique_match && matchbeep && matchbeep->vec != NULL && (Strcmp(*(matchbeep->vec), STRnotunique) == 0)) SoundBeep(); break; case 0: if (matchbeep && matchbeep->vec != NULL) { if (Strcmp(*(matchbeep->vec), STRnomatch) == 0 || Strcmp(*(matchbeep->vec), STRambiguous) == 0 || Strcmp(*(matchbeep->vec), STRnotunique) == 0) SoundBeep(); } else SoundBeep(); break; default: if (matchval < 0) { /* Error from tenematch */ curchoice = -1; SoundBeep(); break; } if (matchbeep && matchbeep->vec != NULL) { if ((Strcmp(*(matchbeep->vec), STRambiguous) == 0 || Strcmp(*(matchbeep->vec), STRnotunique) == 0)) SoundBeep(); } else SoundBeep(); /* - * Addition by David C Lawrence : If an - * attempted completion is ambiguous, list the choices. - * (PWP: this is the best feature addition to tcsh I have + * Addition by David C Lawrence : If an + * attempted completion is ambiguous, list the choices. + * (PWP: this is the best feature addition to tcsh I have * seen in many months.) */ - if (autol && autol->vec != NULL && - (Strcmp(*(autol->vec), STRambiguous) != 0 || + if (autol && autol->vec != NULL && + (Strcmp(*(autol->vec), STRambiguous) != 0 || expnum == Cursor - InputBuf)) { if (adrof(STRhighlight) && MarkIsSet) { /* clear highlighting before showing completions */ MarkIsSet = 0; ClearLines(); ClearDisp(); Refresh(); MarkIsSet = 1; } PastBottom(); fn = (retval == CC_COMPLETE_ALL) ? LIST_ALL : LIST; (void) tenematch(InputBuf, Cursor-InputBuf, fn); } break; } } if (NeedsRedraw) { PastBottom(); ClearLines(); ClearDisp(); NeedsRedraw = 0; } Refresh(); Argument = 1; DoingArg = 0; break; case CC_LIST_CHOICES: case CC_LIST_ALL: if (InputBuf[curlen] && rotate) { newlen = (int) (LastChar - InputBuf); - for (idx = (int) (Cursor - InputBuf); + for (idx = (int) (Cursor - InputBuf); idx <= newlen; idx++) InputBuf[idx - newlen + curlen] = InputBuf[idx]; LastChar = InputBuf + curlen; Cursor = Cursor - newlen + curlen; } curlen = (int) (LastChar - InputBuf); if (curchoice >= 0) curchoice--; fn = (retval == CC_LIST_ALL) ? LIST_ALL : LIST; /* should catch ^C here... */ if (tenematch(InputBuf, Cursor - InputBuf, fn) < 0) SoundBeep(); Refresh(); Argument = 1; DoingArg = 0; break; case CC_LIST_GLOB: if (tenematch(InputBuf, Cursor - InputBuf, GLOB) < 0) SoundBeep(); curlen = Repair(); break; case CC_EXPAND_GLOB: if (tenematch(InputBuf, Cursor - InputBuf, GLOB_EXPAND) <= 0) SoundBeep(); /* Beep = No match */ curlen = Repair(); break; case CC_NORMALIZE_PATH: if (tenematch(InputBuf, Cursor - InputBuf, PATH_NORMALIZE) <= 0) SoundBeep(); /* Beep = No match */ curlen = Repair(); break; case CC_EXPAND_VARS: if (tenematch(InputBuf, Cursor - InputBuf, VARS_EXPAND) <= 0) SoundBeep(); /* Beep = No match */ curlen = Repair(); break; case CC_NORMALIZE_COMMAND: if (tenematch(InputBuf, Cursor - InputBuf, COMMAND_NORMALIZE) <= 0) SoundBeep(); /* Beep = No match */ curlen = Repair(); break; case CC_HELPME: xputchar('\n'); /* should catch ^C here... */ (void) tenematch(InputBuf, LastChar - InputBuf, PRINT_HELP); Refresh(); Argument = 1; DoingArg = 0; curchoice = -1; curlen = (int) (LastChar - InputBuf); break; case CC_FATAL: /* fatal error, reset to known state */ #ifdef DEBUG_EDIT xprintf(CGETS(7, 8, "*** editor fatal ERROR ***\r\n\n")); #endif /* DEBUG_EDIT */ /* put (real) cursor in a known place */ ClearDisp(); /* reset the display stuff */ ResetInLine(1); /* reset the input pointers */ Refresh(); /* print the prompt again */ Argument = 1; DoingArg = 0; curchoice = -1; curlen = (int) (LastChar - InputBuf); break; case CC_ERROR: default: /* functions we don't know about */ if (adrof(STRhighlight)) { ClearLines(); ClearDisp(); Refresh(); } DoingArg = 0; Argument = 1; SoundBeep(); flush(); curchoice = -1; curlen = (int) (LastChar - InputBuf); break; } } (void) Cookedmode(); /* make sure the tty is set up correctly */ GettingInput = 0; flush(); /* flush any buffered output */ return num; } void PushMacro(Char *str) { if (str != NULL && MacroLvl + 1 < MAXMACROLEVELS) { MacroLvl++; KeyMacro[MacroLvl] = str; } else { SoundBeep(); flush(); } } struct eval1_state { Char **evalvec, *evalp; }; static void eval1_cleanup(void *xstate) { struct eval1_state *state; state = xstate; evalvec = state->evalvec; evalp = state->evalp; doneinp = 0; } /* * Like eval, only using the current file descriptors */ static void doeval1(Char **v) { struct eval1_state state; Char **gv; int gflag; gflag = tglob(v); if (gflag) { gv = v = globall(v, gflag); if (v == 0) stderror(ERR_NOMATCH); v = copyblk(v); } else { gv = NULL; v = copyblk(v); trim(v); } if (gv) cleanup_push(gv, blk_cleanup); state.evalvec = evalvec; state.evalp = evalp; evalvec = v; evalp = 0; cleanup_push(&state, eval1_cleanup); process(0); cleanup_until(&state); if (gv) cleanup_until(gv); } static void RunCommand(Char *str) { Char *cmd[2]; xputchar('\n'); /* Start on a clean line */ cmd[0] = str; cmd[1] = NULL; (void) Cookedmode(); GettingInput = 0; doeval1(cmd); (void) Rawmode(); GettingInput = 1; ClearLines(); ClearDisp(); NeedsRedraw = 0; Refresh(); } int GetCmdChar(Char ch) { -#ifndef WINNT_NATIVE // We use more than 256 for various extended keys +#ifndef WINNT_NATIVE // We use more than 256 for various extended keys wint_t c = ch & CHAR; #else wint_t c = ch; #endif return c < NT_NUM_KEYS ? CurrentKeyMap[c] : F_INSERT; } static int GetNextCommand(KEYCMD *cmdnum, Char *ch) { KEYCMD cmd = 0; int num; while (cmd == 0 || cmd == F_XKEY) { if ((num = GetNextChar(ch)) != 1) { /* if EOF or error */ return num; } #ifdef KANJI if ( #ifdef DSPMBYTE _enable_mbdisp && #else MB_LEN_MAX == 1 && #endif !adrof(STRnokanji) && (*ch & META)) { MetaNext = 0; cmd = F_INSERT; break; } else #endif /* KANJI */ if (MetaNext) { MetaNext = 0; *ch |= META; } cmd = GetCmdChar(*ch); if (cmd == F_XKEY) { XmapVal val; CStr cstr; cstr.buf = ch; cstr.len = 1; switch (GetXkey(&cstr, &val)) { case XK_CMD: cmd = val.cmd; break; case XK_STR: PushMacro(val.str.buf); break; case XK_EXE: RunCommand(val.str.buf); break; default: abort(); break; } } - if (!AltKeyMap) + if (!AltKeyMap) CurrentKeyMap = CcKeyMap; } *cmdnum = cmd; return OKCMD; } static Char ungetchar; static int haveungetchar; void UngetNextChar(Char cp) { ungetchar = cp; haveungetchar = 1; } int GetNextChar(Char *cp) { int num_read; int tried = 0; char cbuf[MB_LEN_MAX]; size_t cbp; if (haveungetchar) { haveungetchar = 0; *cp = ungetchar; return 1; } for (;;) { if (MacroLvl < 0) { if (!Load_input_line()) break; } if (*KeyMacro[MacroLvl] == 0) { MacroLvl--; continue; } *cp = *KeyMacro[MacroLvl]++ & CHAR; if (*KeyMacro[MacroLvl] == 0) { /* Needed for QuoteMode On */ MacroLvl--; } return (1); } if (Rawmode() < 0) /* make sure the tty is set up correctly */ return 0; /* oops: SHIN was closed */ #ifdef WINNT_NATIVE __nt_want_vcode = 1; #endif /* WINNT_NATIVE */ #ifdef SIG_WINDOW if (windowchg) (void) check_window_size(0); /* for window systems */ #endif /* SIG_WINDOW */ cbp = 0; for (;;) { while ((num_read = xread(SHIN, cbuf + cbp, 1)) == -1) { if (!tried && fixio(SHIN, errno) != -1) tried = 1; else { # ifdef convex /* need to print error message in case the file is migrated */ stderror(ERR_SYSTEM, progname, strerror(errno)); # endif /* convex */ # ifdef WINNT_NATIVE __nt_want_vcode = 0; # endif /* WINNT_NATIVE */ *cp = '\0'; /* Loses possible partial character */ return -1; } } if (cbp == 0 /* && *cbuf < NT_NUM_KEYS */ && CurrentKeyMap[(unsigned char)*cbuf] == F_XKEY) { *cp = (unsigned char)*cbuf; } else { cbp++; if (normal_mbtowc(cp, cbuf, cbp) == -1) { reset_mbtowc(); if (cbp < MB_CUR_MAX) continue; /* Maybe a partial character */ /* And drop the following bytes, if any */ *cp = (unsigned char)*cbuf | INVALID_BYTE; } } break; } #ifdef WINNT_NATIVE /* This is the part that doesn't work with WIDE_STRINGS */ if (__nt_want_vcode == 2) *cp = __nt_vcode; __nt_want_vcode = 0; #endif /* WINNT_NATIVE */ return num_read; } /* * SpellLine - do spelling correction on the entire command line * (which may have trailing newline). * If cmdonly is set, only check spelling of command words. * Return value: * -1: Something was incorrectible, and nothing was corrected * 0: Everything was correct * 1: Something was corrected */ static int SpellLine(int cmdonly) { int endflag, matchval; Char *argptr, *OldCursor, *OldLastChar; OldLastChar = LastChar; OldCursor = Cursor; argptr = InputBuf; endflag = 1; matchval = 0; do { while (ismetahash(*argptr) || iscmdmeta(*argptr)) argptr++; for (Cursor = argptr; *Cursor != '\0' && ((Cursor != argptr && Cursor[-1] == '\\') || (!ismetahash(*Cursor) && !iscmdmeta(*Cursor))); Cursor++) continue; if (*Cursor == '\0') { Cursor = LastChar; if (LastChar[-1] == '\n') Cursor--; endflag = 0; } if (!MISMATCH(*argptr) && (!cmdonly || starting_a_command(argptr, InputBuf))) { #ifdef WINNT_NATIVE /* * This hack avoids correcting drive letter changes */ if ((Cursor - InputBuf) != 2 || (char)InputBuf[1] != ':') #endif /* WINNT_NATIVE */ { #ifdef HASH_SPELL_CHECK Char save; size_t len = Cursor - InputBuf; save = InputBuf[len]; InputBuf[len] = '\0'; if (find_cmd(InputBuf, 0) != 0) { InputBuf[len] = save; argptr = Cursor; continue; } InputBuf[len] = save; #endif /* HASH_SPELL_CHECK */ switch (tenematch(InputBuf, Cursor - InputBuf, SPELL)) { case 1: /* corrected */ matchval = 1; break; case -1: /* couldn't be corrected */ if (!matchval) matchval = -1; break; default: /* was correct */ break; } } if (LastChar != OldLastChar) { if (argptr < OldCursor) OldCursor += (LastChar - OldLastChar); OldLastChar = LastChar; } } argptr = Cursor; } while (endflag); Cursor = OldCursor; return matchval; } /* * CompleteLine - do command completion on the entire command line * (which may have trailing newline). * Return value: * 0: No command matched or failure * 1: One command matched * 2: Several commands matched */ static int CompleteLine(void) { int endflag, tmatch; Char *argptr, *OldCursor, *OldLastChar; OldLastChar = LastChar; OldCursor = Cursor; argptr = InputBuf; endflag = 1; do { while (ismetahash(*argptr) || iscmdmeta(*argptr)) argptr++; for (Cursor = argptr; *Cursor != '\0' && ((Cursor != argptr && Cursor[-1] == '\\') || (!ismetahash(*Cursor) && !iscmdmeta(*Cursor))); Cursor++) continue; if (*Cursor == '\0') { Cursor = LastChar; if (LastChar[-1] == '\n') Cursor--; endflag = 0; } if (!MISMATCH(*argptr) && starting_a_command(argptr, InputBuf)) { tmatch = tenematch(InputBuf, Cursor - InputBuf, RECOGNIZE); if (tmatch <= 0) { return 0; } else if (tmatch > 1) { return 2; } if (LastChar != OldLastChar) { if (argptr < OldCursor) OldCursor += (LastChar - OldLastChar); OldLastChar = LastChar; } } argptr = Cursor; } while (endflag); Cursor = OldCursor; return 1; } diff --git a/contrib/tcsh/ed.refresh.c b/contrib/tcsh/ed.refresh.c index 3619e1144bf6..c1f1cfb0b16f 100644 --- a/contrib/tcsh/ed.refresh.c +++ b/contrib/tcsh/ed.refresh.c @@ -1,1356 +1,1356 @@ /* * ed.refresh.c: Lower level screen refreshing functions */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" /* #define DEBUG_UPDATE */ /* #define DEBUG_REFRESH */ /* #define DEBUG_LITERAL */ /* refresh.c -- refresh the current set of lines on the screen */ Char *litptr; static int vcursor_h, vcursor_v; static int rprompt_h, rprompt_v; static int MakeLiteral (Char *, int, Char); static int Draw (Char *, int, int); static void Vdraw (Char, int); static void RefreshPromptpart (Char *); static void update_line (Char *, Char *, int); static void str_insert (Char *, int, int, Char *, int); static void str_delete (Char *, int, int, int); static void str_cp (Char *, Char *, int); #ifndef WINNT_NATIVE static #else extern #endif void PutPlusOne (Char, int); static void cpy_pad_spaces (Char *, Char *, int); #if defined(DEBUG_UPDATE) || defined(DEBUG_REFRESH) || defined(DEBUG_LITERAL) static void reprintf (char *, ...); #ifdef DEBUG_UPDATE static void dprintstr (char *, const Char *, const Char *); static void dprintstr(char *str, const Char *f, const Char *t) { reprintf("%s:\"", str); while (f < t) { if (ASC(*f) & ~ASCII) reprintf("[%x]", *f++); else reprintf("%c", CTL_ESC(ASCII & ASC(*f++))); } reprintf("\"\r\n"); } #endif /* DEBUG_UPDATE */ /* reprintf(): - * Print to $DEBUGTTY, so that we can test editing on one pty, and + * Print to $DEBUGTTY, so that we can test editing on one pty, and * print debugging stuff on another. Don't interrupt the shell while * debugging cause you'll mangle up the file descriptors! */ static void reprintf(char *fmt, ...) { static int fd = -1; char *dtty; if ((dtty = getenv("DEBUGTTY"))) { int o; va_list va; va_start(va, fmt); if (fd == -1) fd = xopen(dtty, O_RDWR); o = SHOUT; flush(); SHOUT = fd; xvprintf(fmt, va); va_end(va); flush(); SHOUT = o; } } #endif /* DEBUG_UPDATE || DEBUG_REFRESH || DEBUG_LITERAL */ static int litlen = 0, litalloc = 0; static int MakeLiteral(Char *str, int len, Char addlit) { int i, addlitlen = 0; Char *addlitptr = 0; if (addlit) { if ((addlit & LITERAL) != 0) { addlitptr = litptr + (addlit & ~LITERAL) * LIT_FACTOR; addlitlen = Strlen(addlitptr); } else { addlitptr = &addlit; addlitlen = 1; } for (i = 0; i < litlen; i += LIT_FACTOR) if (!Strncmp(addlitptr, litptr + i, addlitlen) && !Strncmp(str, litptr + i + addlitlen, len) && litptr[i + addlitlen + len] == 0) return (i / LIT_FACTOR) | LITERAL; } else { addlitlen = 0; for (i = 0; i < litlen; i += LIT_FACTOR) if (!Strncmp(str, litptr + i, len) && litptr[i + len] == 0) return (i / LIT_FACTOR) | LITERAL; } if (litlen + addlitlen + len + 1 + (LIT_FACTOR - 1) > litalloc) { Char *newlitptr; int add = 256; while (len + addlitlen + 1 + (LIT_FACTOR - 1) > add) add *= 2; newlitptr = xrealloc(litptr, (litalloc + add) * sizeof(Char)); if (!newlitptr) return '?'; litptr = newlitptr; litalloc += add; if (addlitptr && addlitptr != &addlit) addlitptr = litptr + (addlit & ~LITERAL) * LIT_FACTOR; } i = litlen / LIT_FACTOR; if (i >= LITERAL || i == CHAR_DBWIDTH) return '?'; if (addlitptr) { Strncpy(litptr + litlen, addlitptr, addlitlen); litlen += addlitlen; } Strncpy(litptr + litlen, str, len); litlen += len; do litptr[litlen++] = 0; while (litlen % LIT_FACTOR); return i | LITERAL; } /* draw char at cp, expand tabs, ctl chars */ static int Draw(Char *cp, int nocomb, int drawPrompt) { int w, i, lv, lh; Char c, attr; #ifdef WIDE_STRINGS if (!drawPrompt) { /* draw command-line */ attr = 0; c = *cp; } else { /* draw prompt */ /* prompt with attributes(UNDER,BOLD,STANDOUT) */ if (*cp & (UNDER | BOLD | STANDOUT)) { /* *cp >= STANDOUT */ /* example) * We can't distinguish whether (*cp=)0x02ffffff is * U+02FFFFFF or U+00FFFFFF|STANDOUT. * We handle as U+00FFFFFF|STANDOUT, only when drawing prompt. */ attr = (*cp & ATTRIBUTES); /* ~(UNDER | BOLD | STANDOUT) = 0xf1ffffff */ c = *cp & ~(UNDER | BOLD | STANDOUT); /* if c is ctrl code, we handle *cp as havnig no attributes */ if ((c < 0x20 && c >= 0) || c == 0x7f) { attr = 0; c = *cp; } } else { /* prompt without attributes */ attr = 0; c = *cp; } } #else attr = *cp & ~CHAR; c = *cp & CHAR; #endif w = NLSClassify(c, nocomb, drawPrompt); switch (w) { case NLSCLASS_NL: Vdraw('\0', 0); /* assure end of line */ vcursor_h = 0; /* reset cursor pos */ vcursor_v++; break; case NLSCLASS_TAB: do { Vdraw(' ', 1); } while ((vcursor_h & 07) != 0); break; case NLSCLASS_CTRL: Vdraw('^' | attr, 1); if (c == CTL_ESC('\177')) { Vdraw('?' | attr, 1); } else { #ifdef IS_ASCII /* uncontrolify it; works only for iso8859-1 like sets */ Vdraw(c | 0100 | attr, 1); #else Vdraw(_toebcdic[_toascii[c]|0100] | attr, 1); #endif } break; case NLSCLASS_ILLEGAL: Vdraw('\\' | attr, 1); Vdraw((((c >> 6) & 7) + '0') | attr, 1); Vdraw((((c >> 3) & 7) + '0') | attr, 1); Vdraw(((c & 7) + '0') | attr, 1); break; case NLSCLASS_ILLEGAL2: case NLSCLASS_ILLEGAL3: case NLSCLASS_ILLEGAL4: case NLSCLASS_ILLEGAL5: Vdraw('\\', 1); Vdraw('U', 1); Vdraw('+', 1); for (i = 16 + 4 * (-w-5); i >= 0; i -= 4) Vdraw("0123456789ABCDEF"[(c >> i) & 15] | attr, 1); break; case 0: lv = vcursor_v; lh = vcursor_h; for (;;) { lh--; if (lh < 0) { lv--; if (lv < 0) break; lh = Strlen(Vdisplay[lv]) - 1; } if (Vdisplay[lv][lh] != CHAR_DBWIDTH) break; } if (lv < 0) { Vdraw('\\' | attr, 1); Vdraw((((c >> 6) & 7) + '0') | attr, 1); Vdraw((((c >> 3) & 7) + '0') | attr, 1); Vdraw(((c & 7) + '0') | attr, 1); break; } Vdisplay[lv][lh] = MakeLiteral(cp, 1, Vdisplay[lv][lh]); break; default: Vdraw(*cp, w); break; } return 1; } static void Vdraw(Char c, int width) /* draw char c onto V lines */ { #ifdef DEBUG_REFRESH # ifdef SHORT_STRINGS reprintf("Vdrawing %6.6o '%c' %d\r\n", (unsigned)c, (int)(c & ASCII), width); # else reprintf("Vdrawing %3.3o '%c' %d\r\n", (unsigned)c, (int)c, width); # endif /* SHORT_STRNGS */ #endif /* DEBUG_REFRESH */ /* Hopefully this is what all the terminals do with multi-column characters that "span line breaks". */ while (vcursor_h + width > TermH) Vdraw(' ', 1); Vdisplay[vcursor_v][vcursor_h] = c; if (width) vcursor_h++; /* advance to next place */ while (--width > 0) Vdisplay[vcursor_v][vcursor_h++] = CHAR_DBWIDTH; if (vcursor_h >= TermH) { Vdisplay[vcursor_v][TermH] = '\0'; /* assure end of line */ vcursor_h = 0; /* reset it. */ vcursor_v++; #ifdef DEBUG_REFRESH if (vcursor_v >= TermV) { /* should NEVER happen. */ reprintf("\r\nVdraw: vcursor_v overflow! Vcursor_v == %d > %d\r\n", vcursor_v, TermV); abort(); } #endif /* DEBUG_REFRESH */ } } /* * RefreshPromptpart() * draws a prompt element, expanding literals (we know it's ASCIZ) */ static void RefreshPromptpart(Char *buf) { Char *cp; int w; if (buf == NULL) return; for (cp = buf; *cp; ) { if (*cp & LITERAL) { Char *litstart = cp; while (*cp & LITERAL) cp++; if (*cp) { w = NLSWidth(*cp & CHAR); Vdraw(MakeLiteral(litstart, cp + 1 - litstart, 0), w); cp++; } else { /* * XXX: This is a bug, we lose the last literal, if it is not * followed by a normal character, but it is too hard to fix */ break; } } else cp += Draw(cp, cp == buf, 1); } } /* * Refresh() * draws the new virtual screen image from the current input * line, then goes line-by-line changing the real image to the new * virtual image. The routine to re-draw a line can be replaced * easily in hopes of a smarter one being placed there. */ #ifndef WINNT_NATIVE static #endif int OldvcV = 0; void Refresh(void) { int cur_line; Char *cp; int cur_h, cur_v = 0, new_vcv; int rhdiff; Char oldgetting; #ifdef DEBUG_REFRESH reprintf("Prompt = :%s:\r\n", short2str(Prompt)); reprintf("InputBuf = :%s:\r\n", short2str(InputBuf)); #endif /* DEBUG_REFRESH */ oldgetting = GettingInput; GettingInput = 0; /* avoid re-entrance via SIGWINCH */ /* reset the Vdraw cursor, temporarily draw rprompt to calculate its size */ vcursor_h = 0; vcursor_v = 0; RefreshPromptpart(RPrompt); rprompt_h = vcursor_h; rprompt_v = vcursor_v; /* reset the Vdraw cursor, draw prompt */ vcursor_h = 0; vcursor_v = 0; RefreshPromptpart(Prompt); cur_h = -1; /* set flag in case I'm not set */ /* draw the current input buffer */ for (cp = InputBuf; (cp < LastChar); ) { if (cp >= Cursor && cur_h == -1) { cur_h = vcursor_h; /* save for later */ cur_v = vcursor_v; Cursor = cp; } cp += Draw(cp, cp == InputBuf, 0); } if (cur_h == -1) { /* if I haven't been set yet, I'm at the end */ cur_h = vcursor_h; cur_v = vcursor_v; } rhdiff = TermH - vcursor_h - rprompt_h; if (rprompt_h != 0 && rprompt_v == 0 && vcursor_v == 0 && rhdiff > 1) { /* * have a right-hand side prompt that will fit on * the end of the first line with at least one * character gap to the input buffer. */ while (--rhdiff > 0) /* pad out with spaces */ Vdraw(' ', 1); RefreshPromptpart(RPrompt); } else { rprompt_h = 0; /* flag "not using rprompt" */ rprompt_v = 0; } new_vcv = vcursor_v; /* must be done BEFORE the NUL is written */ Vdraw('\0', 1); /* put NUL on end */ #if defined (DEBUG_REFRESH) reprintf("TermH=%d, vcur_h=%d, vcur_v=%d, Vdisplay[0]=\r\n:%80.80s:\r\n", TermH, vcursor_h, vcursor_v, short2str(Vdisplay[0])); #endif /* DEBUG_REFRESH */ #ifdef DEBUG_UPDATE reprintf("updating %d lines.\r\n", new_vcv); #endif /* DEBUG_UPDATE */ for (cur_line = 0; cur_line <= new_vcv; cur_line++) { /* NOTE THAT update_line MAY CHANGE Display[cur_line] */ update_line(Display[cur_line], Vdisplay[cur_line], cur_line); #ifdef WINNT_NATIVE flush(); #endif /* WINNT_NATIVE */ /* * Copy the new line to be the current one, and pad out with spaces * to the full width of the terminal so that if we try moving the * cursor by writing the character that is at the end of the * screen line, it won't be a NUL or some old leftover stuff. */ cpy_pad_spaces(Display[cur_line], Vdisplay[cur_line], TermH); } #ifdef DEBUG_REFRESH reprintf("\r\nvcursor_v = %d, OldvcV = %d, cur_line = %d\r\n", vcursor_v, OldvcV, cur_line); #endif /* DEBUG_REFRESH */ if (OldvcV > new_vcv) { for (; cur_line <= OldvcV; cur_line++) { update_line(Display[cur_line], STRNULL, cur_line); *Display[cur_line] = '\0'; } } OldvcV = new_vcv; /* set for next time */ #ifdef DEBUG_REFRESH reprintf("\r\nCursorH = %d, CursorV = %d, cur_h = %d, cur_v = %d\r\n", CursorH, CursorV, cur_h, cur_v); #endif /* DEBUG_REFRESH */ #ifdef WINNT_NATIVE flush(); #endif /* WINNT_NATIVE */ MoveToLine(cur_v); /* go to where the cursor is */ MoveToChar(cur_h); SetAttributes(0); /* Clear all attributes */ flush(); /* send the output... */ GettingInput = oldgetting; /* reset to old value */ } #ifdef notdef GotoBottom(void) { /* used to go to last used screen line */ MoveToLine(OldvcV); } -#endif +#endif void PastBottom(void) { /* used to go to last used screen line */ MoveToLine(OldvcV); (void) putraw('\r'); (void) putraw('\n'); ClearDisp(); flush(); } /* insert num characters of s into d (in front of the character) at dat, maximum length of d is dlen */ static void str_insert(Char *d, int dat, int dlen, Char *s, int num) { Char *a, *b; if (num <= 0) return; if (num > dlen - dat) num = dlen - dat; #ifdef DEBUG_REFRESH reprintf("str_insert() starting: %d at %d max %d, d == \"%s\"\n", num, dat, dlen, short2str(d)); reprintf("s == \"%s\"n", short2str(s)); #endif /* DEBUG_REFRESH */ /* open up the space for num chars */ if (num > 0) { b = d + dlen - 1; a = b - num; while (a >= &d[dat]) *b-- = *a--; d[dlen] = '\0'; /* just in case */ } #ifdef DEBUG_REFRESH reprintf("str_insert() after insert: %d at %d max %d, d == \"%s\"\n", num, dat, dlen, short2str(d)); reprintf("s == \"%s\"n", short2str(s)); #endif /* DEBUG_REFRESH */ /* copy the characters */ for (a = d + dat; (a < d + dlen) && (num > 0); num--) *a++ = *s++; #ifdef DEBUG_REFRESH reprintf("str_insert() after copy: %d at %d max %d, d == \"%s\"\n", num, dat, dlen, d, short2str(s)); reprintf("s == \"%s\"n", short2str(s)); #endif /* DEBUG_REFRESH */ } /* delete num characters d at dat, maximum length of d is dlen */ static void str_delete(Char *d, int dat, int dlen, int num) { Char *a, *b; if (num <= 0) return; if (dat + num >= dlen) { d[dat] = '\0'; return; } #ifdef DEBUG_REFRESH reprintf("str_delete() starting: %d at %d max %d, d == \"%s\"\n", num, dat, dlen, short2str(d)); #endif /* DEBUG_REFRESH */ /* open up the space for num chars */ if (num > 0) { b = d + dat; a = b + num; while (a < &d[dlen]) *b++ = *a++; d[dlen] = '\0'; /* just in case */ } #ifdef DEBUG_REFRESH reprintf("str_delete() after delete: %d at %d max %d, d == \"%s\"\n", num, dat, dlen, short2str(d)); #endif /* DEBUG_REFRESH */ } static void str_cp(Char *a, Char *b, int n) { while (n-- && *b) *a++ = *b++; } /* **************************************************************** update_line() is based on finding the middle difference of each line on the screen; vis: /old first difference /beginning of line | /old last same /old EOL v v v v old: eddie> Oh, my little gruntle-buggy is to me, as lurgid as new: eddie> Oh, my little buggy says to me, as lurgid as ^ ^ ^ ^ \beginning of line | \new last same \new end of line \new first difference all are character pointers for the sake of speed. Special cases for no differences, as well as for end of line additions must be handled. **************************************************************** */ /* Minimum at which doing an insert it "worth it". This should be about * half the "cost" of going into insert mode, inserting a character, and * going back out. This should really be calculated from the termcap * data... For the moment, a good number for ANSI terminals. */ #define MIN_END_KEEP 4 static void /* could be changed to make it smarter */ update_line(Char *old, Char *new, int cur_line) { Char *o, *n, *p, c; Char *ofd, *ols, *oe, *nfd, *nls, *ne; Char *osb, *ose, *nsb, *nse; int fx, sx; /* * find first diff (won't be CHAR_DBWIDTH in either line) */ for (o = old, n = new; *o && (*o == *n); o++, n++) continue; ofd = o; nfd = n; /* * Find the end of both old and new */ o = Strend(o); - /* + /* * Remove any trailing blanks off of the end, being careful not to * back up past the beginning. */ if (!(adrof(STRhighlight) && MarkIsSet)) { while (ofd < o) { if (o[-1] != ' ') break; o--; } } oe = o; *oe = (Char) 0; n = Strend(n); /* remove blanks from end of new */ if (!(adrof(STRhighlight) && MarkIsSet)) { while (nfd < n) { if (n[-1] != ' ') break; n--; } } ne = n; *ne = (Char) 0; - + /* * if no diff, continue to next line of redraw */ if (*ofd == '\0' && *nfd == '\0') { #ifdef DEBUG_UPDATE reprintf("no difference.\r\n"); #endif /* DEBUG_UPDATE */ return; } /* * find last same pointer */ while ((o > ofd) && (n > nfd) && (*--o == *--n)) continue; if (*o != *n) { o++; n++; } while (*o == CHAR_DBWIDTH) { o++; n++; } ols = o; nls = n; /* * find same begining and same end */ osb = ols; nsb = nls; ose = ols; nse = nls; /* * case 1: insert: scan from nfd to nls looking for *ofd */ if (*ofd) { for (c = *ofd, n = nfd; n < nls; n++) { if (c == *n) { for (o = ofd, p = n; p < nls && o < ols && *o == *p; o++, p++) continue; /* * if the new match is longer and it's worth keeping, then we * take it */ if (((nse - nsb) < (p - n)) && (2 * (p - n) > n - nfd)) { nsb = n; nse = p; osb = ofd; ose = o; } } } } /* * case 2: delete: scan from ofd to ols looking for *nfd */ if (*nfd) { for (c = *nfd, o = ofd; o < ols; o++) { if (c == *o) { for (n = nfd, p = o; p < ols && n < nls && *p == *n; p++, n++) continue; /* * if the new match is longer and it's worth keeping, then we * take it */ if (((ose - osb) < (p - o)) && (2 * (p - o) > o - ofd)) { nsb = nfd; nse = n; osb = o; ose = p; } } } } #ifdef notdef /* * If `last same' is before `same end' re-adjust */ if (ols < ose) ols = ose; if (nls < nse) nls = nse; #endif /* * Pragmatics I: If old trailing whitespace or not enough characters to * save to be worth it, then don't save the last same info. */ if ((oe - ols) < MIN_END_KEEP) { ols = oe; nls = ne; } /* * Pragmatics II: if the terminal isn't smart enough, make the data dumber * so the smart update doesn't try anything fancy */ /* * fx is the number of characters we need to insert/delete: in the * beginning to bring the two same begins together */ fx = (int) ((nsb - nfd) - (osb - ofd)); /* * sx is the number of characters we need to insert/delete: in the end to * bring the two same last parts together */ sx = (int) ((nls - nse) - (ols - ose)); if (!T_CanIns) { if (fx > 0) { osb = ols; ose = ols; nsb = nls; nse = nls; } if (sx > 0) { ols = oe; nls = ne; } if ((ols - ofd) < (nls - nfd)) { ols = oe; nls = ne; } } if (!T_CanDel) { if (fx < 0) { osb = ols; ose = ols; nsb = nls; nse = nls; } if (sx < 0) { ols = oe; nls = ne; } if ((ols - ofd) > (nls - nfd)) { ols = oe; nls = ne; } } /* * Pragmatics III: make sure the middle shifted pointers are correct if * they don't point to anything (we may have moved ols or nls). */ /* if the change isn't worth it, don't bother */ /* was: if (osb == ose) */ if ((ose - osb) < MIN_END_KEEP) { osb = ols; ose = ols; nsb = nls; nse = nls; } /* * Now that we are done with pragmatics we recompute fx, sx */ fx = (int) ((nsb - nfd) - (osb - ofd)); sx = (int) ((nls - nse) - (ols - ose)); #ifdef DEBUG_UPDATE reprintf("\n"); reprintf("ofd %d, osb %d, ose %d, ols %d, oe %d\n", ofd - old, osb - old, ose - old, ols - old, oe - old); reprintf("nfd %d, nsb %d, nse %d, nls %d, ne %d\n", nfd - new, nsb - new, nse - new, nls - new, ne - new); reprintf("xxx-xxx:\"00000000001111111111222222222233333333334\"\r\n"); reprintf("xxx-xxx:\"01234567890123456789012345678901234567890\"\r\n"); dprintstr("old- oe", old, oe); dprintstr("new- ne", new, ne); dprintstr("old-ofd", old, ofd); dprintstr("new-nfd", new, nfd); dprintstr("ofd-osb", ofd, osb); dprintstr("nfd-nsb", nfd, nsb); dprintstr("osb-ose", osb, ose); dprintstr("nsb-nse", nsb, nse); dprintstr("ose-ols", ose, ols); dprintstr("nse-nls", nse, nls); dprintstr("ols- oe", ols, oe); dprintstr("nls- ne", nls, ne); #endif /* DEBUG_UPDATE */ /* * CursorV to this line cur_line MUST be in this routine so that if we * don't have to change the line, we don't move to it. CursorH to first * diff char */ MoveToLine(cur_line); /* * at this point we have something like this: - * + * * /old /ofd /osb /ose /ols /oe * v.....................v v..................v v........v * eddie> Oh, my fredded gruntle-buggy is to me, as foo var lurgid as * eddie> Oh, my fredded quiux buggy is to me, as gruntle-lurgid as - * ^.....................^ ^..................^ ^........^ + * ^.....................^ ^..................^ ^........^ * \new \nfd \nsb \nse \nls \ne - * + * * fx is the difference in length between the the chars between nfd and * nsb, and the chars between ofd and osb, and is thus the number of * characters to delete if < 0 (new is shorter than old, as above), * or insert (new is longer than short). * * sx is the same for the second differences. */ /* * if we have a net insert on the first difference, AND inserting the net * amount ((nsb-nfd) - (osb-ofd)) won't push the last useful character * (which is ne if nls != ne, otherwise is nse) off the edge of the screen * (TermH - 1) else we do the deletes first so that we keep everything we * need to. */ /* * if the last same is the same like the end, there is no last same part, * otherwise we want to keep the last same part set p to the last useful * old character */ p = (ols != oe) ? oe : ose; /* * if (There is a diffence in the beginning) && (we need to insert * characters) && (the number of characters to insert is less than the term * width) We need to do an insert! else if (we need to delete characters) * We need to delete characters! else No insert or delete */ if ((nsb != nfd) && fx > 0 && ((p - old) + fx < TermH)) { #ifdef DEBUG_UPDATE reprintf("first diff insert at %d...\r\n", nfd - new); #endif /* DEBUG_UPDATE */ /* * Move to the first char to insert, where the first diff is. */ MoveToChar(nfd - new); /* * Check if we have stuff to keep at end */ if (nsb != ne) { #ifdef DEBUG_UPDATE reprintf("with stuff to keep at end\r\n"); #endif /* DEBUG_UPDATE */ /* * insert fx chars of new starting at nfd */ if (fx > 0) { #ifdef DEBUG_UPDATE if (!T_CanIns) reprintf(" ERROR: cannot insert in early first diff\n"); #endif /* DEBUG_UPDATE */ Insert_write(nfd, fx); str_insert(old, (int) (ofd - old), TermH, nfd, fx); } /* * write (nsb-nfd) - fx chars of new starting at (nfd + fx) */ so_write(nfd + fx, (nsb - nfd) - fx); str_cp(ofd + fx, nfd + fx, (int) ((nsb - nfd) - fx)); } else { #ifdef DEBUG_UPDATE reprintf("without anything to save\r\n"); #endif /* DEBUG_UPDATE */ so_write(nfd, (nsb - nfd)); str_cp(ofd, nfd, (int) (nsb - nfd)); /* * Done */ return; } } else if (fx < 0) { #ifdef DEBUG_UPDATE reprintf("first diff delete at %d...\r\n", ofd - old); #endif /* DEBUG_UPDATE */ /* * move to the first char to delete where the first diff is */ MoveToChar(ofd - old); /* * Check if we have stuff to save */ if (osb != oe) { #ifdef DEBUG_UPDATE reprintf("with stuff to save at end\r\n"); #endif /* DEBUG_UPDATE */ /* * fx is less than zero *always* here but we check for code * symmetry */ if (fx < 0) { #ifdef DEBUG_UPDATE if (!T_CanDel) reprintf(" ERROR: cannot delete in first diff\n"); #endif /* DEBUG_UPDATE */ DeleteChars(-fx); str_delete(old, (int) (ofd - old), TermH, -fx); } /* * write (nsb-nfd) chars of new starting at nfd */ so_write(nfd, (nsb - nfd)); str_cp(ofd, nfd, (int) (nsb - nfd)); } else { #ifdef DEBUG_UPDATE reprintf("but with nothing left to save\r\n"); #endif /* DEBUG_UPDATE */ /* * write (nsb-nfd) chars of new starting at nfd */ so_write(nfd, (nsb - nfd)); #ifdef DEBUG_REFRESH reprintf("cleareol %d\n", (oe - old) - (ne - new)); #endif /* DEBUG_UPDATE */ #ifndef WINNT_NATIVE ClearEOL((oe - old) - (ne - new)); #else /* * The calculation above does not work too well on NT */ ClearEOL(TermH - CursorH); #endif /*WINNT_NATIVE*/ /* * Done */ return; } } else fx = 0; if (sx < 0) { #ifdef DEBUG_UPDATE reprintf("second diff delete at %d...\r\n", (ose - old) + fx); #endif /* DEBUG_UPDATE */ /* * Check if we have stuff to delete */ /* * fx is the number of characters inserted (+) or deleted (-) */ MoveToChar((ose - old) + fx); /* * Check if we have stuff to save */ if (ols != oe) { #ifdef DEBUG_UPDATE reprintf("with stuff to save at end\r\n"); #endif /* DEBUG_UPDATE */ /* * Again a duplicate test. */ if (sx < 0) { #ifdef DEBUG_UPDATE if (!T_CanDel) reprintf(" ERROR: cannot delete in second diff\n"); #endif /* DEBUG_UPDATE */ DeleteChars(-sx); } /* * write (nls-nse) chars of new starting at nse */ so_write(nse, (nls - nse)); } else { int olen = (int) (oe - old + fx); if (olen > TermH) olen = TermH; #ifdef DEBUG_UPDATE reprintf("but with nothing left to save\r\n"); #endif /* DEBUG_UPDATE */ so_write(nse, (nls - nse)); #ifdef DEBUG_REFRESH reprintf("cleareol %d\n", olen - (ne - new)); #endif /* DEBUG_UPDATE */ #ifndef WINNT_NATIVE ClearEOL(olen - (ne - new)); #else /* * The calculation above does not work too well on NT */ ClearEOL(TermH - CursorH); #endif /*WINNT_NATIVE*/ } } /* * if we have a first insert AND WE HAVEN'T ALREADY DONE IT... */ if ((nsb != nfd) && (osb - ofd) <= (nsb - nfd) && (fx == 0)) { #ifdef DEBUG_UPDATE reprintf("late first diff insert at %d...\r\n", nfd - new); #endif /* DEBUG_UPDATE */ MoveToChar(nfd - new); /* * Check if we have stuff to keep at the end */ if (nsb != ne) { #ifdef DEBUG_UPDATE reprintf("with stuff to keep at end\r\n"); #endif /* DEBUG_UPDATE */ - /* + /* * We have to recalculate fx here because we set it * to zero above as a flag saying that we hadn't done * an early first insert. */ fx = (int) ((nsb - nfd) - (osb - ofd)); if (fx > 0) { /* * insert fx chars of new starting at nfd */ #ifdef DEBUG_UPDATE if (!T_CanIns) reprintf(" ERROR: cannot insert in late first diff\n"); #endif /* DEBUG_UPDATE */ Insert_write(nfd, fx); str_insert(old, (int) (ofd - old), TermH, nfd, fx); } /* * write (nsb-nfd) - fx chars of new starting at (nfd + fx) */ so_write(nfd + fx, (nsb - nfd) - fx); str_cp(ofd + fx, nfd + fx, (int) ((nsb - nfd) - fx)); } else { #ifdef DEBUG_UPDATE reprintf("without anything to save\r\n"); #endif /* DEBUG_UPDATE */ so_write(nfd, (nsb - nfd)); str_cp(ofd, nfd, (int) (nsb - nfd)); } } /* * line is now NEW up to nse */ if (sx >= 0) { #ifdef DEBUG_UPDATE reprintf("second diff insert at %d...\r\n", nse - new); #endif /* DEBUG_UPDATE */ MoveToChar(nse - new); if (ols != oe) { #ifdef DEBUG_UPDATE reprintf("with stuff to keep at end\r\n"); #endif /* DEBUG_UPDATE */ if (sx > 0) { /* insert sx chars of new starting at nse */ #ifdef DEBUG_UPDATE if (!T_CanIns) reprintf(" ERROR: cannot insert in second diff\n"); #endif /* DEBUG_UPDATE */ Insert_write(nse, sx); } /* * write (nls-nse) - sx chars of new starting at (nse + sx) */ so_write(nse + sx, (nls - nse) - sx); } else { #ifdef DEBUG_UPDATE reprintf("without anything to save\r\n"); #endif /* DEBUG_UPDATE */ so_write(nse, (nls - nse)); /* * No need to do a clear-to-end here because we were doing * a second insert, so we will have over written all of the * old string. */ } } #ifdef DEBUG_UPDATE reprintf("done.\r\n"); #endif /* DEBUG_UPDATE */ } static void cpy_pad_spaces(Char *dst, Char *src, int width) { int i; for (i = 0; i < width; i++) { if (*src == (Char) 0) break; *dst++ = *src++; } while (i < width) { *dst++ = ' '; i++; } *dst = (Char) 0; } void RefCursor(void) { /* only move to new cursor pos */ Char *cp; int w, h, th, v; /* first we must find where the cursor is... */ h = 0; v = 0; th = TermH; /* optimize for speed */ for (cp = Prompt; cp != NULL && *cp; ) { /* do prompt */ if (*cp & LITERAL) { cp++; continue; } w = NLSClassify(*cp & CHAR, cp == Prompt, 0); cp++; switch(w) { case NLSCLASS_NL: h = 0; v++; break; case NLSCLASS_TAB: while (++h & 07) ; break; case NLSCLASS_CTRL: h += 2; break; case NLSCLASS_ILLEGAL: h += 4; break; case NLSCLASS_ILLEGAL2: case NLSCLASS_ILLEGAL3: case NLSCLASS_ILLEGAL4: h += 3 + 2 * NLSCLASS_ILLEGAL_SIZE(w); break; default: h += w; } if (h >= th) { /* check, extra long tabs picked up here also */ h -= th; v++; } } for (cp = InputBuf; cp < Cursor;) { /* do input buffer to Cursor */ w = NLSClassify(*cp & CHAR, cp == InputBuf, 0); cp++; switch(w) { case NLSCLASS_NL: h = 0; v++; break; case NLSCLASS_TAB: while (++h & 07) ; break; case NLSCLASS_CTRL: h += 2; break; case NLSCLASS_ILLEGAL: h += 4; break; case NLSCLASS_ILLEGAL2: case NLSCLASS_ILLEGAL3: case NLSCLASS_ILLEGAL4: h += 3 + 2 * NLSCLASS_ILLEGAL_SIZE(w); break; default: h += w; } if (h >= th) { /* check, extra long tabs picked up here also */ h -= th; v++; } } /* now go there */ MoveToLine(v); MoveToChar(h); if (adrof(STRhighlight) && MarkIsSet) { ClearLines(); ClearDisp(); Refresh(); } flush(); } #ifndef WINTT_NATIVE static void PutPlusOne(Char c, int width) { while (width > 1 && CursorH + width > TermH) PutPlusOne(' ', 1); if ((c & LITERAL) != 0) { Char *d; for (d = litptr + (c & ~LITERAL) * LIT_FACTOR; *d; d++) (void) putwraw(*d); } else { (void) putwraw(c); } Display[CursorV][CursorH++] = (Char) c; while (--width > 0) Display[CursorV][CursorH++] = CHAR_DBWIDTH; if (CursorH >= TermH) { /* if we must overflow */ CursorH = 0; CursorV++; OldvcV++; if (T_Margin & MARGIN_AUTO) { if (T_Margin & MARGIN_MAGIC) { (void) putraw(' '); (void) putraw('\b'); } } else { (void) putraw('\r'); (void) putraw('\n'); } } } #endif void RefPlusOne(int l) { /* we added just one char, handle it fast. * assumes that screen cursor == real cursor */ Char *cp, c; int w; if (Cursor != LastChar) { Refresh(); /* too hard to handle */ return; } if (rprompt_h != 0 && (TermH - CursorH - rprompt_h < 3)) { Refresh(); /* clear out rprompt if less than one char gap*/ return; } cp = Cursor - l; c = *cp & CHAR; w = NLSClassify(c, cp == InputBuf, 0); switch(w) { case NLSCLASS_CTRL: PutPlusOne('^', 1); if (c == CTL_ESC('\177')) { PutPlusOne('?', 1); break; } #ifdef IS_ASCII /* uncontrolify it; works only for iso8859-1 like sets */ PutPlusOne((c | 0100), 1); #else PutPlusOne(_toebcdic[_toascii[c]|0100], 1); #endif break; case NLSCLASS_ILLEGAL: PutPlusOne('\\', 1); PutPlusOne(((c >> 6) & 7) + '0', 1); PutPlusOne(((c >> 3) & 7) + '0', 1); PutPlusOne((c & 7) + '0', 1); break; case 1: if (adrof(STRhighlight) && MarkIsSet) StartHighlight(); if (l > 1) PutPlusOne(MakeLiteral(cp, l, 0), 1); else PutPlusOne(*cp, 1); if (adrof(STRhighlight) && MarkIsSet) StopHighlight(); break; default: Refresh(); /* too hard to handle */ return; } flush(); } /* clear the screen buffers so that new new prompt starts fresh. */ void ClearDisp(void) { int i; CursorV = 0; /* clear the display buffer */ CursorH = 0; for (i = 0; i < TermV; i++) (void) memset(Display[i], 0, (TermH + 1) * sizeof(Display[0][0])); OldvcV = 0; litlen = 0; } void ClearLines(void) { /* Make sure all lines are *really* blank */ int i; if (T_CanCEOL) { /* * Clear the lines from the bottom up so that if we try moving * the cursor down by writing the character that is at the end * of the screen line, we won't rewrite a character that shouldn't * be there. */ for (i = OldvcV; i >= 0; i--) { /* for each line on the screen */ MoveToLine(i); MoveToChar(0); ClearEOL(TermH); } } else { MoveToLine(OldvcV); /* go to last line */ (void) putraw('\r'); /* go to BOL */ (void) putraw('\n'); /* go to new line */ } } diff --git a/contrib/tcsh/ed.screen.c b/contrib/tcsh/ed.screen.c index e8b351fe800d..4c5339b2c307 100644 --- a/contrib/tcsh/ed.screen.c +++ b/contrib/tcsh/ed.screen.c @@ -1,1649 +1,1649 @@ /* * ed.screen.c: Editor/termcap-curses interface */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include "tc.h" #include "ed.defns.h" /* #define DEBUG_LITERAL */ /* * IMPORTANT NOTE: these routines are allowed to look at the current screen * and the current possition assuming that it is correct. If this is not * true, then the update will be WRONG! This is (should be) a valid * assumption... */ #define TC_BUFSIZE 2048 #define GoodStr(a) (tstr[a].str != NULL && tstr[a].str[0] != '\0') #define Str(a) tstr[a].str #define Val(a) tval[a].val static const struct { const char *b_name; speed_t b_rate; } baud_rate[] = { #ifdef B0 { "0", B0 }, #endif #ifdef B50 { "50", B50 }, #endif #ifdef B75 { "75", B75 }, #endif #ifdef B110 { "110", B110 }, #endif #ifdef B134 { "134", B134 }, #endif #ifdef B150 { "150", B150 }, #endif #ifdef B200 { "200", B200 }, #endif #ifdef B300 { "300", B300 }, #endif #ifdef B600 { "600", B600 }, #endif #ifdef B900 { "900", B900 }, #endif #ifdef B1200 { "1200", B1200 }, #endif #ifdef B1800 { "1800", B1800 }, #endif #ifdef B2400 { "2400", B2400 }, #endif #ifdef B3600 { "3600", B3600 }, #endif #ifdef B4800 { "4800", B4800 }, #endif #ifdef B7200 { "7200", B7200 }, #endif #ifdef B9600 { "9600", B9600 }, #endif #ifdef EXTA { "19200", EXTA }, #endif #ifdef B19200 { "19200", B19200 }, #endif #ifdef EXTB { "38400", EXTB }, #endif #ifdef B38400 { "38400", B38400 }, #endif { NULL, 0 } }; #define T_at7 0 #define T_al 1 #define T_bl 2 #define T_cd 3 #define T_ce 4 #define T_ch 5 #define T_cl 6 #define T_dc 7 #define T_dl 8 #define T_dm 9 #define T_ed 10 #define T_ei 11 #define T_fs 12 #define T_ho 13 #define T_ic 14 -#define T_im 15 +#define T_im 15 #define T_ip 16 #define T_kd 17 #define T_kh 18 #define T_kl 19 #define T_kr 20 #define T_ku 21 #define T_md 22 #define T_me 23 #define T_mr 24 #define T_nd 25 #define T_se 26 #define T_so 27 #define T_ts 28 #define T_up 29 #define T_us 30 #define T_ue 31 #define T_vb 32 #define T_DC 33 #define T_DO 34 #define T_IC 35 #define T_LE 36 #define T_RI 37 #define T_UP 38 #define T_str 39 static struct termcapstr { const char *name; const char *long_name; char *str; } tstr[T_str + 1]; #define T_am 0 #define T_pt 1 #define T_li 2 #define T_co 3 #define T_km 4 #define T_xn 5 #define T_val 6 static struct termcapval { const char *name; const char *long_name; int val; } tval[T_val + 1]; void terminit(void) { #ifdef NLS_CATALOGS int i; for (i = 0; i < T_str + 1; i++) xfree((ptr_t)(intptr_t)tstr[i].long_name); for (i = 0; i < T_val + 1; i++) xfree((ptr_t)(intptr_t)tval[i].long_name); #endif tstr[T_al].name = "al"; tstr[T_al].long_name = CSAVS(4, 1, "add new blank line"); tstr[T_bl].name = "bl"; tstr[T_bl].long_name = CSAVS(4, 2, "audible bell"); tstr[T_cd].name = "cd"; tstr[T_cd].long_name = CSAVS(4, 3, "clear to bottom"); tstr[T_ce].name = "ce"; tstr[T_ce].long_name = CSAVS(4, 4, "clear to end of line"); tstr[T_ch].name = "ch"; tstr[T_ch].long_name = CSAVS(4, 5, "cursor to horiz pos"); tstr[T_cl].name = "cl"; tstr[T_cl].long_name = CSAVS(4, 6, "clear screen"); tstr[T_dc].name = "dc"; tstr[T_dc].long_name = CSAVS(4, 7, "delete a character"); tstr[T_dl].name = "dl"; tstr[T_dl].long_name = CSAVS(4, 8, "delete a line"); tstr[T_dm].name = "dm"; tstr[T_dm].long_name = CSAVS(4, 9, "start delete mode"); tstr[T_ed].name = "ed"; tstr[T_ed].long_name = CSAVS(4, 10, "end delete mode"); tstr[T_ei].name = "ei"; tstr[T_ei].long_name = CSAVS(4, 11, "end insert mode"); tstr[T_fs].name = "fs"; tstr[T_fs].long_name = CSAVS(4, 12, "cursor from status line"); tstr[T_ho].name = "ho"; tstr[T_ho].long_name = CSAVS(4, 13, "home cursor"); tstr[T_ic].name = "ic"; tstr[T_ic].long_name = CSAVS(4, 14, "insert character"); tstr[T_im].name = "im"; tstr[T_im].long_name = CSAVS(4, 15, "start insert mode"); tstr[T_ip].name = "ip"; tstr[T_ip].long_name = CSAVS(4, 16, "insert padding"); tstr[T_kd].name = "kd"; tstr[T_kd].long_name = CSAVS(4, 17, "sends cursor down"); tstr[T_kl].name = "kl"; tstr[T_kl].long_name = CSAVS(4, 18, "sends cursor left"); tstr[T_kr].name = "kr"; tstr[T_kr].long_name = CSAVS(4, 19, "sends cursor right"); tstr[T_ku].name = "ku"; tstr[T_ku].long_name = CSAVS(4, 20, "sends cursor up"); tstr[T_md].name = "md"; tstr[T_md].long_name = CSAVS(4, 21, "begin bold"); tstr[T_me].name = "me"; tstr[T_me].long_name = CSAVS(4, 22, "end attributes"); tstr[T_nd].name = "nd"; tstr[T_nd].long_name = CSAVS(4, 23, "non destructive space"); tstr[T_se].name = "se"; tstr[T_se].long_name = CSAVS(4, 24, "end standout"); tstr[T_so].name = "so"; tstr[T_so].long_name = CSAVS(4, 25, "begin standout"); tstr[T_ts].name = "ts"; tstr[T_ts].long_name = CSAVS(4, 26, "cursor to status line"); tstr[T_up].name = "up"; tstr[T_up].long_name = CSAVS(4, 27, "cursor up one"); tstr[T_us].name = "us"; tstr[T_us].long_name = CSAVS(4, 28, "begin underline"); tstr[T_ue].name = "ue"; tstr[T_ue].long_name = CSAVS(4, 29, "end underline"); tstr[T_vb].name = "vb"; tstr[T_vb].long_name = CSAVS(4, 30, "visible bell"); tstr[T_DC].name = "DC"; tstr[T_DC].long_name = CSAVS(4, 31, "delete multiple chars"); tstr[T_DO].name = "DO"; tstr[T_DO].long_name = CSAVS(4, 32, "cursor down multiple"); tstr[T_IC].name = "IC"; tstr[T_IC].long_name = CSAVS(4, 33, "insert multiple chars"); tstr[T_LE].name = "LE"; tstr[T_LE].long_name = CSAVS(4, 34, "cursor left multiple"); tstr[T_RI].name = "RI"; tstr[T_RI].long_name = CSAVS(4, 35, "cursor right multiple"); tstr[T_UP].name = "UP"; tstr[T_UP].long_name = CSAVS(4, 36, "cursor up multiple"); tstr[T_kh].name = "kh"; tstr[T_kh].long_name = CSAVS(4, 43, "send cursor home"); tstr[T_at7].name = "@7"; tstr[T_at7].long_name = CSAVS(4, 44, "send cursor end"); tstr[T_mr].name = "mr"; tstr[T_mr].long_name = CSAVS(4, 45, "begin reverse video"); tstr[T_str].name = NULL; tstr[T_str].long_name = NULL; tval[T_am].name = "am"; tval[T_am].long_name = CSAVS(4, 37, "Has automatic margins"); tval[T_pt].name = "pt"; tval[T_pt].long_name = CSAVS(4, 38, "Can use physical tabs"); tval[T_li].name = "li"; tval[T_li].long_name = CSAVS(4, 39, "Number of lines"); tval[T_co].name = "co"; tval[T_co].long_name = CSAVS(4, 40, "Number of columns"); tval[T_km].name = "km"; tval[T_km].long_name = CSAVS(4, 41, "Has meta key"); tval[T_xn].name = "xn"; tval[T_xn].long_name = CSAVS(4, 42, "Newline ignored at right margin"); tval[T_val].name = NULL; tval[T_val].long_name = NULL; } /* * A very useful table from justin@crim.ca (Justin Bur) :-) * (Modified by per@erix.ericsson.se (Per Hedeland) * - first (and second:-) case fixed) * * Description Termcap variables tcsh behavior * am xn UseRightmost SendCRLF * -------------- ------- ------- ------------ ------------ * Automargins yes no yes no * Magic Margins yes yes yes no * No Wrap no -- yes yes */ static int me_all = 0; /* does two or more of the attributes use me */ static void ReBufferDisplay (void); static void TCset (struct termcapstr *, const char *); static void TCset(struct termcapstr *t, const char *cap) { if (cap == NULL || *cap == '\0') { xfree(t->str); t->str = NULL; } else { size_t size; size = strlen(cap) + 1; t->str = xrealloc(t->str, size); memcpy(t->str, cap, size); } } /*ARGSUSED*/ void TellTC(void) { struct termcapstr *t; char *first, *s; xprintf("%s", CGETS(7, 1, "\n\tTcsh thinks your terminal has the\n")); xprintf("%s", CGETS(7, 2, "\tfollowing characteristics:\n\n")); xprintf(CGETS(7, 3, "\tIt has %d columns and %d lines\n"), Val(T_co), Val(T_li)); s = strsave(T_HasMeta ? CGETS(7, 5, "a") : CGETS(7, 6, "no")); cleanup_push(s, xfree); first = s; xprintf(CGETS(7, 4, "\tIt has %s meta key\n"), s); s = strsave(T_Tabs ? "" : CGETS(7, 8, " not")); cleanup_push(s, xfree); xprintf(CGETS(7, 7, "\tIt can%s use tabs\n"), s); s = strsave((T_Margin&MARGIN_AUTO) ? CGETS(7, 10, "has") : CGETS(7, 11, "does not have")); cleanup_push(s, xfree); xprintf(CGETS(7, 9, "\tIt %s automatic margins\n"), s); if (T_Margin & MARGIN_AUTO) { s = strsave((T_Margin & MARGIN_MAGIC) ? CGETS(7, 10, "has") : CGETS(7, 11, "does not have")); cleanup_push(s, xfree); xprintf(CGETS(7, 12, "\tIt %s magic margins\n"), s); } for (t = tstr; t->name != NULL; t++) { s = strsave(t->str && *t->str ? t->str : CGETS(7, 13, "(empty)")); cleanup_push(s, xfree); xprintf("\t%36s (%s) == %s\n", t->long_name, t->name, s); cleanup_until(s); } xputchar('\n'); cleanup_until(first); } static void ReBufferDisplay(void) { int i; Char **b; b = Display; Display = NULL; blkfree(b); b = Vdisplay; Vdisplay = NULL; blkfree(b); TermH = Val(T_co); TermV = (INBUFSIZE * 4) / TermH + 1;/*FIXBUF*/ b = xmalloc(sizeof(*b) * (TermV + 1)); for (i = 0; i < TermV; i++) b[i] = xmalloc(sizeof(*b[i]) * (TermH + 1)); b[TermV] = NULL; Display = b; b = xmalloc(sizeof(*b) * (TermV + 1)); for (i = 0; i < TermV; i++) b[i] = xmalloc(sizeof(*b[i]) * (TermH + 1)); b[TermV] = NULL; Vdisplay = b; } void SetTC(char *what, char *how) { struct termcapstr *ts; struct termcapval *tv; /* * Do the strings first */ setname("settc"); for (ts = tstr; ts->name != NULL; ts++) if (strcmp(ts->name, what) == 0) break; if (ts->name != NULL) { TCset(ts, how); /* * Reset variables */ if (GoodStr(T_me) && GoodStr(T_ue)) me_all = (strcmp(Str(T_me), Str(T_ue)) == 0); else me_all = 0; if (GoodStr(T_me) && GoodStr(T_se)) me_all |= (strcmp(Str(T_me), Str(T_se)) == 0); T_CanCEOL = GoodStr(T_ce); T_CanDel = GoodStr(T_dc) || GoodStr(T_DC); T_CanIns = GoodStr(T_im) || GoodStr(T_ic) || GoodStr(T_IC); T_CanUP = GoodStr(T_up) || GoodStr(T_UP); return; } /* * Do the numeric ones second */ for (tv = tval; tv->name != NULL; tv++) if (strcmp(tv->name, what) == 0) break; if (tv->name != NULL) { - if (tv == &tval[T_pt] || tv == &tval[T_km] || + if (tv == &tval[T_pt] || tv == &tval[T_km] || tv == &tval[T_am] || tv == &tval[T_xn]) { if (strcmp(how, "yes") == 0) tv->val = 1; else if (strcmp(how, "no") == 0) tv->val = 0; else { stderror(ERR_SETTCUS, tv->name); return; } T_Tabs = Val(T_pt); T_HasMeta = Val(T_km); T_Margin = Val(T_am) ? MARGIN_AUTO : 0; T_Margin |= Val(T_xn) ? MARGIN_MAGIC : 0; - if (tv == &tval[T_am] || tv == &tval[T_xn]) + if (tv == &tval[T_am] || tv == &tval[T_xn]) ChangeSize(Val(T_li), Val(T_co)); return; } else { tv->val = atoi(how); T_Cols = (Char) Val(T_co); T_Lines = (Char) Val(T_li); if (tv == &tval[T_co] || tv == &tval[T_li]) ChangeSize(Val(T_li), Val(T_co)); return; } } stderror(ERR_NAME | ERR_TCCAP, what); return; } /* * Print the termcap string out with variable substitution */ void EchoTC(Char **v) { char *cap, *scap, *cv; int arg_need, arg_cols, arg_rows; int verbose = 0, silent = 0; char *area; static const char fmts[] = "%s\n", fmtd[] = "%d\n"; struct termcapstr *t; char buf[TC_BUFSIZE]; Char **globbed; area = buf; setname("echotc"); v = glob_all_or_error(v); globbed = v; cleanup_push(globbed, blk_cleanup); if (!*v || *v[0] == '\0') goto end; if (v[0][0] == '-') { switch (v[0][1]) { case 'v': verbose = 1; break; case 's': silent = 1; break; default: stderror(ERR_NAME | ERR_TCUSAGE); break; } v++; } if (!*v || *v[0] == '\0') goto end; cv = strsave(short2str(*v)); cleanup_push(cv, xfree); if (strcmp(cv, "tabs") == 0) { xprintf(fmts, T_Tabs ? CGETS(7, 14, "yes") : CGETS(7, 15, "no")); goto end_flush; } else if (strcmp(cv, "meta") == 0) { xprintf(fmts, Val(T_km) ? CGETS(7, 14, "yes") : CGETS(7, 15, "no")); goto end_flush; } else if (strcmp(cv, "xn") == 0) { xprintf(fmts, T_Margin & MARGIN_MAGIC ? CGETS(7, 14, "yes") : CGETS(7, 15, "no")); goto end_flush; } else if (strcmp(cv, "am") == 0) { xprintf(fmts, T_Margin & MARGIN_AUTO ? CGETS(7, 14, "yes") : CGETS(7, 15, "no")); goto end_flush; } else if (strcmp(cv, "baud") == 0) { int i; for (i = 0; baud_rate[i].b_name != NULL; i++) if (T_Speed == baud_rate[i].b_rate) { xprintf(fmts, baud_rate[i].b_name); goto end_flush; } xprintf(fmtd, 0); goto end_flush; } else if (strcmp(cv, "rows") == 0 || strcmp(cv, "lines") == 0 || strcmp(cv, "li") == 0) { xprintf(fmtd, Val(T_li)); goto end_flush; } else if (strcmp(cv, "cols") == 0 || strcmp(cv, "co") == 0) { xprintf(fmtd, Val(T_co)); goto end_flush; } - /* + /* * Try to use our local definition first */ scap = NULL; for (t = tstr; t->name != NULL; t++) if (strcmp(t->name, cv) == 0) { scap = t->str; break; } if (t->name == NULL) scap = tgetstr(cv, &area); if (!scap || scap[0] == '\0') { if (tgetflag(cv)) { xprintf("%s", CGETS(7, 14, "yes\n")); goto end; } if (silent) goto end; else stderror(ERR_NAME | ERR_TCCAP, cv); } /* * Count home many values we need for this capability. */ for (cap = scap, arg_need = 0; *cap; cap++) if (*cap == '%') switch (*++cap) { case 'd': case '2': case '3': case '.': case '+': arg_need++; break; case '%': case '>': case 'i': case 'r': case 'n': case 'B': case 'D': break; default: /* * hpux has lot's of them... */ if (verbose) stderror(ERR_NAME | ERR_TCPARM, *cap); /* This is bad, but I won't complain */ break; } switch (arg_need) { case 0: v++; if (*v && *v[0]) { if (silent) goto end; else stderror(ERR_NAME | ERR_TCARGS, cv, arg_need); } (void) tputs(scap, 1, PUTRAW); break; case 1: v++; if (!*v || *v[0] == '\0') stderror(ERR_NAME | ERR_TCNARGS, cv, 1); arg_cols = 0; arg_rows = atoi(short2str(*v)); v++; if (*v && *v[0]) { if (silent) goto end; else stderror(ERR_NAME | ERR_TCARGS, cv, arg_need); } (void) tputs(tgoto(scap, arg_cols, arg_rows), 1, PUTRAW); break; default: /* This is wrong, but I will ignore it... */ if (verbose) stderror(ERR_NAME | ERR_TCARGS, cv, arg_need); /*FALLTHROUGH*/ case 2: v++; if (!*v || *v[0] == '\0') { if (silent) goto end; else stderror(ERR_NAME | ERR_TCNARGS, cv, 2); } arg_cols = atoi(short2str(*v)); v++; if (!*v || *v[0] == '\0') { if (silent) goto end; else stderror(ERR_NAME | ERR_TCNARGS, cv, 2); } arg_rows = atoi(short2str(*v)); v++; if (*v && *v[0]) { if (silent) goto end; else stderror(ERR_NAME | ERR_TCARGS, cv, arg_need); } (void) tputs(tgoto(scap, arg_cols, arg_rows), arg_rows, PUTRAW); break; } end_flush: flush(); end: cleanup_until(globbed); } int GotTermCaps = 0; static struct { Char *name; int key; XmapVal fun; int type; } arrow[] = { #define A_K_DN 0 { STRdown, T_kd, { 0 }, 0 }, #define A_K_UP 1 { STRup, T_ku, { 0 }, 0 }, #define A_K_LT 2 { STRleft, T_kl, { 0 }, 0 }, #define A_K_RT 3 { STRright, T_kr, { 0 }, 0 }, #define A_K_HO 4 { STRhome, T_kh, { 0 }, 0 }, #define A_K_EN 5 { STRend, T_at7, { 0 }, 0} }; #define A_K_NKEYS 6 void ResetArrowKeys(void) { arrow[A_K_DN].fun.cmd = F_DOWN_HIST; arrow[A_K_DN].type = XK_CMD; arrow[A_K_UP].fun.cmd = F_UP_HIST; arrow[A_K_UP].type = XK_CMD; arrow[A_K_LT].fun.cmd = F_CHARBACK; arrow[A_K_LT].type = XK_CMD; arrow[A_K_RT].fun.cmd = F_CHARFWD; arrow[A_K_RT].type = XK_CMD; arrow[A_K_HO].fun.cmd = F_TOBEG; arrow[A_K_HO].type = XK_CMD; arrow[A_K_EN].fun.cmd = F_TOEND; arrow[A_K_EN].type = XK_CMD; } void DefaultArrowKeys(void) { static Char strA[] = {033, '[', 'A', '\0'}; static Char strB[] = {033, '[', 'B', '\0'}; static Char strC[] = {033, '[', 'C', '\0'}; static Char strD[] = {033, '[', 'D', '\0'}; static Char strH[] = {033, '[', 'H', '\0'}; static Char strF[] = {033, '[', 'F', '\0'}; static Char stOA[] = {033, 'O', 'A', '\0'}; static Char stOB[] = {033, 'O', 'B', '\0'}; static Char stOC[] = {033, 'O', 'C', '\0'}; static Char stOD[] = {033, 'O', 'D', '\0'}; static Char stOH[] = {033, 'O', 'H', '\0'}; static Char stOF[] = {033, 'O', 'F', '\0'}; CStr cs; #ifndef IS_ASCII if (strA[0] == 033) { strA[0] = CTL_ESC('\033'); strB[0] = CTL_ESC('\033'); strC[0] = CTL_ESC('\033'); strD[0] = CTL_ESC('\033'); strH[0] = CTL_ESC('\033'); strF[0] = CTL_ESC('\033'); stOA[0] = CTL_ESC('\033'); stOB[0] = CTL_ESC('\033'); stOC[0] = CTL_ESC('\033'); stOD[0] = CTL_ESC('\033'); stOH[0] = CTL_ESC('\033'); stOF[0] = CTL_ESC('\033'); } #endif cs.len = 3; cs.buf = strA; AddXkey(&cs, &arrow[A_K_UP].fun, arrow[A_K_UP].type); cs.buf = strB; AddXkey(&cs, &arrow[A_K_DN].fun, arrow[A_K_DN].type); cs.buf = strC; AddXkey(&cs, &arrow[A_K_RT].fun, arrow[A_K_RT].type); cs.buf = strD; AddXkey(&cs, &arrow[A_K_LT].fun, arrow[A_K_LT].type); cs.buf = strH; AddXkey(&cs, &arrow[A_K_HO].fun, arrow[A_K_HO].type); cs.buf = strF; AddXkey(&cs, &arrow[A_K_EN].fun, arrow[A_K_EN].type); cs.buf = stOA; AddXkey(&cs, &arrow[A_K_UP].fun, arrow[A_K_UP].type); cs.buf = stOB; AddXkey(&cs, &arrow[A_K_DN].fun, arrow[A_K_DN].type); cs.buf = stOC; AddXkey(&cs, &arrow[A_K_RT].fun, arrow[A_K_RT].type); cs.buf = stOD; AddXkey(&cs, &arrow[A_K_LT].fun, arrow[A_K_LT].type); cs.buf = stOH; AddXkey(&cs, &arrow[A_K_HO].fun, arrow[A_K_HO].type); cs.buf = stOF; AddXkey(&cs, &arrow[A_K_EN].fun, arrow[A_K_EN].type); if (VImode) { cs.len = 2; cs.buf = &strA[1]; AddXkey(&cs, &arrow[A_K_UP].fun, arrow[A_K_UP].type); cs.buf = &strB[1]; AddXkey(&cs, &arrow[A_K_DN].fun, arrow[A_K_DN].type); cs.buf = &strC[1]; AddXkey(&cs, &arrow[A_K_RT].fun, arrow[A_K_RT].type); cs.buf = &strD[1]; AddXkey(&cs, &arrow[A_K_LT].fun, arrow[A_K_LT].type); cs.buf = &strH[1]; AddXkey(&cs, &arrow[A_K_HO].fun, arrow[A_K_HO].type); cs.buf = &strF[1]; AddXkey(&cs, &arrow[A_K_EN].fun, arrow[A_K_EN].type); cs.buf = &stOA[1]; AddXkey(&cs, &arrow[A_K_UP].fun, arrow[A_K_UP].type); cs.buf = &stOB[1]; AddXkey(&cs, &arrow[A_K_DN].fun, arrow[A_K_DN].type); cs.buf = &stOC[1]; AddXkey(&cs, &arrow[A_K_RT].fun, arrow[A_K_RT].type); cs.buf = &stOD[1]; AddXkey(&cs, &arrow[A_K_LT].fun, arrow[A_K_LT].type); cs.buf = &stOH[1]; AddXkey(&cs, &arrow[A_K_HO].fun, arrow[A_K_HO].type); cs.buf = &stOF[1]; AddXkey(&cs, &arrow[A_K_EN].fun, arrow[A_K_EN].type); } } int SetArrowKeys(const CStr *name, XmapVal *fun, int type) { int i; for (i = 0; i < A_K_NKEYS; i++) if (Strcmp(name->buf, arrow[i].name) == 0) { arrow[i].fun = *fun; arrow[i].type = type; return 0; } return -1; } int IsArrowKey(Char *name) { int i; for (i = 0; i < A_K_NKEYS; i++) if (Strcmp(name, arrow[i].name) == 0) return 1; return 0; } int ClearArrowKeys(const CStr *name) { int i; for (i = 0; i < A_K_NKEYS; i++) if (Strcmp(name->buf, arrow[i].name) == 0) { arrow[i].type = XK_NOD; return 0; } return -1; } void PrintArrowKeys(const CStr *name) { int i; for (i = 0; i < A_K_NKEYS; i++) if (name->len == 0 || Strcmp(name->buf, arrow[i].name) == 0) if (arrow[i].type != XK_NOD) printOne(arrow[i].name, &arrow[i].fun, arrow[i].type); } void BindArrowKeys(void) { KEYCMD *map, *dmap; int i, j; char *p; CStr cs; if (!GotTermCaps) return; map = VImode ? CcAltMap : CcKeyMap; dmap = VImode ? CcViCmdMap : CcEmacsMap; DefaultArrowKeys(); for (i = 0; i < A_K_NKEYS; i++) { p = tstr[arrow[i].key].str; if (p && *p) { j = (unsigned char) *p; cs.buf = str2short(p); cs.len = Strlen(cs.buf); /* * Assign the arrow keys only if: * - * 1. They are multi-character arrow keys and the user - * has not re-assigned the leading character, or + * 1. They are multi-character arrow keys and the user + * has not re-assigned the leading character, or * has re-assigned the leading character to be F_XKEY * 2. They are single arrow keys pointing to an unassigned key. */ if (arrow[i].type == XK_NOD) { ClearXkey(map, &cs); } else { if (p[1] && (dmap[j] == map[j] || map[j] == F_XKEY)) { AddXkey(&cs, &arrow[i].fun, arrow[i].type); map[j] = F_XKEY; } else if (map[j] == F_UNASSIGNED) { ClearXkey(map, &cs); if (arrow[i].type == XK_CMD) map[j] = arrow[i].fun.cmd; else AddXkey(&cs, &arrow[i].fun, arrow[i].type); } } } } } static Char cur_atr = 0; /* current attributes */ void SetAttributes(Char atr) { atr &= ATTRIBUTES; if (atr != cur_atr) { if (me_all && GoodStr(T_me)) { if (((cur_atr & BOLD) && !(atr & BOLD)) || ((cur_atr & UNDER) && !(atr & UNDER)) || ((cur_atr & STANDOUT) && !(atr & STANDOUT))) { (void) tputs(Str(T_me), 1, PUTPURE); cur_atr = 0; } } if ((atr & BOLD) != (cur_atr & BOLD)) { if (atr & BOLD) { if (GoodStr(T_md) && GoodStr(T_me)) { (void) tputs(Str(T_md), 1, PUTPURE); cur_atr |= BOLD; } } else { if (GoodStr(T_md) && GoodStr(T_me)) { (void) tputs(Str(T_me), 1, PUTPURE); if ((cur_atr & STANDOUT) && GoodStr(T_se)) { (void) tputs(Str(T_se), 1, PUTPURE); cur_atr &= ~STANDOUT; } if ((cur_atr & UNDER) && GoodStr(T_ue)) { (void) tputs(Str(T_ue), 1, PUTPURE); cur_atr &= ~UNDER; } cur_atr &= ~BOLD; } } } if ((atr & STANDOUT) != (cur_atr & STANDOUT)) { if (atr & STANDOUT) { if (GoodStr(T_so) && GoodStr(T_se)) { (void) tputs(Str(T_so), 1, PUTPURE); cur_atr |= STANDOUT; } } else { if (GoodStr(T_se)) { (void) tputs(Str(T_se), 1, PUTPURE); cur_atr &= ~STANDOUT; } } } if ((atr & UNDER) != (cur_atr & UNDER)) { if (atr & UNDER) { if (GoodStr(T_us) && GoodStr(T_ue)) { (void) tputs(Str(T_us), 1, PUTPURE); cur_atr |= UNDER; } } else { if (GoodStr(T_ue)) { (void) tputs(Str(T_ue), 1, PUTPURE); cur_atr &= ~UNDER; } } } } } int highlighting = 0; void StartHighlight(void) { (void) tputs(Str(T_mr), 1, PUTPURE); highlighting = 1; } void StopHighlight(void) { (void) tputs(Str(T_me), 1, PUTPURE); highlighting = 0; } /* PWP 6-27-88 -- if the tty driver thinks that we can tab, we ask termcap */ int CanWeTab(void) { return (Val(T_pt)); } /* move to line (first line == 0) as efficiently as possible; */ void -MoveToLine(int where) +MoveToLine(int where) { int del; if (where == CursorV) return; if (where > TermV) { #ifdef DEBUG_SCREEN xprintf("MoveToLine: where is ridiculous: %d\r\n", where); flush(); #endif /* DEBUG_SCREEN */ return; } del = where - CursorV; if (del > 0) { while (del > 0) { if ((T_Margin & MARGIN_AUTO) && Display[CursorV][0] != '\0') { size_t h; for (h = TermH - 1; h > 0 && Display[CursorV][h] == CHAR_DBWIDTH; h--) ; /* move without newline */ MoveToChar(h); so_write(&Display[CursorV][CursorH], TermH - CursorH); /* updates CursorH/V*/ del--; } else { if ((del > 1) && GoodStr(T_DO)) { (void) tputs(tgoto(Str(T_DO), del, del), del, PUTPURE); del = 0; } else { - for ( ; del > 0; del--) + for ( ; del > 0; del--) (void) putraw('\n'); CursorH = 0; /* because the \n will become \r\n */ } } } } else { /* del < 0 */ if (GoodStr(T_UP) && (-del > 1 || !GoodStr(T_up))) (void) tputs(tgoto(Str(T_UP), -del, -del), -del, PUTPURE); else { int i; if (GoodStr(T_up)) for (i = 0; i < -del; i++) (void) tputs(Str(T_up), 1, PUTPURE); } } CursorV = where; /* now where is here */ } void MoveToChar(int where) /* move to character position (where) */ { /* as efficiently as possible */ int del; mc_again: if (where == CursorH) return; if (where >= TermH) { #ifdef DEBUG_SCREEN xprintf("MoveToChar: where is riduculous: %d\r\n", where); flush(); #endif /* DEBUG_SCREEN */ return; } if (!where) { /* if where is first column */ (void) putraw('\r'); /* do a CR */ CursorH = 0; return; } del = where - CursorH; if ((del < -4 || del > 4) && GoodStr(T_ch)) /* go there directly */ (void) tputs(tgoto(Str(T_ch), where, where), where, PUTPURE); else { int i; if (del > 0) { /* moving forward */ if ((del > 4) && GoodStr(T_RI)) (void) tputs(tgoto(Str(T_RI), del, del), del, PUTPURE); else { /* if I can do tabs, use them */ if (T_Tabs) { if ((CursorH & 0370) != (where & ~0x7) && Display[CursorV][where & ~0x7] != CHAR_DBWIDTH) { /* if not within tab stop */ for (i = (CursorH & 0370); i < (where & ~0x7); i += 8) (void) putraw('\t'); /* then tab over */ CursorH = where & ~0x7; /* Note: considering that we often want to go to TermH - 1 for the wrapping, it would be nice to optimize this case by tabbing to the last column - but this doesn't work for all terminals! */ } } /* it's usually cheaper to just write the chars, so we do. */ /* NOTE THAT so_write() WILL CHANGE CursorH!!! */ so_write(&Display[CursorV][CursorH], where - CursorH); } } else { /* del < 0 := moving backward */ if ((-del > 4) && GoodStr(T_LE)) (void) tputs(tgoto(Str(T_LE), -del, -del), -del, PUTPURE); else { /* can't go directly there */ /* if the "cost" is greater than the "cost" from col 0 */ if (T_Tabs ? (-del > ((where >> 3) + (where & 07))) : (-del > where)) { (void) putraw('\r'); /* do a CR */ CursorH = 0; goto mc_again; /* and try again */ } for (i = 0; i < -del; i++) (void) putraw('\b'); } } } CursorH = where; /* now where is here */ } void so_write(Char *cp, int n) { int cur_pos, prompt_len = 0, region_start = 0, region_end = 0; if (n <= 0) return; /* catch bugs */ if (n > TermH) { #ifdef DEBUG_SCREEN xprintf("so_write: n is riduculous: %d\r\n", n); flush(); #endif /* DEBUG_SCREEN */ return; } if (adrof(STRhighlight)) { /* find length of prompt */ Char *promptc; for (promptc = Prompt; *promptc; promptc++); prompt_len = promptc - Prompt; /* find region start and end points */ if (IncMatchLen) { region_start = (Cursor - InputBuf) + prompt_len; region_end = region_start + IncMatchLen; } else if (MarkIsSet) { region_start = (min(Cursor, Mark) - InputBuf) + prompt_len; region_end = (max(Cursor, Mark) - InputBuf) + prompt_len; } } do { if (adrof(STRhighlight)) { cur_pos = CursorV * TermH + CursorH; if (!highlighting && cur_pos >= region_start && cur_pos < region_end) StartHighlight(); else if (highlighting && cur_pos >= region_end) StopHighlight(); /* don't highlight over the cursor. the highlighting's reverse * video would cancel it out. :P */ if (highlighting && cur_pos == (Cursor - InputBuf) + prompt_len) StopHighlight(); } if (*cp != CHAR_DBWIDTH) { if (*cp & LITERAL) { Char *d; #ifdef DEBUG_LITERAL xprintf("so: litnum %d\r\n", (int)(*cp & ~LITERAL)); #endif /* DEBUG_LITERAL */ for (d = litptr + (*cp & ~LITERAL) * LIT_FACTOR; *d; d++) (void) putwraw(*d); } else (void) putwraw(*cp); } cp++; CursorH++; } while (--n); if (adrof(STRhighlight) && highlighting) StopHighlight(); if (CursorH >= TermH) { /* wrap? */ if (T_Margin & MARGIN_AUTO) { /* yes */ CursorH = 0; CursorV++; if (T_Margin & MARGIN_MAGIC) { /* force the wrap to avoid the "magic" situation */ Char xc; if ((xc = Display[CursorV][CursorH]) != '\0') { so_write(&xc, 1); while (Display[CursorV][CursorH] == CHAR_DBWIDTH) CursorH++; } else { (void) putraw(' '); CursorH = 1; } } } else /* no wrap, but cursor stays on screen */ CursorH = TermH - 1; } } void DeleteChars(int num) /* deletes characters */ { if (num <= 0) return; if (!T_CanDel) { #ifdef DEBUG_EDIT xprintf(CGETS(7, 16, "ERROR: cannot delete\r\n")); #endif /* DEBUG_EDIT */ flush(); return; } if (num > TermH) { #ifdef DEBUG_SCREEN xprintf(CGETS(7, 17, "DeleteChars: num is riduculous: %d\r\n"), num); flush(); #endif /* DEBUG_SCREEN */ return; } if (GoodStr(T_DC)) /* if I have multiple delete */ if ((num > 1) || !GoodStr(T_dc)) { /* if dc would be more expen. */ (void) tputs(tgoto(Str(T_DC), num, num), num, PUTPURE); return; } if (GoodStr(T_dm)) /* if I have delete mode */ (void) tputs(Str(T_dm), 1, PUTPURE); if (GoodStr(T_dc)) /* else do one at a time */ while (num--) (void) tputs(Str(T_dc), 1, PUTPURE); if (GoodStr(T_ed)) /* if I have delete mode */ (void) tputs(Str(T_ed), 1, PUTPURE); } /* Puts terminal in insert character mode, or inserts num characters in the line */ void Insert_write(Char *cp, int num) { if (num <= 0) return; if (!T_CanIns) { #ifdef DEBUG_EDIT xprintf(CGETS(7, 18, "ERROR: cannot insert\r\n")); #endif /* DEBUG_EDIT */ flush(); return; } if (num > TermH) { #ifdef DEBUG_SCREEN xprintf(CGETS(7, 19, "StartInsert: num is riduculous: %d\r\n"), num); flush(); #endif /* DEBUG_SCREEN */ return; } if (GoodStr(T_IC)) /* if I have multiple insert */ if ((num > 1) || !GoodStr(T_ic)) { /* if ic would be more expen. */ (void) tputs(tgoto(Str(T_IC), num, num), num, PUTPURE); so_write(cp, num); /* this updates CursorH/V */ return; } if (GoodStr(T_im) && GoodStr(T_ei)) { /* if I have insert mode */ (void) tputs(Str(T_im), 1, PUTPURE); so_write(cp, num); /* this updates CursorH/V */ if (GoodStr(T_ip)) /* have to make num chars insert */ (void) tputs(Str(T_ip), 1, PUTPURE); (void) tputs(Str(T_ei), 1, PUTPURE); return; } do { if (GoodStr(T_ic)) /* have to make num chars insert */ (void) tputs(Str(T_ic), 1, PUTPURE); /* insert a char */ so_write(cp++, 1); /* this updates CursorH/V */ if (GoodStr(T_ip)) /* have to make num chars insert */ (void) tputs(Str(T_ip), 1, PUTPURE);/* pad the inserted char */ } while (--num); } /* clear to end of line. There are num characters to clear */ void ClearEOL(int num) { int i; if (num <= 0) return; if (T_CanCEOL && GoodStr(T_ce)) (void) tputs(Str(T_ce), 1, PUTPURE); else { for (i = 0; i < num; i++) (void) putraw(' '); CursorH += num; /* have written num spaces */ } } void ClearScreen(void) { /* clear the whole screen and home */ if (GoodStr(T_cl)) /* send the clear screen code */ (void) tputs(Str(T_cl), Val(T_li), PUTPURE); else if (GoodStr(T_ho) && GoodStr(T_cd)) { (void) tputs(Str(T_ho), Val(T_li), PUTPURE); /* home */ /* clear to bottom of screen */ (void) tputs(Str(T_cd), Val(T_li), PUTPURE); } else { (void) putraw('\r'); (void) putraw('\n'); } } void SoundBeep(void) { /* produce a sound */ beep_cmd (); if (adrof(STRnobeep)) return; if (GoodStr(T_vb) && adrof(STRvisiblebell)) (void) tputs(Str(T_vb), 1, PUTPURE); /* visible bell */ else if (GoodStr(T_bl)) /* what termcap says we should use */ (void) tputs(Str(T_bl), 1, PUTPURE); else (void) putraw(CTL_ESC('\007')); /* an ASCII bell; ^G */ } void ClearToBottom(void) { /* clear to the bottom of the screen */ if (GoodStr(T_cd)) (void) tputs(Str(T_cd), Val(T_li), PUTPURE); else if (GoodStr(T_ce)) (void) tputs(Str(T_ce), Val(T_li), PUTPURE); } void GetTermCaps(void) { /* read in the needed terminal capabilites */ int i; const char *ptr; char buf[TC_BUFSIZE]; static char bp[TC_BUFSIZE]; char *area; struct termcapstr *t; #ifdef SIG_WINDOW sigset_t oset, set; int lins, cols; /* don't want to confuse things here */ sigemptyset(&set); sigaddset(&set, SIG_WINDOW); (void)sigprocmask(SIG_BLOCK, &set, &oset); cleanup_push(&oset, sigprocmask_cleanup); #endif /* SIG_WINDOW */ area = buf; GotTermCaps = 1; setname("gettermcaps"); ptr = getenv("TERM"); #ifdef apollo - /* + /* * If we are on a pad, we pretend that we are dumb. Otherwise the termcap * library will put us in a weird screen mode, thinking that we are going * to use curses */ if (isapad()) ptr = "dumb"; #endif /* apollo */ if (!ptr || !ptr[0] || !strcmp(ptr, "wm") || !strcmp(ptr,"dmx")) ptr = "dumb"; setzero(bp, TC_BUFSIZE); i = tgetent(bp, ptr); if (i <= 0) { if (i == -1) { #if (SYSVREL == 0) || defined(IRIS3D) xprintf(CGETS(7, 20, "%s: The terminal database could not be opened.\n"), progname); } else if (i == 0) { #endif /* SYSVREL */ xprintf(CGETS(7, 21, "%s: No entry for terminal type \"%s\"\n"), progname, getenv("TERM")); } xprintf(CGETS(7, 22, "%s: using dumb terminal settings.\n"), progname); Val(T_co) = 80; /* do a dumb terminal */ Val(T_pt) = Val(T_km) = Val(T_li) = 0; for (t = tstr; t->name != NULL; t++) TCset(t, NULL); } else { /* Can we tab */ Val(T_pt) = tgetflag("pt") && !tgetflag("xt"); /* do we have a meta? */ Val(T_km) = (tgetflag("km") || tgetflag("MT")); Val(T_am) = tgetflag("am"); Val(T_xn) = tgetflag("xn"); Val(T_co) = tgetnum("co"); Val(T_li) = tgetnum("li"); for (t = tstr; t->name != NULL; t++) TCset(t, tgetstr(t->name, &area)); } if (Val(T_co) < 2) Val(T_co) = 80; /* just in case */ if (Val(T_li) < 1) Val(T_li) = 24; T_Cols = (Char) Val(T_co); T_Lines = (Char) Val(T_li); if (T_Tabs) T_Tabs = Val(T_pt); T_HasMeta = Val(T_km); T_Margin = Val(T_am) ? MARGIN_AUTO : 0; T_Margin |= Val(T_xn) ? MARGIN_MAGIC : 0; T_CanCEOL = GoodStr(T_ce); T_CanDel = GoodStr(T_dc) || GoodStr(T_DC); T_CanIns = GoodStr(T_im) || GoodStr(T_ic) || GoodStr(T_IC); T_CanUP = GoodStr(T_up) || GoodStr(T_UP); if (GoodStr(T_me) && GoodStr(T_ue)) me_all = (strcmp(Str(T_me), Str(T_ue)) == 0); else me_all = 0; if (GoodStr(T_me) && GoodStr(T_se)) me_all |= (strcmp(Str(T_me), Str(T_se)) == 0); #ifdef DEBUG_SCREEN if (!T_CanUP) { xprintf(CGETS(7, 23, "%s: WARNING: Your terminal cannot move up.\n", progname)); xprintf(CGETS(7, 24, "Editing may be odd for long lines.\n")); } if (!T_CanCEOL) xprintf(CGETS(7, 25, "no clear EOL capability.\n")); if (!T_CanDel) xprintf(CGETS(7, 26, "no delete char capability.\n")); if (!T_CanIns) xprintf(CGETS(7, 27, "no insert char capability.\n")); #endif /* DEBUG_SCREEN */ #ifdef SIG_WINDOW (void) GetSize(&lins, &cols); /* get the correct window size */ ChangeSize(lins, cols); cleanup_until(&oset); /* can change it again */ #else /* SIG_WINDOW */ ChangeSize(Val(T_li), Val(T_co)); #endif /* SIG_WINDOW */ BindArrowKeys(); } #ifdef SIG_WINDOW /* GetSize(): * Return the new window size in lines and cols, and * true if the size was changed. This can fail if SHIN * is not a tty, but it will work in most cases. */ int GetSize(int *lins, int *cols) { *cols = Val(T_co); *lins = Val(T_li); #ifdef TIOCGWINSZ # define KNOWsize # ifndef lint { struct winsize ws; /* from 4.3 */ if (ioctl(SHIN, TIOCGWINSZ, (ioctl_t) &ws) != -1) { if (ws.ws_col) *cols = ws.ws_col; if (ws.ws_row) *lins = ws.ws_row; } } # endif /* !lint */ #else /* TIOCGWINSZ */ # ifdef TIOCGSIZE # define KNOWsize { struct ttysize ts; /* from Sun */ if (ioctl(SHIN, TIOCGSIZE, (ioctl_t) &ts) != -1) { if (ts.ts_cols) *cols = ts.ts_cols; if (ts.ts_lines) *lins = ts.ts_lines; } } # endif /* TIOCGSIZE */ #endif /* TIOCGWINSZ */ return (Val(T_co) != *cols || Val(T_li) != *lins); } #endif /* SIG_WINDOW */ #ifdef KNOWsize static int UpdateVal(const Char *tag, int value, Char *termcap, Char *backup) { Char *ptr, *p; if ((ptr = Strstr(termcap, tag)) == NULL) { (void)Strcpy(backup, termcap); return 0; } else { size_t len = (ptr - termcap) + Strlen(tag); (void)Strncpy(backup, termcap, len); backup[len] = '\0'; p = Itoa(value, 0, 0); (void) Strcat(backup + len, p); xfree(p); ptr = Strchr(ptr, ':'); if (ptr) (void) Strcat(backup, ptr); return 1; } } #endif void ChangeSize(int lins, int cols) { /* * Just in case */ Val(T_co) = (cols < 2) ? 80 : cols; Val(T_li) = (lins < 1) ? 24 : lins; #ifdef KNOWsize /* * We want to affect the environment only when we have a valid * setup, not when we get bad settings. Consider the following scenario: * We just logged in, and we have not initialized the editor yet. * We reset termcap with tset, and not $TERMCAP has the right * terminal size. But since the editor is not initialized yet, and * the kernel's notion of the terminal size might be wrong we arrive * here with lines = columns = 0. If we reset the environment we lose * our only chance to get the window size right. */ if (Val(T_co) == cols && Val(T_li) == lins) { Char *p; char *tptr; if (getenv("COLUMNS")) { p = Itoa(Val(T_co), 0, 0); cleanup_push(p, xfree); tsetenv(STRCOLUMNS, p); cleanup_until(p); } if (getenv("LINES")) { p = Itoa(Val(T_li), 0, 0); cleanup_push(p, xfree); tsetenv(STRLINES, p); cleanup_until(p); } if ((tptr = getenv("TERMCAP")) != NULL) { /* Leave 64 characters slop in case we enlarge the termcap string */ Char termcap[TC_BUFSIZE+64], backup[TC_BUFSIZE+64], *ptr; int changed; ptr = str2short(tptr); (void) Strncpy(termcap, ptr, TC_BUFSIZE); termcap[TC_BUFSIZE-1] = '\0'; changed = UpdateVal(STRco, Val(T_co), termcap, backup); changed |= UpdateVal(STRli, Val(T_li), termcap, backup); if (changed) { /* * Chop the termcap string at TC_BUFSIZE-1 characters to avoid * core-dumps in the termcap routines */ termcap[TC_BUFSIZE - 1] = '\0'; tsetenv(STRTERMCAP, termcap); } } } #endif /* KNOWsize */ ReBufferDisplay(); /* re-make display buffers */ ClearDisp(); } diff --git a/contrib/tcsh/ed.term.c b/contrib/tcsh/ed.term.c index b0bea10ab1d6..04aefd05bd78 100644 --- a/contrib/tcsh/ed.term.c +++ b/contrib/tcsh/ed.term.c @@ -1,1138 +1,1138 @@ /* * ed.term.c: Low level terminal interface */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #ifndef WINNT_NATIVE #include #include "ed.h" int didsetty = 0; -ttyperm_t ttylist = { +ttyperm_t ttylist = { { #if defined(POSIX) || defined(TERMIO) { "iflag:", ICRNL, (INLCR|IGNCR) }, { "oflag:", (OPOST|ONLCR), ONLRET }, { "cflag:", 0, 0 }, { "lflag:", (ISIG|ICANON|ECHO|ECHOE|ECHOCTL|IEXTEN), (NOFLSH|ECHONL|EXTPROC|FLUSHO|IDEFAULT) }, #else /* GSTTY */ { "nrmal:", (ECHO|CRMOD|ANYP), (CBREAK|RAW|LCASE|VTDELAY|ALLDELAY) }, { "local:", (LCRTBS|LCRTERA|LCRTKIL), (LPRTERA|LFLUSHO) }, #endif /* POSIX || TERMIO */ { "chars:", 0, 0 }, }, { #if defined(POSIX) || defined(TERMIO) { "iflag:", (INLCR|ICRNL), IGNCR }, { "oflag:", (OPOST|ONLCR), ONLRET }, { "cflag:", 0, 0 }, { "lflag:", ISIG, (NOFLSH|ICANON|ECHO|ECHOK|ECHONL|EXTPROC|IEXTEN|FLUSHO| IDEFAULT) }, #else /* GSTTY */ { "nrmal:", (CBREAK|CRMOD|ANYP), (RAW|ECHO|LCASE|VTDELAY|ALLDELAY) }, { "local:", (LCRTBS|LCRTERA|LCRTKIL), (LPRTERA|LFLUSHO) }, #endif /* POSIX || TERMIO */ { "chars:", (C_SH(C_MIN)|C_SH(C_TIME)|C_SH(C_SWTCH)|C_SH(C_DSWTCH)| C_SH(C_WERASE)|C_SH(C_REPRINT)|C_SH(C_SUSP)|C_SH(C_DSUSP)| C_SH(C_EOF)|C_SH(C_EOL)|C_SH(C_DISCARD)|C_SH(C_PGOFF)| - C_SH(C_KILL2)|C_SH(C_PAGE)|C_SH(C_STATUS)|C_SH(C_LNEXT)), + C_SH(C_KILL2)|C_SH(C_PAGE)|C_SH(C_STATUS)|C_SH(C_LNEXT)), 0 } }, { #if defined(POSIX) || defined(TERMIO) { "iflag:", 0, IXON | IXOFF }, { "oflag:", 0, 0 }, { "cflag:", 0, 0 }, { "lflag:", 0, ISIG | IEXTEN }, #else /* GSTTY */ { "nrmal:", RAW, CBREAK }, { "local:", 0, 0 }, #endif /* POSIX || TERMIO */ { "chars:", 0, 0 }, } }; static const struct tcshmodes { const char *m_name; #ifdef SOLARIS2 unsigned long m_value; #else /* !SOLARIS2 */ int m_value; #endif /* SOLARIS2 */ int m_type; } modelist[] = { #if defined(POSIX) || defined(TERMIO) # ifdef IGNBRK { "ignbrk", IGNBRK, M_INPUT }, # endif /* IGNBRK */ # ifdef BRKINT { "brkint", BRKINT, M_INPUT }, # endif /* BRKINT */ # ifdef IGNPAR { "ignpar", IGNPAR, M_INPUT }, # endif /* IGNPAR */ # ifdef PARMRK { "parmrk", PARMRK, M_INPUT }, # endif /* PARMRK */ # ifdef INPCK { "inpck", INPCK, M_INPUT }, # endif /* INPCK */ # ifdef ISTRIP { "istrip", ISTRIP, M_INPUT }, # endif /* ISTRIP */ # ifdef INLCR { "inlcr", INLCR, M_INPUT }, # endif /* INLCR */ # ifdef IGNCR { "igncr", IGNCR, M_INPUT }, # endif /* IGNCR */ # ifdef ICRNL { "icrnl", ICRNL, M_INPUT }, # endif /* ICRNL */ # ifdef IUCLC { "iuclc", IUCLC, M_INPUT }, # endif /* IUCLC */ # ifdef IXON { "ixon", IXON, M_INPUT }, # endif /* IXON */ # ifdef IXANY { "ixany", IXANY, M_INPUT }, # endif /* IXANY */ # ifdef IXOFF { "ixoff", IXOFF, M_INPUT }, # endif /* IXOFF */ # ifdef IMAXBEL { "imaxbel",IMAXBEL,M_INPUT }, # endif /* IMAXBEL */ # ifdef IDELETE { "idelete",IDELETE,M_INPUT }, # endif /* IDELETE */ # ifdef OPOST { "opost", OPOST, M_OUTPUT }, # endif /* OPOST */ # ifdef OLCUC { "olcuc", OLCUC, M_OUTPUT }, # endif /* OLCUC */ # ifdef ONLCR { "onlcr", ONLCR, M_OUTPUT }, # endif /* ONLCR */ # ifdef OCRNL { "ocrnl", OCRNL, M_OUTPUT }, # endif /* OCRNL */ # ifdef ONOCR { "onocr", ONOCR, M_OUTPUT }, # endif /* ONOCR */ # ifdef ONOEOT { "onoeot", ONOEOT, M_OUTPUT }, # endif /* ONOEOT */ # ifdef ONLRET { "onlret", ONLRET, M_OUTPUT }, # endif /* ONLRET */ # ifdef OFILL { "ofill", OFILL, M_OUTPUT }, # endif /* OFILL */ # ifdef OFDEL { "ofdel", OFDEL, M_OUTPUT }, # endif /* OFDEL */ # ifdef NLDLY { "nldly", NLDLY, M_OUTPUT }, # endif /* NLDLY */ # ifdef CRDLY { "crdly", CRDLY, M_OUTPUT }, # endif /* CRDLY */ # ifdef TABDLY { "tabdly", TABDLY, M_OUTPUT }, # endif /* TABDLY */ # ifdef XTABS { "xtabs", XTABS, M_OUTPUT }, # endif /* XTABS */ # ifdef BSDLY { "bsdly", BSDLY, M_OUTPUT }, # endif /* BSDLY */ # ifdef VTDLY { "vtdly", VTDLY, M_OUTPUT }, # endif /* VTDLY */ # ifdef FFDLY { "ffdly", FFDLY, M_OUTPUT }, # endif /* FFDLY */ # ifdef PAGEOUT { "pageout",PAGEOUT,M_OUTPUT }, # endif /* PAGEOUT */ # ifdef WRAP { "wrap", WRAP, M_OUTPUT }, # endif /* WRAP */ # ifdef CIGNORE { "cignore",CIGNORE,M_CONTROL }, # endif /* CBAUD */ # ifdef CBAUD { "cbaud", CBAUD, M_CONTROL }, # endif /* CBAUD */ # ifdef CSTOPB { "cstopb", CSTOPB, M_CONTROL }, # endif /* CSTOPB */ # ifdef CREAD { "cread", CREAD, M_CONTROL }, # endif /* CREAD */ # ifdef PARENB { "parenb", PARENB, M_CONTROL }, # endif /* PARENB */ # ifdef PARODD { "parodd", PARODD, M_CONTROL }, # endif /* PARODD */ # ifdef HUPCL { "hupcl", HUPCL, M_CONTROL }, # endif /* HUPCL */ # ifdef CLOCAL { "clocal", CLOCAL, M_CONTROL }, # endif /* CLOCAL */ # ifdef LOBLK { "loblk", LOBLK, M_CONTROL }, # endif /* LOBLK */ # ifdef CIBAUD { "cibaud", CIBAUD, M_CONTROL }, # endif /* CIBAUD */ # ifdef CRTSCTS # ifdef CCTS_OFLOW { "ccts_oflow",CCTS_OFLOW,M_CONTROL }, # else { "crtscts",CRTSCTS,M_CONTROL }, # endif /* CCTS_OFLOW */ # endif /* CRTSCTS */ # ifdef CRTS_IFLOW { "crts_iflow",CRTS_IFLOW,M_CONTROL }, # endif /* CRTS_IFLOW */ # ifdef MDMBUF { "mdmbuf", MDMBUF, M_CONTROL }, # endif /* MDMBUF */ # ifdef RCV1EN { "rcv1en", RCV1EN, M_CONTROL }, # endif /* RCV1EN */ # ifdef XMT1EN { "xmt1en", XMT1EN, M_CONTROL }, # endif /* XMT1EN */ # ifdef ISIG { "isig", ISIG, M_LINED }, # endif /* ISIG */ # ifdef ICANON { "icanon", ICANON, M_LINED }, # endif /* ICANON */ # ifdef XCASE { "xcase", XCASE, M_LINED }, # endif /* XCASE */ # ifdef ECHO { "echo", ECHO, M_LINED }, # endif /* ECHO */ # ifdef ECHOE { "echoe", ECHOE, M_LINED }, # endif /* ECHOE */ # ifdef ECHOK { "echok", ECHOK, M_LINED }, # endif /* ECHOK */ # ifdef ECHONL { "echonl", ECHONL, M_LINED }, # endif /* ECHONL */ # ifdef NOFLSH { "noflsh", NOFLSH, M_LINED }, # endif /* NOFLSH */ # ifdef TOSTOP { "tostop", TOSTOP, M_LINED }, # endif /* TOSTOP */ # ifdef ECHOCTL { "echoctl",ECHOCTL,M_LINED }, # endif /* ECHOCTL */ # ifdef ECHOPRT { "echoprt",ECHOPRT,M_LINED }, # endif /* ECHOPRT */ # ifdef ECHOKE { "echoke", ECHOKE, M_LINED }, # endif /* ECHOKE */ # ifdef DEFECHO { "defecho",DEFECHO,M_LINED }, # endif /* DEFECHO */ # ifdef FLUSHO { "flusho", FLUSHO, M_LINED }, # endif /* FLUSHO */ # ifdef PENDIN { "pendin", PENDIN, M_LINED }, # endif /* PENDIN */ # ifdef IEXTEN { "iexten", IEXTEN, M_LINED }, # endif /* IEXTEN */ # ifdef NOKERNINFO { "nokerninfo",NOKERNINFO,M_LINED }, # endif /* NOKERNINFO */ # ifdef ALTWERASE { "altwerase",ALTWERASE,M_LINED }, # endif /* ALTWERASE */ # ifdef EXTPROC { "extproc",EXTPROC,M_LINED }, # endif /* EXTPROC */ # ifdef IDEFAULT { "idefault",IDEFAULT,M_LINED }, # endif /* IDEFAULT */ #else /* GSTTY */ # ifdef TANDEM { "tandem", TANDEM, M_CONTROL }, # endif /* TANDEM */ # ifdef CBREAK { "cbreak", CBREAK, M_CONTROL }, # endif /* CBREAK */ # ifdef LCASE { "lcase", LCASE, M_CONTROL }, # endif /* LCASE */ # ifdef ECHO { "echo", ECHO, M_CONTROL }, -# endif /* ECHO */ +# endif /* ECHO */ # ifdef CRMOD { "crmod", CRMOD, M_CONTROL }, # endif /* CRMOD */ # ifdef RAW { "raw", RAW, M_CONTROL }, # endif /* RAW */ # ifdef ODDP { "oddp", ODDP, M_CONTROL }, # endif /* ODDP */ # ifdef EVENP { "evenp", EVENP, M_CONTROL }, # endif /* EVENP */ # ifdef ANYP { "anyp", ANYP, M_CONTROL }, # endif /* ANYP */ # ifdef NLDELAY { "nldelay",NLDELAY,M_CONTROL }, # endif /* NLDELAY */ # ifdef TBDELAY { "tbdelay",TBDELAY,M_CONTROL }, # endif /* TBDELAY */ # ifdef XTABS { "xtabs", XTABS, M_CONTROL }, # endif /* XTABS */ # ifdef CRDELAY { "crdelay",CRDELAY,M_CONTROL }, # endif /* CRDELAY */ # ifdef VTDELAY { "vtdelay",VTDELAY,M_CONTROL }, # endif /* VTDELAY */ # ifdef BSDELAY { "bsdelay",BSDELAY,M_CONTROL }, # endif /* BSDELAY */ # ifdef CRTBS { "crtbs", CRTBS, M_CONTROL }, # endif /* CRTBS */ # ifdef PRTERA { "prtera", PRTERA, M_CONTROL }, # endif /* PRTERA */ # ifdef CRTERA { "crtera", CRTERA, M_CONTROL }, # endif /* CRTERA */ # ifdef TILDE { "tilde", TILDE, M_CONTROL }, # endif /* TILDE */ # ifdef MDMBUF { "mdmbuf", MDMBUF, M_CONTROL }, # endif /* MDMBUF */ # ifdef LITOUT { "litout", LITOUT, M_CONTROL }, # endif /* LITOUT */ # ifdef TOSTOP { "tostop", TOSTOP, M_CONTROL }, # endif /* TOSTOP */ # ifdef FLUSHO { "flusho", FLUSHO, M_CONTROL }, # endif /* FLUSHO */ # ifdef NOHANG { "nohang", NOHANG, M_CONTROL }, # endif /* NOHANG */ # ifdef L001000 { "l001000",L001000,M_CONTROL }, # endif /* L001000 */ # ifdef CRTKIL { "crtkil", CRTKIL, M_CONTROL }, # endif /* CRTKIL */ # ifdef PASS8 { "pass8", PASS8, M_CONTROL }, # endif /* PASS8 */ # ifdef CTLECH { "ctlech", CTLECH, M_CONTROL }, # endif /* CTLECH */ # ifdef PENDIN { "pendin", PENDIN, M_CONTROL }, # endif /* PENDIN */ # ifdef DECCTQ { "decctq", DECCTQ, M_CONTROL }, # endif /* DECCTQ */ # ifdef NOFLSH { "noflsh", NOFLSH, M_CONTROL }, # endif /* NOFLSH */ # ifdef LCRTBS { "lcrtbs", LCRTBS, M_LOCAL }, # endif /* LCRTBS */ # ifdef LPRTERA { "lprtera",LPRTERA,M_LOCAL }, # endif /* LPRTERA */ # ifdef LCRTERA { "lcrtera",LCRTERA,M_LOCAL }, # endif /* LCRTERA */ # ifdef LTILDE { "ltilde", LTILDE, M_LOCAL }, # endif /* LTILDE */ # ifdef LMDMBUF { "lmdmbuf",LMDMBUF,M_LOCAL }, # endif /* LMDMBUF */ # ifdef LLITOUT { "llitout",LLITOUT,M_LOCAL }, # endif /* LLITOUT */ # ifdef LTOSTOP { "ltostop",LTOSTOP,M_LOCAL }, # endif /* LTOSTOP */ # ifdef LFLUSHO { "lflusho",LFLUSHO,M_LOCAL }, # endif /* LFLUSHO */ # ifdef LNOHANG { "lnohang",LNOHANG,M_LOCAL }, # endif /* LNOHANG */ # ifdef LCRTKIL { "lcrtkil",LCRTKIL,M_LOCAL }, # endif /* LCRTKIL */ # ifdef LPASS8 { "lpass8", LPASS8, M_LOCAL }, -# endif /* LPASS8 */ +# endif /* LPASS8 */ # ifdef LCTLECH { "lctlech",LCTLECH,M_LOCAL }, # endif /* LCTLECH */ # ifdef LPENDIN { "lpendin",LPENDIN,M_LOCAL }, # endif /* LPENDIN */ # ifdef LDECCTQ { "ldecctq",LDECCTQ,M_LOCAL }, # endif /* LDECCTQ */ # ifdef LNOFLSH { "lnoflsh",LNOFLSH,M_LOCAL }, # endif /* LNOFLSH */ #endif /* POSIX || TERMIO */ # if defined(VINTR) || defined(TIOCGETC) { "intr", C_SH(C_INTR), M_CHAR }, # endif /* VINTR */ # if defined(VQUIT) || defined(TIOCGETC) { "quit", C_SH(C_QUIT), M_CHAR }, # endif /* VQUIT */ # if defined(VERASE) || defined(TIOCGETP) { "erase", C_SH(C_ERASE), M_CHAR }, # endif /* VERASE */ # if defined(VKILL) || defined(TIOCGETP) { "kill", C_SH(C_KILL), M_CHAR }, # endif /* VKILL */ # if defined(VEOF) || defined(TIOCGETC) { "eof", C_SH(C_EOF), M_CHAR }, # endif /* VEOF */ # if defined(VEOL) { "eol", C_SH(C_EOL), M_CHAR }, # endif /* VEOL */ # if defined(VEOL2) { "eol2", C_SH(C_EOL2), M_CHAR }, # endif /* VEOL2 */ # if defined(VSWTCH) { "swtch", C_SH(C_SWTCH), M_CHAR }, # endif /* VSWTCH */ # if defined(VDSWTCH) { "dswtch", C_SH(C_DSWTCH), M_CHAR }, # endif /* VDSWTCH */ # if defined(VERASE2) { "erase2", C_SH(C_ERASE2), M_CHAR }, # endif /* VERASE2 */ # if defined(VSTART) || defined(TIOCGETC) { "start", C_SH(C_START), M_CHAR }, # endif /* VSTART */ # if defined(VSTOP) || defined(TIOCGETC) { "stop", C_SH(C_STOP), M_CHAR }, # endif /* VSTOP */ # if defined(VWERASE) || defined(TIOCGLTC) { "werase", C_SH(C_WERASE), M_CHAR }, # endif /* VWERASE */ # if defined(VSUSP) || defined(TIOCGLTC) { "susp", C_SH(C_SUSP), M_CHAR }, # endif /* VSUSP */ # if defined(VDSUSP) || defined(TIOCGLTC) { "dsusp", C_SH(C_DSUSP), M_CHAR }, # endif /* VDSUSP */ # if defined(VREPRINT) || defined(TIOCGLTC) { "reprint", C_SH(C_REPRINT),M_CHAR }, # endif /* WREPRINT */ # if defined(VDISCARD) || defined(TIOCGLTC) { "discard", C_SH(C_DISCARD),M_CHAR }, # endif /* VDISCARD */ # if defined(VLNEXT) || defined(TIOCGLTC) { "lnext", C_SH(C_LNEXT), M_CHAR }, # endif /* VLNEXT */ # if defined(VSTATUS) || defined(TIOCGPAGE) { "status", C_SH(C_STATUS), M_CHAR }, # endif /* VSTATUS */ # if defined(VPAGE) || defined(TIOCGPAGE) { "page", C_SH(C_PAGE), M_CHAR }, # endif /* VPAGE */ # if defined(VPGOFF) || defined(TIOCGPAGE) { "pgoff", C_SH(C_PGOFF), M_CHAR }, # endif /* VPGOFF */ -# if defined(VKILL2) +# if defined(VKILL2) { "kill2", C_SH(C_KILL2), M_CHAR }, # endif /* VKILL2 */ # if defined(VBRK) || defined(TIOCGETC) { "brk", C_SH(C_BRK), M_CHAR }, # endif /* VBRK */ # if defined(VMIN) { "min", C_SH(C_MIN), M_CHAR }, # endif /* VMIN */ # if defined(VTIME) { "time", C_SH(C_TIME), M_CHAR }, # endif /* VTIME */ { NULL, 0, -1 }, }; /* * If EAGAIN and/or EWOULDBLOCK are defined, we can't just return -1 in all * situations where ioctl() does. - * + * * On AIX 4.1.5 (and presumably some other versions and OSes), as you * perform the manual test suite in the README, if you 'bg' vi immediately * after suspending it, all is well, but if you wait a few seconds, * usually ioctl() will return -1, which previously caused tty_setty() to * return -1, causing Rawmode() to return -1, causing Inputl() to return * 0, causing bgetc() to return -1, causing readc() to set doneinp to 1, * causing process() to break out of the main loop, causing tcsh to exit * prematurely. - * + * * If ioctl()'s errno is EAGAIN/EWOULDBLOCK ("Resource temporarily * unavailable"), apparently the tty is being messed with by the OS and we * need to try again. In my testing, ioctl() was never called more than * twice in a row. * * -- Dan Harkless * * So, I retry all ioctl's in case others happen to fail too (christos) */ #if defined(EAGAIN) && defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN) # define OKERROR(e) (((e) == EAGAIN) || ((e) == EWOULDBLOCK) || ((e) == EINTR)) #elif defined(EAGAIN) # define OKERROR(e) (((e) == EAGAIN) || ((e) == EINTR)) #elif defined(EWOULDBLOCK) # define OKERROR(e) (((e) == EWOULDBLOCK) || ((e) == EINTR)) #else # define OKERROR(e) ((e) == EINTR) #endif #ifdef __NetBSD__ #define KLUDGE (errno == ENOTTY && count < 10) #else #define KLUDGE 0 #endif /* Retry a system call */ #define RETRY(x) \ do { \ int count; \ \ for (count = 0;; count++) \ if ((x) == -1) { \ if (OKERROR(errno) || KLUDGE) \ continue; \ else \ return -1; \ } \ else \ break; \ } while (0) /*ARGSUSED*/ void dosetty(Char **v, struct command *t) { const struct tcshmodes *m; char x, *d, *cmdname; int aflag = 0; Char *s; int z = EX_IO; USE(t); cmdname = strsave(short2str(*v++)); cleanup_push(cmdname, xfree); setname(cmdname); - while (v && *v && v[0][0] == '-' && v[0][2] == '\0') + while (v && *v && v[0][0] == '-' && v[0][2] == '\0') switch (v[0][1]) { case 'a': aflag++; v++; break; case 'd': v++; z = ED_IO; break; case 'x': v++; z = EX_IO; break; case 'q': v++; z = QU_IO; break; default: stderror(ERR_NAME | ERR_SYSTEM, short2str(v[0]), CGETS(8, 1, "Unknown switch")); break; } didsetty = 1; if (!v || !*v) { int i = -1; int len = 0, st = 0, cu; for (m = modelist; m->m_name; m++) { if (m->m_type != i) { xprintf("%s%s", i != -1 ? "\n" : "", ttylist[z][m->m_type].t_name); i = m->m_type; st = len = strlen(ttylist[z][m->m_type].t_name); } assert(i != -1); x = (ttylist[z][i].t_setmask & m->m_value) ? '+' : '\0'; x = (ttylist[z][i].t_clrmask & m->m_value) ? '-' : x; if (x != '\0' || aflag) { cu = strlen(m->m_name) + (x != '\0') + 1; if (len + cu >= TermH) { xprintf("\n%*s", st, ""); len = st + cu; } - else + else len += cu; if (x != '\0') xprintf("%c%s ", x, m->m_name); else xprintf("%s ", m->m_name); } } xputchar('\n'); cleanup_until(cmdname); return; } while (v && (s = *v++)) { switch (*s) { case '+': case '-': x = *s++; break; default: x = '\0'; break; } d = short2str(s); for (m = modelist; m->m_name; m++) if (strcmp(m->m_name, d) == 0) break; - if (!m->m_name) + if (!m->m_name) stderror(ERR_NAME | ERR_SYSTEM, d, CGETS(8, 2, "Invalid argument")); switch (x) { case '+': ttylist[z][m->m_type].t_setmask |= m->m_value; ttylist[z][m->m_type].t_clrmask &= ~m->m_value; break; case '-': ttylist[z][m->m_type].t_setmask &= ~m->m_value; ttylist[z][m->m_type].t_clrmask |= m->m_value; break; default: ttylist[z][m->m_type].t_setmask &= ~m->m_value; ttylist[z][m->m_type].t_clrmask &= ~m->m_value; break; } } cleanup_until(cmdname); } /* end dosetty */ int tty_getty(int fd, ttydata_t *td) { #ifdef POSIX RETRY(tcgetattr(fd, &td->d_t)); #else /* TERMIO || GSTTY */ # ifdef TERMIO RETRY(ioctl(fd, TCGETA, (ioctl_t) &td->d_t)); # else /* GSTTY */ # ifdef TIOCGETP RETRY(ioctl(fd, TIOCGETP, (ioctl_t) &td->d_t)); # endif /* TIOCGETP */ # ifdef TIOCGETC RETRY(ioctl(fd, TIOCGETC, (ioctl_t) &td->d_tc)); # endif /* TIOCGETC */ # ifdef TIOCGPAGE RETRY(ioctl(fd, TIOCGPAGE, (ioctl_t) &td->d_pc)); # endif /* TIOCGPAGE */ # ifdef TIOCLGET RETRY(ioctl(fd, TIOCLGET, (ioctl_t) &td->d_lb)); # endif /* TIOCLGET */ # endif /* TERMIO */ #endif /* POSIX */ #ifdef TIOCGLTC RETRY(ioctl(fd, TIOCGLTC, (ioctl_t) &td->d_ltc)); #endif /* TIOCGLTC */ return 0; } int tty_setty(int fd, ttydata_t *td) { #ifdef POSIX - RETRY(xtcsetattr(fd, TCSADRAIN, &td->d_t)); + RETRY(xtcsetattr(fd, TCSADRAIN, &td->d_t)); #else # ifdef TERMIO RETRY(ioctl(fd, TCSETAW, (ioctl_t) &td->d_t)); # else # ifdef TIOCSETN RETRY(ioctl(fd, TIOCSETN, (ioctl_t) &td->d_t)); # endif /* TIOCSETN */ # ifdef TIOCGETC RETRY(ioctl(fd, TIOCSETC, (ioctl_t) &td->d_tc)); # endif /* TIOCGETC */ # ifdef TIOCGPAGE RETRY(ioctl(fd, TIOCSPAGE, (ioctl_t) &td->d_pc)); # endif /* TIOCGPAGE */ # ifdef TIOCLGET RETRY(ioctl(fd, TIOCLSET, (ioctl_t) &td->d_lb)); # endif /* TIOCLGET */ # endif /* TERMIO */ #endif /* POSIX */ #ifdef TIOCGLTC RETRY(ioctl(fd, TIOCSLTC, (ioctl_t) &td->d_ltc)); #endif /* TIOCGLTC */ return 0; } void tty_getchar(ttydata_t *td, unsigned char *s) -{ +{ #ifdef TIOCGLTC { struct ltchars *n = &td->d_ltc; s[C_SUSP] = n->t_suspc; s[C_DSUSP] = n->t_dsuspc; s[C_REPRINT] = n->t_rprntc; s[C_DISCARD] = n->t_flushc; s[C_WERASE] = n->t_werasc; s[C_LNEXT] = n->t_lnextc; } #endif /* TIOCGLTC */ #if defined(POSIX) || defined(TERMIO) { # ifdef POSIX struct termios *n = &td->d_t; # else struct termio *n = &td->d_t; # endif /* POSIX */ # ifdef VINTR s[C_INTR] = n->c_cc[VINTR]; # endif /* VINTR */ # ifdef VQUIT s[C_QUIT] = n->c_cc[VQUIT]; # endif /* VQUIT */ # ifdef VERASE s[C_ERASE] = n->c_cc[VERASE]; # endif /* VERASE */ # ifdef VKILL s[C_KILL] = n->c_cc[VKILL]; # endif /* VKILL */ # ifdef VEOF s[C_EOF] = n->c_cc[VEOF]; # endif /* VEOF */ # ifdef VEOL s[C_EOL] = n->c_cc[VEOL]; # endif /* VEOL */ # ifdef VEOL2 s[C_EOL2] = n->c_cc[VEOL2]; # endif /* VEOL2 */ # ifdef VSWTCH s[C_SWTCH] = n->c_cc[VSWTCH]; # endif /* VSWTCH */ # ifdef VDSWTCH s[C_DSWTCH] = n->c_cc[VDSWTCH]; # endif /* VDSWTCH */ # ifdef VERASE2 s[C_ERASE2] = n->c_cc[VERASE2]; # endif /* VERASE2 */ # ifdef VSTART s[C_START] = n->c_cc[VSTART]; # endif /* VSTART */ # ifdef VSTOP s[C_STOP] = n->c_cc[VSTOP]; # endif /* VSTOP */ # ifdef VWERASE s[C_WERASE] = n->c_cc[VWERASE]; # endif /* VWERASE */ # ifdef VSUSP s[C_SUSP] = n->c_cc[VSUSP]; # endif /* VSUSP */ # ifdef VDSUSP s[C_DSUSP] = n->c_cc[VDSUSP]; # endif /* VDSUSP */ # ifdef VREPRINT s[C_REPRINT] = n->c_cc[VREPRINT]; # endif /* WREPRINT */ # ifdef VDISCARD s[C_DISCARD] = n->c_cc[VDISCARD]; # endif /* VDISCARD */ # ifdef VLNEXT s[C_LNEXT] = n->c_cc[VLNEXT]; # endif /* VLNEXT */ # ifdef VSTATUS s[C_STATUS] = n->c_cc[VSTATUS]; # endif /* VSTATUS */ # ifdef VPAGE s[C_PAGE] = n->c_cc[VPAGE]; # endif /* VPAGE */ # ifdef VPGOFF s[C_PGOFF] = n->c_cc[VPGOFF]; # endif /* VPGOFF */ # ifdef VKILL2 s[C_KILL2] = n->c_cc[VKILL2]; # endif /* KILL2 */ # ifdef VMIN s[C_MIN] = n->c_cc[VMIN]; # endif /* VMIN */ # ifdef VTIME s[C_TIME] = n->c_cc[VTIME]; # endif /* VTIME */ } #else /* SGTTY */ # ifdef TIOCGPAGE { struct ttypagestat *n = &td->d_pc; s[C_STATUS] = n->tps_statc; s[C_PAGE] = n->tps_pagec; s[C_PGOFF] = n->tps_pgoffc; } # endif /* TIOCGPAGE */ # ifdef TIOCGETC { struct tchars *n = &td->d_tc; s[C_INTR] = n->t_intrc; s[C_QUIT] = n->t_quitc; s[C_START] = n->t_startc; s[C_STOP] = n->t_stopc; s[C_EOF] = n->t_eofc; s[C_BRK] = n->t_brkc; } # endif /* TIOCGETC */ # ifdef TIOCGETP { struct sgttyb *n = &td->d_t; s[C_ERASE] = n->sg_erase; s[C_KILL] = n->sg_kill; } # endif /* TIOCGETP */ #endif /* !POSIX || TERMIO */ } /* tty_getchar */ void tty_setchar(ttydata_t *td, unsigned char *s) -{ +{ #ifdef TIOCGLTC { - struct ltchars *n = &td->d_ltc; + struct ltchars *n = &td->d_ltc; n->t_suspc = s[C_SUSP]; n->t_dsuspc = s[C_DSUSP]; n->t_rprntc = s[C_REPRINT]; n->t_flushc = s[C_DISCARD]; n->t_werasc = s[C_WERASE]; n->t_lnextc = s[C_LNEXT]; } #endif /* TIOCGLTC */ #if defined(POSIX) || defined(TERMIO) { # ifdef POSIX struct termios *n = &td->d_t; # else struct termio *n = &td->d_t; # endif /* POSIX */ # ifdef VINTR n->c_cc[VINTR] = s[C_INTR]; # endif /* VINTR */ # ifdef VQUIT n->c_cc[VQUIT] = s[C_QUIT]; # endif /* VQUIT */ # ifdef VERASE n->c_cc[VERASE] = s[C_ERASE]; # endif /* VERASE */ # ifdef VKILL n->c_cc[VKILL] = s[C_KILL]; # endif /* VKILL */ # ifdef VEOF n->c_cc[VEOF] = s[C_EOF]; # endif /* VEOF */ # ifdef VEOL n->c_cc[VEOL] = s[C_EOL]; # endif /* VEOL */ # ifdef VEOL2 n->c_cc[VEOL2] = s[C_EOL2]; # endif /* VEOL2 */ # ifdef VSWTCH n->c_cc[VSWTCH] = s[C_SWTCH]; # endif /* VSWTCH */ # ifdef VDSWTCH n->c_cc[VDSWTCH] = s[C_DSWTCH]; # endif /* VDSWTCH */ # ifdef VERASE2 n->c_cc[VERASE2] = s[C_ERASE2]; # endif /* VERASE2 */ # ifdef VSTART n->c_cc[VSTART] = s[C_START]; # endif /* VSTART */ # ifdef VSTOP n->c_cc[VSTOP] = s[C_STOP]; # endif /* VSTOP */ # ifdef VWERASE n->c_cc[VWERASE] = s[C_WERASE]; # endif /* VWERASE */ # ifdef VSUSP n->c_cc[VSUSP] = s[C_SUSP]; # endif /* VSUSP */ # ifdef VDSUSP n->c_cc[VDSUSP] = s[C_DSUSP]; # endif /* VDSUSP */ # ifdef VREPRINT n->c_cc[VREPRINT] = s[C_REPRINT]; # endif /* WREPRINT */ # ifdef VDISCARD n->c_cc[VDISCARD] = s[C_DISCARD]; # endif /* VDISCARD */ # ifdef VLNEXT n->c_cc[VLNEXT] = s[C_LNEXT]; # endif /* VLNEXT */ # ifdef VSTATUS n->c_cc[VSTATUS] = s[C_STATUS]; # endif /* VSTATUS */ # ifdef VPAGE n->c_cc[VPAGE] = s[C_PAGE]; # endif /* VPAGE */ # ifdef VPGOFF n->c_cc[VPGOFF] = s[C_PGOFF]; # endif /* VPGOFF */ # ifdef VKILL2 n->c_cc[VKILL2] = s[C_KILL2]; # endif /* VKILL2 */ # ifdef VMIN n->c_cc[VMIN] = s[C_MIN]; # endif /* VMIN */ # ifdef VTIME n->c_cc[VTIME] = s[C_TIME]; # endif /* VTIME */ } #else /* GSTTY */ # ifdef TIOCGPAGE { struct ttypagestat *n = &td->d_pc; n->tps_length = 0; n->tps_lpos = 0; n->tps_statc = s[C_STATUS]; n->tps_pagec = s[C_PAGE]; n->tps_pgoffc = s[C_PGOFF]; n->tps_flag = 0; } # endif /* TIOCGPAGE */ # ifdef TIOCGETC { struct tchars *n = &td->d_tc; n->t_intrc = s[C_INTR]; n->t_quitc = s[C_QUIT]; n->t_startc = s[C_START]; n->t_stopc = s[C_STOP]; n->t_eofc = s[C_EOF]; n->t_brkc = s[C_BRK]; } # endif /* TIOCGETC */ # ifdef TIOCGETP { struct sgttyb *n = &td->d_t; n->sg_erase = s[C_ERASE]; n->sg_kill = s[C_KILL]; } # endif /* TIOCGETP */ #endif /* !POSIX || TERMIO */ } /* tty_setchar */ speed_t tty_getspeed(ttydata_t *td) { speed_t spd; #ifdef POSIX if ((spd = cfgetispeed(&td->d_t)) == 0) spd = cfgetospeed(&td->d_t); #else /* ! POSIX */ # ifdef TERMIO # ifdef CBAUD spd = td->d_t.c_cflag & CBAUD; -# else +# else spd = 0; -# endif +# endif # else /* SGTTY */ spd = td->d_t.sg_ispeed; # endif /* TERMIO */ #endif /* POSIX */ return spd; } /* end tty_getspeed */ int tty_gettabs(ttydata_t *td) { #if defined(POSIX) || defined(TERMIO) return ((td->d_t.c_oflag & TAB3) == TAB3) ? 0 : 1; #else /* SGTTY */ return (td->d_t.sg_flags & XTABS) == XTABS ? 0 : 1; #endif /* POSIX || TERMIO */ } /* end tty_gettabs */ int tty_geteightbit(ttydata_t *td) { #if defined(POSIX) || defined(TERMIO) return (td->d_t.c_cflag & CSIZE) == CS8; #else /* SGTTY */ return td->d_lb & (LPASS8 | LLITOUT); #endif /* POSIX || TERMIO */ } /* end tty_geteightbit */ int tty_cooked_mode(ttydata_t *td) { #if defined(POSIX) || defined(TERMIO) return (td->d_t.c_lflag & ICANON); #else /* SGTTY */ return !(td->d_t.sg_flags & (RAW | CBREAK)); #endif /* POSIX || TERMIO */ } /* end tty_cooked_mode */ #ifdef _IBMR2 void tty_setdisc(int fd, int dis) { static int edit_discipline = 0; static union txname tx_disc; extern char strPOSIX[]; switch (dis) { case EX_IO: if (edit_discipline) { if (ioctl(fd, TXSETLD, (ioctl_t) & tx_disc) == -1) return; edit_discipline = 0; } return; case ED_IO: tx_disc.tx_which = 0; if (ioctl(fd, TXGETLD, (ioctl_t) & tx_disc) == -1) return; if (strcmp(tx_disc.tx_name, strPOSIX) != 0) { edit_discipline = 1; if (ioctl(fd, TXSETLD, (ioctl_t) strPOSIX) == -1) return; } return; default: return; } } /* end tty_setdisc */ #endif /* _IBMR2 */ #ifdef DEBUG_TTY static void tty_printchar(unsigned char *s) { struct tcshmodes *m; int i; for (i = 0; i < C_NCC; i++) { - for (m = modelist; m->m_name; m++) + for (m = modelist; m->m_name; m++) if (m->m_type == M_CHAR && C_SH(i) == m->m_value) break; if (m->m_name) xprintf("%s ^%c ", m->m_name, s[i] + 'A' - 1); if (i % 5 == 0) xputchar('\n'); } xputchar('\n'); } #endif /* DEBUG_TTY */ #else /* WINNT_NATIVE */ int tty_cooked_mode(void *td) { return do_nt_check_cooked_mode(); } #endif /* !WINNT_NATIVE */ diff --git a/contrib/tcsh/ed.term.h b/contrib/tcsh/ed.term.h index aa62c11b43f1..55e910120057 100644 --- a/contrib/tcsh/ed.term.h +++ b/contrib/tcsh/ed.term.h @@ -1,529 +1,529 @@ /* * ed.term.h: Local terminal header */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _h_ed_term #define _h_ed_term #define TO_CONTROL(A) ((A) & 037) #if defined(TERMIO) || defined(POSIX) /* * Aix compatible names */ # if defined(VWERSE) && !defined(VWERASE) # define VWERASE VWERSE # endif /* VWERSE && !VWERASE */ # if defined(VDISCRD) && !defined(VDISCARD) # define VDISCARD VDISCRD # endif /* VDISCRD && !VDISCARD */ # if defined(VFLUSHO) && !defined(VDISCARD) # define VDISCARD VFLUSHO # endif /* VFLUSHO && VDISCARD */ # if defined(VSTRT) && !defined(VSTART) # define VSTART VSTRT # endif /* VSTRT && ! VSTART */ # if defined(VSTAT) && !defined(VSTATUS) # define VSTATUS VSTAT # endif /* VSTAT && ! VSTATUS */ # ifndef ONLRET # define ONLRET 0 # endif /* ONLRET */ # ifndef TAB3 # ifdef OXTABS # define TAB3 OXTABS # else # define TAB3 0 # endif /* OXTABS */ # endif /* !TAB3 */ # if defined(OXTABS) && !defined(XTABS) # define XTABS OXTABS # endif /* OXTABS && !XTABS */ # ifndef ONLCR # define ONLCR 0 # endif /* ONLCR */ # ifndef IEXTEN # define IEXTEN 0 # endif /* IEXTEN */ /* * emx garbage */ # ifndef IDEFAULT # define IDEFAULT 0 # endif /* IDEFAULT */ # ifndef IDELETE # define IDELETE 0 # endif /* IDELETE */ # ifndef ECHOCTL # define ECHOCTL 0 # endif /* ECHOCTL */ # ifndef PARENB # define PARENB 0 # endif /* PARENB */ # ifndef EXTPROC # define EXTPROC 0 # endif /* EXTPROC */ # ifndef FLUSHO # define FLUSHO 0 # endif /* FLUSHO */ # if defined(VDISABLE) && !defined(_POSIX_VDISABLE) # define _POSIX_VDISABLE VDISABLE # endif /* VDISABLE && ! _POSIX_VDISABLE */ /* * Work around ISC's definition of IEXTEN which is * XCASE! */ # ifdef ISC # if defined(IEXTEN) && defined(XCASE) # if IEXTEN == XCASE # undef IEXTEN # define IEXTEN 0 # endif /* IEXTEN == XCASE */ # endif /* IEXTEN && XCASE */ # if defined(IEXTEN) && !defined(XCASE) # define XCASE IEXTEN # undef IEXTEN # define IEXTEN 0 # endif /* IEXTEN && !XCASE */ # endif /* ISC */ /* * Work around convex weirdness where turning off IEXTEN makes us * lose all postprocessing! */ #ifdef convex # if defined(IEXTEN) && IEXTEN != 0 # undef IEXTEN # define IEXTEN 0 # endif /* IEXTEN != 0 */ #endif /* convex */ # else /* SGTTY */ # ifndef LPASS8 # define LPASS8 0 # endif /* LPASS8 */ #endif /* TERMIO || POSIX */ #ifndef _POSIX_VDISABLE # define _POSIX_VDISABLE ((unsigned char) -1) #endif /* _POSIX_VDISABLE */ #if !defined(CREPRINT) && defined(CRPRNT) # define CREPRINT CRPRNT #endif /* !CREPRINT && CRPRNT */ #if !defined(CDISCARD) && defined(CFLUSH) # define CDISCARD CFLUSH #endif /* !CDISCARD && CFLUSH */ #if !defined(CDISCARD) && defined(CFLUSHO) # define CDISCARD CFLUSHO #endif /* !CDISCARD && CFLUSHO */ /* * IRIX4.0 control macro is broken! * Ignore and undef all default tty chars defined and redefine only * the ones that are different in the IRIX file. */ #if __STDC__ && defined(IRIS4D) # undef CINTR # define CINTR 0177 /* ^? */ # undef CQUIT # undef CERASE # define CERASE TO_CONTROL('h') # undef CKILL # undef CEOF # undef CEOL -# undef CEOL2 -# undef CSWTCH +# undef CEOL2 +# undef CSWTCH # define CSWTCH TO_CONTROL('z') -# undef CDSWTCH +# undef CDSWTCH # undef CERASE2 # undef CSTART # undef CSTOP # undef CWERASE # undef CSUSP # undef CDSUSP # undef CREPRINT # undef CDISCARD # undef CLNEXT # undef CSTATUS # undef CPAGE # undef CPGOFF # undef CKILL2 # undef CBRK # undef CMIN # undef CTIME #endif /* __STDC__ && IRIS4D */ #ifndef CINTR # define CINTR TO_CONTROL('c') #endif /* CINTR */ #ifndef CQUIT # define CQUIT 034 /* ^\ */ #endif /* CQUIT */ #ifndef CERASE # define CERASE 0177 /* ^? */ #endif /* CERASE */ #ifndef CKILL # define CKILL TO_CONTROL('u') #endif /* CKILL */ #ifndef CEOF # define CEOF TO_CONTROL('d') #endif /* CEOF */ #ifndef CEOL # define CEOL _POSIX_VDISABLE #endif /* CEOL */ #ifndef CEOL2 # define CEOL2 _POSIX_VDISABLE #endif /* CEOL2 */ #ifndef CSWTCH # define CSWTCH _POSIX_VDISABLE #endif /* CSWTCH */ #ifndef CDSWTCH # define CDSWTCH _POSIX_VDISABLE #endif /* CDSWTCH */ #ifndef CERASE2 # define CERASE2 _POSIX_VDISABLE #endif /* CERASE2 */ #ifndef CSTART # define CSTART TO_CONTROL('q') #endif /* CSTART */ #ifndef CSTOP # define CSTOP TO_CONTROL('s') #endif /* CSTOP */ #ifndef CSUSP # define CSUSP TO_CONTROL('z') #endif /* CSUSP */ #ifndef CDSUSP # define CDSUSP TO_CONTROL('y') #endif /* CDSUSP */ #ifdef hpux # ifndef CREPRINT # define CREPRINT _POSIX_VDISABLE # endif /* CREPRINT */ # ifndef CDISCARD # define CDISCARD _POSIX_VDISABLE # endif /* CDISCARD */ # ifndef CLNEXT # define CLNEXT _POSIX_VDISABLE # endif /* CLNEXT */ # ifndef CWERASE # define CWERASE _POSIX_VDISABLE # endif /* CWERASE */ #else /* !hpux */ # ifndef CREPRINT # define CREPRINT TO_CONTROL('r') # endif /* CREPRINT */ # ifndef CDISCARD # define CDISCARD TO_CONTROL('o') # endif /* CDISCARD */ # ifndef CLNEXT # define CLNEXT TO_CONTROL('v') # endif /* CLNEXT */ # ifndef CWERASE # define CWERASE TO_CONTROL('w') # endif /* CWERASE */ #endif /* hpux */ #ifndef CSTATUS # define CSTATUS TO_CONTROL('t') #endif /* CSTATUS */ #ifndef CPAGE # define CPAGE ' ' #endif /* CPAGE */ #ifndef CPGOFF # define CPGOFF TO_CONTROL('m') #endif /* CPGOFF */ #ifndef CKILL2 # define CKILL2 _POSIX_VDISABLE #endif /* CKILL2 */ #ifndef CBRK # ifndef masscomp # define CBRK 0377 # else # define CBRK '\0' # endif /* masscomp */ #endif /* CBRK */ #ifndef CMIN # if VMIN == VEOF # define CMIN CEOF # else # define CMIN 1 # endif #endif /* CMIN */ #ifndef CTIME # if VTIME == VEOL # define CTIME CEOL # else # define CTIME 0 # endif #endif /* CTIME */ /* * Fix for sun inconsistency. On termio VSUSP and the rest of the * ttychars > NCC are defined. So we undefine them. */ #if defined(TERMIO) || defined(POSIX) # if defined(POSIX) && defined(NCCS) # define NUMCC NCCS # else # ifdef NCC # define NUMCC NCC # endif /* NCC */ # endif /* POSIX && NCCS */ # ifdef NUMCC # ifdef VINTR # if NUMCC <= VINTR # undef VINTR # endif /* NUMCC <= VINTR */ # endif /* VINTR */ # ifdef VQUIT # if NUMCC <= VQUIT # undef VQUIT # endif /* NUMCC <= VQUIT */ # endif /* VQUIT */ # ifdef VERASE # if NUMCC <= VERASE # undef VERASE # endif /* NUMCC <= VERASE */ # endif /* VERASE */ # ifdef VKILL # if NUMCC <= VKILL # undef VKILL # endif /* NUMCC <= VKILL */ # endif /* VKILL */ # ifdef VEOF # if NUMCC <= VEOF # undef VEOF # endif /* NUMCC <= VEOF */ # endif /* VEOF */ # ifdef VEOL # if NUMCC <= VEOL # undef VEOL # endif /* NUMCC <= VEOL */ # endif /* VEOL */ # ifdef VEOL2 # if NUMCC <= VEOL2 # undef VEOL2 # endif /* NUMCC <= VEOL2 */ # endif /* VEOL2 */ # ifdef VSWTCH # if NUMCC <= VSWTCH # undef VSWTCH # endif /* NUMCC <= VSWTCH */ # endif /* VSWTCH */ # ifdef VDSWTCH # if NUMCC <= VDSWTCH # undef VDSWTCH # endif /* NUMCC <= VDSWTCH */ # endif /* VDSWTCH */ # ifdef VERASE2 # if NUMCC <= VERASE2 # undef VERASE2 # endif /* NUMCC <= VERASE2 */ # endif /* VERASE2 */ # ifdef VSTART # if NUMCC <= VSTART # undef VSTART # endif /* NUMCC <= VSTART */ # endif /* VSTART */ # ifdef VSTOP # if NUMCC <= VSTOP # undef VSTOP # endif /* NUMCC <= VSTOP */ # endif /* VSTOP */ # ifdef VWERASE # if NUMCC <= VWERASE # undef VWERASE # endif /* NUMCC <= VWERASE */ # endif /* VWERASE */ # ifdef VSUSP # if NUMCC <= VSUSP # undef VSUSP # endif /* NUMCC <= VSUSP */ # endif /* VSUSP */ # ifdef VDSUSP # if NUMCC <= VDSUSP # undef VDSUSP # endif /* NUMCC <= VDSUSP */ # endif /* VDSUSP */ # ifdef VREPRINT # if NUMCC <= VREPRINT # undef VREPRINT # endif /* NUMCC <= VREPRINT */ # endif /* VREPRINT */ # ifdef VDISCARD # if NUMCC <= VDISCARD # undef VDISCARD # endif /* NUMCC <= VDISCARD */ # endif /* VDISCARD */ # ifdef VLNEXT # if NUMCC <= VLNEXT # undef VLNEXT # endif /* NUMCC <= VLNEXT */ # endif /* VLNEXT */ # ifdef VSTATUS # if NUMCC <= VSTATUS # undef VSTATUS # endif /* NUMCC <= VSTATUS */ # endif /* VSTATUS */ # ifdef VPAGE # if NUMCC <= VPAGE # undef VPAGE # endif /* NUMCC <= VPAGE */ # endif /* VPAGE */ # ifdef VPGOFF # if NUMCC <= VPGOFF # undef VPGOFF # endif /* NUMCC <= VPGOFF */ # endif /* VPGOFF */ # ifdef VKILL2 # if NUMCC <= VKILL2 # undef VKILL2 # endif /* NUMCC <= VKILL2 */ # endif /* VKILL2 */ # ifdef VBRK # if NUMCC <= VBRK # undef VBRK # endif /* NUMCC <= VBRK */ # endif /* VBRK */ # ifdef VMIN # if NUMCC <= VMIN # undef VMIN # endif /* NUMCC <= VMIN */ # endif /* VMIN */ # ifdef VTIME # if NUMCC <= VTIME # undef VTIME # endif /* NUMCC <= VTIME */ # endif /* VTIME */ # endif /* NUMCC */ #endif /* !POSIX */ /* * fix for hpux10 inconsistency: it has VWERASE, but TIOCSLTC returns * EINVAL if one tries to change it * Also for RH6.2 on the alpha, defined TIOCGLTC, but does not have * struct ltchars */ #if (defined(hpux) && defined(VSUSP) && defined(VDSUSP) && defined(VWERASE) && defined(VLNEXT)) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__) || defined(__QNXNTO__) # undef TIOCGLTC /* not really needed */ # undef TIOCSLTC #endif #define C_INTR 0 #define C_QUIT 1 #define C_ERASE 2 #define C_KILL 3 #define C_EOF 4 #define C_EOL 5 #define C_EOL2 6 #define C_SWTCH 7 #define C_DSWTCH 8 #define C_ERASE2 9 #define C_START 10 #define C_STOP 11 #define C_WERASE 12 #define C_SUSP 13 #define C_DSUSP 14 #define C_REPRINT 15 #define C_DISCARD 16 #define C_LNEXT 17 #define C_STATUS 18 #define C_PAGE 19 #define C_PGOFF 20 #define C_KILL2 21 #define C_BRK 22 #define C_MIN 23 #define C_TIME 24 #define C_NCC 25 #define C_SH(A) (1 << (A)) /* * Terminal dependend data structures */ typedef struct { #ifdef WINNT_NATIVE int dummy; #else /* !WINNT_NATIVE */ # if defined(POSIX) || defined(TERMIO) # ifdef POSIX struct termios d_t; # else struct termio d_t; # endif /* POSIX */ # else /* SGTTY */ # ifdef TIOCGETP struct sgttyb d_t; # endif /* TIOCGETP */ # ifdef TIOCGETC struct tchars d_tc; # endif /* TIOCGETC */ # ifdef TIOCGPAGE struct ttypagestat d_pc; # endif /* TIOCGPAGE */ # ifdef TIOCLGET int d_lb; # endif /* TIOCLGET */ # endif /* POSIX || TERMIO */ # ifdef TIOCGLTC struct ltchars d_ltc; # endif /* TIOCGLTC */ #endif /* WINNT_NATIVE */ } ttydata_t; #endif /* _h_ed_term */ diff --git a/contrib/tcsh/ed.xmap.c b/contrib/tcsh/ed.xmap.c index 6473519726dd..cc7d7054a229 100644 --- a/contrib/tcsh/ed.xmap.c +++ b/contrib/tcsh/ed.xmap.c @@ -1,758 +1,758 @@ /* * ed.xmap.c: This module contains the procedures for maintaining * the extended-key map. * * An extended-key (Xkey) is a sequence of keystrokes * introduced with an sequence introducer and consisting * of an arbitrary number of characters. This module maintains * a map (the Xmap) to convert these extended-key sequences * into input strings (XK_STR), editor functions (XK_CMD), or * unix commands (XK_EXE). It contains the * following externally visible functions. * * int GetXkey(ch,val); * CStr *ch; * XmapVal *val; * * Looks up *ch in map and then reads characters until a * complete match is found or a mismatch occurs. Returns the * type of the match found (XK_STR, XK_CMD, or XK_EXE). - * Returns NULL in val.str and XK_STR for no match. + * Returns NULL in val.str and XK_STR for no match. * The last character read is returned in *ch. * * void AddXkey(Xkey, val, ntype); * CStr *Xkey; * XmapVal *val; * int ntype; * * Adds Xkey to the Xmap and associates the value in val with it. * If Xkey is already is in Xmap, the new code is applied to the * existing Xkey. Ntype specifies if code is a command, an * out string or a unix command. * * int DeleteXkey(Xkey); * CStr *Xkey; * * Delete the Xkey and all longer Xkeys staring with Xkey, if * they exists. * * Warning: * If Xkey is a substring of some other Xkeys, then the longer * Xkeys are lost!! That is, if the Xkeys "abcd" and "abcef" * are in Xmap, adding the key "abc" will cause the first two * definitions to be lost. * * void ResetXmap(); * * Removes all entries from Xmap and resets the defaults. * * void PrintXkey(Xkey); * CStr *Xkey; * * Prints all extended keys prefixed by Xkey and their associated * commands. * * Restrictions: * ------------- * 1) It is not possible to have one Xkey that is a * substring of another. */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include "ed.defns.h" #ifndef NULL #define NULL 0 #endif /* Internal Data types and declarations */ /* The Nodes of the Xmap. The Xmap is a linked list of these node * elements */ typedef struct Xmapnode { Char ch; /* single character of Xkey */ int type; XmapVal val; /* command code or pointer to string, if this * is a leaf */ struct Xmapnode *next; /* ptr to next char of this Xkey */ struct Xmapnode *sibling; /* ptr to another Xkey with same prefix */ } XmapNode; static XmapNode *Xmap = NULL; /* the current Xmap */ /* Some declarations of procedures */ static int TraverseMap (XmapNode *, CStr *, XmapVal *); static int TryNode (XmapNode *, CStr *, XmapVal *, int); static XmapNode *GetFreeNode (CStr *); static void PutFreeNode (XmapNode *); static int TryDeleteNode (XmapNode **, CStr *); static int Lookup (struct Strbuf *, const CStr *, const XmapNode *); static void Enumerate (struct Strbuf *, const XmapNode *); static void unparsech (struct Strbuf *, Char); XmapVal * XmapCmd(int cmd) { static XmapVal xm; xm.cmd = (KEYCMD) cmd; return &xm; } XmapVal * XmapStr(CStr *str) { static XmapVal xm; xm.str.len = str->len; xm.str.buf = str->buf; return &xm; } /* ResetXmap(): * Takes all nodes on Xmap and puts them on free list. Then * initializes Xmap with arrow keys */ void ResetXmap(void) { PutFreeNode(Xmap); Xmap = NULL; DefaultArrowKeys(); return; } /* GetXkey(): * Calls the recursive function with entry point Xmap */ int GetXkey(CStr *ch, XmapVal *val) { return (TraverseMap(Xmap, ch, val)); } /* TraverseMap(): * recursively traverses node in tree until match or mismatch is * found. May read in more characters. */ static int TraverseMap(XmapNode *ptr, CStr *ch, XmapVal *val) { Char tch; if (ptr->ch == *(ch->buf)) { /* match found */ if (ptr->next) { /* Xkey not complete so get next char */ if (GetNextChar(&tch) != 1) { /* if EOF or error */ val->cmd = F_SEND_EOF; return XK_CMD;/* PWP: Pretend we just read an end-of-file */ } *(ch->buf) = tch; return (TraverseMap(ptr->next, ch, val)); } else { *val = ptr->val; if (ptr->type != XK_CMD) *(ch->buf) = '\0'; return ptr->type; } } else { /* no match found here */ if (ptr->sibling) { /* try next sibling */ return (TraverseMap(ptr->sibling, ch, val)); } else { /* no next sibling -- mismatch */ val->str.buf = NULL; val->str.len = 0; return XK_STR; } } } void AddXkey(const CStr *Xkey, XmapVal *val, int ntype) { CStr cs; cs.buf = Xkey->buf; cs.len = Xkey->len; if (Xkey->len == 0) { xprintf("%s", CGETS(9, 1, "AddXkey: Null extended-key not allowed.\n")); return; } if (ntype == XK_CMD && val->cmd == F_XKEY) { xprintf("%s", CGETS(9, 2, "AddXkey: sequence-lead-in command not allowed\n")); return; } if (Xmap == NULL) /* tree is initially empty. Set up new node to match Xkey[0] */ Xmap = GetFreeNode(&cs); /* it is properly initialized */ /* Now recurse through Xmap */ - (void) TryNode(Xmap, &cs, val, ntype); + (void) TryNode(Xmap, &cs, val, ntype); return; } static int TryNode(XmapNode *ptr, CStr *str, XmapVal *val, int ntype) { /* * Find a node that matches *string or allocate a new one */ if (ptr->ch != *(str->buf)) { XmapNode *xm; for (xm = ptr; xm->sibling != NULL; xm = xm->sibling) if (xm->sibling->ch == *(str->buf)) break; if (xm->sibling == NULL) xm->sibling = GetFreeNode(str); /* setup new node */ ptr = xm->sibling; } str->buf++; str->len--; if (str->len == 0) { size_t len; /* we're there */ if (ptr->next != NULL) { PutFreeNode(ptr->next); /* lose longer Xkeys with this prefix */ ptr->next = NULL; } switch (ptr->type) { case XK_STR: case XK_EXE: xfree(ptr->val.str.buf); ptr->val.str.len = 0; break; case XK_NOD: case XK_CMD: break; default: abort(); break; } switch (ptr->type = ntype) { case XK_CMD: ptr->val = *val; break; case XK_STR: case XK_EXE: ptr->val.str.len = val->str.len; len = (val->str.len + 1) * sizeof(*ptr->val.str.buf); ptr->val.str.buf = xmalloc(len); (void) memcpy(ptr->val.str.buf, val->str.buf, len); break; default: abort(); break; } } else { /* still more chars to go */ if (ptr->next == NULL) ptr->next = GetFreeNode(str); /* setup new node */ (void) TryNode(ptr->next, str, val, ntype); } return (0); } void ClearXkey(KEYCMD *map, const CStr *in) { unsigned char c = (unsigned char) *(in->buf); if ((map[c] == F_XKEY) && ((map == CcKeyMap && CcAltMap[c] != F_XKEY) || (map == CcAltMap && CcKeyMap[c] != F_XKEY))) (void) DeleteXkey(in); } int DeleteXkey(const CStr *Xkey) { CStr s; s = *Xkey; if (s.len == 0) { xprintf("%s", CGETS(9, 3, "DeleteXkey: Null extended-key not allowed.\n")); return (-1); } if (Xmap == NULL) return (0); (void) TryDeleteNode(&Xmap, &s); return (0); } /* Destroys str */ static int TryDeleteNode(XmapNode **inptr, CStr *str) { XmapNode *ptr; ptr = *inptr; /* * Find a node that matches *string or allocate a new one */ if (ptr->ch != *(str->buf)) { XmapNode *xm; for (xm = ptr; xm->sibling != NULL; xm = xm->sibling) if (xm->sibling->ch == *(str->buf)) break; if (xm->sibling == NULL) return (0); inptr = &xm->sibling; ptr = xm->sibling; } str->buf++; str->len--; if (str->len == 0) { /* we're there */ *inptr = ptr->sibling; ptr->sibling = NULL; PutFreeNode(ptr); return (1); } else if (ptr->next != NULL && TryDeleteNode(&ptr->next, str) == 1) { if (ptr->next != NULL) return (0); *inptr = ptr->sibling; ptr->sibling = NULL; PutFreeNode(ptr); return (1); } else { return (0); } } /* PutFreeNode(): * Puts a tree of nodes onto free list using free(3). */ static void PutFreeNode(XmapNode *ptr) { if (ptr == NULL) return; if (ptr->next != NULL) { PutFreeNode(ptr->next); ptr->next = NULL; } PutFreeNode(ptr->sibling); switch (ptr->type) { case XK_CMD: case XK_NOD: break; case XK_EXE: case XK_STR: xfree(ptr->val.str.buf); break; default: abort(); break; } xfree(ptr); } /* GetFreeNode(): * Returns pointer to an XmapNode for ch. */ static XmapNode * GetFreeNode(CStr *ch) { XmapNode *ptr; ptr = xmalloc(sizeof(XmapNode)); ptr->ch = ch->buf[0]; ptr->type = XK_NOD; ptr->val.str.buf = NULL; ptr->val.str.len = 0; ptr->next = NULL; ptr->sibling = NULL; return (ptr); } - + /* PrintXKey(): * Print the binding associated with Xkey key. * Print entire Xmap if null */ void PrintXkey(const CStr *key) { struct Strbuf buf = Strbuf_INIT; CStr cs; if (key) { cs.buf = key->buf; cs.len = key->len; } else { cs.buf = STRNULL; cs.len = 0; } /* do nothing if Xmap is empty and null key specified */ if (Xmap == NULL && cs.len == 0) return; Strbuf_append1(&buf, '"'); cleanup_push(&buf, Strbuf_cleanup); if (Lookup(&buf, &cs, Xmap) <= -1) /* key is not bound */ xprintf(CGETS(9, 4, "Unbound extended key \"%S\"\n"), cs.buf); cleanup_until(&buf); } /* Lookup(): * look for the string starting at node ptr. * Print if last node */ static int Lookup(struct Strbuf *buf, const CStr *str, const XmapNode *ptr) { if (ptr == NULL) return (-1); /* cannot have null ptr */ if (str->len == 0) { /* no more chars in string. Enumerate from here. */ Enumerate(buf, ptr); return (0); } else { /* If match put this char into buf. Recurse */ if (ptr->ch == *(str->buf)) { /* match found */ unparsech(buf, ptr->ch); if (ptr->next != NULL) { /* not yet at leaf */ CStr tstr; tstr.buf = str->buf + 1; tstr.len = str->len - 1; return (Lookup(buf, &tstr, ptr->next)); } else { /* next node is null so key should be complete */ if (str->len == 1) { Strbuf_append1(buf, '"'); Strbuf_terminate(buf); printOne(buf->s, &ptr->val, ptr->type); return (0); } else return (-1);/* mismatch -- string still has chars */ } } else { /* no match found try sibling */ if (ptr->sibling) return (Lookup(buf, str, ptr->sibling)); else return (-1); } } } static void Enumerate(struct Strbuf *buf, const XmapNode *ptr) { size_t old_len; if (ptr == NULL) { #ifdef DEBUG_EDIT xprintf(CGETS(9, 6, "Enumerate: BUG!! Null ptr passed\n!")); #endif return; } old_len = buf->len; unparsech(buf, ptr->ch); /* put this char at end of string */ if (ptr->next == NULL) { /* print this Xkey and function */ Strbuf_append1(buf, '"'); Strbuf_terminate(buf); printOne(buf->s, &ptr->val, ptr->type); } else Enumerate(buf, ptr->next); /* go to sibling if there is one */ if (ptr->sibling) { buf->len = old_len; Enumerate(buf, ptr->sibling); } } /* PrintOne(): * Print the specified key and its associated * function specified by val */ void printOne(const Char *key, const XmapVal *val, int ntype) { struct KeyFuncs *fp; static const char *fmt = "%s\n"; xprintf("%-15S-> ", key); if (val != NULL) switch (ntype) { case XK_STR: case XK_EXE: { unsigned char *p; p = unparsestring(&val->str, ntype == XK_STR ? STRQQ : STRBB); cleanup_push(p, xfree); xprintf(fmt, p); cleanup_until(p); break; } case XK_CMD: for (fp = FuncNames; fp->name; fp++) if (val->cmd == fp->func) xprintf(fmt, fp->name); - break; + break; default: abort(); break; } else xprintf(fmt, CGETS(9, 7, "no input")); } static void unparsech(struct Strbuf *buf, Char ch) { if (ch == 0) { Strbuf_append1(buf, '^'); Strbuf_append1(buf, '@'); } else if (Iscntrl(ch)) { Strbuf_append1(buf, '^'); if (ch == CTL_ESC('\177')) Strbuf_append1(buf, '?'); else #ifdef IS_ASCII Strbuf_append1(buf, ch | 0100); #else Strbuf_append1(buf, _toebcdic[_toascii[ch]|0100]); #endif } else if (ch == '^') { Strbuf_append1(buf, '\\'); Strbuf_append1(buf, '^'); } else if (ch == '\\') { Strbuf_append1(buf, '\\'); Strbuf_append1(buf, '\\'); } else if (ch == ' ' || (Isprint(ch) && !Isspace(ch))) { Strbuf_append1(buf, ch); } else { Strbuf_append1(buf, '\\'); Strbuf_append1(buf, ((ch >> 6) & 7) + '0'); Strbuf_append1(buf, ((ch >> 3) & 7) + '0'); Strbuf_append1(buf, (ch & 7) + '0'); } } eChar parseescape(const Char **ptr) { const Char *p; Char c; p = *ptr; if ((p[1] & CHAR) == 0) { xprintf(CGETS(9, 8, "Something must follow: %c\n"), (char)*p); return CHAR_ERR; } if ((*p & CHAR) == '\\') { p++; switch (*p & CHAR) { case 'a': c = CTL_ESC('\007'); /* Bell */ break; case 'b': c = CTL_ESC('\010'); /* Backspace */ break; case 'e': c = CTL_ESC('\033'); /* Escape */ break; case 'f': c = CTL_ESC('\014'); /* Form Feed */ break; case 'n': c = CTL_ESC('\012'); /* New Line */ break; case 'r': c = CTL_ESC('\015'); /* Carriage Return */ break; case 't': c = CTL_ESC('\011'); /* Horizontal Tab */ break; case 'v': c = CTL_ESC('\013'); /* Vertical Tab */ break; case '\\': c = '\\'; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { int cnt, val; Char ch; for (cnt = 0, val = 0; cnt < 3; cnt++) { ch = *p++ & CHAR; if (ch < '0' || ch > '7') { p--; break; } val = (val << 3) | (ch - '0'); } if ((val & ~0xff) != 0) { xprintf("%s", CGETS(9, 9, "Octal constant does not fit in a char.\n")); return 0; } #ifndef IS_ASCII if (CTL_ESC(val) != val && adrof(STRwarnebcdic)) xprintf(/*CGETS(9, 9, no NLS-String yet!*/ "Warning: Octal constant \\%3.3o is interpreted as EBCDIC value.\n", val/*)*/); #endif c = (Char) val; --p; } break; default: c = *p; break; } } - else if ((*p & CHAR) == '^' && (Isalpha(p[1] & CHAR) || + else if ((*p & CHAR) == '^' && (Isalpha(p[1] & CHAR) || strchr("@^_?\\|[{]}", p[1] & CHAR))) { p++; #ifdef IS_ASCII c = ((*p & CHAR) == '?') ? CTL_ESC('\177') : ((*p & CHAR) & 0237); #else c = ((*p & CHAR) == '?') ? CTL_ESC('\177') : _toebcdic[_toascii[*p & CHAR] & 0237]; if (adrof(STRwarnebcdic)) xprintf(/*CGETS(9, 9, no NLS-String yet!*/ "Warning: Control character ^%c may be interpreted differently in EBCDIC.\n", *p & CHAR /*)*/); #endif } else c = *p & CHAR; *ptr = p; return (c); } unsigned char * unparsestring(const CStr *str, const Char *sep) { unsigned char *buf, *b; Char p; int l; /* Worst-case is "\uuu" or result of wctomb() for each char from str */ buf = xmalloc((str->len + 1) * max(4, MB_LEN_MAX)); b = buf; if (sep[0]) #ifndef WINNT_NATIVE *b++ = sep[0]; #else /* WINNT_NATIVE */ *b++ = CHAR & sep[0]; #endif /* !WINNT_NATIVE */ for (l = 0; l < str->len; l++) { p = str->buf[l]; if (Iscntrl(p)) { *b++ = '^'; if (p == CTL_ESC('\177')) *b++ = '?'; else #ifdef IS_ASCII *b++ = (unsigned char) (p | 0100); #else *b++ = _toebcdic[_toascii[p]|0100]; #endif } else if (p == '^' || p == '\\') { *b++ = '\\'; *b++ = (unsigned char) p; } else if (p == ' ' || (Isprint(p) && !Isspace(p))) b += one_wctomb((char *)b, p); else { *b++ = '\\'; *b++ = ((p >> 6) & 7) + '0'; *b++ = ((p >> 3) & 7) + '0'; *b++ = (p & 7) + '0'; } } if (sep[0] && sep[1]) #ifndef WINNT_NATIVE *b++ = sep[1]; #else /* WINNT_NATIVE */ *b++ = CHAR & sep[1]; #endif /* !WINNT_NATIVE */ *b++ = 0; return buf; /* should check for overflow */ } diff --git a/contrib/tcsh/gethost.c b/contrib/tcsh/gethost.c index ddb09f3ea4c1..a21c0fc166ce 100644 --- a/contrib/tcsh/gethost.c +++ b/contrib/tcsh/gethost.c @@ -1,404 +1,404 @@ /* * gethost.c: Create version file from prototype */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #ifdef SCO # define perror __perror # define rename __rename # define getopt __getopt # define system __system #endif #include #ifdef SCO # undef perror # undef rename # undef getopt # undef system #endif #include #define ISSPACE(p) (isspace((unsigned char) (p)) && (p) != '\n') -/* +/* * We cannot do that, because some compilers like #line and others * like # - * #define LINEDIRECTIVE + * #define LINEDIRECTIVE */ static const char *keyword[] = { "vendor", #define T_VENDOR 0 "hosttype", #define T_HOSTTYPE 1 "machtype", #define T_MACHTYPE 2 "ostype", #define T_OSTYPE 3 "newdef", #define T_NEWDEF 4 "enddef", #define T_ENDDEF 5 "newcode", #define T_NEWCODE 6 "endcode", #define T_ENDCODE 7 "comment", #define T_COMMENT 8 "macro", #define T_MACRO 9 NULL #define T_NONE 10 }; #define S_DISCARD 0 #define S_COMMENT 1 #define S_CODE 2 #define S_KEYWORD 3 static int findtoken (char *); static char *gettoken (char **, char *); static char *pname; int main (int, char *[]); /* findtoken(): * Return the token number of the given token */ static int findtoken(char *ptr) { int i; if (ptr == NULL || *ptr == '\0') return T_NONE; for (i = 0; keyword[i] != NULL; i++) if (strcmp(keyword[i], ptr) == 0) return i; return T_NONE; } /* gettoken(): * Get : delimited token and remove leading/trailing blanks/newlines */ static char * gettoken(char **pptr, char *token) { char *ptr = *pptr; char *tok = token; for (; *ptr && ISSPACE(*ptr); ptr++) continue; for (; *ptr && *ptr != ':'; *tok++ = *ptr++) continue; if (*ptr == ':') ptr++; else tok--; for (tok--; tok >= token && *tok && ISSPACE(*tok); tok--) continue; *++tok = '\0'; *pptr = ptr; return token; } static char * cat(const char *a, const char *b, size_t len) { size_t l; char *r; if (len == 0) len = strlen(b) + 1; if (a) l = strlen(a) + len; else l = len; if ((r = malloc(l)) == NULL) abort(); if (a) snprintf(r, l, "%s%.*s", a, (int)len, b); else snprintf(r, l, "%.*s", (int)len, b); return r; } static const char * explode(const char *defs) { static const char def[] = "defined("; /* ) */ static char *buf; size_t len; const char *ptr, *bptr, *eptr = NULL, *name; if (strstr(defs, "#machine(" /* ) */)) return defs; if (!strstr(defs, def)) return defs; free(buf); buf = NULL; for (ptr = defs; (bptr = strstr(ptr, def)) != NULL; ptr = eptr + 1) { if (ptr != bptr) buf = cat(buf, ptr, bptr - ptr + 1); buf = cat(buf, "(", 0); /* ) */ if ((eptr = strchr(ptr + sizeof(def) - 1, ')')) == NULL) { (void) fprintf(stderr, "%s: missing close paren `%s'\n", pname, defs); free(buf); return defs; } buf = cat(buf, bptr, eptr - bptr + 1); name = bptr + sizeof(def) - 1; len = eptr - name; if (len < 1) { (void) fprintf(stderr, "%s: empty define `%s'\n", pname, defs); free(buf); return defs; } if (*name != '_' && (*name != 'M' && name[1] != '_')) { char *undername = malloc(len + 10); if (undername == NULL) abort(); buf = cat(buf, ") || defined(", 0); snprintf(undername, len + 10, "__%.*s__)", (int)len, name); buf = cat(buf, undername, len + 5); buf = cat(buf, ") || defined(", 0); snprintf(undername, len + 10, "__%.*s)", (int)len, name); buf = cat(buf, undername, len + 3); } buf = cat(buf, "))", 0); } if (!eptr) { (void) fprintf(stderr, "%s: invalid input `%s'\n", pname, defs); return defs; } buf = cat(buf, eptr + 1, 0); return buf; } - + int main(int argc, char *argv[]) { char line[INBUFSIZE]; const char *fname = "stdin"; char *ptr, *tok; char defs[INBUFSIZE]; char stmt[INBUFSIZE]; FILE *fp = stdin; int lineno = 0; int inprocess = 0; int token, state; int errs = 0; if ((pname = strrchr(argv[0], '/')) == NULL) pname = argv[0]; else pname++; if (argc > 2) { (void) fprintf(stderr, "Usage: %s []\n", pname); return 1; } if (argc == 2) if ((fp = fopen(fname = argv[1], "r")) == NULL) { (void) fprintf(stderr, "%s: Cannot open `%s'\n", pname, fname); return 1; } state = S_DISCARD; while ((ptr = fgets(line, sizeof(line), fp)) != NULL) { lineno++; switch (token = findtoken(gettoken(&ptr, defs))) { case T_NEWCODE: state = S_CODE; break; case T_ENDCODE: state = S_DISCARD; break; case T_COMMENT: state = S_COMMENT; break; case T_NEWDEF: state = S_KEYWORD; break; case T_ENDDEF: state = S_DISCARD; break; case T_VENDOR: state = S_KEYWORD; break; case T_HOSTTYPE: state = S_KEYWORD; break; case T_MACHTYPE: state = S_KEYWORD; break; case T_OSTYPE: state = S_KEYWORD; break; case T_MACRO: if (gettoken(&ptr, defs) == NULL) { (void) fprintf(stderr, "%s: \"%s\", %d: Missing macro name\n", pname, fname, lineno); break; } if (gettoken(&ptr, stmt) == NULL) { (void) fprintf(stderr, "%s: \"%s\", %d: Missing macro body\n", pname, fname, lineno); break; } (void) fprintf(stdout, "\n#if %s\n# define %s\n#endif\n\n", explode(stmt), defs); break; case T_NONE: if (state != S_CODE && *defs != '\0') { (void) fprintf(stderr, "%s: \"%s\", %d: Discarded\n", pname, fname, lineno); if (++errs == 30) { (void) fprintf(stderr, "%s: Too many errors\n", pname); return 1; } break; } (void) fprintf(stdout, "%s", line); break; default: (void) fprintf(stderr, "%s: \"%s\", %d: Unexpected token\n", pname, fname, lineno); return 1; } switch (state) { case S_DISCARD: if (inprocess) { inprocess = 0; (void) fprintf(stdout, "#endif\n"); } break; case S_KEYWORD: tok = gettoken(&ptr, defs); if (token == T_NEWDEF) { if (inprocess) { (void) fprintf(stderr, "%s: \"%s\", %d: Missing enddef\n", pname, fname, lineno); return 1; } if (tok == NULL) { (void) fprintf(stderr, "%s: \"%s\", %d: No defs\n", pname, fname, lineno); return 1; } (void) fprintf(stdout, "\n\n"); #ifdef LINEDIRECTIVE (void) fprintf(stdout, "# %d \"%s\"\n", lineno + 1, fname); #endif /* LINEDIRECTIVE */ (void) fprintf(stdout, "#if (%s)\n", explode(defs)); inprocess = 1; } else { if (tok && *tok) (void) fprintf(stdout, "# if (%s) && !defined(_%s_)\n", explode(defs), keyword[token]); else - (void) fprintf(stdout, "# if !defined(_%s_)\n", + (void) fprintf(stdout, "# if !defined(_%s_)\n", keyword[token]); if (gettoken(&ptr, stmt) == NULL) { (void) fprintf(stderr, "%s: \"%s\", %d: No statement\n", pname, fname, lineno); return 1; } (void) fprintf(stdout, "# define _%s_\n", keyword[token]); (void) fprintf(stdout, " %s = %s;\n", keyword[token], stmt); (void) fprintf(stdout, "# endif\n"); } break; case S_COMMENT: if (gettoken(&ptr, defs)) (void) fprintf(stdout, " /* %s */\n", defs); break; case S_CODE: if (token == T_NEWCODE) { #ifdef LINEDIRECTIVE (void) fprintf(stdout, "# %d \"%s\"\n", lineno + 1, fname); #endif /* LINEDIRECTIVE */ } break; default: (void) fprintf(stderr, "%s: \"%s\", %d: Unexpected state\n", pname, fname, lineno); return 1; } } if (inprocess) { (void) fprintf(stderr, "%s: \"%s\", %d: Missing enddef\n", pname, fname, lineno); return 1; } if (fp != stdin) (void) fclose(fp); return 0; } diff --git a/contrib/tcsh/glob.c b/contrib/tcsh/glob.c index bd9856c8a8af..a5a21f1f715c 100644 --- a/contrib/tcsh/glob.c +++ b/contrib/tcsh/glob.c @@ -1,801 +1,801 @@ /* * Copyright (c) 1989 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * Guido van Rossum. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)glob.c 5.12 (Berkeley) 6/24/91"; #endif /* LIBC_SCCS and not lint */ /* * Glob: the interface is a superset of the one defined in POSIX 1003.2, * draft 9. * * The [!...] convention to negate a range is supported (SysV, Posix, ksh). * * Optional extra services, controlled by flags not defined by POSIX: * * GLOB_QUOTE: * Escaping convention: \ inhibits any special meaning the following * character might have (except \ at end of string is retained). * GLOB_MAGCHAR: * Set in gl_flags if pattern contained a globbing character. * GLOB_ALTNOT: * Use ^ instead of ! for "not". * gl_matchc: * Number of matches in the current invocation of glob. */ #ifdef WINNT_NATIVE #pragma warning(disable:4244) #endif /* WINNT_NATIVE */ #define Char __Char #include "sh.h" #include "glob.h" #ifndef HAVE_MBLEN #undef mblen #define mblen(_s,_n) mbrlen((_s),(_n),NULL) #endif #undef Char #undef QUOTE #undef TILDE #undef META #undef ismeta #undef Strchr #ifndef S_ISDIR #define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR) #endif #if !defined(S_ISLNK) && defined(S_IFLNK) #define S_ISLNK(a) (((a) & S_IFMT) == S_IFLNK) #endif #if !defined(S_ISLNK) && !defined(lstat) #define lstat stat #endif typedef unsigned short Char; static int glob1 (Char *, glob_t *, int); static int glob2 (struct strbuf *, const Char *, glob_t *, int); static int glob3 (struct strbuf *, const Char *, const Char *, const Char *, glob_t *, int); static void globextend (const char *, glob_t *); static int match (const char *, const Char *, const Char *, int); static int compare (const void *, const void *); static DIR *Opendir (const char *); #ifdef S_IFLNK static int Lstat (const char *, struct stat *); #endif static int Stat (const char *, struct stat *sb); static Char *Strchr (Char *, int); #ifdef DEBUG static void qprintf (const char *, const Char *); #endif #define DOLLAR '$' #define DOT '.' #define EOS '\0' #define LBRACKET '[' #define NOT '!' #define ALTNOT '^' #define QUESTION '?' #define QUOTE '\\' #define RANGE '-' #define RBRACKET ']' #define SEP '/' #define STAR '*' #define TILDE '~' #define UNDERSCORE '_' #define M_META 0x8000 #define M_PROTECT 0x4000 #define M_MASK 0xffff #define M_ASCII 0x00ff #define LCHAR(c) ((c)&M_ASCII) #define META(c) ((c)|M_META) #define M_ALL META('*') #define M_END META(']') #define M_NOT META('!') #define M_ALTNOT META('^') #define M_ONE META('?') #define M_RNG META('-') #define M_SET META('[') #define ismeta(c) (((c)&M_META) != 0) int globcharcoll(__Char c1, __Char c2, int cs) { #if defined(NLS) && defined(LC_COLLATE) && defined(HAVE_STRCOLL) # if defined(WIDE_STRINGS) wchar_t s1[2], s2[2]; if (c1 == c2) return (0); if (cs) { c1 = towlower(c1); c2 = towlower(c2); } else { #ifndef __FreeBSD__ /* This should not be here, but I'll rather leave it in than engage in a LC_COLLATE flamewar about a shell I don't use... */ if (iswlower(c1) && iswupper(c2)) return (1); if (iswupper(c1) && iswlower(c2)) return (-1); #endif } s1[0] = c1; s2[0] = c2; s1[1] = s2[1] = '\0'; return wcscoll(s1, s2); # else /* not WIDE_STRINGS */ char s1[2], s2[2]; if (c1 == c2) return (0); /* * From kevin lyda : * strcoll does not guarantee case sorting, so we pre-process now: */ if (cs) { c1 = islower(c1) ? c1 : tolower(c1); c2 = islower(c2) ? c2 : tolower(c2); } else { if (islower(c1) && isupper(c2)) return (1); if (isupper(c1) && islower(c2)) return (-1); } s1[0] = c1; s2[0] = c2; s1[1] = s2[1] = '\0'; return strcoll(s1, s2); # endif #else return (c1 - c2); #endif } /* * Need to dodge two kernel bugs: * opendir("") != opendir(".") * NAMEI_BUG: on plain files trailing slashes are ignored in some kernels. * POSIX specifies that they should be ignored in directories. */ static DIR * Opendir(const char *str) { #if defined(hpux) || defined(__hpux) struct stat st; #endif if (!*str) return (opendir(".")); #if defined(hpux) || defined(__hpux) /* * Opendir on some device files hangs, so avoid it */ if (stat(str, &st) == -1 || !S_ISDIR(st.st_mode)) return NULL; #endif return opendir(str); } #ifdef S_IFLNK static int Lstat(const char *fn, struct stat *sb) { int st; st = lstat(fn, sb); # ifdef NAMEI_BUG if (*fn != 0 && strend(fn)[-1] == '/' && !S_ISDIR(sb->st_mode)) st = -1; # endif /* NAMEI_BUG */ return st; } #else #define Lstat Stat #endif /* S_IFLNK */ static int Stat(const char *fn, struct stat *sb) { int st; st = stat(fn, sb); #ifdef NAMEI_BUG if (*fn != 0 && strend(fn)[-1] == '/' && !S_ISDIR(sb->st_mode)) st = -1; #endif /* NAMEI_BUG */ return st; } static Char * Strchr(Char *str, int ch) { do if (*str == ch) return (str); while (*str++); return (NULL); } #ifdef DEBUG static void qprintf(const char *pre, const Char *s) { const Char *p; - + xprintf("%s", pre); for (p = s; *p; p++) xprintf("%c", *p & 0xff); xprintf("\n%s", pre); for (p = s; *p; p++) xprintf("%c", *p & M_PROTECT ? '"' : ' '); xprintf("\n%s", pre); for (p = s; *p; p++) xprintf("%c", *p & M_META ? '_' : ' '); xprintf("\n"); } #endif /* DEBUG */ static int compare(const void *p, const void *q) { #if defined(NLS) && defined(HAVE_STRCOLL) return (strcoll(*(char *const *) p, *(char *const *) q)); #else return (strcmp(*(char *const *) p, *(char *const *) q)); #endif /* NLS && HAVE_STRCOLL */ } /* * The main glob() routine: compiles the pattern (optionally processing * quotes), calls glob1() to do the real pattern matching, and finally * sorts the list (unless unsorted operation is requested). Returns 0 * if things went well, nonzero if errors occurred. It is not an error * to find no matches. */ int glob(const char *pattern, int flags, int (*errfunc) (const char *, int), glob_t *pglob) { int err, oldpathc; Char *bufnext, m_not; const unsigned char *patnext; int c, not; Char *qpatnext, *patbuf; int no_match; patnext = (const unsigned char *) pattern; if (!(flags & GLOB_APPEND)) { pglob->gl_pathc = 0; pglob->gl_pathv = NULL; if (!(flags & GLOB_DOOFFS)) pglob->gl_offs = 0; } pglob->gl_flags = flags & ~GLOB_MAGCHAR; pglob->gl_errfunc = errfunc; oldpathc = pglob->gl_pathc; pglob->gl_matchc = 0; if (pglob->gl_flags & GLOB_ALTNOT) { not = ALTNOT; m_not = M_ALTNOT; } else { not = NOT; m_not = M_NOT; } patbuf = xmalloc((strlen(pattern) + 1) * sizeof(*patbuf)); bufnext = patbuf; no_match = *patnext == not; if (no_match) patnext++; if (flags & GLOB_QUOTE) { /* Protect the quoted characters */ while ((c = *patnext++) != EOS) { #ifdef WIDE_STRINGS int len; - + len = mblen((const char *)(patnext - 1), MB_LEN_MAX); if (len == -1) TCSH_IGNORE(mblen(NULL, 0)); else if (len > 1) { *bufnext++ = (Char) c; while (--len != 0) *bufnext++ = (Char) (*patnext++ | M_PROTECT); } else #endif /* WIDE_STRINGS */ if (c == QUOTE) { if ((c = *patnext++) == EOS) { c = QUOTE; --patnext; } *bufnext++ = (Char) (c | M_PROTECT); } else *bufnext++ = (Char) c; } } else while ((c = *patnext++) != EOS) *bufnext++ = (Char) c; *bufnext = EOS; bufnext = patbuf; qpatnext = patbuf; while ((c = *qpatnext++) != EOS) { switch (c) { case LBRACKET: c = *qpatnext; if (c == not) ++qpatnext; if (*qpatnext == EOS || Strchr(qpatnext + 1, RBRACKET) == NULL) { *bufnext++ = LBRACKET; if (c == not) --qpatnext; break; } pglob->gl_flags |= GLOB_MAGCHAR; *bufnext++ = M_SET; if (c == not) *bufnext++ = m_not; c = *qpatnext++; do { *bufnext++ = LCHAR(c); if (*qpatnext == RANGE && (c = qpatnext[1]) != RBRACKET) { *bufnext++ = M_RNG; *bufnext++ = LCHAR(c); qpatnext += 2; } } while ((c = *qpatnext++) != RBRACKET); *bufnext++ = M_END; break; case QUESTION: pglob->gl_flags |= GLOB_MAGCHAR; *bufnext++ = M_ONE; break; case STAR: pglob->gl_flags |= GLOB_MAGCHAR; /* collapse adjacent stars to one [or three if globstar], * to avoid exponential behavior */ if (bufnext == patbuf || bufnext[-1] != M_ALL || - ((flags & GLOB_STAR) != 0 && + ((flags & GLOB_STAR) != 0 && (bufnext - 1 == patbuf || bufnext[-2] != M_ALL || bufnext - 2 == patbuf || bufnext[-3] != M_ALL))) *bufnext++ = M_ALL; break; default: *bufnext++ = LCHAR(c); break; } } *bufnext = EOS; #ifdef DEBUG qprintf("patbuf=", patbuf); #endif if ((err = glob1(patbuf, pglob, no_match)) != 0) { xfree(patbuf); return (err); } /* - * If there was no match we are going to append the pattern + * If there was no match we are going to append the pattern * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified * and the pattern did not contain any magic characters * GLOB_NOMAGIC is there just for compatibility with csh. */ - if (pglob->gl_pathc == oldpathc && - ((flags & GLOB_NOCHECK) || + if (pglob->gl_pathc == oldpathc && + ((flags & GLOB_NOCHECK) || ((flags & GLOB_NOMAGIC) && !(pglob->gl_flags & GLOB_MAGCHAR)))) { if (!(flags & GLOB_QUOTE)) globextend(pattern, pglob); else { char *copy, *dest; const char *src; /* copy pattern, interpreting quotes */ copy = xmalloc(strlen(pattern) + 1); dest = copy; src = pattern; while (*src != EOS) { /* Don't interpret quotes. The spec does not say we should do */ if (*src == QUOTE) { if (*++src == EOS) --src; } *dest++ = *src++; } *dest = EOS; globextend(copy, pglob); xfree(copy); } xfree(patbuf); return 0; } else if (!(flags & GLOB_NOSORT) && (pglob->gl_pathc != oldpathc)) qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc, pglob->gl_pathc - oldpathc, sizeof(char *), compare); xfree(patbuf); return (0); } static int glob1(Char *pattern, glob_t *pglob, int no_match) { struct strbuf pathbuf = strbuf_INIT; int err; /* * a null pathname is invalid -- POSIX 1003.1 sect. 2.4. */ if (*pattern == EOS) return (0); err = glob2(&pathbuf, pattern, pglob, no_match); xfree(pathbuf.s); return err; } /* * functions glob2 and glob3 are mutually recursive; there is one level * of recursion for each segment in the pattern that contains one or * more meta characters. */ static int glob2(struct strbuf *pathbuf, const Char *pattern, glob_t *pglob, int no_match) { struct stat sbuf; int anymeta; const Char *p; size_t orig_len; /* * loop over pattern segments until end of pattern or until segment with * meta character found. */ anymeta = 0; for (;;) { if (*pattern == EOS) { /* end of pattern? */ strbuf_terminate(pathbuf); if (Lstat(pathbuf->s, &sbuf)) return (0); if (((pglob->gl_flags & GLOB_MARK) && pathbuf->s[pathbuf->len - 1] != SEP) && (S_ISDIR(sbuf.st_mode) #ifdef S_IFLNK || (S_ISLNK(sbuf.st_mode) && (Stat(pathbuf->s, &sbuf) == 0) && S_ISDIR(sbuf.st_mode)) #endif )) { strbuf_append1(pathbuf, SEP); strbuf_terminate(pathbuf); } ++pglob->gl_matchc; globextend(pathbuf->s, pglob); return 0; } /* find end of next segment, tentatively copy to pathbuf */ p = pattern; orig_len = pathbuf->len; while (*p != EOS && *p != SEP) { if (ismeta(*p)) anymeta = 1; strbuf_append1(pathbuf, *p++); } if (!anymeta) { /* no expansion, do next segment */ pattern = p; while (*pattern == SEP) strbuf_append1(pathbuf, *pattern++); } else { /* need expansion, recurse */ pathbuf->len = orig_len; return (glob3(pathbuf, pattern, p, pattern, pglob, no_match)); } } /* NOTREACHED */ } static size_t One_Char_mbtowc(__Char *pwc, const Char *s, size_t n) { #ifdef WIDE_STRINGS char buf[MB_LEN_MAX], *p; if (n > MB_LEN_MAX) n = MB_LEN_MAX; p = buf; while (p < buf + n && (*p++ = LCHAR(*s++)) != 0) ; return one_mbtowc(pwc, buf, n); #else *pwc = *s & CHAR; return 1; #endif } - + static int glob3(struct strbuf *pathbuf, const Char *pattern, const Char *restpattern, const Char *pglobstar, glob_t *pglob, int no_match) { DIR *dirp; struct dirent *dp; struct stat sbuf; int err; Char m_not = (pglob->gl_flags & GLOB_ALTNOT) ? M_ALTNOT : M_NOT; size_t orig_len; int globstar = 0; int chase_symlinks = 0; const Char *termstar = NULL; strbuf_terminate(pathbuf); orig_len = pathbuf->len; errno = err = 0; while (pglobstar < restpattern) { __Char wc; size_t width = One_Char_mbtowc(&wc, pglobstar, MB_LEN_MAX); if ((pglobstar[0] & M_MASK) == M_ALL && (pglobstar[width] & M_MASK) == M_ALL) { globstar = 1; chase_symlinks = (pglobstar[2 * width] & M_MASK) == M_ALL; termstar = pglobstar + (2 + chase_symlinks) * width; break; } pglobstar += width; - } + } if (globstar) { err = pglobstar==pattern && termstar==restpattern ? *restpattern == EOS ? glob2(pathbuf, restpattern - 1, pglob, no_match) : glob2(pathbuf, restpattern + 1, pglob, no_match) : glob3(pathbuf, pattern, restpattern, termstar, pglob, no_match); if (err) return err; pathbuf->len = orig_len; strbuf_terminate(pathbuf); } if (*pathbuf->s && (Lstat(pathbuf->s, &sbuf) || !S_ISDIR(sbuf.st_mode) #ifdef S_IFLINK && ((globstar && !chase_symlinks) || !S_ISLNK(sbuf.st_mode)) #endif )) return 0; if (!(dirp = Opendir(pathbuf->s))) { /* todo: don't call for ENOENT or ENOTDIR? */ if ((pglob->gl_errfunc && (*pglob->gl_errfunc) (pathbuf->s, errno)) || (pglob->gl_flags & GLOB_ERR)) return (GLOB_ABEND); else return (0); } /* search directory for matching names */ while ((dp = readdir(dirp)) != NULL) { /* initial DOT must be matched literally */ if (dp->d_name[0] == DOT && *pattern != DOT) if (!(pglob->gl_flags & GLOB_DOT) || !dp->d_name[1] || (dp->d_name[1] == DOT && !dp->d_name[2])) continue; /*unless globdot and not . or .. */ pathbuf->len = orig_len; strbuf_append(pathbuf, dp->d_name); strbuf_terminate(pathbuf); if (globstar) { #ifdef S_IFLNK if (!chase_symlinks && (Lstat(pathbuf->s, &sbuf) || S_ISLNK(sbuf.st_mode))) continue; #endif if (match(pathbuf->s + orig_len, pattern, termstar, - (int)m_not) == no_match) + (int)m_not) == no_match) continue; strbuf_append1(pathbuf, SEP); strbuf_terminate(pathbuf); if ((err = glob2(pathbuf, pglobstar, pglob, no_match)) != 0) break; } else { if (match(pathbuf->s + orig_len, pattern, restpattern, (int) m_not) == no_match) continue; if ((err = glob2(pathbuf, restpattern, pglob, no_match)) != 0) break; } } /* todo: check error from readdir? */ closedir(dirp); return (err); } /* * Extend the gl_pathv member of a glob_t structure to accomodate a new item, * add the new item, and update gl_pathc. * * This assumes the BSD realloc, which only copies the block when its size * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic * behavior. * * Return 0 if new item added, error code if memory couldn't be allocated. * * Invariant of the glob_t structure: * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and * gl_pathv points to (gl_offs + gl_pathc + 1) items. */ static void globextend(const char *path, glob_t *pglob) { char **pathv; int i; size_t newsize; newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs); pathv = xrealloc(pglob->gl_pathv, newsize); if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) { /* first time around -- clear initial gl_offs items */ pathv += pglob->gl_offs; for (i = pglob->gl_offs; --i >= 0;) *--pathv = NULL; } pglob->gl_pathv = pathv; pathv[pglob->gl_offs + pglob->gl_pathc++] = strsave(path); pathv[pglob->gl_offs + pglob->gl_pathc] = NULL; } /* * pattern matching function for filenames. */ static int match(const char *name, const Char *pat, const Char *patend, int m_not) { int ok, negate_range; const Char *patNext; const char *nameNext, *nameStart, *nameEnd; Char c; patNext = pat; nameStart = nameNext = name; nameEnd = NULL; while (pat < patend || *name) { size_t lwk, pwk; __Char wc, wk, wc1; c = *pat; /* Only for M_MASK bits */ if (*name == EOS) nameEnd = name; pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX); lwk = one_mbtowc(&wk, name, MB_LEN_MAX); switch (c & M_MASK) { case M_ALL: while ((*(pat + pwk) & M_MASK) == M_ALL) { pat += pwk; pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX); } patNext = pat; nameNext = name + lwk; pat += pwk; continue; case M_ONE: if (*name == EOS) break; name += lwk; pat += pwk; continue; case M_SET: ok = 0; if (*name == EOS) break; pat += pwk; pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX); name += lwk; if ((negate_range = ((*pat & M_MASK) == m_not)) != 0) { pat += pwk; pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX); } wc1 = wc; while ((*pat & M_MASK) != M_END) { if ((*pat & M_MASK) == M_RNG) { __Char wc2; pat += pwk; pwk = One_Char_mbtowc(&wc2, pat, MB_LEN_MAX); if (globcharcoll(wc1, wk, 0) <= 0 && globcharcoll(wk, wc2, 0) <= 0) ok = 1; } else if (wc == wk) ok = 1; pat += pwk; wc1 = wc; pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX); } pat += pwk; pwk = One_Char_mbtowc(&wc, pat, MB_LEN_MAX); if (ok == negate_range) break; continue; default: if (*name == EOS || samecase(wk) != samecase(wc)) break; name += lwk; pat += pwk; continue; } if (nameNext != nameStart && (nameEnd == NULL || nameNext <= nameEnd)) { pat = patNext; name = nameNext; continue; } return 0; } return 1; } /* free allocated data belonging to a glob_t structure */ void globfree(glob_t *pglob) { int i; char **pp; if (pglob->gl_pathv != NULL) { pp = pglob->gl_pathv + pglob->gl_offs; for (i = pglob->gl_pathc; i--; ++pp) if (*pp) xfree(*pp), *pp = NULL; xfree(pglob->gl_pathv), pglob->gl_pathv = NULL; } } diff --git a/contrib/tcsh/glob.h b/contrib/tcsh/glob.h index 7ce381622df7..220e39eda0e2 100644 --- a/contrib/tcsh/glob.h +++ b/contrib/tcsh/glob.h @@ -1,93 +1,93 @@ /* NetBSD: glob.h,v 1.13 2001/03/16 21:02:42 christos Exp */ /* * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Guido van Rossum. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)glob.h 8.1 (Berkeley) 6/2/93 */ #ifndef _GLOB_H_ #define _GLOB_H_ typedef struct { int gl_pathc; /* Count of total paths so far. */ int gl_matchc; /* Count of paths matching pattern. */ int gl_offs; /* Reserved at beginning of gl_pathv. */ int gl_flags; /* Copy of flags parameter to glob. */ char **gl_pathv; /* List of paths matching pattern. */ /* Copy of errfunc parameter to glob. */ int (*gl_errfunc) (const char *, int); /* * Alternate filesystem access methods for glob; replacement * versions of closedir(3), readdir(3), opendir(3), stat(2) * and lstat(2). */ void (*gl_closedir) (void *); struct dirent *(*gl_readdir) (void *); void *(*gl_opendir) (const char *); int (*gl_lstat) (const char *, struct stat *); int (*gl_stat) (const char *, struct stat *); } glob_t; #define GLOB_APPEND 0x0001 /* Append to output from previous call. */ #define GLOB_DOOFFS 0x0002 /* Use gl_offs. */ #define GLOB_ERR 0x0004 /* Return on error. */ #define GLOB_MARK 0x0008 /* Append / to matching directories. */ #define GLOB_NOCHECK 0x0010 /* Return pattern itself if nothing matches. */ #define GLOB_NOSORT 0x0020 /* Don't sort. */ #define GLOB_NOESCAPE 0x1000 /* Disable backslash escaping. */ #define GLOB_NOSPACE (-1) /* Malloc call failed. */ #define GLOB_ABORTED (-2) /* Unignored error. */ #define GLOB_NOMATCH (-3) /* No match, and GLOB_NOCHECK was not set. */ #define GLOB_NOSYS (-4) /* Implementation does not support function. */ /* #if !defined(_POSIX_C_SOURCE) && !defined(_XOPEN_SOURCE) */ #define GLOB_ALTDIRFUNC 0x0040 /* Use alternately specified directory funcs. */ #define GLOB_BRACE 0x0080 /* Expand braces ala csh. */ #define GLOB_MAGCHAR 0x0100 /* Pattern had globbing characters. */ #define GLOB_NOMAGIC 0x0200 /* GLOB_NOCHECK without magic chars (csh). */ #define GLOB_LIMIT 0x0400 /* Limit memory used by matches to ARG_MAX */ #define GLOB_TILDE 0x0800 /* Expand tilde names from the passwd file. */ -#define GLOB_ALTNOT 0x1000 /* use alternate glob character [^ not !] */ +#define GLOB_ALTNOT 0x1000 /* use alternate glob character [^ not !] */ #define GLOB_QUOTE 0x2000 /* XXX: source compatibility */ #define GLOB_STAR 0x4000 /* use glob ** to recurse directories */ #define GLOB_DOT 0x8000 /* don't skip dotfiles (except . and ..) */ #define GLOB_ABEND GLOB_ABORTED /* source compatibility */ /* #endif */ int glob (const char *, int, int (*)(const char *, int), glob_t *); void globfree (glob_t *); int globcharcoll (Char, Char, int); #endif /* !_GLOB_H_ */ diff --git a/contrib/tcsh/ma.setp.c b/contrib/tcsh/ma.setp.c index 5d5adac246bf..b80ff892a138 100644 --- a/contrib/tcsh/ma.setp.c +++ b/contrib/tcsh/ma.setp.c @@ -1,593 +1,593 @@ /* * Copyright (c) 1990 Carnegie Mellon University * All Rights Reserved. - * + * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * THE SOFTWARE IS PROVIDED "AS IS" AND CARNEGIE MELLON UNIVERSITY * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT * SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Users of this software agree to return to Carnegie Mellon any * improvements or extensions that they make and grant Carnegie the * rights to redistribute these changes. * * Export of this software is permitted only after complying with the * regulations of the U.S. Deptartment of Commerce relating to the * Export of Technical Data. */ /* * setpath --- smart interface for setting path variables * * usage: setpath(paths, cmds, localsyspath, dosuffix, printerrors) * char **paths, **cmds, *localsyspath; * int dosuffix, printerrors; * * The 'paths' argument is a list of pointers to path lists of the * form "name=value" where name is the name of the path and value * is a colon separated list of directories. There can never be * more than MAXDIRS (64) directories in a path. * * The 'cmds' argument may be a sequence of any of the following: * -r reset path to default * -i newpath insert newpath before localsyspath * -ia oldpath newpath insert newpath after oldpath * -ib oldpath newpath insert newpath before oldpath * -i# newpath insert newpath at position # * -d oldpath delete oldpath * -d# delete path at position # * -c oldpath newpath change oldpath to newpath * -c# newpath change position # to newpath * * The "-i newpath" command is equivilent to "-ib 'localsyspath' newpath". * * If 'dosuffix' is true, the appropriate suffix will be added to * all command operands for any system path in 'paths'. * * Both of the 'paths' and 'cmds' lists are terminated by a NULL * entry. * * if 'printerrors' is true, setpath will printf error diagnostics. * * WARNING !!!: Under no circumstances should anyone change this * module without fully understanding the impact on the C shell. * The C shell has it's own malloc and printf routines and this * module was carefully written taking that into account. Do not * use any stdio routines from this module except printf. * ********************************************************************** * HISTORY * * Revision 1.4 90/12/11 17:58:44 mja * Add copyright/disclaimer for distribution. - * + * * 05-Jun-88 Glenn Marcy (gm0w) at Carnegie-Mellon University * Make all non-entry points static. * * 30-Apr-88 Glenn Marcy (gm0w) at Carnegie-Mellon University * Added -r switch to reset paths to their default values. * * 06-Jan-86 Glenn Marcy (gm0w) at Carnegie-Mellon University * Created from old setpath program for the shell. * ********************************************************************** */ #include "sh.h" #ifdef MACH #define MAXDIRS 64 /* max directories on a path */ #ifndef NULL # define NULL 0 #endif static int npaths; /* # pathlist arguments */ static struct pelem { struct pelem *pnext; /* pointer to next path */ char *pname; /* name of pathlist */ char *psuf; /* suffix for pathlist */ char *pdef; /* default for pathlist */ int pdirs; /* # directories on each pathlist */ char *pdir[MAXDIRS]; /* directory names for each pathlist */ } *pathhead = NULL; static struct { char *name; char *suffix; char *defalt; } syspath[] = { "PATH", "/bin", ":/usr/ucb:/bin:/usr/bin", "CPATH", "/include", ":/usr/include", "LPATH", "/lib", ":/lib:/usr/lib", "MPATH", "/man", ":/usr/man", "EPATH", "/maclib", "", 0, 0, 0 }; static int sflag; static int eflag; #define INVALID { \ if (eflag) xprintf(CGETS(10, 1, \ "setpath: invalid command '%s'.\n"), cmd); \ freepaths(); \ return(-1); \ } #define TOOFEW { \ if (eflag) xprintf(CGETS(10, 2, \ "setpath: insufficient arguments to command '%s'.\n"), cmd); \ freepaths(); \ return(-1); \ } static int initpaths (char **); static void savepaths (char **); static void freepaths (void); static void tcsh_rcmd (char *); static void icmd (char *, char *); static void iacmd (char *, char *); static void ibcmd (char *, char *); static void incmd (char *, int); static void insert (struct pelem *, int, char *); static void dcmd (char *); static void dncmd (int); static void delete (struct pelem *, int); static void ccmd (char *, char *); static void cncmd (char *, int); static void change (struct pelem *, int, char *); static int locate (struct pelem *, char *); int setpath(char **paths, char **cmds, char *localsyspath, int dosuffix, int printerrors) { char *cmd, *cmd1, *cmd2; int ncmd; sflag = dosuffix; eflag = printerrors; if (initpaths(paths) < 0) return(-1); if (npaths == 0) return(0); for (ncmd = 0; cmd = cmds[ncmd]; ncmd++) { if (cmd[0] != '-') INVALID; cmd1 = cmds[ncmd+1]; cmd2 = cmds[ncmd+2]; switch (cmd[1]) { case 'r': if (cmd[2] != '\0') INVALID; tcsh_rcmd(localsyspath); break; case 'i': if (cmd[2] == '\0') { ncmd++; if (cmd1 == NULL) TOOFEW; icmd(cmd1, localsyspath); } else if (isdigit(cmd[2])) { ncmd++; if (cmd1 == NULL) TOOFEW; incmd(cmd1, atoi(cmd+2)); } else if (cmd[3] != '\0' || (cmd[2] != 'a' && cmd[2] != 'b')) { INVALID; } else { ncmd += 2; if (cmd1 == NULL || cmd2 == NULL) TOOFEW; if (cmd[2] == 'a') iacmd(cmd1, cmd2); else ibcmd(cmd1, cmd2); } break; case 'd': if (cmd[2] == '\0') { ncmd++; if (cmd1 == NULL) TOOFEW; dcmd(cmd1); } else if (isdigit(cmd[2])) dncmd(atoi(cmd+2)); else { INVALID; } break; case 'c': if (cmd[2] == '\0') { ncmd += 2; if (cmd1 == NULL || cmd2 == NULL) TOOFEW; ccmd(cmd1, cmd2); } else if (isdigit(cmd[2])) { ncmd++; if (cmd1 == NULL) TOOFEW; cncmd(cmd1, atoi(cmd+2)); } else { INVALID; } break; default: INVALID; } } savepaths(paths); freepaths(); return(0); } static int initpaths(char **paths) { char *path, *val, *p, *q; int i, done; struct pelem *pe, *pathend; freepaths(); for (npaths = 0; path = paths[npaths]; npaths++) { val = index(path, '='); if (val == NULL) { if (eflag) xprintf(CGETS(10, 3, "setpath: value missing in path '%s'\n"), path); freepaths(); return(-1); } *val++ = '\0'; pe = xmalloc(sizeof(struct pelem)); setzero(pe, sizeof(struct pelem)); if (pathhead == NULL) pathhead = pathend = pe; else { pathend->pnext = pe; pathend = pe; } p = strsave(path); pe->pname = p; pe->psuf = ""; pe->pdef = ""; for (i = 0; syspath[i].name; i++) if (strcmp(pe->pname, syspath[i].name) == 0) { pe->psuf = syspath[i].suffix; pe->pdef = syspath[i].defalt; break; } q = val; for (;;) { q = index(p = q, ':'); done = (q == NULL); if (!done) *q++ = '\0'; p = strsave(p); pe->pdir[pe->pdirs] = p; pe->pdirs++; if (done) break; } } return(0); } static void savepaths(char **paths) { char *p, *q; int npath, i, len; struct pelem *pe; for (npath = 0, pe = pathhead; pe; npath++, pe = pe->pnext) { len = strlen(pe->pname) + 1; if (pe->pdirs == 0) len++; else for (i = 0; i < pe->pdirs; i++) len += strlen(pe->pdir[i]) + 1; p = xmalloc((unsigned)len); paths[npath] = p; for (q = pe->pname; *p = *q; p++, q++); *p++ = '='; if (pe->pdirs != 0) { for (i = 0; i < pe->pdirs; i++) { for (q = pe->pdir[i]; *p = *q; p++, q++); *p++ = ':'; } p--; } *p = '\0'; } } static void freepaths(void) { char *p; int i; struct pelem *pe; if (npaths == 0 || pathhead == NULL) return; while (pe = pathhead) { if (pe->pname) { for (i = 0; i < pe->pdirs; i++) { if (pe->pdir[i] == NULL) continue; p = pe->pdir[i]; pe->pdir[i] = NULL; xfree((ptr_t) p); } pe->pdirs = 0; p = pe->pname; pe->pname = NULL; xfree((ptr_t) p); } pathhead = pe->pnext; xfree((ptr_t) pe); } npaths = 0; } /*********************************************** *** R E S E T A P A T H N A M E *** ***********************************************/ static void tcsh_rcmd(char *localsyspath) /* reset path with localsyspath */ { int n, done; char *new, *p; struct pelem *pe; char newbuf[MAXPATHLEN+1];/*FIXBUF*/ for (pe = pathhead; pe; pe = pe->pnext) { new = newbuf; *new = '\0'; if (localsyspath != NULL) { *new = ':'; (void) strcpy(new + 1, localsyspath); (void) strcat(new, pe->psuf); } (void) strcat(new, pe->pdef); for (n = 0; n < pe->pdirs; n++) { if (pe->pdir[n] == NULL) continue; p = pe->pdir[n]; pe->pdir[n] = NULL; xfree((ptr_t) p); } pe->pdirs = 0; for (;;) { new = index(p = new, ':'); done = (new == NULL); if (!done) *new++ = '\0'; p = strsave(p); pe->pdir[pe->pdirs] = p; pe->pdirs++; if (done) break; } } } /*********************************************** *** I N S E R T A P A T H N A M E *** ***********************************************/ static void icmd(char *path, char *localsyspath) /* insert path before localsyspath */ { int n; char *new; struct pelem *pe; char newbuf[MAXPATHLEN+1];/*FIXBUF*/ for (pe = pathhead; pe; pe = pe->pnext) { if (sflag) new = localsyspath; else { new = newbuf; (void) strcpy(new, localsyspath); (void) strcat(new, pe->psuf); } n = locate(pe, new); if (n >= 0) insert(pe, n, path); else insert(pe, 0, path); } } static void iacmd(char *inpath, char *path) /* insert path after inpath */ { int n; struct pelem *pe; for (pe = pathhead; pe; pe = pe->pnext) { n = locate(pe, inpath); if (n >= 0) insert(pe, n + 1, path); else xprintf(CGETS(10, 4, "setpath: %s not found in %s\n"), inpath, pe->pname); } } static void ibcmd(char *inpath, char *path) /* insert path before inpath */ { int n; struct pelem *pe; for (pe = pathhead; pe; pe = pe->pnext) { n = locate(pe, inpath); if (n >= 0) insert(pe, n, path); else xprintf(CGETS(10, 4, "setpath: %s not found in %s\n"), inpath, pe->pname); } } static void incmd(char *path, int n) /* insert path at position n */ { struct pelem *pe; for (pe = pathhead; pe; pe = pe->pnext) insert(pe, n, path); } static void insert(struct pelem *pe, int loc, char *key) { int i; char *new; char newbuf[2000];/*FIXBUF*/ if (sflag) { /* add suffix */ new = newbuf; (void) strcpy(new, key); (void) strcat(new, pe->psuf); } else new = key; new = strsave(new); for (i = pe->pdirs; i > loc; --i) pe->pdir[i] = pe->pdir[i-1]; if (loc > pe->pdirs) loc = pe->pdirs; pe->pdir[loc] = new; pe->pdirs++; } /*********************************************** *** D E L E T E A P A T H N A M E *** ***********************************************/ static void dcmd(char *path) /* delete path */ { int n; struct pelem *pe; for (pe = pathhead; pe; pe = pe->pnext) { n = locate(pe, path); if (n >= 0) delete(pe, n); else xprintf(CGETS(10, 4, "setpath: %s not found in %s\n"), path, pe->pname); } } static void dncmd(int n) /* delete at position n */ { struct pelem *pe; for (pe = pathhead; pe; pe = pe->pnext) { if (n < pe->pdirs) delete(pe, n); else xprintf(CGETS(10, 5, "setpath: %d not valid position in %s\n"), n, pe->pname); } } static void delete(struct pelem *pe, int n) { int d; xfree((ptr_t) (pe->pdir[n])); for (d = n; d < pe->pdirs - 1; d++) pe->pdir[d] = pe->pdir[d+1]; --pe->pdirs; } /*********************************************** *** C H A N G E A P A T H N A M E *** ***********************************************/ static void ccmd(char *inpath, char *path) /* change inpath to path */ { int n; struct pelem *pe; for (pe = pathhead; pe; pe = pe->pnext) { n = locate(pe, inpath); if (n >= 0) change(pe, n, path); else xprintf(CGETS(10, 4, "setpath: %s not found in %s\n"), inpath, pe->pname); } } static void cncmd(char *path, int n) /* change at position n to path */ { struct pelem *pe; for (pe = pathhead; pe; pe = pe->pnext) { if (n < pe->pdirs) change(pe, n, path); else xprintf(CGETS(10, 5, "setpath: %d not valid position in %s\n"), n, pe->pname); } } static void change(struct pelem *pe, int loc, char *key) { char *new; char newbuf[MAXPATHLEN+1];/*FIXBUF*/ if (sflag) { /* append suffix */ new = newbuf; (void) strcpy(new, key); (void) strcat(new, pe->psuf); } else new = key; new = strsave(new); xfree((ptr_t) (pe->pdir[loc])); pe->pdir[loc] = new; } /*************************************** *** F I N D P A T H N A M E *** ***************************************/ static int locate(struct pelem *pe, char *key) { int i; char *realkey; char keybuf[MAXPATHLEN+1];/*FIXBUF*/ if (sflag) { realkey = keybuf; (void) strcpy(realkey, key); (void) strcat(realkey, pe->psuf); } else realkey = key; for (i = 0; i < pe->pdirs; i++) if (strcmp(pe->pdir[i], realkey) == 0) break; return((i < pe->pdirs) ? i : -1); } #endif diff --git a/contrib/tcsh/mi.termios.c b/contrib/tcsh/mi.termios.c index d7863855b2ed..739b501f9f93 100644 --- a/contrib/tcsh/mi.termios.c +++ b/contrib/tcsh/mi.termios.c @@ -1,391 +1,391 @@ -/* termios.c - fake termios interface using sgtty interface +/* termios.c - fake termios interface using sgtty interface * by Magnus Doell and Bruce Evans. * */ #include "sh.h" #if defined(_MINIX) && !defined(_MINIX_VMD) /* Undefine everything that clashes with sgtty.h. */ #undef B0 #undef B50 #undef B75 #undef B110 #undef B134 #undef B150 #undef B200 #undef B300 #undef B600 #undef B1200 #undef B1800 #undef B2400 #undef B4800 #undef B9600 #undef B19200 #undef B28800 #undef B38400 #undef B57600 #undef B115200 /* Do not #undef CRMOD. We want a warning when they differ! */ #undef ECHO /* Do not #undef XTABS. We want a warning when they differ! */ /* Redefine some of the termios.h names just undefined with 'T_' prefixed * to the name. Don't bother with the low speeds - Minix does not support * them. Add support for higher speeds (speeds are now easy and don't need * defines because they are not encoded). */ #define T_ECHO 000001 #include #include static _PROTOTYPE( int tc_to_sg_speed, (speed_t speed) ); static _PROTOTYPE( speed_t sg_to_tc_speed, (int speed) ); #define B19200 192 /* The speed get/set functions could be macros in the Minix implementation * because there are speed fields in the structure with no fancy packing * and it is not practical to check the values outside the driver. * Where tests are necessary because the driver acts different from what * POSIX requires, they are done in tcsetattr. */ speed_t cfgetispeed(termios_p) struct termios *termios_p; { return termios_p->c_ispeed; } speed_t cfgetospeed(termios_p) struct termios *termios_p; { return termios_p->c_ospeed; } speed_t cfsetispeed(termios_p, speed) struct termios *termios_p; speed_t speed; { termios_p->c_ispeed = speed; return 0; } speed_t cfsetospeed(termios_p, speed) struct termios *termios_p; speed_t speed; { termios_p->c_ospeed = speed; return 0; } static speed_t sg_to_tc_speed(speed) int speed; { /* The speed encodings in sgtty.h and termios.h are different. Both are * inflexible. Minix doesn't really support B0 but we map it through * anyway. It doesn't support B50, B75 or B134. */ switch (speed) { case B0: return 0; case B110: return 110; case B200: return 200; case B300: return 300; case B600: return 600; case B1200: return 1200; case B1800: return 1800; case B2400: return 2400; case B4800: return 4800; case B9600: return 9600; case B19200: return 19200; #ifdef B28800 case B28800: return 28800; #endif #ifdef B38400 case B38400: return 38400; #endif #ifdef B57600 case B57600: return 57600; #endif #ifdef B115200 case B115200: return 115200; #endif default: return (speed_t)-1; } } static int tc_to_sg_speed(speed) speed_t speed; { /* Don't use a switch here in case the compiler is 16-bit and doesn't * properly support longs (speed_t's) in switches. It turns out the * switch is larger and slower for most compilers anyway! */ if (speed == 0) return 0; if (speed == 110) return B110; if (speed == 200) return B200; if (speed == 300) return B300; if (speed == 600) return B600; if (speed == 1200) return B1200; if (speed == 1800) return B1800; if (speed == 2400) return B2400; if (speed == 4800) return B4800; if (speed == 9600) return B9600; if (speed == 19200) return B19200; #ifdef B28800 if (speed == 28800) return B28800; #endif #ifdef B38400 if (speed == 38400) return B38400; #endif #ifdef B57600 if (speed == 57600) return B57600; #endif #ifdef B115200 if (speed == 115200) return B115200; #endif return -1; } int tcgetattr(filedes, termios_p) int filedes; struct termios *termios_p; { struct sgttyb sgbuf; struct tchars tcbuf; if (ioctl(filedes, TIOCGETP, &sgbuf) < 0 || ioctl(filedes, TIOCGETC, (struct sgttyb *) &tcbuf) < 0) { return -1; } /* Minix input flags: * BRKINT: forced off (break is not recognized) * IGNBRK: forced on (break is not recognized) * ICRNL: set if CRMOD is set and not RAW (CRMOD also controls output) * IGNCR: forced off (ignoring cr's is not supported) * INLCR: forced off (mapping nl's to cr's is not supported) * ISTRIP: forced off (should be off for consoles, on for rs232 no RAW) * IXOFF: forced off (rs232 uses CTS instead of XON/XOFF) * IXON: forced on if not RAW * PARMRK: forced off (no '\377', '\0', X sequence on errors) * ? IGNPAR: forced off (input with parity/framing errors is kept) * ? INPCK: forced off (input parity checking is not supported) */ termios_p->c_iflag = IGNBRK; if (!(sgbuf.sg_flags & RAW)) { termios_p->c_iflag |= IXON; if (sgbuf.sg_flags & CRMOD) { termios_p->c_iflag |= ICRNL; } } /* Minix output flags: * OPOST: set if CRMOD or XTABS is set * XTABS: copied from sg_flags * CRMOD: copied from sg_flags */ termios_p->c_oflag = sgbuf.sg_flags & (CRMOD | XTABS); if (termios_p->c_oflag) { termios_p->c_oflag |= OPOST; } /* Minix local flags: * ECHO: set if ECHO is set * ECHOE: set if ECHO is set (ERASE echoed as error-corecting backspace) * ECHOK: set if ECHO is set ('\n' echoed after KILL char) * ECHONL: forced off ('\n' not echoed when ECHO isn't set) * ICANON: set if neither CBREAK nor RAW * IEXTEN: forced off * ISIG: set if not RAW * NOFLSH: forced off (input/output queues are always flushed) * TOSTOP: forced off (no job control) */ termios_p->c_lflag = 0; if (sgbuf.sg_flags & ECHO) { termios_p->c_lflag |= T_ECHO | ECHOE | ECHOK; } if (!(sgbuf.sg_flags & RAW)) { termios_p->c_lflag |= ISIG; if (!(sgbuf.sg_flags & CBREAK)) { termios_p->c_lflag |= ICANON; } } /* Minix control flags: * CLOCAL: forced on (ignore modem status lines - not quite right) * CREAD: forced on (receiver is always enabled) * CSIZE: CS5-CS8 correspond directly to BITS5-BITS8 * CSTOPB: set for B110 (driver will generate 2 stop-bits than) * HUPCL: forced off * PARENB: set if EVENP or ODDP is set * PARODD: set if ODDP is set */ termios_p->c_cflag = CLOCAL | CREAD; switch (sgbuf.sg_flags & BITS8) { case BITS5: termios_p->c_cflag |= CS5; break; case BITS6: termios_p->c_cflag |= CS6; break; case BITS7: termios_p->c_cflag |= CS7; break; case BITS8: termios_p->c_cflag |= CS8; break; } if (sgbuf.sg_flags & ODDP) { termios_p->c_cflag |= PARENB | PARODD; } if (sgbuf.sg_flags & EVENP) { termios_p->c_cflag |= PARENB; } if (sgbuf.sg_ispeed == B110) { termios_p->c_cflag |= CSTOPB; } /* Minix may give back different input and output baudrates, * but only the input baudrate is valid for both. * As our termios emulation will fail, if input baudrate differs * from output baudrate, force them to be equal. * Otherwise it would be very suprisingly not to be able to set * the terminal back to the state returned by tcgetattr :). */ termios_p->c_ospeed = termios_p->c_ispeed = sg_to_tc_speed((unsigned char) sgbuf.sg_ispeed); /* Minix control characters correspond directly except VSUSP and the * important VMIN and VTIME are not really supported. */ termios_p->c_cc[VEOF] = tcbuf.t_eofc; termios_p->c_cc[VEOL] = tcbuf.t_brkc; termios_p->c_cc[VERASE] = sgbuf.sg_erase; termios_p->c_cc[VINTR] = tcbuf.t_intrc; termios_p->c_cc[VKILL] = sgbuf.sg_kill; termios_p->c_cc[VQUIT] = tcbuf.t_quitc; termios_p->c_cc[VSTART] = tcbuf.t_startc; termios_p->c_cc[VSTOP] = tcbuf.t_stopc; termios_p->c_cc[VMIN] = 1; termios_p->c_cc[VTIME] = 0; termios_p->c_cc[VSUSP] = 0; return 0; } int tcsetattr(filedes, opt_actions, termios_p) int filedes; int opt_actions; struct termios *termios_p; { struct sgttyb sgbuf; struct tchars tcbuf; int sgspeed; /* Posix 1003.1-1988 page 135 says: * Attempts to set unsupported baud rates shall be ignored, and it is * implementation-defined whether an error is returned by any or all of * cfsetispeed(), cfsetospeed(), or tcsetattr(). This refers both to * changes to baud rates not supported by the hardware, and to changes * setting the input and output baud rates to different values if the * hardware does not support it. * Ignoring means not to change the existing settings, doesn't it? */ if ((termios_p->c_ispeed != 0 && termios_p->c_ispeed != termios_p->c_ospeed) || (sgspeed = tc_to_sg_speed(termios_p->c_ospeed)) < 0) { errno = EINVAL; return -1; } sgbuf.sg_ispeed = sgbuf.sg_ospeed = sgspeed; sgbuf.sg_flags = 0; /* I don't know what should happen with requests that are not supported by * old Minix drivers and therefore cannot be emulated. * Returning an error may confuse the application (the values aren't really * invalid or unsupported by the hardware, they just couldn't be satisfied * by the driver). Not returning an error might be even worse because the * driver will act different to what the application requires it to act * after sucessfully setting the attributes as specified. * Settings that cannot be emulated fully include: * c_ospeed != 110 && c_cflag & CSTOPB * c_ospeed == 110 && ! c_cflag & CSTOPB * (c_cc[VMIN] != 1 || c_cc[VTIME] != 0) && ! c_lflag & ICANON * c_lflag & ICANON && ! c_lflag & ISIG * For the moment I just ignore these conflicts. */ if (termios_p->c_oflag & OPOST) { /* CRMOD isn't Posix and may conflict with ICRNL, which is Posix, * so we just ignore it. */ if (termios_p->c_oflag & XTABS) { sgbuf.sg_flags |= XTABS; } } if (termios_p->c_iflag & ICRNL) { /* We couldn't do it better :-(. */ sgbuf.sg_flags |= CRMOD; } if (termios_p->c_lflag & T_ECHO) { sgbuf.sg_flags |= ECHO; } if (!(termios_p->c_lflag & ICANON)) { if (termios_p->c_lflag & ISIG) { sgbuf.sg_flags |= CBREAK; } else { sgbuf.sg_flags |= RAW; } } switch (termios_p->c_cflag & CSIZE) { case CS5: sgbuf.sg_flags |= BITS5; break; case CS6: sgbuf.sg_flags |= BITS6; break; case CS7: sgbuf.sg_flags |= BITS7; break; case CS8: sgbuf.sg_flags |= BITS8; break; } if (termios_p->c_cflag & PARENB) { if (termios_p->c_cflag & PARODD) { sgbuf.sg_flags |= ODDP; } else { sgbuf.sg_flags |= EVENP; } } sgbuf.sg_erase = termios_p->c_cc[VERASE]; sgbuf.sg_kill = termios_p->c_cc[VKILL]; tcbuf.t_intrc = termios_p->c_cc[VINTR]; tcbuf.t_quitc = termios_p->c_cc[VQUIT]; tcbuf.t_startc = termios_p->c_cc[VSTART]; tcbuf.t_stopc = termios_p->c_cc[VSTOP]; tcbuf.t_eofc = termios_p->c_cc[VEOF]; tcbuf.t_brkc = termios_p->c_cc[VEOL]; return ioctl(filedes, TIOCSETP, &sgbuf) < 0 && ioctl(filedes, TIOCSETC, (struct sgttyb *) &tcbuf) < 0 ? -1 : 0; } #endif /* _MINIX && !_MINIX_VMD */ diff --git a/contrib/tcsh/mi.wait.h b/contrib/tcsh/mi.wait.h index 205ac6812df6..101adf6e648f 100644 --- a/contrib/tcsh/mi.wait.h +++ b/contrib/tcsh/mi.wait.h @@ -1,44 +1,44 @@ /* The header contains macros related to wait(). The value - * returned by wait() and waitpid() depends on whether the process + * returned by wait() and waitpid() depends on whether the process * terminated by an exit() call, was killed by a signal, or was stopped * due to job control, as follows: * * High byte Low byte * +---------------------+ * exit(status) | status | 0 | * +---------------------+ * killed by signal | 0 | signal | * +---------------------+ * stopped (job control) | signal | 0177 | * +---------------------+ */ #ifndef _WAIT_H #define _WAIT_H #ifndef _TYPES_H /* not quite right */ #include #endif #define __LOW(v) ((v) & 0377) #define __HIGH(v) (((v) >> 8) & 0377) #define WNOHANG 1 /* do not wait for child to exit */ #define WUNTRACED 2 /* for job control; not implemented */ #define WIFEXITED(s) (__LOW(s) == 0) /* normal exit */ #define WEXITSTATUS(s) (__HIGH(s)) /* exit status */ #define WTERMSIG(s) (__LOW(s) & 0177) /* sig value */ #define WIFSIGNALED(s) ((((unsigned int)(s)-1) & 0xFFFF) < 0xFF) /* signaled */ #define WIFSTOPPED(s) (__LOW(s) == 0177) /* stopped */ #define WSTOPSIG(s) (__HIGH(s) & 0377) /* stop signal */ /* Function Prototypes. */ #ifndef _ANSI_H #include #endif _PROTOTYPE( pid_t wait, (int *_stat_loc) ); _PROTOTYPE( pid_t waitpid, (pid_t _pid, int *_stat_loc, int _options) ); #endif /* _WAIT_H */ diff --git a/contrib/tcsh/patchlevel.h b/contrib/tcsh/patchlevel.h index 3c71e48b78f3..78cdf2023e56 100644 --- a/contrib/tcsh/patchlevel.h +++ b/contrib/tcsh/patchlevel.h @@ -1,13 +1,13 @@ /* * patchlevel.h: Our life story. */ #ifndef _h_patchlevel #define _h_patchlevel #define ORIGIN "Astron" #define REV 6 #define VERS 22 -#define PATCHLEVEL 03 -#define DATE "2020-11-18" +#define PATCHLEVEL 04 +#define DATE "2021-04-26" #endif /* _h_patchlevel */ diff --git a/contrib/tcsh/sh.c b/contrib/tcsh/sh.c index d888e8e91d21..4d3094bde463 100644 --- a/contrib/tcsh/sh.c +++ b/contrib/tcsh/sh.c @@ -1,2562 +1,2562 @@ /* * sh.c: Main shell routines */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #define EXTERN /* Intern */ #include "sh.h" #ifndef lint char copyright[] = "@(#) Copyright (c) 1991 The Regents of the University of California.\n\ All rights reserved.\n"; #endif /* not lint */ #include "tc.h" #include "ed.h" #include "tw.h" extern int MapsAreInited; extern int NLSMapsAreInited; /* * C Shell * * Bill Joy, UC Berkeley, California, USA * October 1978, May 1980 * * Jim Kulp, IIASA, Laxenburg, Austria * April 1980 * * Filename recognition added: * Ken Greer, Ind. Consultant, Palo Alto CA * October 1983. * * Karl Kleinpaste, Computer Consoles, Inc. * Added precmd, periodic/tperiod, prompt changes, * directory stack hack, and login watch. * Sometime March 1983 - Feb 1984. * * Added scheduled commands, including the "sched" command, * plus the call to sched_run near the precmd et al * routines. * Upgraded scheduled events for running events while * sitting idle at command input. * * Paul Placeway, Ohio State * added stuff for running with twenex/inputl 9 Oct 1984. * * ported to Apple Unix (TM) (OREO) 26 -- 29 Jun 1987 */ jmp_buf_t reslab IZERO_STRUCT; struct wordent paraml IZERO_STRUCT; static const char tcshstr[] = "tcsh"; struct sigaction parintr; /* Parents interrupt catch */ struct sigaction parterm; /* Parents terminate catch */ #ifdef TESLA int do_logout = 0; #endif /* TESLA */ int use_fork = 0; /* use fork() instead of vfork()? */ /* * Magic pointer values. Used to specify other invalid conditions aside * from null. */ static Char INVCHAR; Char *INVPTR = &INVCHAR; Char **INVPPTR = &INVPTR; static int fast = 0; static int mflag = 0; static int prompt = 1; int enterhist = 0; int tellwhat = 0; time_t t_period; Char *ffile = NULL; int dolzero = 0; int insource = 0; int exitset = 0; static time_t chktim; /* Time mail last checked */ char *progname; int tcsh; /* * This preserves the input state of the shell. It is used by * st_save and st_restore to manupulate shell state. */ struct saved_state { int insource; int OLDSTD; int SHIN; int SHOUT; int SHDIAG; int intty; struct whyle *whyles; Char *gointr; Char *arginp; Char *evalp; Char **evalvec; Char *alvecp; Char **alvec; int onelflg; int enterhist; Char **argv; Char **av; Char HIST; int cantell; struct Bin B; int justpr; }; static int srccat (Char *, Char *); #ifndef WINNT_NATIVE static int srcfile (const char *, int, int, Char **); #else int srcfile (const char *, int, int, Char **); #endif /*WINNT_NATIVE*/ static void srcunit (int, int, int, Char **); static void mailchk (void); #ifndef _PATH_DEFPATH static Char **defaultpath (void); #endif static void record (void); static void st_save (struct saved_state *, int, int, Char **, Char **); static void st_restore (void *); int main (int, char **); #ifndef LOCALEDIR #define LOCALEDIR "/usr/share/locale" #endif #ifdef NLS_CATALOGS static void add_localedir_to_nlspath(const char *path) { static const char msgs_LOC[] = "/%L/LC_MESSAGES/%N.cat"; static const char msgs_lang[] = "/%l/LC_MESSAGES/%N.cat"; char *old; char *new, *new_p; size_t len; int add_LOC = 1; int add_lang = 1; char trypath[MAXPATHLEN]; struct stat st; if (path == NULL) return; (void) xsnprintf(trypath, sizeof(trypath), "%s/C/LC_MESSAGES/tcsh.cat", path); if (stat(trypath, &st) == -1) return; if ((old = getenv("NLSPATH")) != NULL) len = strlen(old) + 1; /* don't forget the colon. */ else len = 0; len += 2 * strlen(path) + sizeof(msgs_LOC) + sizeof(msgs_lang); /* includes the extra colon */ new = new_p = xcalloc(len, 1); if (old != NULL) { size_t pathlen = strlen(path); char *old_p; (void) xsnprintf(new_p, len, "%s", old); new_p += strlen(new_p); len -= new_p - new; /* Check if the paths we try to add are already present in NLSPATH. If so, note it by setting the appropriate flag to 0. */ for (old_p = old; old_p; old_p = strchr(old_p, ':'), old_p = old_p ? old_p + 1 : NULL) { if (strncmp(old_p, path, pathlen) != 0) continue; if (strncmp(old_p + pathlen, msgs_LOC, sizeof(msgs_LOC) - 1) == 0) add_LOC = 0; else if (strncmp(old_p + pathlen, msgs_lang, sizeof(msgs_lang) - 1) == 0) add_lang = 0; } } /* Add the message catalog paths not already present to NLSPATH. */ if (add_LOC || add_lang) (void) xsnprintf(new_p, len, "%s%s%s%s%s%s", old ? ":" : "", add_LOC ? path : "", add_LOC ? msgs_LOC : "", add_LOC && add_lang ? ":" : "", add_lang ? path : "", add_lang ? msgs_lang : ""); tsetenv(STRNLSPATH, str2short(new)); free(new); } #endif int main(int argc, char **argv) { int batch = 0; volatile int nexececho = 0; int nofile = 0; volatile int nverbose = 0; volatile int rdirs = 0; volatile int exitcode = 0; int quitit = 0; Char *cp; #ifdef AUTOLOGOUT Char *cp2; #endif char *tcp, *ttyn; int f, reenter; char **tempv; static const char *targinp = NULL; int osetintr; struct sigaction oparintr; #ifdef WINNT_NATIVE nt_init(); #endif /* WINNT_NATIVE */ (void)memset(&reslab, 0, sizeof(reslab)); #if defined(NLS_CATALOGS) && defined(LC_MESSAGES) (void) setlocale(LC_MESSAGES, ""); #endif /* NLS_CATALOGS && LC_MESSAGES */ #ifdef NLS # ifdef LC_CTYPE (void) setlocale(LC_CTYPE, ""); /* for iscntrl */ # endif /* LC_CTYPE */ #endif /* NLS */ STR_environ = blk2short(environ); environ = short2blk(STR_environ); /* So that we can free it */ #ifdef NLS_CATALOGS add_localedir_to_nlspath(LOCALEDIR); #endif nlsinit(); initlex(¶ml); #ifdef MALLOC_TRACE - mal_setstatsfile(fdopen(dmove(xopen("/tmp/tcsh.trace", + mal_setstatsfile(fdopen(dmove(xopen("/tmp/tcsh.trace", O_WRONLY|O_CREAT|O_LARGEFILE, 0666), 25), "w")); mal_trace(1); #endif /* MALLOC_TRACE */ #if !(defined(BSDTIMES) || defined(_SEQUENT_)) && defined(POSIX) # ifdef _SC_CLK_TCK clk_tck = (clock_t) sysconf(_SC_CLK_TCK); # else /* ! _SC_CLK_TCK */ # ifdef CLK_TCK clk_tck = CLK_TCK; # else /* !CLK_TCK */ clk_tck = HZ; # endif /* CLK_TCK */ # endif /* _SC_CLK_TCK */ #endif /* !BSDTIMES && POSIX */ settimes(); /* Immed. estab. timing base */ #ifdef TESLA do_logout = 0; #endif /* TESLA */ /* * Make sure we have 0, 1, 2 open * Otherwise `` jobs will not work... (From knaff@poly.polytechnique.fr) */ { - do + do if ((f = xopen(_PATH_DEVNULL, O_RDONLY|O_LARGEFILE)) == -1 && - (f = xopen("/", O_RDONLY|O_LARGEFILE)) == -1) + (f = xopen("/", O_RDONLY|O_LARGEFILE)) == -1) exit(1); while (f < 3); xclose(f); } osinit(); /* Os dependent initialization */ - + { char *t; t = strrchr(argv[0], '/'); #ifdef WINNT_NATIVE { char *s = strrchr(argv[0], '\\'); if (s) t = s; } #endif /* WINNT_NATIVE */ t = t ? t + 1 : argv[0]; if (*t == '-') t++; progname = strsave((t && *t) ? t : tcshstr); /* never want a null */ tcsh = strncmp(progname, tcshstr, sizeof(tcshstr) - 1) == 0; } /* * Initialize non constant strings */ #ifdef _PATH_BSHELL STR_BSHELL = SAVE(_PATH_BSHELL); #endif #ifdef _PATH_TCSHELL STR_SHELLPATH = SAVE(_PATH_TCSHELL); #else # ifdef _PATH_CSHELL STR_SHELLPATH = SAVE(_PATH_CSHELL); # endif #endif STR_WORD_CHARS = SAVE(WORD_CHARS); STR_WORD_CHARS_VI = SAVE(WORD_CHARS_VI); HIST = '!'; HISTSUB = '^'; PRCH = tcsh ? '>' : '%'; /* to replace %# in $prompt for normal users */ PRCHROOT = '#'; /* likewise for root */ word_chars = STR_WORD_CHARS; bslash_quote = 0; /* PWP: do tcsh-style backslash quoting? */ anyerror = 1; /* for compatibility */ setcopy(STRanyerror, STRNULL, VAR_READWRITE); /* Default history size to 100 */ setcopy(STRhistory, str2short("100"), VAR_READWRITE); sethistory(100); tempv = argv; ffile = SAVE(tempv[0]); dolzero = 0; if (eq(ffile, STRaout)) /* A.out's are quittable */ quitit = 1; uid = getuid(); gid = getgid(); euid = geteuid(); egid = getegid(); /* * We are a login shell if: 1. we were invoked as - with * optional arguments 2. or we were invoked only with the -l flag */ loginsh = (**tempv == '-') || (argc == 2 && tempv[1][0] == '-' && tempv[1][1] == 'l' && tempv[1][2] == '\0'); #ifdef _VMS_POSIX /* No better way to find if we are a login shell */ if (!loginsh) { loginsh = (argc == 1 && getppid() == 1); **tempv = '-'; /* Avoid giving VMS an acidic stomach */ } #endif /* _VMS_POSIX */ if (loginsh && **tempv != '-') { char *argv0; /* * Mangle the argv space */ tempv[1][0] = '\0'; tempv[1][1] = '\0'; tempv[1] = NULL; argv0 = strspl("-", *tempv); *tempv = argv0; argc--; } if (loginsh) { (void) time(&chktim); setNS(STRloginsh); } NoNLSRebind = getenv("NOREBIND") != NULL; #ifdef NLS # ifdef SETLOCALEBUG dont_free = 1; # endif /* SETLOCALEBUG */ (void) setlocale(LC_ALL, ""); # ifdef LC_COLLATE (void) setlocale(LC_COLLATE, ""); # endif # ifdef SETLOCALEBUG dont_free = 0; # endif /* SETLOCALEBUG */ # ifdef STRCOLLBUG fix_strcoll_bug(); # endif /* STRCOLLBUG */ /* * On solaris ISO8859-1 contains no printable characters in the upper half * so we need to test only for MB_CUR_MAX == 1, otherwise for multi-byte * locales we are always AsciiOnly == 0. */ if (MB_CUR_MAX == 1) { int k; for (k = 0200; k <= 0377 && !isprint(CTL_ESC(k)); k++) continue; AsciiOnly = k > 0377; } else AsciiOnly = 0; #else AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL; #endif /* NLS */ if (MapsAreInited && !NLSMapsAreInited) ed_InitNLSMaps(); ResetArrowKeys(); /* * Initialize for periodic command intervals. Also, initialize the dummy * tty list for login-watch. */ (void) time(&t_period); #ifndef HAVENOUTMP initwatch(); #endif /* !HAVENOUTMP */ #if defined(alliant) /* * From: Jim Pace * tcsh does not work properly on the alliants through an rlogin session. * The shell generally hangs. Also, reference to the controlling terminal * does not work ( ie: echo foo > /dev/tty ). * * A security feature was added to rlogind affecting FX/80's Concentrix * from revision 5.5.xx upwards (through 5.7 where this fix was implemented) * This security change also affects the FX/2800 series. * The security change to rlogind requires the process group of an rlogin * session become disassociated with the tty in rlogind. * * The changes needed are: * 1. set the process group * 2. reenable the control terminal */ if (loginsh && isatty(SHIN)) { ttyn = ttyname(SHIN); xclose(SHIN); SHIN = xopen(ttyn, O_RDWR|O_LARGEFILE); shpgrp = getpid(); (void) ioctl (SHIN, TIOCSPGRP, (ioctl_t) &shpgrp); (void) setpgid(0, shpgrp); } #endif /* alliant */ /* * Move the descriptors to safe places. The variable didfds is 0 while we * have only FSH* to work with. When didfds is true, we have 0,1,2 and * prefer to use these. */ initdesc(); cdtohome = 1; setv(STRcdtohome, SAVE(""), VAR_READWRITE); /* * Get and set the tty now */ if ((ttyn = ttyname(SHIN)) != NULL) { /* * Could use rindex to get rid of other possible path components, but * hpux preserves the subdirectory /pty/ when storing the tty name in * utmp, so we keep it too. */ if (strncmp(ttyn, "/dev/", 5) == 0) setv(STRtty, cp = SAVE(ttyn + 5), VAR_READWRITE); else setv(STRtty, cp = SAVE(ttyn), VAR_READWRITE); } else setv(STRtty, cp = SAVE(""), VAR_READWRITE); /* * Initialize the shell variables. ARGV and PROMPT are initialized later. * STATUS is also munged in several places. CHILD is munged when * forking/waiting */ /* * 7-10-87 Paul Placeway autologout should be set ONLY on login shells and * on shells running as root. Out of these, autologout should NOT be set * for any psudo-terminals (this catches most window systems) and not for * any terminal running X windows. - * - * At Ohio State, we have had problems with a user having his X session - * drop out from under him (on a Sun) because the shell in his master + * + * At Ohio State, we have had problems with a user having his X session + * drop out from under him (on a Sun) because the shell in his master * xterm timed out and exited. - * + * * Really, this should be done with a program external to the shell, that * watches for no activity (and NO running programs, such as dump) on a * terminal for a long peroid of time, and then SIGHUPS the shell on that * terminal. - * - * bugfix by Rich Salz : For root rsh things - * allways first check to see if loginsh or really root, then do things + * + * bugfix by Rich Salz : For root rsh things + * allways first check to see if loginsh or really root, then do things * with ttyname() - * + * * Also by Jean-Francois Lamy : check the * value of cp before using it! ("root can rsh too") - * - * PWP: keep the nested ifs; the order of the tests matters and a good + * + * PWP: keep the nested ifs; the order of the tests matters and a good * (smart) C compiler might re-arange things wrong. */ #ifdef AUTOLOGOUT # ifdef convex if (uid == 0) /* root always has a 15 minute autologout */ setcopy(STRautologout, STRrootdefautologout, VAR_READWRITE); else if (loginsh) /* users get autologout set to 0 */ setcopy(STRautologout, STR0, VAR_READWRITE); # else /* convex */ if (loginsh || (uid == 0)) { if (*cp) { /* only for login shells or root and we must have a tty */ if (((cp2 = Strrchr(cp, (Char) '/')) != NULL) && (Strncmp(cp, STRptssl, 3) != 0)) { cp2 = cp2 + 1; } else cp2 = cp; if (!(((Strncmp(cp2, STRtty, 3) == 0) && Isalpha(cp2[3])) || Strstr(cp, STRptssl) != NULL)) { if (getenv("DISPLAY") == NULL) { /* NOT on X window shells */ setcopy(STRautologout, STRdefautologout, VAR_READWRITE); } } } } # endif /* convex */ #endif /* AUTOLOGOUT */ sigset_interrupting(SIGALRM, queue_alrmcatch); setcopy(STRstatus, STR0, VAR_READWRITE); /* * get and set machine specific environment variables */ getmachine(); /* * Publish the selected echo style */ #if ECHO_STYLE != BSD_ECHO if (tcsh) { # if ECHO_STYLE == NONE_ECHO setcopy(STRecho_style, STRnone, VAR_READWRITE); # endif /* ECHO_STYLE == NONE_ECHO */ # if ECHO_STYLE == SYSV_ECHO setcopy(STRecho_style, STRsysv, VAR_READWRITE); # endif /* ECHO_STYLE == SYSV_ECHO */ # if ECHO_STYLE == BOTH_ECHO setcopy(STRecho_style, STRboth, VAR_READWRITE); # endif /* ECHO_STYLE == BOTH_ECHO */ } else #endif /* ECHO_STYLE != BSD_ECHO */ setcopy(STRecho_style, STRbsd, VAR_READWRITE); /* * increment the shell level. */ shlvl(1); #ifdef __ANDROID__ /* On Android, $HOME either isn't set or set to /data, a R/O location. Check for the environment variable EXTERNAL_STORAGE, which contains the mount point of the external storage (SD card, mostly). If EXTERNAL_STORAGE isn't set fall back to "/sdcard". Eventually override $HOME so the environment is on the same page. */ if (((tcp = getenv("HOME")) != NULL && strcmp (tcp, "/data") != 0) || (tcp = getenv("EXTERNAL_STORAGE")) != NULL) { cp = quote(SAVE(tcp)); } else cp = quote(SAVE("/sdcard")); tsetenv(STRKHOME, cp); #else if ((tcp = getenv("HOME")) != NULL) cp = quote(SAVE(tcp)); else cp = NULL; #endif if (cp == NULL) fast = 1; /* No home -> can't read scripts */ else setv(STRhome, cp, VAR_READWRITE); dinit(cp); /* dinit thinks that HOME == cwd in a login * shell */ /* * Grab other useful things from the environment. Should we grab * everything?? */ { char *cln, *cus, *cgr; struct passwd *pw; struct group *gr; #ifdef apollo int oid = getoid(); setv(STRoid, Itoa(oid, 0, 0), VAR_READWRITE); #endif /* apollo */ setv(STReuid, Itoa(euid, 0, 0), VAR_READWRITE); if ((pw = xgetpwuid(euid)) == NULL) setcopy(STReuser, STRunknown, VAR_READWRITE); else setcopy(STReuser, str2short(pw->pw_name), VAR_READWRITE); setv(STRuid, Itoa(uid, 0, 0), VAR_READWRITE); setv(STRgid, Itoa(gid, 0, 0), VAR_READWRITE); cln = getenv("LOGNAME"); cus = getenv("USER"); if (cus != NULL) setv(STRuser, quote(SAVE(cus)), VAR_READWRITE); else if (cln != NULL) setv(STRuser, quote(SAVE(cln)), VAR_READWRITE); else if ((pw = xgetpwuid(uid)) == NULL) setcopy(STRuser, STRunknown, VAR_READWRITE); else setcopy(STRuser, str2short(pw->pw_name), VAR_READWRITE); if (cln == NULL) tsetenv(STRLOGNAME, varval(STRuser)); if (cus == NULL) tsetenv(STRKUSER, varval(STRuser)); - + cgr = getenv("GROUP"); if (cgr != NULL) setv(STRgroup, quote(SAVE(cgr)), VAR_READWRITE); else if ((gr = xgetgrgid(gid)) == NULL) setcopy(STRgroup, STRunknown, VAR_READWRITE); else setcopy(STRgroup, str2short(gr->gr_name), VAR_READWRITE); if (cgr == NULL) tsetenv(STRKGROUP, varval(STRgroup)); } /* * HOST may be wrong, since rexd transports the entire environment on sun * 3.x Just set it again */ { char cbuff[MAXHOSTNAMELEN]; if (gethostname(cbuff, sizeof(cbuff)) >= 0) { cbuff[sizeof(cbuff) - 1] = '\0'; /* just in case */ tsetenv(STRHOST, str2short(cbuff)); } else tsetenv(STRHOST, STRunknown); } #ifdef REMOTEHOST /* * Try to determine the remote host we were logged in from. */ remotehost(); #endif /* REMOTEHOST */ - + #ifdef apollo if ((tcp = getenv("SYSTYPE")) == NULL) tcp = "bsd4.3"; tsetenv(STRSYSTYPE, quote(str2short(tcp))); #endif /* apollo */ /* * set editing on by default, unless running under Emacs as an inferior * shell. * We try to do this intelligently. If $TERM is available, then it * should determine if we should edit or not. $TERM is preserved * across rlogin sessions, so we will not get confused if we rlogin * under an emacs shell. Another advantage is that if we run an - * xterm under an emacs shell, then the $TERM will be set to + * xterm under an emacs shell, then the $TERM will be set to * xterm, so we are going to want to edit. Unfortunately emacs * does not restore all the tty modes, so xterm is not very well * set up. But this is not the shell's fault. * Also don't edit if $TERM == wm, for when we're running under an ATK app. * Finally, emacs compiled under terminfo, sets the terminal to dumb, * so disable editing for that too. - * + * * Unfortunately, in some cases the initial $TERM setting is "unknown", * "dumb", or "network" which is then changed in the user's startup files. * We fix this by setting noediting here if $TERM is unknown/dumb and * if noediting is set, we switch on editing if $TERM is changed. */ if ((tcp = getenv("TERM")) != NULL) { setv(STRterm, quote(SAVE(tcp)), VAR_READWRITE); noediting = strcmp(tcp, "unknown") == 0 || strcmp(tcp, "dumb") == 0 || strcmp(tcp, "network") == 0; editing = strcmp(tcp, "emacs") != 0 && strcmp(tcp, "wm") != 0 && !noediting; } else { noediting = 0; editing = ((tcp = getenv("EMACS")) == NULL || strcmp(tcp, "t") != 0); } - /* - * The 'edit' variable is either set or unset. It doesn't - * need a value. Making it 'emacs' might be confusing. + /* + * The 'edit' variable is either set or unset. It doesn't + * need a value. Making it 'emacs' might be confusing. */ if (editing) setNS(STRedit); /* * still more mutability: make the complete routine automatically add the * suffix of file names... */ setNS(STRaddsuffix); /* * Compatibility with tcsh >= 6.12 by default */ setNS(STRcsubstnonl); - + /* * Random default kill ring size */ setcopy(STRkillring, str2short("30"), VAR_READWRITE); /* * Re-initialize path if set in environment */ if ((tcp = getenv("PATH")) == NULL) #ifdef _PATH_DEFPATH importpath(str2short(_PATH_DEFPATH)); #else /* !_PATH_DEFPATH */ setq(STRpath, defaultpath(), &shvhed, VAR_READWRITE); #endif /* _PATH_DEFPATH */ else /* Importpath() allocates memory for the path, and the * returned pointer from SAVE() was discarded, so * this was a memory leak.. (sg) * * importpath(SAVE(tcp)); */ importpath(str2short(tcp)); { /* If the SHELL environment variable ends with "tcsh", set * STRshell to the same path. This is to facilitate using * the executable in environments where the compiled-in * default isn't appropriate (sg). */ size_t sh_len = 0; if ((tcp = getenv("SHELL")) != NULL) { sh_len = strlen(tcp); - if ((sh_len >= 5 && strcmp(tcp + (sh_len - 5), "/tcsh") == 0) || + if ((sh_len >= 5 && strcmp(tcp + (sh_len - 5), "/tcsh") == 0) || (!tcsh && sh_len >= 4 && strcmp(tcp + (sh_len - 4), "/csh") == 0)) setv(STRshell, quote(SAVE(tcp)), VAR_READWRITE); else sh_len = 0; } if (sh_len == 0) setcopy(STRshell, STR_SHELLPATH, VAR_READWRITE); } #ifdef _OSD_POSIX /* BS2000 needs this variable set to "SHELL" */ if ((tcp = getenv("PROGRAM_ENVIRONMENT")) == NULL) tcp = "SHELL"; tsetenv(STRPROGRAM_ENVIRONMENT, quote(str2short(tcp))); #endif /* _OSD_POSIX */ #ifdef COLOR_LS_F if ((tcp = getenv("LS_COLORS")) != NULL) parseLS_COLORS(str2short(tcp)); if ((tcp = getenv("LSCOLORS")) != NULL) parseLSCOLORS(str2short(tcp)); #endif /* COLOR_LS_F */ mainpid = getpid(); doldol = putn((tcsh_number_t)mainpid); /* For $$ */ #ifdef WINNT_NATIVE { char *tmp; Char *tmp2; if ((tmp = getenv("TMP")) != NULL) { tmp = xasprintf("%s/%s", tmp, "sh"); tmp2 = SAVE(tmp); xfree(tmp); } else { - tmp2 = SAVE(""); + tmp2 = SAVE(""); } shtemp = Strspl(tmp2, doldol); /* For << */ xfree(tmp2); } #else /* !WINNT_NATIVE */ #ifdef HAVE_MKSTEMP { const char *tmpdir = getenv ("TMPDIR"); if (!tmpdir) tmpdir = "/tmp"; shtemp = Strspl(SAVE(tmpdir), SAVE("/sh" TMP_TEMPLATE)); /* For << */ } #else /* !HAVE_MKSTEMP */ shtemp = Strspl(STRtmpsh, doldol); /* For << */ #endif /* HAVE_MKSTEMP */ #endif /* WINNT_NATIVE */ /* * Record the interrupt states from the parent process. If the parent is * non-interruptible our hand must be forced or we (and our children) won't * be either. Our children inherit termination from our parent. We catch it * only if we are the login shell. */ sigaction(SIGINT, NULL, &parintr); sigaction(SIGTERM, NULL, &parterm); #ifdef TCF /* Enable process migration on ourselves and our progeny */ (void) signal(SIGMIGRATE, SIG_DFL); #endif /* TCF */ /* * dspkanji/dspmbyte autosetting */ /* PATCH IDEA FROM Issei.Suzuki VERY THANKS */ #if defined(DSPMBYTE) #if defined(NLS) && defined(LC_CTYPE) if (((tcp = setlocale(LC_CTYPE, NULL)) != NULL || (tcp = getenv("LANG")) != NULL) && !adrof(CHECK_MBYTEVAR)) #else if ((tcp = getenv("LANG")) != NULL && !adrof(CHECK_MBYTEVAR)) #endif { autoset_dspmbyte(str2short(tcp)); } #if defined(WINNT_NATIVE) else if (!adrof(CHECK_MBYTEVAR)) nt_autoset_dspmbyte(); #endif /* WINNT_NATIVE */ #endif -#if defined(AUTOSET_KANJI) +#if defined(AUTOSET_KANJI) # if defined(NLS) && defined(LC_CTYPE) if (setlocale(LC_CTYPE, NULL) != NULL || getenv("LANG") != NULL) # else if (getenv("LANG") != NULL) # endif autoset_kanji(); #endif /* AUTOSET_KANJI */ fix_version(); /* publish the shell version */ if (argc > 1 && strcmp(argv[1], "--version") == 0) { xprintf("%S\n", varval(STRversion)); xexit(0); } if (argc > 1 && strcmp(argv[1], "--help") == 0) { xprintf("%S\n\n", varval(STRversion)); xprintf("%s", CGETS(11, 8, HELP_STRING)); xexit(0); } /* * Process the arguments. - * + * * Note that processing of -v/-x is actually delayed till after script * processing. - * - * We set the first character of our name to be '-' if we are a shell - * running interruptible commands. Many programs which examine ps'es + * + * We set the first character of our name to be '-' if we are a shell + * running interruptible commands. Many programs which examine ps'es * use this to filter such shells out. */ argc--, tempv++; while (argc > 0 && (tcp = tempv[0])[0] == '-' && *++tcp != '\0' && !batch) { do switch (*tcp++) { case 0: /* - Interruptible, no prompt */ prompt = 0; setintr = 1; nofile = 1; break; case 'b': /* -b Next arg is input file */ batch = 1; break; case 'c': /* -c Command input from arg */ if (argc == 1) xexit(0); argc--, tempv++; #ifdef M_XENIX /* Xenix Vi bug: it relies on a 7 bit environment (/bin/sh), so it pass ascii arguments with the 8th bit set */ if (!strcmp(argv[0], "sh")) { char *p; for (p = tempv[0]; *p; ++p) *p &= ASCII; } #endif targinp = tempv[0]; prompt = 0; nofile = 1; break; case 'd': /* -d Load directory stack from file */ rdirs = 1; break; #ifdef apollo case 'D': /* -D Define environment variable */ { Char *dp; cp = str2short(tcp); if (dp = Strchr(cp, '=')) { *dp++ = '\0'; tsetenv(cp, dp); } else tsetenv(cp, STRNULL); } *tcp = '\0'; /* done with this argument */ break; #endif /* apollo */ case 'e': /* -e Exit on any error */ exiterr = 1; break; case 'f': /* -f Fast start */ fast = 1; break; case 'i': /* -i Interactive, even if !intty */ intact = 1; nofile = 1; break; case 'm': /* -m read .cshrc (from su) */ mflag = 1; break; case 'n': /* -n Don't execute */ noexec = 1; break; case 'q': /* -q (Undoc'd) ... die on quit */ quitit = 1; break; case 's': /* -s Read from std input */ nofile = 1; break; case 't': /* -t Read one line from input */ onelflg = 2; prompt = 0; nofile = 1; break; case 'v': /* -v Echo hist expanded input */ nverbose = 1; /* ... later */ break; case 'x': /* -x Echo just before execution */ nexececho = 1; /* ... later */ break; case 'V': /* -V Echo hist expanded input */ setNS(STRverbose); /* NOW! */ break; case 'X': /* -X Echo just before execution */ setNS(STRecho); /* NOW! */ break; case 'F': /* * This will cause children to be created using fork instead of * vfork. */ use_fork = 1; break; case ' ': case '\t': case '\r': case '\n': - /* - * for O/S's that don't do the argument parsing right in + /* + * for O/S's that don't do the argument parsing right in * "#!/foo -f " scripts */ break; default: /* Unknown command option */ exiterr = 1; stderror(ERR_TCSHUSAGE, tcp-1, progname); break; } while (*tcp); tempv++, argc--; } if (quitit) /* With all due haste, for debugging */ (void) signal(SIGQUIT, SIG_DFL); /* * Unless prevented by -, -c, -i, -s, or -t, if there are remaining * arguments the first of them is the name of a shell file from which to * read commands. */ if (nofile == 0 && argc > 0) { nofile = xopen(tempv[0], O_RDONLY|O_LARGEFILE); if (nofile < 0) { child = 1; /* So this ... */ /* ... doesn't return */ stderror(ERR_SYSTEM, tempv[0], strerror(errno)); } xfree(ffile); dolzero = 1; ffile = SAVE(tempv[0]); - /* + /* * Replace FSHIN. Handle /dev/std{in,out,err} specially * since once they are closed we cannot open them again. * In that case we use our own saved descriptors */ - if ((SHIN = dmove(nofile, FSHIN)) < 0) + if ((SHIN = dmove(nofile, FSHIN)) < 0) switch(nofile) { case 0: SHIN = FSHIN; break; case 1: SHIN = FSHOUT; break; case 2: SHIN = FSHDIAG; break; default: stderror(ERR_SYSTEM, tempv[0], strerror(errno)); break; } (void) close_on_exec(SHIN, 1); prompt = 0; /* argc not used any more */ tempv++; } - /* + /* * Call to closem() used to be part of initdesc(). Now called below where * the script name argument has become stdin. Kernel may have used a file * descriptor to hold the name of the script (setuid case) and this name * mustn't be lost by closing the fd too soon. */ closem(); /* * Consider input a tty if it really is or we are interactive. but not for * editing (christos) */ if (!(intty = isatty(SHIN))) { if (adrof(STRedit)) unsetv(STRedit); editing = 0; } intty |= intact; #ifndef convex if (intty || (intact && isatty(SHOUT))) { if (!batch && (uid != euid || gid != egid)) { errno = EACCES; child = 1; /* So this ... */ /* ... doesn't return */ stderror(ERR_SYSTEM, progname, strerror(errno)); } } #endif /* convex */ isoutatty = isatty(SHOUT); isdiagatty = isatty(SHDIAG); /* * Decide whether we should play with signals or not. If we are explicitly * told (via -i, or -) or we are a login shell (arg0 starts with -) or the * input and output are both the ttys("csh", or "csh/dev/ttyx") * Note that in only the login shell is it likely that parent may have set * signals to be ignored */ if (loginsh || intact || (intty && isatty(SHOUT))) setintr = 1; settell(); /* * Save the remaining arguments in argv. */ setq(STRargv, blk2short(tempv), &shvhed, VAR_READWRITE); /* * Set up the prompt. */ if (prompt) { setcopy(STRprompt, STRdefprompt, VAR_READWRITE); /* that's a meta-questionmark */ setcopy(STRprompt2, STRmquestion, VAR_READWRITE); setcopy(STRprompt3, STRKCORRECT, VAR_READWRITE); } /* * If we are an interactive shell, then start fiddling with the signals; * this is a tricky game. */ shpgrp = mygetpgrp(); opgrp = tpgrp = -1; if (setintr) { struct sigaction osig; **argv = '-'; if (!quitit) /* Wary! */ (void) signal(SIGQUIT, SIG_IGN); pintr_disabled = 1; sigset_interrupting(SIGINT, queue_pintr); (void) signal(SIGTERM, SIG_IGN); - /* + /* * No reason I can see not to save history on all these events.. * Most usual occurrence is in a window system, where we're not a login * shell, but might as well be... (sg) * But there might be races when lots of shells exit together... * [this is also incompatible]. - * We have to be mre careful here. If the parent wants to + * We have to be mre careful here. If the parent wants to * ignore the signals then we leave them untouched... * We also only setup the handlers for shells that are trully * interactive. */ sigaction(SIGHUP, NULL, &osig); if (loginsh || osig.sa_handler != SIG_IGN) /* exit processing on HUP */ sigset_interrupting(SIGHUP, queue_phup); #ifdef SIGXCPU sigaction(SIGXCPU, NULL, &osig); if (loginsh || osig.sa_handler != SIG_IGN) /* exit processing on XCPU */ sigset_interrupting(SIGXCPU, queue_phup); #endif #ifdef SIGXFSZ sigaction(SIGXFSZ, NULL, &osig); if (loginsh || osig.sa_handler != SIG_IGN) /* exit processing on XFSZ */ sigset_interrupting(SIGXFSZ, queue_phup); #endif if (quitit == 0 && targinp == 0) { #ifdef SIGTSTP (void) signal(SIGTSTP, SIG_IGN); #endif #ifdef SIGTTIN (void) signal(SIGTTIN, SIG_IGN); #endif #ifdef SIGTTOU (void) signal(SIGTTOU, SIG_IGN); #endif /* * Wait till in foreground, in case someone stupidly runs csh & * dont want to try to grab away the tty. */ if (isatty(FSHDIAG)) f = FSHDIAG; else if (isatty(FSHOUT)) f = FSHOUT; else if (isatty(OLDSTD)) f = OLDSTD; else f = -1; #ifdef NeXT /* NeXT 2.0 /usr/etc/rlogind, does not set our process group! */ if (f != -1 && shpgrp == 0) { shpgrp = getpid(); (void) setpgid(0, shpgrp); (void) tcsetpgrp(f, shpgrp); } #endif /* NeXT */ #ifdef BSDJOBS /* if we have tty job control */ if (f != -1 && grabpgrp(f, shpgrp) != -1) { /* * Thanks to Matt Day for the POSIX references, and to * Paul Close for the SGI clarification. */ if (setdisc(f) != -1) { opgrp = shpgrp; shpgrp = getpid(); tpgrp = shpgrp; if (tcsetpgrp(f, shpgrp) == -1) { /* * On hpux 7.03 this fails with EPERM. This happens on * the 800 when opgrp != shpgrp at this point. (we were * forked from a non job control shell) * POSIX 7.2.4, says we failed because the process * group specified did not belong to a process * in the same session with the tty. So we set our * process group and try again. */ if (setpgid(0, shpgrp) == -1) { xprintf("setpgid:"); goto notty; } if (tcsetpgrp(f, shpgrp) == -1) { xprintf("tcsetpgrp:"); goto notty; } } /* * We check the process group now. If it is the same, then * we don't need to set it again. On hpux 7.0 on the 300's * if we set it again it fails with EPERM. This is the * correct behavior according to POSIX 4.3.3 if the process * was a session leader . */ else if (shpgrp != mygetpgrp()) { if (setpgid(0, shpgrp) == -1) { xprintf("setpgid:"); goto notty; } } #ifdef IRIS4D /* * But on irix 3.3 we need to set it again, even if it is * the same. We do that to tell the system that we * need BSD process group compatibility. */ else (void) setpgid(0, shpgrp); #endif (void) close_on_exec(dcopy(f, FSHTTY), 1); } else tpgrp = -1; } if (tpgrp == -1) { notty: xprintf(CGETS(11, 1, "Warning: no access to tty (%s).\n"), strerror(errno)); xprintf("%s", CGETS(11, 2, "Thus no job control in this shell.\n")); /* * Fix from:Sakari Jalovaara if we don't * have access to tty, disable editing too */ if (adrof(STRedit)) unsetv(STRedit); editing = 0; } #else /* BSDJOBS */ /* don't have job control, so frotz it */ tpgrp = -1; #endif /* BSDJOBS */ } } if (setintr == 0 && parintr.sa_handler == SIG_DFL) setintr = 1; /* * SVR4 doesn't send a SIGCHLD when a child is stopped or continued if the * handler is installed with signal(2) or sigset(2). sigaction(2) must * be used instead. * * David Dawes (dawes@physics.su.oz.au) Sept 1991 */ sigset_interrupting(SIGCHLD, queue_pchild); - if (intty && !targinp) + if (intty && !targinp) (void) ed_Setup(editing);/* Get the tty state, and set defaults */ /* Only alter the tty state if editing */ - + /* * Set an exit here in case of an interrupt or error reading the shell * start-up scripts. */ osetintr = setintr; oparintr = parintr; (void)cleanup_push_mark(); /* There is no outer handler */ if (setexit() != 0) /* PWP */ reenter = 1; else reenter = 0; exitset++; haderr = 0; /* In case second time through */ if (!fast && reenter == 0) { /* Will have varval(STRhome) here because set fast if don't */ { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); setintr = 0;/*FIXRESET:cleanup*/ /* onintr in /etc/ files has no effect */ parintr.sa_handler = SIG_IGN;/*FIXRESET: cleanup*/ #ifdef LOGINFIRST #ifdef _PATH_DOTLOGIN if (loginsh) (void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL); #endif #endif #ifdef _PATH_DOTCSHRC (void) srcfile(_PATH_DOTCSHRC, 0, 0, NULL); #endif if (!targinp && !onelflg && !havhash) dohash(NULL,NULL); #ifndef LOGINFIRST #ifdef _PATH_DOTLOGIN if (loginsh) (void) srcfile(_PATH_DOTLOGIN, 0, 0, NULL); #endif #endif cleanup_until(&pintr_disabled); setintr = osetintr; parintr = oparintr; } #ifdef LOGINFIRST if (loginsh) (void) srccat(varval(STRhome), STRsldotlogin); #endif /* upward compat. */ if (!srccat(varval(STRhome), STRsldottcshrc)) (void) srccat(varval(STRhome), STRsldotcshrc); if (!targinp && !onelflg && !havhash) dohash(NULL,NULL); /* * Source history before .login so that it is available in .login */ loadhist(NULL, 0); #ifndef LOGINFIRST if (loginsh) (void) srccat(varval(STRhome), STRsldotlogin); #endif if (loginsh || rdirs) loaddirs(NULL); } /* Reset interrupt flag */ setintr = osetintr; parintr = oparintr; exitset--; /* Initing AFTER .cshrc is the Right Way */ if (intty && !targinp) { /* PWP setup stuff */ ed_Init(); /* init the new line editor */ #ifdef SIG_WINDOW check_window_size(1); /* mung environment */ #endif /* SIG_WINDOW */ } /* * Now are ready for the -v and -x flags */ if (nverbose) setNS(STRverbose); if (nexececho) setNS(STRecho); - + if (targinp) { /* If this -c command caused an error before, skip processing */ if (reenter && arginp) { exitcode = 1; goto done; } arginp = SAVE(targinp); /* * we put the command into a variable */ if (arginp != NULL) setv(STRcommand, quote(Strsave(arginp)), VAR_READWRITE); /* * * Give an error on -c arguments that end in * backslash to * ensure that you don't make * nonportable csh scripts. */ { int count; cp = Strend(arginp); count = 0; while (cp > arginp && *--cp == '\\') ++count; if ((count & 1) != 0) { exiterr = 1; stderror(ERR_ARGC); } } } /* * All the rest of the world is inside this call. The argument to process * indicates whether it should catch "error unwinds". Thus if we are a * interactive shell our call here will never return by being blown past on * an error. */ process(setintr); done: /* * Mop-up. */ /* Take care of these (especially HUP) here instead of inside flush. */ handle_pending_signals(); if (intty) { if (loginsh) { xprintf("logout\n"); xclose(SHIN); child = 1; #ifdef TESLA do_logout = 1; #endif /* TESLA */ goodbye(NULL, NULL); } else { xprintf("exit\n"); } } record(); exitstat(); return exitcode; } void untty(void) { #ifdef BSDJOBS if (tpgrp > 0 && opgrp != shpgrp) { (void) setpgid(0, opgrp); (void) tcsetpgrp(FSHTTY, opgrp); (void) resetdisc(FSHTTY); } #endif /* BSDJOBS */ } void importpath(Char *cp) { size_t i = 0; Char *dp; Char **pv; int c; for (dp = cp; *dp; dp++) if (*dp == PATHSEP) i++; /* * i+2 where i is the number of colons in the path. There are i+1 * directories in the path plus we need room for a zero terminator. */ pv = xcalloc(i + 2, sizeof(Char *)); dp = cp; i = 0; if (*dp) for (;;) { if ((c = *dp) == PATHSEP || c == 0) { *dp = 0; pv[i++] = Strsave(*cp ? cp : STRdot); if (c) { cp = dp + 1; *dp = PATHSEP; } else break; } #ifdef WINNT_NATIVE else if (*dp == '\\') *dp = '/'; #endif /* WINNT_NATIVE */ dp++; } pv[i] = 0; cleanup_push(pv, blk_cleanup); setq(STRpath, pv, &shvhed, VAR_READWRITE); cleanup_ignore(pv); cleanup_until(pv); } /* * Source to the file which is the catenation of the argument names. */ static int srccat(Char *cp, Char *dp) { - if (cp[0] == '/' && cp[1] == '\0') + if (cp[0] == '/' && cp[1] == '\0') return srcfile(short2str(dp), (mflag ? 0 : 1), 0, NULL); else { Char *ep; char *ptr; int rv; #ifdef WINNT_NATIVE ep = Strend(cp); if (ep != cp && ep[-1] == '/' && dp[0] == '/') /* silly win95 */ dp++; #endif /* WINNT_NATIVE */ ep = Strspl(cp, dp); cleanup_push(ep, xfree); ptr = short2str(ep); rv = srcfile(ptr, (mflag ? 0 : 1), 0, NULL); cleanup_until(ep); return rv; } } /* * Source to a file putting the file descriptor in a safe place (> 2). */ #ifndef WINNT_NATIVE static int #else int #endif /*WINNT_NATIVE*/ srcfile(const char *f, int onlyown, int flag, Char **av) { int unit; - if ((unit = xopen(f, O_RDONLY|O_LARGEFILE)) == -1) + if ((unit = xopen(f, O_RDONLY|O_LARGEFILE)) == -1) return 0; cleanup_push(&unit, open_cleanup); unit = dmove(unit, -1); cleanup_ignore(&unit); cleanup_until(&unit); (void) close_on_exec(unit, 1); srcunit(unit, onlyown, flag, av); return 1; } /* * Save the shell state, and establish new argument vector, and new input * fd. */ static void st_save(struct saved_state *st, int unit, int hflg, Char **al, Char **av) { st->insource = insource; st->SHIN = SHIN; /* Want to preserve the meaning of "source file >output". * Save old descriptors, move new 0,1,2 to safe places and assign * them to SH* and let process() redo 0,1,2 from them. * * The macro returns true if d1 and d2 are good and they point to * different things. If you don't avoid saving duplicate * descriptors, you really limit the depth of "source" recursion * you can do because of all the open file descriptors. -IAN! */ #define NEED_SAVE_FD(d1,d2) \ (fstat(d1, &s1) != -1 && fstat(d2, &s2) != -1 \ && (s1.st_ino != s2.st_ino || s1.st_dev != s2.st_dev) ) st->OLDSTD = st->SHOUT = st->SHDIAG = -1;/* test later to restore these */ if (didfds) { struct stat s1, s2; if (NEED_SAVE_FD(0,OLDSTD)) { st->OLDSTD = OLDSTD; OLDSTD = dmove(0, -1); (void)close_on_exec(OLDSTD, 1); } if (NEED_SAVE_FD(1,SHOUT)) { st->SHOUT = SHOUT; SHOUT = dmove(1, -1); (void)close_on_exec(SHOUT, 1); } if (NEED_SAVE_FD(2,SHDIAG)) { st->SHDIAG = SHDIAG; SHDIAG = dmove(2, -1); (void)close_on_exec(SHDIAG, 1); } donefds(); } st->intty = intty; st->whyles = whyles; st->gointr = gointr; st->arginp = arginp; st->evalp = evalp; st->evalvec = evalvec; st->alvecp = alvecp; st->alvec = alvec; st->onelflg = onelflg; st->enterhist = enterhist; st->justpr = justpr; if (hflg) st->HIST = HIST; else st->HIST = '\0'; st->cantell = cantell; cpybin(st->B, B); /* - * we can now pass arguments to source. + * we can now pass arguments to source. * For compatibility we do that only if arguments were really * passed, otherwise we keep the old, global $argv like before. */ if (av != NULL && *av != NULL) { struct varent *vp; if ((vp = adrof(STRargv)) != NULL && vp->vec != NULL) st->argv = saveblk(vp->vec); else st->argv = NULL; setq(STRargv, saveblk(av), &shvhed, VAR_READWRITE); } else st->argv = NULL; st->av = av; SHIN = unit; /* Do this first */ /* Establish new input arena */ { fbuf = NULL; fseekp = feobp = fblocks = 0; settell(); } arginp = 0; onelflg = 0; intty = isatty(SHIN); whyles = 0; gointr = 0; evalvec = 0; evalp = 0; alvec = al; alvecp = 0; enterhist = hflg; if (enterhist) HIST = '\0'; insource = 1; } /* * Restore the shell to a saved state */ static void st_restore(void *xst) { struct saved_state *st; st = xst; if (st->SHIN == -1) return; /* Reset input arena */ { int i; Char** nfbuf = fbuf; int nfblocks = fblocks; fblocks = 0; fbuf = NULL; for (i = 0; i < nfblocks; i++) xfree(nfbuf[i]); xfree(nfbuf); } cpybin(B, st->B); xclose(SHIN); insource = st->insource; SHIN = st->SHIN; if (st->OLDSTD != -1) xclose(OLDSTD), OLDSTD = st->OLDSTD; if (st->SHOUT != -1) xclose(SHOUT), SHOUT = st->SHOUT; if (st->SHDIAG != -1) xclose(SHDIAG), SHDIAG = st->SHDIAG; arginp = st->arginp; onelflg = st->onelflg; evalp = st->evalp; evalvec = st->evalvec; alvecp = st->alvecp; alvec = st->alvec; intty = st->intty; whyles = st->whyles; gointr = st->gointr; if (st->HIST != '\0') HIST = st->HIST; enterhist = st->enterhist; cantell = st->cantell; justpr = st->justpr; if (st->argv != NULL) setq(STRargv, st->argv, &shvhed, VAR_READWRITE); else if (st->av != NULL && *st->av != NULL && adrof(STRargv) != NULL) unsetv(STRargv); } /* * Source to a unit. If onlyown it must be our file or our group or * we don't chance it. This occurs on ".cshrc"s and the like. */ static void srcunit(int unit, int onlyown, int hflg, Char **av) { struct saved_state st; st.SHIN = -1; /* st_restore checks this */ if (unit < 0) return; if (onlyown) { struct stat stb; if (fstat(unit, &stb) < 0) { xclose(unit); return; } } /* Does nothing before st_save() because st.SHIN == -1 */ cleanup_push(&st, st_restore); if (setintr) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); } /* Save the current state and move us to a new state */ st_save(&st, unit, hflg, NULL, av); /* * Now if we are allowing commands to be interrupted, we let ourselves be * interrupted. */ if (setintr) { cleanup_until(&pintr_disabled); pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); } process(0); /* 0 -> blow away on errors */ /* Restore the old state */ cleanup_until(&st); } /*ARGSUSED*/ void goodbye(Char **v, struct command *c) { USE(v); USE(c); record(); if (loginsh) { size_t omark; sigset_t set; sigemptyset(&set); signal(SIGQUIT, SIG_IGN); sigaddset(&set, SIGQUIT); sigprocmask(SIG_UNBLOCK, &set, NULL); signal(SIGINT, SIG_IGN); sigaddset(&set, SIGINT); signal(SIGTERM, SIG_IGN); sigaddset(&set, SIGTERM); signal(SIGHUP, SIG_IGN); sigaddset(&set, SIGHUP); sigprocmask(SIG_UNBLOCK, &set, NULL); phup_disabled = 1; setintr = 0; /* No interrupts after "logout" */ /* Trap errors inside .logout */ omark = cleanup_push_mark(); if (setexit() == 0) { if (!(adrof(STRlogout))) setcopy(STRlogout, STRnormal, VAR_READWRITE); #ifdef _PATH_DOTLOGOUT (void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL); #endif if (adrof(STRhome)) (void) srccat(varval(STRhome), STRsldtlogout); #ifdef TESLA do_logout = 1; #endif /* TESLA */ } cleanup_pop_mark(omark); } exitstat(); } void exitstat(void) { #ifdef PROF _mcleanup(); #endif /* * Note that if STATUS is corrupted (i.e. getn bombs) then error will exit * directly because we poke child here. Otherwise we might continue * unwarrantedly (sic). */ child = 1; xexit(getn(varval(STRstatus))); } /* * in the event of a HUP we want to save the history */ void phup(void) { static int again = 0; if (again++) return; if (loginsh) { setcopy(STRlogout, STRhangup, VAR_READWRITE); #ifdef _PATH_DOTLOGOUT (void) srcfile(_PATH_DOTLOGOUT, 0, 0, NULL); #endif if (adrof(STRhome)) (void) srccat(varval(STRhome), STRsldtlogout); } record(); -#ifdef POSIXJOBS +#ifdef POSIXJOBS /* * We kill the last foreground process group. It then becomes - * responsible to propagate the SIGHUP to its progeny. + * responsible to propagate the SIGHUP to its progeny. */ { struct process *pp, *np; for (pp = proclist.p_next; pp; pp = pp->p_next) { np = pp; - /* + /* * Find if this job is in the foreground. It could be that * the process leader has exited and the foreground flag * is cleared for it. */ - do + do /* * If a process is in the foreground we try to kill - * it's process group. If we succeed, then the + * it's process group. If we succeed, then the * whole job is gone. Otherwise we keep going... * But avoid sending HUP to the shell again. */ if (((np->p_flags & PFOREGND) != 0) && np->p_jobid != shpgrp) { np->p_flags &= ~PHUP; if (killpg(np->p_jobid, SIGHUP) != -1) { /* In case the job was suspended... */ #ifdef SIGCONT (void) killpg(np->p_jobid, SIGCONT); #endif break; } } while ((np = np->p_friends) != pp); } } #endif /* POSIXJOBS */ xexit(SIGHUP); } static Char *jobargv[2] = {STRjobs, 0}; /* * Catch an interrupt, e.g. during lexical input. * If we are an interactive shell, we reset the interrupt catch * immediately. In any case we drain the shell output, * and finally go through the normal error mechanism, which * gets a chance to make the shell go away. */ int just_signaled; /* bugfix by Michael Bloom (mg@ttidca.TTI.COM) */ void pintr(void) { just_signaled = 1; pintr1(1); } void pintr1(int wantnl) { if (setintr) { if (pjobs) { pjobs = 0; xputchar('\n'); dojobs(jobargv, NULL); stderror(ERR_NAME | ERR_INTR); } } /* MH - handle interrupted completions specially */ { if (InsideCompletion) stderror(ERR_SILENT); } /* JV - Make sure we shut off inputl */ { (void) Cookedmode(); GettingInput = 0; if (evalvec) doneinp = 1; } drainoline(); #ifdef HAVE_GETPWENT (void) endpwent(); #endif /* * If we have an active "onintr" then we search for the label. Note that if * one does "onintr -" then we shan't be interruptible so we needn't worry * about that here. */ if (gointr) { gotolab(gointr); reset(); } else if (intty && wantnl) { if (editing) { - /* + /* * If we are editing a multi-line input command, and move to * the beginning of the line, we don't want to trash it when * we hit ^C */ PastBottom(); ClearLines(); ClearDisp(); } else { /* xputchar('\n'); *//* Some like this, others don't */ (void) putraw('\r'); (void) putraw('\n'); } } stderror(ERR_SILENT); } /* * Process is the main driving routine for the shell. * It runs all command processing, except for those within { ... } * in expressions (which is run by a routine evalav in sh.exp.c which * is a stripped down process), and `...` evaluation which is run * also by a subset of this code in sh.glob.c in the routine backeval. * * The code here is a little strange because part of it is interruptible * and hence freeing of structures appears to occur when none is necessary * if this is ignored. * * Note that if catch is not set then we will unwind on any error. * If an end-of-file occurs, we return. */ void process(int catch) { jmp_buf_t osetexit; /* PWP: This might get nuked by longjmp so don't make it a register var */ size_t omark; volatile int didexitset = 0; getexit(osetexit); omark = cleanup_push_mark(); for (;;) { struct command *t; int hadhist, old_pintr_disabled; (void)setexit(); if (didexitset == 0) { exitset++; didexitset++; } pendjob(); justpr = enterhist; /* execute if not entering history */ if (haderr) { if (!catch) { /* unwind */ doneinp = 0; cleanup_pop_mark(omark); resexit(osetexit); reset(); } haderr = 0; /* * Every error is eventually caught here or the shell dies. It is * at this point that we clean up any left-over open files, by * closing all but a fixed number of pre-defined files. Thus * routines don't have to worry about leaving files open due to * deeper errors... they will get closed here. */ closem(); continue; } if (doneinp) { doneinp = 0; break; } if (chkstop) chkstop--; if (neednote) pnote(); if (intty && prompt && evalvec == 0) { just_signaled = 0; mailchk(); /* * Watch for logins/logouts. Next is scheduled commands stored * previously using "sched." Then execute periodic commands. * Following that, the prompt precmd is run. */ #ifndef HAVENOUTMP watch_login(0); #endif /* !HAVENOUTMP */ sched_run(); period_cmd(); precmd(); /* * If we are at the end of the input buffer then we are going to * read fresh stuff. Otherwise, we are rereading input and don't * need or want to prompt. */ if (fseekp == feobp && aret == TCSH_F_SEEK) printprompt(0, NULL); flush(); setalarm(1); } if (seterr) { xfree(seterr); seterr = NULL; } /* * Interruptible during interactive reads */ if (setintr) pintr_push_enable(&old_pintr_disabled); freelex(¶ml); hadhist = lex(¶ml); if (setintr) cleanup_until(&old_pintr_disabled); cleanup_push(¶ml, lex_cleanup); /* * Echo not only on VERBOSE, but also with history expansion. If there * is a lexical error then we forego history echo. * Do not echo if we're only entering history (source -h). */ if ((hadhist && !seterr && intty && !tellwhat && !Expand && !whyles) || (!enterhist && adrof(STRverbose))) { int odidfds = didfds; haderr = 1; didfds = 0; prlex(¶ml); flush(); haderr = 0; didfds = odidfds; } (void) alarm(0); /* Autologout OFF */ alrmcatch_disabled = 1; /* * Save input text on the history list if reading in old history, or it * is from the terminal at the top level and not in a loop. - * + * * PWP: entry of items in the history list while in a while loop is done * elsewhere... */ if (enterhist || (catch && intty && !whyles && !tellwhat && !arun)) savehist(¶ml, enterhist > 1); if (Expand && seterr) Expand = 0; /* * Print lexical error messages, except when sourcing history lists. */ if (!enterhist && seterr) stderror(ERR_OLD); /* * If had a history command :p modifier then this is as far as we * should go */ if (justpr) goto cmd_done; /* * If had a tellwhat from twenex() then do */ if (tellwhat) { (void) tellmewhat(¶ml, NULL); goto cmd_done; } alias(¶ml); #ifdef BSDJOBS /* * If we are interactive, try to continue jobs that we have stopped */ if (prompt) continue_jobs(¶ml); #endif /* BSDJOBS */ /* * Check to see if the user typed "rm * .o" or something */ if (prompt) rmstar(¶ml); /* * Parse the words of the input into a parse tree. */ t = syntax(paraml.next, ¶ml, 0); /* * We cannot cleanup push here, because cd /blah; echo foo * would rewind t on the chdir error, and free the rest of the command */ if (seterr) { freesyn(t); stderror(ERR_OLD); } postcmd(); /* * Execute the parse tree From: Michael Schroeder * was execute(t, tpgrp); */ execute(t, (tpgrp > 0 ? tpgrp : -1), NULL, NULL, TRUE); freesyn(t); /* * Made it! */ #ifdef SIG_WINDOW if (windowchg || (catch && intty && !whyles && !tellwhat)) { (void) check_window_size(0); /* for window systems */ } #endif /* SIG_WINDOW */ setcopy(STR_, InputBuf, VAR_READWRITE | VAR_NOGLOB); cmd_done: if (cleanup_reset()) cleanup_until(¶ml); else haderr = 1; } cleanup_pop_mark(omark); resexit(osetexit); exitset--; handle_pending_signals(); } /*ARGSUSED*/ void dosource(Char **t, struct command *c) { Char *f; int hflg = 0; char *file; USE(c); t++; if (*t && eq(*t, STRmh)) { if (*++t == NULL) stderror(ERR_NAME | ERR_HFLAG); hflg++; } else if (*t && eq(*t, STRmm)) { if (*++t == NULL) stderror(ERR_NAME | ERR_MFLAG); hflg = 2; } f = globone(*t++, G_ERROR); file = strsave(short2str(f)); cleanup_push(file, xfree); xfree(f); t = glob_all_or_error(t); cleanup_push(t, blk_cleanup); if ((!srcfile(file, 0, hflg, t)) && (!hflg) && (!bequiet)) stderror(ERR_SYSTEM, file, strerror(errno)); cleanup_until(file); } /* * Check for mail. * If we are a login shell, then we don't want to tell * about any mail file unless its been modified * after the time we started. * This prevents us from telling the user things he already * knows, since the login program insists on saying * "You have mail." */ /* * The AMS version. * This version checks if the file is a directory, and if so, * tells you the number of files in it, otherwise do the old thang. * The magic "+1" in the time calculation is to compensate for * an AFS bug where directory mtimes are set to 1 second in * the future. */ static void mailchk(void) { struct varent *v; Char **vp; time_t t; int intvl, cnt; struct stat stb; int new; v = adrof(STRmail); if (v == NULL || v->vec == NULL) return; (void) time(&t); vp = v->vec; cnt = blklen(vp); intvl = (cnt && number(*vp)) ? (--cnt, getn(*vp++)) : MAILINTVL; if (intvl < 1) intvl = 1; if (chktim + intvl > t) return; for (; *vp; vp++) { char *filename = short2str(*vp); char *mboxdir = filename; if (stat(filename, &stb) < 0) continue; #if defined(BSDTIMES) || defined(_SEQUENT_) new = stb.st_mtime > time0.tv_sec; #else new = stb.st_mtime > seconds0; #endif if (S_ISDIR(stb.st_mode)) { DIR *mailbox; int mailcount = 0; char *tempfilename; struct stat stc; tempfilename = xasprintf("%s/new", filename); if (stat(tempfilename, &stc) != -1 && S_ISDIR(stc.st_mode)) { /* * "filename/new" exists and is a directory; you are * using Qmail. */ stb = stc; #if defined(BSDTIMES) || defined(_SEQUENT_) new = stb.st_mtime > time0.tv_sec; #else new = stb.st_mtime > seconds0; #endif mboxdir = tempfilename; } if (stb.st_mtime <= chktim + 1 || (loginsh && !new)) { xfree(tempfilename); continue; } mailbox = opendir(mboxdir); xfree(tempfilename); if (mailbox == NULL) continue; /* skip . and .. */ if (!readdir(mailbox) || !readdir(mailbox)) { (void)closedir(mailbox); continue; } while (readdir(mailbox)) mailcount++; (void)closedir(mailbox); if (mailcount == 0) continue; if (cnt == 1) xprintf(CGETS(11, 3, "You have %d mail messages.\n"), mailcount); else xprintf(CGETS(11, 4, "You have %d mail messages in %s.\n"), mailcount, filename); } else { char *type; - + if (stb.st_size == 0 || stb.st_atime >= stb.st_mtime || (stb.st_atime <= chktim && stb.st_mtime <= chktim) || (loginsh && !new)) continue; type = strsave(new ? CGETS(11, 6, "new ") : ""); cleanup_push(type, xfree); if (cnt == 1) xprintf(CGETS(11, 5, "You have %smail.\n"), type); else xprintf(CGETS(11, 7, "You have %smail in %s.\n"), type, filename); cleanup_until(type); } } chktim = t; } /* * Extract a home directory from the password file * The argument points to a buffer where the name of the * user whose home directory is sought is currently. * We return home directory of the user, or NULL. */ Char * gethdir(const Char *home) { Char *h; /* * Is it us? */ if (*home == '\0') { if ((h = varval(STRhome)) != STRNULL) return Strsave(h); else return NULL; } /* * Look in the cache */ if ((h = gettilde(home)) == NULL) return NULL; else return Strsave(h); } /* * Move the initial descriptors to their eventual * resting places, closing all other units. */ void initdesc(void) { #ifdef NLS_BUGS #ifdef NLS_CATALOGS nlsclose(); #endif /* NLS_CATALOGS */ #endif /* NLS_BUGS */ didfds = 0; /* 0, 1, 2 aren't set up */ (void) close_on_exec(SHIN = dcopy(0, FSHIN), 1); (void) close_on_exec(SHOUT = dcopy(1, FSHOUT), 1); (void) close_on_exec(SHDIAG = dcopy(2, FSHDIAG), 1); (void) close_on_exec(OLDSTD = dcopy(SHIN, FOLDSTD), 1); #ifndef CLOSE_ON_EXEC didcch = 0; /* Havent closed for child */ #endif /* CLOSE_ON_EXEC */ if (SHDIAG >= 0) isdiagatty = isatty(SHDIAG); else isdiagatty = 0; if (SHDIAG >= 0) isoutatty = isatty(SHOUT); else isoutatty = 0; #ifdef NLS_BUGS #ifdef NLS_CATALOGS nlsinit(); #endif /* NLS_CATALOGS */ #endif /* NLS_BUGS */ } void #ifdef PROF done(int i) #else xexit(int i) #endif { #ifdef TESLA if (loginsh && do_logout) { /* this is to send hangup signal to the develcon */ /* we toggle DTR. clear dtr - sleep 1 - set dtr */ /* ioctl will return ENOTTY for pty's but we ignore it */ /* exitstat will run after disconnect */ /* we sleep for 2 seconds to let things happen in */ /* .logout and rechist() */ #ifdef TIOCCDTR (void) sleep(2); (void) ioctl(FSHTTY, TIOCCDTR, NULL); (void) sleep(1); (void) ioctl(FSHTTY, TIOCSDTR, NULL); #endif /* TIOCCDTR */ } #endif /* TESLA */ { struct process *pp, *np; pid_t mypid = getpid(); /* Kill all processes marked for hup'ing */ for (pp = proclist.p_next; pp; pp = pp->p_next) { np = pp; do if ((np->p_flags & PHUP) && np->p_jobid != shpgrp && np->p_parentid == mypid) { if (killpg(np->p_jobid, SIGHUP) != -1) { /* In case the job was suspended... */ #ifdef SIGCONT (void) killpg(np->p_jobid, SIGCONT); #endif break; } } while ((np = np->p_friends) != pp); } } untty(); #ifdef NLS_CATALOGS /* * We need to call catclose, because SVR4 leaves symlinks behind otherwise * in the catalog directories. We cannot close on a vforked() child, * because messages will stop working on the parent too. */ if (child == 0) nlsclose(); #endif /* NLS_CATALOGS */ #ifdef WINNT_NATIVE nt_cleanup(); #endif /* WINNT_NATIVE */ _exit(i); } #ifndef _PATH_DEFPATH static Char ** defaultpath(void) { char *ptr; Char **blk, **blkp; struct stat stb; blkp = blk = xmalloc(sizeof(Char *) * 10); #ifndef NODOT # ifndef DOTLAST *blkp++ = Strsave(STRdot); # endif #endif #define DIRAPPEND(a) \ if (stat(ptr = a, &stb) == 0 && S_ISDIR(stb.st_mode)) \ *blkp++ = SAVE(ptr) #ifdef _PATH_LOCAL DIRAPPEND(_PATH_LOCAL); #endif #ifdef _PATH_USRUCB DIRAPPEND(_PATH_USRUCB); #endif #ifdef _PATH_USRBSD DIRAPPEND(_PATH_USRBSD); #endif #ifdef _PATH_BIN DIRAPPEND(_PATH_BIN); #endif #ifdef _PATH_USRBIN DIRAPPEND(_PATH_USRBIN); #endif #undef DIRAPPEND #ifndef NODOT # ifdef DOTLAST *blkp++ = Strsave(STRdot); # endif #endif *blkp = NULL; return (blk); } #endif static void record(void) { static int again = 0; int ophup_disabled; if (again++) return; ophup_disabled = phup_disabled; phup_disabled = 1; if (!fast) { recdirs(NULL, adrof(STRsavedirs) != NULL); rechist(NULL, adrof(STRsavehist) != NULL); } displayHistStats("Exiting"); /* no-op unless DEBUG_HIST */ phup_disabled = ophup_disabled; } /* * Grab the tty repeatedly, and give up if we are not in the correct * tty process group. */ int grabpgrp(int fd, pid_t desired) { struct sigaction old; pid_t pgrp; size_t i; for (i = 0; i < 100; i++) { if ((pgrp = tcgetpgrp(fd)) == -1) return -1; if (pgrp == desired) return 0; (void)sigaction(SIGTTIN, NULL, &old); (void)signal(SIGTTIN, SIG_DFL); (void)kill(0, SIGTTIN); (void)sigaction(SIGTTIN, &old, NULL); } errno = EPERM; return -1; } diff --git a/contrib/tcsh/sh.char.c b/contrib/tcsh/sh.char.c index bc8142611b99..c3cb280b9f7e 100644 --- a/contrib/tcsh/sh.char.c +++ b/contrib/tcsh/sh.char.c @@ -1,1167 +1,1167 @@ /* * sh.char.c: Character classification tables */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "sh.char.h" /* on default same as original map */ unsigned short _cmap[256] = { /* 0 nul 1 soh 2 stx 3 etx */ _CTR, _CTR, _CTR, _CTR, /* 4 eot 5 enq 6 ack 7 bel */ _CTR, _CTR, _CTR, _CTR, /* 8 bs 9 ht 10 nl 11 vt */ _CTR, _CTR|_SP|_META, _CTR|_NL|_META, _CTR, /* 12 np 13 cr 14 so 15 si */ _CTR, _CTR, _CTR, _CTR, /* 16 dle 17 dc1 18 dc2 19 dc3 */ _CTR, _CTR, _CTR, _CTR, /* 20 dc4 21 nak 22 syn 23 etb */ _CTR, _CTR, _CTR, _CTR, /* 24 can 25 em 26 sub 27 esc */ _CTR, _CTR, _CTR, _CTR, /* 28 fs 29 gs 30 rs 31 us */ _CTR, _CTR, _CTR, _CTR, /* 32 sp 33 ! 34 " 35 # */ _SP|_META, _PUN, _QF|_PUN, _META|_PUN, /* 36 $ 37 % 38 & 39 ' */ _DOL|_PUN, _PUN, _META|_CMD|_PUN,_QF|_PUN, /* 40 ( 41 ) 42 * 43 + */ _META|_CMD|_PUN,_META|_PUN, _GLOB|_PUN, _PUN, /* 44 , 45 - 46 . 47 / */ _PUN, _PUN, _PUN, _PUN, /* 48 0 49 1 50 2 51 3 */ _DIG|_XD, _DIG|_XD, _DIG|_XD, _DIG|_XD, /* 52 4 53 5 54 6 55 7 */ _DIG|_XD, _DIG|_XD, _DIG|_XD, _DIG|_XD, /* 56 8 57 9 58 : 59 ; */ _DIG|_XD, _DIG|_XD, _PUN, _META|_CMD|_PUN, /* 60 < 61 = 62 > 63 ? */ _META|_PUN, _PUN, _META|_PUN, _GLOB|_PUN, /* 64 @ 65 A 66 B 67 C */ _PUN, _LET|_UP|_XD, _LET|_UP|_XD, _LET|_UP|_XD, /* 68 D 69 E 70 F 71 G */ _LET|_UP|_XD, _LET|_UP|_XD, _LET|_UP|_XD, _LET|_UP, /* 72 H 73 I 74 J 75 K */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 76 L 77 M 78 N 79 O */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 80 P 81 Q 82 R 83 S */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 84 T 85 U 86 V 87 W */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 88 X 89 Y 90 Z 91 [ */ _LET|_UP, _LET|_UP, _LET|_UP, _GLOB|_PUN, /* 92 \ 93 ] 94 ^ 95 _ */ _ESC|_PUN, _PUN, _PUN, _PUN, /* 96 ` 97 a 98 b 99 c */ _QB|_GLOB|_META|_PUN, _LET|_DOW|_XD, _LET|_DOW|_XD, _LET|_DOW|_XD, /* 100 d 101 e 102 f 103 g */ _LET|_DOW|_XD, _LET|_DOW|_XD, _LET|_DOW|_XD, _LET|_DOW, /* 104 h 105 i 106 j 107 k */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 108 l 109 m 110 n 111 o */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 112 p 113 q 114 r 115 s */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 116 t 117 u 118 v 119 w */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 120 x 121 y 122 z 123 { */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _GLOB|_PUN, /* 124 | 125 } 126 ~ 127 del */ _META|_CMD|_PUN,_PUN, _PUN, _CTR, #ifdef SHORT_STRINGS /****************************************************************/ /* 128 - 255 The below is supposedly ISO 8859/1 */ /****************************************************************/ /* 128 (undef) 129 (undef) 130 (undef) 131 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 132 (undef) 133 (undef) 134 (undef) 135 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 136 (undef) 137 (undef) 138 (undef) 139 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 140 (undef) 141 (undef) 142 (undef) 143 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 144 (undef) 145 (undef) 146 (undef) 147 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 148 (undef) 149 (undef) 150 (undef) 151 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 152 (undef) 153 (undef) 154 (undef) 155 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 156 (undef) 157 (undef) 158 (undef) 159 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 160 nobreakspace 161 exclamdown 162 cent 163 sterling */ _PUN, /* XXX */ _PUN, _PUN, _PUN, /* 164 currency 165 yen 166 brokenbar 167 section */ _PUN, _PUN, _PUN, _PUN, /* 168 diaeresis 169 copyright 170 ordfeminine 171 guillemotleft*/ _PUN, _PUN, _PUN, _PUN, /* 172 notsign 173 hyphen 174 registered 175 macron */ _PUN, _PUN, _PUN, _PUN, /* 176 degree 177 plusminus 178 twosuperior 179 threesuperior*/ _PUN, _PUN, _PUN, _PUN, /* 180 acute 181 mu 182 paragraph 183 periodcentered*/ _PUN, _PUN, /*XXX*/ _PUN, _PUN, /* 184 cedilla 185 onesuperior 186 masculine 187 guillemotright*/ _PUN, _PUN, _PUN, _PUN, /* 188 onequarter 189 onehalf 190 threequarters 191 questiondown*/ _PUN, _PUN, _PUN, _PUN, /* 192 Agrave 193 Aacute 194 Acircumflex 195 Atilde */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 196 Adiaeresis 197 Aring 198 AE 199 Ccedilla */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 200 Egrave 201 Eacute 202 Ecircumflex 203 Ediaeresis */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 204 Igrave 205 Iacute 206 Icircumflex 207 Idiaeresis */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 208 ETH 209 Ntilde 210 Ograve 211 Oacute */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 212 Ocircumflex 213 Otilde 214 Odiaeresis 215 multiply */ _LET|_UP, _LET|_UP, _LET|_UP, _PUN, /* 216 Ooblique 217 Ugrave 218 Uacute 219 Ucircumflex */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 220 Udiaeresis 221 Yacute 222 THORN 223 ssharp */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_DOW, /* 224 agrave 225 aacute 226 acircumflex 227 atilde */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 228 adiaeresis 229 aring 230 ae 231 ccedilla */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 232 egrave 233 eacute 234 ecircumflex 235 ediaeresis */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 236 igrave 237 iacute 238 icircumflex 239 idiaeresis */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 240 eth 241 ntilde 242 ograve 243 oacute */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 244 ocircumflex 245 otilde 246 odiaeresis 247 division */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _PUN, /* 248 oslash 249 ugrave 250 uacute 251 ucircumflex */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 252 udiaeresis 253 yacute 254 thorn 255 ydiaeresis */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, #endif /* SHORT_STRINGS */ }; #if defined(KANJI) && defined(SHORT_STRINGS) && defined(DSPMBYTE) /* original table */ unsigned short _cmap_c[256] = { /* 0 nul 1 soh 2 stx 3 etx */ _CTR, _CTR, _CTR, _CTR, /* 4 eot 5 enq 6 ack 7 bel */ _CTR, _CTR, _CTR, _CTR, /* 8 bs 9 ht 10 nl 11 vt */ _CTR, _CTR|_SP|_META, _CTR|_NL|_META, _CTR, /* 12 np 13 cr 14 so 15 si */ _CTR, _CTR, _CTR, _CTR, /* 16 dle 17 dc1 18 dc2 19 dc3 */ _CTR, _CTR, _CTR, _CTR, /* 20 dc4 21 nak 22 syn 23 etb */ _CTR, _CTR, _CTR, _CTR, /* 24 can 25 em 26 sub 27 esc */ _CTR, _CTR, _CTR, _CTR, /* 28 fs 29 gs 30 rs 31 us */ _CTR, _CTR, _CTR, _CTR, /* 32 sp 33 ! 34 " 35 # */ _SP|_META, _PUN, _QF|_PUN, _META|_PUN, /* 36 $ 37 % 38 & 39 ' */ _DOL|_PUN, _PUN, _META|_CMD|_PUN,_QF|_PUN, /* 40 ( 41 ) 42 * 43 + */ _META|_CMD|_PUN,_META|_PUN, _GLOB|_PUN, _PUN, /* 44 , 45 - 46 . 47 / */ _PUN, _PUN, _PUN, _PUN, /* 48 0 49 1 50 2 51 3 */ _DIG|_XD, _DIG|_XD, _DIG|_XD, _DIG|_XD, /* 52 4 53 5 54 6 55 7 */ _DIG|_XD, _DIG|_XD, _DIG|_XD, _DIG|_XD, /* 56 8 57 9 58 : 59 ; */ _DIG|_XD, _DIG|_XD, _PUN, _META|_CMD|_PUN, /* 60 < 61 = 62 > 63 ? */ _META|_PUN, _PUN, _META|_PUN, _GLOB|_PUN, /* 64 @ 65 A 66 B 67 C */ _PUN, _LET|_UP|_XD, _LET|_UP|_XD, _LET|_UP|_XD, /* 68 D 69 E 70 F 71 G */ _LET|_UP|_XD, _LET|_UP|_XD, _LET|_UP|_XD, _LET|_UP, /* 72 H 73 I 74 J 75 K */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 76 L 77 M 78 N 79 O */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 80 P 81 Q 82 R 83 S */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 84 T 85 U 86 V 87 W */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 88 X 89 Y 90 Z 91 [ */ _LET|_UP, _LET|_UP, _LET|_UP, _GLOB|_PUN, /* 92 \ 93 ] 94 ^ 95 _ */ _ESC|_PUN, _PUN, _PUN, _PUN, /* 96 ` 97 a 98 b 99 c */ _QB|_GLOB|_META|_PUN, _LET|_DOW|_XD, _LET|_DOW|_XD, _LET|_DOW|_XD, /* 100 d 101 e 102 f 103 g */ _LET|_DOW|_XD, _LET|_DOW|_XD, _LET|_DOW|_XD, _LET|_DOW, /* 104 h 105 i 106 j 107 k */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 108 l 109 m 110 n 111 o */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 112 p 113 q 114 r 115 s */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 116 t 117 u 118 v 119 w */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 120 x 121 y 122 z 123 { */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _GLOB|_PUN, /* 124 | 125 } 126 ~ 127 del */ _META|_CMD|_PUN,_PUN, _PUN, _CTR, /****************************************************************/ /* 128 - 255 The below is supposedly ISO 8859/1 */ /****************************************************************/ /* 128 (undef) 129 (undef) 130 (undef) 131 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 132 (undef) 133 (undef) 134 (undef) 135 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 136 (undef) 137 (undef) 138 (undef) 139 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 140 (undef) 141 (undef) 142 (undef) 143 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 144 (undef) 145 (undef) 146 (undef) 147 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 148 (undef) 149 (undef) 150 (undef) 151 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 152 (undef) 153 (undef) 154 (undef) 155 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 156 (undef) 157 (undef) 158 (undef) 159 (undef) */ _CTR, _CTR, _CTR, _CTR, /* 160 nobreakspace 161 exclamdown 162 cent 163 sterling */ _PUN, /* XXX */ _PUN, _PUN, _PUN, /* 164 currency 165 yen 166 brokenbar 167 section */ _PUN, _PUN, _PUN, _PUN, /* 168 diaeresis 169 copyright 170 ordfeminine 171 guillemotleft*/ _PUN, _PUN, _PUN, _PUN, /* 172 notsign 173 hyphen 174 registered 175 macron */ _PUN, _PUN, _PUN, _PUN, /* 176 degree 177 plusminus 178 twosuperior 179 threesuperior*/ _PUN, _PUN, _PUN, _PUN, /* 180 acute 181 mu 182 paragraph 183 periodcentered*/ _PUN, _PUN, /*XXX*/ _PUN, _PUN, /* 184 cedilla 185 onesuperior 186 masculine 187 guillemotright*/ _PUN, _PUN, _PUN, _PUN, /* 188 onequarter 189 onehalf 190 threequarters 191 questiondown*/ _PUN, _PUN, _PUN, _PUN, /* 192 Agrave 193 Aacute 194 Acircumflex 195 Atilde */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 196 Adiaeresis 197 Aring 198 AE 199 Ccedilla */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 200 Egrave 201 Eacute 202 Ecircumflex 203 Ediaeresis */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 204 Igrave 205 Iacute 206 Icircumflex 207 Idiaeresis */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 208 ETH 209 Ntilde 210 Ograve 211 Oacute */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 212 Ocircumflex 213 Otilde 214 Odiaeresis 215 multiply */ _LET|_UP, _LET|_UP, _LET|_UP, _PUN, /* 216 Ooblique 217 Ugrave 218 Uacute 219 Ucircumflex */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 220 Udiaeresis 221 Yacute 222 THORN 223 ssharp */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_DOW, /* 224 agrave 225 aacute 226 acircumflex 227 atilde */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 228 adiaeresis 229 aring 230 ae 231 ccedilla */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 232 egrave 233 eacute 234 ecircumflex 235 ediaeresis */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 236 igrave 237 iacute 238 icircumflex 239 idiaeresis */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 240 eth 241 ntilde 242 ograve 243 oacute */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 244 ocircumflex 245 otilde 246 odiaeresis 247 division */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _PUN, /* 248 oslash 249 ugrave 250 uacute 251 ucircumflex */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 252 udiaeresis 253 yacute 254 thorn 255 ydiaeresis */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, }; /* multi-byte table */ /* BY Masaaki Koyanagi VERY THANKS */ unsigned short _cmap_mbyte[256] = { /* 0 nul 1 soh 2 stx 3 etx */ _CTR, _CTR, _CTR, _CTR, /* 4 eot 5 enq 6 ack 7 bel */ _CTR, _CTR, _CTR, _CTR, /* 8 bs 9 ht 10 nl 11 vt */ _CTR, _CTR|_SP|_META, _CTR|_NL|_META, _CTR, /* 12 np 13 cr 14 so 15 si */ _CTR, _CTR, _CTR, _CTR, /* 16 dle 17 dc1 18 dc2 19 dc3 */ _CTR, _CTR, _CTR, _CTR, /* 20 dc4 21 nak 22 syn 23 etb */ _CTR, _CTR, _CTR, _CTR, /* 24 can 25 em 26 sub 27 esc */ _CTR, _CTR, _CTR, _CTR, /* 28 fs 29 gs 30 rs 31 us */ _CTR, _CTR, _CTR, _CTR, /* 32 sp 33 ! 34 " 35 # */ _SP|_META, _PUN, _QF|_PUN, _META|_PUN, /* 36 $ 37 % 38 & 39 ' */ _DOL|_PUN, _PUN, _META|_CMD|_PUN,_QF|_PUN, /* 40 ( 41 ) 42 * 43 + */ _META|_CMD|_PUN,_META|_PUN, _GLOB|_PUN, _PUN, /* 44 , 45 - 46 . 47 / */ _PUN, _PUN, _PUN, _PUN, /* 48 0 49 1 50 2 51 3 */ _DIG|_XD, _DIG|_XD, _DIG|_XD, _DIG|_XD, /* 52 4 53 5 54 6 55 7 */ _DIG|_XD, _DIG|_XD, _DIG|_XD, _DIG|_XD, /* 56 8 57 9 58 : 59 ; */ _DIG|_XD, _DIG|_XD, _PUN, _META|_CMD|_PUN, /* 60 < 61 = 62 > 63 ? */ _META|_PUN, _PUN, _META|_PUN, _GLOB|_PUN, /* 64 @ 65 A 66 B 67 C */ _PUN, _LET|_UP|_XD, _LET|_UP|_XD, _LET|_UP|_XD, /* 68 D 69 E 70 F 71 G */ _LET|_UP|_XD, _LET|_UP|_XD, _LET|_UP|_XD, _LET|_UP, /* 72 H 73 I 74 J 75 K */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 76 L 77 M 78 N 79 O */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 80 P 81 Q 82 R 83 S */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 84 T 85 U 86 V 87 W */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 88 X 89 Y 90 Z 91 [ */ _LET|_UP, _LET|_UP, _LET|_UP, _GLOB|_PUN, /* 92 \ 93 ] 94 ^ 95 _ */ _ESC|_PUN, _PUN, _PUN, _PUN, /* 96 ` 97 a 98 b 99 c */ _QB|_GLOB|_META|_PUN, _LET|_DOW|_XD, _LET|_DOW|_XD, _LET|_DOW|_XD, /* 100 d 101 e 102 f 103 g */ _LET|_DOW|_XD, _LET|_DOW|_XD, _LET|_DOW|_XD, _LET|_DOW, /* 104 h 105 i 106 j 107 k */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 108 l 109 m 110 n 111 o */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 112 p 113 q 114 r 115 s */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 116 t 117 u 118 v 119 w */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 120 x 121 y 122 z 123 { */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _GLOB|_PUN, /* 124 | 125 } 126 ~ 127 del */ _META|_CMD|_PUN,_PUN, _PUN, _CTR, /****************************************************************/ /* 128 - 255 The below is supposedly ISO 8859/1 */ /****************************************************************/ /* 128 (undef) 129 (undef) 130 (undef) 131 (undef) */ _PUN, _PUN, _PUN, _PUN, /* 132 (undef) 133 (undef) 134 (undef) 135 (undef) */ _PUN, _PUN, _PUN, _PUN, /* 136 (undef) 137 (undef) 138 (undef) 139 (undef) */ _PUN, _PUN, _PUN, _PUN, /* 140 (undef) 141 (undef) 142 (undef) 143 (undef) */ _PUN, _PUN, _PUN, _PUN, /* 144 (undef) 145 (undef) 146 (undef) 147 (undef) */ _PUN, _PUN, _PUN, _PUN, /* 148 (undef) 149 (undef) 150 (undef) 151 (undef) */ _PUN, _PUN, _PUN, _PUN, /* 152 (undef) 153 (undef) 154 (undef) 155 (undef) */ _PUN, _PUN, _PUN, _PUN, /* 156 (undef) 157 (undef) 158 (undef) 159 (undef) */ _PUN, _PUN, _PUN, _PUN, /* 160 nobreakspace 161 exclamdown 162 cent 163 sterling */ _PUN, /* XXX */ _PUN, _PUN, _PUN, /* 164 currency 165 yen 166 brokenbar 167 section */ _PUN, _PUN, _PUN, _PUN, /* 168 diaeresis 169 copyright 170 ordfeminine 171 guillemotleft*/ _PUN, _PUN, _PUN, _PUN, /* 172 notsign 173 hyphen 174 registered 175 macron */ _PUN, _PUN, _PUN, _PUN, /* 176 degree 177 plusminus 178 twosuperior 179 threesuperior*/ _PUN, _PUN, _PUN, _PUN, /* 180 acute 181 mu 182 paragraph 183 periodcentered*/ _PUN, _PUN, /*XXX*/ _PUN, _PUN, /* 184 cedilla 185 onesuperior 186 masculine 187 guillemotright*/ _PUN, _PUN, _PUN, _PUN, /* 188 onequarter 189 onehalf 190 threequarters 191 questiondown*/ _PUN, _PUN, _PUN, _PUN, /* 192 Agrave 193 Aacute 194 Acircumflex 195 Atilde */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 196 Adiaeresis 197 Aring 198 AE 199 Ccedilla */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 200 Egrave 201 Eacute 202 Ecircumflex 203 Ediaeresis */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 204 Igrave 205 Iacute 206 Icircumflex 207 Idiaeresis */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 208 ETH 209 Ntilde 210 Ograve 211 Oacute */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 212 Ocircumflex 213 Otilde 214 Odiaeresis 215 multiply */ _LET|_UP, _LET|_UP, _LET|_UP, _PUN, /* 216 Ooblique 217 Ugrave 218 Uacute 219 Ucircumflex */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_UP, /* 220 Udiaeresis 221 Yacute 222 THORN 223 ssharp */ _LET|_UP, _LET|_UP, _LET|_UP, _LET|_DOW, /* 224 agrave 225 aacute 226 acircumflex 227 atilde */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 228 adiaeresis 229 aring 230 ae 231 ccedilla */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 232 egrave 233 eacute 234 ecircumflex 235 ediaeresis */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 236 igrave 237 iacute 238 icircumflex 239 idiaeresis */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 240 eth 241 ntilde 242 ograve 243 oacute */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 244 ocircumflex 245 otilde 246 odiaeresis 247 division */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _PUN, /* 248 oslash 249 ugrave 250 uacute 251 ucircumflex */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, /* 252 udiaeresis 253 yacute 254 thorn 255 ydiaeresis */ _LET|_DOW, _LET|_DOW, _LET|_DOW, _LET|_DOW, }; short _enable_mbdisp = 0; /* control multi-byte 0...disable 1...enable */ /* multi-byte check table */ /* default = all 0 (clear process in update_vars()/unset()) */ unsigned short _mbmap[256]; unsigned short _mbmap_euc[256] = { /* first byte 0x8e,0xa0 - 0xf4 */ /* second byte 0xa0 - 0xfe */ /* 0 - 7f all 0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 80 81 82 83 */ 0, 0, 0, 0, /* 84 85 86 87 */ 0, 0, 0, 0, /* 88 89 8a 8b */ 0, 0, 0, 0, /* 8c 8d 8e 8f */ 0, 0, _MB1, 0, /* 90 - 9f all 0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* a0 a1 a2 a3 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* a4 a5 a6 a7 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* a8 a9 aa ab */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* ac ad ae af */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* b0 b1 b2 b3 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* b4 b5 b6 b7 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* b8 b9 ba bb */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* bc bd be bf */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* c0 c1 c2 c3 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* c4 c5 c6 c7 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* c8 c9 ca cb */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* cc cd ce cf */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* d0 d1 d2 d3 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* d4 d5 d6 d7 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* d8 d9 da db */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* dc dd de df */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* e0 e1 e2 e3 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* e4 e5 e6 e7 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* e8 e9 ea eb */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* ec ed ee ef */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* f0 f1 f2 f3 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* f4 f5 f6 f7 */ _MB1|_MB2, _MB2, _MB2, _MB2, /* f8 f9 fa fb */ _MB2, _MB2, _MB2, _MB2, /* fc fd fe ff */ _MB2, _MB2, _MB2, 0, }; unsigned short _mbmap_sjis[256] = { /* first byte 0x81-0x9f,0xe0 - 0xfc */ /* second byte 0x40-0x7e,0x80 - 0xfc */ /* 0 - 3f all 0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 40 41 42 43 */ _MB2, _MB2, _MB2, _MB2, /* 44 45 46 47 */ _MB2, _MB2, _MB2, _MB2, /* 48 49 4a 4b */ _MB2, _MB2, _MB2, _MB2, /* 4c 4d 4e 4f */ _MB2, _MB2, _MB2, _MB2, /* 50 51 52 53 */ _MB2, _MB2, _MB2, _MB2, /* 54 55 56 57 */ _MB2, _MB2, _MB2, _MB2, /* 58 59 5a 5b */ _MB2, _MB2, _MB2, _MB2, /* 5c 5d 5e 5f */ _MB2, _MB2, _MB2, _MB2, /* 60 61 62 63 */ _MB2, _MB2, _MB2, _MB2, /* 64 65 66 67 */ _MB2, _MB2, _MB2, _MB2, /* 68 69 6a 6b */ _MB2, _MB2, _MB2, _MB2, /* 6c 6d 6e 6f */ _MB2, _MB2, _MB2, _MB2, /* 70 71 72 73 */ _MB2, _MB2, _MB2, _MB2, /* 74 75 76 77 */ _MB2, _MB2, _MB2, _MB2, /* 78 79 7a 7b */ _MB2, _MB2, _MB2, _MB2, /* 7c 7d 7e 7f */ _MB2, _MB2, _MB2, 0, /* 80 81 82 83 */ _MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* 84 85 86 87 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* 88 89 8a 8b */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* 8c 8d 8e 8f */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* 90 91 92 93 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* 94 95 96 97 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* 98 99 9a 9b */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* 9c 9d 9e 9f */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* a0 a1 a2 a3 */ _MB2, _MB2, _MB2, _MB2, /* a4 a5 a6 a7 */ _MB2, _MB2, _MB2, _MB2, /* a8 a9 aa ab */ _MB2, _MB2, _MB2, _MB2, /* ac ad ae af */ _MB2, _MB2, _MB2, _MB2, /* b0 b1 b2 b3 */ _MB2, _MB2, _MB2, _MB2, /* b4 b5 b6 b7 */ _MB2, _MB2, _MB2, _MB2, /* b8 b9 ba bb */ _MB2, _MB2, _MB2, _MB2, /* bc bd be bf */ _MB2, _MB2, _MB2, _MB2, /* c0 c1 c2 c3 */ _MB2, _MB2, _MB2, _MB2, /* c4 c5 c6 c7 */ _MB2, _MB2, _MB2, _MB2, /* c8 c9 ca cb */ _MB2, _MB2, _MB2, _MB2, /* cc cd ce cf */ _MB2, _MB2, _MB2, _MB2, /* d0 d1 d2 d3 */ _MB2, _MB2, _MB2, _MB2, /* d4 d5 d6 d7 */ _MB2, _MB2, _MB2, _MB2, /* d8 d9 da db */ _MB2, _MB2, _MB2, _MB2, /* dc dd de df */ _MB2, _MB2, _MB2, _MB2, /* e0 e1 e2 e3 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* e4 e5 e6 e7 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* e8 e9 ea eb */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* ec ed ee ef */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* f0 f1 f2 f3 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* f4 f5 f6 f7 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* f8 f9 fa fb */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* fc fd fe ff */ _MB1|_MB2, 0, 0, 0, }; unsigned short _mbmap_big5[256] = { /* This is latest big5 charmap, so called "Big5+" */ /* first byte 0x81 - 0xfe */ /* second byte 0x40 - 0x7e, 0x80 - 0xfe */ /* 0x00 - 0x3f = 0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0x40 - 0x7e = 2 */ _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, /* 0x7f = 0 */ _MB2, _MB2, _MB2, 0, /* 0x80 = 2, 0x81 - 0xfe = 3 */ _MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, - _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, - _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, + _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, + _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, /* 0xff = 0 */ _MB1|_MB2, _MB1|_MB2, _MB1|_MB2, 0, }; unsigned short _mbmap_utf8[256] = { /* utf8 uses up to 6 bytes */ /* first byte 0xc0 - 0xfd */ /* any further bytes 0x80 - 0xbf */ /* 0 - 7f all 0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 80 - bf : all _MB2 */ _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, _MB2, /* c0 - fc : all _MB1 */ _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, /* f8 f9 fa fb fc fd fe ff*/ _MB1, _MB1, _MB1, _MB1, _MB1, _MB1, 0, 0 }; #endif /* defined(KANJI) && defined(SHORT_STRINGS) && defined(DSPMBYTE) */ #ifndef NLS /* _cmap_lower, _cmap_upper for ISO 8859/1 */ unsigned char _cmap_lower[256] = { 0000, 0001, 0002, 0003, 0004, 0005, 0006, 0007, 0010, 0011, 0012, 0013, 0014, 0015, 0016, 0017, 0020, 0021, 0022, 0023, 0024, 0025, 0026, 0027, 0030, 0031, 0032, 0033, 0034, 0035, 0036, 0037, 0040, 0041, 0042, 0043, 0044, 0045, 0046, 0047, 0050, 0051, 0052, 0053, 0054, 0055, 0056, 0057, 0060, 0061, 0062, 0063, 0064, 0065, 0066, 0067, 0070, 0071, 0072, 0073, 0074, 0075, 0076, 0077, 0100, 0141, 0142, 0143, 0144, 0145, 0146, 0147, 0150, 0151, 0152, 0153, 0154, 0155, 0156, 0157, 0160, 0161, 0162, 0163, 0164, 0165, 0166, 0167, 0170, 0171, 0172, 0133, 0134, 0135, 0136, 0137, 0140, 0141, 0142, 0143, 0144, 0145, 0146, 0147, 0150, 0151, 0152, 0153, 0154, 0155, 0156, 0157, 0160, 0161, 0162, 0163, 0164, 0165, 0166, 0167, 0170, 0171, 0172, 0173, 0174, 0175, 0176, 0177, 0200, 0201, 0202, 0203, 0204, 0205, 0206, 0207, 0210, 0211, 0212, 0213, 0214, 0215, 0216, 0217, 0220, 0221, 0222, 0223, 0224, 0225, 0226, 0227, 0230, 0231, 0232, 0233, 0234, 0235, 0236, 0237, 0240, 0241, 0242, 0243, 0244, 0245, 0246, 0247, 0250, 0251, 0252, 0253, 0254, 0255, 0256, 0257, 0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267, 0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277, 0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347, 0350, 0351, 0352, 0353, 0354, 0355, 0356, 0357, 0360, 0361, 0362, 0363, 0364, 0365, 0366, 0327, 0370, 0371, 0372, 0373, 0374, 0375, 0376, 0337, 0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347, 0350, 0351, 0352, 0353, 0354, 0355, 0356, 0357, 0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367, 0370, 0371, 0372, 0373, 0374, 0375, 0376, 0377, }; unsigned char _cmap_upper[256] = { 0000, 0001, 0002, 0003, 0004, 0005, 0006, 0007, 0010, 0011, 0012, 0013, 0014, 0015, 0016, 0017, 0020, 0021, 0022, 0023, 0024, 0025, 0026, 0027, 0030, 0031, 0032, 0033, 0034, 0035, 0036, 0037, 0040, 0041, 0042, 0043, 0044, 0045, 0046, 0047, 0050, 0051, 0052, 0053, 0054, 0055, 0056, 0057, 0060, 0061, 0062, 0063, 0064, 0065, 0066, 0067, 0070, 0071, 0072, 0073, 0074, 0075, 0076, 0077, 0100, 0101, 0102, 0103, 0104, 0105, 0106, 0107, 0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117, 0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127, 0130, 0131, 0132, 0133, 0134, 0135, 0136, 0137, 0140, 0101, 0102, 0103, 0104, 0105, 0106, 0107, 0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117, 0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127, 0130, 0131, 0132, 0173, 0174, 0175, 0176, 0177, 0200, 0201, 0202, 0203, 0204, 0205, 0206, 0207, 0210, 0211, 0212, 0213, 0214, 0215, 0216, 0217, 0220, 0221, 0222, 0223, 0224, 0225, 0226, 0227, 0230, 0231, 0232, 0233, 0234, 0235, 0236, 0237, 0240, 0241, 0242, 0243, 0244, 0245, 0246, 0247, 0250, 0251, 0252, 0253, 0254, 0255, 0256, 0257, 0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267, 0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277, 0300, 0301, 0302, 0303, 0304, 0305, 0306, 0307, 0310, 0311, 0312, 0313, 0314, 0315, 0316, 0317, 0320, 0321, 0322, 0323, 0324, 0325, 0326, 0327, 0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337, 0300, 0301, 0302, 0303, 0304, 0305, 0306, 0307, 0310, 0311, 0312, 0313, 0314, 0315, 0316, 0317, 0320, 0321, 0322, 0323, 0324, 0325, 0326, 0367, 0330, 0331, 0332, 0333, 0334, 0335, 0336, 0377, }; #endif /* NLS */ #ifdef _OSD_POSIX /* Initial Port for tcsh-6.07.04 by "BS2000 OSD" is a POSIX on a main frame. It is made by Siemens Nixdorf AG, Germany. Within the POSIX subsystem, the same character set was chosen as in "native BS2000", namely EBCDIC. Yes, tcsh now runs on EBCDIC platforms, too. EBCDIC Table. (Yes, in EBCDIC, the letters 'a'..'z' are not contiguous!) This table is bijective, i.e. there are no ambigous or duplicate characters 00 00 01 02 03 85 09 86 7f 87 8d 8e 0b 0c 0d 0e 0f * ................ * 10 10 11 12 13 8f 0a 08 97 18 19 9c 9d 1c 1d 1e 1f * ................ * 20 80 81 82 83 84 92 17 1b 88 89 8a 8b 8c 05 06 07 * ................ * 30 90 91 16 93 94 95 96 04 98 99 9a 9b 14 15 9e 1a * ................ * 40 20 a0 e2 e4 e0 e1 e3 e5 e7 f1 60 2e 3c 28 2b 7c * .........`.<(+| * 50 26 e9 ea eb e8 ed ee ef ec df 21 24 2a 29 3b 9f * &.........!$*);. * 60 2d 2f c2 c4 c0 c1 c3 c5 c7 d1 5e 2c 25 5f 3e 3f * -/........^,%_>? * 70 f8 c9 ca cb c8 cd ce cf cc a8 3a 23 40 27 3d 22 * ..........:#@'=" * 80 d8 61 62 63 64 65 66 67 68 69 ab bb f0 fd fe b1 * .abcdefghi...... * 90 b0 6a 6b 6c 6d 6e 6f 70 71 72 aa ba e6 b8 c6 a4 * .jklmnopqr...... * a0 b5 af 73 74 75 76 77 78 79 7a a1 bf d0 dd de ae * ..stuvwxyz...... * b0 a2 a3 a5 b7 a9 a7 b6 bc bd be ac 5b 5c 5d b4 d7 * ...........[\].. * c0 f9 41 42 43 44 45 46 47 48 49 ad f4 f6 f2 f3 f5 * .ABCDEFGHI...... * d0 a6 4a 4b 4c 4d 4e 4f 50 51 52 b9 fb fc db fa ff * .JKLMNOPQR...... * e0 d9 f7 53 54 55 56 57 58 59 5a b2 d4 d6 d2 d3 d5 * ..STUVWXYZ...... * f0 30 31 32 33 34 35 36 37 38 39 b3 7b dc 7d da 7e * 0123456789.{.}.~ * */ unsigned short _toascii[256] = { /*00*/ 0x00, 0x01, 0x02, 0x03, 0x85, 0x09, 0x86, 0x7f, 0x87, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* ................ */ /*10*/ 0x10, 0x11, 0x12, 0x13, 0x8f, 0x0a, 0x08, 0x97, 0x18, 0x19, 0x9c, 0x9d, 0x1c, 0x1d, 0x1e, 0x1f, /* ................ */ /*20*/ 0x80, 0x81, 0x82, 0x83, 0x84, 0x92, 0x17, 0x1b, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, /* ................ */ /*30*/ 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, /* ................ */ /*40*/ 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5, 0xe7, 0xf1, 0x60, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, /* .........`.<(+| */ /*50*/ 0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef, 0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x9f, /* &.........!$*);. */ /*60*/ 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5, 0xc7, 0xd1, 0x5e, 0x2c, 0x25, 0x5f, 0x3e, 0x3f, /* -/........^,%_>? */ /*70*/ 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf, 0xcc, 0xa8, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, /* ..........:#@'=" */ /*80*/ 0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, /* .abcdefghi...... */ /*90*/ 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, /* .jklmnopqr...... */ /*a0*/ 0xb5, 0xaf, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0xdd, 0xde, 0xae, /* ..stuvwxyz...... */ /*b0*/ 0xa2, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc, 0xbd, 0xbe, 0xac, 0x5b, 0x5c, 0x5d, 0xb4, 0xd7, /* ...........[\].. */ /*c0*/ 0xf9, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, /* .ABCDEFGHI...... */ /*d0*/ 0xa6, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xdb, 0xfa, 0xff, /* .JKLMNOPQR...... */ /*e0*/ 0xd9, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, /* ..STUVWXYZ...... */ /*f0*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xb3, 0x7b, 0xdc, 0x7d, 0xda, 0x7e /* 0123456789.{.}.~ */ }; /* The same, for ascii-in-ebcdic 00 00 01 02 03 37 2d 2e 2f 16 05 15 0b 0c 0d 0e 0f * ................ * 10 10 11 12 13 3c 3d 32 26 18 19 3f 27 1c 1d 1e 1f * ................ * 20 40 5a 7f 7b 5b 6c 50 7d 4d 5d 5c 4e 6b 60 4b 61 * !"#$%&'()*+,-./ * 30 f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 7a 5e 4c 7e 6e 6f * 0123456789:;<=>? * 40 7c c1 c2 c3 c4 c5 c6 c7 c8 c9 d1 d2 d3 d4 d5 d6 * @ABCDEFGHIJKLMNO * 50 d7 d8 d9 e2 e3 e4 e5 e6 e7 e8 e9 bb bc bd 6a 6d * PQRSTUVWXYZ[\]^_ * 60 4a 81 82 83 84 85 86 87 88 89 91 92 93 94 95 96 * `abcdefghijklmno * 70 97 98 99 a2 a3 a4 a5 a6 a7 a8 a9 fb 4f fd ff 07 * pqrstuvwxyz{|}~. * 80 20 21 22 23 24 04 06 08 28 29 2a 2b 2c 09 0a 14 * ................ * 90 30 31 25 33 34 35 36 17 38 39 3a 3b 1a 1b 3e 5f * ................ * a0 41 aa b0 b1 9f b2 d0 b5 79 b4 9a 8a ba ca af a1 * ................ * b0 90 8f ea fa be a0 b6 b3 9d da 9b 8b b7 b8 b9 ab * ................ * c0 64 65 62 66 63 67 9e 68 74 71 72 73 78 75 76 77 * ................ * d0 ac 69 ed ee eb ef ec bf 80 e0 fe dd fc ad ae 59 * ................ * e0 44 45 42 46 43 47 9c 48 54 51 52 53 58 55 56 57 * ................ * f0 8c 49 cd ce cb cf cc e1 70 c0 de db dc 8d 8e df * ................ * */ unsigned short _toebcdic[256] = { /*00*/ 0x00, 0x01, 0x02, 0x03, 0x37, 0x2d, 0x2e, 0x2f, 0x16, 0x05, 0x15, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* ................ */ /*10*/ 0x10, 0x11, 0x12, 0x13, 0x3c, 0x3d, 0x32, 0x26, 0x18, 0x19, 0x3f, 0x27, 0x1c, 0x1d, 0x1e, 0x1f, /* ................ */ /*20*/ 0x40, 0x5a, 0x7f, 0x7b, 0x5b, 0x6c, 0x50, 0x7d, 0x4d, 0x5d, 0x5c, 0x4e, 0x6b, 0x60, 0x4b, 0x61, /* !"#$%&'()*+,-./ */ /*30*/ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0x7a, 0x5e, 0x4c, 0x7e, 0x6e, 0x6f, /* 0123456789:;<=>? */ /*40*/ 0x7c, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, /* @ABCDEFGHIJKLMNO */ /*50*/ 0xd7, 0xd8, 0xd9, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xbb, 0xbc, 0xbd, 0x6a, 0x6d, /* PQRSTUVWXYZ[\]^_ */ /*60*/ 0x4a, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, /* `abcdefghijklmno */ /*70*/ 0x97, 0x98, 0x99, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xfb, 0x4f, 0xfd, 0xff, 0x07, /* pqrstuvwxyz{|}~. */ /*80*/ 0x20, 0x21, 0x22, 0x23, 0x24, 0x04, 0x06, 0x08, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x09, 0x0a, 0x14, /* ................ */ /*90*/ 0x30, 0x31, 0x25, 0x33, 0x34, 0x35, 0x36, 0x17, 0x38, 0x39, 0x3a, 0x3b, 0x1a, 0x1b, 0x3e, 0x5f, /* ................ */ /*a0*/ 0x41, 0xaa, 0xb0, 0xb1, 0x9f, 0xb2, 0xd0, 0xb5, 0x79, 0xb4, 0x9a, 0x8a, 0xba, 0xca, 0xaf, 0xa1, /* ................ */ /*b0*/ 0x90, 0x8f, 0xea, 0xfa, 0xbe, 0xa0, 0xb6, 0xb3, 0x9d, 0xda, 0x9b, 0x8b, 0xb7, 0xb8, 0xb9, 0xab, /* ................ */ /*c0*/ 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9e, 0x68, 0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, /* ................ */ /*d0*/ 0xac, 0x69, 0xed, 0xee, 0xeb, 0xef, 0xec, 0xbf, 0x80, 0xe0, 0xfe, 0xdd, 0xfc, 0xad, 0xae, 0x59, /* ................ */ /*e0*/ 0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9c, 0x48, 0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, /* ................ */ /*f0*/ 0x8c, 0x49, 0xcd, 0xce, 0xcb, 0xcf, 0xcc, 0xe1, 0x70, 0xc0, 0xde, 0xdb, 0xdc, 0x8d, 0x8e, 0xdf /* ................ */ }; #endif /*_OSD_POSIX*/ #ifdef __MVS__ -/* - The IBM 1047 coded char set to/from ISO 8859-1 mapping differs from +/* + The IBM 1047 coded char set to/from ISO 8859-1 mapping differs from the POSIX-BC mapping in several places */ unsigned short _toascii[256] = { - 0x00, 0x01, 0x02, 0x03, 0x9c, 0x09, 0x86, 0x7f, - 0x97, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x9d, 0x0a, 0x08, 0x87, - 0x18, 0x19, 0x92, 0x8f, 0x1c, 0x1d, 0x1e, 0x1f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x17, 0x1b, - 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, - 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, - 0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, - 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5, - 0xe7, 0xf1, 0xa2, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, - 0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef, - 0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x5e, - 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5, - 0xc7, 0xd1, 0xa6, 0x2c, 0x25, 0x5f, 0x3e, 0x3f, - 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf, - 0xcc, 0x60, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, - 0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, - 0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, - 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, - 0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, - 0xb5, 0x7e, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, - 0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0x5b, 0xde, 0xae, - 0xac, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc, - 0xbd, 0xbe, 0xdd, 0xa8, 0xaf, 0x5d, 0xb4, 0xd7, - 0x7b, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, - 0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, - 0x7d, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, - 0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xf9, 0xfa, 0xff, - 0x5c, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, - 0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, - 0x38, 0x39, 0xb3, 0xdb, 0xdc, 0xd9, 0xda, 0x9f, + 0x00, 0x01, 0x02, 0x03, 0x9c, 0x09, 0x86, 0x7f, + 0x97, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x9d, 0x0a, 0x08, 0x87, + 0x18, 0x19, 0x92, 0x8f, 0x1c, 0x1d, 0x1e, 0x1f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x17, 0x1b, + 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, + 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, + 0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, + 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5, + 0xe7, 0xf1, 0xa2, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, + 0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef, + 0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x5e, + 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5, + 0xc7, 0xd1, 0xa6, 0x2c, 0x25, 0x5f, 0x3e, 0x3f, + 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf, + 0xcc, 0x60, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, + 0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, + 0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, + 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, + 0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, + 0xb5, 0x7e, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, + 0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0x5b, 0xde, 0xae, + 0xac, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc, + 0xbd, 0xbe, 0xdd, 0xa8, 0xaf, 0x5d, 0xb4, 0xd7, + 0x7b, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, + 0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, + 0x7d, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, + 0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xf9, 0xfa, 0xff, + 0x5c, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0xb3, 0xdb, 0xdc, 0xd9, 0xda, 0x9f, }; unsigned short _toebcdic[256] = { - 0x00, 0x01, 0x02, 0x03, 0x37, 0x2d, 0x2e, 0x2f, - 0x16, 0x05, 0x15, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x3c, 0x3d, 0x32, 0x26, - 0x18, 0x19, 0x3f, 0x27, 0x1c, 0x1d, 0x1e, 0x1f, - 0x40, 0x5a, 0x7f, 0x7b, 0x5b, 0x6c, 0x50, 0x7d, - 0x4d, 0x5d, 0x5c, 0x4e, 0x6b, 0x60, 0x4b, 0x61, - 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, - 0xf8, 0xf9, 0x7a, 0x5e, 0x4c, 0x7e, 0x6e, 0x6f, - 0x7c, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, - 0xc8, 0xc9, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, - 0xd7, 0xd8, 0xd9, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, - 0xe7, 0xe8, 0xe9, 0xad, 0xe0, 0xbd, 0x5f, 0x6d, - 0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, - 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, - 0x97, 0x98, 0x99, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, - 0xa7, 0xa8, 0xa9, 0xc0, 0x4f, 0xd0, 0xa1, 0x07, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x06, 0x17, - 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x09, 0x0a, 0x1b, - 0x30, 0x31, 0x1a, 0x33, 0x34, 0x35, 0x36, 0x08, - 0x38, 0x39, 0x3a, 0x3b, 0x04, 0x14, 0x3e, 0xff, - 0x41, 0xaa, 0x4a, 0xb1, 0x9f, 0xb2, 0x6a, 0xb5, - 0xbb, 0xb4, 0x9a, 0x8a, 0xb0, 0xca, 0xaf, 0xbc, - 0x90, 0x8f, 0xea, 0xfa, 0xbe, 0xa0, 0xb6, 0xb3, - 0x9d, 0xda, 0x9b, 0x8b, 0xb7, 0xb8, 0xb9, 0xab, - 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9e, 0x68, - 0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, - 0xac, 0x69, 0xed, 0xee, 0xeb, 0xef, 0xec, 0xbf, - 0x80, 0xfd, 0xfe, 0xfb, 0xfc, 0xba, 0xae, 0x59, - 0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9c, 0x48, - 0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, - 0x8c, 0x49, 0xcd, 0xce, 0xcb, 0xcf, 0xcc, 0xe1, - 0x70, 0xdd, 0xde, 0xdb, 0xdc, 0x8d, 0x8e, 0xdf + 0x00, 0x01, 0x02, 0x03, 0x37, 0x2d, 0x2e, 0x2f, + 0x16, 0x05, 0x15, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x3c, 0x3d, 0x32, 0x26, + 0x18, 0x19, 0x3f, 0x27, 0x1c, 0x1d, 0x1e, 0x1f, + 0x40, 0x5a, 0x7f, 0x7b, 0x5b, 0x6c, 0x50, 0x7d, + 0x4d, 0x5d, 0x5c, 0x4e, 0x6b, 0x60, 0x4b, 0x61, + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, + 0xf8, 0xf9, 0x7a, 0x5e, 0x4c, 0x7e, 0x6e, 0x6f, + 0x7c, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, + 0xc8, 0xc9, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, + 0xd7, 0xd8, 0xd9, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, + 0xe7, 0xe8, 0xe9, 0xad, 0xe0, 0xbd, 0x5f, 0x6d, + 0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, + 0x97, 0x98, 0x99, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, + 0xa7, 0xa8, 0xa9, 0xc0, 0x4f, 0xd0, 0xa1, 0x07, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x06, 0x17, + 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x09, 0x0a, 0x1b, + 0x30, 0x31, 0x1a, 0x33, 0x34, 0x35, 0x36, 0x08, + 0x38, 0x39, 0x3a, 0x3b, 0x04, 0x14, 0x3e, 0xff, + 0x41, 0xaa, 0x4a, 0xb1, 0x9f, 0xb2, 0x6a, 0xb5, + 0xbb, 0xb4, 0x9a, 0x8a, 0xb0, 0xca, 0xaf, 0xbc, + 0x90, 0x8f, 0xea, 0xfa, 0xbe, 0xa0, 0xb6, 0xb3, + 0x9d, 0xda, 0x9b, 0x8b, 0xb7, 0xb8, 0xb9, 0xab, + 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9e, 0x68, + 0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, + 0xac, 0x69, 0xed, 0xee, 0xeb, 0xef, 0xec, 0xbf, + 0x80, 0xfd, 0xfe, 0xfb, 0xfc, 0xba, 0xae, 0x59, + 0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9c, 0x48, + 0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, + 0x8c, 0x49, 0xcd, 0xce, 0xcb, 0xcf, 0xcc, 0xe1, + 0x70, 0xdd, 0xde, 0xdb, 0xdc, 0x8d, 0x8e, 0xdf }; #endif /*__MVS__*/ diff --git a/contrib/tcsh/sh.char.h b/contrib/tcsh/sh.char.h index ee468184c6ee..fea7441de70c 100644 --- a/contrib/tcsh/sh.char.h +++ b/contrib/tcsh/sh.char.h @@ -1,312 +1,312 @@ /* * sh.char.h: Table for spotting special characters quickly * Makes for very obscure but efficient coding. */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _h_sh_char #define _h_sh_char #if defined(NeXT) && defined(NLS) # include #else # include # ifdef WIDE_STRINGS # ifdef HAVE_WCTYPE_H # include # else # include # endif # endif #endif typedef unsigned char tcshuc; #ifdef _MINIX # undef _SP #endif /* _MINIX */ extern unsigned short _cmap[]; #if defined(DSPMBYTE) # define CHECK_MBYTEVAR STRdspmbyte #endif extern unsigned short _cmap_c[]; extern unsigned short _cmap_mbyte[]; extern short _enable_mbdisp; extern unsigned short _mbmap[]; extern unsigned short _mbmap_euc[]; extern unsigned short _mbmap_sjis[]; extern unsigned short _mbmap_big5[]; extern unsigned short _mbmap_utf8[]; /* VARIABLE Check str */ /* same compiler require #define even not define DSPMBYTE */ #undef _MB1 #define _MB1 0x0001 #undef _MB2 #define _MB2 0x0002 #ifndef NLS extern tcshuc _cmap_lower[], _cmap_upper[]; #endif #ifndef __QNXNTO__ #undef _QF #define _QF 0x0001 /* '" (Forward quotes) */ #undef _QB #define _QB 0x0002 /* ` (Backquote) */ #undef _SP #define _SP 0x0004 /* space and tab */ #else #undef _XD #define _XD 0x0001 /* As in */ #undef _UP #define _UP 0x0002 /* As in */ #undef _SP #define _SP 0x0004 /* As in */ #endif #undef _NL #define _NL 0x0008 /* \n */ #undef _META #define _META 0x0010 /* lex meta characters, sp #'`";&<>()|\t\n */ #undef _GLOB #define _GLOB 0x0020 /* glob characters, *?{[` */ #undef _ESC #define _ESC 0x0040 /* \ */ #undef _DOL #define _DOL 0x0080 /* $ */ #undef _DIG #define _DIG 0x0100 /* 0-9 */ #undef _LET #define _LET 0x0200 /* a-z, A-Z, _, or locale-specific */ #ifndef __QNXNTO__ #undef _UP #define _UP 0x0400 /* A-Z, or locale-specific */ #else #undef _QF #define _QF 0x0400 /* '" (Forward quotes) */ #endif #undef _DOW #define _DOW 0x0800 /* a-z, or locale-specific */ #ifndef __QNXNTO__ #undef _XD #define _XD 0x1000 /* 0-9, a-f, A-F */ #else #undef _QB #define _QB 0x1000 /* 0-9, a-f, A-F */ #endif #undef _CMD #define _CMD 0x2000 /* lex end of command chars, ;&(|` */ #undef _CTR #define _CTR 0x4000 /* control */ #undef _PUN #define _PUN 0x8000 /* punctuation */ #ifdef IS_ASCII # define ASC(ch) (ch) # define CTL_ESC(ch) (ch) #else # ifdef _OSD_POSIX /* "BS2000 OSD" is a POSIX on a main frame using a EBCDIC char set */ # include # else /* "OS/390 USS" is a POSIX on a main frame using an IBM1047 char set */ # endif extern unsigned short _toascii[256]; extern unsigned short _toebcdic[256]; /* mainly for comparisons if (ASC(ch)=='\177')... */ # define ASC(ch) _toascii[(tcshuc)(ch)] /* Literal escapes ('\010') must be mapped to EBCDIC, * for C-Escapes ('\b'), the compiler already does it. */ # define CTL_ESC(ch) _toebcdic[(tcshuc)(ch)] #endif /*IS_ASCII*/ #ifdef WIDE_STRINGS # define cmap(c, bits) \ (((c) & QUOTE) || (unsigned int)(c) >= 0x0080 ? 0 : \ (_cmap[(tcshuc)ASC(c)] & (bits))) #elif defined(SHORT_STRINGS) && defined(KANJI) # define cmap(c, bits) \ ((((c) & QUOTE) || ((tcshuc)(ASC(c) & 0x80) && adrof(STRnokanji))) ? \ 0 : (_cmap[(tcshuc)ASC(c)] & (bits))) #else /* SHORT_STRINGS && KANJI */ # define cmap(c, bits) \ (((c) & QUOTE) ? 0 : (_cmap[(tcshuc)ASC(c)] & (bits))) #endif /* SHORT_STRINGS && KANJI */ #define isglob(c) cmap((c), _GLOB) #define isspc(c) cmap((c), _SP) #define ismeta(c) cmap((c), _META) #define iscmdmeta(c) cmap((c), _CMD) #ifdef WIDE_STRINGS #define letter(c) (((c) & QUOTE) ? 0 : \ (iswalpha((c)) || (c) == '_')) #define alnum(c) (((c) & QUOTE) ? 0 : \ (iswalnum((c)) || (c) == '_')) #else #define letter(c) (((Char)(c) & QUOTE) ? 0 : \ ((isalpha((c)) && !(cmap((c), _PUN))) \ || (c) == '_')) #define alnum(c) (((Char)(c) & QUOTE) ? 0 : \ ((isalnum((c)) && !(cmap((c), _PUN))) \ || (c) == '_')) #endif #if defined(DSPMBYTE) # define IsmbyteU(c) (Ismbyte1((Char)(c))||(Ismbyte2((Char)(c))&&((c)&0200))) #endif #ifdef NLS # ifdef WIDE_STRINGS # define Isspace(c) (((c) & QUOTE) ? 0 : iswspace(c)) # define Isdigit(c) (((c) & QUOTE) ? 0 : iswdigit(c)) # define Isalpha(c) (((c) & QUOTE) ? 0 : iswalpha(c)) # define Islower(c) (((c) & QUOTE) ? 0 : iswlower(c)) # define Isupper(c) (((c) & QUOTE) ? 0 : iswupper(c)) # define Tolower(c) (((c) & QUOTE) ? 0 : (wchar_t)towlower(c)) # define Toupper(c) (((c) & QUOTE) ? 0 : (wchar_t)towupper(c)) # define Isxdigit(c) (((c) & QUOTE) ? 0 : iswxdigit(c)) # define Isalnum(c) (((c) & QUOTE) ? 0 : iswalnum(c)) # define Iscntrl(c) (((c) & QUOTE) ? 0 : iswcntrl(c)) # define Isprint(c) (((c) & QUOTE) ? 0 : iswprint(c)) # define Ispunct(c) (((c) & QUOTE) ? 0 : iswpunct(c)) # elif defined (NeXT) # define Isspace(c) (((Char)(c) & QUOTE) ? 0 : NXIsSpace((unsigned) (c))) # define Isdigit(c) (((Char)(c) & QUOTE) ? 0 : NXIsDigit((unsigned) (c))) # define Isalpha(c) (((Char)(c) & QUOTE) ? 0 : NXIsAlpha((unsigned) (c))) # define Islower(c) (((Char)(c) & QUOTE) ? 0 : NXIsLower((unsigned) (c))) # define Isupper(c) (((Char)(c) & QUOTE) ? 0 : NXIsUpper((unsigned) (c))) # define Tolower(c) (((Char)(c) & QUOTE) ? 0 : NXToLower((unsigned) (c))) # define Toupper(c) (((Char)(c) & QUOTE) ? 0 : NXToUpper((unsigned) (c))) # define Isxdigit(c) (((Char)(c) & QUOTE) ? 0 : NXIsXDigit((unsigned) (c))) #if defined(DSPMBYTE) # define IscntrlM(c) (((Char)(c) & QUOTE) ? 0 : NXIsCntrl((unsigned) (c))) # define Iscntrl(c) ( (IscntrlM(c)) && !(_enable_mbdisp&&(IsmbyteU((c)))) ) # define IsprintM(c) (((Char)(c) & QUOTE) ? 0 : NXIsPrint((unsigned) (c))) # define Isprint(c) ( (IsprintM(c)) || (_enable_mbdisp&&(IsmbyteU((c)))) ) #else # define Isalnum(c) (((Char)(c) & QUOTE) ? 0 : NXIsAlNum((unsigned) (c))) # define Iscntrl(c) (((Char)(c) & QUOTE) ? 0 : NXIsCntrl((unsigned) (c))) # define Isprint(c) (((Char)(c) & QUOTE) ? 0 : NXIsPrint((unsigned) (c))) #endif /* !defined(DSPMBYTE) */ # define Ispunct(c) (((Char)(c) & QUOTE) ? 0 : NXIsPunct((unsigned) (c))) # else /* !NeXT */ # ifndef WINNT_NATIVE # define Isspace(c) (((Char)(c) & QUOTE) ? 0 : isspace((tcshuc) (c))) # define Isdigit(c) (((Char)(c) & QUOTE) ? 0 : isdigit((tcshuc) (c))) # define Isalpha(c) (((Char)(c) & QUOTE) ? 0 : isalpha((tcshuc) (c))) # define Islower(c) (((Char)(c) & QUOTE) ? 0 : islower((tcshuc) (c))) # define Isupper(c) (((Char)(c) & QUOTE) ? 0 : isupper((tcshuc) (c))) # define Tolower(c) (((Char)(c) & QUOTE) ? 0 : tolower((tcshuc) (c))) # define Toupper(c) (((Char)(c) & QUOTE) ? 0 : toupper((tcshuc) (c))) # define Isxdigit(c) (((Char)(c) & QUOTE) ? 0 : isxdigit((tcshuc) (c))) # define Isalnum(c) (((Char)(c) & QUOTE) ? 0 : isalnum((tcshuc) (c))) #if defined(DSPMBYTE) # define IscntrlM(c) (((Char)(c) & QUOTE) ? 0 : iscntrl((tcshuc) (c))) # define Iscntrl(c) ( (IscntrlM(c)) && !(_enable_mbdisp&&(IsmbyteU((c)))) ) #else # define Iscntrl(c) (((Char)(c) & QUOTE) ? 0 : iscntrl((tcshuc) (c))) #endif /* !defined(DSPMBYTE) */ # if SOLARIS2 == 24 - /* + /* * From Casper Dik: * In Solaris 2.4, isprint('\t') returns true after setlocal(LC_ALL,""). * This breaks commandline editing when you include tabs. * (This is in the en_US locale). */ #if defined(DSPMBYTE) # define IsprintM(c) (((Char)(c) & QUOTE) ? 0 : \ (isprint((tcshuc) (c)) && (c) != '\t')) #else # define Isprint(c) (((Char)(c) & QUOTE) ? 0 : \ (isprint((tcshuc) (c)) && (c) != '\t')) #endif /* !defined(DSPMBYTE) */ # else #if defined(DSPMBYTE) # define IsprintM(c) (((Char)(c) & QUOTE) ? 0 : isprint((tcshuc) (c))) #else # define Isprint(c) (((Char)(c) & QUOTE) ? 0 : isprint((tcshuc) (c))) #endif /* !defined(DSPMBYTE) */ # endif /* SOLARIS2 == 24 */ #if defined(DSPMBYTE) # define Isprint(c) ( (IsprintM(c)) || (_enable_mbdisp&&(IsmbyteU((c)))) ) #endif /* !defined(DSPMBYTE) */ # define Ispunct(c) (((Char)(c) & QUOTE) ? 0 : ispunct((tcshuc) (c))) # else /* WINNT_NATIVE */ # define Isspace(c) (((Char)(c) & QUOTE) ? 0 : isspace( oem_it((tcshuc)(c)))) # define Isdigit(c) (((Char)(c) & QUOTE) ? 0 : isdigit( oem_it((tcshuc)(c)))) # define Isalpha(c) (((Char)(c) & QUOTE) ? 0 : isalpha( oem_it((tcshuc)(c)))) # define Islower(c) (((Char)(c) & QUOTE) ? 0 : islower( oem_it((tcshuc)(c)))) # define Isupper(c) (((Char)(c) & QUOTE) ? 0 : isupper( oem_it((tcshuc)(c)))) # define Tolower(c) (((Char)(c) & QUOTE) ? 0 : tolower( oem_it((tcshuc)(c)))) # define Toupper(c) (((Char)(c) & QUOTE) ? 0 : toupper( oem_it((tcshuc)(c)))) # define Isxdigit(c)(((Char)(c) & QUOTE) ? 0 : isxdigit(oem_it((tcshuc)(c)))) # define Isalnum(c) (((Char)(c) & QUOTE) ? 0 : isalnum( oem_it((tcshuc)(c)))) # define Ispunct(c) (((Char)(c) & QUOTE) ? 0 : ispunct( oem_it((tcshuc)(c)))) #if defined(DSPMBYTE) # define IscntrlM(c) (((Char)(c) & QUOTE) ? 0 : iscntrl( oem_it((tcshuc)(c)))) # define Iscntrl(c) ( (IscntrlM(c)) && !(_enable_mbdisp&&(IsmbyteU((c)))) ) # define IsprintM(c) (((Char)(c) & QUOTE) ? 0 : isprint( oem_it((tcshuc)(c)))) # define Isprint(c) ( (IsprintM(c)) || (_enable_mbdisp&&(IsmbyteU((c)))) ) #else # define Iscntrl(c) (((Char)(c) & QUOTE) ? 0 : iscntrl( oem_it((tcshuc)(c)))) # define Isprint(c) (((Char)(c) & QUOTE) ? 0 : isprint( oem_it((tcshuc)(c)))) #endif /* !defined(DSPMBYTE) */ # endif /* WINNT_NATIVE */ # endif /* !NeXT */ #else /* !NLS */ # define Isspace(c) cmap((c), _SP|_NL) # define Isdigit(c) cmap((c), _DIG) # define Isalpha(c) (cmap((c),_LET) && !(((c) & META) && AsciiOnly)) # define Islower(c) (cmap((c),_DOW) && !(((c) & META) && AsciiOnly)) # define Isupper(c) (cmap((c), _UP) && !(((c) & META) && AsciiOnly)) # define Tolower(c) (_cmap_lower[ASC(c)]) # define Toupper(c) (_cmap_upper[ASC(c)]) # define Isxdigit(c) cmap((c), _XD) # define Isalnum(c) (cmap((c), _DIG|_LET) && !(((Char)(c) & META) && AsciiOnly)) #if defined(DSPMBYTE) # define IscntrlM(c) (cmap((c),_CTR) && !(((c) & META) && AsciiOnly)) # define Iscntrl(c) ( (IscntrlM(c)) && !(_enable_mbdisp&&(IsmbyteU((c)))) ) # define IsprintM(c) (!cmap((c),_CTR) && !(((c) & META) && AsciiOnly)) # define Isprint(c) ( (IsprintM(c)) || (_enable_mbdisp&&(IsmbyteU((c)))) ) #else # define Iscntrl(c) (cmap((c),_CTR) && !(((c) & META) && AsciiOnly)) # define Isprint(c) (!cmap((c),_CTR) && !(((c) & META) && AsciiOnly)) #endif /* !defined(DSPMBYTE) */ # define Ispunct(c) (cmap((c),_PUN) && !(((c) & META) && AsciiOnly)) #endif /* !NLS */ #if defined(DSPMBYTE) # define Ismbyte1(c) ((_mbmap[(c) & 0377] & _MB1) ? 1 : 0) # define Ismbyte2(c) ((_mbmap[(c) & 0377] & _MB2) ? 1 : 0) #endif #endif /* _h_sh_char */ diff --git a/contrib/tcsh/sh.decls.h b/contrib/tcsh/sh.decls.h index 4e1bc12277cb..e230becd8e0e 100644 --- a/contrib/tcsh/sh.decls.h +++ b/contrib/tcsh/sh.decls.h @@ -1,447 +1,447 @@ /* * sh.decls.h External declarations from sh*.c */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _h_sh_decls #define _h_sh_decls /* * sh.c */ extern Char *gethdir (const Char *); extern void dosource (Char **, struct command *); -extern void exitstat (void); +extern void exitstat (void) __attribute__((__noreturn__)); extern void goodbye (Char **, struct command *); extern void importpath (Char *); extern void initdesc (void); extern void pintr (void); extern void pintr1 (int); extern void phup (void); extern void process (int); extern void untty (void); #ifdef PROF extern void done (int) __attribute__((__noreturn__)); #else extern void xexit (int) __attribute__((__noreturn__)); #endif extern int grabpgrp (int, pid_t); /* * sh.dir.c */ extern void dinit (Char *); extern void dodirs (Char **, struct command *); extern Char *dcanon (Char *, Char *); extern void dtildepr (Char *); extern void dtilde (void); extern void dochngd (Char **, struct command *); extern Char *dnormalize (const Char *, int); extern void dopushd (Char **, struct command *); extern void dopopd (Char **, struct command *); extern void dfree (struct directory *); extern void dsetstack (void); extern const Char *getstakd (int); extern void recdirs (Char *, int); extern void loaddirs (Char *); /* * sh.dol.c */ extern void Dfix (struct command *); extern Char *Dfix1 (Char *); extern void heredoc (Char *); extern Char *randsuf (void); /* * sh.err.c */ extern void reset (void) __attribute__((__noreturn__)); extern void cleanup_push_internal(void *, void (*fn) (void *) #ifdef CLEANUP_DEBUG , const char *, size_t #define cleanup_push(v, f) cleanup_push_internal(v, f, __FILE__, __LINE__) #else #define cleanup_push(v, f) cleanup_push_internal(v, f) #endif ); extern int cleanup_reset(void); extern void cleanup_ignore(void *); extern void cleanup_until(void *); extern void cleanup_until_mark(void); extern size_t cleanup_push_mark(void); extern void cleanup_pop_mark(size_t); extern void open_cleanup(void *); extern void opendir_cleanup(void *); extern void sigint_cleanup(void *); extern void sigprocmask_cleanup(void *); extern void xfree_indirect(void *); extern void errinit (void); extern void seterror (unsigned int, ...); extern void fixerror (void); extern void stderror (unsigned int, ...) __attribute__((__noreturn__)); /* * sh.exec.c */ extern void doexec (struct command *, int); extern void dohash (Char **, struct command *); extern void dounhash (Char **, struct command *); extern void execash (Char **, struct command *); extern void hashstat (Char **, struct command *); extern void xechoit (Char **); extern int executable (const Char *, const Char *, int); extern int tellmewhat (struct wordent *, Char **); extern void dowhere (Char **, struct command *); extern int find_cmd (Char *, int); /* * sh.exp.c */ extern Char *filetest (Char *, Char ***, int); extern tcsh_number_t expr (Char ***); extern tcsh_number_t exp0 (Char ***, int); /* * sh.file.c */ #if defined(FILEC) && defined(TIOCSTI) extern size_t tenex (Char *, size_t); #endif /* * sh.func.c */ extern void tsetenv (const Char *, const Char *); extern void Unsetenv (Char *); extern void doalias (Char **, struct command *); extern void dobreak (Char **, struct command *); extern void docontin (Char **, struct command *); extern void doecho (Char **, struct command *); extern void doelse (Char **, struct command *); extern void doend (Char **, struct command *); extern void doeval (Char **, struct command *); extern void doexit (Char **, struct command *); extern void doforeach (Char **, struct command *); extern void doglob (Char **, struct command *); extern void dogoto (Char **, struct command *); extern void doif (Char **, struct command *); extern void dolimit (Char **, struct command *); extern void dologin (Char **, struct command *); extern void dologout (Char **, struct command *); #ifdef NEWGRP extern void donewgrp (Char **, struct command *); #endif extern void donohup (Char **, struct command *); extern void dohup (Char **, struct command *); extern void doonintr (Char **, struct command *); extern void doprintenv (Char **, struct command *); extern void dorepeat (Char **, struct command *); extern void dofiletest (Char **, struct command *); extern void dosetenv (Char **, struct command *); extern void dosuspend (Char **, struct command *); extern void doswbrk (Char **, struct command *); extern void doswitch (Char **, struct command *); extern void doumask (Char **, struct command *); extern void dounlimit (Char **, struct command *); extern void dounsetenv (Char **, struct command *); extern void dowhile (Char **, struct command *); extern void dozip (Char **, struct command *); extern void func (struct command *, const struct biltins *); extern void gotolab (Char *); extern const struct biltins *isbfunc (struct command *); extern void prvars (void); extern int srchx (Char *); extern void unalias (Char **, struct command *); extern void wfree (void); extern void dobuiltins (Char **, struct command *); extern void reexecute (struct command *); extern int getYN (const char *); /* * sh.glob.c */ extern Char *globequal (Char *); extern Char **dobackp (Char *, int); extern Char *globone (Char *, int); extern int Gmatch (const Char *, const Char *); extern int Gnmatch (const Char *, const Char *, const Char **); extern Char **globall (Char **, int); extern Char **glob_all_or_error(Char **); extern void rscan (Char **, void (*)(Char)); extern int tglob (Char **); extern void trim (Char **); #if !defined(WINNT_NATIVE) && defined(NLS_CATALOGS) extern char *xcatgets (nl_catd, int, int, const char *); #if defined(HAVE_ICONV) && defined(HAVE_NL_LANGINFO) extern char *iconv_catgets (nl_catd, int, int, const char *); #endif #endif extern void nlsinit (void); extern void nlsclose (void); extern int t_pmatch (const Char *, const Char *, const Char **, int); /* * sh.hist.c */ extern void dohist (Char **, struct command *); extern struct Hist *enthist (int, struct wordent *, int, int, int); extern void savehist (struct wordent *, int); extern char *fmthist (int, ptr_t); extern void rechist (Char *, int); extern void loadhist (Char *, int); extern void displayHistStats(const char *); extern void sethistory (int); /* * sh.init.c */ extern void mesginit (void); /* * sh.lex.c */ extern void addla (Char *); extern void bseek (struct Ain *); extern void btell (struct Ain *); extern void btoeof (void); extern void copylex (struct wordent *, struct wordent *); extern Char *domod (Char *, Char); extern void initlex (struct wordent *); extern void freelex (struct wordent *); extern int lex (struct wordent *); extern void lex_cleanup (void *); extern void prlex (struct wordent *); extern eChar readc (int); extern void settell (void); extern void unreadc (Char); extern ssize_t wide_read (int, Char *, size_t, int); /* * sh.misc.c */ extern int any (const char *, Char); extern Char **blkcpy (Char **, Char **); extern void blkfree (Char **); extern void blk_cleanup (void *); extern void blk_indirect_cleanup(void *); extern int blklen (Char **); extern void blkpr (Char *const *); extern Char *blkexpand (Char *const *); extern Char **blkspl (Char **, Char **); extern void closem (void); #ifndef CLOSE_ON_EXEC extern void closech (void); #endif /* !CLOSE_ON_EXEC */ extern Char **copyblk (Char **); extern int dcopy (int, int); extern int dmove (int, int); extern void donefds (void); extern Char lastchr (Char *); extern void lshift (Char **, int); extern int number (Char *); extern int prefix (const Char *, const Char *); extern Char **saveblk (Char **); extern void setzero (void *, size_t); extern Char *strip (Char *); extern Char *quote (Char *); extern const Char *quote_meta (struct Strbuf *, const Char *); #ifndef SHORT_STRINGS extern char *strnsave (const char *, size_t); #endif extern char *strsave (const char *); extern void udvar (Char *) __attribute__((__noreturn__)); #ifndef POSIX extern char *strstr (const char *, const char *); #endif /* !POSIX */ extern char *strspl (const char *, const char *); extern char *strend (const char *); extern char *areadlink (const char *); extern void xclose (int); extern void xclosedir (DIR *); extern int xcreat (const char *, mode_t); extern struct group *xgetgrgid (gid_t); extern struct passwd *xgetpwnam (const char *); extern struct passwd *xgetpwuid (uid_t); extern int xopen (const char *, int, ...); extern ssize_t xread (int, void *, size_t); extern int xtcsetattr (int, int, const struct termios *); extern ssize_t xwrite (int, const void *, size_t); /* * sh.parse.c */ extern void alias (struct wordent *); extern void freesyn (struct command *); extern struct command *syntax (const struct wordent *, const struct wordent *, int); extern void syntax_cleanup(void *); /* * sh.print.c */ extern void drainoline (void); extern void flush (void); #ifdef BSDTIMES extern void pcsecs (unsigned long); #else /* !BSDTIMES */ # ifdef POSIX extern void pcsecs (clock_t); # else /* !POSIX */ extern void pcsecs (time_t); # endif /* !POSIX */ #endif /* BSDTIMES */ #ifdef BSDLIMIT extern void psecs (unsigned long); #endif /* BSDLIMIT */ extern int putpure (int); extern int putraw (int); extern void xputchar (int); #ifdef WIDE_STRINGS extern void putwraw (Char); extern void xputwchar (Char); #else # define putwraw(C) putraw(C) # define xputwchar(C) xputchar(C) #endif extern void output_raw_restore(void *); /* * sh.proc.c */ extern void dobg (Char **, struct command *); extern void dobg1 (Char **, struct command *); extern void dofg (Char **, struct command *); extern void dofg1 (Char **, struct command *); extern void dojobs (Char **, struct command *); extern void dokill (Char **, struct command *); extern void donotify (Char **, struct command *); extern void dostop (Char **, struct command *); extern void dowait (Char **, struct command *); extern void palloc (pid_t, struct command *); extern void panystop (int); extern void pchild (void); extern void pendjob (void); extern pid_t pfork (struct command *, int); extern void pgetty (int, pid_t); extern void pjwait (struct process *); extern void pnote (void); extern void psavejob (void); extern void psavejob_cleanup(void *); extern int pstart (struct process *, int); extern void pwait (void); extern struct process *pfind (Char *); /* * sh.sem.c */ extern void execute (struct command *, volatile int, int *, int *, int); extern void mypipe (int *); /* * sh.set.c */ extern struct varent *adrof1 (const Char *, struct varent *); extern void doset (Char **, struct command *); extern void dolet (Char **, struct command *); extern Char *putn (tcsh_number_t); extern tcsh_number_t getn (const Char *); extern Char *value1 (Char *, struct varent *); extern void setcopy (const Char *, const Char *, int); extern void setv (const Char *, Char *, int); extern void set1 (const Char *, Char **, struct varent *, int); extern void setq (const Char *, Char **, struct varent *, int); extern void unset (Char **, struct command *); extern void unset1 (Char *[], struct varent *); extern void unsetv (Char *); extern void setNS (const Char *); extern void shift (Char **, struct command *); extern void plist (struct varent *, int); extern Char *unparse (struct command *); #if defined(DSPMBYTE) extern void update_dspmbyte_vars (void); extern void autoset_dspmbyte (const Char *); #endif #if defined(AUTOSET_KANJI) extern void autoset_kanji (void); #endif extern void update_wordchars (void); /* * sh.time.c */ extern void donice (Char **, struct command *); extern void dotime (Char **, struct command *); #ifdef BSDTIMES extern void prusage (struct sysrusage *, - struct sysrusage *, + struct sysrusage *, timeval_t *, timeval_t *); extern void ruadd (struct sysrusage *, struct sysrusage *); #else /* BSDTIMES */ # ifdef _SEQUENT_ extern void prusage (struct process_stats *, - struct process_stats *, + struct process_stats *, timeval_t *, timeval_t *); extern void ruadd (struct process_stats *, struct process_stats *); # else /* !_SEQUENT_ */ # ifdef POSIX -extern void prusage (struct tms *, struct tms *, +extern void prusage (struct tms *, struct tms *, clock_t, clock_t); # else /* !POSIX */ -extern void prusage (struct tms *, struct tms *, +extern void prusage (struct tms *, struct tms *, time_t, time_t); # endif /* !POSIX */ # endif /* !_SEQUENT_ */ #endif /* BSDTIMES */ extern void settimes (void); #if defined(BSDTIMES) || defined(_SEQUENT_) -extern void tvsub (struct timeval *, - struct timeval *, +extern void tvsub (struct timeval *, + struct timeval *, struct timeval *); #endif /* BSDTIMES || _SEQUENT_ */ /* * tw.parse.c */ extern void copyn (Char *, const Char *, size_t); extern void catn (Char *, const Char *, int); #endif /* _h_sh_decls */ diff --git a/contrib/tcsh/sh.dir.c b/contrib/tcsh/sh.dir.c index f57e9950af36..7d6b767b2e87 100644 --- a/contrib/tcsh/sh.dir.c +++ b/contrib/tcsh/sh.dir.c @@ -1,1423 +1,1423 @@ /* * sh.dir.c: Directory manipulation functions */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" /* * C Shell - directory management */ static Char *agetcwd (void); static void dstart (const char *); static struct directory *dfind (Char *); static Char *dfollow (Char *, int); static void printdirs (int); static Char *dgoto (Char *); static void dnewcwd (struct directory *, int); static void dset (Char *); static void dextract (struct directory *); static int skipargs (Char ***, const char *, const char *); static void dgetstack (void); static Char *dcanon_internal(Char *, Char *); static struct directory dhead INIT_ZERO_STRUCT; /* "head" of loop */ static int printd; /* force name to be printed */ int bequiet = 0; /* do not print dir stack -strike */ static Char * agetcwd(void) { char *buf; Char *cwd; size_t len; len = MAXPATHLEN; buf = xmalloc(len); while (getcwd(buf, len) == NULL) { int err; err = errno; if (err != ERANGE) { xfree(buf); errno = err; return NULL; } len *= 2; buf = xrealloc(buf, len); } if (*buf == '\0') { xfree(buf); return NULL; } cwd = SAVE(buf); xfree(buf); return cwd; } static void dstart(const char *from) { xprintf(CGETS(12, 1, "%s: Trying to start from \"%s\"\n"), progname, from); } /* * dinit - initialize current working directory */ void dinit(Char *hp) { Char *cp, *tcp; struct directory *dp; /* Don't believe the login shell home, because it may be a symlink */ tcp = agetcwd(); if (tcp == NULL) { xprintf("%s: %s\n", progname, strerror(errno)); if (hp && *hp) { char *xcp = short2str(hp); dstart(xcp); if (chdir(xcp) == -1) cp = NULL; else cp = Strsave(hp); } else cp = NULL; if (cp == NULL) { dstart("/"); if (chdir("/") == -1) /* I am not even try to print an error message! */ xexit(1); cp = SAVE("/"); } } else { #ifdef S_IFLNK struct stat swd, shp; int swd_ok; swd_ok = stat(short2str(tcp), &swd) == 0; /* * See if $HOME is the working directory we got and use that */ if (swd_ok && hp && *hp && stat(short2str(hp), &shp) != -1 && DEV_DEV_COMPARE(swd.st_dev, shp.st_dev) && swd.st_ino == shp.st_ino) cp = Strsave(hp); else { char *cwd; /* * use PWD if we have it (for subshells) */ if (swd_ok && (cwd = getenv("PWD")) != NULL) { if (stat(cwd, &shp) != -1 && DEV_DEV_COMPARE(swd.st_dev, shp.st_dev) && swd.st_ino == shp.st_ino) { tcp = SAVE(cwd); cleanup_push(tcp, xfree); } } cp = dcanon(tcp, STRNULL); } #else /* S_IFLNK */ cp = dcanon(tcp, STRNULL); #endif /* S_IFLNK */ } dp = xcalloc(sizeof(struct directory), 1); dp->di_name = cp; dp->di_count = 0; dhead.di_next = dhead.di_prev = dp; dp->di_next = dp->di_prev = &dhead; printd = 0; dnewcwd(dp, 0); setcopy(STRdirstack, dp->di_name, VAR_READWRITE|VAR_NOGLOB); } static void dset(Char *dp) { /* * Don't call set() directly cause if the directory contains ` or - * other junk characters glob will fail. + * other junk characters glob will fail. */ setcopy(STRowd, varval(STRcwd), VAR_READWRITE|VAR_NOGLOB); setcopy(STRcwd, dp, VAR_READWRITE|VAR_NOGLOB); tsetenv(STRPWD, dp); } #define DIR_PRINT 0x01 /* -p */ #define DIR_LONG 0x02 /* -l */ #define DIR_VERT 0x04 /* -v */ #define DIR_LINE 0x08 /* -n */ #define DIR_SAVE 0x10 /* -S */ #define DIR_LOAD 0x20 /* -L */ #define DIR_CLEAR 0x40 /* -c */ #define DIR_OLD 0x80 /* - */ static int skipargs(Char ***v, const char *dstr, const char *str) { Char **n = *v, *s; int dflag = 0, loop = 1; - for (n++; loop && *n != NULL && (*n)[0] == '-'; n++) + for (n++; loop && *n != NULL && (*n)[0] == '-'; n++) if (*(s = &((*n)[1])) == '\0') /* test for bare "-" argument */ dflag |= DIR_OLD; else if ((*n)[1] == '-' && (*n)[2] == '\0') { /* test for -- */ n++; break; } else { char *p; while (*s != '\0') /* examine flags */ { if ((p = strchr(dstr, *s++)) != NULL) dflag |= (1 << (p - dstr)); else stderror(ERR_DIRUS, short2str(**v), dstr, str); } } if (*n && (dflag & DIR_OLD)) stderror(ERR_DIRUS, short2str(**v), dstr, str); *v = n; /* make -l, -v, and -n imply -p */ if (dflag & (DIR_LONG|DIR_VERT|DIR_LINE)) dflag |= DIR_PRINT; return dflag; } /* * dodirs - list all directories in directory loop */ /*ARGSUSED*/ void dodirs(Char **v, struct command *c) { static const char flags[] = "plvnSLc"; int dflag = skipargs(&v, flags, ""); USE(c); if ((dflag & DIR_CLEAR) != 0) { struct directory *dp, *fdp; for (dp = dcwd->di_next; dp != dcwd; ) { fdp = dp; dp = dp->di_next; if (fdp != &dhead) dfree(fdp); } dhead.di_next = dhead.di_prev = dp; dp->di_next = dp->di_prev = &dhead; } - if ((dflag & DIR_LOAD) != 0) + if ((dflag & DIR_LOAD) != 0) loaddirs(*v); else if ((dflag & DIR_SAVE) != 0) recdirs(*v, 1); if (*v && (dflag & (DIR_SAVE|DIR_LOAD))) v++; if (*v != NULL || (dflag & DIR_OLD)) stderror(ERR_DIRUS, "dirs", flags, ""); if ((dflag & (DIR_CLEAR|DIR_LOAD|DIR_SAVE)) == 0 || (dflag & DIR_PRINT)) printdirs(dflag); } static void printdirs(int dflag) { struct directory *dp; Char *s, *user; int idx, len, cur; dp = dcwd; idx = 0; cur = 0; do { if (dp == &dhead) continue; if (dflag & DIR_VERT) { xprintf("%d\t", idx++); cur = 0; } - s = dp->di_name; + s = dp->di_name; user = NULL; if (!(dflag & DIR_LONG) && (user = getusername(&s)) != NULL) len = (int) (Strlen(user) + Strlen(s) + 2); else len = (int) (Strlen(s) + 1); cur += len; if ((dflag & DIR_LINE) && cur >= TermH - 1 && len < TermH) { xputchar('\n'); cur = len; } - if (user) + if (user) xprintf("~%S", user); xprintf("%-S%c", s, (dflag & DIR_VERT) ? '\n' : ' '); } while ((dp = dp->di_prev) != dcwd); if (!(dflag & DIR_VERT)) xputchar('\n'); } void dtildepr(Char *dir) { Char* user; if ((user = getusername(&dir)) != NULL) xprintf("~%-S%S", user, dir); else xprintf("%S", dir); } void dtilde(void) { struct directory *d = dcwd; do { if (d == &dhead) continue; d->di_name = dcanon_internal(d->di_name, STRNULL); } while ((d = d->di_prev) != dcwd); dset(dcwd->di_name); } /* dnormalize(): * The path will be normalized if it * 1) is "..", * 2) or starts with "../", * 3) or ends with "/..", * 4) or contains the string "/../", - * then it will be normalized, unless those strings are quoted. + * then it will be normalized, unless those strings are quoted. * Otherwise, a copy is made and sent back. */ Char * dnormalize(const Char *cp, int expnd) { /* return true if dp is of the form "../xxx" or "/../xxx" */ #define IS_DOTDOT(sp, p) (ISDOTDOT(p) && ((p) == (sp) || *((p) - 1) == '/')) #define IS_DOT(sp, p) (ISDOT(p) && ((p) == (sp) || *((p) - 1) == '/')) #ifdef S_IFLNK if (expnd) { struct Strbuf buf = Strbuf_INIT; int dotdot = 0; Char *dp, *cwd; const Char *start = cp; # ifdef HAVE_SLASHSLASH int slashslash; # endif /* HAVE_SLASHSLASH */ /* * count the number of "../xxx" or "xxx/../xxx" in the path */ for ( ; *cp && *(cp + 1); cp++) if (IS_DOTDOT(start, cp)) dotdot++; /* * if none, we are done. */ if (dotdot == 0) return (Strsave(start)); - + # ifdef notdef struct stat sb; /* * We disable this test because: * cd /tmp; mkdir dir1 dir2; cd dir2; ln -s /tmp/dir1; cd dir1; * echo ../../dir1 does not expand. We had enabled this before * because it was bothering people with expansions in compilation * lines like -I../../foo. Maybe we need some kind of finer grain * control? * * If the path doesn't exist, we are done too. */ if (lstat(short2str(start), &sb) != 0 && errno == ENOENT) return (Strsave(start)); # endif cwd = xmalloc((Strlen(dcwd->di_name) + 3) * sizeof(Char)); (void) Strcpy(cwd, dcwd->di_name); /* * If the path starts with a slash, we are not relative to * the current working directory. */ if (ABSOLUTEP(start)) *cwd = '\0'; # ifdef HAVE_SLASHSLASH slashslash = cwd[0] == '/' && cwd[1] == '/'; # endif /* HAVE_SLASHSLASH */ /* * Ignore . and count ..'s */ cp = start; do { dotdot = 0; buf.len = 0; - while (*cp) + while (*cp) if (IS_DOT(start, cp)) { if (*++cp) cp++; } else if (IS_DOTDOT(start, cp)) { if (buf.len != 0) break; /* finish analyzing .././../xxx/[..] */ dotdot++; cp += 2; if (*cp) cp++; } - else + else Strbuf_append1(&buf, *cp++); Strbuf_terminate(&buf); - while (dotdot > 0) + while (dotdot > 0) if ((dp = Strrchr(cwd, '/')) != NULL) { # ifdef HAVE_SLASHSLASH - if (dp == &cwd[1]) + if (dp == &cwd[1]) slashslash = 1; # endif /* HAVE_SLASHSLASH */ *dp = '\0'; dotdot--; } else break; if (!*cwd) { /* too many ..'s, starts with "/" */ cwd[0] = '/'; # ifdef HAVE_SLASHSLASH /* * Only append another slash, if already the former cwd * was in a double-slash path. */ cwd[1] = slashslash ? '/' : '\0'; cwd[2] = '\0'; # else /* !HAVE_SLASHSLASH */ cwd[1] = '\0'; # endif /* HAVE_SLASHSLASH */ } # ifdef HAVE_SLASHSLASH else if (slashslash && cwd[1] == '\0') { cwd[1] = '/'; cwd[2] = '\0'; } # endif /* HAVE_SLASHSLASH */ if (buf.len != 0) { size_t i; i = Strlen(cwd); if (TRM(cwd[i - 1]) != '/') { cwd[i++] = '/'; cwd[i] = '\0'; } dp = Strspl(cwd, TRM(buf.s[0]) == '/' ? &buf.s[1] : buf.s); xfree(cwd); cwd = dp; i = Strlen(cwd) - 1; if (TRM(cwd[i]) == '/') cwd[i] = '\0'; } /* Reduction of ".." following the stuff we collected in buf * only makes sense if the directory item in buf really exists. * Avoid reduction of "-I../.." (typical compiler call) to "" * or "/usr/nonexistant/../bin" to "/usr/bin": */ if (cwd[0]) { struct stat exists; if (0 != stat(short2str(cwd), &exists)) { xfree(buf.s); xfree(cwd); return Strsave(start); } } } while (*cp != '\0'); xfree(buf.s); return cwd; } #endif /* S_IFLNK */ return Strsave(cp); } /* * dochngd - implement chdir command. */ /*ARGSUSED*/ void dochngd(Char **v, struct command *c) { Char *cp; struct directory *dp; int dflag = skipargs(&v, "plvn", "[-|]"); USE(c); printd = 0; cp = (dflag & DIR_OLD) ? varval(STRowd) : *v; if (cp == NULL) { if (!cdtohome) stderror(ERR_NAME | ERR_TOOFEW); else if ((cp = varval(STRhome)) == STRNULL || *cp == 0) stderror(ERR_NAME | ERR_NOHOMEDIR); if (chdir(short2str(cp)) < 0) stderror(ERR_NAME | ERR_CANTCHANGE); cp = Strsave(cp); } else if ((dflag & DIR_OLD) == 0 && v[1] != NULL) { stderror(ERR_NAME | ERR_TOOMANY); /* NOTREACHED */ return; } else if ((dp = dfind(cp)) != 0) { char *tmp; printd = 1; if (chdir(tmp = short2str(dp->di_name)) < 0) stderror(ERR_SYSTEM, tmp, strerror(errno)); dcwd->di_prev->di_next = dcwd->di_next; dcwd->di_next->di_prev = dcwd->di_prev; dfree(dcwd); dnewcwd(dp, dflag); return; } else if ((cp = dfollow(cp, dflag & DIR_OLD)) == NULL) return; dp = xcalloc(sizeof(struct directory), 1); dp->di_name = cp; dp->di_count = 0; dp->di_next = dcwd->di_next; dp->di_prev = dcwd->di_prev; dp->di_prev->di_next = dp; dp->di_next->di_prev = dp; dfree(dcwd); dnewcwd(dp, dflag); } static Char * dgoto(Char *cp) { Char *dp, *ret; if (!ABSOLUTEP(cp)) { Char *p, *q; size_t cwdlen; cwdlen = Strlen(dcwd->di_name); if (cwdlen == 1) /* root */ cwdlen = 0; dp = xmalloc((cwdlen + Strlen(cp) + 2) * sizeof(Char)); for (p = dp, q = dcwd->di_name; (*p++ = *q++) != '\0';) continue; if (cwdlen) p[-1] = '/'; else p--; /* don't add a / after root */ Strcpy(p, cp); xfree(cp); cp = dp; dp += cwdlen; } else dp = cp; #if defined(WINNT_NATIVE) return agetcwd(); #elif defined(__CYGWIN__) if (ABSOLUTEP(cp) && cp[1] == ':') { /* Only DOS paths are treated that way */ return agetcwd(); } else { ret = dcanon(cp, dp); } #else /* !WINNT_NATIVE */ ret = dcanon(cp, dp); #endif /* WINNT_NATIVE */ return ret; } /* * dfollow - change to arg directory; fall back on cdpath if not valid */ static Char * dfollow(Char *cp, int old) { Char *dp; struct varent *c; int serrno; cp = old ? Strsave(cp) : globone(cp, G_ERROR); cleanup_push(cp, xfree); #ifdef apollo if (Strchr(cp, '`')) { char *dptr; - if (chdir(dptr = short2str(cp)) < 0) + if (chdir(dptr = short2str(cp)) < 0) stderror(ERR_SYSTEM, dptr, strerror(errno)); dp = agetcwd(); cleanup_push(dp, xfree); if (dp != NULL) { cleanup_until(cp); return dgoto(dp); } else stderror(ERR_SYSTEM, dptr, strerror(errno)); } #endif /* apollo */ /* * if we are ignoring symlinks, try to fix relatives now. * if we are expading symlinks, it should be done by now. - */ + */ dp = dnormalize(cp, symlinks == SYM_IGNORE); if (chdir(short2str(dp)) >= 0) { cleanup_until(cp); return dgoto(dp); } else { xfree(dp); if (chdir(short2str(cp)) >= 0) { cleanup_ignore(cp); cleanup_until(cp); return dgoto(cp); } else if (errno != ENOENT && errno != ENOTDIR) { int err; err = errno; stderror(ERR_SYSTEM, short2str(cp), strerror(err)); } serrno = errno; } if (cp[0] != '/' && !prefix(STRdotsl, cp) && !prefix(STRdotdotsl, cp) && (c = adrof(STRcdpath)) && c->vec != NULL) { struct Strbuf buf = Strbuf_INIT; Char **cdp; for (cdp = c->vec; *cdp; cdp++) { size_t len = Strlen(*cdp); buf.len = 0; if (len > 0) { Strbuf_append(&buf, *cdp); if ((*cdp)[len - 1] != '/') Strbuf_append1(&buf, '/'); } Strbuf_append(&buf, cp); Strbuf_terminate(&buf); /* * We always want to fix the directory here * If we are normalizing symlinks */ - dp = dnormalize(buf.s, symlinks == SYM_IGNORE || + dp = dnormalize(buf.s, symlinks == SYM_IGNORE || symlinks == SYM_EXPAND); if (chdir(short2str(dp)) >= 0) { printd = 1; xfree(buf.s); cleanup_until(cp); return dgoto(dp); } else if (chdir(short2str(cp)) >= 0) { printd = 1; xfree(dp); xfree(buf.s); cleanup_ignore(cp); cleanup_until(cp); return dgoto(cp); } xfree(dp); } xfree(buf.s); } dp = varval(cp); if ((dp[0] == '/' || dp[0] == '.') && chdir(short2str(dp)) >= 0) { cleanup_until(cp); cp = Strsave(dp); printd = 1; return dgoto(cp); } /* * on login source of ~/.cshdirs, errors are eaten. the dir stack is all * directories we could get to. */ if (!bequiet) stderror(ERR_SYSTEM, short2str(cp), strerror(serrno)); cleanup_until(cp); return (NULL); } /* * dopushd - push new directory onto directory stack. * with no arguments exchange top and second. * with numeric argument (+n) bring it to top. */ /*ARGSUSED*/ void dopushd(Char **v, struct command *c) { struct directory *dp; Char *cp; int dflag = skipargs(&v, "plvn", " [-||+]"); - + USE(c); printd = 1; cp = (dflag & DIR_OLD) ? varval(STRowd) : *v; if (cp == NULL) { if (adrof(STRpushdtohome)) { if ((cp = varval(STRhome)) == STRNULL || *cp == 0) stderror(ERR_NAME | ERR_NOHOMEDIR); if (chdir(short2str(cp)) < 0) stderror(ERR_NAME | ERR_CANTCHANGE); if ((cp = dfollow(cp, dflag & DIR_OLD)) == NULL) return; dp = xcalloc(sizeof(struct directory), 1); dp->di_name = cp; dp->di_count = 0; dp->di_prev = dcwd; dp->di_next = dcwd->di_next; dcwd->di_next = dp; dp->di_next->di_prev = dp; } else { char *tmp; if ((dp = dcwd->di_prev) == &dhead) dp = dhead.di_prev; if (dp == dcwd) stderror(ERR_NAME | ERR_NODIR); if (chdir(tmp = short2str(dp->di_name)) < 0) stderror(ERR_SYSTEM, tmp, strerror(errno)); dp->di_prev->di_next = dp->di_next; dp->di_next->di_prev = dp->di_prev; dp->di_next = dcwd->di_next; dp->di_prev = dcwd; dcwd->di_next->di_prev = dp; dcwd->di_next = dp; } } else if ((dflag & DIR_OLD) == 0 && v[1] != NULL) { stderror(ERR_NAME | ERR_TOOMANY); /* NOTREACHED */ return; } else if ((dp = dfind(cp)) != NULL) { char *tmp; if (chdir(tmp = short2str(dp->di_name)) < 0) stderror(ERR_SYSTEM, tmp, strerror(errno)); /* * kfk - 10 Feb 1984 - added new "extraction style" pushd +n */ if (adrof(STRdextract)) dextract(dp); } else { Char *ccp; if ((ccp = dfollow(cp, dflag & DIR_OLD)) == NULL) return; dp = xcalloc(sizeof(struct directory), 1); dp->di_name = ccp; dp->di_count = 0; dp->di_prev = dcwd; dp->di_next = dcwd->di_next; dcwd->di_next = dp; dp->di_next->di_prev = dp; } dnewcwd(dp, dflag); } /* * dfind - find a directory if specified by numeric (+n) argument */ static struct directory * dfind(Char *cp) { struct directory *dp; int i; Char *ep; if (*cp++ != '+') return (0); for (ep = cp; Isdigit(*ep); ep++) continue; if (*ep) return (0); i = getn(cp); if (i <= 0) return (0); for (dp = dcwd; i != 0; i--) { if ((dp = dp->di_prev) == &dhead) dp = dp->di_prev; if (dp == dcwd) stderror(ERR_NAME | ERR_DEEP); } return (dp); } /* * dopopd - pop a directory out of the directory stack * with a numeric argument just discard it. */ /*ARGSUSED*/ void dopopd(Char **v, struct command *c) { Char *cp; struct directory *dp, *p = NULL; int dflag = skipargs(&v, "plvn", " [-|+]"); USE(c); printd = 1; cp = (dflag & DIR_OLD) ? varval(STRowd) : *v; if (cp == NULL) dp = dcwd; else if ((dflag & DIR_OLD) == 0 && v[1] != NULL) { stderror(ERR_NAME | ERR_TOOMANY); /* NOTREACHED */ return; } else if ((dp = dfind(cp)) == 0) stderror(ERR_NAME | ERR_BADDIR); if (dp->di_prev == &dhead && dp->di_next == &dhead) stderror(ERR_NAME | ERR_EMPTY); if (dp == dcwd) { char *tmp; if ((p = dp->di_prev) == &dhead) p = dhead.di_prev; if (chdir(tmp = short2str(p->di_name)) < 0) stderror(ERR_SYSTEM, tmp, strerror(errno)); } dp->di_prev->di_next = dp->di_next; dp->di_next->di_prev = dp->di_prev; dfree(dp); if (dp == dcwd) { dnewcwd(p, dflag); } else { printdirs(dflag); } } /* * dfree - free the directory (or keep it if it still has ref count) */ void dfree(struct directory *dp) { if (dp->di_count != 0) { dp->di_next = dp->di_prev = 0; } else { xfree(dp->di_name); xfree(dp); } } /* * dcanon - a safe version of dcanon_internal that arranges for cleanup */ Char * dcanon(Char *cp, Char *p) { cleanup_push(cp, xfree); p = dcanon_internal(cp, p); // coverity[use_after_free] we use the pointer as a marker cleanup_ignore(cp); cleanup_until(cp); return p; } /* * dcanon_internal - canonicalize the pathname, removing excess ./ and ../ etc. * we are of course assuming that the file system is standardly * constructed (always have ..'s, directories have links) */ static Char * dcanon_internal(Char *cp, Char *p) { Char *sp; Char *p1, *p2; /* general purpose */ int slash; #ifdef HAVE_SLASHSLASH int slashslash; #endif /* HAVE_SLASHSLASH */ size_t clen; #ifdef S_IFLNK /* if we have symlinks */ Char *mlink, *newcp; char *tlink; size_t cc; #endif /* S_IFLNK */ clen = Strlen(cp); /* * christos: if the path given does not start with a slash prepend cwd. If * cwd does not start with a slash or the result would be too long try to * correct it. */ if (!ABSOLUTEP(cp)) { Char *tmpdir; size_t len; p1 = varval(STRcwd); if (p1 == STRNULL || !ABSOLUTEP(p1)) { Char *new_cwd = agetcwd(); if (new_cwd == NULL) { xprintf("%s: %s\n", progname, strerror(errno)); setcopy(STRcwd, str2short("/"), VAR_READWRITE|VAR_NOGLOB); } else setv(STRcwd, new_cwd, VAR_READWRITE|VAR_NOGLOB); p1 = varval(STRcwd); } len = Strlen(p1); tmpdir = xmalloc((len + clen + 2) * sizeof (*tmpdir)); (void) Strcpy(tmpdir, p1); (void) Strcat(tmpdir, STRslash); (void) Strcat(tmpdir, cp); xfree(cp); cp = p = tmpdir; } #ifdef HAVE_SLASHSLASH slashslash = (cp[0] == '/' && cp[1] == '/'); #endif /* HAVE_SLASHSLASH */ while (*p) { /* for each component */ sp = p; /* save slash address */ while (*++p == '/') /* flush extra slashes */ continue; if (p != ++sp) for (p1 = sp, p2 = p; (*p1++ = *p2++) != '\0';) continue; p = sp; /* save start of component */ slash = 0; - if (*p) + if (*p) while (*++p) /* find next slash or end of path */ if (*p == '/') { slash = 1; *p = 0; break; } #ifdef HAVE_SLASHSLASH if (&cp[1] == sp && sp[0] == '.' && sp[1] == '.' && sp[2] == '\0') slashslash = 1; #endif /* HAVE_SLASHSLASH */ if (*sp == '\0') { /* if component is null */ - if (--sp == cp) /* if path is one char (i.e. /) */ + if (--sp == cp) /* if path is one char (i.e. /) */ break; else *sp = '\0'; } else if (sp[0] == '.' && sp[1] == 0) { if (slash) { for (p1 = sp, p2 = p + 1; (*p1++ = *p2++) != '\0';) continue; p = --sp; } else if (--sp != cp) *sp = '\0'; else sp[1] = '\0'; } else if (sp[0] == '.' && sp[1] == '.' && sp[2] == 0) { /* * We have something like "yyy/xxx/..", where "yyy" can be null or * a path starting at /, and "xxx" is a single component. Before * compressing "xxx/..", we want to expand "yyy/xxx", if it is a * symbolic link. */ *--sp = 0; /* form the pathname for readlink */ #ifdef S_IFLNK /* if we have symlinks */ if (sp != cp && /* symlinks != SYM_IGNORE && */ (tlink = areadlink(short2str(cp))) != NULL) { mlink = str2short(tlink); xfree(tlink); if (slash) *p = '/'; /* * Point p to the '/' in "/..", and restore the '/'. */ *(p = sp) = '/'; if (*mlink != '/') { /* * Relative path, expand it between the "yyy/" and the * "/..". First, back sp up to the character past "yyy/". */ while (*--sp != '/') continue; sp++; *sp = 0; /* * New length is "yyy/" + mlink + "/.." and rest */ p1 = newcp = xmalloc(((sp - cp) + Strlen(mlink) + Strlen(p) + 1) * sizeof(Char)); /* * Copy new path into newcp */ for (p2 = cp; (*p1++ = *p2++) != '\0';) continue; for (p1--, p2 = mlink; (*p1++ = *p2++) != '\0';) continue; for (p1--, p2 = p; (*p1++ = *p2++) != '\0';) continue; /* * Restart canonicalization at expanded "/xxx". */ p = sp - cp - 1 + newcp; } else { newcp = Strspl(mlink, p); /* * Restart canonicalization at beginning */ p = newcp; } xfree(cp); cp = newcp; #ifdef HAVE_SLASHSLASH slashslash = (cp[0] == '/' && cp[1] == '/'); #endif /* HAVE_SLASHSLASH */ continue; /* canonicalize the link */ } #endif /* S_IFLNK */ *sp = '/'; if (sp != cp) while (*--sp != '/') continue; if (slash) { for (p1 = sp + 1, p2 = p + 1; (*p1++ = *p2++) != '\0';) continue; p = sp; } else if (cp == sp) *++sp = '\0'; else *sp = '\0'; } else { /* normal dir name (not . or .. or nothing) */ #ifdef S_IFLNK /* if we have symlinks */ if (sp != cp && symlinks == SYM_CHASE && (tlink = areadlink(short2str(cp))) != NULL) { mlink = str2short(tlink); xfree(tlink); /* * restore the '/'. */ if (slash) *p = '/'; /* * point sp to p (rather than backing up). */ sp = p; if (*mlink != '/') { /* * Relative path, expand it between the "yyy/" and the * remainder. First, back sp up to the character past * "yyy/". */ while (*--sp != '/') continue; sp++; *sp = 0; /* * New length is "yyy/" + mlink + "/.." and rest */ p1 = newcp = xmalloc(((sp - cp) + Strlen(mlink) + Strlen(p) + 1) * sizeof(Char)); /* * Copy new path into newcp */ for (p2 = cp; (*p1++ = *p2++) != '\0';) continue; for (p1--, p2 = mlink; (*p1++ = *p2++) != '\0';) continue; for (p1--, p2 = p; (*p1++ = *p2++) != '\0';) continue; /* * Restart canonicalization at expanded "/xxx". */ p = sp - cp - 1 + newcp; } else { newcp = Strspl(mlink, p); /* * Restart canonicalization at beginning */ p = newcp; } xfree(cp); cp = newcp; #ifdef HAVE_SLASHSLASH slashslash = (cp[0] == '/' && cp[1] == '/'); #endif /* HAVE_SLASHSLASH */ continue; /* canonicalize the mlink */ } #endif /* S_IFLNK */ if (slash) *p = '/'; } } /* * fix home... */ #ifdef S_IFLNK p1 = varval(STRhome); cc = Strlen(p1); /* * See if we're not in a subdir of STRhome */ if (p1 && *p1 == '/' && (Strncmp(p1, cp, cc) != 0 || (cp[cc] != '/' && cp[cc] != '\0'))) { static ino_t home_ino = (ino_t) -1; static dev_t home_dev = (dev_t) -1; static Char *home_ptr = NULL; struct stat statbuf; int found; Char *copy; /* * Get dev and ino of STRhome */ if (home_ptr != p1 && stat(short2str(p1), &statbuf) != -1) { home_dev = statbuf.st_dev; home_ino = statbuf.st_ino; home_ptr = p1; } /* * Start comparing dev & ino backwards */ p2 = copy = Strsave(cp); found = 0; while (*p2 && stat(short2str(p2), &statbuf) != -1) { if (DEV_DEV_COMPARE(statbuf.st_dev, home_dev) && statbuf.st_ino == home_ino) { found = 1; break; } if ((sp = Strrchr(p2, '/')) != NULL) *sp = '\0'; } /* * See if we found it */ if (*p2 && found) { /* * Use STRhome to make '~' work */ newcp = Strspl(p1, cp + Strlen(p2)); xfree(cp); cp = newcp; } xfree(copy); } #endif /* S_IFLNK */ #ifdef HAVE_SLASHSLASH if (slashslash) { if (cp[1] != '/') { p = xmalloc((Strlen(cp) + 2) * sizeof(Char)); *p = '/'; (void) Strcpy(&p[1], cp); xfree(cp); cp = p; } } if (cp[1] == '/' && cp[2] == '/') { for (p1 = &cp[1], p2 = &cp[2]; (*p1++ = *p2++) != '\0';) continue; } #endif /* HAVE_SLASHSLASH */ return cp; } /* * dnewcwd - make a new directory in the loop the current one */ static void dnewcwd(struct directory *dp, int dflag) { int print; if (adrof(STRdunique)) { struct directory *dn; - for (dn = dhead.di_prev; dn != &dhead; dn = dn->di_prev) + for (dn = dhead.di_prev; dn != &dhead; dn = dn->di_prev) if (dn != dp && Strcmp(dn->di_name, dp->di_name) == 0) { dn->di_next->di_prev = dn->di_prev; dn->di_prev->di_next = dn->di_next; dfree(dn); break; } } dcwd = dp; dset(dcwd->di_name); dgetstack(); print = printd; /* if printd is set, print dirstack... */ if (adrof(STRpushdsilent)) /* but pushdsilent overrides printd... */ print = 0; if (dflag & DIR_PRINT) /* but DIR_PRINT overrides pushdsilent... */ print = 1; if (bequiet) /* and bequiet overrides everything */ print = 0; if (print) printdirs(dflag); cwd_cmd(); /* PWP: run the defined cwd command */ } void dsetstack(void) { Char **cp; struct varent *vp; struct directory *dn, *dp; if ((vp = adrof(STRdirstack)) == NULL || vp->vec == NULL) return; /* Free the whole stack */ while ((dn = dhead.di_prev) != &dhead) { dn->di_next->di_prev = dn->di_prev; dn->di_prev->di_next = dn->di_next; if (dn != dcwd) dfree(dn); } /* thread the current working directory */ dhead.di_prev = dhead.di_next = dcwd; dcwd->di_next = dcwd->di_prev = &dhead; /* put back the stack */ for (cp = vp->vec; cp && *cp && **cp; cp++) { dp = xcalloc(sizeof(struct directory), 1); dp->di_name = Strsave(*cp); dp->di_count = 0; dp->di_prev = dcwd; dp->di_next = dcwd->di_next; dcwd->di_next = dp; dp->di_next->di_prev = dp; } dgetstack(); /* Make $dirstack reflect the current state */ } static void dgetstack(void) { int i = 0; Char **dblk, **dbp; struct directory *dn; - if (adrof(STRdirstack) == NULL) + if (adrof(STRdirstack) == NULL) return; for (dn = dhead.di_prev; dn != &dhead; dn = dn->di_prev, i++) continue; dbp = dblk = xmalloc((i + 1) * sizeof(Char *)); for (dn = dhead.di_prev; dn != &dhead; dn = dn->di_prev, dbp++) *dbp = Strsave(dn->di_name); *dbp = NULL; cleanup_push(dblk, blk_cleanup); setq(STRdirstack, dblk, &shvhed, VAR_READWRITE); cleanup_ignore(dblk); cleanup_until(dblk); } /* * getstakd - added by kfk 17 Jan 1984 * Support routine for the stack hack. Finds nth directory in * the directory stack, or finds last directory in stack. */ const Char * getstakd(int cnt) { struct directory *dp; dp = dcwd; if (cnt < 0) { /* < 0 ==> last dir requested. */ dp = dp->di_next; if (dp == &dhead) dp = dp->di_next; } else { while (cnt-- > 0) { dp = dp->di_prev; if (dp == &dhead) dp = dp->di_prev; if (dp == dcwd) return NULL; } } return dp->di_name; } /* * Karl Kleinpaste - 10 Feb 1984 * Added dextract(), which is used in pushd +n. * Instead of just rotating the entire stack around, dextract() * lets the user have the nth dir extracted from its current * position, and pushes it onto the top. */ static void dextract(struct directory *dp) { if (dp == dcwd) return; dp->di_next->di_prev = dp->di_prev; dp->di_prev->di_next = dp->di_next; dp->di_next = dcwd->di_next; dp->di_prev = dcwd; dp->di_next->di_prev = dp; dcwd->di_next = dp; } static void bequiet_cleanup(void *dummy) { USE(dummy); bequiet = 0; } void loaddirs(Char *fname) { static Char *loaddirs_cmd[] = { STRsource, NULL, NULL }; bequiet = 1; cleanup_push(&bequiet, bequiet_cleanup); if (fname) loaddirs_cmd[1] = fname; else if ((fname = varval(STRdirsfile)) != STRNULL) loaddirs_cmd[1] = fname; else loaddirs_cmd[1] = STRtildotdirs; dosource(loaddirs_cmd, NULL); cleanup_until(&bequiet); } /* * create a file called ~/.cshdirs which has a sequence * of pushd commands which will restore the dir stack to * its state before exit/logout. remember that the order * is reversed in the file because we are pushing. * -strike */ void recdirs(Char *fname, int def) { int fp, ftmp, oldidfds, ophup_disabled; int cdflag = 0; struct directory *dp; unsigned int num; Char *snum; struct Strbuf qname = Strbuf_INIT; - if (fname == NULL && !def) + if (fname == NULL && !def) return; ophup_disabled = phup_disabled; phup_disabled = 1; if (fname == NULL) { if ((fname = varval(STRdirsfile)) == STRNULL) fname = Strspl(varval(STRhome), &STRtildotdirs[1]); else fname = Strsave(fname); } - else + else fname = globone(fname, G_ERROR); cleanup_push(fname, xfree); if ((fp = xcreat(short2str(fname), 0600)) == -1) { cleanup_until(fname); phup_disabled = ophup_disabled; return; } - if ((snum = varval(STRsavedirs)) == STRNULL || snum[0] == '\0') + if ((snum = varval(STRsavedirs)) == STRNULL || snum[0] == '\0') num = (unsigned int) ~0; else num = (unsigned int) atoi(short2str(snum)); oldidfds = didfds; didfds = 0; ftmp = SHOUT; SHOUT = fp; cleanup_push(&qname, Strbuf_cleanup); dp = dcwd->di_next; do { if (dp == &dhead) continue; if (cdflag == 0) { cdflag = 1; xprintf("cd %S\n", quote_meta(&qname, dp->di_name)); } else xprintf("pushd %S\n", quote_meta(&qname, dp->di_name)); if (num-- == 0) break; } while ((dp = dp->di_next) != dcwd->di_next); xclose(fp); SHOUT = ftmp; didfds = oldidfds; cleanup_until(fname); phup_disabled = ophup_disabled; } diff --git a/contrib/tcsh/sh.dol.c b/contrib/tcsh/sh.dol.c index 28e8639be8b9..b7aae3421d03 100644 --- a/contrib/tcsh/sh.dol.c +++ b/contrib/tcsh/sh.dol.c @@ -1,1148 +1,1148 @@ /* * sh.dol.c: Variable substitutions */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" /* * C shell */ /* * These routines perform variable substitution and quoting via ' and ". * To this point these constructs have been preserved in the divided * input words. Here we expand variables and turn quoting via ' and " into * QUOTE bits on characters (which prevent further interpretation). * If the `:q' modifier was applied during history expansion, then * some QUOTEing may have occurred already, so we dont "trim()" here. */ static eChar Dpeekc; /* Peek for DgetC */ static eChar Dpeekrd; /* Peek for Dreadc */ static Char *Dcp, *const *Dvp; /* Input vector for Dreadc */ #define DEOF CHAR_ERR #define unDgetC(c) Dpeekc = c #define QUOTES (_QF|_QB|_ESC) /* \ ' " ` */ /* * The following variables give the information about the current * $ expansion, recording the current word position, the remaining * words within this expansion, the count of remaining words, and the * information about any : modifier which is being applied. */ static Char *dolp; /* Remaining chars from this word */ static Char **dolnxt; /* Further words */ static int dolcnt; /* Count of further words */ static struct Strbuf dolmod; /* = Strbuf_INIT; : modifier characters */ static int ndolflags; /* keep track of mod counts for each modifier */ static int *dolmcnts; /* :gx -> INT_MAX, else 1 */ static int *dolaflags; /* :ax -> 1, else 0 */ static Char **Dfix2 (Char *const *); static int Dpack (struct Strbuf *); static int Dword (struct blk_buf *); static void dolerror (Char *); static eChar DgetC (int); static void Dgetdol (void); static void fixDolMod (void); static void setDolp (Char *); static void unDredc (eChar); static eChar Dredc (void); static void Dtestq (Char); /* * Fix up the $ expansions and quotations in the * argument list to command t. */ void Dfix(struct command *t) { Char **pp; Char *p; if (noexec) return; /* Note that t_dcom isn't trimmed thus !...:q's aren't lost */ for (pp = t->t_dcom; (p = *pp++) != NULL;) { for (; *p; p++) { if (cmap(*p, _DOL | QUOTES)) { /* $, \, ', ", ` */ Char **expanded; expanded = Dfix2(t->t_dcom); /* found one */ blkfree(t->t_dcom); t->t_dcom = expanded; return; } } } } /* * $ substitute one word, for i/o redirection */ Char * Dfix1(Char *cp) { Char *Dv[2], **expanded; if (noexec) return (0); Dv[0] = cp; Dv[1] = NULL; expanded = Dfix2(Dv); if (expanded[0] == NULL || expanded[1] != NULL) { blkfree(expanded); setname(short2str(cp)); stderror(ERR_NAME | ERR_AMBIG); } cp = Strsave(expanded[0]); blkfree(expanded); return (cp); } /* * Subroutine to do actual fixing after state initialization. */ static Char ** Dfix2(Char *const *v) { struct blk_buf *bb = bb_alloc(); Char **vec; Dvp = v; Dcp = STRNULL; /* Setup input vector for Dreadc */ unDgetC(0); unDredc(0); /* Clear out any old peeks (at error) */ dolp = 0; dolcnt = 0; /* Clear out residual $ expands (...) */ cleanup_push(bb, bb_free); while (Dword(bb)) continue; cleanup_ignore(bb); cleanup_until(bb); vec = bb_finish(bb); xfree(bb); return vec; } /* * Pack up more characters in this word */ static int Dpack(struct Strbuf *wbuf) { eChar c; for (;;) { c = DgetC(DODOL); if (c == '\\') { c = DgetC(0); if (c == DEOF) { unDredc(c); return 1; } if (c == '\n') c = ' '; else c |= QUOTE; } if (c == DEOF) { unDredc(c); return 1; } if (cmap(c, _SP | _NL | _QF | _QB)) { /* sp \t\n'"` */ unDgetC(c); if (cmap(c, QUOTES)) return 0; return 1; } Strbuf_append1(wbuf, (Char) c); } } /* * Get a word. This routine is analogous to the routine * word() in sh.lex.c for the main lexical input. One difference * here is that we don't get a newline to terminate our expansion. * Rather, DgetC will return a DEOF when we hit the end-of-input. */ static int Dword(struct blk_buf *bb) { eChar c, c1; struct Strbuf *wbuf = Strbuf_alloc(); int dolflg; int sofar = 0; Char *str; cleanup_push(wbuf, Strbuf_free); for (;;) { c = DgetC(DODOL); switch (c) { case DEOF: if (sofar == 0) { cleanup_until(wbuf); return (0); } /* finish this word and catch the code above the next time */ unDredc(c); /*FALLTHROUGH*/ case '\n': goto end; case ' ': case '\t': continue; case '`': /* We preserve ` quotations which are done yet later */ Strbuf_append1(wbuf, (Char) c); /*FALLTHROUGH*/ case '\'': case '"': /* * Note that DgetC never returns a QUOTES character from an * expansion, so only true input quotes will get us here or out. */ c1 = c; dolflg = c1 == '"' ? DODOL : 0; for (;;) { c = DgetC(dolflg); if (c == c1) break; if (c == '\n' || c == DEOF) { cleanup_until(bb); stderror(ERR_UNMATCHED, (int)c1); } if ((c & (QUOTE | TRIM)) == ('\n' | QUOTE)) { if (wbuf->len != 0 && (wbuf->s[wbuf->len - 1] & TRIM) == '\\') wbuf->len--; } switch (c1) { case '"': /* * Leave any `s alone for later. Other chars are all * quoted, thus `...` can tell it was within "...". */ Strbuf_append1(wbuf, c == '`' ? '`' : c | QUOTE); break; case '\'': /* Prevent all further interpretation */ Strbuf_append1(wbuf, c | QUOTE); break; case '`': /* Leave all text alone for later */ Strbuf_append1(wbuf, (Char) c); break; default: break; } } if (c1 == '`') Strbuf_append1(wbuf, '`'); sofar = 1; if (Dpack(wbuf) != 0) goto end; continue; case '\\': c = DgetC(0); /* No $ subst! */ if (c == '\n' || c == DEOF) continue; c |= QUOTE; break; default: break; } unDgetC(c); sofar = 1; if (Dpack(wbuf) != 0) goto end; } end: cleanup_ignore(wbuf); cleanup_until(wbuf); str = Strbuf_finish(wbuf); bb_append(bb, str); xfree(wbuf); return 1; } /* * Get a character, performing $ substitution unless flag is 0. * Any QUOTES character which is returned from a $ expansion is * QUOTEd so that it will not be recognized above. */ static eChar DgetC(int flag) { eChar c; top: if ((c = Dpeekc) != 0) { Dpeekc = 0; return (c); } if (lap < labuf.len) { c = labuf.s[lap++] & (QUOTE | TRIM); quotspec: if (cmap(c, QUOTES)) return (c | QUOTE); return (c); } if (dolp) { if ((c = *dolp++ & (QUOTE | TRIM)) != 0) goto quotspec; if (dolcnt > 0) { setDolp(*dolnxt++); --dolcnt; return (' '); } dolp = 0; } if (dolcnt > 0) { setDolp(*dolnxt++); --dolcnt; goto top; } c = Dredc(); if (c == '$' && flag) { Dgetdol(); goto top; } return (c); } static Char *nulvec[] = { NULL }; -static struct varent nulargv = {nulvec, STRargv, VAR_READWRITE, +static struct varent nulargv = {nulvec, STRargv, VAR_READWRITE, { NULL, NULL, NULL }, 0 }; static void dolerror(Char *s) { setname(short2str(s)); stderror(ERR_NAME | ERR_RANGE); } /* * Handle the multitudinous $ expansion forms. * Ugh. */ static void Dgetdol(void) { Char *np; struct varent *vp = NULL; struct Strbuf *name = Strbuf_alloc(); eChar c, sc; int subscr = 0, lwb = 1, upb = 0; int dimen = 0, bitset = 0, length = 0; static Char *dolbang = NULL; cleanup_push(name, Strbuf_free); dolmod.len = ndolflags = 0; c = sc = DgetC(0); if (c == DEOF) { stderror(ERR_SYNTAX); return; } if (c == '{') c = DgetC(0); /* sc is { to take } later */ if ((c & TRIM) == '#') dimen++, c = DgetC(0); /* $# takes dimension */ else if (c == '?') bitset++, c = DgetC(0); /* $? tests existence */ else if (c == '%') length++, c = DgetC(0); /* $% returns length in chars */ switch (c) { case '!': if (dimen || bitset || length) stderror(ERR_SYNTAX); if (backpid != 0) { xfree(dolbang); setDolp(dolbang = putn((tcsh_number_t)backpid)); } cleanup_until(name); goto eatbrac; case '$': if (dimen || bitset || length) stderror(ERR_SYNTAX); setDolp(doldol); cleanup_until(name); goto eatbrac; case '<'|QUOTE: { static struct Strbuf wbuf; /* = Strbuf_INIT; */ if (bitset) stderror(ERR_NOTALLOWED, "$?<"); if (dimen) stderror(ERR_NOTALLOWED, "$#<"); if (length) stderror(ERR_NOTALLOWED, "$%<"); wbuf.len = 0; { char cbuf[MB_LEN_MAX]; size_t cbp = 0; int old_pintr_disabled; for (;;) { int len; ssize_t res; Char wc; pintr_push_enable(&old_pintr_disabled); res = force_read(OLDSTD, cbuf + cbp, 1); cleanup_until(&old_pintr_disabled); if (res != 1) break; cbp++; len = normal_mbtowc(&wc, cbuf, cbp); if (len == -1) { reset_mbtowc(); if (cbp < MB_LEN_MAX) continue; /* Maybe a partial character */ wc = (unsigned char)*cbuf | INVALID_BYTE; } if (len <= 0) len = 1; if (cbp != (size_t)len) memmove(cbuf, cbuf + len, cbp - len); cbp -= len; if (wc == '\n') break; Strbuf_append1(&wbuf, wc); } while (cbp != 0) { int len; Char wc; len = normal_mbtowc(&wc, cbuf, cbp); if (len == -1) { reset_mbtowc(); wc = (unsigned char)*cbuf | INVALID_BYTE; } if (len <= 0) len = 1; if (cbp != (size_t)len) memmove(cbuf, cbuf + len, cbp - len); cbp -= len; if (wc == '\n') break; Strbuf_append1(&wbuf, wc); } Strbuf_terminate(&wbuf); } fixDolMod(); setDolp(wbuf.s); /* Kept allocated until next $< expansion */ cleanup_until(name); goto eatbrac; } case '*': Strbuf_append(name, STRargv); Strbuf_terminate(name); vp = adrof(STRargv); subscr = -1; /* Prevent eating [...] */ break; case DEOF: case '\n': np = dimen ? STRargv : (bitset ? STRstatus : NULL); if (np) { bitset = 0; Strbuf_append(name, np); Strbuf_terminate(name); vp = adrof(np); subscr = -1; /* Prevent eating [...] */ unDredc(c); break; } else stderror(ERR_SYNTAX); /*NOTREACHED*/ default: if (Isdigit(c)) { if (dimen) stderror(ERR_NOTALLOWED, "$#"); subscr = 0; do { subscr = subscr * 10 + c - '0'; c = DgetC(0); } while (c != DEOF && Isdigit(c)); unDredc(c); if (subscr < 0) stderror(ERR_RANGE); if (subscr == 0) { if (bitset) { dolp = dolzero ? STR1 : STR0; cleanup_until(name); goto eatbrac; } if (ffile == 0) stderror(ERR_DOLZERO); if (length) { length = Strlen(ffile); addla(putn((tcsh_number_t)length)); } else { fixDolMod(); setDolp(ffile); } cleanup_until(name); goto eatbrac; } #if 0 if (bitset) stderror(ERR_NOTALLOWED, "$?"); if (length) stderror(ERR_NOTALLOWED, "$%"); #endif vp = adrof(STRargv); if (vp == 0) { vp = &nulargv; cleanup_until(name); goto eatmod; } break; } if (c == DEOF || !alnum(c)) { np = dimen ? STRargv : (bitset ? STRstatus : NULL); if (np) { bitset = 0; Strbuf_append(name, np); Strbuf_terminate(name); vp = adrof(np); subscr = -1; /* Prevent eating [...] */ unDredc(c); break; } else stderror(ERR_VARALNUM); } for (;;) { Strbuf_append1(name, (Char) c); c = DgetC(0); if (c == DEOF || !alnum(c)) break; } Strbuf_terminate(name); unDredc(c); vp = adrof(name->s); } if (bitset) { dolp = (vp || getenv(short2str(name->s))) ? STR1 : STR0; cleanup_until(name); goto eatbrac; } if (vp == NULL || vp->vec == NULL) { np = str2short(getenv(short2str(name->s))); if (np) { static Char *env_val; /* = NULL; */ cleanup_until(name); fixDolMod(); if (length) { addla(putn((tcsh_number_t)Strlen(np))); } else { xfree(env_val); env_val = Strsave(np); setDolp(env_val); } goto eatbrac; } udvar(name->s); /* NOTREACHED */ } cleanup_until(name); c = DgetC(0); upb = blklen(vp->vec); if (dimen == 0 && subscr == 0 && c == '[') { name = Strbuf_alloc(); cleanup_push(name, Strbuf_free); np = name->s; for (;;) { c = DgetC(DODOL); /* Allow $ expand within [ ] */ if (c == ']') break; if (c == '\n' || c == DEOF) stderror(ERR_INCBR); Strbuf_append1(name, (Char) c); } Strbuf_terminate(name); np = name->s; if (dolp || dolcnt) /* $ exp must end before ] */ stderror(ERR_EXPORD); if (!*np) stderror(ERR_SYNTAX); if (Isdigit(*np)) { int i; for (i = 0; Isdigit(*np); i = i * 10 + *np++ - '0') continue; if (i < 0 || (i > upb && !any("-*", *np))) { cleanup_until(name); dolerror(vp->v_name); return; } lwb = i; if (!*np) upb = lwb, np = STRstar; } if (*np == '*') np++; else if (*np != '-') stderror(ERR_MISSING, '-'); else { int i = upb; np++; if (Isdigit(*np)) { i = 0; while (Isdigit(*np)) i = i * 10 + *np++ - '0'; if (i < 0 || i > upb) { cleanup_until(name); dolerror(vp->v_name); return; } } if (i < lwb) upb = lwb - 1; else upb = i; } if (lwb == 0) { if (upb != 0) { cleanup_until(name); dolerror(vp->v_name); return; } upb = -1; } if (*np) stderror(ERR_SYNTAX); cleanup_until(name); } else { if (subscr > 0) { if (subscr > upb) lwb = 1, upb = 0; else lwb = upb = subscr; } unDredc(c); } if (dimen) { /* this is a kludge. It prevents Dgetdol() from */ /* pushing erroneous ${# values into the labuf. */ if (sc == '{') { c = Dredc(); if (c != '}') stderror(ERR_MISSING, '}'); unDredc(c); } addla(putn((tcsh_number_t)(upb - lwb + 1))); } else if (length) { int i; for (i = lwb - 1, length = 0; i < upb; i++) length += Strlen(vp->vec[i]); #ifdef notdef /* We don't want that, since we can always compute it by adding $#xxx */ length += i - 1; /* Add the number of spaces in */ #endif addla(putn((tcsh_number_t)length)); } else { eatmod: fixDolMod(); dolnxt = &vp->vec[lwb - 1]; dolcnt = upb - lwb + 1; } eatbrac: if (sc == '{') { c = Dredc(); if (c != '}') stderror(ERR_MISSING, '}'); } } static void fixDolMod(void) { eChar c; c = DgetC(0); if (c == ':') { ndolflags = 0; do { ++ndolflags; dolmcnts = xrealloc(dolmcnts, ndolflags * sizeof(int)); dolaflags = xrealloc(dolaflags, ndolflags * sizeof(int)); c = DgetC(0), dolmcnts[ndolflags - 1] = 1, dolaflags[ndolflags - 1] = 0; if (c == 'g' || c == 'a') { if (c == 'g') { dolmcnts[ndolflags - 1] = INT_MAX; } else { dolaflags[ndolflags - 1] = 1; } c = DgetC(0); } - if ((c == 'g' && dolmcnts[ndolflags - 1] != INT_MAX) || + if ((c == 'g' && dolmcnts[ndolflags - 1] != INT_MAX) || (c == 'a' && dolaflags[ndolflags - 1] == 0)) { if (c == 'g') { dolmcnts[ndolflags - 1] = INT_MAX; } else { dolaflags[ndolflags - 1] = 1; } c = DgetC(0); } if (c == 's') { /* [eichin:19910926.0755EST] */ int delimcnt = 2; eChar delim = DgetC(0); Strbuf_append1(&dolmod, (Char) c); Strbuf_append1(&dolmod, (Char) delim); if (delim == DEOF || !delim || letter(delim) || Isdigit(delim) || any(" \t\n", delim)) { seterror(ERR_BADSUBST); break; - } + } while ((c = DgetC(0)) != DEOF) { Strbuf_append1(&dolmod, (Char) c); if (c == delim) delimcnt--; if (!delimcnt) break; } if (delimcnt) { seterror(ERR_BADSUBST); break; } continue; } if (!any(TCSH_MODIFIERS, c)) stderror(ERR_BADMOD, (int)c); Strbuf_append1(&dolmod, (Char) c); if (c == 'q') { dolmcnts[ndolflags - 1] = INT_MAX; } } while ((c = DgetC(0)) == ':'); unDredc(c); } else unDredc(c); } static int -all_dolmcnts_are_0() +all_dolmcnts_are_0(void) { int i = 0; for (; i < ndolflags; ++i) { if (dolmcnts[i] != 0) return 0; } return 1; } static void setDolp(Char *cp) { Char *dp; size_t i; int nthMod = 0; if (dolmod.len == 0 || all_dolmcnts_are_0()) { dolp = cp; return; } cp = Strsave(cp); for (i = 0; i < dolmod.len; i++) { int didmod = 0; /* handle s// [eichin:19910926.0510EST] */ if (dolmod.s[i] == 's') { Char delim; Char *lhsub, *rhsub, *np; size_t lhlen = 0, rhlen = 0; /* keep track of where the last :a match hit */ ptrdiff_t last_match = 0; delim = dolmod.s[++i]; if (!delim || letter(delim) || Isdigit(delim) || any(" \t\n", delim)) { seterror(ERR_BADSUBST); break; } lhsub = &dolmod.s[++i]; while (dolmod.s[i] != delim && dolmod.s[++i]) { lhlen++; } dolmod.s[i] = 0; rhsub = &dolmod.s[++i]; while (dolmod.s[i] != delim && dolmod.s[++i]) { rhlen++; } dolmod.s[i] = 0; strip(lhsub); strip(rhsub); if (dolmcnts[nthMod] != 0) { strip(cp); dp = cp; do { dp = Strstr(dp + last_match, lhsub); if (dp) { ptrdiff_t diff = dp - cp; size_t len = (Strlen(cp) + 1 - lhlen + rhlen); np = xmalloc(len * sizeof(Char)); (void) Strncpy(np, cp, diff); (void) Strcpy(np + diff, rhsub); (void) Strcpy(np + diff + rhlen, dp + lhlen); last_match = diff + rhlen; xfree(cp); dp = cp = np; cp[--len] = '\0'; didmod = 1; if (diff >= (ssize_t)len) break; } else { /* should this do a seterror? */ break; } } while (dolaflags[nthMod] != 0); } /* * restore dolmod for additional words */ dolmod.s[i] = rhsub[-1] = (Char) delim; } else if (dolmcnts[nthMod] != 0) { do { if ((dp = domod(cp, dolmod.s[i])) != NULL) { didmod = 1; if (Strcmp(cp, dp) == 0) { xfree(cp); cp = dp; break; } else { xfree(cp); cp = dp; } } else break; } while (dolaflags[nthMod] != 0); } if (didmod && dolmcnts[nthMod] != INT_MAX) dolmcnts[nthMod]--; #ifdef notdef else break; #endif ++nthMod; } addla(cp); dolp = STRNULL; if (seterr) stderror(ERR_OLD); } static void unDredc(eChar c) { Dpeekrd = c; } static eChar Dredc(void) { eChar c; if ((c = Dpeekrd) != 0) { Dpeekrd = 0; return (c); } if (Dcp && (c = *Dcp++)) return (c & (QUOTE | TRIM)); if (*Dvp == 0) { Dcp = 0; return (DEOF); } Dcp = *Dvp++; return (' '); } static int gflag; static void Dtestq(Char c) { if (cmap(c, QUOTES)) gflag = 1; } static void inheredoc_cleanup(void *dummy) { USE(dummy); inheredoc = 0; } Char * randsuf(void) { #ifndef WINNT_NATIVE struct timeval tv; (void) gettimeofday(&tv, NULL); - return putn((((tcsh_number_t)tv.tv_sec) ^ + return putn((((tcsh_number_t)tv.tv_sec) ^ ((tcsh_number_t)tv.tv_usec) ^ ((tcsh_number_t)getpid())) & 0x00ffffff); #else return putn(getpid()); #endif } /* * Form a shell temporary file (in unit 0) from the words * of the shell input up to EOF or a line the same as "term". * Unit 0 should have been closed before this call. */ void heredoc(Char *term) { eChar c; Char *Dv[2]; struct Strbuf lbuf = Strbuf_INIT, mbuf = Strbuf_INIT; Char obuf[BUFSIZE + 1]; #define OBUF_END (obuf + sizeof(obuf) / sizeof (*obuf) - 1) Char *lbp, *obp, *mbp; Char **vp; int quoted; #ifdef HAVE_MKSTEMP char *tmp = short2str(shtemp); char *dot = strrchr(tmp, '.'); if (!dot) stderror(ERR_NAME | ERR_NOMATCH); strcpy(dot, TMP_TEMPLATE); xclose(0); if (mkstemp(tmp) == -1) stderror(ERR_SYSTEM, tmp, strerror(errno)); #else /* !HAVE_MKSTEMP */ char *tmp; # ifndef WINNT_NATIVE again: # endif /* WINNT_NATIVE */ tmp = short2str(shtemp); # if O_CREAT == 0 if (xcreat(tmp, 0600) < 0) stderror(ERR_SYSTEM, tmp, strerror(errno)); # endif xclose(0); if (xopen(tmp, O_RDWR|O_CREAT|O_EXCL|O_TEMPORARY|O_LARGEFILE, 0600) == -1) { int oerrno = errno; # ifndef WINNT_NATIVE if (errno == EEXIST) { if (unlink(tmp) == -1) { xfree(shtemp); mbp = randsuf(); shtemp = Strspl(STRtmpsh, mbp); xfree(mbp); } goto again; } # endif /* WINNT_NATIVE */ (void) unlink(tmp); errno = oerrno; stderror(ERR_SYSTEM, tmp, strerror(errno)); } #endif /* HAVE_MKSTEMP */ (void) unlink(tmp); /* 0 0 inode! */ Dv[0] = term; Dv[1] = NULL; gflag = 0; trim(Dv); rscan(Dv, Dtestq); quoted = gflag; obp = obuf; obuf[BUFSIZE] = 0; inheredoc = 1; cleanup_push(&inheredoc, inheredoc_cleanup); #ifdef WINNT_NATIVE __dup_stdin = 1; #endif /* WINNT_NATIVE */ cleanup_push(&lbuf, Strbuf_cleanup); cleanup_push(&mbuf, Strbuf_cleanup); for (;;) { Char **words; /* * Read up a line */ lbuf.len = 0; for (;;) { c = readc(1); /* 1 -> Want EOF returns */ if (c == CHAR_ERR || c == '\n') break; if ((c &= TRIM) != 0) Strbuf_append1(&lbuf, (Char) c); } Strbuf_terminate(&lbuf); /* Catch EOF in the middle of a line. */ if (c == CHAR_ERR && lbuf.len != 0) c = '\n'; /* * Check for EOF or compare to terminator -- before expansion */ if (c == CHAR_ERR || eq(lbuf.s, term)) break; /* * If term was quoted or -n just pass it on */ if (quoted || noexec) { Strbuf_append1(&lbuf, '\n'); Strbuf_terminate(&lbuf); for (lbp = lbuf.s; (c = *lbp++) != 0;) { *obp++ = (Char) c; if (obp == OBUF_END) { tmp = short2str(obuf); (void) xwrite(0, tmp, strlen (tmp)); obp = obuf; } } continue; } /* * Term wasn't quoted so variable and then command expand the input * line */ Dcp = lbuf.s; Dvp = Dv + 1; mbuf.len = 0; for (;;) { c = DgetC(DODOL); if (c == DEOF) break; if ((c &= TRIM) == 0) continue; /* \ quotes \ $ ` here */ if (c == '\\') { c = DgetC(0); if (!any("$\\`", c)) unDgetC(c | QUOTE), c = '\\'; else c |= QUOTE; } Strbuf_append1(&mbuf, (Char) c); } Strbuf_terminate(&mbuf); /* * If any ` in line do command substitution */ mbp = mbuf.s; if (Strchr(mbp, '`') != NULL) { /* * 1 arg to dobackp causes substitution to be literal. Words are * broken only at newlines so that all blanks and tabs are * preserved. Blank lines (null words) are not discarded. */ words = dobackp(mbp, 1); } else /* Setup trivial vector similar to return of dobackp */ Dv[0] = mbp, Dv[1] = NULL, words = Dv; /* * Resurrect the words from the command substitution each separated by * a newline. Note that the last newline of a command substitution * will have been discarded, but we put a newline after the last word * because this represents the newline after the last input line! */ for (vp= words; *vp; vp++) { for (mbp = *vp; *mbp; mbp++) { *obp++ = *mbp & TRIM; if (obp == OBUF_END) { tmp = short2str(obuf); (void) xwrite(0, tmp, strlen (tmp)); obp = obuf; } } *obp++ = '\n'; if (obp == OBUF_END) { tmp = short2str(obuf); (void) xwrite(0, tmp, strlen (tmp)); obp = obuf; } } if (words != Dv) blkfree(words); } *obp = 0; tmp = short2str(obuf); (void) xwrite(0, tmp, strlen (tmp)); (void) lseek(0, (off_t) 0, L_SET); cleanup_until(&inheredoc); } diff --git a/contrib/tcsh/sh.err.c b/contrib/tcsh/sh.err.c index 010b23c7d99b..3e1fedce8fd3 100644 --- a/contrib/tcsh/sh.err.c +++ b/contrib/tcsh/sh.err.c @@ -1,656 +1,656 @@ /* - * sh.err.c: Error printing routines. + * sh.err.c: Error printing routines. */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #define _h_sh_err /* Don't redefine the errors */ #include "sh.h" #include /* * C Shell */ #ifdef lint #undef va_arg #define va_arg(a, b) (a ? (b) 0 : (b) 0) #endif char *seterr = NULL; /* Holds last error if there was one */ extern int enterhist; #define ERR_FLAGS 0xf0000000 #define ERR_NAME 0x10000000 #define ERR_SILENT 0x20000000 #define ERR_OLD 0x40000000 #define ERR_INTERRUPT 0x80000000 #define ERR_SYNTAX 0 #define ERR_NOTALLOWED 1 #define ERR_WTOOLONG 2 #define ERR_LTOOLONG 3 #define ERR_DOLZERO 4 #define ERR_INCBR 5 #define ERR_EXPORD 6 #define ERR_BADMOD 7 #define ERR_SUBSCRIPT 8 #define ERR_BADNUM 9 #define ERR_NOMORE 10 #define ERR_FILENAME 11 #define ERR_GLOB 12 #define ERR_COMMAND 13 #define ERR_TOOFEW 14 #define ERR_TOOMANY 15 #define ERR_DANGER 16 #define ERR_EMPTYIF 17 #define ERR_IMPRTHEN 18 #define ERR_NOPAREN 19 #define ERR_NOTFOUND 20 #define ERR_MASK 21 #define ERR_LIMIT 22 #define ERR_TOOLARGE 23 #define ERR_SCALEF 24 #define ERR_UNDVAR 25 #define ERR_DEEP 26 #define ERR_BADSIG 27 #define ERR_UNKSIG 28 #define ERR_VARBEGIN 29 #define ERR_VARTOOLONG 30 #define ERR_VARALNUM 31 #define ERR_JOBCONTROL 32 #define ERR_EXPRESSION 33 #define ERR_NOHOMEDIR 34 #define ERR_CANTCHANGE 35 #define ERR_NULLCOM 36 #define ERR_ASSIGN 37 #define ERR_UNKNOWNOP 38 #define ERR_AMBIG 39 #define ERR_EXISTS 40 #define ERR_ARGC 41 #define ERR_INTR 42 #define ERR_RANGE 43 #define ERR_OVERFLOW 44 #define ERR_NOSUCHJOB 45 #define ERR_TERMINAL 46 #define ERR_NOTWHILE 47 #define ERR_NOPROC 48 #define ERR_NOMATCH 49 #define ERR_MISSING 50 #define ERR_UNMATCHED 51 #define ERR_NOMEM 52 #define ERR_PIPE 53 #define ERR_SYSTEM 54 #define ERR_STRING 55 #define ERR_JOBS 56 #define ERR_JOBARGS 57 #define ERR_JOBCUR 58 #define ERR_JOBPREV 59 #define ERR_JOBPAT 60 #define ERR_NESTING 61 #define ERR_JOBCTRLSUB 62 #define ERR_SYNC 63 #define ERR_STOPPED 64 #define ERR_NODIR 65 #define ERR_EMPTY 66 #define ERR_BADDIR 67 #define ERR_DIRUS 68 #define ERR_HFLAG 69 #define ERR_NOTLOGIN 70 #define ERR_DIV0 71 #define ERR_MOD0 72 #define ERR_BADSCALE 73 #define ERR_SUSPLOG 74 #define ERR_UNKUSER 75 #define ERR_NOHOME 76 #define ERR_HISTUS 77 #define ERR_SPDOLLT 78 #define ERR_NEWLINE 79 #define ERR_SPSTAR 80 #define ERR_DIGIT 81 #define ERR_VARILL 82 #define ERR_NLINDEX 83 #define ERR_EXPOVFL 84 #define ERR_VARSYN 85 #define ERR_BADBANG 86 #define ERR_NOSUBST 87 #define ERR_BADSUBST 88 #define ERR_LHS 89 #define ERR_RHSLONG 90 #define ERR_BADBANGMOD 91 #define ERR_MODFAIL 92 #define ERR_SUBOVFL 93 #define ERR_BADBANGARG 94 #define ERR_NOSEARCH 95 #define ERR_NOEVENT 96 #define ERR_TOOMANYRP 97 #define ERR_TOOMANYLP 98 #define ERR_BADPLP 99 #define ERR_MISRED 100 #define ERR_OUTRED 101 #define ERR_REDPAR 102 #define ERR_INRED 103 #define ERR_BADPLPS 104 #define ERR_ALIASLOOP 105 #define ERR_NOWATCH 106 #define ERR_NOSCHED 107 #define ERR_SCHEDUSAGE 108 #define ERR_SCHEDEV 109 #define ERR_SCHEDCOM 110 #define ERR_SCHEDTIME 111 #define ERR_SCHEDREL 112 #define ERR_TCNOSTR 113 #define ERR_SETTCUS 114 #define ERR_TCCAP 115 #define ERR_TCPARM 116 #define ERR_TCARGS 117 #define ERR_TCNARGS 118 #define ERR_TCUSAGE 119 #define ERR_ARCH 120 #define ERR_HISTLOOP 121 #define ERR_FILEINQ 122 #define ERR_SELOVFL 123 #define ERR_TCSHUSAGE 124 #define ERR_COMPCOM 125 #define ERR_COMPINV 126 #define ERR_COMPMIS 127 #define ERR_COMPINC 128 #define ERR_MFLAG 129 #define ERR_ULIMUS 130 #define ERR_READONLY 131 #define ERR_BADJOB 132 #define ERR_INVALID 133 #define ERR_BADCOLORVAR 134 #define ERR_EOF 135 #define NO_ERRORS 136 static const char *elst[NO_ERRORS] INIT_ZERO_STRUCT; /* * Init the elst depending on the locale */ void errinit(void) { #ifdef NLS_CATALOGS size_t i; for (i = 0; i < NO_ERRORS; i++) xfree((char *)(intptr_t)elst[i]); # if defined(__FreeBSD__) || defined(hpux) || defined(__MidnightBSD__) # define NLS_MAXSET 30 for (i = 1; i <= NLS_MAXSET; i++) CGETS(i, 1, "" ); # endif #endif elst[ERR_SYNTAX] = CSAVS(1, 1, "Syntax Error"); elst[ERR_NOTALLOWED] = CSAVS(1, 2, "%s is not allowed"); elst[ERR_WTOOLONG] = CSAVS(1, 3, "Word too long"); elst[ERR_LTOOLONG] = CSAVS(1, 4, "$< line too long"); elst[ERR_DOLZERO] = CSAVS(1, 5, "No file for $0"); elst[ERR_INCBR] = CSAVS(1, 6, "Incomplete [] modifier"); elst[ERR_EXPORD] = CSAVS(1, 7, "$ expansion must end before ]"); elst[ERR_BADMOD] = CSAVS(1, 8, "Bad : modifier in $ '%c'"); elst[ERR_SUBSCRIPT] = CSAVS(1, 9, "Subscript error"); elst[ERR_BADNUM] = CSAVS(1, 10, "Badly formed number"); elst[ERR_NOMORE] = CSAVS(1, 11, "No more words"); elst[ERR_FILENAME] = CSAVS(1, 12, "Missing file name"); elst[ERR_GLOB] = CSAVS(1, 13, "Internal glob error"); elst[ERR_COMMAND] = CSAVS(1, 14, "Command not found"); elst[ERR_TOOFEW] = CSAVS(1, 15, "Too few arguments"); elst[ERR_TOOMANY] = CSAVS(1, 16, "Too many arguments"); elst[ERR_DANGER] = CSAVS(1, 17, "Too dangerous to alias that"); elst[ERR_EMPTYIF] = CSAVS(1, 18, "Empty if"); elst[ERR_IMPRTHEN] = CSAVS(1, 19, "Improper then"); elst[ERR_NOPAREN] = CSAVS(1, 20, "Words not parenthesized"); elst[ERR_NOTFOUND] = CSAVS(1, 21, "%s not found"); elst[ERR_MASK] = CSAVS(1, 22, "Improper mask"); elst[ERR_LIMIT] = CSAVS(1, 23, "No such limit"); elst[ERR_TOOLARGE] = CSAVS(1, 24, "Argument too large"); elst[ERR_SCALEF] = CSAVS(1, 25, "Improper or unknown scale factor"); elst[ERR_UNDVAR] = CSAVS(1, 26, "Undefined variable"); elst[ERR_DEEP] = CSAVS(1, 27, "Directory stack not that deep"); elst[ERR_BADSIG] = CSAVS(1, 28, "Bad signal number"); elst[ERR_UNKSIG] = CSAVS(1, 29, "Unknown signal; kill -l lists signals"); elst[ERR_VARBEGIN] = CSAVS(1, 30, "Variable name must begin with a letter"); elst[ERR_VARTOOLONG] = CSAVS(1, 31, "Variable name too long"); elst[ERR_VARALNUM] = CSAVS(1, 32, "Variable name must contain alphanumeric characters"); elst[ERR_JOBCONTROL] = CSAVS(1, 33, "No job control in this shell"); elst[ERR_EXPRESSION] = CSAVS(1, 34, "Expression Syntax"); elst[ERR_NOHOMEDIR] = CSAVS(1, 35, "No home directory"); elst[ERR_CANTCHANGE] = CSAVS(1, 36, "Can't change to home directory"); elst[ERR_NULLCOM] = CSAVS(1, 37, "Invalid null command"); elst[ERR_ASSIGN] = CSAVS(1, 38, "Assignment missing expression"); elst[ERR_UNKNOWNOP] = CSAVS(1, 39, "Unknown operator"); elst[ERR_AMBIG] = CSAVS(1, 40, "Ambiguous"); elst[ERR_EXISTS] = CSAVS(1, 41, "%s: File exists"); elst[ERR_ARGC] = CSAVS(1, 42, "Argument for -c ends in backslash"); elst[ERR_INTR] = CSAVS(1, 43, "Interrupted"); elst[ERR_RANGE] = CSAVS(1, 44, "Subscript out of range"); elst[ERR_OVERFLOW] = CSAVS(1, 45, "Line overflow"); elst[ERR_NOSUCHJOB] = CSAVS(1, 46, "No such job"); elst[ERR_TERMINAL] = CSAVS(1, 47, "Can't from terminal"); elst[ERR_NOTWHILE] = CSAVS(1, 48, "Not in while/foreach"); elst[ERR_NOPROC] = CSAVS(1, 49, "No more processes"); elst[ERR_NOMATCH] = CSAVS(1, 50, "No match"); elst[ERR_MISSING] = CSAVS(1, 51, "Missing '%c'"); elst[ERR_UNMATCHED] = CSAVS(1, 52, "Unmatched '%c'"); elst[ERR_NOMEM] = CSAVS(1, 53, "Out of memory"); elst[ERR_PIPE] = CSAVS(1, 54, "Can't make pipe"); elst[ERR_SYSTEM] = CSAVS(1, 55, "%s: %s"); elst[ERR_STRING] = CSAVS(1, 56, "%s"); elst[ERR_JOBS] = CSAVS(1, 57, "Usage: jobs [ -l ]"); elst[ERR_JOBARGS] = CSAVS(1, 58, "Arguments should be jobs or process id's"); elst[ERR_JOBCUR] = CSAVS(1, 59, "No current job"); elst[ERR_JOBPREV] = CSAVS(1, 60, "No previous job"); elst[ERR_JOBPAT] = CSAVS(1, 61, "No job matches pattern"); elst[ERR_NESTING] = CSAVS(1, 62, "Fork nesting > %d; maybe `...` loop"); elst[ERR_JOBCTRLSUB] = CSAVS(1, 63, "No job control in subshells"); elst[ERR_SYNC] = CSAVS(1, 64, "Sync fault: Process %d not found"); elst[ERR_STOPPED] = #ifdef SUSPENDED CSAVS(1, 65, "%sThere are suspended jobs"); #else CSAVS(1, 66, "%sThere are stopped jobs"); #endif /* SUSPENDED */ elst[ERR_NODIR] = CSAVS(1, 67, "No other directory"); elst[ERR_EMPTY] = CSAVS(1, 68, "Directory stack empty"); elst[ERR_BADDIR] = CSAVS(1, 69, "Bad directory"); elst[ERR_DIRUS] = CSAVS(1, 70, "Usage: %s [-%s]%s"); elst[ERR_HFLAG] = CSAVS(1, 71, "No operand for -h flag"); elst[ERR_NOTLOGIN] = CSAVS(1, 72, "Not a login shell"); elst[ERR_DIV0] = CSAVS(1, 73, "Division by 0"); elst[ERR_MOD0] = CSAVS(1, 74, "Mod by 0"); elst[ERR_BADSCALE] = CSAVS(1, 75, "Bad scaling; did you mean \"%s\"?"); elst[ERR_SUSPLOG] = CSAVS(1, 76, "Can't suspend a login shell (yet)"); elst[ERR_UNKUSER] = CSAVS(1, 77, "Unknown user: %s"); elst[ERR_NOHOME] = CSAVS(1, 78, "No $home variable set"); elst[ERR_HISTUS] = CSAVS(1, 79, "Usage: history [-%s] [# number of events]"); elst[ERR_SPDOLLT] = CSAVS(1, 80, "$, ! or < not allowed with $# or $?"); elst[ERR_NEWLINE] = CSAVS(1, 81, "Newline in variable name"); elst[ERR_SPSTAR] = CSAVS(1, 82, "* not allowed with $# or $?"); elst[ERR_DIGIT] = CSAVS(1, 83, "$? or $# not allowed"); elst[ERR_VARILL] = CSAVS(1, 84, "Illegal variable name"); elst[ERR_NLINDEX] = CSAVS(1, 85, "Newline in variable index"); elst[ERR_EXPOVFL] = CSAVS(1, 86, "Expansion buffer overflow"); elst[ERR_VARSYN] = CSAVS(1, 87, "Variable syntax"); elst[ERR_BADBANG] = CSAVS(1, 88, "Bad ! form"); elst[ERR_NOSUBST] = CSAVS(1, 89, "No previous substitute"); elst[ERR_BADSUBST] = CSAVS(1, 90, "Bad substitute"); elst[ERR_LHS] = CSAVS(1, 91, "No previous left hand side"); elst[ERR_RHSLONG] = CSAVS(1, 92, "Right hand side too long"); elst[ERR_BADBANGMOD] = CSAVS(1, 93, "Bad ! modifier: '%c'"); elst[ERR_MODFAIL] = CSAVS(1, 94, "Modifier failed"); elst[ERR_SUBOVFL] = CSAVS(1, 95, "Substitution buffer overflow"); elst[ERR_BADBANGARG] = CSAVS(1, 96, "Bad ! arg selector"); elst[ERR_NOSEARCH] = CSAVS(1, 97, "No prev search"); elst[ERR_NOEVENT] = CSAVS(1, 98, "%s: Event not found"); elst[ERR_TOOMANYRP] = CSAVS(1, 99, "Too many )'s"); elst[ERR_TOOMANYLP] = CSAVS(1, 100, "Too many ('s"); elst[ERR_BADPLP] = CSAVS(1, 101, "Badly placed ("); elst[ERR_MISRED] = CSAVS(1, 102, "Missing name for redirect"); elst[ERR_OUTRED] = CSAVS(1, 103, "Ambiguous output redirect"); elst[ERR_REDPAR] = CSAVS(1, 104, "Can't << within ()'s"); elst[ERR_INRED] = CSAVS(1, 105, "Ambiguous input redirect"); elst[ERR_BADPLPS] = CSAVS(1, 106, "Badly placed ()'s"); elst[ERR_ALIASLOOP] = CSAVS(1, 107, "Alias loop"); elst[ERR_NOWATCH] = CSAVS(1, 108, "No $watch variable set"); elst[ERR_NOSCHED] = CSAVS(1, 109, "No scheduled events"); elst[ERR_SCHEDUSAGE] = CSAVS(1, 110, "Usage: sched -.\nUsage: sched [+]hh:mm "); elst[ERR_SCHEDEV] = CSAVS(1, 111, "Not that many scheduled events"); elst[ERR_SCHEDCOM] = CSAVS(1, 112, "No command to run"); elst[ERR_SCHEDTIME] = CSAVS(1, 113, "Invalid time for event"); elst[ERR_SCHEDREL] = CSAVS(1, 114, "Relative time inconsistent with am/pm"); elst[ERR_TCNOSTR] = CSAVS(1, 115, "Out of termcap string space"); elst[ERR_SETTCUS] = CSAVS(1, 116, "Usage: settc %s [yes|no]"); elst[ERR_TCCAP] = CSAVS(1, 117, "Unknown capability `%s'"); elst[ERR_TCPARM] = CSAVS(1, 118, "Unknown termcap parameter '%%%c'"); elst[ERR_TCARGS] = CSAVS(1, 119, "Too many arguments for `%s' (%d)"); elst[ERR_TCNARGS] = CSAVS(1, 120, "`%s' requires %d arguments"); elst[ERR_TCUSAGE] = CSAVS(1, 121, "Usage: echotc [-v|-s] [ []]"); elst[ERR_ARCH] = CSAVS(1, 122, "%s: %s. Binary file not executable"); elst[ERR_HISTLOOP] = CSAVS(1, 123, "!# History loop"); elst[ERR_FILEINQ] = CSAVS(1, 124, "Malformed file inquiry"); elst[ERR_SELOVFL] = CSAVS(1, 125, "Selector overflow"); #ifdef apollo elst[ERR_TCSHUSAGE] = CSAVS(1, 126, "Unknown option: `-%s'\nUsage: %s [ -bcdefilmnqstvVxX -Dname[=value] ] [ argument ... ]"); #else /* !apollo */ # ifdef convex elst[ERR_TCSHUSAGE] = CSAVS(1, 127, "Unknown option: `-%s'\nUsage: %s [ -bcdefFilmnqstvVxX ] [ argument ... ]"); # else /* rest */ elst[ERR_TCSHUSAGE] = CSAVS(1, 128, "Unknown option: `-%s'\nUsage: %s [ -bcdefilmnqstvVxX ] [ argument ... ]"); # endif /* convex */ #endif /* apollo */ elst[ERR_COMPCOM] = CSAVS(1, 129, "\nInvalid completion: \"%s\""); elst[ERR_COMPINV] = CSAVS(1, 130, "\nInvalid %s: '%c'"); elst[ERR_COMPMIS] = CSAVS(1, 131, "\nMissing separator '%c' after %s \"%s\""); elst[ERR_COMPINC] = CSAVS(1, 132, "\nIncomplete %s: \"%s\""); elst[ERR_MFLAG] = CSAVS(1, 133, "No operand for -m flag"); elst[ERR_ULIMUS] = CSAVS(1, 134, "Usage: unlimit [-fh] [limits]"); elst[ERR_READONLY] = CSAVS(1, 135, "$%S is read-only"); elst[ERR_BADJOB] = CSAVS(1, 136, "No such job (badjob)"); elst[ERR_BADCOLORVAR] = CSAVS(1, 137, "Unknown colorls variable '%c%c'"); elst[ERR_EOF] = CSAVS(1, 138, "Unexpected end of file"); } /* Cleanup data. */ struct cleanup_entry { void *var; void (*fn) (void *); #ifdef CLEANUP_DEBUG const char *file; size_t line; #endif }; static struct cleanup_entry *cleanup_stack INIT_ZERO; /* = NULL; */ static size_t cleanup_sp INIT_ZERO; /* = 0; Next free entry */ static size_t cleanup_mark INIT_ZERO; /* = 0; Last entry to handle before unwinding */ static size_t cleanup_stack_size INIT_ZERO; /* = 0 */ /* fn() will be run with all signals blocked, so it should not do anything risky. */ void cleanup_push_internal(void *var, void (*fn) (void *) #ifdef CLEANUP_DEBUG , const char *file, size_t line #endif ) { struct cleanup_entry *ce; if (cleanup_sp == cleanup_stack_size) { if (cleanup_stack_size == 0) cleanup_stack_size = 64; /* Arbitrary */ else cleanup_stack_size *= 2; cleanup_stack = xrealloc(cleanup_stack, cleanup_stack_size * sizeof (*cleanup_stack)); } ce = cleanup_stack + cleanup_sp; ce->var = var; ce->fn = fn; #ifdef CLEANUP_DEBUG ce->file = file; ce->line = line; #endif cleanup_sp++; } static void cleanup_ignore_fn(void *dummy) { USE(dummy); } void cleanup_ignore(void *var) { struct cleanup_entry *ce; ce = cleanup_stack + cleanup_sp; while (ce != cleanup_stack) { ce--; if (ce->var == var) { ce->fn = cleanup_ignore_fn; return; } } abort(); } void cleanup_until(void *last_var) { while (cleanup_sp != 0) { struct cleanup_entry ce; cleanup_sp--; ce = cleanup_stack[cleanup_sp]; ce.fn(ce.var); if (ce.var == last_var) return; } abort(); } int cleanup_reset(void) { return cleanup_sp > cleanup_mark; } void cleanup_until_mark(void) { while (cleanup_sp > cleanup_mark) { struct cleanup_entry ce; cleanup_sp--; ce = cleanup_stack[cleanup_sp]; ce.fn(ce.var); } } size_t cleanup_push_mark(void) { size_t old_mark; old_mark = cleanup_mark; cleanup_mark = cleanup_sp; return old_mark; } void cleanup_pop_mark(size_t mark) { assert (mark <= cleanup_sp); cleanup_mark = mark; } void sigint_cleanup(void *xsa) { const struct sigaction *sa; sa = xsa; sigaction(SIGINT, sa, NULL); } void sigprocmask_cleanup(void *xmask) { sigset_t *mask; mask = xmask; sigprocmask(SIG_SETMASK, mask, NULL); } void open_cleanup(void *xptr) { int *ptr; ptr = xptr; xclose(*ptr); } void opendir_cleanup(void *xdir) { DIR *dir; dir = xdir; xclosedir(dir); } void xfree_indirect(void *xptr) { void **ptr; /* This is actually type punning :( */ ptr = xptr; xfree(*ptr); } void reset(void) { cleanup_until_mark(); _reset(); abort(); } /* * The parser and scanner set up errors for later by calling seterr, * which sets the variable err as a side effect; later to be tested, * e.g. in process. */ void /*VARARGS1*/ seterror(unsigned int id, ...) { if (seterr == 0) { va_list va; va_start(va, id); if (id >= sizeof(elst) / sizeof(elst[0])) id = ERR_INVALID; seterr = xvasprintf(elst[id], va); va_end(va); } } void fixerror(void) { didfds = 0; /* Forget about 0,1,2 */ /* * Go away if -e or we are a child shell */ if (!exitset || exiterr || child) xexit(1); /* * Reset the state of the input. This buffered seek to end of file will * also clear the while/foreach stack. */ btoeof(); setcopy(STRstatus, STR1, VAR_READWRITE);/*FIXRESET*/ #ifdef BSDJOBS if (tpgrp > 0) (void) tcsetpgrp(FSHTTY, tpgrp); #endif } /* * Print the error with the given id. * * Special ids: * ERR_SILENT: Print nothing. * ERR_OLD: Print the previously set error * ERR_NAME: If this bit is set, print the name of the function * in bname * * This routine always resets or exits. The flag haderr * is set so the routine who catches the unwind can propogate * it if they want. * * Note that any open files at the point of error will eventually * be closed in the routine process in sh.c which is the only * place error unwinds are ever caught. */ void /*VARARGS*/ stderror(unsigned int id, ...) { va_list va; int flags; va_start(va, id); /* * Reset don't free flag for buggy os's */ dont_free = 0; flags = (int) id & ERR_FLAGS; id &= ~ERR_FLAGS; /* Pyramid's OS/x has a subtle bug in which prevents calling * va_end more than once in the same function. -- sterling@netcom.com */ assert(!((flags & ERR_OLD) && seterr == NULL)); if (id >= sizeof(elst) / sizeof(elst[0])) id = ERR_INVALID; if (!(flags & ERR_SILENT)) { /* * Must flush before we print as we wish output before the error * to go on (some form of) standard output, while output after * goes on (some form of) diagnostic output. If didfds then output * will go to 1/2 else to FSHOUT/FSHDIAG. See flush in sh.print.c. */ flush();/*FIXRESET*/ haderr = 1; /* Now to diagnostic output */ if (enterhist) xprintf("Can't load history: ");/*FIXRESET*/ if (flags & ERR_NAME) xprintf("%s: ", bname);/*FIXRESET*/ if ((flags & ERR_OLD)) { /* Old error. */ xprintf("%s.\n", seterr);/*FIXRESET*/ } else { xvprintf(elst[id], va);/*FIXRESET*/ xprintf(".\n");/*FIXRESET*/ } } va_end(va); if (seterr) { xfree(seterr); seterr = NULL; } fixerror(); reset(); /* Unwind */ } diff --git a/contrib/tcsh/sh.exec.c b/contrib/tcsh/sh.exec.c index 979d9b234b22..d327e3e6e519 100644 --- a/contrib/tcsh/sh.exec.c +++ b/contrib/tcsh/sh.exec.c @@ -1,1200 +1,1200 @@ /* * sh.exec.c: Search, find, and execute a command! */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "tc.h" #include "tw.h" #ifdef WINNT_NATIVE #include #endif /*WINNT_NATIVE*/ /* * C shell */ #ifndef OLDHASH # define FASTHASH /* Fast hashing is the default */ #endif /* OLDHASH */ /* * System level search and execute of a command. * We look in each directory for the specified command name. * If the name contains a '/' then we execute only the full path name. * If there is no search path then we execute only full path names. */ /* * As we search for the command we note the first non-trivial error * message for presentation to the user. This allows us often * to show that a file has the wrong mode/no access when the file * is not in the last component of the search path, so we must * go on after first detecting the error. */ static char *exerr; /* Execution error message */ static Char *expath; /* Path for exerr */ /* * The two part hash function is designed to let texec() call the * more expensive hashname() only once and the simple hash() several * times (once for each path component checked). * Byte size is assumed to be 8. */ #define BITS_PER_BYTE 8 #ifdef FASTHASH /* * xhash is an array of hash buckets which are used to hash execs. If * it is allocated (havhash true), then to tell if ``name'' is * (possibly) present in the i'th component of the variable path, look * at the [hashname(name)] bucket of size [hashwidth] bytes, in the [i * mod size*8]'th bit. The cache size is defaults to a length of 1024 * buckets, each 1 byte wide. This implementation guarantees that * objects n bytes wide will be aligned on n byte boundaries. */ # define HSHMUL 241 static unsigned long *xhash = NULL; static unsigned int hashlength = 0, uhashlength = 0; static unsigned int hashwidth = 0, uhashwidth = 0; static int hashdebug = 0; # define hash(a, b) (((a) * HSHMUL + (b)) % (hashlength)) # define widthof(t) (sizeof(t) * BITS_PER_BYTE) # define tbit(f, i, t) (((t *) xhash)[(f)] & \ (1UL << (i & (widthof(t) - 1)))) # define tbis(f, i, t) (((t *) xhash)[(f)] |= \ (1UL << (i & (widthof(t) - 1)))) # define cbit(f, i) tbit(f, i, unsigned char) # define cbis(f, i) tbis(f, i, unsigned char) # define sbit(f, i) tbit(f, i, unsigned short) # define sbis(f, i) tbis(f, i, unsigned short) # define ibit(f, i) tbit(f, i, unsigned int) # define ibis(f, i) tbis(f, i, unsigned int) # define lbit(f, i) tbit(f, i, unsigned long) # define lbis(f, i) tbis(f, i, unsigned long) # define bit(f, i) (hashwidth==sizeof(unsigned char) ? cbit(f,i) : \ ((hashwidth==sizeof(unsigned short) ? sbit(f,i) : \ ((hashwidth==sizeof(unsigned int) ? ibit(f,i) : \ lbit(f,i)))))) # define bis(f, i) (hashwidth==sizeof(unsigned char) ? cbis(f,i) : \ ((hashwidth==sizeof(unsigned short) ? sbis(f,i) : \ ((hashwidth==sizeof(unsigned int) ? ibis(f,i) : \ lbis(f,i)))))) #else /* OLDHASH */ /* * Xhash is an array of HSHSIZ bits (HSHSIZ / 8 chars), which are used * to hash execs. If it is allocated (havhash true), then to tell * whether ``name'' is (possibly) present in the i'th component * of the variable path, you look at the bit in xhash indexed by * hash(hashname("name"), i). This is setup automatically * after .login is executed, and recomputed whenever ``path'' is * changed. */ # define HSHSIZ 8192 /* 1k bytes */ # define HSHMASK (HSHSIZ - 1) # define HSHMUL 243 static char xhash[HSHSIZ / BITS_PER_BYTE]; # define hash(a, b) (((a) * HSHMUL + (b)) & HSHMASK) # define bit(h, b) ((h)[(b) >> 3] & 1 << ((b) & 7)) /* bit test */ # define bis(h, b) ((h)[(b) >> 3] |= 1 << ((b) & 7)) /* bit set */ #endif /* FASTHASH */ #ifdef VFORK static int hits, misses; #endif /* VFORK */ /* Dummy search path for just absolute search when no path */ static Char *justabs[] = {STRNULL, 0}; static void pexerr (void) __attribute__((__noreturn__)); static void texec (Char *, Char **); int hashname (Char *); static int iscommand (Char *); void doexec(struct command *t, int do_glob) { Char *dp, **pv, **opv, **av, *sav; struct varent *v; int slash, gflag, rehashed; int hashval, i; Char *blk[2]; /* * Glob the command name. We will search $path even if this does something, * as in sh but not in csh. One special case: if there is no PATH, then we * execute only commands which start with '/'. */ blk[0] = t->t_dcom[0]; blk[1] = 0; gflag = 0; if (do_glob) gflag = tglob(blk); if (gflag) { pv = globall(blk, gflag); if (pv == 0) { setname(short2str(blk[0])); stderror(ERR_NAME | ERR_NOMATCH); } } else pv = saveblk(blk); cleanup_push(pv, blk_cleanup); trim(pv); exerr = 0; expath = Strsave(pv[0]); #ifdef VFORK Vexpath = expath; #endif /* VFORK */ v = adrof(STRpath); if (v == 0 && expath[0] != '/' && expath[0] != '.') pexerr(); slash = any(short2str(expath), '/'); /* * Glob the argument list, if necessary. Otherwise trim off the quote bits. */ gflag = 0; av = &t->t_dcom[1]; if (do_glob) gflag = tglob(av); if (gflag) { av = globall(av, gflag); if (av == 0) { setname(short2str(expath)); stderror(ERR_NAME | ERR_NOMATCH); } } else av = saveblk(av); blkfree(t->t_dcom); cleanup_ignore(pv); cleanup_until(pv); t->t_dcom = blkspl(pv, av); xfree(pv); xfree(av); av = t->t_dcom; trim(av); if (*av == NULL || **av == '\0') pexerr(); xechoit(av); /* Echo command if -x */ #ifdef CLOSE_ON_EXEC /* * Since all internal file descriptors are set to close on exec, we don't * need to close them explicitly here. Just reorient ourselves for error * messages. */ SHIN = 0; SHOUT = 1; SHDIAG = 2; OLDSTD = 0; isoutatty = isatty(SHOUT); isdiagatty = isatty(SHDIAG); #else closech(); /* Close random fd's */ #endif /* * We must do this AFTER any possible forking (like `foo` in glob) so that * this shell can still do subprocesses. */ { sigset_t set; sigemptyset(&set); sigaddset(&set, SIGINT); sigaddset(&set, SIGCHLD); sigprocmask(SIG_UNBLOCK, &set, NULL); } pintr_disabled = 0; pchild_disabled = 0; /* * If no path, no words in path, or a / in the filename then restrict the * command search. */ if (v == NULL || v->vec == NULL || v->vec[0] == NULL || slash) opv = justabs; else opv = v->vec; sav = Strspl(STRslash, *av);/* / command name for postpending */ #ifndef VFORK cleanup_push(sav, xfree); #else /* VFORK */ Vsav = sav; #endif /* VFORK */ hashval = havhash ? hashname(*av) : 0; rehashed = 0; retry: pv = opv; i = 0; #ifdef VFORK hits++; #endif /* VFORK */ do { /* * Try to save time by looking at the hash table for where this command * could be. If we are doing delayed hashing, then we put the names in * one at a time, as the user enters them. This is kinda like Korn * Shell's "tracked aliases". */ if (!slash && ABSOLUTEP(pv[0]) && havhash) { #ifdef FASTHASH if (!bit(hashval, i)) goto cont; #else /* OLDHASH */ int hashval1 = hash(hashval, i); if (!bit(xhash, hashval1)) goto cont; #endif /* FASTHASH */ } if (pv[0][0] == 0 || eq(pv[0], STRdot)) /* don't make ./xxx */ texec(*av, av); else { dp = Strspl(*pv, sav); #ifndef VFORK cleanup_push(dp, xfree); #else /* VFORK */ Vdp = dp; #endif /* VFORK */ texec(dp, av); #ifndef VFORK cleanup_until(dp); #else /* VFORK */ Vdp = 0; xfree(dp); #endif /* VFORK */ } #ifdef VFORK misses++; #endif /* VFORK */ cont: pv++; i++; } while (*pv); #ifdef VFORK hits--; #endif /* VFORK */ if (adrof(STRautorehash) && !rehashed && havhash && opv != justabs) { dohash(NULL, NULL); rehashed = 1; goto retry; } #ifndef VFORK cleanup_until(sav); #else /* VFORK */ Vsav = 0; xfree(sav); #endif /* VFORK */ pexerr(); } static void pexerr(void) { /* Couldn't find the damn thing */ if (expath) { setname(short2str(expath)); #ifdef VFORK Vexpath = 0; #endif /* VFORK */ xfree(expath); expath = 0; } else setname(""); if (exerr) stderror(ERR_NAME | ERR_STRING, exerr); stderror(ERR_NAME | ERR_COMMAND); } /* * Execute command f, arg list t. * Record error message if not found. * Also do shell scripts here. */ static void texec(Char *sf, Char **st) { char **t; char *f; struct varent *v; Char **vp; Char *lastsh[2]; char pref[2]; int fd; Char *st0, **ost; /* The order for the conversions is significant */ t = short2blk(st); f = short2str(sf); #ifdef VFORK Vt = t; #endif /* VFORK */ errno = 0; /* don't use a previous error */ #ifdef apollo /* * If we try to execute an nfs mounted directory on the apollo, we * hang forever. So until apollo fixes that.. */ { struct stat stb; if (stat(f, &stb) == 0 && S_ISDIR(stb.st_mode)) errno = EISDIR; } if (errno == 0) #endif /* apollo */ { #ifdef ISC_POSIX_EXEC_BUG __setostype(0); /* "0" is "__OS_SYSV" in */ #endif /* ISC_POSIX_EXEC_BUG */ (void) execv(f, t); #ifdef ISC_POSIX_EXEC_BUG __setostype(1); /* "1" is "__OS_POSIX" in */ #endif /* ISC_POSIX_EXEC_BUG */ } #ifdef VFORK Vt = 0; #endif /* VFORK */ blkfree((Char **) t); switch (errno) { case ENOEXEC: #ifdef WINNT_NATIVE nt_feed_to_cmd(f,t); #endif /* WINNT_NATIVE */ /* * From: casper@fwi.uva.nl (Casper H.S. Dik) If we could not execute * it, don't feed it to the shell if it looks like a binary! */ if ((fd = xopen(f, O_RDONLY|O_LARGEFILE)) != -1) { int nread; if ((nread = xread(fd, pref, 2)) == 2) { if (!isprint((unsigned char)pref[0]) && (pref[0] != '\n' && pref[0] != '\t')) { int err; err = errno; xclose(fd); /* * We *know* what ENOEXEC means. */ stderror(ERR_ARCH, f, strerror(err)); } } else if (nread < 0) { #ifdef convex int err; err = errno; xclose(fd); /* need to print error incase the file is migrated */ stderror(ERR_SYSTEM, f, strerror(err)); #endif } #ifdef _PATH_BSHELL else { pref[0] = '#'; pref[1] = '\0'; } #endif } #ifdef HASHBANG if (fd == -1 || pref[0] != '#' || pref[1] != '!' || hashbang(fd, &vp) == -1) { #endif /* HASHBANG */ /* * If there is an alias for shell, then put the words of the alias in * front of the argument list replacing the command name. Note no * interpretation of the words at this point. */ v = adrof1(STRshell, &aliases); if (v == NULL || v->vec == NULL) { vp = lastsh; vp[0] = adrof(STRshell) ? varval(STRshell) : STR_SHELLPATH; vp[1] = NULL; #ifdef _PATH_BSHELL - if (fd != -1 + if (fd != -1 # ifndef ISC /* Compatible with ISC's /bin/csh */ && pref[0] != '#' # endif /* ISC */ ) vp[0] = STR_BSHELL; #endif vp = saveblk(vp); } else vp = saveblk(v->vec); #ifdef HASHBANG } #endif /* HASHBANG */ if (fd != -1) xclose(fd); st0 = st[0]; st[0] = sf; ost = st; st = blkspl(vp, st); /* Splice up the new arglst */ ost[0] = st0; sf = *st; /* The order for the conversions is significant */ t = short2blk(st); f = short2str(sf); xfree(st); blkfree((Char **) vp); #ifdef VFORK Vt = t; #endif /* VFORK */ #ifdef ISC_POSIX_EXEC_BUG __setostype(0); /* "0" is "__OS_SYSV" in */ #endif /* ISC_POSIX_EXEC_BUG */ (void) execv(f, t); #ifdef ISC_POSIX_EXEC_BUG __setostype(1); /* "1" is "__OS_POSIX" in */ #endif /* ISC_POSIX_EXEC_BUG */ #ifdef VFORK Vt = 0; #endif /* VFORK */ blkfree((Char **) t); /* The sky is falling, the sky is falling! */ stderror(ERR_SYSTEM, f, strerror(errno)); break; case ENOMEM: stderror(ERR_SYSTEM, f, strerror(errno)); break; #ifdef _IBMR2 case 0: /* execv fails and returns 0! */ #endif /* _IBMR2 */ case ENOENT: break; default: if (exerr == 0) { exerr = strerror(errno); xfree(expath); expath = Strsave(sf); #ifdef VFORK Vexpath = expath; #endif /* VFORK */ } break; } } struct execash_state { int saveIN, saveOUT, saveDIAG, saveSTD; int SHIN, SHOUT, SHDIAG, OLDSTD; int didfds; #ifndef CLOSE_ON_EXEC int didcch; #endif struct sigaction sigint, sigquit, sigterm; }; static void execash_cleanup(void *xstate) { struct execash_state *state; state = xstate; sigaction(SIGINT, &state->sigint, NULL); sigaction(SIGQUIT, &state->sigquit, NULL); sigaction(SIGTERM, &state->sigterm, NULL); doneinp = 0; #ifndef CLOSE_ON_EXEC didcch = state->didcch; #endif /* CLOSE_ON_EXEC */ didfds = state->didfds; xclose(SHIN); xclose(SHOUT); xclose(SHDIAG); xclose(OLDSTD); close_on_exec(SHIN = dmove(state->saveIN, state->SHIN), 1); close_on_exec(SHOUT = dmove(state->saveOUT, state->SHOUT), 1); close_on_exec(SHDIAG = dmove(state->saveDIAG, state->SHDIAG), 1); close_on_exec(OLDSTD = dmove(state->saveSTD, state->OLDSTD), 1); } /*ARGSUSED*/ void execash(Char **t, struct command *kp) { struct execash_state state; USE(t); if (chkstop == 0 && setintr) panystop(0); /* * Hmm, we don't really want to do that now because we might * fail, but what is the choice */ rechist(NULL, adrof(STRsavehist) != NULL); sigaction(SIGINT, &parintr, &state.sigint); sigaction(SIGQUIT, &parintr, &state.sigquit); sigaction(SIGTERM, &parterm, &state.sigterm); state.didfds = didfds; #ifndef CLOSE_ON_EXEC state.didcch = didcch; #endif /* CLOSE_ON_EXEC */ state.SHIN = SHIN; state.SHOUT = SHOUT; state.SHDIAG = SHDIAG; state.OLDSTD = OLDSTD; (void)close_on_exec (state.saveIN = dcopy(SHIN, -1), 1); (void)close_on_exec (state.saveOUT = dcopy(SHOUT, -1), 1); (void)close_on_exec (state.saveDIAG = dcopy(SHDIAG, -1), 1); (void)close_on_exec (state.saveSTD = dcopy(OLDSTD, -1), 1); lshift(kp->t_dcom, 1); (void)close_on_exec (SHIN = dcopy(0, -1), 1); (void)close_on_exec (SHOUT = dcopy(1, -1), 1); (void)close_on_exec (SHDIAG = dcopy(2, -1), 1); #ifndef CLOSE_ON_EXEC didcch = 0; #endif /* CLOSE_ON_EXEC */ didfds = 0; cleanup_push(&state, execash_cleanup); /* * Decrement the shell level, if not in a subshell */ if (mainpid == getpid()) shlvl(-1); #ifdef WINNT_NATIVE __nt_really_exec=1; #endif /* WINNT_NATIVE */ doexec(kp, 1); cleanup_until(&state); } void xechoit(Char **t) { if (adrof(STRecho)) { int odidfds = didfds; flush(); haderr = 1; didfds = 0; blkpr(t), xputchar('\n'); flush(); didfds = odidfds; haderr = 0; } } /*ARGSUSED*/ void dohash(Char **vv, struct command *c) { #ifdef COMMENT struct stat stb; #endif DIR *dirp; struct dirent *dp; int i = 0; struct varent *v = adrof(STRpath); Char **pv; int hashval; #ifdef WINNT_NATIVE int is_windir; /* check if it is the windows directory */ USE(hashval); #endif /* WINNT_NATIVE */ USE(c); #ifdef FASTHASH if (vv && vv[1]) { uhashlength = atoi(short2str(vv[1])); if (vv[2]) { uhashwidth = atoi(short2str(vv[2])); - if ((uhashwidth != sizeof(unsigned char)) && - (uhashwidth != sizeof(unsigned short)) && + if ((uhashwidth != sizeof(unsigned char)) && + (uhashwidth != sizeof(unsigned short)) && (uhashwidth != sizeof(unsigned long))) uhashwidth = 0; if (vv[3]) hashdebug = atoi(short2str(vv[3])); } } if (uhashwidth) hashwidth = uhashwidth; else { hashwidth = 0; if (v == NULL) return; for (pv = v->vec; pv && *pv; pv++, hashwidth++) continue; if (hashwidth <= widthof(unsigned char)) hashwidth = sizeof(unsigned char); else if (hashwidth <= widthof(unsigned short)) hashwidth = sizeof(unsigned short); else if (hashwidth <= widthof(unsigned int)) hashwidth = sizeof(unsigned int); else hashwidth = sizeof(unsigned long); } if (uhashlength) hashlength = uhashlength; else hashlength = hashwidth * (8*64);/* "average" files per dir in path */ xfree(xhash); xhash = xcalloc(hashlength * hashwidth, 1); #endif /* FASTHASH */ (void) getusername(NULL); /* flush the tilde cashe */ tw_cmd_free(); havhash = 1; if (v == NULL) return; for (pv = v->vec; pv && *pv; pv++, i++) { if (!ABSOLUTEP(pv[0])) continue; dirp = opendir(short2str(*pv)); if (dirp == NULL) continue; cleanup_push(dirp, opendir_cleanup); #ifdef COMMENT /* this isn't needed. opendir won't open * non-dirs */ if (fstat(dirp->dd_fd, &stb) < 0 || !S_ISDIR(stb.st_mode)) { cleanup_until(dirp); continue; } #endif #ifdef WINNT_NATIVE is_windir = nt_check_if_windir(short2str(*pv)); #endif /* WINNT_NATIVE */ while ((dp = readdir(dirp)) != NULL) { if (dp->d_ino == 0) continue; if (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))) continue; #ifdef WINNT_NATIVE nt_check_name_and_hash(is_windir, dp->d_name, i); #else /* !WINNT_NATIVE*/ #if defined(_UWIN) || defined(__CYGWIN__) /* Turn foo.{exe,com,bat} into foo since UWIN's readdir returns * the file with the .exe, .com, .bat extension * * Same for Cygwin, but only for .exe and .com extension. */ { ssize_t ext = strlen(dp->d_name) - 4; if ((ext > 0) && (strcasecmp(&dp->d_name[ext], ".exe") == 0 || #ifndef __CYGWIN__ strcasecmp(&dp->d_name[ext], ".bat") == 0 || #endif strcasecmp(&dp->d_name[ext], ".com") == 0)) { #ifdef __CYGWIN__ /* Also store the variation with extension. */ hashval = hashname(str2short(dp->d_name)); bis(hashval, i); #endif /* __CYGWIN__ */ dp->d_name[ext] = '\0'; } } #endif /* _UWIN || __CYGWIN__ */ # ifdef FASTHASH hashval = hashname(str2short(dp->d_name)); bis(hashval, i); if (hashdebug & 1) xprintf(CGETS(13, 1, "hash=%-4d dir=%-2d prog=%s\n"), hashname(str2short(dp->d_name)), i, dp->d_name); # else /* OLD HASH */ hashval = hash(hashname(str2short(dp->d_name)), i); bis(xhash, hashval); # endif /* FASTHASH */ /* tw_add_comm_name (dp->d_name); */ #endif /* WINNT_NATIVE */ } cleanup_until(dirp); } } /*ARGSUSED*/ void dounhash(Char **v, struct command *c) { USE(c); USE(v); havhash = 0; #ifdef FASTHASH xfree(xhash); xhash = NULL; #endif /* FASTHASH */ } /*ARGSUSED*/ void hashstat(Char **v, struct command *c) { USE(c); USE(v); -#ifdef FASTHASH +#ifdef FASTHASH if (havhash && hashlength && hashwidth) xprintf(CGETS(13, 2, "%d hash buckets of %d bits each\n"), hashlength, hashwidth*8); if (hashdebug) xprintf(CGETS(13, 3, "debug mask = 0x%08x\n"), hashdebug); #endif /* FASTHASH */ #ifdef VFORK if (hits + misses) xprintf(CGETS(13, 4, "%d hits, %d misses, %d%%\n"), hits, misses, 100 * hits / (hits + misses)); #endif } /* * Hash a command name. */ int hashname(Char *cp) { unsigned long h; for (h = 0; *cp; cp++) h = hash(h, *cp); return ((int) h); } static int iscommand(Char *name) { Char **opv, **pv; Char *sav; struct varent *v; int slash = any(short2str(name), '/'); int hashval, rehashed, i; v = adrof(STRpath); if (v == NULL || v->vec == NULL || v->vec[0] == NULL || slash) opv = justabs; else opv = v->vec; sav = Strspl(STRslash, name); /* / command name for postpending */ hashval = havhash ? hashname(name) : 0; rehashed = 0; retry: pv = opv; i = 0; do { if (!slash && ABSOLUTEP(pv[0]) && havhash) { #ifdef FASTHASH if (!bit(hashval, i)) goto cont; #else /* OLDHASH */ int hashval1 = hash(hashval, i); if (!bit(xhash, hashval1)) goto cont; #endif /* FASTHASH */ } if (pv[0][0] == 0 || eq(pv[0], STRdot)) { /* don't make ./xxx */ if (executable(NULL, name, 0)) { xfree(sav); return i + 1; } } else { if (executable(*pv, sav, 0)) { xfree(sav); return i + 1; } } cont: pv++; i++; } while (*pv); if (adrof(STRautorehash) && !rehashed && havhash && opv != justabs) { dohash(NULL, NULL); rehashed = 1; goto retry; } xfree(sav); return 0; } /* Also by: * Andreas Luik * I S A GmbH - Informationssysteme fuer computerintegrierte Automatisierung * Azenberstr. 35 * D-7000 Stuttgart 1 * West-Germany * is the executable() routine below and changes to iscommand(). * Thanks again!! */ #ifndef WINNT_NATIVE /* * executable() examines the pathname obtained by concatenating dir and name * (dir may be NULL), and returns 1 either if it is executable by us, or * if dir_ok is set and the pathname refers to a directory. * This is a bit kludgy, but in the name of optimization... */ int executable(const Char *dir, const Char *name, int dir_ok) { struct stat stbuf; char *strname; if (dir && *dir) { Char *path; path = Strspl(dir, name); strname = short2str(path); xfree(path); } else strname = short2str(name); return (stat(strname, &stbuf) != -1 && ((dir_ok && S_ISDIR(stbuf.st_mode)) || (S_ISREG(stbuf.st_mode) && /* save time by not calling access() in the hopeless case */ (stbuf.st_mode & (S_IXOTH | S_IXGRP | S_IXUSR)) && access(strname, X_OK) == 0 ))); } #endif /*!WINNT_NATIVE*/ struct tellmewhat_s0_cleanup { Char **dest, *val; }; static void tellmewhat_s0_cleanup(void *xstate) { struct tellmewhat_s0_cleanup *state; state = xstate; *state->dest = state->val; } int tellmewhat(struct wordent *lexp, Char **str) { struct tellmewhat_s0_cleanup s0; int i; const struct biltins *bptr; struct wordent *sp = lexp->next; int aliased = 0, found; Char *s1, *s2, *cmd; Char qc; if (adrof1(sp->word, &aliases)) { alias(lexp); sp = lexp->next; aliased = 1; } s0.dest = &sp->word; /* to get the memory freeing right... */ s0.val = sp->word; cleanup_push(&s0, tellmewhat_s0_cleanup); /* handle quoted alias hack */ if ((*(sp->word) & (QUOTE | TRIM)) == QUOTE) (sp->word)++; /* do quoting, if it hasn't been done */ s1 = s2 = sp->word; while (*s2) switch (*s2) { case '\'': case '"': qc = *s2++; while (*s2 && *s2 != qc) *s1++ = *s2++ | QUOTE; if (*s2) s2++; break; case '\\': if (*++s2) *s1++ = *s2++ | QUOTE; break; default: *s1++ = *s2++; } *s1 = '\0'; for (bptr = bfunc; bptr < &bfunc[nbfunc]; bptr++) { if (eq(sp->word, str2short(bptr->bname))) { if (str == NULL) { if (aliased) prlex(lexp); xprintf(CGETS(13, 5, "%S: shell built-in command.\n"), sp->word); flush(); } else *str = Strsave(sp->word); cleanup_until(&s0); return TRUE; } } #ifdef WINNT_NATIVE for (bptr = nt_bfunc; bptr < &nt_bfunc[nt_nbfunc]; bptr++) { if (eq(sp->word, str2short(bptr->bname))) { if (str == NULL) { if (aliased) prlex(lexp); xprintf(CGETS(13, 5, "%S: shell built-in command.\n"), sp->word); flush(); } else *str = Strsave(sp->word); cleanup_until(&s0); return TRUE; } } #endif /* WINNT_NATIVE*/ sp->word = cmd = globone(sp->word, G_IGNORE); cleanup_push(cmd, xfree); if ((i = iscommand(sp->word)) != 0) { Char **pv; struct varent *v; int slash = any(short2str(sp->word), '/'); v = adrof(STRpath); if (v == NULL || v->vec == NULL || v->vec[0] == NULL || slash) pv = justabs; else pv = v->vec; pv += i - 1; if (pv[0][0] == 0 || eq(pv[0], STRdot)) { if (!slash) { sp->word = Strspl(STRdotsl, sp->word); cleanup_push(sp->word, xfree); prlex(lexp); cleanup_until(sp->word); } else prlex(lexp); } else { s1 = Strspl(*pv, STRslash); sp->word = Strspl(s1, sp->word); xfree(s1); cleanup_push(sp->word, xfree); if (str == NULL) prlex(lexp); else *str = Strsave(sp->word); cleanup_until(sp->word); } found = 1; } else { if (str == NULL) { if (aliased) prlex(lexp); xprintf(CGETS(13, 6, "%S: Command not found.\n"), sp->word); flush(); } else *str = Strsave(sp->word); found = 0; } cleanup_until(&s0); return found; } /* * Builtin to look at and list all places a command may be defined: * aliases, shell builtins, and the path. * * Marc Horowitz * MIT Student Information Processing Board */ /*ARGSUSED*/ void dowhere(Char **v, struct command *c) { int found = 1; USE(c); if (adrof(STRautorehash)) dohash(NULL, NULL); for (v++; *v; v++) found &= find_cmd(*v, 1); /* Make status nonzero if any command is not found. */ if (!found) setcopy(STRstatus, STR1, VAR_READWRITE); } int find_cmd(Char *cmd, int prt) { struct varent *var; const struct biltins *bptr; Char **pv; Char *sv; int hashval, rehashed, i, ex, rval = 0; if (prt && any(short2str(cmd), '/')) { xprintf("%s", CGETS(13, 7, "where: / in command makes no sense\n")); return rval; } /* first, look for an alias */ if (prt && adrof1(cmd, &aliases)) { if ((var = adrof1(cmd, &aliases)) != NULL) { xprintf(CGETS(13, 8, "%S is aliased to "), cmd); if (var->vec != NULL) blkpr(var->vec); xputchar('\n'); rval = 1; } } /* next, look for a shell builtin */ for (bptr = bfunc; bptr < &bfunc[nbfunc]; bptr++) { if (eq(cmd, str2short(bptr->bname))) { rval = 1; if (prt) xprintf(CGETS(13, 9, "%S is a shell built-in\n"), cmd); else return rval; } } #ifdef WINNT_NATIVE for (bptr = nt_bfunc; bptr < &nt_bfunc[nt_nbfunc]; bptr++) { if (eq(cmd, str2short(bptr->bname))) { rval = 1; if (prt) xprintf(CGETS(13, 9, "%S is a shell built-in\n"), cmd); else return rval; } } #endif /* WINNT_NATIVE*/ /* last, look through the path for the command */ if ((var = adrof(STRpath)) == NULL) return rval; hashval = havhash ? hashname(cmd) : 0; sv = Strspl(STRslash, cmd); cleanup_push(sv, xfree); rehashed = 0; retry: for (pv = var->vec, i = 0; pv && *pv; pv++, i++) { if (havhash && !eq(*pv, STRdot)) { #ifdef FASTHASH if (!bit(hashval, i)) continue; #else /* OLDHASH */ int hashval1 = hash(hashval, i); if (!bit(xhash, hashval1)) continue; #endif /* FASTHASH */ } ex = executable(*pv, sv, 0); #ifdef FASTHASH if (!ex && (hashdebug & 2)) { xprintf("%s", CGETS(13, 10, "hash miss: ")); ex = 1; /* Force printing */ } #endif /* FASTHASH */ if (ex) { rval = 1; if (prt) { xprintf("%S/", *pv); xprintf("%S\n", cmd); } else return rval; } } /* - * If we are printing, we are being called from dowhere() which it + * If we are printing, we are being called from dowhere() which it * has rehashed already */ if (!prt && adrof(STRautorehash) && !rehashed && havhash) { dohash(NULL, NULL); rehashed = 1; goto retry; } cleanup_until(sv); return rval; } #ifdef WINNT_NATIVE int hashval_extern(cp) Char *cp; { return havhash?hashname(cp):0; } int bit_extern(val,i) int val; int i; { return bit(val,i); } void bis_extern(val,i) int val; int i; { bis(val,i); } #endif /* WINNT_NATIVE */ diff --git a/contrib/tcsh/sh.exp.c b/contrib/tcsh/sh.exp.c index f9e92c515382..2f5f0088e126 100644 --- a/contrib/tcsh/sh.exp.c +++ b/contrib/tcsh/sh.exp.c @@ -1,1053 +1,1053 @@ /* * sh.exp.c: Expression evaluations */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "tw.h" /* * C shell */ #define TEXP_IGNORE 1 /* in ignore, it means to ignore value, just parse */ #define TEXP_NOGLOB 2 /* in ignore, it means not to globone */ #define ADDOP 1 #define MULOP 2 #define EQOP 4 #define RELOP 8 #define RESTOP 16 #define ANYOP 31 #define EQEQ 1 #define GTR 2 #define LSS 4 #define NOTEQ 6 #define EQMATCH 7 #define NOTEQMATCH 8 static int sh_access (const Char *, int); static tcsh_number_t exp1 (Char ***, int); static tcsh_number_t exp2x (Char ***, int); static tcsh_number_t exp2a (Char ***, int); static tcsh_number_t exp2b (Char ***, int); static tcsh_number_t exp2c (Char ***, int); static Char *exp3 (Char ***, int); static Char *exp3a (Char ***, int); static Char *exp4 (Char ***, int); static Char *exp5 (Char ***, int); static Char *exp6 (Char ***, int); static void evalav (Char **); static int isa (Char *, int); static tcsh_number_t egetn (const Char *); #ifdef EDEBUG static void etracc (const char *, const Char *, Char ***); static void etraci (const char *, tcsh_number_t, Char ***); #else /* !EDEBUG */ #define etracc(A, B, C) ((void)0) #define etraci(A, B, C) ((void)0) #endif /* !EDEBUG */ /* * shell access function according to POSIX and non POSIX * From Beto Appleton (beto@aixwiz.aix.ibm.com) */ static int sh_access(const Char *fname, int mode) { #if defined(POSIX) && !defined(USE_ACCESS) struct stat statb; #endif /* POSIX */ char *name = short2str(fname); if (*name == '\0') return 1; #if !defined(POSIX) || defined(USE_ACCESS) return access(name, mode); #else /* POSIX */ /* - * POSIX 1003.2-d11.2 - * -r file True if file exists and is readable. - * -w file True if file exists and is writable. - * True shall indicate only that the write flag is on. + * POSIX 1003.2-d11.2 + * -r file True if file exists and is readable. + * -w file True if file exists and is writable. + * True shall indicate only that the write flag is on. * The file shall not be writable on a read-only file * system even if this test indicates true. - * -x file True if file exists and is executable. - * True shall indicate only that the execute flag is on. - * If file is a directory, true indicates that the file + * -x file True if file exists and is executable. + * True shall indicate only that the execute flag is on. + * If file is a directory, true indicates that the file * can be searched. */ if (mode != W_OK && mode != X_OK) return access(name, mode); - if (stat(name, &statb) == -1) + if (stat(name, &statb) == -1) return 1; if (access(name, mode) == 0) { #ifdef S_ISDIR if (S_ISDIR(statb.st_mode) && mode == X_OK) return 0; #endif /* S_ISDIR */ /* root needs permission for someone */ switch (mode) { case W_OK: mode = S_IWUSR | S_IWGRP | S_IWOTH; break; case X_OK: mode = S_IXUSR | S_IXGRP | S_IXOTH; break; default: abort(); break; } - } + } else if (euid == statb.st_uid) mode <<= 6; else if (egid == statb.st_gid) mode <<= 3; # ifdef NGROUPS_MAX else { /* you can be in several groups */ long n; GETGROUPS_T *groups; /* * Try these things to find a positive maximum groups value: * 1) sysconf(_SC_NGROUPS_MAX) * 2) NGROUPS_MAX * 3) getgroups(0, unused) * Then allocate and scan the groups array if one of these worked. */ # if defined (HAVE_SYSCONF) && defined (_SC_NGROUPS_MAX) if ((n = sysconf(_SC_NGROUPS_MAX)) == -1) # endif /* _SC_NGROUPS_MAX */ n = NGROUPS_MAX; if (n <= 0) n = getgroups(0, (GETGROUPS_T *) NULL); if (n > 0) { groups = xmalloc(n * sizeof(*groups)); n = getgroups((int) n, groups); while (--n >= 0) if (groups[n] == statb.st_gid) { mode <<= 3; break; } xfree(groups); } } # endif /* NGROUPS_MAX */ if (statb.st_mode & mode) return 0; else return 1; #endif /* !POSIX */ } tcsh_number_t expr(Char ***vp) { return (exp0(vp, 0)); } tcsh_number_t exp0(Char ***vp, int ignore) { tcsh_number_t p1 = exp1(vp, ignore); etraci("exp0 p1", p1, vp); while (**vp && eq(**vp, STRor2)) { int p2; (*vp)++; - p2 = compat_expr ? + p2 = compat_expr ? exp0(vp, (ignore & TEXP_IGNORE) || p1) : exp1(vp, (ignore & TEXP_IGNORE) || p1); if (compat_expr || !(ignore & TEXP_IGNORE)) p1 = (p1 || p2); etraci("exp0 p1", p1, vp); if (compat_expr) break; } return (p1); } static tcsh_number_t exp1(Char ***vp, int ignore) { tcsh_number_t p1 = exp2x(vp, ignore); etraci("exp1 p1", p1, vp); while (**vp && eq(**vp, STRand2)) { tcsh_number_t p2; (*vp)++; p2 = compat_expr ? exp1(vp, (ignore & TEXP_IGNORE) || !p1) : exp2x(vp, (ignore & TEXP_IGNORE) || !p1); etraci("exp1 p2", p2, vp); if (compat_expr || !(ignore & TEXP_IGNORE)) p1 = (p1 && p2); etraci("exp1 p1", p1, vp); if (compat_expr) break; } return (p1); } static tcsh_number_t exp2x(Char ***vp, int ignore) { tcsh_number_t p1 = exp2a(vp, ignore); etraci("exp2x p1", p1, vp); while (**vp && eq(**vp, STRor)) { tcsh_number_t p2; (*vp)++; p2 = compat_expr ? exp2x(vp, ignore) : exp2a(vp, ignore); etraci("exp2x p2", p2, vp); if (compat_expr || !(ignore & TEXP_IGNORE)) p1 = (p1 | p2); etraci("exp2x p1", p1, vp); if (compat_expr) break; } return (p1); } static tcsh_number_t exp2a(Char ***vp, int ignore) { tcsh_number_t p1 = exp2b(vp, ignore); etraci("exp2a p1", p1, vp); while (**vp && eq(**vp, STRcaret)) { tcsh_number_t p2; (*vp)++; p2 = compat_expr ? exp2a(vp, ignore) : exp2b(vp, ignore); etraci("exp2a p2", p2, vp); if (compat_expr || !(ignore & TEXP_IGNORE)) p1 = (p1 ^ p2); etraci("exp2a p1", p1, vp); if (compat_expr) break; } return (p1); } static tcsh_number_t exp2b(Char ***vp, int ignore) { tcsh_number_t p1 = exp2c(vp, ignore); etraci("exp2b p1", p1, vp); while (**vp && eq(**vp, STRand)) { tcsh_number_t p2; (*vp)++; p2 = compat_expr ? exp2b(vp, ignore) : exp2c(vp, ignore); etraci("exp2b p2", p2, vp); if (compat_expr || !(ignore & TEXP_IGNORE)) p1 = (p1 & p2); etraci("exp2b p1", p1, vp); if (compat_expr) break; } return (p1); } static tcsh_number_t exp2c(Char ***vp, int ignore) { Char *p1 = exp3(vp, ignore); Char *p2; tcsh_number_t i; cleanup_push(p1, xfree); etracc("exp2c p1", p1, vp); if ((i = isa(**vp, EQOP)) != 0) { (*vp)++; if (i == EQMATCH || i == NOTEQMATCH) ignore |= TEXP_NOGLOB; p2 = exp3(vp, ignore); cleanup_push(p2, xfree); etracc("exp2c p2", p2, vp); if (!(ignore & TEXP_IGNORE)) switch ((int)i) { case EQEQ: i = eq(p1, p2); break; case NOTEQ: i = !eq(p1, p2); break; case EQMATCH: i = Gmatch(p1, p2); break; case NOTEQMATCH: i = !Gmatch(p1, p2); break; } cleanup_until(p1); return (i); } i = egetn(p1); cleanup_until(p1); return (i); } static Char * exp3(Char ***vp, int ignore) { Char *p1, *p2; tcsh_number_t i; p1 = exp3a(vp, ignore); etracc("exp3 p1", p1, vp); while ((i = isa(**vp, RELOP)) != 0) { (*vp)++; if (**vp && eq(**vp, STRequal)) i |= 1, (*vp)++; cleanup_push(p1, xfree); p2 = compat_expr ? exp3(vp, ignore) : exp3a(vp, ignore); cleanup_push(p2, xfree); etracc("exp3 p2", p2, vp); if (!(ignore & TEXP_IGNORE)) switch ((int)i) { case GTR: i = egetn(p1) > egetn(p2); break; case GTR | 1: i = egetn(p1) >= egetn(p2); break; case LSS: i = egetn(p1) < egetn(p2); break; case LSS | 1: i = egetn(p1) <= egetn(p2); break; } cleanup_until(p1); p1 = putn(i); etracc("exp3 p1", p1, vp); if (compat_expr) break; } return (p1); } static Char * exp3a(Char ***vp, int ignore) { Char *p1, *p2; const Char *op; tcsh_number_t i; p1 = exp4(vp, ignore); etracc("exp3a p1", p1, vp); op = **vp; if (op && any("<>", op[0]) && op[0] == op[1]) { (*vp)++; cleanup_push(p1, xfree); p2 = compat_expr ? exp3a(vp, ignore) : exp4(vp, ignore); cleanup_push(p2, xfree); etracc("exp3a p2", p2, vp); if (op[0] == '<') i = egetn(p1) << egetn(p2); else i = egetn(p1) >> egetn(p2); cleanup_until(p1); p1 = putn(i); etracc("exp3a p1", p1, vp); } return (p1); } static Char * exp4(Char ***vp, int ignore) { Char *p1, *p2; tcsh_number_t i = 0; p1 = exp5(vp, ignore); etracc("exp4 p1", p1, vp); while (isa(**vp, ADDOP)) { const Char *op = *(*vp)++; cleanup_push(p1, xfree); p2 = compat_expr ? exp4(vp, ignore) : exp5(vp, ignore); cleanup_push(p2, xfree); etracc("exp4 p2", p2, vp); if (!(ignore & TEXP_IGNORE)) switch (op[0]) { case '+': i = egetn(p1) + egetn(p2); break; case '-': i = egetn(p1) - egetn(p2); break; } cleanup_until(p1); p1 = putn(i); etracc("exp4 p1", p1, vp); if (compat_expr) break; } return (p1); } static Char * exp5(Char ***vp, int ignore) { Char *p1, *p2; tcsh_number_t i = 0; p1 = exp6(vp, ignore); etracc("exp5 p1", p1, vp); while (isa(**vp, MULOP)) { const Char *op = *(*vp)++; if ((ignore & TEXP_NOGLOB) != 0) { /* * We are just trying to get the right side of * a =~ or !~ operator */ xfree(p1); return Strsave(op); } cleanup_push(p1, xfree); - p2 = compat_expr ? + p2 = compat_expr ? exp5(vp, ignore) : exp6(vp, ignore); cleanup_push(p2, xfree); etracc("exp5 p2", p2, vp); if (!(ignore & TEXP_IGNORE)) switch (op[0]) { case '*': i = egetn(p1) * egetn(p2); break; case '/': i = egetn(p2); if (i == 0) stderror(ERR_DIV0); i = egetn(p1) / i; break; case '%': i = egetn(p2); if (i == 0) stderror(ERR_MOD0); i = egetn(p1) % i; break; } cleanup_until(p1); p1 = putn(i); etracc("exp5 p1", p1, vp); if (compat_expr) break; } return (p1); } static Char * exp6(Char ***vp, int ignore) { tcsh_number_t ccode; tcsh_number_t i = 0; Char *cp; if (**vp == 0) stderror(ERR_NAME | ERR_EXPRESSION); if (eq(**vp, STRbang)) { (*vp)++; cp = exp6(vp, ignore); cleanup_push(cp, xfree); etracc("exp6 ! cp", cp, vp); i = egetn(cp); cleanup_until(cp); return (putn(!i)); } if (eq(**vp, STRtilde)) { (*vp)++; cp = exp6(vp, ignore); cleanup_push(cp, xfree); etracc("exp6 ~ cp", cp, vp); i = egetn(cp); cleanup_until(cp); return (putn(~i)); } if (eq(**vp, STRLparen)) { (*vp)++; ccode = exp0(vp, ignore); etraci("exp6 () ccode", ccode, vp); if (**vp == 0 || ***vp != ')') stderror(ERR_NAME | ERR_EXPRESSION); (*vp)++; return (putn(ccode)); } if (eq(**vp, STRLbrace)) { Char **v; struct command faket; Char *fakecom[2]; faket.t_dtyp = NODE_COMMAND; faket.t_dflg = F_BACKQ; faket.t_dcar = faket.t_dcdr = faket.t_dspr = NULL; faket.t_dcom = fakecom; fakecom[0] = STRfakecom; fakecom[1] = NULL; (*vp)++; v = *vp; for (;;) { if (!**vp) stderror(ERR_NAME | ERR_MISSING, '}'); if (eq(*(*vp)++, STRRbrace)) break; } if (ignore & TEXP_IGNORE) return (Strsave(STRNULL)); psavejob(); cleanup_push(&faket, psavejob_cleanup); /* faket is only a marker */ if (pfork(&faket, -1) == 0) { *--(*vp) = 0; evalav(v); exitstat(); } pwait(); cleanup_until(&faket); etraci("exp6 {} status", egetn(varval(STRstatus)), vp); return (putn(egetn(varval(STRstatus)) == 0)); } if (isa(**vp, ANYOP)) return (Strsave(STRNULL)); cp = *(*vp)++; #ifdef convex # define FILETESTS "erwxfdzoplstSXLbcugkmKR" #else # define FILETESTS "erwxfdzoplstSXLbcugkmK" #endif /* convex */ #define FILEVALS "ZAMCDIUGNFPL" if (*cp == '-' && (any(FILETESTS, cp[1]) || any(FILEVALS, cp[1]))) return(filetest(cp, vp, ignore)); etracc("exp6 default", cp, vp); return (ignore & TEXP_NOGLOB ? Strsave(cp) : globone(cp, G_APPEND)); } -/* +/* * Extended file tests * From: John Rowe */ Char * filetest(Char *cp, Char ***vp, int ignore) { #ifdef convex struct cvxstat stb, *st = NULL; # define TCSH_STAT stat64 #else # define TCSH_STAT stat struct stat stb, *st = NULL; #endif /* convex */ #ifdef S_IFLNK # ifdef convex struct cvxstat lstb, *lst = NULL; # define TCSH_LSTAT lstat64 # else # define TCSH_LSTAT lstat struct stat lstb, *lst = NULL; # endif /* convex */ char *filnam; #endif /* S_IFLNK */ tcsh_number_t i = 0; unsigned pmask = 0xffff; int altout = 0; Char *ft = cp, *dp, *ep, *strdev, *strino, *strF, *str, valtest = '\0', *errval = STR0; char *string, string0[22 + MB_LEN_MAX + 1]; /* space for 64 bit octal */ time_t footime; struct passwd *pw; struct group *gr; while (any(FILETESTS, *++ft)) continue; if (!*ft && *(ft - 1) == 'L') --ft; if (any(FILEVALS, *ft)) { valtest = *ft++; /* * Value tests return '-1' on failure as 0 is * a legitimate value for many of them. * 'F' returns ':' for compatibility. */ errval = valtest == 'F' ? STRcolon : STRminus1; if (valtest == 'P' && *ft >= '0' && *ft <= '7') { pmask = (char) *ft - '0'; while ( *++ft >= '0' && *ft <= '7' ) pmask = 8 * pmask + ((char) *ft - '0'); } if (Strcmp(ft, STRcolon) == 0 && any("AMCUGP", valtest)) { altout = 1; ++ft; } } if (*ft || ft == cp + 1) stderror(ERR_NAME | ERR_FILEINQ); /* * Detect missing file names by checking for operator in the file name * position. However, if an operator name appears there, we must make * sure that there's no file by that name (e.g., "/") before announcing * an error. Even this check isn't quite right, since it doesn't take * globbing into account. */ if (isa(**vp, ANYOP) && TCSH_STAT(short2str(**vp), &stb)) stderror(ERR_NAME | ERR_FILENAME); dp = *(*vp)++; if (ignore & TEXP_IGNORE) return (Strsave(STRNULL)); ep = globone(dp, G_APPEND); cleanup_push(ep, xfree); ft = &cp[1]; - do + do switch (*ft) { case 'r': i = !sh_access(ep, R_OK); break; case 'w': i = !sh_access(ep, W_OK); break; case 'x': i = !sh_access(ep, X_OK); break; case 'X': /* tcsh extension, name is an executable in the path - * or a tcsh builtin command + * or a tcsh builtin command */ i = find_cmd(ep, 0); break; case 't': /* SGI extension, true when file is a tty */ i = isatty(atoi(short2str(ep))); break; default: #ifdef S_IFLNK if (tolower(*ft) == 'l') { - /* + /* * avoid convex compiler bug. */ if (!lst) { lst = &lstb; if (TCSH_LSTAT(short2str(ep), lst) == -1) { cleanup_until(ep); return (Strsave(errval)); } } if (*ft == 'L') st = lst; } - else + else #endif /* S_IFLNK */ - /* + /* * avoid convex compiler bug. */ if (!st) { st = &stb; if (TCSH_STAT(short2str(ep), st) == -1) { cleanup_until(ep); return (Strsave(errval)); } } switch (*ft) { case 'f': #ifdef S_ISREG i = S_ISREG(st->st_mode); #else /* !S_ISREG */ i = 0; #endif /* S_ISREG */ break; case 'd': #ifdef S_ISDIR i = S_ISDIR(st->st_mode); #else /* !S_ISDIR */ i = 0; #endif /* S_ISDIR */ break; case 'p': #ifdef S_ISFIFO i = S_ISFIFO(st->st_mode); #else /* !S_ISFIFO */ i = 0; #endif /* S_ISFIFO */ break; case 'm' : #ifdef S_ISOFL i = S_ISOFL(st->st_dm_mode); #else /* !S_ISOFL */ i = 0; #endif /* S_ISOFL */ break ; case 'K' : #ifdef S_ISOFL i = stb.st_dm_key; #else /* !S_ISOFL */ i = 0; #endif /* S_ISOFL */ break ; - + case 'l': #ifdef S_ISLNK i = S_ISLNK(lst->st_mode); #else /* !S_ISLNK */ i = 0; #endif /* S_ISLNK */ break; case 'S': # ifdef S_ISSOCK i = S_ISSOCK(st->st_mode); # else /* !S_ISSOCK */ i = 0; # endif /* S_ISSOCK */ break; case 'b': #ifdef S_ISBLK i = S_ISBLK(st->st_mode); #else /* !S_ISBLK */ i = 0; #endif /* S_ISBLK */ break; case 'c': #ifdef S_ISCHR i = S_ISCHR(st->st_mode); #else /* !S_ISCHR */ i = 0; #endif /* S_ISCHR */ break; case 'u': i = (S_ISUID & st->st_mode) != 0; break; case 'g': i = (S_ISGID & st->st_mode) != 0; break; case 'k': i = (S_ISVTX & st->st_mode) != 0; break; case 'z': i = st->st_size == 0; break; #ifdef convex case 'R': i = (stb.st_dmonflags & IMIGRATED) == IMIGRATED; break; #endif /* convex */ case 's': i = stb.st_size != 0; break; case 'e': i = 1; break; case 'o': i = st->st_uid == uid; break; /* * Value operators are a tcsh extension. */ case 'D': i = (tcsh_number_t) st->st_dev; break; case 'I': i = (tcsh_number_t) st->st_ino; break; - + case 'F': strdev = putn( (int) st->st_dev); strino = putn( (int) st->st_ino); strF = xmalloc((2 + Strlen(strdev) + Strlen(strino)) * sizeof(Char)); (void) Strcat(Strcat(Strcpy(strF, strdev), STRcolon), strino); xfree(strdev); xfree(strino); cleanup_until(ep); return(strF); - + case 'L': if ( *(ft + 1) ) { i = 1; break; } #ifdef S_ISLNK filnam = short2str(ep); string = areadlink(filnam); strF = string == NULL ? errval : str2short(string); xfree(string); cleanup_until(ep); return(Strsave(strF)); #else /* !S_ISLNK */ i = 0; break; #endif /* S_ISLNK */ - + case 'N': i = (tcsh_number_t) st->st_nlink; break; case 'P': string = string0 + 1; (void) xsnprintf(string, sizeof(string0) - 1, "%o", - pmask & (unsigned int) + pmask & (unsigned int) ((S_IRWXU|S_IRWXG|S_IRWXO|S_ISUID|S_ISGID) & st->st_mode)); if (altout && *string != '0') *--string = '0'; cleanup_until(ep); return(Strsave(str2short(string))); case 'U': if (altout && (pw = xgetpwuid(st->st_uid))) { cleanup_until(ep); return(Strsave(str2short(pw->pw_name))); } i = (tcsh_number_t) st->st_uid; break; case 'G': if (altout && (gr = xgetgrgid(st->st_gid))) { cleanup_until(ep); return(Strsave(str2short(gr->gr_name))); } i = (tcsh_number_t) st->st_gid; break; case 'Z': i = (tcsh_number_t) st->st_size; break; case 'A': case 'M': case 'C': footime = *ft == 'A' ? st->st_atime : *ft == 'M' ? st->st_mtime : st->st_ctime; if (altout) { strF = str2short(ctime(&footime)); if ((str = Strchr(strF, '\n')) != NULL) *str = (Char) '\0'; cleanup_until(ep); return(Strsave(strF)); } i = (tcsh_number_t) footime; break; } } while (*++ft && i); etraci("exp6 -? i", i, vp); cleanup_until(ep); return (putn(i)); } static void evalav(Char **v) { struct wordent paraml1; struct wordent *hp = ¶ml1; struct command *t; struct wordent *wdp = hp; setcopy(STRstatus, STR0, VAR_READWRITE); initlex(hp); while (*v) { struct wordent *new = xcalloc(1, sizeof *wdp); new->prev = wdp; new->next = hp; wdp->next = new; wdp = new; wdp->word = Strsave(*v++); } hp->prev = wdp; cleanup_push(¶ml1, lex_cleanup); alias(¶ml1); t = syntax(paraml1.next, ¶ml1, 0); cleanup_push(t, syntax_cleanup); if (seterr) stderror(ERR_OLD); execute(t, -1, NULL, NULL, TRUE); cleanup_until(¶ml1); } static int isa(Char *cp, int what) { if (cp == 0) return ((what & RESTOP) != 0); if (*cp == '\0') return 0; if (cp[1] == 0) { if (what & ADDOP && (*cp == '+' || *cp == '-')) return (1); if (what & MULOP && (*cp == '*' || *cp == '/' || *cp == '%')) return (1); if (what & RESTOP && (*cp == '(' || *cp == ')' || *cp == '!' || *cp == '~' || *cp == '^' || *cp == '"')) return (1); } else if (cp[2] == 0) { if (what & RESTOP) { if (cp[0] == '|' && cp[1] == '&') return (1); if (cp[0] == '<' && cp[1] == '<') return (1); if (cp[0] == '>' && cp[1] == '>') return (1); } if (what & EQOP) { if (cp[0] == '=') { if (cp[1] == '=') return (EQEQ); if (cp[1] == '~') return (EQMATCH); } else if (cp[0] == '!') { if (cp[1] == '=') return (NOTEQ); if (cp[1] == '~') return (NOTEQMATCH); } } } if (what & RELOP) { if (*cp == '<') return (LSS); if (*cp == '>') return (GTR); } return (0); } static tcsh_number_t egetn(const Char *cp) { if (*cp && *cp != '-' && !Isdigit(*cp)) stderror(ERR_NAME | ERR_EXPRESSION); return (getn(cp)); } /* Phew! */ #ifdef EDEBUG static void etraci(const char *str, tcsh_number_t i, Char ***vp) { #ifdef HAVE_LONG_LONG xprintf("%s=%lld\t", str, i); #else xprintf("%s=%ld\t", str, i); #endif blkpr(*vp); xputchar('\n'); } static void etracc(const char *str, const Char *cp, Char ***vp) { xprintf("%s=%S\t", str, cp); blkpr(*vp); xputchar('\n'); } #endif /* EDEBUG */ diff --git a/contrib/tcsh/sh.file.c b/contrib/tcsh/sh.file.c index 9b715bf56a30..eb529b949702 100644 --- a/contrib/tcsh/sh.file.c +++ b/contrib/tcsh/sh.file.c @@ -1,766 +1,766 @@ /* * sh.file.c: File completion for csh. This file is not used in tcsh. */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #if defined(FILEC) && defined(TIOCSTI) /* * Tenex style file name recognition, .. and more. * History: * Author: Ken Greer, Sept. 1975, CMU. * Finally got around to adding to the Cshell., Ken Greer, Dec. 1981. */ #define ON 1 #define OFF 0 #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #define ESC CTL_ESC('\033') typedef enum { LIST, RECOGNIZE } COMMAND; static void setup_tty (int); static void back_to_col_1 (void); static void pushback (const Char *); static int filetype (const Char *, const Char *); static void print_by_column (const Char *, Char *[], size_t); static Char *tilde (const Char *); static void retype (void); static void beep (void); static void print_recognized_stuff (const Char *); static void extract_dir_and_name (const Char *, Char **, const Char **); static Char *getitem (DIR *, int); static size_t tsearch (Char *, COMMAND, size_t); static int compare (const void *, const void *); static int recognize (Char **, Char *, size_t, size_t); static int is_prefix (const Char *, const Char *); static int is_suffix (const Char *, const Char *); static int ignored (const Char *); /* * Put this here so the binary can be patched with adb to enable file * completion by default. Filec controls completion, nobeep controls * ringing the terminal bell on incomplete expansions. */ int filec = 0; static void setup_tty(int on) { #ifdef TERMIO # ifdef POSIX struct termios tchars; # else struct termio tchars; # endif /* POSIX */ # ifdef POSIX (void) tcgetattr(SHIN, &tchars); # else (void) ioctl(SHIN, TCGETA, (ioctl_t) &tchars); # endif /* POSIX */ if (on) { tchars.c_cc[VEOL] = ESC; if (tchars.c_lflag & ICANON) # ifdef POSIX on = TCSADRAIN; # else on = TCSETA; # endif /* POSIX */ else { # ifdef POSIX on = TCSAFLUSH; # else on = TCSETAF; # endif /* POSIX */ tchars.c_lflag |= ICANON; - + } } else { tchars.c_cc[VEOL] = _POSIX_VDISABLE; # ifdef POSIX on = TCSADRAIN; # else on = TCSETA; # endif /* POSIX */ } # ifdef POSIX (void) xtcsetattr(SHIN, on, &tchars); # else (void) ioctl(SHIN, on, (ioctl_t) &tchars); # endif /* POSIX */ #else struct sgttyb sgtty; static struct tchars tchars;/* INT, QUIT, XON, XOFF, EOF, BRK */ if (on) { (void) ioctl(SHIN, TIOCGETC, (ioctl_t) & tchars); tchars.t_brkc = ESC; (void) ioctl(SHIN, TIOCSETC, (ioctl_t) & tchars); /* * This must be done after every command: if the tty gets into raw or * cbreak mode the user can't even type 'reset'. */ (void) ioctl(SHIN, TIOCGETP, (ioctl_t) & sgtty); if (sgtty.sg_flags & (RAW | CBREAK)) { sgtty.sg_flags &= ~(RAW | CBREAK); (void) ioctl(SHIN, TIOCSETP, (ioctl_t) & sgtty); } } else { tchars.t_brkc = -1; (void) ioctl(SHIN, TIOCSETC, (ioctl_t) & tchars); } #endif /* TERMIO */ } /* * Move back to beginning of current line */ static void back_to_col_1(void) { #ifdef TERMIO # ifdef POSIX struct termios tty, tty_normal; # else struct termio tty, tty_normal; # endif /* POSIX */ #else struct sgttyb tty, tty_normal; #endif /* TERMIO */ pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); #ifdef TERMIO # ifdef POSIX (void) tcgetattr(SHOUT, &tty); # else (void) ioctl(SHOUT, TCGETA, (ioctl_t) &tty_normal); # endif /* POSIX */ tty_normal = tty; tty.c_iflag &= ~INLCR; tty.c_oflag &= ~ONLCR; # ifdef POSIX (void) xtcsetattr(SHOUT, TCSANOW, &tty); # else (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty); # endif /* POSIX */ (void) xwrite(SHOUT, "\r", 1); # ifdef POSIX (void) xtcsetattr(SHOUT, TCSANOW, &tty_normal); # else (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty_normal); # endif /* POSIX */ #else (void) ioctl(SHIN, TIOCGETP, (ioctl_t) & tty); tty_normal = tty; tty.sg_flags &= ~CRMOD; (void) ioctl(SHIN, TIOCSETN, (ioctl_t) & tty); (void) xwrite(SHOUT, "\r", 1); (void) ioctl(SHIN, TIOCSETN, (ioctl_t) & tty_normal); #endif /* TERMIO */ cleanup_until(&pintr_disabled); } /* * Push string contents back into tty queue */ static void pushback(const Char *string) { const Char *p; #ifdef TERMIO # ifdef POSIX struct termios tty, tty_normal; # else struct termio tty, tty_normal; # endif /* POSIX */ #else struct sgttyb tty, tty_normal; #endif /* TERMIO */ pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); #ifdef TERMIO # ifdef POSIX (void) tcgetattr(SHOUT, &tty); # else (void) ioctl(SHOUT, TCGETA, (ioctl_t) &tty); # endif /* POSIX */ tty_normal = tty; tty.c_lflag &= ~(ECHOKE | ECHO | ECHOE | ECHOK | ECHONL | #ifndef __QNXNTO__ ECHOPRT | #endif ECHOCTL); # ifdef POSIX (void) xtcsetattr(SHOUT, TCSANOW, &tty); # else (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty); # endif /* POSIX */ for (p = string; *p != '\0'; p++) { char buf[MB_LEN_MAX]; size_t i, len; len = one_wctomb(buf, *p); for (i = 0; i < len; i++) (void) ioctl(SHOUT, TIOCSTI, (ioctl_t) &buf[i]); } # ifdef POSIX (void) xtcsetattr(SHOUT, TCSANOW, &tty_normal); # else (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty_normal); # endif /* POSIX */ #else (void) ioctl(SHOUT, TIOCGETP, (ioctl_t) & tty); tty_normal = tty; tty.sg_flags &= ~ECHO; (void) ioctl(SHOUT, TIOCSETN, (ioctl_t) & tty); for (p = string; c = *p; p++) (void) ioctl(SHOUT, TIOCSTI, (ioctl_t) & c); (void) ioctl(SHOUT, TIOCSETN, (ioctl_t) & tty_normal); #endif /* TERMIO */ cleanup_until(&pintr_disabled); } static int filetype(const Char *dir, const Char *file) { Char *path; char *spath; struct stat statb; path = Strspl(dir, file); spath = short2str(path); xfree(path); if (lstat(spath, &statb) == 0) { switch (statb.st_mode & S_IFMT) { case S_IFDIR: return ('/'); case S_IFLNK: if (stat(spath, &statb) == 0 && /* follow it out */ S_ISDIR(statb.st_mode)) return ('>'); else return ('@'); case S_IFSOCK: return ('='); default: if (statb.st_mode & 0111) return ('*'); } } return (' '); } /* * Print sorted down columns */ static void print_by_column(const Char *dir, Char *items[], size_t count) { struct winsize win; size_t i; int rows, r, c, maxwidth = 0, columns; if (ioctl(SHOUT, TIOCGWINSZ, (ioctl_t) & win) < 0 || win.ws_col == 0) win.ws_col = 80; for (i = 0; i < count; i++) maxwidth = maxwidth > (r = Strlen(items[i])) ? maxwidth : r; maxwidth += 2; /* for the file tag and space */ columns = win.ws_col / maxwidth; if (columns == 0) columns = 1; rows = (count + (columns - 1)) / columns; for (r = 0; r < rows; r++) { for (c = 0; c < columns; c++) { i = c * rows + r; if (i < count) { int w; xprintf("%S", items[i]); xputchar(dir ? filetype(dir, items[i]) : ' '); if (c < columns - 1) { /* last column? */ w = Strlen(items[i]) + 1; for (; w < maxwidth; w++) xputchar(' '); } } } xputchar('\r'); xputchar('\n'); } } /* * Expand file name with possible tilde usage * ~person/mumble * expands to * home_directory_of_person/mumble */ static Char * tilde(const Char *old) { const Char *o, *home; struct passwd *pw; if (old[0] != '~') return (Strsave(old)); old++; for (o = old; *o != '\0' && *o != '/'; o++) ; if (o == old) home = varval(STRhome); else { Char *person; person = Strnsave(old, o - old); pw = xgetpwnam(short2str(person)); xfree(person); if (pw == NULL) return (NULL); home = str2short(pw->pw_dir); } return Strspl(home, o); } /* * Cause pending line to be printed */ static void retype(void) { #ifdef TERMIO # ifdef POSIX struct termios tty; (void) tcgetattr(SHOUT, &tty); # else struct termio tty; (void) ioctl(SHOUT, TCGETA, (ioctl_t) &tty); # endif /* POSIX */ #ifndef __QNXNTO__ tty.c_lflag |= PENDIN; #endif # ifdef POSIX (void) xtcsetattr(SHOUT, TCSANOW, &tty); # else (void) ioctl(SHOUT, TCSETAW, (ioctl_t) &tty); # endif /* POSIX */ #else int pending_input = LPENDIN; (void) ioctl(SHOUT, TIOCLBIS, (ioctl_t) & pending_input); #endif /* TERMIO */ } static void beep(void) { if (adrof(STRnobeep) == 0) #ifdef IS_ASCII (void) xwrite(SHOUT, "\007", 1); #else { unsigned char beep_ch = CTL_ESC('\007'); (void) xwrite(SHOUT, &beep_ch, 1); } #endif } /* * Erase that silly ^[ and * print the recognized part of the string */ static void print_recognized_stuff(const Char *recognized_part) { /* An optimized erasing of that silly ^[ */ (void) putraw('\b'); (void) putraw('\b'); switch (Strlen(recognized_part)) { case 0: /* erase two Characters: ^[ */ (void) putraw(' '); (void) putraw(' '); (void) putraw('\b'); (void) putraw('\b'); break; case 1: /* overstrike the ^, erase the [ */ xprintf("%S", recognized_part); (void) putraw(' '); (void) putraw('\b'); break; default: /* overstrike both Characters ^[ */ xprintf("%S", recognized_part); break; } flush(); } /* * Parse full path in file into 2 parts: directory and file names * Should leave final slash (/) at end of dir. */ static void extract_dir_and_name(const Char *path, Char **dir, const Char **name) { const Char *p; p = Strrchr(path, '/'); if (p == NULL) p = path; else p++; *name = p; *dir = Strnsave(path, p - path); } static Char * getitem(DIR *dir_fd, int looking_for_lognames) { struct passwd *pw; struct dirent *dirp; if (looking_for_lognames) { #ifndef HAVE_GETPWENT return (NULL); #else if ((pw = getpwent()) == NULL) return (NULL); return (str2short(pw->pw_name)); #endif /* atp vmsposix */ } if ((dirp = readdir(dir_fd)) != NULL) return (str2short(dirp->d_name)); return (NULL); } /* * Perform a RECOGNIZE or LIST command on string "word". */ static size_t tsearch(Char *word, COMMAND command, size_t max_word_length) { DIR *dir_fd; int ignoring = TRUE, nignored = 0; int looking_for_lognames; Char *tilded_dir = NULL, *dir = NULL; Char *extended_name = NULL; const Char *name; Char *item; struct blk_buf items = BLK_BUF_INIT; size_t name_length; looking_for_lognames = (*word == '~') && (Strchr(word, '/') == NULL); if (looking_for_lognames) { #ifdef HAVE_GETPWENT (void) setpwent(); #endif name = word + 1; /* name sans ~ */ dir_fd = NULL; cleanup_push(dir, xfree); } else { extract_dir_and_name(word, &dir, &name); cleanup_push(dir, xfree); tilded_dir = tilde(dir); if (tilded_dir == NULL) goto end; cleanup_push(tilded_dir, xfree); dir_fd = opendir(*tilded_dir ? short2str(tilded_dir) : "."); if (dir_fd == NULL) goto end; } name_length = Strlen(name); cleanup_push(&extended_name, xfree_indirect); cleanup_push(&items, bb_cleanup); again: /* search for matches */ while ((item = getitem(dir_fd, looking_for_lognames)) != NULL) { if (!is_prefix(name, item)) continue; /* Don't match . files on null prefix match */ if (name_length == 0 && item[0] == '.' && !looking_for_lognames) continue; if (command == LIST) bb_append(&items, Strsave(item)); else { /* RECOGNIZE command */ if (ignoring && ignored(item)) nignored++; else if (recognize(&extended_name, item, name_length, ++items.len)) break; } } if (ignoring && items.len == 0 && nignored > 0) { ignoring = FALSE; nignored = 0; if (looking_for_lognames) { #ifdef HAVE_GETPWENT (void) setpwent(); #endif /* atp vmsposix */ } else rewinddir(dir_fd); goto again; } if (looking_for_lognames) { #ifdef HAVE_GETPWENT (void) endpwent(); #endif } else xclosedir(dir_fd); if (items.len != 0) { if (command == RECOGNIZE) { if (looking_for_lognames) copyn(word, STRtilde, 2);/*FIXBUF, sort of */ else /* put back dir part */ copyn(word, dir, max_word_length);/*FIXBUF*/ /* add extended name */ catn(word, extended_name, max_word_length);/*FIXBUF*/ } else { /* LIST */ qsort(items.vec, items.len, sizeof(items.vec[0]), compare); print_by_column(looking_for_lognames ? NULL : tilded_dir, items.vec, items.len); } } end: cleanup_until(dir); return items.len; } static int compare(const void *p, const void *q) { #if defined (WIDE_STRINGS) && !defined (UTF16_STRING) errno = 0; return (wcscoll(*(Char *const *) p, *(Char *const *) q)); #else char *p1, *q1; int res; p1 = strsave(short2str(*(Char *const *) p)); q1 = strsave(short2str(*(Char *const *) q)); # if defined(NLS) && defined(HAVE_STRCOLL) res = strcoll(p1, q1); # else res = strcmp(p1, q1); # endif /* NLS && HAVE_STRCOLL */ xfree (p1); xfree (q1); return res; #endif /* not WIDE_STRINGS */ } /* * Object: extend what user typed up to an ambiguity. * Algorithm: * On first match, copy full item (assume it'll be the only match) * On subsequent matches, shorten extended_name to the first * Character mismatch between extended_name and item. * If we shorten it back to the prefix length, stop searching. */ static int recognize(Char **extended_name, Char *item, size_t name_length, size_t numitems) { if (numitems == 1) /* 1st match */ *extended_name = Strsave(item); else { /* 2nd & subsequent matches */ Char *x, *ent; size_t len = 0; x = *extended_name; for (ent = item; *x && *x == *ent++; x++, len++); *x = '\0'; /* Shorten at 1st Char diff */ if (len == name_length) /* Ambiguous to prefix? */ return (-1); /* So stop now and save time */ } return (0); } /* * Return true if check matches initial Chars in template. * This differs from PWB imatch in that if check is null * it matches anything. */ static int is_prefix(const Char *check, const Char *template) { do if (*check == 0) return (TRUE); while (*check++ == *template++); return (FALSE); } /* * Return true if the Chars in template appear at the * end of check, I.e., are it's suffix. */ static int is_suffix(const Char *check, const Char *template) { const Char *c, *t; for (c = check; *c++;); for (t = template; *t++;); for (;;) { if (t == template) return 1; if (c == check || *--t != *--c) return 0; } } static void setup_tty_cleanup(void *dummy) { USE(dummy); setup_tty(OFF); } size_t tenex(Char *inputline, size_t inputline_size) { size_t numitems; ssize_t num_read; char tinputline[BUFSIZE + 1];/*FIXBUF*/ setup_tty(ON); cleanup_push(&num_read, setup_tty_cleanup); /* num_read is only a marker */ while ((num_read = xread(SHIN, tinputline, BUFSIZE)) > 0) {/*FIXBUF*/ static const Char delims[] = {' ', '\'', '"', '\t', ';', '&', '<', '>', '(', ')', '|', '^', '%', '\0'}; Char *str_end, *word_start, last_Char, should_retype; size_t space_left; COMMAND command; tinputline[num_read] = 0; Strcpy(inputline, str2short(tinputline));/*FIXBUF*/ num_read = Strlen(inputline); last_Char = CTL_ESC(ASC(inputline[num_read - 1]) & ASCII); if (last_Char == '\n' || (size_t)num_read == inputline_size) break; command = (last_Char == ESC) ? RECOGNIZE : LIST; if (command == LIST) xputchar('\n'); str_end = &inputline[num_read]; if (last_Char == ESC) --str_end; /* wipeout trailing cmd Char */ *str_end = '\0'; /* * Find LAST occurence of a delimiter in the inputline. The word start * is one Character past it. */ for (word_start = str_end; word_start > inputline; --word_start) if (Strchr(delims, word_start[-1])) break; space_left = inputline_size - (word_start - inputline) - 1; numitems = tsearch(word_start, command, space_left); if (command == RECOGNIZE) { /* print from str_end on */ print_recognized_stuff(str_end); if (numitems != 1) /* Beep = No match/ambiguous */ beep(); } /* * Tabs in the input line cause trouble after a pushback. tty driver * won't backspace over them because column positions are now * incorrect. This is solved by retyping over current line. */ should_retype = FALSE; if (Strchr(inputline, '\t')) { /* tab Char in input line? */ back_to_col_1(); should_retype = TRUE; } if (command == LIST) /* Always retype after a LIST */ should_retype = TRUE; if (should_retype) printprompt(0, NULL); pushback(inputline); if (should_retype) retype(); } cleanup_until(&num_read); return (num_read); } static int ignored(const Char *item) { struct varent *vp; Char **cp; if ((vp = adrof(STRfignore)) == NULL || (cp = vp->vec) == NULL) return (FALSE); for (; *cp != NULL; cp++) if (is_suffix(item, *cp)) return (TRUE); return (FALSE); } #endif /* FILEC && TIOCSTI */ diff --git a/contrib/tcsh/sh.func.c b/contrib/tcsh/sh.func.c index c978ffe844fe..ede623f2ff10 100644 --- a/contrib/tcsh/sh.func.c +++ b/contrib/tcsh/sh.func.c @@ -1,2746 +1,2746 @@ /* * sh.func.c: csh builtin functions */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include "tw.h" #include "tc.h" #ifdef WINNT_NATIVE #include "nt.const.h" #endif /* WINNT_NATIVE */ #if defined (NLS_CATALOGS) && defined(HAVE_ICONV) static iconv_t catgets_iconv; /* Or (iconv_t)-1 */ #endif /* * C shell */ extern int MapsAreInited; extern int NLSMapsAreInited; extern int GotTermCaps; static int zlast = -1; static void islogin (void); static void preread (void); static void doagain (void); static const char *isrchx (int); static void search (int, int, Char *); static int getword (struct Strbuf *); static struct wordent *histgetword (struct wordent *); static void toend (void); static void xecho (int, Char **); static int islocale_var (Char *); static void wpfree (struct whyle *); const struct biltins * isbfunc(struct command *t) { Char *cp = t->t_dcom[0]; const struct biltins *bp, *bp1, *bp2; static struct biltins label = {"", dozip, 0, 0}; static struct biltins foregnd = {"%job", dofg1, 0, 0}; static struct biltins backgnd = {"%job &", dobg1, 0, 0}; /* * We never match a builtin that has quoted the first - * character; this has been the traditional way to escape + * character; this has been the traditional way to escape * builtin commands. */ if (*cp & QUOTE) return NULL; if (*cp != ':' && lastchr(cp) == ':') { label.bname = short2str(cp); return (&label); } if (*cp == '%') { if (t->t_dflg & F_AMPERSAND) { t->t_dflg &= ~F_AMPERSAND; backgnd.bname = short2str(cp); return (&backgnd); } foregnd.bname = short2str(cp); return (&foregnd); } #ifdef WARP /* * This is a perhaps kludgy way to determine if the warp builtin is to be * acknowledged or not. If checkwarp() fails, then we are to assume that * the warp command is invalid, and carry on as we would handle any other * non-builtin command. -- JDK 2/4/88 */ if (eq(STRwarp, cp) && !checkwarp()) { return (0); /* this builtin disabled */ } #endif /* WARP */ /* * Binary search Bp1 is the beginning of the current search range. Bp2 is * one past the end. */ for (bp1 = bfunc, bp2 = bfunc + nbfunc; bp1 < bp2;) { int i; bp = bp1 + ((bp2 - bp1) >> 1); if ((i = ((char) *cp) - *bp->bname) == 0 && (i = StrQcmp(cp, str2short(bp->bname))) == 0) return bp; if (i < 0) bp2 = bp; else bp1 = bp + 1; } #ifdef WINNT_NATIVE return nt_check_additional_builtins(cp); #endif /*WINNT_NATIVE*/ return (0); } void func(struct command *t, const struct biltins *bp) { int i; xechoit(t->t_dcom); setname(bp->bname); i = blklen(t->t_dcom) - 1; if (i < bp->minargs) stderror(ERR_NAME | ERR_TOOFEW); if (i > bp->maxargs) stderror(ERR_NAME | ERR_TOOMANY); (*bp->bfunct) (t->t_dcom, t); } /*ARGSUSED*/ void doonintr(Char **v, struct command *c) { Char *cp; Char *vv = v[1]; USE(c); if (parintr.sa_handler == SIG_IGN) return; if (setintr && intty) stderror(ERR_NAME | ERR_TERMINAL); cp = gointr; gointr = 0; xfree(cp); if (vv == 0) { if (setintr) sigset_interrupting(SIGINT, queue_pintr); else (void) signal(SIGINT, SIG_DFL); gointr = 0; } else if (eq((vv = strip(vv)), STRminus)) { (void) signal(SIGINT, SIG_IGN); gointr = Strsave(STRminus); } else { gointr = Strsave(vv); sigset_interrupting(SIGINT, queue_pintr); } } /*ARGSUSED*/ void donohup(Char **v, struct command *c) { USE(c); USE(v); if (intty) stderror(ERR_NAME | ERR_TERMINAL); if (setintr == 0) { (void) signal(SIGHUP, SIG_IGN); phup_disabled = 1; #ifdef CC submit(getpid()); #endif /* CC */ } } /*ARGSUSED*/ void dohup(Char **v, struct command *c) { USE(c); USE(v); if (intty) stderror(ERR_NAME | ERR_TERMINAL); if (setintr == 0) sigset_interrupting(SIGHUP, SIG_DFL); } /*ARGSUSED*/ void dozip(Char **v, struct command *c) { USE(c); USE(v); } /*ARGSUSED*/ void dofiletest(Char **v, struct command *c) { Char **globbed, **fileptr, *ftest, *res; USE(c); if (*(ftest = *++v) != '-') stderror(ERR_NAME | ERR_FILEINQ); ++v; v = glob_all_or_error(v); globbed = v; cleanup_push(globbed, blk_cleanup); while (*(fileptr = v++) != NULL) { res = filetest(ftest, &fileptr, 0); cleanup_push(res, xfree); xprintf("%S", res); cleanup_until(res); if (*v) xprintf(" "); } xprintf("\n"); cleanup_until(globbed); } void prvars(void) { plist(&shvhed, VAR_ALL); } /*ARGSUSED*/ void doalias(Char **v, struct command *c) { struct varent *vp; Char *p; USE(c); v++; p = *v++; if (p == 0) plist(&aliases, VAR_ALL); else if (*v == 0) { vp = adrof1(strip(p), &aliases); if (vp && vp->vec) blkpr(vp->vec), xputchar('\n'); } else { if (eq(p, STRalias) || eq(p, STRunalias)) { setname(short2str(p)); stderror(ERR_NAME | ERR_DANGER); } set1(strip(p), saveblk(v), &aliases, VAR_READWRITE); tw_cmd_free(); } } /*ARGSUSED*/ void unalias(Char **v, struct command *c) { USE(c); unset1(v, &aliases); tw_cmd_free(); } /*ARGSUSED*/ void dologout(Char **v, struct command *c) { USE(c); USE(v); islogin(); goodbye(NULL, NULL); } /*ARGSUSED*/ void dologin(Char **v, struct command *c) { #ifdef WINNT_NATIVE USE(c); USE(v); #else /* !WINNT_NATIVE */ char **p = short2blk(v); USE(c); cleanup_push((Char **)p, blk_cleanup); islogin(); rechist(NULL, adrof(STRsavehist) != NULL); sigaction(SIGTERM, &parterm, NULL); (void) execv(_PATH_BIN_LOGIN, p); (void) execv(_PATH_USRBIN_LOGIN, p); cleanup_until((Char **)p); untty(); xexit(1); #endif /* !WINNT_NATIVE */ } #ifdef NEWGRP /*ARGSUSED*/ void donewgrp(Char **v, struct command *c) { char **p; if (chkstop == 0 && setintr) panystop(0); sigaction(SIGTERM, &parterm, NULL); p = short2blk(v); /* * From Beto Appleton (beto@aixwiz.austin.ibm.com) * Newgrp can take 2 arguments... */ (void) execv(_PATH_BIN_NEWGRP, p); (void) execv(_PATH_USRBIN_NEWGRP, p); blkfree((Char **) p); untty(); xexit(1); } #endif /* NEWGRP */ static void islogin(void) { if (chkstop == 0 && setintr) panystop(0); if (loginsh) return; stderror(ERR_NOTLOGIN); } void doif(Char **v, struct command *kp) { int i; Char **vv; v++; i = noexec ? 1 : expr(&v); vv = v; if (*vv == NULL) stderror(ERR_NAME | ERR_EMPTYIF); if (eq(*vv, STRthen)) { if (*++vv) stderror(ERR_NAME | ERR_IMPRTHEN); setname(short2str(STRthen)); /* * If expression was zero, then scan to else , otherwise just fall into * following code. */ if (!i) search(TC_IF, 0, NULL); return; } /* * Simple command attached to this if. Left shift the node in this tree, * munging it so we can reexecute it. */ if (i) { lshift(kp->t_dcom, vv - kp->t_dcom); reexecute(kp); donefds(); } } /* * Reexecute a command, being careful not * to redo i/o redirection, which is already set up. */ void reexecute(struct command *kp) { kp->t_dflg &= F_SAVE; kp->t_dflg |= F_REPEAT; /* * If tty is still ours to arbitrate, arbitrate it; otherwise dont even set * pgrp's as the jobs would then have no way to get the tty (we can't give * it to them, and our parent wouldn't know their pgrp, etc. */ execute(kp, (tpgrp > 0 ? tpgrp : -1), NULL, NULL, TRUE); } /*ARGSUSED*/ void doelse (Char **v, struct command *c) { USE(c); USE(v); if (!noexec) search(TC_ELSE, 0, NULL); } /*ARGSUSED*/ void dogoto(Char **v, struct command *c) { Char *lp; USE(c); lp = globone(v[1], G_ERROR); cleanup_push(lp, xfree); if (!noexec) gotolab(lp); cleanup_until(lp); } void gotolab(Char *lab) { struct whyle *wp; /* * While we still can, locate any unknown ends of existing loops. This * obscure code is the WORST result of the fact that we don't really parse. */ zlast = TC_GOTO; for (wp = whyles; wp; wp = wp->w_next) if (wp->w_end.type == TCSH_F_SEEK && wp->w_end.f_seek == 0) { search(TC_BREAK, 0, NULL); btell(&wp->w_end); } else { bseek(&wp->w_end); } search(TC_GOTO, 0, lab); /* * Eliminate loops which were exited. */ wfree(); } /*ARGSUSED*/ void doswitch(Char **v, struct command *c) { Char *cp, *lp; USE(c); v++; if (!*v || *(*v++) != '(') stderror(ERR_SYNTAX); cp = **v == ')' ? STRNULL : *v++; if (*(*v++) != ')') v--; if (*v) stderror(ERR_SYNTAX); lp = globone(cp, G_ERROR); cleanup_push(lp, xfree); if (!noexec) search(TC_SWITCH, 0, lp); cleanup_until(lp); } /*ARGSUSED*/ void dobreak(Char **v, struct command *c) { USE(v); USE(c); if (whyles == NULL) stderror(ERR_NAME | ERR_NOTWHILE); if (!noexec) toend(); } /*ARGSUSED*/ void doexit(Char **v, struct command *c) { USE(c); if (chkstop == 0 && (intty || intact) && evalvec == 0) panystop(0); /* * Don't DEMAND parentheses here either. */ v++; if (*v) { setv(STRstatus, putn(expr(&v)), VAR_READWRITE); if (*v) stderror(ERR_NAME | ERR_EXPRESSION); } btoeof(); #if 0 if (intty) #endif /* Always close, why only on ttys? */ xclose(SHIN); } /*ARGSUSED*/ void doforeach(Char **v, struct command *c) { Char *cp, *sp; struct whyle *nwp; int gflag; USE(c); v++; cp = sp = strip(*v); if (!letter(*cp)) stderror(ERR_NAME | ERR_VARBEGIN); do { cp++; } while (alnum(*cp)); if (*cp != '\0') stderror(ERR_NAME | ERR_VARALNUM); cp = *v++; if (v[0][0] != '(' || v[blklen(v) - 1][0] != ')') stderror(ERR_NAME | ERR_NOPAREN); v++; gflag = tglob(v); if (gflag) { v = globall(v, gflag); if (v == 0 && !noexec) stderror(ERR_NAME | ERR_NOMATCH); } else { v = saveblk(v); trim(v); } nwp = xcalloc(1, sizeof *nwp); nwp->w_fe = nwp->w_fe0 = v; btell(&nwp->w_start); nwp->w_fename = Strsave(cp); nwp->w_next = whyles; nwp->w_end.type = TCSH_F_SEEK; whyles = nwp; /* * Pre-read the loop so as to be more comprehensible to a terminal user. */ zlast = TC_FOREACH; if (intty) preread(); if (!noexec) doagain(); } /*ARGSUSED*/ void dowhile(Char **v, struct command *c) { int status; - int again = whyles != 0 && + int again = whyles != 0 && SEEKEQ(&whyles->w_start, &lineloc) && whyles->w_fename == 0; USE(c); v++; /* * Implement prereading here also, taking care not to evaluate the * expression before the loop has been read up from a terminal. */ if (noexec) status = 0; else if (intty && !again) status = !exp0(&v, 1); else status = !expr(&v); if (*v && !noexec) stderror(ERR_NAME | ERR_EXPRESSION); if (!again) { struct whyle *nwp = xcalloc(1, sizeof(*nwp)); nwp->w_start = lineloc; nwp->w_end.type = TCSH_F_SEEK; nwp->w_end.f_seek = 0; nwp->w_end.a_seek = 0; nwp->w_next = whyles; whyles = nwp; zlast = TC_WHILE; if (intty) { /* * The tty preread */ preread(); doagain(); return; } } if (status) /* We ain't gonna loop no more, no more! */ toend(); } static void preread(void) { int old_pintr_disabled; whyles->w_end.type = TCSH_I_SEEK; if (setintr) pintr_push_enable(&old_pintr_disabled); search(TC_BREAK, 0, NULL); /* read the expression in */ if (setintr) cleanup_until(&old_pintr_disabled); btell(&whyles->w_end); } /*ARGSUSED*/ void doend(Char **v, struct command *c) { USE(v); USE(c); if (!whyles) stderror(ERR_NAME | ERR_NOTWHILE); btell(&whyles->w_end); if (!noexec) doagain(); } /*ARGSUSED*/ void docontin(Char **v, struct command *c) { USE(v); USE(c); if (!whyles) stderror(ERR_NAME | ERR_NOTWHILE); if (!noexec) doagain(); } static void doagain(void) { /* Repeating a while is simple */ if (whyles->w_fename == 0) { bseek(&whyles->w_start); return; } /* * The foreach variable list actually has a spurious word ")" at the end of * the w_fe list. Thus we are at the of the list if one word beyond this * is 0. */ if (!whyles->w_fe[1]) { dobreak(NULL, NULL); return; } setv(whyles->w_fename, quote(Strsave(*whyles->w_fe++)), VAR_READWRITE); bseek(&whyles->w_start); } void dorepeat(Char **v, struct command *kp) { int i = 1; do { i *= getn(v[1]); lshift(v, 2); } while (v[0] != NULL && Strcmp(v[0], STRrepeat) == 0); if (noexec) i = 1; if (setintr) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); } while (i > 0) { if (setintr && pintr_disabled == 1) { cleanup_until(&pintr_disabled); pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); } reexecute(kp); --i; } if (setintr && pintr_disabled == 1) cleanup_until(&pintr_disabled); donefds(); } /*ARGSUSED*/ void doswbrk(Char **v, struct command *c) { USE(v); USE(c); if (!noexec) search(TC_BRKSW, 0, NULL); } int srchx(Char *cp) { struct srch *sp, *sp1, *sp2; int i; /* * Ignore keywords inside heredocs */ if (inheredoc) return -1; /* * Binary search Sp1 is the beginning of the current search range. Sp2 is * one past the end. */ for (sp1 = srchn, sp2 = srchn + nsrchn; sp1 < sp2;) { sp = sp1 + ((sp2 - sp1) >> 1); if ((i = *cp - *sp->s_name) == 0 && (i = Strcmp(cp, str2short(sp->s_name))) == 0) return sp->s_value; if (i < 0) sp2 = sp; else sp1 = sp + 1; } return (-1); } static const char * isrchx(int n) { struct srch *sp, *sp2; for (sp = srchn, sp2 = srchn + nsrchn; sp < sp2; sp++) if (sp->s_value == n) return (sp->s_name); return (""); } static int Stype; static Char *Sgoal; static void search(int type, int level, Char *goal) { struct Strbuf word = Strbuf_INIT; Char *cp; struct whyle *wp; int wlevel = 0; struct wordent *histent = NULL, *ohistent = NULL; Stype = type; Sgoal = goal; if (type == TC_GOTO) { struct Ain a; a.type = TCSH_F_SEEK; a.f_seek = 0; a.a_seek = 0; bseek(&a); } cleanup_push(&word, Strbuf_cleanup); do { - + if (intty) { histent = xmalloc(sizeof(*histent)); ohistent = xmalloc(sizeof(*histent)); ohistent->word = STRNULL; ohistent->next = histent; histent->prev = ohistent; } if (intty && fseekp == feobp && aret == TCSH_F_SEEK) printprompt(1, isrchx(type == TC_BREAK ? zlast : type)); /* xprintf("? "), flush(); */ (void) getword(&word); Strbuf_terminate(&word); if (intty && Strlen(word.s) > 0) { histent->word = Strsave(word.s); histent->next = xmalloc(sizeof(*histent)); histent->next->prev = histent; histent = histent->next; } switch (srchx(word.s)) { case TC_ELSE: if (level == 0 && type == TC_IF) goto end; break; case TC_IF: while (getword(&word)) { if (intty) { histent->word = Strsave(word.s); histent->next = xmalloc(sizeof(*histent)); histent->next->prev = histent; histent = histent->next; } continue; } - + if ((type == TC_IF || type == TC_ELSE) && eq(word.s, STRthen)) level++; break; case TC_ENDIF: if (type == TC_IF || type == TC_ELSE) level--; break; case TC_FOREACH: case TC_WHILE: wlevel++; if (type == TC_BREAK) level++; break; case TC_END: if (type == TC_BRKSW) { if (wlevel == 0) { wp = whyles; if (wp) { whyles = wp->w_next; wpfree(wp); } } } if (type == TC_BREAK) level--; wlevel--; break; case TC_SWITCH: if (type == TC_SWITCH || type == TC_BRKSW) level++; break; case TC_ENDSW: if (type == TC_SWITCH || type == TC_BRKSW) level--; break; case TC_LABEL: if (type == TC_GOTO && getword(&word) && eq(word.s, goal)) level = -1; break; default: if (type != TC_GOTO && (type != TC_SWITCH || level != 0)) break; if (word.len == 0 || word.s[word.len - 1] != ':') break; word.s[--word.len] = 0; if ((type == TC_GOTO && eq(word.s, goal)) || (type == TC_SWITCH && eq(word.s, STRdefault))) level = -1; break; case TC_CASE: if (type != TC_SWITCH || level != 0) break; (void) getword(&word); if (word.len != 0 && word.s[word.len - 1] == ':') word.s[--word.len] = 0; cp = strip(Dfix1(word.s)); cleanup_push(cp, xfree); if (Gmatch(goal, cp)) level = -1; cleanup_until(cp); break; case TC_DEFAULT: if (type == TC_SWITCH && level == 0) level = -1; break; } if (intty) { ohistent->prev = histgetword(histent); ohistent->prev->next = ohistent; savehist(ohistent, 0); freelex(ohistent); xfree(ohistent); - } else + } else (void) getword(NULL); } while (level >= 0); end: cleanup_until(&word); } static struct wordent * -histgetword(struct wordent *histent) +histgetword(struct wordent *histent) { int first; eChar c, d; int e; struct Strbuf *tmp; tmp = xmalloc(sizeof(*tmp)); tmp->size = 0; tmp->s = NULL; c = readc(1); d = 0; e = 0; for (;;) { tmp->len = 0; Strbuf_terminate (tmp); while (c == ' ' || c == '\t') c = readc(1); if (c == '#') do c = readc(1); while (c != CHAR_ERR && c != '\n'); if (c == CHAR_ERR) goto past; - if (c == '\n') + if (c == '\n') goto nl; unreadc(c); first = 1; do { e = (c == '\\'); c = readc(1); if (c == '\\' && !e) { if ((c = readc(1)) == '\n') { e = 1; c = ' '; } else { unreadc(c); c = '\\'; } } if ((c == '\'' || c == '"') && !e) { if (d == 0) d = c; else if (d == c) d = 0; } if (c == CHAR_ERR) goto past; - + Strbuf_append1(tmp, (Char) c); - + if (!first && !d && c == '(' && !e) { break; } first = 0; } while (d || e || (c != ' ' && c != '\t' && c != '\n')); tmp->len--; if (tmp->len) { Strbuf_terminate(tmp); histent->word = Strsave(tmp->s); histent->next = xmalloc(sizeof (*histent)); histent->next->prev = histent; histent = histent->next; } if (c == '\n') { nl: tmp->len = 0; Strbuf_append1(tmp, (Char) c); Strbuf_terminate(tmp); histent->word = Strsave(tmp->s); return histent; } } - + past: switch (Stype) { case TC_IF: stderror(ERR_NAME | ERR_NOTFOUND, "then/endif"); break; case TC_ELSE: stderror(ERR_NAME | ERR_NOTFOUND, "endif"); break; case TC_BRKSW: case TC_SWITCH: stderror(ERR_NAME | ERR_NOTFOUND, "endsw"); break; case TC_BREAK: stderror(ERR_NAME | ERR_NOTFOUND, "end"); break; case TC_GOTO: setname(short2str(Sgoal)); stderror(ERR_NAME | ERR_NOTFOUND, "label"); break; default: break; } /* NOTREACHED */ return NULL; } static int getword(struct Strbuf *wp) { int found = 0, first; eChar c, d; if (wp) wp->len = 0; c = readc(1); d = 0; do { while (c == ' ' || c == '\t') c = readc(1); if (c == '#') do c = readc(1); while (c != CHAR_ERR && c != '\n'); if (c == CHAR_ERR) goto past; if (c == '\n') { if (wp) break; return (0); } unreadc(c); found = 1; first = 1; do { c = readc(1); if (c == '\\' && (c = readc(1)) == '\n') c = ' '; if (c == '\'' || c == '"') { if (d == 0) d = c; else if (d == c) d = 0; } if (c == CHAR_ERR) goto past; if (wp) Strbuf_append1(wp, (Char) c); if (!d && c == ')') { if (!first && wp) { goto past_word_end; } else { if (wp) { wp->len = 1; Strbuf_terminate(wp); } return found; } } if (!first && !d && c == '(') { if (wp) goto past_word_end; - else + else break; } first = 0; } while ((d || (c != ' ' && c != '\t')) && c != '\n'); } while (wp == 0); past_word_end: unreadc(c); if (found) { wp->len--; Strbuf_terminate(wp); } return (found); past: switch (Stype) { case TC_IF: stderror(ERR_NAME | ERR_NOTFOUND, "then/endif"); break; case TC_ELSE: stderror(ERR_NAME | ERR_NOTFOUND, "endif"); break; case TC_BRKSW: case TC_SWITCH: stderror(ERR_NAME | ERR_NOTFOUND, "endsw"); break; case TC_BREAK: stderror(ERR_NAME | ERR_NOTFOUND, "end"); break; case TC_GOTO: setname(short2str(Sgoal)); stderror(ERR_NAME | ERR_NOTFOUND, "label"); break; default: break; } /* NOTREACHED */ return (0); } static void toend(void) { if (whyles->w_end.type == TCSH_F_SEEK && whyles->w_end.f_seek == 0) { search(TC_BREAK, 0, NULL); btell(&whyles->w_end); whyles->w_end.f_seek--; } else { bseek(&whyles->w_end); } wfree(); } static void wpfree(struct whyle *wp) { if (wp->w_fe0) blkfree(wp->w_fe0); xfree(wp->w_fename); xfree(wp); } void wfree(void) { struct Ain o; struct whyle *nwp; #ifdef lint nwp = NULL; /* sun lint is dumb! */ #endif #ifdef FDEBUG static const char foo[] = "IAFE"; #endif /* FDEBUG */ btell(&o); #ifdef FDEBUG xprintf("o->type %c o->a_seek %d o->f_seek %d\n", foo[o.type + 1], o.a_seek, o.f_seek); #endif /* FDEBUG */ for (; whyles; whyles = nwp) { struct whyle *wp = whyles; nwp = wp->w_next; #ifdef FDEBUG xprintf("start->type %c start->a_seek %d start->f_seek %d\n", - foo[wp->w_start.type+1], + foo[wp->w_start.type+1], wp->w_start.a_seek, wp->w_start.f_seek); xprintf("end->type %c end->a_seek %d end->f_seek %d\n", foo[wp->w_end.type + 1], wp->w_end.a_seek, wp->w_end.f_seek); #endif /* FDEBUG */ /* * XXX: We free loops that have different seek types. */ if (wp->w_end.type != TCSH_I_SEEK && wp->w_start.type == wp->w_end.type && wp->w_start.type == o.type) { if (wp->w_end.type == TCSH_F_SEEK) { - if (o.f_seek >= wp->w_start.f_seek && + if (o.f_seek >= wp->w_start.f_seek && (wp->w_end.f_seek == 0 || o.f_seek < wp->w_end.f_seek)) break; } else { - if (o.a_seek >= wp->w_start.a_seek && + if (o.a_seek >= wp->w_start.a_seek && (wp->w_end.a_seek == 0 || o.a_seek < wp->w_end.a_seek)) break; } } wpfree(wp); } } /*ARGSUSED*/ void doecho(Char **v, struct command *c) { USE(c); xecho(' ', v); } /*ARGSUSED*/ void doglob(Char **v, struct command *c) { USE(c); xecho(0, v); flush(); } static void xecho(int sep, Char **v) { Char *cp, **globbed = NULL; int nonl = 0; int echo_style = ECHO_STYLE; struct varent *vp; if ((vp = adrof(STRecho_style)) != NULL && vp->vec != NULL && vp->vec[0] != NULL) { if (Strcmp(vp->vec[0], STRbsd) == 0) echo_style = BSD_ECHO; else if (Strcmp(vp->vec[0], STRsysv) == 0) echo_style = SYSV_ECHO; else if (Strcmp(vp->vec[0], STRboth) == 0) echo_style = BOTH_ECHO; else if (Strcmp(vp->vec[0], STRnone) == 0) echo_style = NONE_ECHO; } v++; if (*v == 0) goto done; if (setintr) { int old_pintr_disabled; pintr_push_enable(&old_pintr_disabled); v = glob_all_or_error(v); cleanup_until(&old_pintr_disabled); } else { v = glob_all_or_error(v); } globbed = v; if (globbed != NULL) cleanup_push(globbed, blk_cleanup); if ((echo_style & BSD_ECHO) != 0 && sep == ' ' && *v && eq(*v, STRmn)) nonl++, v++; while ((cp = *v++) != 0) { Char c; if (setintr) { int old_pintr_disabled; pintr_push_enable(&old_pintr_disabled); cleanup_until(&old_pintr_disabled); } while ((c = *cp++) != 0) { if ((echo_style & SYSV_ECHO) != 0 && c == '\\') { switch (c = *cp++) { case 'a': c = '\a'; break; case 'b': c = '\b'; break; case 'c': nonl = 1; goto done; case 'e': #if 0 /* Windows does not understand \e */ c = '\e'; #else c = CTL_ESC('\033'); #endif break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = '\v'; break; case '\\': c = '\\'; break; case '0': c = 0; if (*cp >= '0' && *cp < '8') c = c * 8 + *cp++ - '0'; if (*cp >= '0' && *cp < '8') c = c * 8 + *cp++ - '0'; if (*cp >= '0' && *cp < '8') c = c * 8 + *cp++ - '0'; break; case '\0': c = '\\'; cp--; break; default: xputchar('\\' | QUOTE); break; } } xputwchar(c | QUOTE); } if (*v) xputchar(sep | QUOTE); } done: if (sep && nonl == 0) xputchar('\n'); else flush(); if (globbed != NULL) cleanup_until(globbed); } /* check whether an environment variable should invoke 'set_locale()' */ static int islocale_var(Char *var) { static Char *locale_vars[] = { STRLANG, STRLC_ALL, STRLC_CTYPE, STRLC_NUMERIC, STRLC_TIME, STRLC_COLLATE, STRLC_MESSAGES, STRLC_MONETARY, 0 }; Char **v; for (v = locale_vars; *v; ++v) if (eq(var, *v)) return 1; return 0; } static void xlate_cr_cleanup(void *dummy) { USE(dummy); xlate_cr = 0; } /*ARGSUSED*/ void -doprintenv(Char **v, struct command *c) +doprintenv(Char **v, struct command *c) { Char *e; USE(c); v++; if (*v == 0) { Char **ep; xlate_cr = 1; cleanup_push(&xlate_cr, xlate_cr_cleanup); for (ep = STR_environ; *ep; ep++) { if (setintr) { int old_pintr_disabled; pintr_push_enable(&old_pintr_disabled); cleanup_until(&old_pintr_disabled); } xprintf("%S\n", *ep); } cleanup_until(&xlate_cr); } else if ((e = tgetenv(*v)) != NULL) { int old_output_raw; old_output_raw = output_raw; output_raw = 1; cleanup_push(&old_output_raw, output_raw_restore); xprintf("%S\n", e); cleanup_until(&old_output_raw); } else setcopy(STRstatus, STR1, VAR_READWRITE); } /* from "Karl Berry." -- for NeXT things (and anything else with a modern compiler) */ /*ARGSUSED*/ void dosetenv(Char **v, struct command *c) { Char *vp, *lp; USE(c); if (*++v == 0) { doprintenv(--v, 0); return; } vp = *v++; lp = vp; if (!letter(*lp)) stderror(ERR_NAME | ERR_VARBEGIN); do { lp++; } while (alnum(*lp) || *lp == '.'); if (*lp != '\0') stderror(ERR_NAME | ERR_VARALNUM); if ((lp = *v++) == 0) lp = STRNULL; lp = globone(lp, G_APPEND); cleanup_push(lp, xfree); tsetenv(vp, lp); if (eq(vp, STRKPATH)) { importpath(lp); dohash(NULL, NULL); cleanup_until(lp); return; } #ifdef apollo if (eq(vp, STRSYSTYPE)) { dohash(NULL, NULL); cleanup_until(lp); return; } #endif /* apollo */ /* dspkanji/dspmbyte autosetting */ /* PATCH IDEA FROM Issei.Suzuki VERY THANKS */ #if defined(DSPMBYTE) if (eq(vp, STRLANG) && !adrof(CHECK_MBYTEVAR)) { autoset_dspmbyte(lp); } #endif if (islocale_var(vp)) { #ifdef NLS int k; # ifdef SETLOCALEBUG dont_free = 1; # endif /* SETLOCALEBUG */ (void) setlocale(LC_ALL, ""); # ifdef LC_COLLATE (void) setlocale(LC_COLLATE, ""); # endif # ifdef LC_CTYPE (void) setlocale(LC_CTYPE, ""); /* for iscntrl */ # endif /* LC_CTYPE */ # if defined(AUTOSET_KANJI) autoset_kanji(); # endif /* AUTOSET_KANJI */ # ifdef NLS_CATALOGS # ifdef LC_MESSAGES (void) setlocale(LC_MESSAGES, ""); # endif /* LC_MESSAGES */ nlsclose(); nlsinit(); # endif /* NLS_CATALOGS */ # ifdef SETLOCALEBUG dont_free = 0; # endif /* SETLOCALEBUG */ # ifdef STRCOLLBUG fix_strcoll_bug(); # endif /* STRCOLLBUG */ tw_cmd_free(); /* since the collation sequence has changed */ for (k = 0200; k <= 0377 && !Isprint(CTL_ESC(k)); k++) continue; AsciiOnly = MB_CUR_MAX == 1 && k > 0377; #else /* !NLS */ AsciiOnly = 0; #endif /* NLS */ NLSMapsAreInited = 0; ed_Init(); if (MapsAreInited && !NLSMapsAreInited) ed_InitNLSMaps(); cleanup_until(lp); return; } #ifdef NLS_CATALOGS if (eq(vp, STRNLSPATH)) { nlsclose(); nlsinit(); } #endif if (eq(vp, STRNOREBIND)) { NoNLSRebind = 1; MapsAreInited = 0; NLSMapsAreInited = 0; ed_InitMaps(); cleanup_until(lp); return; } #ifdef WINNT_NATIVE if (eq(vp, STRtcshlang)) { nlsinit(); cleanup_until(lp); return; } #endif /* WINNT_NATIVE */ if (eq(vp, STRKTERM)) { char *t; setv(STRterm, quote(lp), VAR_READWRITE); /* lp memory used here */ cleanup_ignore(lp); cleanup_until(lp); t = short2str(lp); if (noediting && strcmp(t, "unknown") != 0 && strcmp(t,"dumb") != 0) { editing = 1; noediting = 0; setNS(STRedit); } GotTermCaps = 0; ed_Init(); return; } if (eq(vp, STRKHOME)) { Char *canon; /* * convert to canonical pathname (possibly resolving symlinks) */ cleanup_ignore(lp); canon = dcanon(lp, lp); cleanup_push(canon, xfree); setv(STRhome, quote(canon), VAR_READWRITE); /* lp memory used here */ cleanup_ignore(canon); cleanup_until(canon); /* fix directory stack for new tilde home */ dtilde(); return; } if (eq(vp, STRKSHLVL)) { setv(STRshlvl, quote(lp), VAR_READWRITE); /* lp memory used here */ cleanup_ignore(lp); cleanup_until(lp); return; } if (eq(vp, STRKUSER)) { setv(STRuser, quote(lp), VAR_READWRITE); /* lp memory used here */ cleanup_ignore(lp); cleanup_until(lp); return; } if (eq(vp, STRKGROUP)) { setv(STRgroup, quote(lp), VAR_READWRITE); /* lp memory used here */ cleanup_ignore(lp); cleanup_until(lp); return; } #ifdef COLOR_LS_F if (eq(vp, STRLS_COLORS)) { parseLS_COLORS(lp); cleanup_until(lp); return; } if (eq(vp, STRLSCOLORS)) { parseLSCOLORS(lp); cleanup_until(lp); return; } #endif /* COLOR_LS_F */ #ifdef SIG_WINDOW /* * Load/Update $LINES $COLUMNS */ if ((eq(lp, STRNULL) && (eq(vp, STRLINES) || eq(vp, STRCOLUMNS))) || eq(vp, STRTERMCAP)) { cleanup_until(lp); check_window_size(1); return; } /* * Change the size to the one directed by $LINES and $COLUMNS */ if (eq(vp, STRLINES) || eq(vp, STRCOLUMNS)) { #if 0 GotTermCaps = 0; #endif cleanup_until(lp); ed_Init(); return; } #endif /* SIG_WINDOW */ cleanup_until(lp); } /*ARGSUSED*/ void dounsetenv(Char **v, struct command *c) { Char **ep, *p, *n, *name; int i, maxi; USE(c); /* * Find the longest environment variable */ for (maxi = 0, ep = STR_environ; *ep; ep++) { for (i = 0, p = *ep; *p && *p != '='; p++, i++) continue; if (i > maxi) maxi = i; } name = xmalloc((maxi + 1) * sizeof(Char)); cleanup_push(name, xfree); - while (++v && *v) + while (++v && *v) for (maxi = 1; maxi;) for (maxi = 0, ep = STR_environ; *ep; ep++) { for (n = name, p = *ep; *p && *p != '='; *n++ = *p++) continue; *n = '\0'; if (!Gmatch(name, *v)) continue; maxi = 1; /* Unset the name. This wasn't being done until * later but most of the stuff following won't * work (particularly the setlocale() and getenv() * stuff) as intended until the name is actually * removed. (sg) */ Unsetenv(name); if (eq(name, STRNOREBIND)) { NoNLSRebind = 0; MapsAreInited = 0; NLSMapsAreInited = 0; ed_InitMaps(); } #ifdef apollo else if (eq(name, STRSYSTYPE)) dohash(NULL, NULL); #endif /* apollo */ else if (islocale_var(name)) { #ifdef NLS int k; # ifdef SETLOCALEBUG dont_free = 1; # endif /* SETLOCALEBUG */ (void) setlocale(LC_ALL, ""); # ifdef LC_COLLATE (void) setlocale(LC_COLLATE, ""); # endif # ifdef LC_CTYPE (void) setlocale(LC_CTYPE, ""); /* for iscntrl */ # endif /* LC_CTYPE */ # ifdef NLS_CATALOGS # ifdef LC_MESSAGES (void) setlocale(LC_MESSAGES, ""); # endif /* LC_MESSAGES */ nlsclose(); nlsinit(); # endif /* NLS_CATALOGS */ # ifdef SETLOCALEBUG dont_free = 0; # endif /* SETLOCALEBUG */ # ifdef STRCOLLBUG fix_strcoll_bug(); # endif /* STRCOLLBUG */ tw_cmd_free();/* since the collation sequence has changed */ for (k = 0200; k <= 0377 && !Isprint(CTL_ESC(k)); k++) continue; AsciiOnly = MB_CUR_MAX == 1 && k > 0377; #else /* !NLS */ AsciiOnly = getenv("LANG") == NULL && getenv("LC_CTYPE") == NULL; #endif /* NLS */ NLSMapsAreInited = 0; ed_Init(); if (MapsAreInited && !NLSMapsAreInited) ed_InitNLSMaps(); } #ifdef WINNT_NATIVE else if (eq(name,(STRtcshlang))) { nls_dll_unload(); nlsinit(); } #endif /* WINNT_NATIVE */ #ifdef COLOR_LS_F else if (eq(name, STRLS_COLORS)) parseLS_COLORS(n); else if (eq(name, STRLSCOLORS)) parseLSCOLORS(n); #endif /* COLOR_LS_F */ #ifdef NLS_CATALOGS else if (eq(name, STRNLSPATH)) { nlsclose(); nlsinit(); } #endif /* * start again cause the environment changes */ break; } cleanup_until(name); } void tsetenv(const Char *name, const Char *val) { #ifdef SETENV_IN_LIB /* * XXX: This does not work right, since tcsh cannot track changes to * the environment this way. (the builtin setenv without arguments does * not print the right stuff neither does unsetenv). This was for Mach, * it is not needed anymore. */ #undef setenv char *cname; if (name == NULL) return; cname = strsave(short2str(name)); setenv(cname, short2str(val), 1); xfree(cname); #else /* !SETENV_IN_LIB */ Char **ep = STR_environ; const Char *ccp; Char *cp, *dp; Char *blk[2]; Char **oep = ep; #ifdef WINNT_NATIVE nt_set_env(name,val); #endif /* WINNT_NATIVE */ for (; *ep; ep++) { #ifdef WINNT_NATIVE for (ccp = name, dp = *ep; *ccp && Tolower(*ccp & TRIM) == Tolower(*dp); ccp++, dp++) #else for (ccp = name, dp = *ep; *ccp && (*ccp & TRIM) == *dp; ccp++, dp++) #endif /* WINNT_NATIVE */ continue; if (*ccp != 0 || *dp != '=') continue; cp = Strspl(STRequal, val); xfree(*ep); *ep = strip(Strspl(name, cp)); xfree(cp); blkfree((Char **) environ); environ = short2blk(STR_environ); return; } cp = Strspl(name, STRequal); blk[0] = strip(Strspl(cp, val)); xfree(cp); blk[1] = 0; STR_environ = blkspl(STR_environ, blk); blkfree((Char **) environ); environ = short2blk(STR_environ); xfree(oep); #endif /* SETENV_IN_LIB */ } void Unsetenv(Char *name) { Char **ep = STR_environ; Char *cp, *dp; Char **oep = ep; #ifdef WINNT_NATIVE nt_set_env(name,NULL); #endif /*WINNT_NATIVE */ for (; *ep; ep++) { for (cp = name, dp = *ep; *cp && *cp == *dp; cp++, dp++) continue; if (*cp != 0 || *dp != '=') continue; cp = *ep; *ep = 0; STR_environ = blkspl(STR_environ, ep + 1); blkfree((Char **) environ); environ = short2blk(STR_environ); *ep = cp; xfree(cp); xfree(oep); return; } } /*ARGSUSED*/ void doumask(Char **v, struct command *c) { Char *cp = v[1]; int i; USE(c); if (cp == 0) { i = (int)umask(0); (void) umask(i); xprintf("%o\n", i); return; } i = 0; while (Isdigit(*cp) && *cp != '8' && *cp != '9') i = i * 8 + *cp++ - '0'; if (*cp || i < 0 || i > 0777) stderror(ERR_NAME | ERR_MASK); (void) umask(i); } #ifndef HAVENOLIMIT # ifndef BSDLIMIT typedef long RLIM_TYPE; # ifdef _OSD_POSIX /* BS2000 */ # include # endif # ifndef RLIM_INFINITY # if !defined(_MINIX) && !defined(__clipper__) && !defined(_CRAY) extern RLIM_TYPE ulimit(); # endif /* ! _MINIX && !__clipper__ */ # define RLIM_INFINITY 0x003fffff # define RLIMIT_FSIZE 1 # endif /* RLIM_INFINITY */ # ifdef aiws # define toset(a) (((a) == 3) ? 1004 : (a) + 1) # define RLIMIT_DATA 3 # define RLIMIT_STACK 1005 # else /* aiws */ # define toset(a) ((a) + 1) # endif /* aiws */ # else /* BSDLIMIT */ # if (defined(BSD4_4) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__) || (HPUXVERSION >= 1100)) && !defined(__386BSD__) typedef rlim_t RLIM_TYPE; # else # if defined(SOLARIS2) || (defined(sgi) && SYSVREL > 3) typedef rlim_t RLIM_TYPE; # else # if defined(_SX) typedef long long RLIM_TYPE; # else /* !_SX */ typedef unsigned long RLIM_TYPE; # endif /* _SX */ # endif /* SOLARIS2 || (sgi && SYSVREL > 3) */ # endif /* BSD4_4 && !__386BSD__ */ # endif /* BSDLIMIT */ # if (HPUXVERSION > 700) && (HPUXVERSION < 1100) && defined(BSDLIMIT) /* Yes hpux8.0 has limits but does not make them public */ /* Yes, we could have defined _KERNEL, and -I/etc/conf/h, but is that better? */ # ifndef RLIMIT_CPU # define RLIMIT_CPU 0 # define RLIMIT_FSIZE 1 # define RLIMIT_DATA 2 # define RLIMIT_STACK 3 # define RLIMIT_CORE 4 # define RLIMIT_RSS 5 # define RLIMIT_NOFILE 6 # endif /* RLIMIT_CPU */ # ifndef RLIM_INFINITY # define RLIM_INFINITY 0x7fffffff # endif /* RLIM_INFINITY */ /* * old versions of HP/UX counted limits in 512 bytes */ # ifndef SIGRTMIN # define FILESIZE512 # endif /* SIGRTMIN */ # endif /* (HPUXVERSION > 700) && (HPUXVERSION < 1100) && BSDLIMIT */ # if SYSVREL > 3 && defined(BSDLIMIT) && !defined(_SX) /* In order to use rusage, we included "/usr/ucbinclude/sys/resource.h" in */ /* sh.h. However, some SVR4 limits are defined in . Rather */ /* than include both and get warnings, we define the extra SVR4 limits here. */ /* XXX: I don't understand if RLIMIT_AS is defined, why don't we define */ /* RLIMIT_VMEM based on it? */ # ifndef RLIMIT_VMEM # define RLIMIT_VMEM 6 # endif # ifndef RLIMIT_AS # define RLIMIT_AS RLIMIT_VMEM # endif # endif /* SYSVREL > 3 && BSDLIMIT */ # if (defined(__linux__) || defined(__GNU__) || defined(__GLIBC__)) # if defined(RLIMIT_AS) && !defined(RLIMIT_VMEM) # define RLIMIT_VMEM RLIMIT_AS # endif /* * Oh well, has it, but does not * Linux headers: When the left hand does not know what the right hand does. */ # if defined(RLIMIT_RTPRIO) && !defined(RLIMIT_RTTIME) # define RLIMIT_RTTIME (RLIMIT_RTPRIO + 1) # endif # endif -struct limits limits[] = +struct limits limits[] = { # ifdef RLIMIT_CPU { RLIMIT_CPU, "cputime", 1, "seconds" }, # endif /* RLIMIT_CPU */ # ifdef RLIMIT_FSIZE # ifndef aiws { RLIMIT_FSIZE, "filesize", 1024, "kbytes" }, # else { RLIMIT_FSIZE, "filesize", 512, "blocks" }, # endif /* aiws */ # endif /* RLIMIT_FSIZE */ # ifdef RLIMIT_DATA { RLIMIT_DATA, "datasize", 1024, "kbytes" }, # endif /* RLIMIT_DATA */ # ifdef RLIMIT_STACK # ifndef aiws { RLIMIT_STACK, "stacksize", 1024, "kbytes" }, # else { RLIMIT_STACK, "stacksize", 1024 * 1024, "kbytes"}, # endif /* aiws */ # endif /* RLIMIT_STACK */ # ifdef RLIMIT_CORE { RLIMIT_CORE, "coredumpsize", 1024, "kbytes" }, # endif /* RLIMIT_CORE */ # ifdef RLIMIT_RSS { RLIMIT_RSS, "memoryuse", 1024, "kbytes" }, # endif /* RLIMIT_RSS */ # ifdef RLIMIT_UMEM { RLIMIT_UMEM, "memoryuse", 1024, "kbytes" }, # endif /* RLIMIT_UMEM */ # ifdef RLIMIT_VMEM { RLIMIT_VMEM, "vmemoryuse", 1024, "kbytes" }, # endif /* RLIMIT_VMEM */ # if defined(RLIMIT_HEAP) /* found on BS2000/OSD systems */ { RLIMIT_HEAP, "heapsize", 1024, "kbytes" }, # endif /* RLIMIT_HEAP */ # ifdef RLIMIT_NOFILE { RLIMIT_NOFILE, "descriptors", 1, "" }, # endif /* RLIMIT_NOFILE */ # ifdef RLIMIT_NPTS { RLIMIT_NPTS, "pseudoterminals", 1, "" }, # endif /* RLIMIT_NPTS */ # ifdef RLIMIT_KQUEUES { RLIMIT_KQUEUES, "kqueues", 1, "" }, # endif /* RLIMIT_KQUEUES */ # ifdef RLIMIT_CONCUR { RLIMIT_CONCUR, "concurrency", 1, "thread(s)" }, # endif /* RLIMIT_CONCUR */ # ifdef RLIMIT_MEMLOCK { RLIMIT_MEMLOCK, "memorylocked", 1024, "kbytes" }, # endif /* RLIMIT_MEMLOCK */ # ifdef RLIMIT_NPROC { RLIMIT_NPROC, "maxproc", 1, "" }, # endif /* RLIMIT_NPROC */ # ifdef RLIMIT_NTHR { RLIMIT_NTHR, "maxthread", 1, "" }, # endif /* RLIMIT_NTHR */ # if defined(RLIMIT_OFILE) && !defined(RLIMIT_NOFILE) { RLIMIT_OFILE, "openfiles", 1, "" }, # endif /* RLIMIT_OFILE && !defined(RLIMIT_NOFILE) */ # ifdef RLIMIT_SBSIZE { RLIMIT_SBSIZE, "sbsize", 1, "" }, # endif /* RLIMIT_SBSIZE */ -# ifdef RLIMIT_SWAP - { RLIMIT_SWAP, "swapsize", 1024, "kbytes" }, -# endif /* RLIMIT_SWAP */ +# ifdef RLIMIT_SWAP + { RLIMIT_SWAP, "swapsize", 1024, "kbytes" }, +# endif /* RLIMIT_SWAP */ -# ifdef RLIMIT_LOCKS - { RLIMIT_LOCKS, "maxlocks", 1, "" }, -# endif /* RLIMIT_LOCKS */ +# ifdef RLIMIT_LOCKS + { RLIMIT_LOCKS, "maxlocks", 1, "" }, +# endif /* RLIMIT_LOCKS */ # ifdef RLIMIT_POSIXLOCKS { RLIMIT_POSIXLOCKS,"posixlocks", 1, "" }, # endif /* RLIMIT_POSIXLOCKS */ -# ifdef RLIMIT_SIGPENDING - { RLIMIT_SIGPENDING,"maxsignal", 1, "" }, -# endif /* RLIMIT_SIGPENDING */ +# ifdef RLIMIT_SIGPENDING + { RLIMIT_SIGPENDING,"maxsignal", 1, "" }, +# endif /* RLIMIT_SIGPENDING */ -# ifdef RLIMIT_MSGQUEUE - { RLIMIT_MSGQUEUE, "maxmessage", 1, "" }, -# endif /* RLIMIT_MSGQUEUE */ +# ifdef RLIMIT_MSGQUEUE + { RLIMIT_MSGQUEUE, "maxmessage", 1, "" }, +# endif /* RLIMIT_MSGQUEUE */ -# ifdef RLIMIT_NICE - { RLIMIT_NICE, "maxnice", 1, "" }, -# endif /* RLIMIT_NICE */ +# ifdef RLIMIT_NICE + { RLIMIT_NICE, "maxnice", 1, "" }, +# endif /* RLIMIT_NICE */ -# ifdef RLIMIT_RTPRIO - { RLIMIT_RTPRIO, "maxrtprio", 1, "" }, -# endif /* RLIMIT_RTPRIO */ +# ifdef RLIMIT_RTPRIO + { RLIMIT_RTPRIO, "maxrtprio", 1, "" }, +# endif /* RLIMIT_RTPRIO */ -# ifdef RLIMIT_RTTIME - { RLIMIT_RTTIME, "maxrttime", 1, "usec" }, -# endif /* RLIMIT_RTTIME */ +# ifdef RLIMIT_RTTIME + { RLIMIT_RTTIME, "maxrttime", 1, "usec" }, +# endif /* RLIMIT_RTTIME */ { -1, NULL, 0, NULL } }; static struct limits *findlim (Char *); static RLIM_TYPE getval (struct limits *, Char **); static int strtail (Char *, const char *); static void limtail (Char *, const char *); static void limtail2 (Char *, const char *, const char *); static void plim (struct limits *, int); static int setlim (struct limits *, int, RLIM_TYPE); #ifdef convex static RLIM_TYPE restrict_limit(double value) { /* * is f too large to cope with? return the maximum or minimum int */ if (value > (double) INT_MAX) return (RLIM_TYPE) INT_MAX; else if (value < (double) INT_MIN) return (RLIM_TYPE) INT_MIN; else return (RLIM_TYPE) value; } #else /* !convex */ # define restrict_limit(x) ((RLIM_TYPE) (x)) #endif /* convex */ static struct limits * findlim(Char *cp) { struct limits *lp, *res; res = NULL; for (lp = limits; lp->limconst >= 0; lp++) if (prefix(cp, str2short(lp->limname))) { if (res) stderror(ERR_NAME | ERR_AMBIG); res = lp; } if (res) return (res); stderror(ERR_NAME | ERR_LIMIT); /* NOTREACHED */ return (0); } /*ARGSUSED*/ void dolimit(Char **v, struct command *c) { struct limits *lp; RLIM_TYPE limit; int hard = 0; USE(c); v++; if (*v && eq(*v, STRmh)) { hard = 1; v++; } if (*v == 0) { for (lp = limits; lp->limconst >= 0; lp++) plim(lp, hard); return; } lp = findlim(v[0]); if (v[1] == 0) { plim(lp, hard); return; } limit = getval(lp, v + 1); if (setlim(lp, hard, limit) < 0) stderror(ERR_SILENT); } static RLIM_TYPE getval(struct limits *lp, Char **v) { float f; Char *cp = *v++; f = atof(short2str(cp)); # ifdef convex /* * is f too large to cope with. limit f to minint, maxint - X-6768 by * strike */ if ((f < (double) INT_MIN) || (f > (double) INT_MAX)) { stderror(ERR_NAME | ERR_TOOLARGE); } # endif /* convex */ while (Isdigit(*cp) || *cp == '.' || *cp == 'e' || *cp == 'E') cp++; if (*cp == 0) { if (*v == 0) return restrict_limit((f * lp->limdiv) + 0.5); cp = *v; } switch (*cp) { # ifdef RLIMIT_CPU case ':': if (lp->limconst != RLIMIT_CPU) goto badscal; return f == 0.0 ? (RLIM_TYPE) 0 : restrict_limit((f * 60.0 + atof(short2str(cp + 1)))); case 'h': if (lp->limconst != RLIMIT_CPU) goto badscal; limtail(cp, "hours"); f *= 3600.0; break; # endif /* RLIMIT_CPU */ case 'm': # ifdef RLIMIT_CPU if (lp->limconst == RLIMIT_CPU) { limtail(cp, "minutes"); f *= 60.0; break; } # endif /* RLIMIT_CPU */ limtail2(cp, "megabytes", "mbytes"); f *= 1024.0 * 1024.0; break; # ifdef RLIMIT_CPU case 's': if (lp->limconst != RLIMIT_CPU) goto badscal; limtail(cp, "seconds"); break; # endif /* RLIMIT_CPU */ case 'G': *cp = 'g'; /*FALLTHROUGH*/ case 'g': # ifdef RLIMIT_CPU if (lp->limconst == RLIMIT_CPU) goto badscal; # endif /* RLIMIT_CPU */ limtail2(cp, "gigabytes", "gbytes"); f *= 1024.0 * 1024.0 * 1024.0; break; case 'M': # ifdef RLIMIT_CPU if (lp->limconst == RLIMIT_CPU) goto badscal; # endif /* RLIMIT_CPU */ *cp = 'm'; limtail2(cp, "megabytes", "mbytes"); f *= 1024.0 * 1024.0; break; case 'k': # ifdef RLIMIT_CPU if (lp->limconst == RLIMIT_CPU) goto badscal; # endif /* RLIMIT_CPU */ limtail2(cp, "kilobytes", "kbytes"); f *= 1024.0; break; case 'b': # ifdef RLIMIT_CPU if (lp->limconst == RLIMIT_CPU) goto badscal; # endif /* RLIMIT_CPU */ limtail(cp, "blocks"); f *= 512.0; break; case 'u': limtail(cp, "unlimited"); return ((RLIM_TYPE) RLIM_INFINITY); default: # ifdef RLIMIT_CPU badscal: # endif /* RLIMIT_CPU */ stderror(ERR_NAME | ERR_SCALEF); } # ifdef convex return f == 0.0 ? (RLIM_TYPE) 0 : restrict_limit((f + 0.5)); # else f += 0.5; if (f > (float) ((RLIM_TYPE) RLIM_INFINITY)) return ((RLIM_TYPE) RLIM_INFINITY); else return ((RLIM_TYPE) f); # endif /* convex */ } static int strtail(Char *cp, const char *str) { while (*cp && *cp == (Char)*str) cp++, str++; return (*cp != '\0'); } static void limtail(Char *cp, const char *str) { if (strtail(cp, str)) stderror(ERR_BADSCALE, str); } static void limtail2(Char *cp, const char *str1, const char *str2) { if (strtail(cp, str1) && strtail(cp, str2)) stderror(ERR_BADSCALE, str1); } /*ARGSUSED*/ static void plim(struct limits *lp, int hard) { # ifdef BSDLIMIT struct rlimit rlim; # endif /* BSDLIMIT */ RLIM_TYPE limit; int xdiv = lp->limdiv; xprintf("%-13.13s", lp->limname); # ifndef BSDLIMIT limit = ulimit(lp->limconst, 0); # ifdef aiws if (lp->limconst == RLIMIT_DATA) limit -= 0x20000000; # endif /* aiws */ # else /* BSDLIMIT */ (void) getrlimit(lp->limconst, &rlim); limit = hard ? rlim.rlim_max : rlim.rlim_cur; # endif /* BSDLIMIT */ # if !defined(BSDLIMIT) || defined(FILESIZE512) /* * Christos: filesize comes in 512 blocks. we divide by 2 to get 1024 * blocks. Note we cannot pre-multiply cause we might overflow (A/UX) */ if (lp->limconst == RLIMIT_FSIZE) { if (limit >= (RLIM_INFINITY / 512)) limit = RLIM_INFINITY; else xdiv = (xdiv == 1024 ? 2 : 1); } # endif /* !BSDLIMIT || FILESIZE512 */ if (limit == RLIM_INFINITY) xprintf("unlimited"); else # if defined(RLIMIT_CPU) && defined(_OSD_POSIX) if (lp->limconst == RLIMIT_CPU && (unsigned long)limit >= 0x7ffffffdUL) xprintf("unlimited"); else # endif # ifdef RLIMIT_CPU if (lp->limconst == RLIMIT_CPU) psecs(limit); else # endif /* RLIMIT_CPU */ xprintf("%ld %s", (long) (limit / xdiv), lp->limscale); xputchar('\n'); } /*ARGSUSED*/ void dounlimit(Char **v, struct command *c) { struct limits *lp; int lerr = 0; int hard = 0; int force = 0; USE(c); while (*++v && **v == '-') { Char *vp = *v; while (*++vp) switch (*vp) { case 'f': force = 1; break; case 'h': hard = 1; break; default: stderror(ERR_ULIMUS); break; } } if (*v == 0) { for (lp = limits; lp->limconst >= 0; lp++) if (setlim(lp, hard, (RLIM_TYPE) RLIM_INFINITY) < 0) lerr++; if (!force && lerr) stderror(ERR_SILENT); return; } while (*v) { lp = findlim(*v++); if (setlim(lp, hard, (RLIM_TYPE) RLIM_INFINITY) < 0 && !force) stderror(ERR_SILENT); } } static int setlim(struct limits *lp, int hard, RLIM_TYPE limit) { # ifdef BSDLIMIT struct rlimit rlim; (void) getrlimit(lp->limconst, &rlim); # ifdef FILESIZE512 /* Even though hpux has setrlimit(), it expects fsize in 512 byte blocks */ if (limit != RLIM_INFINITY && lp->limconst == RLIMIT_FSIZE) limit /= 512; # endif /* FILESIZE512 */ if (hard) rlim.rlim_max = limit; else if (limit == RLIM_INFINITY && euid != 0) rlim.rlim_cur = rlim.rlim_max; else rlim.rlim_cur = limit; if (rlim.rlim_cur > rlim.rlim_max) rlim.rlim_max = rlim.rlim_cur; if (setrlimit(lp->limconst, &rlim) < 0) { # else /* BSDLIMIT */ if (limit != RLIM_INFINITY && lp->limconst == RLIMIT_FSIZE) limit /= 512; # ifdef aiws if (lp->limconst == RLIMIT_DATA) limit += 0x20000000; # endif /* aiws */ if (ulimit(toset(lp->limconst), limit) < 0) { # endif /* BSDLIMIT */ int err; char *op, *type; err = errno; op = strsave(limit == RLIM_INFINITY ? CGETS(15, 2, "remove") : CGETS(15, 3, "set")); cleanup_push(op, xfree); type = strsave(hard ? CGETS(15, 4, " hard") : ""); cleanup_push(type, xfree); xprintf(CGETS(15, 1, "%s: %s: Can't %s%s limit (%s)\n"), bname, lp->limname, op, type, strerror(err)); cleanup_until(op); return (-1); } return (0); } #endif /* !HAVENOLIMIT */ /*ARGSUSED*/ void dosuspend(Char **v, struct command *c) { #ifdef BSDJOBS struct sigaction old; #endif /* BSDJOBS */ USE(c); USE(v); if (loginsh) stderror(ERR_SUSPLOG); untty(); #ifdef BSDJOBS sigaction(SIGTSTP, NULL, &old); signal(SIGTSTP, SIG_DFL); (void) kill(0, SIGTSTP); /* the shell stops here */ sigaction(SIGTSTP, &old, NULL); #else /* !BSDJOBS */ stderror(ERR_JOBCONTROL); #endif /* BSDJOBS */ #ifdef BSDJOBS if (tpgrp != -1) { if (grabpgrp(FSHTTY, opgrp) == -1) stderror(ERR_SYSTEM, "tcgetpgrp", strerror(errno)); (void) setpgid(0, shpgrp); (void) tcsetpgrp(FSHTTY, shpgrp); } #endif /* BSDJOBS */ (void) setdisc(FSHTTY); } /* This is the dreaded EVAL built-in. * If you don't fiddle with file descriptors, and reset didfds, * this command will either ignore redirection inside or outside * its arguments, e.g. eval "date >x" vs. eval "date" >x * The stuff here seems to work, but I did it by trial and error rather * than really knowing what was going on. If tpgrp is zero, we are * probably a background eval, e.g. "eval date &", and we want to * make sure that any processes we start stay in our pgrp. * This is also the case for "time eval date" -- stay in same pgrp. * Otherwise, under stty tostop, processes will stop in the wrong * pgrp, with no way for the shell to get them going again. -IAN! */ struct doeval_state { Char **evalvec, *evalp; int didfds; #ifndef CLOSE_ON_EXEC int didcch; #endif int saveIN, saveOUT, saveDIAG; int SHIN, SHOUT, SHDIAG; }; static void doeval_cleanup(void *xstate) { struct doeval_state *state; state = xstate; evalvec = state->evalvec; evalp = state->evalp; doneinp = 0; #ifndef CLOSE_ON_EXEC didcch = state->didcch; #endif /* CLOSE_ON_EXEC */ didfds = state->didfds; if (state->saveIN != SHIN) xclose(SHIN); if (state->saveOUT != SHOUT) xclose(SHOUT); if (state->saveDIAG != SHDIAG) xclose(SHDIAG); close_on_exec(SHIN = dmove(state->saveIN, state->SHIN), 1); close_on_exec(SHOUT = dmove(state->saveOUT, state->SHOUT), 1); close_on_exec(SHDIAG = dmove(state->saveDIAG, state->SHDIAG), 1); if (didfds) { close_on_exec(dcopy(SHIN, 0), 1); close_on_exec(dcopy(SHOUT, 1), 1); close_on_exec(dcopy(SHDIAG, 2), 1); } } static Char **Ggv; /*ARGSUSED*/ void doeval(Char **v, struct command *c) { struct doeval_state state; int gflag, my_reenter; Char **gv; jmp_buf_t osetexit; USE(c); v++; if (*v == 0) return; gflag = tglob(v); if (gflag) { gv = v = globall(v, gflag); if (v == 0) stderror(ERR_NOMATCH); cleanup_push(gv, blk_cleanup); v = copyblk(v); } else { gv = NULL; v = copyblk(v); trim(v); } Ggv = gv; state.evalvec = evalvec; state.evalp = evalp; state.didfds = didfds; #ifndef CLOSE_ON_EXEC state.didcch = didcch; #endif /* CLOSE_ON_EXEC */ state.SHIN = SHIN; state.SHOUT = SHOUT; state.SHDIAG = SHDIAG; (void)close_on_exec(state.saveIN = dcopy(SHIN, -1), 1); (void)close_on_exec(state.saveOUT = dcopy(SHOUT, -1), 1); (void)close_on_exec(state.saveDIAG = dcopy(SHDIAG, -1), 1); cleanup_push(&state, doeval_cleanup); getexit(osetexit); /* PWP: setjmp/longjmp bugfix for optimizing compilers */ #ifdef cray my_reenter = 1; /* assume non-zero return val */ if (setexit() == 0) { my_reenter = 0; /* Oh well, we were wrong */ #else /* !cray */ if ((my_reenter = setexit()) == 0) { #endif /* cray */ evalvec = v; evalp = 0; (void)close_on_exec(SHIN = dcopy(0, -1), 1); (void)close_on_exec(SHOUT = dcopy(1, -1), 1); (void)close_on_exec(SHDIAG = dcopy(2, -1), 1); #ifndef CLOSE_ON_EXEC didcch = 0; #endif /* CLOSE_ON_EXEC */ didfds = 0; gv = Ggv; process(0); Ggv = gv; } if (my_reenter == 0) { cleanup_until(&state); if (Ggv) cleanup_until(Ggv); } resexit(osetexit); if (my_reenter) stderror(ERR_SILENT); } /*************************************************************************/ /* print list of builtin commands */ static void lbuffed_cleanup (void *dummy) { USE(dummy); lbuffed = 1; } /*ARGSUSED*/ void dobuiltins(Char **v, struct command *c) { /* would use print_by_column() in tw.parse.c but that assumes * we have an array of Char * to pass.. (sg) */ const struct biltins *b; int row, col, columns, rows; unsigned int w, maxwidth; USE(c); USE(v); lbuffed = 0; /* turn off line buffering */ cleanup_push(&lbuffed, lbuffed_cleanup); /* find widest string */ for (maxwidth = 0, b = bfunc; b < &bfunc[nbfunc]; ++b) maxwidth = max(maxwidth, strlen(b->bname)); ++maxwidth; /* for space */ columns = (TermH + 1) / maxwidth; /* PWP: terminal size change */ if (!columns) columns = 1; rows = (nbfunc + (columns - 1)) / columns; for (b = bfunc, row = 0; row < rows; row++) { for (col = 0; col < columns; col++) { if (b < &bfunc[nbfunc]) { w = strlen(b->bname); xprintf("%s", b->bname); if (col < (columns - 1)) /* Not last column? */ for (; w < maxwidth; w++) xputchar(' '); ++b; } } if (row < (rows - 1)) { if (Tty_raw_mode) xputchar('\r'); xputchar('\n'); } } #ifdef WINNT_NATIVE nt_print_builtins(maxwidth); #else if (Tty_raw_mode) xputchar('\r'); xputchar('\n'); #endif /* WINNT_NATIVE */ cleanup_until(&lbuffed); /* turn back on line buffering */ flush(); } #ifdef NLS_CATALOGS char * xcatgets(nl_catd ctd, int set_id, int msg_id, const char *s) { char *res; errno = 0; while ((res = catgets(ctd, set_id, msg_id, s)) == s && errno == EINTR) { handle_pending_signals(); errno = 0; } return res; } # if defined(HAVE_ICONV) && defined(HAVE_NL_LANGINFO) char * iconv_catgets(nl_catd ctd, int set_id, int msg_id, const char *s) { static char *buf = NULL; static size_t buf_size = 0; - + char *orig, *dest, *p; ICONV_CONST char *src; size_t src_size, dest_size; - + orig = xcatgets(ctd, set_id, msg_id, s); if (catgets_iconv == (iconv_t)-1 || orig == s) return orig; src = orig; src_size = strlen(src) + 1; if (buf == NULL && (buf = xmalloc(buf_size = src_size + 32)) == NULL) return orig; dest = buf; while (src_size != 0) { dest_size = buf + buf_size - dest; if (iconv(catgets_iconv, &src, &src_size, &dest, &dest_size) == (size_t)-1) { switch (errno) { case E2BIG: if ((p = xrealloc(buf, buf_size * 2)) == NULL) return orig; buf_size *= 2; dest = p + (dest - buf); buf = p; break; - + case EILSEQ: case EINVAL: default: return orig; } } } return buf; } # endif /* HAVE_ICONV && HAVE_NL_LANGINFO */ #endif /* NLS_CATALOGS */ void nlsinit(void) { #ifdef NLS_CATALOGS static const char default_catalog[] = "tcsh"; char *catalog = (char *)(intptr_t)default_catalog; if (adrof(STRcatalog) != NULL) catalog = xasprintf("tcsh.%s", short2str(varval(STRcatalog))); #ifdef NL_CAT_LOCALE /* POSIX-compliant. */ /* * Check if LC_MESSAGES is set in the environment and use it, if so. * If not, fall back to the setting of LANG. */ catd = catopen(catalog, tgetenv(STRLC_MESSAGES) ? NL_CAT_LOCALE : 0); #else /* pre-POSIX */ # ifndef MCLoadBySet # define MCLoadBySet 0 # endif catd = catopen(catalog, MCLoadBySet); #endif if (catalog != default_catalog) xfree(catalog); #if defined(HAVE_ICONV) && defined(HAVE_NL_LANGINFO) /* xcatgets (), not CGETS, the charset name should be in ASCII anyway. */ catgets_iconv = iconv_open (nl_langinfo (CODESET), xcatgets(catd, 255, 1, "UTF-8")); #endif /* HAVE_ICONV && HAVE_NL_LANGINFO */ #endif /* NLS_CATALOGS */ #ifdef WINNT_NATIVE nls_dll_init(); #endif /* WINNT_NATIVE */ errinit(); /* init the errorlist in correct locale */ mesginit(); /* init the messages for signals */ dateinit(); /* init the messages for dates */ editinit(); /* init the editor messages */ terminit(); /* init the termcap messages */ } void nlsclose(void) { #ifdef NLS_CATALOGS #if defined(HAVE_ICONV) && defined(HAVE_NL_LANGINFO) if (catgets_iconv != (iconv_t)-1) { iconv_close(catgets_iconv); catgets_iconv = (iconv_t)-1; } #endif /* HAVE_ICONV && HAVE_NL_LANGINFO */ if (catd != (nl_catd)-1) { /* * catclose can call other functions which can call longjmp * making us re-enter this code. Prevent infinite recursion * by resetting catd. Problem reported and solved by: * Gerhard Niklasch */ nl_catd oldcatd = catd; catd = (nl_catd)-1; while (catclose(oldcatd) == -1 && errno == EINTR) handle_pending_signals(); } #endif /* NLS_CATALOGS */ } int getYN(const char *prompt) { int doit; char c; xprintf("%s", prompt); flush(); (void) force_read(SHIN, &c, sizeof(c)); - /* + /* * Perhaps we should use the yesexpr from the * actual locale */ doit = (strchr(CGETS(22, 14, "Yy"), c) != NULL); while (c != '\n' && force_read(SHIN, &c, sizeof(c)) == sizeof(c)) continue; return doit; } diff --git a/contrib/tcsh/sh.glob.c b/contrib/tcsh/sh.glob.c index a57404013f88..992f5e47362d 100644 --- a/contrib/tcsh/sh.glob.c +++ b/contrib/tcsh/sh.glob.c @@ -1,1022 +1,1022 @@ /* * sh.glob.c: Regular expression expansion */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "tc.h" #include "tw.h" #include "glob.h" /* * Values for gflag */ #define G_NONE 0 /* No globbing needed */ #define G_GLOB 1 /* string contains *?[] characters */ #define G_CSH 2 /* string contains ~`{ characters */ #define GLOBSPACE 100 /* Alloc increment */ #define LBRC '{' #define RBRC '}' #define LBRK '[' #define RBRK ']' #define EOS '\0' /* * globbing is now done in two stages. In the first pass we expand * csh globbing idioms ~`{ and then we proceed doing the normal * globbing if needed ?*[ * * Csh type globbing is handled in globexpand() and the rest is * handled in glob() which is part of the 4.4BSD libc. * */ static Char *globtilde (Char *); static Char *handleone (Char *, Char **, int); static Char **libglob (Char **); static Char **globexpand (Char **, int); static int globbrace (const Char *, Char ***); static void expbrace (Char ***, Char ***, int); static void pword (struct blk_buf *, struct Strbuf *); static void backeval (struct blk_buf *, struct Strbuf *, Char *, int); static Char * globtilde(Char *s) { Char *name, *u, *home, *res; u = s; if (s[1] == '~') return Strsave(s); for (s++; *s && *s != '/' && *s != ':'; s++) continue; name = Strnsave(u + 1, s - (u + 1)); cleanup_push(name, xfree); home = gethdir(name); if (home == NULL) { if (adrof(STRnonomatch)) { cleanup_until(name); return u; } if (*name) stderror(ERR_UNKUSER, short2str(name)); else stderror(ERR_NOHOME); } cleanup_until(name); if (home[0] == '/' && home[1] == '\0' && s[0] == '/') res = Strsave(s); else res = Strspl(home, s); xfree(home); xfree(u); return res; } /* Returns a newly allocated string, old or NULL */ Char * globequal(Char *old) { int dig; const Char *dir; Char *b; /* * kfk - 17 Jan 1984 - stack hack allows user to get at arbitrary dir names * in stack. PWP: let =foobar pass through (for X windows) */ if (old[1] == '-' && (old[2] == '\0' || old[2] == '/')) { /* =- */ const Char *olddir = varval (STRowd); if (olddir && *olddir && !dcwd->di_next->di_name && !dcwd->di_prev->di_name) return Strspl(olddir, &old[2]); dig = -1; b = &old[2]; } else if (Isdigit(old[1])) { /* = */ dig = old[1] - '0'; for (b = &old[2]; Isdigit(*b); b++) dig = dig * 10 + (*b - '0'); if (*b != '\0' && *b != '/') /* =foobar */ return old; } else /* =foobar */ return old; dir = getstakd(dig); if (dir == NULL) return NULL; return Strspl(dir, b); } static int globbrace(const Char *s, Char ***bl) { struct Strbuf gbuf = Strbuf_INIT; struct blk_buf bb = BLK_BUF_INIT; int i; const Char *p, *pm, *pe, *pl; size_t prefix_len; /* copy part up to the brace */ for (p = s; *p != LBRC; p++) ; prefix_len = p - s; /* check for balanced braces */ for (i = 0, pe = ++p; *pe; pe++) if (*pe == LBRK) { /* Ignore everything between [] */ for (++pe; *pe != RBRK && *pe != EOS; pe++) continue; if (*pe == EOS) return (-RBRK); } else if (*pe == LBRC) i++; else if (*pe == RBRC) { if (i == 0) break; i--; } if (i != 0 || *pe == '\0') return (-RBRC); Strbuf_appendn(&gbuf, s, prefix_len); for (i = 0, pl = pm = p; pm <= pe; pm++) switch (*pm) { case LBRK: for (++pm; *pm != RBRK && *pm != EOS; pm++) continue; if (*pm == EOS) { bb_cleanup(&bb); xfree(gbuf.s); return (-RBRK); } break; case LBRC: i++; break; case RBRC: if (i) { i--; break; } /* FALLTHROUGH */ case ',': if (i && *pm == ',') break; else { gbuf.len = prefix_len; Strbuf_appendn(&gbuf, pl, pm - pl); Strbuf_append(&gbuf, pe + 1); Strbuf_terminate(&gbuf); bb_append(&bb, Strsave(gbuf.s)); pl = pm + 1; } break; default: break; } *bl = bb_finish(&bb); xfree(gbuf.s); return bb.len; } static void expbrace(Char ***nvp, Char ***elp, int size) { Char **vl, **el, **nv, *s; vl = nv = *nvp; if (elp != NULL) el = *elp; else el = vl + blklen(vl); for (s = *vl; s; s = *++vl) { Char **vp, **bp; /* leave {} untouched for find */ if (s[0] == '{' && (s[1] == '\0' || (s[1] == '}' && s[2] == '\0'))) continue; if (Strchr(s, '{') != NULL) { Char **bl = NULL; int len; if ((len = globbrace(s, &bl)) < 0) stderror(ERR_MISSING, -len); xfree(s); if (len == 1) { *vl-- = *bl; xfree(bl); continue; } if (&el[len] >= &nv[size]) { size_t l, e; l = &el[len] - &nv[size]; size += GLOBSPACE > l ? GLOBSPACE : l; l = vl - nv; e = el - nv; nv = xrealloc(nv, size * sizeof(Char *)); *nvp = nv; /* To keep cleanups working */ vl = nv + l; el = nv + e; } /* nv vl el bl * | | | | * -.--..-- x-- * | len * vp */ vp = vl--; *vp = *bl; len--; for (bp = el; bp != vp; bp--) bp[len] = *bp; el += len; /* nv vl el bl * | | | | * -.-x --- -- * |len * vp */ vp++; for (bp = bl + 1; *bp; *vp++ = *bp++) continue; xfree(bl); } } if (elp != NULL) *elp = el; } static Char ** globexpand(Char **v, int noglob) { Char *s; Char ***fnv, **vl, **el; int size = GLOBSPACE; fnv = xmalloc(sizeof(Char ***)); *fnv = vl = xmalloc(sizeof(Char *) * size); *vl = NULL; cleanup_push(fnv, blk_indirect_cleanup); /* * Step 1: expand backquotes. */ while ((s = *v++) != NULL) { if (Strchr(s, '`')) { int i; Char **expanded; expanded = dobackp(s, 0); for (i = 0; expanded[i] != NULL; i++) { *vl++ = expanded[i]; if (vl == &(*fnv)[size]) { size += GLOBSPACE; *fnv = xrealloc(*fnv, size * sizeof(Char *)); vl = &(*fnv)[size - GLOBSPACE]; } } xfree(expanded); } else { *vl++ = Strsave(s); if (vl == &(*fnv)[size]) { size += GLOBSPACE; *fnv = xrealloc(*fnv, size * sizeof(Char *)); vl = &(*fnv)[size - GLOBSPACE]; } } *vl = NULL; } if (noglob) goto done; /* * Step 2: expand braces */ el = vl; expbrace(fnv, &el, size); /* * Step 3: expand ~ = */ vl = *fnv; for (s = *vl; s; s = *++vl) switch (*s) { Char *ns; case '~': *vl = globtilde(s); break; case '=': if ((ns = globequal(s)) == NULL) { if (!adrof(STRnonomatch)) stderror(ERR_DEEP); /* Error */ } if (ns && ns != s) { /* Expansion succeeded */ xfree(s); *vl = ns; } break; default: break; } vl = *fnv; /* * Step 4: expand .. if the variable symlinks==expand is set */ if (symlinks == SYM_EXPAND) { for (s = *vl; s; s = *++vl) { *vl = dnormalize(s, 1); xfree(s); } } done: cleanup_ignore(fnv); cleanup_until(fnv); vl = *fnv; xfree(fnv); return vl; } static Char * handleone(Char *str, Char **vl, int action) { size_t chars; Char **t, *p, *strp; switch (action) { case G_ERROR: setname(short2str(str)); blkfree(vl); stderror(ERR_NAME | ERR_AMBIG); break; case G_APPEND: chars = 0; for (t = vl; (p = *t++) != NULL; chars++) chars += Strlen(p); str = xmalloc(chars * sizeof(Char)); for (t = vl, strp = str; (p = *t++) != NULL; chars++) { while (*p) *strp++ = *p++ & TRIM; *strp++ = ' '; } *--strp = '\0'; blkfree(vl); break; case G_IGNORE: str = Strsave(strip(*vl)); blkfree(vl); break; default: break; } return (str); } static Char ** libglob(Char **vl) { int gflgs = GLOB_QUOTE | GLOB_NOMAGIC | GLOB_ALTNOT; glob_t globv; char *ptr; int nonomatch = adrof(STRnonomatch) != 0, magic = 0, match = 0; if (adrof(STRglobdot)) gflgs |= GLOB_DOT; if (adrof(STRglobstar)) gflgs |= GLOB_STAR; if (!vl || !vl[0]) return(vl); globv.gl_offs = 0; globv.gl_pathv = 0; globv.gl_pathc = 0; if (nonomatch) gflgs |= GLOB_NOCHECK; do { ptr = short2qstr(*vl); switch (glob(ptr, gflgs, 0, &globv)) { case GLOB_ABEND: globfree(&globv); setname(ptr); stderror(ERR_NAME | ERR_GLOB); /* NOTREACHED */ case GLOB_NOSPACE: globfree(&globv); stderror(ERR_NOMEM); /* NOTREACHED */ default: break; } if (globv.gl_flags & GLOB_MAGCHAR) { match |= (globv.gl_matchc != 0); magic = 1; } gflgs |= GLOB_APPEND; } while (*++vl); - vl = (globv.gl_pathc == 0 || (magic && !match && !nonomatch)) ? + vl = (globv.gl_pathc == 0 || (magic && !match && !nonomatch)) ? NULL : blk2short(globv.gl_pathv); globfree(&globv); return (vl); } Char * globone(Char *str, int action) { Char *v[2], **vl, **vo; int gflg, noglob; noglob = adrof(STRnoglob) != 0; v[0] = str; v[1] = 0; gflg = tglob(v); if (gflg == G_NONE) return (strip(Strsave(str))); if (gflg & G_CSH) { /* * Expand back-quote, tilde and brace */ vo = globexpand(v, noglob); if (noglob || (gflg & G_GLOB) == 0) { vl = vo; goto result; } cleanup_push(vo, blk_cleanup); } else if (noglob || (gflg & G_GLOB) == 0) return (strip(Strsave(str))); else vo = v; vl = libglob(vo); if (gflg & G_CSH) { if (vl != vo) cleanup_until(vo); else cleanup_ignore(vo); } if (vl == NULL) { setname(short2str(str)); stderror(ERR_NAME | ERR_NOMATCH); } result: if (vl && vl[0] == NULL) { if (vl != v) xfree(vl); return (Strsave(STRNULL)); } - if (vl && vl[1]) + if (vl && vl[1]) return (handleone(str, vl, action)); else { str = strip(*vl); if (vl != v) xfree(vl); return (str); } } Char ** globall(Char **v, int gflg) { Char **vl, **vo; int noglob; if (!v || !v[0]) return saveblk(v); noglob = adrof(STRnoglob) != 0; if (gflg & G_CSH) /* * Expand back-quote, tilde and brace */ vl = vo = globexpand(v, noglob); else vl = vo = saveblk(v); if (!noglob && (gflg & G_GLOB)) { cleanup_push(vo, blk_cleanup); vl = libglob(vo); if (vl == vo) cleanup_ignore(vo); cleanup_until(vo); } else trim(vl); return vl; } Char ** glob_all_or_error(Char **v) { int gflag; gflag = tglob(v); if (gflag) { v = globall(v, gflag); if (v == NULL) stderror(ERR_NAME | ERR_NOMATCH); } else { v = saveblk(v); trim(v); } return v; } void rscan(Char **t, void (*f) (Char)) { Char *p; while ((p = *t++) != NULL) while (*p) (*f) (*p++); } void trim(Char **t) { Char *p; while ((p = *t++) != NULL) while (*p) { #if INVALID_BYTE != 0 if ((*p & INVALID_BYTE) != INVALID_BYTE) /* *p < INVALID_BYTE */ #endif *p &= TRIM; p++; } } int tglob(Char **t) { int gflag; const Char *p; gflag = 0; while ((p = *t++) != NULL) { if (*p == '~' || *p == '=') gflag |= G_CSH; else if (*p == '{' && (p[1] == '\0' || (p[1] == '}' && p[2] == '\0'))) continue; while (*p != '\0') { if (*p == '`') { gflag |= G_CSH; #ifdef notdef /* * We do want to expand echo `echo '*'`, so we don't\ * use this piece of code anymore. */ p++; - while (*p && *p != '`') + while (*p && *p != '`') if (*p++ == '\\') { if (*p) /* Quoted chars */ p++; else break; } if (!*p) /* The matching ` */ break; #endif } else if (*p == '{') gflag |= G_CSH; else if (isglob(*p)) gflag |= G_GLOB; - else if (symlinks == SYM_EXPAND && + else if (symlinks == SYM_EXPAND && p[1] && ISDOTDOT(p) && (p == *(t-1) || *(p-1) == '/') ) gflag |= G_CSH; p++; } } return gflag; } /* * Command substitute cp. If literal, then this is a substitution from a * << redirection, and so we should not crunch blanks and tabs, separating * words only at newlines. */ Char ** dobackp(Char *cp, int literal) { struct Strbuf word = Strbuf_INIT; struct blk_buf bb = BLK_BUF_INIT; Char *lp, *rp, *ep; cleanup_push(&bb, bb_cleanup); cleanup_push(&word, Strbuf_cleanup); for (;;) { for (lp = cp; *lp != '\0' && *lp != '`'; lp++) ; Strbuf_appendn(&word, cp, lp - cp); if (*lp == 0) break; lp++; for (rp = lp; *rp && *rp != '`'; rp++) if (*rp == '\\') { rp++; if (!*rp) goto oops; } if (!*rp) { oops: cleanup_until(&bb); stderror(ERR_UNMATCHED, '`'); } ep = Strnsave(lp, rp - lp); cleanup_push(ep, xfree); backeval(&bb, &word, ep, literal); cleanup_until(ep); cp = rp + 1; } if (word.len != 0) pword(&bb, &word); cleanup_ignore(&bb); cleanup_until(&bb); return bb_finish(&bb); } static void backeval(struct blk_buf *bb, struct Strbuf *word, Char *cp, int literal) { ssize_t icnt; Char c, *ip; struct command faket; int hadnl; int pvec[2], quoted; Char *fakecom[2], ibuf[BUFSIZE]; hadnl = 0; icnt = 0; if (!literal) { for (ip = cp; (*ip & QUOTE) != 0; ip++) continue; quoted = *ip == '\0'; } else quoted = literal; faket.t_dtyp = NODE_COMMAND; faket.t_dflg = F_BACKQ; faket.t_dlef = 0; faket.t_drit = 0; faket.t_dspr = 0; faket.t_dcom = fakecom; fakecom[0] = STRfakecom1; fakecom[1] = 0; /* * We do the psave job to temporarily change the current job so that the * following fork is considered a separate job. This is so that when * backquotes are used in a builtin function that calls glob the "current * job" is not corrupted. We only need one level of pushed jobs as long as * we are sure to fork here. */ psavejob(); cleanup_push(&faket, psavejob_cleanup); /* faket is only a marker */ /* * It would be nicer if we could integrate this redirection more with the * routines in sh.sem.c by doing a fake execute on a builtin function that * was piped out. */ mypipe(pvec); cleanup_push(&pvec[0], open_cleanup); cleanup_push(&pvec[1], open_cleanup); if (pfork(&faket, -1) == 0) { jmp_buf_t osetexit; struct command *t; size_t omark; xclose(pvec[0]); (void) dmove(pvec[1], 1); (void) dmove(SHDIAG, 2); initdesc(); closem(); arginp = cp; for (arginp = cp; *cp; cp++) { *cp &= TRIM; if (is_set(STRcsubstnonl) && (*cp == '\n' || *cp == '\r')) *cp = ' '; } /* * In the child ``forget'' everything about current aliases or * eval vectors. */ alvec = NULL; evalvec = NULL; alvecp = NULL; evalp = NULL; omark = cleanup_push_mark(); getexit(osetexit); for (;;) { struct wordent paraml1; initlex(¶ml1); (void) setexit(); justpr = 0; - + if (haderr) { /* unwind */ doneinp = 0; cleanup_pop_mark(omark); resexit(osetexit); reset(); } if (seterr) { xfree(seterr); seterr = NULL; } freelex(¶ml1); (void) lex(¶ml1); cleanup_push(¶ml1, lex_cleanup); if (seterr) stderror(ERR_OLD); alias(¶ml1); t = syntax(paraml1.next, ¶ml1, 0); cleanup_push(t, syntax_cleanup); /* The F_BACKQ flag must set so the job output is correct if * printexitvalue is set. If it's not set, the job output * will have "Exit N" appended where N is the exit status. */ if (t) t->t_dflg = F_BACKQ|F_NOFORK; if (seterr) stderror(ERR_OLD); #ifdef SIGTSTP signal(SIGTSTP, SIG_IGN); #endif #ifdef SIGTTIN signal(SIGTTIN, SIG_IGN); #endif #ifdef SIGTTOU signal(SIGTTOU, SIG_IGN); #endif execute(t, -1, NULL, NULL, TRUE); cleanup_until(¶ml1); } } cleanup_until(&pvec[1]); c = 0; ip = NULL; do { ssize_t cnt = 0; for (;;) { if (icnt == 0) { ip = ibuf; icnt = wide_read(pvec[0], ibuf, BUFSIZE, 0); if (icnt <= 0) goto eof; } if (hadnl) break; --icnt; c = (*ip++ & TRIM); if (c == 0) break; #if defined(WINNT_NATIVE) || defined(__CYGWIN__) if (c == '\r') c = ' '; #endif /* WINNT_NATIVE || __CYGWIN__ */ if (c == '\n') { /* * Continue around the loop one more time, so that we can eat * the last newline without terminating this word. */ hadnl = 1; continue; } if (!quoted && (c == ' ' || c == '\t')) break; cnt++; if (c == '\\' || quoted) c |= QUOTE; Strbuf_append1(word, c); } /* * Unless at end-of-file, we will form a new word here if there were * characters in the word, or in any case when we take text literally. * If we didn't make empty words here when literal was set then we * would lose blank lines. */ if (c != 0 && (cnt || literal)) pword(bb, word); hadnl = 0; } while (c > 0); eof: cleanup_until(&pvec[0]); pwait(); cleanup_until(&faket); /* psavejob_cleanup(); */ } static void pword(struct blk_buf *bb, struct Strbuf *word) { Char *s; s = Strbuf_finish(word); bb_append(bb, s); *word = Strbuf_init; } int Gmatch(const Char *string, const Char *pattern) { return Gnmatch(string, pattern, NULL); } int Gnmatch(const Char *string, const Char *pattern, const Char **endstr) { Char ***fblk, **p; const Char *tstring = string; int gpol = 1, gres = 0; if (*pattern == '^') { gpol = 0; pattern++; } fblk = xmalloc(sizeof(Char ***)); *fblk = xmalloc(GLOBSPACE * sizeof(Char *)); (*fblk)[0] = Strsave(pattern); (*fblk)[1] = NULL; cleanup_push(fblk, blk_indirect_cleanup); expbrace(fblk, NULL, GLOBSPACE); if (endstr == NULL) /* Exact matches only */ - for (p = *fblk; *p; p++) + for (p = *fblk; *p; p++) gres |= t_pmatch(string, *p, &tstring, 1) == 2 ? 1 : 0; else { const Char *end; /* partial matches */ end = Strend(string); for (p = *fblk; *p; p++) if (t_pmatch(string, *p, &tstring, 1) != 0) { gres |= 1; if (end > tstring) end = tstring; } *endstr = end; } cleanup_until(fblk); return(gres == gpol); -} +} /* t_pmatch(): - * Return 2 on exact match, + * Return 2 on exact match, * Return 1 on substring match. * Return 0 on no match. * *estr will point to the end of the longest exact or substring match. */ int t_pmatch(const Char *string, const Char *pattern, const Char **estr, int cs) { Char stringc, patternc, rangec; int match, negate_range; const Char *pestr, *nstring; for (nstring = string;; string = nstring) { stringc = *nstring++ & TRIM; patternc = *pattern++ & TRIM; switch (patternc) { case '\0': *estr = string; return (stringc == '\0' ? 2 : 1); case '?': if (stringc == 0) return (0); break; case '*': if (!*pattern) { *estr = Strend(string); return (2); } pestr = NULL; for (;;) { switch(t_pmatch(string, pattern, estr, cs)) { case 0: break; case 1: pestr = *estr;/*FIXME: does not guarantee longest match */ break; case 2: return 2; default: abort(); /* Cannot happen */ } stringc = *string++ & TRIM; if (!stringc) break; } if (pestr) { *estr = pestr; return 1; } else return 0; case '[': match = 0; if ((negate_range = (*pattern == '^')) != 0) pattern++; while ((rangec = *pattern++ & TRIM) != '\0') { if (rangec == ']') break; if (match) continue; if (*pattern == '-' && pattern[1] != ']') { Char rangec2; pattern++; rangec2 = *pattern++ & TRIM; match = (globcharcoll(stringc, rangec2, 0) <= 0 && globcharcoll(rangec, stringc, 0) <= 0); } - else + else match = (stringc == rangec); } if (rangec == '\0') stderror(ERR_NAME | ERR_MISSING, ']'); if ((!match) && (stringc == '\0')) return (0); if (match == negate_range) return (0); break; default: if (cs ? patternc != stringc : Tolower(patternc) != Tolower(stringc)) return (0); break; } } } diff --git a/contrib/tcsh/sh.h b/contrib/tcsh/sh.h index 94f4af236671..3c285a9e8a36 100644 --- a/contrib/tcsh/sh.h +++ b/contrib/tcsh/sh.h @@ -1,1299 +1,1299 @@ /* * sh.h: Catch it all globals and includes file! */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _h_sh #define _h_sh #include "config.h" #include #include #ifdef HAVE_ICONV # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #if !defined(HAVE_STDINT_H) && !defined(HAVE_INTTYPES_H) && !defined(WINNT_NATIVE) typedef unsigned long intptr_t; #endif #ifndef EXTERN # define EXTERN extern #else /* !EXTERN */ # ifdef WINNT_NATIVE # define IZERO = 0 # define IZERO_STRUCT = {0} # endif /* WINNT_NATIVE */ #endif /* EXTERN */ #ifndef IZERO # define IZERO #endif /* IZERO */ #ifndef IZERO_STRUCT # define IZERO_STRUCT #endif /* IZERO_STRUCT */ #ifndef WINNT_NATIVE # define INIT_ZERO # define INIT_ZERO_STRUCT # define force_read xread #endif /*!WINNT_NATIVE */ #if defined(KANJI) && defined(WIDE_STRINGS) && defined(HAVE_NL_LANGINFO) && defined(CODESET) #define AUTOSET_KANJI #endif /* * Sanity */ #if defined(_POSIX_SOURCE) && !defined(POSIX) # define POSIX -#endif +#endif #if defined(POSIXJOBS) && !defined(BSDJOBS) # define BSDJOBS -#endif +#endif #define TMP_TEMPLATE ".XXXXXX" #ifdef SHORT_STRINGS # ifdef WIDE_STRINGS #include # ifdef UTF16_STRINGS typedef wint_t Char; # else typedef wchar_t Char; #endif typedef unsigned long uChar; typedef wint_t eChar; /* Can contain any Char value or CHAR_ERR */ #define CHAR_ERR WEOF /* Pretty please, use bit 31... */ #define normal_mbtowc(PWC, S, N) rt_mbtowc(PWC, S, N) #define reset_mbtowc() TCSH_IGNORE(mbtowc(NULL, NULL, 0)) # else typedef short Char; typedef unsigned short uChar; typedef int eChar; #define CHAR_ERR (-1) #define normal_mbtowc(PWC, S, N) ((void)(N), *(PWC) = (unsigned char)*(S), 1) #define reset_mbtowc() ((void)0) # endif # define SAVE(a) (Strsave(str2short(a))) #else typedef char Char; typedef unsigned char uChar; typedef int eChar; #define CHAR_ERR (-1) #define normal_mbtowc(PWC, S, N) ((void)(N), *(PWC) = (unsigned char)*(S), 1) #define reset_mbtowc() ((void)0) # define SAVE(a) (strsave(a)) #endif #if !defined(__inline) && !defined(__GNUC__) && !defined(_MSC_VER) #define __inline #endif #ifdef _MSC_VER #define TCSH_PTRDIFF_T_FMT "I" #else #define TCSH_PTRDIFF_T_FMT "t" #endif /* Elide unused argument warnings */ #define USE(a) (void) (a) #define TCSH_IGNORE(a) tcsh_ignore((intptr_t)a) static __inline void tcsh_ignore(intptr_t a) { USE(a); } /* * Return true if the path is absolute */ #if defined(WINNT_NATIVE) # define ABSOLUTEP(p) ((p)[0] == '/' || \ (Isalpha((p)[0]) && (p)[1] == ':')) #elif defined(__CYGWIN__) # define ABSOLUTEP(p) ((p)[0] == '/' || \ (Isalpha((p)[0]) && (p)[1] == ':' && \ ((p)[2] == '\0' || (p)[2] == '/'))) #else /* !WINNT_NATIVE && !__CYGWIN__ */ # define ABSOLUTEP(p) (*(p) == '/') #endif /* WINNT_NATIVE || __CYGWIN__ */ /* * Fundamental definitions which may vary from system to system. * * BUFSIZE The i/o buffering size; also limits word size * MAILINTVL How often to mailcheck; more often is more expensive */ #ifdef BUFSIZE # if BUFSIZE < 4096 # undef BUFSIZE # define BUFSIZE 4096 /* buffer size should be no less than this */ # endif #else # define BUFSIZE 4096 #endif /* BUFSIZE */ #define FORKSLEEP 10 /* delay loop on non-interactive fork failure */ #define MAILINTVL 600 /* 10 minutes */ #ifndef INBUFSIZE # define INBUFSIZE 2*BUFSIZE /* Num input characters on the command line */ #endif /* INBUFSIZE */ /* * What our builtin echo looks like */ #define NONE_ECHO 0 #define BSD_ECHO 1 #define SYSV_ECHO 2 #define BOTH_ECHO (BSD_ECHO|SYSV_ECHO) #ifndef ECHO_STYLE # if SYSVREL > 0 # define ECHO_STYLE SYSV_ECHO # else /* SYSVREL == 0 */ # define ECHO_STYLE BSD_ECHO # endif /* SYSVREL */ #endif /* ECHO_STYLE */ /* values for noclobber */ #define NOCLOBBER_DEFAULT 1 #define NOCLOBBER_NOTEMPTY 2 #define NOCLOBBER_ASK 4 /* * The shell moves std in/out/diag and the old std input away from units * 0, 1, and 2 so that it is easy to set up these standards for invoked * commands. */ #define FSAFE 5 /* We keep the first 5 descriptors untouched */ #define FSHTTY 15 /* /dev/tty when manip pgrps */ #define FSHIN 16 /* Preferred desc for shell input */ #define FSHOUT 17 /* ... shell output */ #define FSHDIAG 18 /* ... shell diagnostics */ #define FOLDSTD 19 /* ... old std input */ #ifdef PROF #define xexit(n) done(n) -#endif +#endif #ifdef cray # define word word_t /* sys/types.h defines word.. bad move! */ #endif #include #ifdef cray # undef word -#endif +#endif -/* +/* * Path separator in environment variables */ #ifndef PATHSEP # if defined(__EMX__) || defined(WINNT_NATIVE) # define PATHSEP ';' # else /* unix */ # define PATHSEP ':' # endif /* __EMX__ || WINNT_NATIVE */ #endif /* !PATHSEP */ #if defined(__HP_CXD_SPP) && !defined(__hpux) # include # define stat stat64 # define fstat fstat64 # define lstat lstat64 #endif /* __HP_CXD_SPP && !__hpux */ #ifdef HAVE_LONG_LONG typedef long long tcsh_number_t; #else typedef long tcsh_number_t; #endif /* * This macro compares the st_dev field of struct stat. On aix on ibmESA - * st_dev is a structure, so comparison does not work. + * st_dev is a structure, so comparison does not work. */ #ifndef DEV_DEV_COMPARE # define DEV_DEV_COMPARE(x,y) ((x) == (y)) #endif /* DEV_DEV_COMPARE */ #ifdef _SEQUENT_ # include #endif /* _SEQUENT_ */ #if (defined(POSIX) || SYSVREL > 0) && !defined(WINNT_NATIVE) # include #endif /* (POSIX || SYSVREL > 0) && !WINNT_NATIVE */ #ifdef NLS # include #endif /* NLS */ #if !defined(_MINIX) && !defined(_VMS_POSIX) && !defined(WINNT_NATIVE) && !defined(__MVS__) # include #endif /* !_MINIX && !_VMS_POSIX && !WINNT_NATIVE && !__MVS__ */ #include #if defined(BSDTIMES) || defined(BSDLIMIT) # include # if SYSVREL>3 && !defined(SCO) && !defined(sgi) && !defined(SNI) && !defined(sun) && !(defined(__alpha) && defined(__osf__)) && !defined(_SX) && !defined(__MVS__) # include "/usr/ucbinclude/sys/resource.h" # else # ifdef convex # define sysrusage cvxrusage # include # else # define sysrusage rusage # include # endif /* convex */ # endif /* SYSVREL>3 */ #endif /* BSDTIMES */ #ifndef WINNT_NATIVE # ifndef POSIX # ifdef TERMIO # include # else /* SGTTY */ # include # endif /* TERMIO */ # else /* POSIX */ # ifndef _UWIN # include # else # include # endif /* _UWIN */ # if SYSVREL > 3 || defined(__linux__) # undef TIOCGLTC /* we don't need those, since POSIX has them */ # undef TIOCSLTC # undef CSWTCH # define CSWTCH _POSIX_VDISABLE /* So job control works */ # endif /* SYSVREL > 3 */ # endif /* POSIX */ #endif /* WINNT_NATIVE */ #ifdef sonyrisc # include #endif /* sonyrisc */ #if defined(POSIX) && !defined(WINNT_NATIVE) # include /* * the gcc+protoize version of * redefines malloc(), so we define the following * to avoid it. */ # if defined(SYSMALLOC) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__) || defined(sgi) || defined(_OSD_POSIX) # define NO_FIX_MALLOC # include # else /* glibc */ # define _GNU_STDLIB_H # define malloc __malloc # define free __free # define calloc __calloc # define realloc __realloc # include # undef malloc # undef free # undef calloc # undef realloc # endif /* glibc || sgi */ #endif /* POSIX && !WINNT_NATIVE */ #include #if SYSVREL > 0 || defined(_IBMR2) || defined(_MINIX) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__) # if !defined(pyr) && !defined(stellar) # include # ifdef _MINIX # define HZ CLOCKS_PER_SEC # endif /* _MINIX */ # endif /* !pyr && !stellar */ #endif /* SYSVREL > 0 || _IBMR2 */ /* In the following ifdef the DECOSF1 has been commented so that later * versions of DECOSF1 will get TIOCGWINSZ. This might break older versions... */ #if !((defined(SUNOS4) || defined(_MINIX) /* || defined(DECOSF1) */) && defined(TERMIO)) # if !defined(_VMS_POSIX) && !defined(WINNT_NATIVE) # include # if SYSVREL > 3 || defined(__linux__) # undef TIOCGLTC /* we don't need those, since POSIX has them */ # undef TIOCSLTC # undef CSWTCH # define CSWTCH _POSIX_VDISABLE /* So job control works */ # endif /* SYSVREL > 3 */ # endif -#endif +#endif #if (defined(__DGUX__) && defined(POSIX)) || defined(DGUX) #undef CSWTCH #define CSWTCH _POSIX_VDISABLE #endif #if (!defined(FIOCLEX) && defined(SUNOS4)) || ((SYSVREL == 4) && !defined(_SEQUENT_) && !defined(SCO) && !defined(_SX)) && !defined(__MVS__) # include #endif /* (!FIOCLEX && SUNOS4) || (SYSVREL == 4 && !_SEQUENT_ && !SCO && !_SX ) */ #if !defined(_MINIX) && !defined(supermax) && !defined(WINNT_NATIVE) && !defined(IRIS4D) # include #endif /* !_MINIX && !supermax && !WINNT_NATIVE && !defined(IRIS4D) */ #if !defined(O_RDONLY) || !defined(O_NDELAY) # include -#endif +#endif #include #include #include #ifdef HAVE_DIRENT_H # include #else # ifdef HAVE_NDIR_H # include # else # include # endif # define dirent direct #endif /* HAVE_DIRENT_H */ #ifndef HAVE_STRUCT_DIRENT_D_INO # define d_ino d_fileno #endif #if defined(hpux) || defined(sgi) || defined(OREO) # include /* So the fgetpwent() prototypes work */ #endif /* hpux || sgi || OREO */ #ifndef WINNT_NATIVE #include #include #endif /* WINNT_NATIVE */ #ifdef HAVE_SHADOW_H # include #endif /* HAVE_SHADOW_H */ #ifdef HAVE_AUTH_H # include #endif /* HAVE_AUTH_H */ #if defined(BSD) && !defined(POSIX) # include # define strchr(a, b) index(a, b) # define strrchr(a, b) rindex(a, b) #else # include #endif /* BSD */ /* * IRIX-5.0 has , but most system include files do not * include it yet, so we include it here */ #if defined(sgi) && SYSVREL > 3 # include #endif /* sgi && SYSVREL > 3 */ #ifdef REMOTEHOST # ifdef ISC # undef MAXHOSTNAMELEN /* Busted headers? */ # endif # include # include # include # if (defined(_SS_SIZE) || defined(_SS_MAXSIZE)) && defined(HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY) # if !defined(__APPLE__) /* Damnit, where is getnameinfo() folks? */ # if !defined(sgi) # define INET6 # endif /* sgi */ # endif /* __APPLE__ */ # endif # include /* For struct iovec */ #endif /* REMOTEHOST */ #ifdef PURIFY /* exit normally, allowing purify to trace leaks */ # define _exit exit #endif /* !PURIFY */ /* * ASCII vs. EBCDIC */ #if 'Z' - 'A' == 25 # ifndef IS_ASCII # define IS_ASCII # endif #endif #include "sh.types.h" #if !HAVE_DECL_GETPGRP # ifndef GETPGRP_VOID extern pid_t getpgrp (int); # else extern pid_t getpgrp (void); # endif #endif #ifndef lint typedef ptr_t memalign_t; #else typedef union { char am_char, *am_char_p; short am_short, *am_short_p; int am_int, *am_int_p; long am_long, *am_long_p; float am_float, *am_float_p; double am_double, *am_double_p; } *memalign_t; # define malloc lint_malloc # define free lint_free # define realloc lint_realloc # define calloc lint_calloc -#endif +#endif #ifdef SYSMALLOC # define xmalloc(i) smalloc(i) # define xrealloc(p, i) srealloc(p, i) # define xcalloc(n, s) scalloc(n, s) # define xfree sfree #else # define xmalloc(i) malloc(i) # define xrealloc(p, i) realloc(p, i) # define xcalloc(n, s) calloc(n, s) # define xfree free #endif /* SYSMALLOC */ #include "sh.char.h" #include "sh.err.h" #include "sh.dir.h" #include "sh.proc.h" #include "pathnames.h" /* * C shell * * Bill Joy, UC Berkeley * October, 1978; May 1980 * * Jim Kulp, IIASA, Laxenburg Austria * April, 1980 */ #ifdef HESIOD # include #endif /* HESIOD */ #ifdef REMOTEHOST # include #endif /* REMOTEHOST */ #ifndef MAXHOSTNAMELEN # ifdef HOST_NAME_MAX # define MAXHOSTNAMELEN (HOST_NAME_MAX + 1) # elif defined(SCO) && (SYSVREL > 3) # include # else # define MAXHOSTNAMELEN 256 # endif #endif /* MAXHOSTNAMELEN */ #define eq(a, b) (Strcmp(a, b) == 0) /* globone() flags */ #define G_ERROR 0 /* default action: error if multiple words */ #define G_IGNORE 1 /* ignore the rest of the words */ #define G_APPEND 2 /* make a sentence by cat'ing the words */ /* * Global flags */ EXTERN int chkstop IZERO; /* Warned of stopped jobs... allow exit */ #if (defined(FIOCLEX) && defined(FIONCLEX)) || defined(F_SETFD) # define CLOSE_ON_EXEC #else EXTERN int didcch IZERO; /* Have closed unused fd's for child */ #endif /* (FIOCLEX && FIONCLEX) || F_SETFD */ EXTERN int didfds IZERO; /* Have setup i/o fd's for child */ EXTERN int doneinp IZERO; /* EOF indicator after reset from readc */ EXTERN int exiterr IZERO; /* Exit if error or non-zero exit status */ EXTERN int child IZERO; /* Child shell ... errors cause exit */ EXTERN int haderr IZERO; /* Reset was because of an error */ EXTERN int intty IZERO; /* Input is a tty */ EXTERN int intact IZERO; /* We are interactive... therefore prompt */ EXTERN int justpr IZERO; /* Just print because of :p hist mod */ EXTERN int loginsh IZERO; /* We are a loginsh -> .login/.logout */ EXTERN int neednote IZERO; /* Need to pnotify() */ EXTERN int noexec IZERO; /* Don't execute, just syntax check */ EXTERN int pjobs IZERO; /* want to print jobs if interrupted */ EXTERN int setintr IZERO; /* Set interrupts on/off -> Wait intr... */ EXTERN int handle_interrupt IZERO;/* Are we currently handling an interrupt? */ EXTERN int havhash IZERO; /* path hashing is available */ EXTERN int editing IZERO; /* doing filename expansion and line editing */ EXTERN int noediting IZERO; /* initial $term defaulted to noedit */ EXTERN int bslash_quote IZERO;/* PWP: tcsh-style quoting? (in sh.c) */ EXTERN int anyerror IZERO; /* propagate errors from pipelines/backq */ EXTERN int compat_expr IZERO;/* csh-style expressions? */ EXTERN int isoutatty IZERO; /* is SHOUT a tty */ EXTERN int isdiagatty IZERO;/* is SHDIAG a tty */ EXTERN int is1atty IZERO; /* is file descriptor 1 a tty (didfds mode) */ EXTERN int is2atty IZERO; /* is file descriptor 2 a tty (didfds mode) */ EXTERN int arun IZERO; /* Currently running multi-line-aliases */ EXTERN int implicit_cd IZERO;/* implicit cd enabled?(1=enabled,2=verbose) */ EXTERN int cdtohome IZERO; /* cd without args goes home */ EXTERN int inheredoc IZERO; /* Currently parsing a heredoc */ EXTERN int no_clobber IZERO; /* no clobber enabled? 1=yes 2=notempty, 4=ask*/ /* We received a window change event */ EXTERN volatile sig_atomic_t windowchg IZERO; #if defined(KANJI) && defined(SHORT_STRINGS) && defined(DSPMBYTE) EXTERN int dspmbyte_ls; #endif /* * Global i/o info */ EXTERN Char *arginp IZERO; /* Argument input for sh -c and internal `xx` */ EXTERN int onelflg IZERO; /* 2 -> need line for -t, 1 -> exit on read */ extern Char *ffile; /* Name of shell file for $0 */ extern int dolzero; /* if $?0 should return true... */ extern char *seterr; /* Error message from scanner/parser */ #ifndef errno extern int errno; /* Error from C library routines */ #endif extern int exitset; /* Temp name for << shell files in /tmp, for xfree() */ EXTERN Char *shtemp IZERO; #ifdef BSDTIMES EXTERN struct timeval time0; /* Time at which the shell started */ EXTERN struct sysrusage ru0; #else # ifdef _SEQUENT_ EXTERN timeval_t time0; /* time at which shell started */ EXTERN struct process_stats ru0; # else /* _SEQUENT_ */ # ifndef POSIX EXTERN time_t time0; /* time at which shell started */ # else /* POSIX */ EXTERN clock_t time0; /* time at which shell started */ EXTERN clock_t clk_tck; # endif /* POSIX */ EXTERN struct tms shtimes; /* shell and child times for process timing */ # endif /* _SEQUENT_ */ EXTERN time_t seconds0; #endif /* BSDTIMES */ #ifndef HZ # define HZ 100 /* for division into seconds */ #endif /* * Miscellany */ EXTERN pid_t mainpid; /* pid of the main shell ($$) */ EXTERN Char *doldol; /* Character pid for $$ */ EXTERN pid_t backpid; /* pid of the last background job */ /* * Ideally these should be uid_t, gid_t, pid_t. I cannot do that right now - * cause pid's could be unsigned and that would break our -1 flag, and + * cause pid's could be unsigned and that would break our -1 flag, and * uid_t and gid_t are not defined in all the systems so I would have to * make special cases for them. In the future... */ EXTERN uid_t uid, euid; /* Invokers real and effective */ EXTERN gid_t gid, egid; /* User and group ids */ EXTERN pid_t opgrp, /* Initial pgrp and tty pgrp */ shpgrp, /* Pgrp of shell */ tpgrp; /* Terminal process group */ /* If tpgrp is -1, leave tty alone! */ EXTERN Char *Prompt; /* The actual printed prompt or NULL */ EXTERN Char *RPrompt; /* Right-hand side prompt or NULL */ /* * To be able to redirect i/o for builtins easily, the shell moves the i/o * descriptors it uses away from 0,1,2. * Ideally these should be in units which are closed across exec's * (this saves work) but for version 6, this is not usually possible. * The desired initial values for these descriptors are defined in * sh.local.h. */ EXTERN int SHIN IZERO; /* Current shell input (script) */ EXTERN int SHOUT IZERO; /* Shell output */ EXTERN int SHDIAG IZERO; /* Diagnostic output... shell errs go here */ EXTERN int OLDSTD IZERO; /* Old standard input (def for cmds) */ #if (SYSVREL == 4 && defined(_UTS)) || defined(__linux__) -/* +/* * From: fadden@uts.amdahl.com (Andy McFadden) * we need sigsetjmp for UTS4, but not UTS2.1 */ # define SIGSETJMP #endif /* * Error control * * Errors in scanning and parsing set up an error message to be printed * at the end and complete. Other errors always cause a reset. * Because of source commands and .cshrc we need nested error catches. */ #ifdef SIGSETJMP typedef struct { const char *f; size_t l; sigjmp_buf j; } jmp_buf_t; # define tcsh_setjmp() sigsetjmp(reslab.j, 1) # define tcsh_longjmp() siglongjmp(reslab.j, 1) #else typedef struct { const char *f; size_t l; jmp_buf j; } jmp_buf_t; # define tcsh_setjmp() setjmp(reslab.j) # define tcsh_longjmp() longjmp(reslab.j, 1) #endif #define setexit() (reslab.f = __func__, \ reslab.l = __LINE__, \ tcsh_setjmp()) #ifdef SETJMP_DEBUG # define _reset() xprintf("reset %s %zu\n", reslab.f, reslab.l), \ flush(), tcsh_longjmp() #else # define _reset() tcsh_longjmp() #endif #define getexit(a) (void) ((a) = reslab) #define resexit(a) (void) (reslab = (a)) #define cpybin(a, b) (void) ((a) = (b)) extern jmp_buf_t reslab; EXTERN Char *gointr; /* Label for an onintr transfer */ extern struct sigaction parintr; /* Parents interrupt catch */ extern struct sigaction parterm; /* Parents terminate catch */ /* * Lexical definitions. * * All lexical space is allocated dynamically. * The eighth/sixteenth bit of characters is used to prevent recognition, * and eventually stripped. */ #define META 0200 #define ASCII 0177 #ifdef WIDE_STRINGS /* Implies SHORT_STRINGS */ /* 31st char bit used for 'ing (not 32nd, we want all values nonnegative) */ /* * Notice * * By fix for handling unicode name file, 32nd bit is used. * We need use '&' instead of '> or <' when comparing with INVALID_BYTE etc.. * Cast to uChar is not recommended, * becase Char is 4bytes but uChar is 8bytes on I32LP64. */ # define QUOTE 0x80000000 # define TRIM 0x7FFFFFFF /* Mask to strip quote bit */ # define UNDER 0x08000000 /* Underline flag */ # define BOLD 0x04000000 /* Bold flag */ # define STANDOUT 0x02000000 /* Standout flag */ # define LITERAL 0x01000000 /* Literal character flag */ # define ATTRIBUTES 0x0F000000 /* The bits used for attributes */ # define INVALID_BYTE 0xF0000000 /* Invalid character on input */ # ifdef SOLARIS2 # define CHAR 0x30FFFFFF /* Mask to mask out the character */ # else # define CHAR 0x00FFFFFF /* Mask to mask out the character */ # endif #elif defined (SHORT_STRINGS) # define QUOTE ((Char) 0100000)/* 16nth char bit used for 'ing */ # define TRIM 0073777 /* Mask to strip quote/lit bit */ # define UNDER 0040000 /* Underline flag */ # define BOLD 0020000 /* Bold flag */ # define STANDOUT 0010000 /* Standout flag */ # define LITERAL 0004000 /* Literal character flag */ # define ATTRIBUTES 0074000 /* The bits used for attributes */ # define INVALID_BYTE 0 # define CHAR 0000377 /* Mask to mask out the character */ #else # define QUOTE ((Char) 0200) /* Eighth char bit used for 'ing */ # define TRIM 0177 /* Mask to strip quote bit */ # define UNDER 0000000 /* No extra bits to do both */ # define BOLD 0000000 /* Bold flag */ # define STANDOUT META /* Standout flag */ # define LITERAL 0000000 /* Literal character flag */ # define ATTRIBUTES 0200 /* The bits used for attributes */ # define INVALID_BYTE 0 # define CHAR 0000177 /* Mask to mask out the character */ #endif #define CHAR_DBWIDTH (LITERAL|(LITERAL-1)) # define MAX_UTF32 0x7FFFFFFF /* max UTF32 is U+7FFFFFFF */ EXTERN int AsciiOnly; /* If set only 7 bits expected in characters */ /* * Each level of input has a buffered input structure. * There are one or more blocks of buffered input for each level, * exactly one if the input is seekable and tell is available. * In other cases, the shell buffers enough blocks to keep all loops * in the buffer. * * If (WIDE_STRINGS && cantell), fbobp is always a byte offset, but * (fseekp - fbobp) and (feobp - fbobp) are character offsets (usable for * fbuf indexing). * * If (!cantell), all offsets are character offsets; if (!WIDE_STRINGS), there * is no difference between byte and character offsets. */ EXTERN struct Bin { off_t Bfseekp; /* Seek pointer, generally != lseek() value */ off_t Bfbobp; /* Seekp of beginning of buffers */ off_t Bfeobp; /* Seekp of end of buffers */ int Bfblocks; /* Number of buffer blocks */ Char **Bfbuf; /* The array of buffer blocks */ #ifdef WIDE_STRINGS /* Number of bytes in each character if (cantell) */ unsigned char Bfclens[BUFSIZE + 1]; #endif } B; /* * This structure allows us to seek inside aliases */ struct Ain { int type; #define TCSH_I_SEEK 0 /* Invalid seek */ #define TCSH_A_SEEK 1 /* Alias seek */ #define TCSH_F_SEEK 2 /* File seek */ #define TCSH_E_SEEK 3 /* Eval seek */ union { off_t _f_seek; /* A byte offset if (cantell) */ Char* _c_seek; } fc; #define f_seek fc._f_seek #define c_seek fc._c_seek Char **a_seek; } ; extern int aret; /* Type of last char returned */ #define SEEKEQ(a, b) ((a)->type == (b)->type && \ (a)->f_seek == (b)->f_seek && \ (a)->a_seek == (b)->a_seek) #define fseekp B.Bfseekp #define fbobp B.Bfbobp #define feobp B.Bfeobp #define fblocks B.Bfblocks #define fbuf B.Bfbuf #define fclens B.Bfclens /* * The shell finds commands in loops by reseeking the input * For whiles, in particular, it reseeks to the beginning of the * line the while was on; hence the while placement restrictions. */ EXTERN struct Ain lineloc; EXTERN int cantell; /* Is current source tellable ? */ /* * Input lines are parsed into doubly linked circular * lists of words of the following form. */ struct wordent { Char *word; struct wordent *prev; struct wordent *next; }; /* * During word building, both in the initial lexical phase and * when expanding $ variable substitutions, expansion by `!' and `$' * must be inhibited when reading ahead in routines which are themselves * processing `!' and `$' expansion or after characters such as `\' or in * quotations. The following flags are passed to the getC routines * telling them which of these substitutions are appropriate for the * next character to be returned. */ #define DODOL 1 #define DOEXCL 2 #define DOALL DODOL|DOEXCL /* * Labuf implements a general buffer for lookahead during lexical operations. * Text which is to be placed in the input stream can be stuck here. * We stick parsed ahead $ constructs during initial input, * process id's from `$$', and modified variable values (from qualifiers * during expansion in sh.dol.c) here. */ extern struct Strbuf labuf; EXTERN size_t lap; /* N/A if == labuf.len, index into labuf.s otherwise */ /* * Parser structure * * Each command is parsed to a tree of command structures and * flags are set bottom up during this process, to be propagated down * as needed during the semantics/exeuction pass (sh.sem.c). */ struct command { unsigned char t_dtyp; /* Type of node */ #define NODE_COMMAND 1 /* t_dcom t_drit */ #define NODE_PAREN 2 /* ( t_dspr ) t_drit */ #define NODE_PIPE 3 /* t_dlef | t_drit */ #define NODE_LIST 4 /* t_dlef ; t_drit */ #define NODE_OR 5 /* t_dlef || t_drit */ #define NODE_AND 6 /* t_dlef && t_drit */ unsigned char t_nice; /* Nice value */ #ifdef apollo unsigned char t_systype; /* System environment */ -#endif +#endif unsigned long t_dflg; /* Flags, e.g. F_AMPERSAND|... */ /* save these when re-doing */ #ifndef apollo -#define F_SAVE (F_NICE|F_TIME|F_NOHUP|F_HUP) +#define F_SAVE (F_NICE|F_TIME|F_NOHUP|F_HUP) #else #define F_SAVE (F_NICE|F_TIME|F_NOHUP||F_HUP|F_VER) -#endif +#endif #define F_AMPERSAND (1<<0) /* executes in background */ #define F_APPEND (1<<1) /* output is redirected >> */ #define F_PIPEIN (1<<2) /* input is a pipe */ #define F_PIPEOUT (1<<3) /* output is a pipe */ #define F_NOFORK (1<<4) /* don't fork, last ()ized cmd */ #define F_NOINTERRUPT (1<<5) /* should be immune from intr's */ /* spare */ #define F_STDERR (1<<7) /* redirect unit 2 with unit 1 */ #define F_OVERWRITE (1<<8) /* output was ! */ #define F_READ (1<<9) /* input redirection is << */ #define F_REPEAT (1<<10) /* reexec aft if, repeat,... */ #define F_NICE (1<<11) /* t_nice is meaningful */ #define F_NOHUP (1<<12) /* nohup this command */ #define F_TIME (1<<13) /* time this command */ #define F_BACKQ (1<<14) /* command is in `` */ #define F_HUP (1<<15) /* hup this command */ #ifdef apollo #define F_VER (1<<16) /* execute command under SYSTYPE */ -#endif +#endif union { Char *T_dlef; /* Input redirect word */ struct command *T_dcar; /* Left part of list/pipe */ } L; union { Char *T_drit; /* Output redirect word */ struct command *T_dcdr; /* Right part of list/pipe */ } R; #define t_dlef L.T_dlef #define t_dcar L.T_dcar #define t_drit R.T_drit #define t_dcdr R.T_dcdr Char **t_dcom; /* Command/argument vector */ struct command *t_dspr; /* Pointer to ()'d subtree */ }; /* * The keywords for the parser */ #define TC_BREAK 0 #define TC_BRKSW 1 #define TC_CASE 2 #define TC_DEFAULT 3 #define TC_ELSE 4 #define TC_END 5 #define TC_ENDIF 6 #define TC_ENDSW 7 #define TC_EXIT 8 #define TC_FOREACH 9 #define TC_GOTO 10 #define TC_IF 11 #define TC_LABEL 12 #define TC_LET 13 #define TC_SET 14 #define TC_SWITCH 15 #define TC_TEST 16 #define TC_THEN 17 #define TC_WHILE 18 /* * These are declared here because they want to be * initialized in sh.init.c (to allow them to be made readonly) */ #if defined(hpux) && defined(__STDC__) && !defined(__GNUC__) /* Avoid hpux ansi mode spurious warnings */ typedef void (*bfunc_t) (); #else typedef void (*bfunc_t) (Char **, struct command *); #endif /* hpux && __STDC__ && !__GNUC__ */ extern const struct biltins { const char *bname; bfunc_t bfunct; int minargs, maxargs; } bfunc[]; extern int nbfunc; #ifdef WINNT_NATIVE extern struct biltins nt_bfunc[]; extern int nt_nbfunc; #endif /* WINNT_NATIVE*/ extern int bequiet; extern struct srch { const char *s_name; int s_value; } srchn[]; extern int nsrchn; /* * Structure defining the existing while/foreach loops at this * source level. Loops are implemented by seeking back in the * input. For foreach (fe), the word list is attached here. */ EXTERN struct whyle { struct Ain w_start; /* Point to restart loop */ struct Ain w_end; /* End of loop (0 if unknown) */ Char **w_fe, **w_fe0; /* Current/initial wordlist for fe */ Char *w_fename; /* Name for fe */ struct whyle *w_next; /* Next (more outer) loop */ } *whyles; /* * Variable structure * * Aliases and variables are stored in AVL balanced binary trees. */ EXTERN struct varent { Char **vec; /* Array of words which is the value */ Char *v_name; /* Name of variable/alias */ int v_flags; /* Flags */ #define VAR_ALL -1 #define VAR_READONLY 1 #define VAR_READWRITE 2 #define VAR_NOGLOB 4 #define VAR_FIRST 32 #define VAR_LAST 64 struct varent *v_link[3]; /* The links, see below */ int v_bal; /* Balance factor */ } shvhed IZERO_STRUCT, aliases IZERO_STRUCT; #define v_left v_link[0] #define v_right v_link[1] #define v_parent v_link[2] #define adrof(v) adrof1(v, &shvhed) #define varval(v) value1(v, &shvhed) /* * The following are for interfacing redo substitution in * aliases to the lexical routines. */ EXTERN struct wordent *alhistp IZERO_STRUCT;/* Argument list (first) */ EXTERN struct wordent *alhistt IZERO_STRUCT;/* Node after last in arg list */ EXTERN Char **alvec IZERO_STRUCT, *alvecp IZERO_STRUCT;/* The (remnants of) alias vector */ /* * Filename/command name expansion variables */ #ifndef MAXPATHLEN # ifdef PATH_MAX # define MAXPATHLEN PATH_MAX # else # define MAXPATHLEN 2048 # endif #endif /* MAXPATHLEN */ #ifndef HAVENOLIMIT /* * resource limits */ extern struct limits { int limconst; const char *limname; int limdiv; const char *limscale; } limits[]; #endif /* !HAVENOLIMIT */ /* * History list * * Each history list entry contains an embedded wordlist * from the scanner, a number for the event, and a reference count * to aid in discarding old entries. * * Essentially "invisible" entries are put on the history list * when history substitution includes modifiers, and thrown away * at the next discarding since their event numbers are very negative. */ EXTERN struct Hist { struct wordent Hlex; int Hnum; /* eventno when inserted into history list */ int Href; time_t Htime; Char *histline; struct Hist *Hnext, *Hprev; /* doubly linked list */ unsigned Hhash; /* hash value of command line */ } Histlist IZERO_STRUCT; extern struct wordent paraml; /* Current lexical word list */ EXTERN int eventno; /* Next events number */ EXTERN int lastev; /* Last event reference (default) */ EXTERN Char HIST; /* history invocation character */ EXTERN Char HISTSUB; /* auto-substitute character */ EXTERN Char PRCH; /* Prompt symbol for regular users */ EXTERN Char PRCHROOT; /* Prompt symbol for root */ /* * For operating systems with single case filenames (OS/2) */ #ifdef CASE_INSENSITIVE # ifdef WIDE_STRINGS # define samecase(x) (towlower(x)) # else # define samecase(x) (isupper((unsigned char)(x)) ? \ tolower((unsigned char)(x)) : (x)) # endif #else # define samecase(x) (x) #endif /* CASE_INSENSITIVE */ /* * strings.h: */ #ifndef SHORT_STRINGS #define Strchr(a, b) strchr(a, b) #define Strrchr(a, b) strrchr(a, b) #define Strcat(a, b) strcat(a, b) #define Strncat(a, b, c) strncat(a, b, c) #define Strcpy(a, b) strcpy(a, b) #define Strncpy(a, b, c) strncpy(a, b, c) #define Strlen(a) strlen(a) #define Strcmp(a, b) strcmp(a, b) #define Strncmp(a, b, c) strncmp(a, b, c) #define Strcasecmp(a, b) strcasecmp(a, b) #define Strspl(a, b) strspl(a, b) #define Strnsave(a, b) strnsave(a, b) #define Strsave(a) strsave(a) #define Strend(a) strend(a) #define Strstr(a, b) strstr(a, b) #define str2short(a) (a) #define blk2short(a) saveblk(a) #define short2blk(a) saveblk(a) #define short2str(a) caching_strip(a) #else #if defined(WIDE_STRINGS) && !defined(UTF16_STRINGS) #define Strchr(a, b) wcschr(a, b) #define Strrchr(a, b) wcsrchr(a, b) #define Strcat(a, b) wcscat(a, b) #define Strncat(a, b, c) wcsncat(a, b, c) #define Strcpy(a, b) wcscpy(a, b) #define Strncpy(a, b, c) wcsncpy(a, b, c) #define Strlen(a) wcslen(a) #define Strcmp(a, b) wcscmp(a, b) #define Strncmp(a, b, c) wcsncmp(a, b, c) #else #define Strchr(a, b) s_strchr(a, b) #define Strrchr(a, b) s_strrchr(a, b) #define Strcat(a, b) s_strcat(a, b) #define Strncat(a, b, c) s_strncat(a, b, c) #define Strcpy(a, b) s_strcpy(a, b) #define Strncpy(a, b, c) s_strncpy(a, b, c) #define Strlen(a) s_strlen(a) #define Strcmp(a, b) s_strcmp(a, b) #define Strncmp(a, b, c) s_strncmp(a, b, c) #endif #define Strcasecmp(a, b) s_strcasecmp(a, b) #define Strspl(a, b) s_strspl(a, b) #define Strnsave(a, b) s_strnsave(a, b) #define Strsave(a) s_strsave(a) #define Strend(a) s_strend(a) #define Strstr(a, b) s_strstr(a, b) -#endif +#endif #define TCSH_MODIFIERS "ehlqrstuxQ" /* * setname is a macro to save space (see sh.err.c) */ EXTERN const char *bname; #define setname(a) (bname = (a)) #ifdef VFORK EXTERN Char *Vsav; EXTERN Char *Vdp; EXTERN Char *Vexpath; EXTERN char **Vt; #endif /* VFORK */ EXTERN Char **evalvec; EXTERN Char *evalp; extern struct mesg { const char *iname; /* name from /usr/include */ const char *pname; /* print name */ } mesg[]; /* word_chars is set by default to WORD_CHARS (or WORD_CHARS_VI) but can be overridden by the wordchars variable--if unset, reverts to WORD_CHARS (or WORD_CHARS_VI) */ EXTERN Char *word_chars; #define WORD_CHARS "*?_-.[]~=" /* default chars besides alnums in words */ #define WORD_CHARS_VI "_" /* default chars besides alnums in words */ EXTERN Char *STR_SHELLPATH; #ifdef _PATH_BSHELL EXTERN Char *STR_BSHELL; -#endif +#endif EXTERN Char *STR_WORD_CHARS; EXTERN Char *STR_WORD_CHARS_VI; EXTERN Char **STR_environ IZERO; extern int dont_free; /* Tell free that we are in danger if we free */ extern Char *INVPTR; extern Char **INVPPTR; extern char *progname; extern int tcsh; extern int xlate_cr; extern int output_raw; extern int lbuffed; extern time_t Htime; extern int numeof; extern int insource; extern char linbuf[]; extern char *linp; extern int nsig; #ifdef VFORK extern int use_fork; #endif extern int tellwhat; extern int NoNLSRebind; #if !HAVE_DECL_ENVIRON extern char **environ; #endif #include "tc.h" #ifndef WINNT_NATIVE # ifdef NLS_CATALOGS # ifdef HAVE_FEATURES_H # include # endif # ifdef HAVE_NL_LANGINFO # include # endif # ifdef __uxps__ # define gettxt gettxt_ds # endif # include # ifdef __uxps__ # undef gettxt # endif EXTERN nl_catd catd; # if defined(HAVE_ICONV) && defined(HAVE_NL_LANGINFO) # define CGETS(b, c, d) iconv_catgets(catd, b, c, d) # else # define CGETS(b, c, d) xcatgets(catd, b, c, d) # endif # define CSAVS(b, c, d) strsave(CGETS(b, c, d)) # else # define CGETS(b, c, d) d # define CSAVS(b, c, d) d -# endif +# endif #else /* WINNT_NATIVE */ # define CGETS(b, c, d) nt_cgets( b, c, d) # define CSAVS(b, c, d) strsave(CGETS(b, c, d)) #endif /* WINNT_NATIVE */ #if defined(FILEC) extern int filec; #endif /* FILEC */ #include "sh.decls.h" /* * Since on some machines characters are unsigned, and the signed * keyword is not universally implemented, we treat all characters * as unsigned and sign extend them where we need. */ #define SIGN_EXTEND_CHAR(a) (((a) & 0x80) ? ((a) | ~0x7f) : (a)) /* * explanation for use by the "--help" option */ #define HELP_STRING "\ -b file batch mode, read and execute commands from `file' \n\ -c command run `command' from next argument \n\ -d load directory stack from `~/.cshdirs' \n\ -Dname[=value] define environment variable `name' to `value' (DomainOS only) \n\ -e exit on any error \n\ -f start faster by ignoring the start-up file \n\ -F use fork() instead of vfork() when spawning (ConvexOS only) \n\ -i interactive, even when input is not from a terminal \n\ -l act as a login shell, must be the only option specified \n\ -m load the start-up file, whether or not owned by effective user \n\ -n file no execute mode, just check syntax of the following `file' \n\ -q accept SIGQUIT for running under a debugger \n\ -s read commands from standard input \n\ -t read one line from standard input \n\ -v echo commands after history substitution \n\ -V like -v but including commands read from the start-up file \n\ -x echo commands immediately before execution \n\ -X like -x but including commands read from the start-up file \n\ --help print this message and exit \n\ --version print the version shell variable and exit \n\ \nSee the tcsh(1) manual page for detailed information.\n" #include "tc.nls.h" #endif /* _h_sh */ diff --git a/contrib/tcsh/sh.hist.c b/contrib/tcsh/sh.hist.c index d061f40d8c0e..14d862a3e7bb 100644 --- a/contrib/tcsh/sh.hist.c +++ b/contrib/tcsh/sh.hist.c @@ -1,1373 +1,1385 @@ /* * sh.hist.c: Shell history expansions and substitutions */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include /* for rename(2), grr. */ #include #include "tc.h" #include "dotlock.h" extern int histvalid; extern struct Strbuf histline; Char HistLit = 0; static int heq (const struct wordent *, const struct wordent *); static void hfree (struct Hist *); #define HIST_ONLY 0x01 #define HIST_SAVE 0x02 #define HIST_LOAD 0x04 #define HIST_REV 0x08 #define HIST_CLEAR 0x10 #define HIST_MERGE 0x20 #define HIST_TIME 0x40 /* * C shell */ /* Static functions don't show up in gprof summaries. So eliminate "static" * modifier from some frequently called functions. */ #ifdef PROF #define PG_STATIC #else #define PG_STATIC static #endif /* #define DEBUG_HIST 1 */ static const int fastMergeErase = 1; static unsigned histCount = 0; /* number elements on history list */ static int histlen = 0; static struct Hist *histTail = NULL; /* last element on history list */ static struct Hist *histMerg = NULL; /* last element merged by Htime */ static void insertHistHashTable(struct Hist *, unsigned); /* Insert new element (hp) in history list after specified predecessor (pp). */ static void hinsert(struct Hist *hp, struct Hist *pp) { struct Hist *fp = pp->Hnext; /* following element, if any */ hp->Hnext = fp, hp->Hprev = pp; pp->Hnext = hp; if (fp) fp->Hprev = hp; else histTail = hp; /* meaning hp->Hnext == NULL */ histCount++; } /* Remove the entry from the history list. */ static void hremove(struct Hist *hp) { struct Hist *pp = hp->Hprev; assert(pp); /* elements always have a previous */ pp->Hnext = hp->Hnext; if (hp->Hnext) hp->Hnext->Hprev = pp; else histTail = pp; /* we must have been last */ if (hp == histMerg) /* deleting this hint from list */ histMerg = NULL; assert(histCount > 0); histCount--; } /* Prune length of history list to specified size by history variable. */ PG_STATIC void discardExcess(int hlen) { struct Hist *hp, *np; if (histTail == NULL) { assert(histCount == 0); return; /* no entries on history list */ } /* Prune dummy entries from the front, then old entries from the back. If * the list is still too long scan the whole list as before. But only do a * full scan if the list is more than 6% (1/16th) too long. */ while (histCount > (unsigned)hlen && (np = Histlist.Hnext)) { if (eventno - np->Href >= hlen || hlen == 0) hremove(np), hfree(np); else break; } while (histCount > (unsigned)hlen && (np = histTail) != &Histlist) { if (eventno - np->Href >= hlen || hlen == 0) hremove(np), hfree(np); else break; } if (histCount - (hlen >> 4) <= (unsigned)hlen) return; /* don't bother doing the full scan */ for (hp = &Histlist; histCount > (unsigned)hlen && (np = hp->Hnext) != NULL;) if (eventno - np->Href >= hlen || hlen == 0) hremove(np), hfree(np); else hp = np; } /* Add the command "sp" to the history list. */ void savehist( struct wordent *sp, int mflg) /* true if -m (merge) specified */ { /* throw away null lines */ if (sp && sp->next->word[0] == '\n') return; if (sp) (void) enthist(++eventno, sp, 1, mflg, histlen); discardExcess(histlen); } #define USE_JENKINS_HASH 1 /* #define USE_ONE_AT_A_TIME 1 */ #undef PRIME_LENGTH /* no need for good HTL */ #ifdef USE_JENKINS_HASH #define hashFcnName "lookup3" /* From: lookup3.c, by Bob Jenkins, May 2006, Public Domain. "... You can use this free for any purpose. It's in the public domain. It has no warranty." http://burtleburtle.net/bob/hash/index.html */ #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k)))) #define mix(a,b,c) \ { \ a -= c; a ^= rot(c, 4); c += b; \ b -= a; b ^= rot(a, 6); a += c; \ c -= b; c ^= rot(b, 8); b += a; \ a -= c; a ^= rot(c,16); c += b; \ b -= a; b ^= rot(a,19); a += c; \ c -= b; c ^= rot(b, 4); b += a; \ } #define final(a,b,c) \ { \ c ^= b; c -= rot(b,14); \ a ^= c; a -= rot(c,11); \ b ^= a; b -= rot(a,25); \ c ^= b; c -= rot(b,16); \ a ^= c; a -= rot(c, 4); \ b ^= a; b -= rot(a,14); \ c ^= b; c -= rot(b,24); \ } struct hashValue /* State used to hash a wordend word list. */ { uint32_t a, b, c; }; /* Set up the internal state */ static void initializeHash(struct hashValue *h) { h->a = h->b = h->c = 0xdeadbeef; } /* This does a partial hash of the Chars in a single word. For efficiency we * include 3 versions of the code to pack Chars into 32-bit words for the * mixing function. */ static void addWordToHash(struct hashValue *h, const Char *word) { uint32_t a = h->a, b = h->b, c = h->c; #ifdef SHORT_STRINGS +#define GETK if ((k = (uChar)*word++) == 0) break #ifdef WIDE_STRINGS assert(sizeof(Char) >= 4); while (1) { unsigned k; - if ((k = (uChar)*word++) == 0) break; a += k; - if ((k = (uChar)*word++) == 0) break; b += k; - if ((k = (uChar)*word++) == 0) break; c += k; + GETK; + a += k; + GETK; + b += k; + GETK; + c += k; mix(a, b, c); } #else assert(sizeof(Char) == 2); while (1) { unsigned k; - if ((k = (uChar)*word++) == 0) break; a += k; - if ((k = (uChar)*word++) == 0) break; a += k << 16; - if ((k = (uChar)*word++) == 0) break; b += k; - if ((k = (uChar)*word++) == 0) break; b += k << 16; - if ((k = (uChar)*word++) == 0) break; c += k; - if ((k = (uChar)*word++) == 0) break; c += k << 16; + GETK; + a += k; + GETK; + a += k << 16; + GETK; + b += k; + GETK; + b += k << 16; + GETK; + c += k; + GETK; + c += k << 16; mix(a, b, c); } #endif #else assert(sizeof(Char) == 1); while (1) { unsigned k; if ((k = *word++) == 0) break; a += k; if ((k = *word++) == 0) break; a += k << 8; if ((k = *word++) == 0) break; a += k << 16; if ((k = *word++) == 0) break; a += k << 24; if ((k = *word++) == 0) break; b += k; if ((k = *word++) == 0) break; b += k << 8; if ((k = *word++) == 0) break; b += k << 16; if ((k = *word++) == 0) break; b += k << 24; if ((k = *word++) == 0) break; c += k; if ((k = *word++) == 0) break; c += k << 8; if ((k = *word++) == 0) break; c += k << 16; if ((k = *word++) == 0) break; c += k << 24; mix(a, b, c); } #endif h->a = a, h->b = b, h->c = c; } static void addCharToHash(struct hashValue *h, Char ch) { /* The compiler (gcc -O2) seems to do a good job optimizing this without * explicitly extracting into local variables. */ h->a += (uChar)ch; mix(h->a, h->b, h->c); } static uint32_t finalizeHash(struct hashValue *h) { uint32_t a = h->a, b = h->b, c = h->c; final(a, b, c); return c; } #elif USE_ONE_AT_A_TIME #define hashFcnName "one-at-a-time" /* This one is also from Bob Jenkins, but is slower but simpler than lookup3. "... The code given here are all public domain." http://burtleburtle.net/bob/hash/doobs.html */ #if 0 ub4 one_at_a_time(char *key, ub4 len) { ub4 hash, i; for (hash=0, i=0; i> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return (hash & mask); } #endif struct hashValue { uint32_t h; }; static void initializeHash(struct hashValue *h) { h->h = 0; } static void addWordToHash(struct hashValue *h, const Char *word) { unsigned k; uint32_t hash = h->h; while (k = (uChar)*word++) hash += k, hash += hash << 10, hash ^= hash >> 6; h->h = hash; } static void addCharToHash(struct hashValue *h, Char c) { Char b[2] = { c, 0 }; addWordToHash(h, b); } static uint32_t finalizeHash(struct hashValue *h) { unsigned hash = h->h; hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; } #else #define hashFcnName "add-mul" /* Simple multipy and add hash. */ #define PRIME_LENGTH 1 /* need "good" HTL */ struct hashValue { uint32_t h; }; static void initializeHash(struct hashValue *h) { h->h = 0xe13e2345; } static void addWordToHash(struct hashValue *h, const Char *word) { unsigned k; uint32_t hash = h->h; while (k = (uChar)*word++) hash = hash * 0x9e4167b9 + k; h->h = hash; } static void addCharToHash(struct hashValue *h, Char c) { h->h = h->h * 0x9e4167b9 + (uChar)c; } static uint32_t finalizeHash(struct hashValue *h) { return h->h; } #endif static unsigned hashhist(struct wordent *h0) { struct hashValue s; struct wordent *firstWord = h0->next; struct wordent *h = firstWord; unsigned hash = 0; initializeHash(&s); for (; h != h0; h = h->next) { if (h->word[0] == '\n') break; /* don't hash newline */ if (h != firstWord) addCharToHash(&s, ' '); /* space between words */ addWordToHash(&s, h->word); } hash = finalizeHash(&s); /* Zero means no hash value, so never return zero as a hash value. */ return hash ? hash : 0x7fffffff; /* prime! */ } #if 0 unsigned hashStr(Char *str) { struct hashValue s; initializeHash(&s); addWordToHash(&s, str); return finalizeHash(&s); } #endif #ifdef PRIME_LENGTH /* need good HTL */ #define hash2tableIndex(hash, len) ((hash) % len) #else #define hash2tableIndex(hash, len) ((hash) & (len-1)) #endif /* This code can be enabled to test the above hash functions for speed and * collision avoidance. The testing is enabled by "occasional" calls to * displayHistStats(), see which. */ #ifdef DEBUG_HIST #ifdef BSDTIMES static double doTiming(int start) { static struct timeval beginTime; if (start) { gettimeofday(&beginTime, NULL); return 0.0; } else { struct timeval now; gettimeofday(&now, NULL); return (now.tv_sec-beginTime.tv_sec) + (now.tv_usec-beginTime.tv_usec)/1e6; } } #else static double doTiming(int start) { USE(start); return 0.0; } #endif static void generateHashes(int nChars, unsigned nWords, unsigned samples, unsigned *hashes, unsigned length) { if (nChars < 1) return; nWords = (nWords < 1) ? 1 : (nWords > 4) ? 4 : nWords; Char *number = xmalloc((nChars+nWords)*sizeof(Char)); struct wordent word[4]; struct wordent base = { NULL, &word[0], &word[0] }; word[0].word = number, word[0].next = &base, word[0].prev = &base; unsigned w = 0; /* word number */ /* Generate multiple words of length 2, 3, 5, then all the rest. */ unsigned wBoundaries[4] = { 2-1, 2+3-1, 2+3+5-1, 0 }; /* Ensure the last word has at least 4 Chars in it. */ while (nWords >= 2 && nChars < (wBoundaries[nWords-2]+1) + 4) nWords--; wBoundaries[nWords-1] = 0xffffffff; /* don't end word past this point */ unsigned i; for (i = 0; i 10) break; } } if (i >= samples) sec = doTiming(0); else samples = i; /* number we actually did */ if (sec > 0.01) { xprintf("Hash %d (%d Char %u words) with %s: %d nsec/hash, %d mcps\n", samples, nChars, w+1, hashFcnName, (int)((sec/samples)*1e9), (int)((double)samples*nChars/sec/1e6)); } } #endif /* DEBUG_HIST */ #ifdef DEBUG_HIST static void testHash(void) { static const Char STRtestHashTimings[] = { 't','e','s','t','H','a','s','h','T','i','m','i','n','g','s', 0 }; struct varent *vp = adrof(STRtestHashTimings); if (vp && vp->vec) { unsigned hashes[4]; /* dummy place to put hashes */ Char **vals = vp->vec; while (*vals) { int length = getn(*vals); unsigned words = (length < 5) ? 1 : (length < 25) ? 2 : (length < 75) ? 3 : 4; if (length > 0) generateHashes(length, words, 0, hashes, 4); vals++; } } unsigned length = 1024; #ifdef PRIME_LENGTH /* need good HTL */ length = 1021; #endif unsigned *hashes = xmalloc(length*sizeof(unsigned)); memset(hashes, 0, length*sizeof(unsigned)); /* Compute collision statistics for half full hashes modulo "length". */ generateHashes(4, 1, length/2, hashes, length); /* Evaluate collisions by comparing occupancy rates (mean value 0.5). * One bin for each number of hits. */ unsigned bins[155]; memset(bins, 0, sizeof(bins)); unsigned highest = 0; unsigned i; for (i = 0; i= sizeof(bins)/sizeof(bins[0])) /* clip */ hits = highest = sizeof(bins)/sizeof(bins[0]) - 1; if (hits > highest) highest = hits; bins[hits]++; } xprintf("Occupancy of %d buckets by %d hashes %d Chars %d word with %s\n", length, length/2, 4, 1, hashFcnName); for (i = 0; i <= highest; i++) { xprintf(" %d buckets (%d%%) with %d hits\n", bins[i], bins[i]*100/length, i); } /* Count run lengths to evaluate linear rehashing effectiveness. Estimate * a little corrupted by edge effects. */ memset(bins, 0, sizeof(bins)); highest = 0; for (i = 0; hashes[i] == 0; i++); /* find first occupied bucket */ unsigned run = 0; unsigned rehashed = 0; for (; i 0) hits = 1 && rehashed--; else if (hits > 1) rehashed += hits-1; if (hits) run++; else { /* a real free slot, count it */ if (run >= sizeof(bins)/sizeof(bins[0])) /* clip */ run = highest = sizeof(bins)/sizeof(bins[0]) - 1; if (run > highest) highest = run; bins[run]++; run = 0; } } /* Ignore the partial run at end as we ignored the beginning. */ double merit = 0.0, entries = 0; for (i = 0; i <= highest; i++) { entries += bins[i]*i; /* total hashed objects */ merit += bins[i]*i*i; } xprintf("Rehash collision figure of merit %u (ideal=100), run lengths:\n", (int)(100.0*merit/entries)); for (i = 0; i <= highest; i++) { if (bins[i] != 0) xprintf(" %d runs of length %d buckets\n", bins[i], i); } xfree(hashes); } #endif /* DEBUG_HIST */ /* Compares two word lists for equality. */ static int heq(const struct wordent *a0, const struct wordent *b0) { const struct wordent *a = a0->next, *b = b0->next; for (;;) { if (Strcmp(a->word, b->word) != 0) return 0; a = a->next; b = b->next; if (a == a0) return (b == b0) ? 1 : 0; if (b == b0) return 0; } } /* Renumber entries following p, which we will be deleting. */ PG_STATIC void renumberHist(struct Hist *p) { int n = p->Href; while ((p = p->Hnext)) p->Href = n--; } /* The hash table is implemented as an array of pointers to Hist entries. Each * entry is located in the table using hash2tableIndex() and checking the * following entries in case of a collision (linear rehash). Free entries in * the table are zero (0, NULL, emptyHTE). Deleted entries that cannot yet be * freed are set to one (deletedHTE). The Hist.Hhash member is non-zero iff * the entry is in the hash table. When the hash table get too full, it is * reallocated to be approximately twice the history length (see * getHashTableSize). */ static struct Hist **histHashTable = NULL; static unsigned histHashTableLength = 0; /* number of Hist pointers in table */ static struct Hist * const emptyHTE = NULL; static struct Hist * const deletedHTE = (struct Hist *)1; static struct { unsigned insertCount; unsigned removeCount; unsigned rehashes; int deleted; } hashStats; #ifdef DEBUG_HIST void checkHistHashTable(int print) { unsigned occupied = 0; unsigned deleted = 0; unsigned i; for (i = 0; i= hashStats.removeCount); checkHistHashTable(1); memset(&hashStats, 0, sizeof(hashStats)); if (!doneTest) { testHash(); doneTest = 1; } } #else void displayHistStats(const char *reason) { USE(reason); } #endif static void discardHistHashTable(void) { if (histHashTable == NULL) return; displayHistStats("Discarding"); xfree(histHashTable); histHashTable = NULL; } /* Computes a new hash table size, when the current one is too small. */ static unsigned getHashTableSize(int hlen) { unsigned target = hlen * 2; unsigned e = 5; unsigned size; while ((size = 1< (int)histCount ? hlen : (int)histCount); histHashTable = xmalloc(histHashTableLength * sizeof(struct Hist *)); memset(histHashTable, 0, histHashTableLength * sizeof(struct Hist *)); assert(histHashTable[0] == emptyHTE); /* Now insert all the entries on the history list into the hash table. */ { struct Hist *hp; for (hp = &Histlist; (hp = hp->Hnext) != NULL;) { unsigned lpHash = hashhist(&hp->Hlex); assert(!hp->Hhash || hp->Hhash == lpHash); hp->Hhash = 0; /* force insert to new hash table */ insertHistHashTable(hp, lpHash); } } } /* Insert np into the hash table. We assume that np is already on the * Histlist. The specified hashval matches the new Hist entry but has not yet * been assigned to Hhash (or the element is already on the hash table). */ static void insertHistHashTable(struct Hist *np, unsigned hashval) { unsigned rehashes = 0; unsigned hi = 0; if (!histHashTable) return; if (np->Hhash != 0) { /* already in hash table */ assert(hashval == np->Hhash); return; } assert(np != deletedHTE); /* Find a free (empty or deleted) slot, using linear rehash. */ assert(histHashTable); for (rehashes = 0; ((hi = hash2tableIndex(hashval + rehashes, histHashTableLength)), histHashTable[hi] != emptyHTE && histHashTable[hi] != deletedHTE); rehashes++) { assert(np != histHashTable[hi]); if (rehashes >= histHashTableLength / 10) { /* Hash table is full, so grow it. We assume the create function * will roughly double the size we give it. Create initializes the * new table with everything on the Histlist, so we are done when * it returns. */ #ifdef DEBUG_HIST xprintf("Growing history hash table from %d ...", histHashTableLength); flush(); #endif discardHistHashTable(); createHistHashTable(histHashTableLength); #ifdef DEBUG_HIST xprintf("to %d.\n", histHashTableLength); #endif return; } } /* Might be sensible to grow hash table if rehashes is "too big" here. */ if (histHashTable[hi] == deletedHTE) hashStats.deleted--; histHashTable[hi] = np; np->Hhash = hashval; hashStats.insertCount++; hashStats.rehashes += rehashes; } /* Remove the 'np' entry from the hash table. */ static void removeHistHashTable(struct Hist *np) { unsigned hi = np->Hhash; if (!histHashTable || !hi) return; /* no hash table or not on it */ /* find desired entry */ while ((hi = hash2tableIndex(hi, histHashTableLength)), histHashTable[hi] != emptyHTE) { if (np == histHashTable[hi]) { unsigned i; unsigned deletes = 0; histHashTable[hi] = deletedHTE; /* dummy, but non-zero entry */ /* now peek ahead to see if the dummies are really necessary. */ i = 1; while (histHashTable[hash2tableIndex(hi+i, histHashTableLength)] == deletedHTE) i++; if (histHashTable[hash2tableIndex(hi+i, histHashTableLength)] == emptyHTE) { /* dummies are no longer necessary placeholders. */ deletes = i; while (i-- > 0) { histHashTable[hash2tableIndex(hi+i, histHashTableLength)] = emptyHTE; } } hashStats.deleted += 1 - deletes; /* delta deleted entries */ hashStats.removeCount++; return; } hi++; /* linear rehash */ } assert(!"Hist entry not found in hash table"); } /* Search the history hash table for a command matching lp, using hashval as * its hash value. */ static struct Hist * findHistHashTable(struct wordent *lp, unsigned hashval) { unsigned deleted = 0; /* number of deleted entries skipped */ unsigned hi = hashval; struct Hist *hp; if (!histHashTable) return NULL; while ((hi = hash2tableIndex(hi, histHashTableLength)), (hp = histHashTable[hi]) != emptyHTE) { if (hp == deletedHTE) deleted++; else if (hp->Hhash == hashval && heq(lp, &(hp->Hlex))) return hp; if (deleted > (histHashTableLength>>4)) { /* lots of deletes, so we need a sparser table. */ discardHistHashTable(); createHistHashTable(histHashTableLength); return findHistHashTable(lp, hashval); } hi++; /* linear rehash */ } return NULL; } /* When merge semantics are in use, find the approximate predecessor for the * new entry, so that the Htime entries are decreasing. Return the entry just * before the first entry with equal times, so the caller can check for * duplicates. When pTime is not NULL, use it as a starting point for search, * otherwise search from beginning (largest time value) of history list. */ PG_STATIC struct Hist * mergeInsertionPoint( struct Hist *np, /* new entry to be inserted */ struct Hist *pTime) /* hint about where to insert */ { struct Hist *pp, *p; if (histTail && histTail->Htime >= np->Htime) pTime = histTail; /* new entry goes at the end */ if (histMerg && histMerg != &Histlist && histMerg != Histlist.Hnext) { /* Check above and below previous insertion point, in case we're adding * sequential times in the middle of the list (e.g. history -M). */ if (histMerg->Htime >= np->Htime) pTime = histMerg; else if (histMerg->Hprev->Htime >= np->Htime) pTime = histMerg->Hprev; } if (pTime) { /* With hint, search up the list until Htime is greater. We skip past * the equal ones, too, so our caller can elide duplicates. */ pp = pTime; while (pp != &Histlist && pp->Htime <= np->Htime) pp = pp->Hprev; } else pp = &Histlist; /* Search down the list while current entry's time is too large. */ while ((p = pp->Hnext) && (p->Htime > np->Htime)) pp = p; /* advance insertion point */ /* Remember recent position as hint for next time */ histMerg = pp; return pp; } /* Bubble Hnum & Href in new entry down to pp through earlier part of list. */ PG_STATIC void bubbleHnumHrefDown(struct Hist *np, struct Hist *pp) { struct Hist *p; for (p = Histlist.Hnext; p != pp->Hnext; p = p->Hnext) { /* swap Hnum & Href values of p and np. */ int n = p->Hnum, r = p->Href; p->Hnum = np->Hnum; p->Href = np->Href; np->Hnum = n; np->Href = r; } } /* Enter new command into the history list according to current settings. */ struct Hist * enthist( int event, /* newly incremented global eventno */ struct wordent *lp, int docopy, int mflg, /* true if merge requested */ int hlen) /* -1 if unknown */ { struct Hist *p = NULL, *pp = &Histlist, *pTime = NULL; struct Hist *np; const Char *dp; unsigned lpHash = 0; /* non-zero if hashing entries */ if ((dp = varval(STRhistdup)) != STRNULL) { if (eq(dp, STRerase)) { /* masaoki@akebono.tky.hp.com (Kobayashi Masaoki) */ createHistHashTable(hlen); lpHash = hashhist(lp); assert(lpHash != 0); p = findHistHashTable(lp, lpHash); if (p) { if (Htime != 0 && p->Htime > Htime) Htime = p->Htime; /* If we are merging, and the old entry is at the place we want * to insert the new entry, then remember the place. */ if (mflg && Htime != 0 && p->Hprev->Htime >= Htime) pTime = p->Hprev; if (!fastMergeErase) renumberHist(p); /* Reset Href of subsequent entries */ hremove(p); hfree(p); p = NULL; /* so new entry is allocated below */ } } else if (eq(dp, STRall)) { createHistHashTable(hlen); lpHash = hashhist(lp); assert(lpHash != 0); p = findHistHashTable(lp, lpHash); if (p) /* p!=NULL, only update this entry's Htime below */ eventno--; /* not adding a new event */ } else if (eq(dp, STRprev)) { if (pp->Hnext && heq(lp, &(pp->Hnext->Hlex))) { p = pp->Hnext; eventno--; } } } np = p ? p : xmalloc(sizeof(*np)); /* Pick up timestamp set by lex() in Htime if reading saved history */ if (Htime != 0) { np->Htime = Htime; Htime = 0; } else (void) time(&(np->Htime)); if (p == np) return np; /* reused existing entry */ /* Initialize the new entry. */ np->Hnum = np->Href = event; if (docopy) { copylex(&np->Hlex, lp); if (histvalid) np->histline = Strsave(histline.s); else np->histline = NULL; } else { np->Hlex.next = lp->next; lp->next->prev = &np->Hlex; np->Hlex.prev = lp->prev; lp->prev->next = &np->Hlex; np->histline = NULL; } np->Hhash = 0; /* The head of history list is the default insertion point. If merging, advance insertion point, in pp, according to Htime. */ /* XXX -- In histdup=all, Htime values can be non-monotonic. */ if (mflg) { /* merge according to np->Htime */ pp = mergeInsertionPoint(np, pTime); for (p = pp->Hnext; p && p->Htime == np->Htime; pp = p, p = p->Hnext) { if (heq(&p->Hlex, &np->Hlex)) { eventno--; /* duplicate, so don't add new event */ hfree(np); return (p); } } /* pp is now the last entry with time >= to np. */ if (!fastMergeErase) { /* renumber at end of loadhist */ /* Before inserting np after pp, bubble its Hnum & Href values down * through the earlier part of list. */ bubbleHnumHrefDown(np, pp); } } else pp = &Histlist; /* insert at beginning of history */ hinsert(np, pp); if (lpHash && hlen != 0) /* erase & all modes use hash table */ insertHistHashTable(np, lpHash); else discardHistHashTable(); return (np); } static void hfree(struct Hist *hp) { assert(hp != histMerg); if (hp->Hhash) removeHistHashTable(hp); freelex(&hp->Hlex); if (hp->histline) xfree(hp->histline); xfree(hp); } PG_STATIC void phist(struct Hist *hp, int hflg) { if (hp->Href < 0) return; if (hflg & HIST_ONLY) { int old_output_raw; /* * Control characters have to be written as is (output_raw). * This way one can preserve special characters (like tab) in * the history file. * From: mveksler@vnet.ibm.com (Veksler Michael) */ old_output_raw = output_raw; output_raw = 1; cleanup_push(&old_output_raw, output_raw_restore); if (hflg & HIST_TIME) - /* + /* * Make file entry with history time in format: - * "+NNNNNNNNNN" (10 digits, left padded with ascii '0') + * "+NNNNNNNNNN" (10 digits, left padded with ascii '0') */ xprintf("#+%010lu\n", (unsigned long)hp->Htime); if (HistLit && hp->histline) xprintf("%S\n", hp->histline); else prlex(&hp->Hlex); cleanup_until(&old_output_raw); } else { Char *cp = str2short("%h\t%T\t%R\n"); Char *p; struct varent *vp = adrof(STRhistory); if (vp && vp->vec != NULL && vp->vec[0] && vp->vec[1]) cp = vp->vec[1]; p = tprintf(FMT_HISTORY, cp, NULL, hp->Htime, hp); cleanup_push(p, xfree); for (cp = p; *cp;) xputwchar(*cp++); cleanup_until(p); } } PG_STATIC void dophist(int n, int hflg) { struct Hist *hp; if (setintr) { int old_pintr_disabled; pintr_push_enable(&old_pintr_disabled); cleanup_until(&old_pintr_disabled); } if ((hflg & HIST_REV) == 0) { /* Since the history list is stored most recent first, non-reversing * print needs to print (backwards) up the list. */ if ((unsigned)n >= histCount) hp = histTail; else { for (hp = Histlist.Hnext; --n > 0 && hp->Hnext != NULL; hp = hp->Hnext) ; } if (hp == NULL) return; /* nothing to print */ for (; hp != &Histlist; hp = hp->Hprev) phist(hp, hflg); } else { for (hp = Histlist.Hnext; n-- > 0 && hp != NULL; hp = hp->Hnext) phist(hp, hflg); } } /*ARGSUSED*/ void dohist(Char **vp, struct command *c) { int n, hflg = 0; USE(c); if (getn(varval(STRhistory)) == 0) return; while (*++vp && **vp == '-') { Char *vp2 = *vp; while (*++vp2) switch (*vp2) { case 'c': hflg |= HIST_CLEAR; break; case 'h': hflg |= HIST_ONLY; break; case 'r': hflg |= HIST_REV; break; case 'S': hflg |= HIST_SAVE; break; case 'L': hflg |= HIST_LOAD; break; case 'M': hflg |= HIST_MERGE; break; case 'T': hflg |= HIST_TIME; break; default: stderror(ERR_HISTUS, "chrSLMT"); break; } } if (hflg & HIST_CLEAR) { struct Hist *np, *hp; for (hp = &Histlist; (np = hp->Hnext) != NULL;) hremove(np), hfree(np); } if (hflg & (HIST_LOAD | HIST_MERGE)) loadhist(*vp, (hflg & HIST_MERGE) ? 1 : 0); else if (hflg & HIST_SAVE) rechist(*vp, 1); else { if (*vp) n = getn(*vp); else { n = getn(varval(STRhistory)); } dophist(n, hflg); } } char * fmthist(int fmt, ptr_t ptr) { struct Hist *hp = ptr; char *buf; switch (fmt) { case 'h': return xasprintf("%6d", hp->Hnum); case 'R': if (HistLit && hp->histline) return xasprintf("%S", hp->histline); else { Char *istr, *ip; char *p; istr = sprlex(&hp->Hlex); buf = xmalloc(Strlen(istr) * MB_LEN_MAX + 1); for (p = buf, ip = istr; *ip != '\0'; ip++) p += one_wctomb(p, *ip); *p = '\0'; xfree(istr); return buf; } default: buf = xmalloc(1); buf[0] = '\0'; return buf; } } static void dotlock_cleanup(void* lockpath) { dot_unlock((char*)lockpath); } /* Save history before exiting the shell. */ void -rechist(Char *fname, int ref) +rechist(Char *xfname, int ref) { Char *snum, *rs; int fp, ftmp, oldidfds, ophup_disabled; struct varent *shist; char path[MAXPATHLEN]; struct stat st; + static Char *fname; static Char *dumphist[] = {STRhistory, STRmhT, 0, 0}; - if (fname == NULL && !ref) + if (fname == NULL && !ref) return; + fname = xfname; ophup_disabled = phup_disabled; phup_disabled = 1; /* * If $savehist is just set, we use the value of $history * else we use the value in $savehist */ if (((snum = varval(STRsavehist)) == STRNULL) && ((snum = varval(STRhistory)) == STRNULL)) snum = STRmaxint; if (fname == NULL) { if ((fname = varval(STRhistfile)) == STRNULL) fname = Strspl(varval(STRhome), &STRtildothist[1]); else fname = Strsave(fname); } else fname = globone(fname, G_ERROR); cleanup_push(fname, xfree); /* * The 'savehist merge' feature is intended for an environment * with numerous shells being in simultaneous use. Imagine - * any kind of window system. All these shells 'share' the same - * ~/.history file for recording their command line history. + * any kind of window system. All these shells 'share' the same + * ~/.history file for recording their command line history. * We try to handle the case of multiple shells trying to merge * histories at the same time, by creating semi-unique filenames * and saving the history there first and then trying to rename * them in the proper history file. * * Users that like to nuke their environment require here an atomic * loadhist-creat-dohist(dumphist)-close sequence which is given * by optional lock parameter to savehist. * * jw. - */ + */ /* * We need the didfds stuff before loadhist otherwise * exec in a script will fail to print if merge is set. * From: mveksler@iil.intel.com (Veksler Michael) */ oldidfds = didfds; didfds = 0; if ((shist = adrof(STRsavehist)) != NULL && shist->vec != NULL) { size_t i; int merge = 0, lock = 0; for (i = 1; shist->vec[i]; i++) { if (eq(shist->vec[i], STRmerge)) merge++; if (eq(shist->vec[i], STRlock)) lock++; } if (merge) { jmp_buf_t osetexit; if (lock) { #ifndef WINNT_NATIVE char *lockpath = strsave(short2str(fname)); cleanup_push(lockpath, xfree); /* Poll in 100 miliseconds interval to obtain the lock. */ if ((dot_lock(lockpath, 100) == 0)) cleanup_push(lockpath, dotlock_cleanup); #endif } getexit(osetexit); if (setexit() == 0) loadhist(fname, 1); resexit(osetexit); } } rs = randsuf(); xsnprintf(path, sizeof(path), "%S.%S", fname, rs); xfree(rs); fp = xcreat(path, 0600); if (fp == -1) { didfds = oldidfds; cleanup_until(fname); phup_disabled = ophup_disabled; return; } /* Try to preserve ownership and permissions of the original history file */ #ifndef WINNT_NATIVE if (stat(short2str(fname), &st) != -1) { TCSH_IGNORE(fchown(fp, st.st_uid, st.st_gid)); TCSH_IGNORE(fchmod(fp, st.st_mode)); } #else UNREFERENCED_PARAMETER(st); #endif ftmp = SHOUT; SHOUT = fp; dumphist[2] = snum; dohist(dumphist, NULL); xclose(fp); SHOUT = ftmp; didfds = oldidfds; #ifndef WINNT_NATIVE (void)rename(path, short2str(fname)); #else - (void)ReplaceFile( short2str(fname),path,NULL,0,NULL,NULL); + (void)ReplaceFile(short2str(fname), path, NULL, 0, NULL, NULL); #endif cleanup_until(fname); phup_disabled = ophup_disabled; } /* This is the entry point for loading history data from a file. */ void loadhist(Char *fname, int mflg) { static Char *loadhist_cmd[] = {STRsource, NULL, NULL, NULL}; loadhist_cmd[1] = mflg ? STRmm : STRmh; if (fname != NULL) loadhist_cmd[2] = fname; else if ((fname = varval(STRhistfile)) != STRNULL) loadhist_cmd[2] = fname; else loadhist_cmd[2] = STRtildothist; dosource(loadhist_cmd, NULL); /* During history merging (enthist sees mflg set), we disable management of * Hnum and Href (because fastMergeErase is true). So now reset all the * values based on the final ordering of the history list. */ if (mflg) { int n = eventno; struct Hist *hp = &Histlist; while ((hp = hp->Hnext)) hp->Hnum = hp->Href = n--; } } void sethistory(int n) { histlen = n; discardExcess(histlen); } diff --git a/contrib/tcsh/sh.init.c b/contrib/tcsh/sh.init.c index 931ed9feb450..997b94108338 100644 --- a/contrib/tcsh/sh.init.c +++ b/contrib/tcsh/sh.init.c @@ -1,1069 +1,1069 @@ /* * sh.init.c: Function and signal tables */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include "tw.h" /* * C shell */ #define INF INT_MAX const struct biltins bfunc[] = { { ":", dozip, 0, INF }, { "@", dolet, 0, INF }, { "alias", doalias, 0, INF }, { "alloc", showall, 0, 1 }, #if defined(_CX_UX) { "att", doatt, 0, INF }, #endif /* _CX_UX */ { "bg", dobg, 0, INF }, { "bindkey", dobindkey, 0, 8 }, { "break", dobreak, 0, 0 }, { "breaksw", doswbrk, 0, 0 }, #ifdef _OSD_POSIX { "bs2cmd", dobs2cmd, 1, INF }, #endif /* OBSOLETE */ { "builtins", dobuiltins, 0, 0 }, #ifdef KAI { "bye", goodbye, 0, 0 }, #endif /* KAI */ { "case", dozip, 0, 1 }, { "cd", dochngd, 0, INF }, { "chdir", dochngd, 0, INF }, { "complete", docomplete, 0, INF }, { "continue", docontin, 0, 0 }, { "default", dozip, 0, 0 }, { "dirs", dodirs, 0, INF }, #if defined(_CRAY) && !defined(_CRAYMPP) { "dmmode", dodmmode, 0, 1 }, #endif /* _CRAY && !_CRAYMPP */ { "echo", doecho, 0, INF }, { "echotc", doechotc, 0, INF }, { "else", doelse, 0, INF }, { "end", doend, 0, 0 }, { "endif", dozip, 0, 0 }, { "endsw", dozip, 0, 0 }, { "eval", doeval, 0, INF }, { "exec", execash, 1, INF }, { "exit", doexit, 0, INF }, { "fg", dofg, 0, INF }, { "filetest", dofiletest, 2, INF }, { "foreach", doforeach, 3, INF }, #ifdef TCF { "getspath", dogetspath, 0, 0 }, { "getxvers", dogetxvers, 0, 0 }, #endif /* TCF */ { "glob", doglob, 0, INF }, { "goto", dogoto, 1, 1 }, { "hashstat", hashstat, 0, 0 }, { "history", dohist, 0, 2 }, { "hup", dohup, 0, INF }, { "if", doif, 1, INF }, #ifdef apollo { "inlib", doinlib, 1, INF }, #endif /* apollo */ { "jobs", dojobs, 0, 1 }, { "kill", dokill, 1, INF }, #ifndef HAVENOLIMIT { "limit", dolimit, 0, 3 }, #endif /* !HAVENOLIMIT */ #ifdef OBSOLETE { "linedit", doecho, 0, INF }, #endif /* OBSOLETE */ #if !defined(HAVENOUTMP) && !defined(KAI) { "log", dolog, 0, 0 }, #endif /* !HAVENOUTMP && !KAI */ { "login", dologin, 0, 1 }, { "logout", dologout, 0, 0 }, { "ls-F", dolist, 0, INF }, #ifdef TCF { "migrate", domigrate, 1, INF }, #endif /* TCF */ #ifdef NEWGRP { "newgrp", donewgrp, 0, 2 }, #endif /* NEWGRP */ { "nice", donice, 0, INF }, { "nohup", donohup, 0, INF }, { "notify", donotify, 0, INF }, { "onintr", doonintr, 0, 2 }, { "popd", dopopd, 0, INF }, { "printenv", doprintenv, 0, 1 }, { "pushd", dopushd, 0, INF }, { "rehash", dohash, 0, 3 }, { "repeat", dorepeat, 2, INF }, #ifdef apollo { "rootnode", dorootnode, 1, 1 }, #endif /* apollo */ { "sched", dosched, 0, INF }, { "set", doset, 0, INF }, { "setenv", dosetenv, 0, 2 }, #ifdef MACH { "setpath", dosetpath, 0, INF }, #endif /* MACH */ #ifdef TCF { "setspath", dosetspath, 1, INF }, #endif /* TCF */ { "settc", dosettc, 2, 2 }, { "setty", dosetty, 0, INF }, #ifdef TCF { "setxvers", dosetxvers, 0, 1 }, #endif /* TCF */ { "shift", shift, 0, 1 }, { "source", dosource, 1, INF }, { "stop", dostop, 1, INF }, { "suspend", dosuspend, 0, 0 }, { "switch", doswitch, 1, INF }, { "telltc", dotelltc, 0, INF }, #ifndef WINNT_NATIVE { "termname", dotermname, 0, 1 }, #endif { "time", dotime, 0, INF }, #if defined(_CX_UX) { "ucb", doucb, 0, INF }, #endif /* _CX_UX */ { "umask", doumask, 0, 1 }, { "unalias", unalias, 1, INF }, { "uncomplete", douncomplete, 1, INF }, { "unhash", dounhash, 0, 0 }, #if defined(masscomp) || defined(_CX_UX) { "universe", douniverse, 0, INF }, #endif /* masscomp || _CX_UX */ #ifndef HAVENOLIMIT { "unlimit", dounlimit, 0, INF }, #endif /* !HAVENOLIMIT */ { "unset", unset, 1, INF }, { "unsetenv", dounsetenv, 1, INF }, #ifdef apollo { "ver", dover, 0, INF }, #endif /* apollo */ { "wait", dowait, 0, 0 }, #ifdef WARP { "warp", dowarp, 0, 2 }, #endif /* WARP */ #if !defined(HAVENOUTMP) && defined(KAI) { "watchlog", dolog, 0, 0 }, #endif /* !HAVENOUTMP && KAI */ { "where", dowhere, 1, INF }, { "which", dowhich, 1, INF }, { "while", dowhile, 1, INF } }; int nbfunc = sizeof bfunc / sizeof *bfunc; struct srch srchn[] = { { "@", TC_LET }, { "break", TC_BREAK }, { "breaksw", TC_BRKSW }, { "case", TC_CASE }, { "default", TC_DEFAULT }, { "else", TC_ELSE }, { "end", TC_END }, { "endif", TC_ENDIF }, { "endsw", TC_ENDSW }, { "exit", TC_EXIT }, { "foreach", TC_FOREACH }, { "goto", TC_GOTO }, { "if", TC_IF }, { "label", TC_LABEL }, { "set", TC_SET }, { "switch", TC_SWITCH }, { "while", TC_WHILE } }; int nsrchn = sizeof srchn / sizeof *srchn; /* * Note: For some machines, (hpux eg.) * NSIG = number of signals + 1... - * so we define 33 or 65 (POSIX) signals for + * so we define 33 or 65 (POSIX) signals for * everybody */ /* We define NUMSIG to avoid changing NSIG or MAXSIG */ #if defined(POSIX) && (!defined(__CYGWIN__) || defined (__x86_64__)) # define NUMSIG 65 #else /* !POSIX */ # define NUMSIG 33 #endif /* POSIX */ int nsig = NUMSIG - 1; /* This should be the number of real signals */ /* not counting signal 0 */ struct mesg mesg[NUMSIG]; /* Arrays start at [0] so we initialize from */ /* 0 to 32 or 64, the max real signal number */ void mesginit(void) { #ifdef NLS_CATALOGS int i; for (i = 0; i < NUMSIG; i++) { xfree((char *)(intptr_t)mesg[i].pname); mesg[i].pname = NULL; } #endif /* NLS_CATALOGS */ #if defined(SIGNULL) || defined(DECOSF1) # ifndef SIGNULL # define SIGNULL 0 # endif /* !SIGNULL */ if (mesg[SIGNULL].pname == NULL) { mesg[SIGNULL].iname = "NULL"; mesg[SIGNULL].pname = CSAVS(2, 1, "Null signal"); } #endif /* SIGNULL || DECOSF1 */ #ifdef SIGHUP if (mesg[SIGHUP].pname == NULL) { - mesg[SIGHUP].iname = "HUP"; + mesg[SIGHUP].iname = "HUP"; mesg[SIGHUP].pname = CSAVS(2, 2, "Hangup"); } #endif /* SIGHUP */ #ifdef SIGINT if (mesg[SIGINT].pname == NULL) { mesg[SIGINT].iname = "INT"; mesg[SIGINT].pname = CSAVS(2, 3, "Interrupt"); } #endif /* SIGINT */ #ifdef SIGQUIT if (mesg[SIGQUIT].pname == NULL) { mesg[SIGQUIT].iname = "QUIT"; mesg[SIGQUIT].pname = CSAVS(2, 4, "Quit"); } #endif /* SIGQUIT */ #ifdef SIGILL if (mesg[SIGILL].pname == NULL) { mesg[SIGILL].iname = "ILL"; mesg[SIGILL].pname = CSAVS(2, 5, "Illegal instruction"); } #endif /* SIGILL */ #ifdef SIGTRAP if (mesg[SIGTRAP].pname == NULL) { mesg[SIGTRAP].iname = "TRAP"; mesg[SIGTRAP].pname = CSAVS(2, 6, "Trace/BPT trap"); } #endif /* SIGTRAP */ #ifdef SIGABRT if (mesg[SIGABRT].pname == NULL) { mesg[SIGABRT].iname = "ABRT"; mesg[SIGABRT].pname = CSAVS(2, 7, "Abort"); } #endif /* SIGABRT */ #ifdef SIGIOT if (mesg[SIGIOT].pname == NULL) { mesg[SIGIOT].iname = "IOT"; mesg[SIGIOT].pname = CSAVS(2, 8, "IOT trap"); } #endif /* SIGIOT */ #ifdef SIGDANGER /* aiws */ if (mesg[SIGDANGER].pname == NULL) { mesg[SIGDANGER].iname = "DANGER"; mesg[SIGDANGER].pname = CSAVS(2, 9, "System Crash Imminent"); } #endif /* SIGDANGER */ #ifdef SIGERR /* _CRAY */ if (mesg[SIGERR].pname == NULL) { mesg[SIGERR].iname = "ERR"; mesg[SIGERR].pname = CSAVS(2, 10, "Error exit"); } #endif /* SIGERR */ #ifdef SIGEMT if (mesg[SIGEMT].pname == NULL) { mesg[SIGEMT].iname = "EMT"; mesg[SIGEMT].pname = CSAVS(2, 11, "EMT trap"); } #endif /* SIGEMT */ #ifdef SIGFPE if (mesg[SIGFPE].pname == NULL) { mesg[SIGFPE].iname = "FPE"; mesg[SIGFPE].pname = CSAVS(2, 12, "Floating exception"); } #endif /* SIGFPE */ #ifdef SIGKILL if (mesg[SIGKILL].pname == NULL) { mesg[SIGKILL].iname = "KILL"; mesg[SIGKILL].pname = CSAVS(2, 13, "Killed"); } #endif /* SIGKILL */ #ifdef SIGUSR1 if (mesg[SIGUSR1].pname == NULL) { mesg[SIGUSR1].iname = "USR1"; mesg[SIGUSR1].pname = CSAVS(2, 14, "User signal 1"); } #endif /* SIGUSR1 */ #ifdef SIGUSR2 if (mesg[SIGUSR2].pname == NULL) { mesg[SIGUSR2].iname = "USR2"; mesg[SIGUSR2].pname = CSAVS(2, 15, "User signal 2"); } #endif /* SIGUSR2 */ #ifdef SIGSEGV if (mesg[SIGSEGV].pname == NULL) { mesg[SIGSEGV].iname = "SEGV"; mesg[SIGSEGV].pname = CSAVS(2, 16, "Segmentation fault"); } #endif /* SIGSEGV */ #ifdef SIGBUS if (mesg[SIGBUS].pname == NULL) { mesg[SIGBUS].iname = "BUS"; mesg[SIGBUS].pname = CSAVS(2, 17, "Bus error"); } #endif /* SIGBUS */ #ifdef SIGPRE /* _CRAY || IBMAIX */ if (mesg[SIGPRE].pname == NULL) { mesg[SIGPRE].iname = "PRE"; mesg[SIGPRE].pname = CSAVS(2, 18, "Program range error"); } #endif /* SIGPRE */ #ifdef SIGORE /* _CRAY */ if (mesg[SIGORE].pname == NULL) { mesg[SIGORE].iname = "ORE"; mesg[SIGORE].pname = CSAVS(2, 19, "Operand range error"); } #endif /* SIGORE */ #ifdef SIGSYS if (mesg[SIGSYS].pname == NULL) { mesg[SIGSYS].iname = "SYS"; mesg[SIGSYS].pname = CSAVS(2, 20, "Bad system call"); } #endif /* SIGSYS */ #ifdef SIGPIPE if (mesg[SIGPIPE].pname == NULL) { mesg[SIGPIPE].iname = "PIPE"; mesg[SIGPIPE].pname = CSAVS(2, 21, "Broken pipe"); } #endif /* SIGPIPE */ #ifdef SIGALRM if (mesg[SIGALRM].pname == NULL) { mesg[SIGALRM].iname = "ALRM"; mesg[SIGALRM].pname = CSAVS(2, 22, "Alarm clock"); } #endif /* SIGALRM */ #ifdef SIGTERM if (mesg[SIGTERM].pname == NULL) { mesg[SIGTERM].iname = "TERM"; mesg[SIGTERM].pname = CSAVS(2, 23, "Terminated"); } #endif /* SIGTERM */ /* SIGCLD vs SIGCHLD */ #if !defined(SIGCHLD) || defined(SOLARIS2) || defined(apollo) || defined(__EMX__) /* If we don't define SIGCHLD, or our OS prefers SIGCLD to SIGCHLD, */ /* check for SIGCLD */ # ifdef SIGCLD if (mesg[SIGCLD].pname == NULL) { mesg[SIGCLD].iname = "CLD"; # ifdef BSDJOBS mesg[SIGCLD].pname = CSAVS(2, 24, "Child status change"); # else /* !BSDJOBS */ mesg[SIGCLD].pname = CSAVS(2, 25, "Death of child"); # endif /* BSDJOBS */ } # endif /* SIGCLD */ #else /* !(!SIGCHLD || SOLARIS2 || apollo || __EMX__) */ /* We probably define SIGCHLD */ # ifdef SIGCHLD if (mesg[SIGCHLD].pname == NULL) { mesg[SIGCHLD].iname = "CHLD"; # ifdef BSDJOBS mesg[SIGCHLD].pname = CSAVS(2, 27, "Child stopped or exited"); # else /* !BSDJOBS */ mesg[SIGCHLD].pname = CSAVS(2, 28, "Child exited"); # endif /* BSDJOBS */ } # endif /* SIGCHLD */ #endif /* !SIGCHLD || SOLARIS2 || apollo || __EMX__ */ #ifdef SIGAPOLLO /* apollo */ if (mesg[SIGAPOLLO].pname == NULL) { mesg[SIGAPOLLO].iname = "APOLLO"; mesg[SIGAPOLLO].pname = CSAVS(2, 26, "Apollo-specific fault"); } #endif /* SIGAPOLLO */ #ifdef SIGPWR if (mesg[SIGPWR].pname == NULL) { mesg[SIGPWR].iname = "PWR"; mesg[SIGPWR].pname = CSAVS(2, 29, "Power failure"); } #endif /* SIGPWR */ #ifdef SIGLOST if (mesg[SIGLOST].pname == NULL) { mesg[SIGLOST].iname = "LOST"; mesg[SIGLOST].pname = CSAVS(2, 30, "Resource Lost"); } #endif /* SIGLOST */ #ifdef SIGBREAK /* __EMX__ */ if (mesg[SIGBREAK].pname == NULL) { mesg[SIGBREAK].iname = "BREAK"; mesg[SIGBREAK].pname = CSAVS(2, 31, "Break (Ctrl-Break)"); } #endif /* SIGBREAK */ #ifdef SIGIO # if !defined(SIGPOLL) || SIGPOLL != SIGIO if (mesg[SIGIO].pname == NULL) { mesg[SIGIO].iname = "IO"; # ifdef cray mesg[SIGIO].pname = CSAVS(2, 32, "Input/output possible signal"); # else /* !cray */ mesg[SIGIO].pname = CSAVS(2, 33, "Asynchronous I/O (select)"); # endif /* cray */ } # endif /* !SIGPOLL || SIGPOLL != SIGIO */ #endif /* SIGIO */ #ifdef SIGURG if (mesg[SIGURG].pname == NULL) { mesg[SIGURG].iname = "URG"; mesg[SIGURG].pname = CSAVS(2, 34, "Urgent condition on I/O channel"); } #endif /* SIGURG */ #ifdef SIGMT /* cray */ if (mesg[SIGMT].pname == NULL) { mesg[SIGMT].iname = "MT"; mesg[SIGMT].pname = CSAVS(2, 35, "Multitasking wake-up"); } #endif /* SIGMT */ #ifdef SIGMTKILL /* cray */ if (mesg[SIGMTKILL].pname == NULL) { mesg[SIGMTKILL].iname = "MTKILL"; mesg[SIGMTKILL].pname = CSAVS(2, 36, "Multitasking kill"); } #endif /* SIGMTKILL */ #ifdef SIGBUFIO /* _CRAYCOM */ if (mesg[SIGBUFIO].pname == NULL) { mesg[SIGBUFIO].iname = "BUFIO"; mesg[SIGBUFIO].pname = CSAVS(2, 37, "Fortran asynchronous I/O completion"); } #endif /* SIGBUFIO */ #ifdef SIGRECOVERY /* _CRAYCOM */ if (mesg[SIGRECOVERY].pname == NULL) { mesg[SIGRECOVERY].iname = "RECOVERY"; mesg[SIGRECOVERY].pname = CSAVS(2, 38, "Recovery"); } #endif /* SIGRECOVERY */ #ifdef SIGUME /* _CRAYCOM */ if (mesg[SIGUME].pname == NULL) { mesg[SIGUME].iname = "UME"; mesg[SIGUME].pname = CSAVS(2, 39, "Uncorrectable memory error"); } #endif /* SIGUME */ #ifdef SIGCPULIM /* _CRAYCOM */ if (mesg[SIGCPULIM].pname == NULL) { mesg[SIGCPULIM].iname = "CPULIM"; mesg[SIGCPULIM].pname = CSAVS(2, 40, "CPU time limit exceeded"); } #endif /* SIGCPULIM */ #ifdef SIGSHUTDN /* _CRAYCOM */ if (mesg[SIGSHUTDN].pname == NULL) { mesg[SIGSHUTDN].iname = "SHUTDN"; mesg[SIGSHUTDN].pname = CSAVS(2, 41, "System shutdown imminent"); } #endif /* SIGSHUTDN */ #ifdef SIGNOWAK /* _CRAYCOM */ if (mesg[SIGNOWAK].pname == NULL) { mesg[SIGNOWAK].iname = "NOWAK"; mesg[SIGNOWAK].pname = CSAVS(2, 42, "Micro-tasking group-no wakeup flag set"); } #endif /* SIGNOWAK */ #ifdef SIGTHERR /* _CRAYCOM */ if (mesg[SIGTHERR].pname == NULL) { mesg[SIGTHERR].iname = "THERR"; - mesg[SIGTHERR].pname = CSAVS(2, 43, + mesg[SIGTHERR].pname = CSAVS(2, 43, "Thread error - (use cord -T for detailed info)"); } #endif /* SIGTHERR */ #ifdef SIGRPE /* cray */ if (mesg[SIGRPE].pname == NULL) { mesg[SIGRPE].pname = CSAVS(2, 44, "CRAY Y-MP register parity error"); mesg[SIGRPE].iname = "RPE"; } #endif /* SIGRPE */ #ifdef SIGINFO if (mesg[SIGINFO].pname == NULL) { mesg[SIGINFO].iname = "INFO"; mesg[SIGINFO].pname = CSAVS(2, 45, "Information request"); } #endif /* SIGINFO */ #ifdef SIGSTOP if (mesg[SIGSTOP].pname == NULL) { mesg[SIGSTOP].iname = "STOP"; # ifdef SUSPENDED mesg[SIGSTOP].pname = CSAVS(2, 46, "Suspended (signal)"); # else /* !SUSPENDED */ mesg[SIGSTOP].pname = CSAVS(2, 47, "Stopped (signal)"); # endif /* SUSPENDED */ } #endif /* SIGSTOP */ #ifdef SIGTSTP if (mesg[SIGTSTP].pname == NULL) { mesg[SIGTSTP].iname = "TSTP"; # ifdef SUSPENDED mesg[SIGTSTP].pname = CSAVS(2, 48, "Suspended"); # else /* !SUSPENDED */ mesg[SIGTSTP].pname = CSAVS(2, 49, "Stopped"); # endif /* SUSPENDED */ } #endif /* SIGTSTP */ #ifdef SIGCONT if (mesg[SIGCONT].pname == NULL) { mesg[SIGCONT].iname = "CONT"; mesg[SIGCONT].pname = CSAVS(2, 50, "Continued"); } #endif /* SIGCONT */ #ifdef SIGTTIN if (mesg[SIGTTIN].pname == NULL) { mesg[SIGTTIN].iname = "TTIN"; # ifdef SUSPENDED mesg[SIGTTIN].pname = CSAVS(2, 51, "Suspended (tty input)"); # else /* !SUSPENDED */ mesg[SIGTTIN].pname = CSAVS(2, 52, "Stopped (tty input)"); # endif /* SUSPENDED */ } #endif /* SIGTTIN */ #ifdef SIGTTOU if (mesg[SIGTTOU].pname == NULL) { mesg[SIGTTOU].iname = "TTOU"; # ifdef SUSPENDED mesg[SIGTTOU].pname = CSAVS(2, 53, "Suspended (tty output)"); # else /* SUSPENDED */ mesg[SIGTTOU].pname = CSAVS(2, 54, "Stopped (tty output)"); # endif /* SUSPENDED */ } #endif /* SIGTTOU */ #ifdef SIGWIND /* UNIXPC */ if (mesg[SIGWIND].pname == NULL) { mesg[SIGWIND].iname = "WIND"; mesg[SIGWIND].pname = CSAVS(2, 55, "Window status changed"); } #endif /* SIGWIND */ #ifdef SIGWINDOW if (mesg[SIGWINDOW].pname == NULL) { mesg[SIGWINDOW].iname = "WINDOW"; mesg[SIGWINDOW].pname = CSAVS(2, 56, "Window size changed"); } #endif /* SIGWINDOW */ #ifdef SIGWINCH if (mesg[SIGWINCH].pname == NULL) { mesg[SIGWINCH].iname = "WINCH"; mesg[SIGWINCH].pname = CSAVS(2, 56, "Window size changed"); } #endif /* SIGWINCH */ #ifdef SIGPHONE /* UNIXPC */ if (mesg[SIGPHONE].pname == NULL) { mesg[SIGPHONE].iname = "PHONE"; mesg[SIGPHONE].pname = CSAVS(2, 57, "Phone status changed"); } # endif /* SIGPHONE */ #ifdef SIGXCPU if (mesg[SIGXCPU].pname == NULL) { mesg[SIGXCPU].iname = "XCPU"; mesg[SIGXCPU].pname = CSAVS(2, 58, "Cputime limit exceeded"); } #endif /* SIGXCPU */ #ifdef SIGXFSZ if (mesg[SIGXFSZ].pname == NULL) { mesg[SIGXFSZ].iname = "XFSZ"; mesg[SIGXFSZ].pname = CSAVS(2, 59, "Filesize limit exceeded"); } #endif /* SIGXFSZ */ #ifdef SIGVTALRM if (mesg[SIGVTALRM].pname == NULL) { mesg[SIGVTALRM].iname = "VTALRM"; mesg[SIGVTALRM].pname = CSAVS(2, 60, "Virtual time alarm"); } #endif /* SIGVTALRM */ #ifdef SIGPROF if (mesg[SIGPROF].pname == NULL) { mesg[SIGPROF].iname = "PROF"; mesg[SIGPROF].pname = CSAVS(2, 61, "Profiling time alarm"); } #endif /* SIGPROF */ #ifdef SIGDIL /* hpux */ if (mesg[SIGDIL].pname == NULL) { mesg[SIGDIL].iname = "DIL"; mesg[SIGDIL].pname = CSAVS(2, 62, "DIL signal"); } #endif /* SIGDIL */ #ifdef SIGPOLL if (mesg[SIGPOLL].pname == NULL) { mesg[SIGPOLL].iname = "POLL"; mesg[SIGPOLL].pname = CSAVS(2, 63, "Pollable event occured"); } #endif /* SIGPOLL */ #ifdef SIGWAITING /* solaris */ if (mesg[SIGWAITING].pname == NULL) { mesg[SIGWAITING].iname = "WAITING"; mesg[SIGWAITING].pname = CSAVS(2, 64, "Process's lwps are blocked"); } #endif /* SIGWAITING */ #ifdef SIGLWP /* solaris */ if (mesg[SIGLWP].pname == NULL) { mesg[SIGLWP].iname = "LWP"; mesg[SIGLWP].pname = CSAVS(2, 65, "Special LWP signal"); } #endif /* SIGLWP */ #ifdef SIGFREEZE /* solaris */ if (mesg[SIGFREEZE].pname == NULL) { mesg[SIGFREEZE].iname = "FREEZE"; mesg[SIGFREEZE].pname = CSAVS(2, 66, "Special CPR Signal"); } #endif /* SIGFREEZE */ #ifdef SIGTHAW /* solaris */ if (mesg[SIGTHAW].pname == NULL) { mesg[SIGTHAW].iname = "THAW"; mesg[SIGTHAW].pname = CSAVS(2, 67, "Special CPR Signal"); } #endif /* SIGTHAW */ #ifdef SIGCANCEL /* solaris */ if (mesg[SIGCANCEL].pname == NULL) { mesg[SIGCANCEL].iname = "CANCEL"; - mesg[SIGCANCEL].pname = CSAVS(2, 109, + mesg[SIGCANCEL].pname = CSAVS(2, 109, "Thread cancellation signal used by libthread"); } #endif /* SIGCANCEL */ /* * Careful, some OS's (HP/UX 10.0) define these as -1 */ -#ifdef SIGRTMIN +#ifdef SIGRTMIN /* * Cannot do this at compile time; Solaris2 uses _sysconf for these */ - if (SIGRTMIN > 0 && SIGRTMIN < NUMSIG) { + if (SIGRTMIN > 0 && SIGRTMIN < NUMSIG) { if (mesg[SIGRTMIN].pname == NULL) { mesg[SIGRTMIN].iname = "RTMIN"; mesg[SIGRTMIN].pname = CSAVS(2, 68, "First Realtime Signal"); } if (SIGRTMIN + 1 < SIGRTMAX && SIGRTMIN + 1 < NUMSIG && mesg[SIGRTMIN+1].pname == NULL) { mesg[SIGRTMIN+1].iname = "RTMIN+1"; mesg[SIGRTMIN+1].pname = CSAVS(2, 69, "Second Realtime Signal"); } if (SIGRTMIN + 2 < SIGRTMAX && SIGRTMIN + 2 < NUMSIG && mesg[SIGRTMIN+2].pname == NULL) { mesg[SIGRTMIN+2].iname = "RTMIN+2"; mesg[SIGRTMIN+2].pname = CSAVS(2, 70, "Third Realtime Signal"); } if (SIGRTMIN + 3 < SIGRTMAX && SIGRTMIN + 3 < NUMSIG && mesg[SIGRTMIN+3].pname == NULL) { mesg[SIGRTMIN+3].iname = "RTMIN+3"; mesg[SIGRTMIN+3].pname = CSAVS(2, 71, "Fourth Realtime Signal"); } } #endif /* SIGRTMIN */ #ifdef SIGRTMAX /* * Cannot do this at compile time; Solaris2 uses _sysconf for these */ if (SIGRTMAX > 0 && SIGRTMAX < NUMSIG) { if (SIGRTMAX - 3 > SIGRTMIN && mesg[SIGRTMAX-3].pname == NULL) { mesg[SIGRTMAX-3].iname = "RTMAX-3"; mesg[SIGRTMAX-3].pname = CSAVS(2, 72, "Fourth Last Realtime Signal"); } if (SIGRTMAX - 2 > SIGRTMIN && mesg[SIGRTMAX-2].pname == NULL) { mesg[SIGRTMAX-2].iname = "RTMAX-2"; mesg[SIGRTMAX-2].pname = CSAVS(2, 73, "Third Last Realtime Signal"); } if (SIGRTMAX - 1 > SIGRTMIN && mesg[SIGRTMAX-1].pname == NULL) { mesg[SIGRTMAX-1].iname = "RTMAX-1"; mesg[SIGRTMAX-1].pname = CSAVS(2, 74, "Second Last Realtime Signal"); } if (SIGRTMAX > SIGRTMIN && mesg[SIGRTMAX].pname == NULL) { mesg[SIGRTMAX].iname = "RTMAX"; mesg[SIGRTMAX].pname = CSAVS(2, 75, "Last Realtime Signal"); } } #endif /* SIGRTMAX */ #ifdef SIGAIO /* aiws */ if (mesg[SIGAIO].pname == NULL) { mesg[SIGAIO].iname = "AIO"; mesg[SIGAIO].pname = CSAVS(2, 76, "LAN Asyncronous I/O"); } #endif /* SIGAIO */ #ifdef SIGPTY /* aiws */ if (mesg[SIGPTY].pname == NULL) { mesg[SIGPTY].iname = "PTY"; mesg[SIGPTY].pname = CSAVS(2, 77, "PTY read/write availability"); } #endif /* SIGPTY */ #ifdef SIGIOINT /* aiws */ if (mesg[SIGIOINT].pname == NULL) { mesg[SIGIOINT].iname = "IOINT"; mesg[SIGIOINT].pname = CSAVS(2, 78, "I/O intervention required"); } #endif /* SIGIOINT */ #ifdef SIGGRANT /* aiws */ if (mesg[SIGGRANT].pname == NULL) { mesg[SIGGRANT].iname = "GRANT"; mesg[SIGGRANT].pname = CSAVS(2, 79, "HFT monitor mode granted"); } #endif /* SIGGRANT */ #ifdef SIGRETRACT /* aiws */ if (mesg[SIGRETRACT].pname == NULL) { mesg[SIGRETRACT].iname = "RETRACT"; mesg[SIGRETRACT].pname = CSAVS(2, 80, "HFT monitor mode should be relinguished"); } #endif /* SIGRETRACT */ #ifdef SIGSOUND /* aiws */ if (mesg[SIGSOUND].pname == NULL) { mesg[SIGSOUND].iname = "SOUND"; mesg[SIGSOUND].pname = CSAVS(2, 81, "HFT sound control has completed"); } #endif /* SIGSOUND */ #ifdef SIGSMSG /* aiws */ if (mesg[SIGSMSG].pname == NULL) { mesg[SIGSMSG].iname = "SMSG"; mesg[SIGSMSG].pname = CSAVS(2, 82, "Data in HFT ring buffer"); } #endif /* SIGMSG */ #ifdef SIGMIGRATE /* IBMAIX */ if (mesg[SIGMIGRATE].pname == NULL) { mesg[SIGMIGRATE].iname = "MIGRATE"; mesg[SIGMIGRATE].pname = CSAVS(2, 83, "Migrate process"); } #endif /* SIGMIGRATE */ #ifdef SIGSAK /* IBMAIX */ if (mesg[SIGSAK].pname == NULL) { mesg[SIGSAK].iname = "SAK"; mesg[SIGSAK].pname = CSAVS(2, 84, "Secure attention key"); } #endif /* SIGSAK */ #ifdef SIGRESCHED /* CX/UX */ if (mesg[SIGRESCHED].pname == NULL) { mesg[SIGRESCHED].iname = "RESCHED"; mesg[SIGRESCHED].pname = CSAVS(2, 85, "Reschedule"); } #endif /* SIGRESCHED */ #ifdef SIGDEBUG /* VMS_POSIX */ if (mesg[SIGDEBUG].pname == NULL) { mesg[SIGDEBUG].iname = "DEBUG"; mesg[SIGDEBUG].pname = CSAVS(2, 86, "Signaling SS$_DEBUG"); } #endif /* SIGDEBUG */ #ifdef SIGPRIO /* Lynx */ if (mesg[SIGPRIO].pname == NULL) { mesg[SIGPRIO].iname = "PRIO"; mesg[SIGPRIO].pname = CSAVS(2, 87, "Priority changed"); } #endif /* SIGPRIO */ #ifdef SIGDLK /* cray */ if (mesg[SIGDLK].pname == NULL) { mesg[SIGDLK].iname = "DLK"; mesg[SIGDLK].pname = CSAVS(2, 88, "True deadlock detected"); } #endif /* SIGDLK */ #ifdef SIGTINT /* masscomp */ if (mesg[SIGTINT].pname == NULL) { mesg[SIGTINT].iname = "TINT"; mesg[SIGTINT].pname = CSAVS(2, 89, "New input character"); } #endif /* SIGTINT */ #ifdef SIGSTKFLT if (mesg[SIGSTKFLT].pname == NULL) { mesg[SIGSTKFLT].iname = "STKFLT"; mesg[SIGSTKFLT].pname = CSAVS(2, 90, "Stack limit exceeded"); } #endif /* SIGSTKFLT */ #ifdef SIGUNUSED if (mesg[SIGUNUSED].pname == NULL) { mesg[SIGUNUSED].iname = "UNUSED"; mesg[SIGUNUSED].pname = CSAVS(2, 91, "Unused signal"); } #endif /* SIGUNUSED */ #ifdef SIGOVLY /* SX-4 */ if (mesg[SIGOVLY].pname == NULL) { mesg[SIGOVLY].iname = "OVLY"; mesg[SIGOVLY].pname = CSAVS(2, 92, "LM overlay"); } #endif /* SIGOVLY */ #ifdef SIGFRZ /* SX-4 */ if (mesg[SIGFRZ].pname == NULL) { mesg[SIGFRZ].iname = "FRZ"; mesg[SIGFRZ].pname = CSAVS(2, 93, "system freeze"); } #endif /* SIGFRZ */ #ifdef SIGDFRZ /* SX-4 */ if (mesg[SIGDFRZ].pname == NULL) { mesg[SIGDFRZ].iname = "DFRZ"; mesg[SIGDFRZ].pname = CSAVS(2, 94, "system defreeze"); } #endif /* SIGDFRZ */ #ifdef SIGDEAD /* SX-4 */ if (mesg[SIGDEAD].pname == NULL) { mesg[SIGDEAD].iname = "DEAD"; mesg[SIGDEAD].pname = CSAVS(2, 95, "dead lock"); } #endif /* SIGDEAD */ #ifdef SIGXMEM /* SX-4 */ if (mesg[SIGXMEM].pname == NULL) { mesg[SIGXMEM].iname = "XMEM"; mesg[SIGXMEM].pname = CSAVS(2, 96, "exceeded memory size limit"); } #endif /* SIGXMEM */ #ifdef SIGXDSZ /* SX-4 */ if (mesg[SIGXDSZ].pname == NULL) { mesg[SIGXDSZ].iname = "XDSZ"; mesg[SIGXDSZ].pname = CSAVS(2, 97, "exceeded data size limit"); } #endif /* SIGXDSZ */ #ifdef SIGMEM32 /* SX-4 */ if (mesg[SIGMEM32].pname == NULL) { mesg[SIGMEM32].iname = "MEM32"; mesg[SIGMEM32].pname = CSAVS(2, 98, "exceeded memory size limit of 32KB"); } #endif /* SIGMEM32 */ #ifdef SIGNMEM /* SX-4 */ if (mesg[SIGNMEM].pname == NULL) { mesg[SIGNMEM].iname = "NMEM"; mesg[SIGNMEM].pname = CSAVS(2, 99, "exce error for no memory"); } #endif /* SIGNMEM */ #ifdef SIGCHKP /* SX-4 */ if (mesg[SIGCHKP].pname == NULL) { mesg[SIGCHKP].iname = "CHKP"; mesg[SIGCHKP].pname = CSAVS(2, 100, "check point start"); } #endif /* SIGCHKP */ #ifdef SIGKCHKP #if 0 /* SX-4 */ if (mesg[SIGKCHKP].pname == NULL) { mesg[SIGKCHKP].iname = "KCHKP"; mesg[SIGKCHKP].pname = CSAVS(2, 101, "check point start of kernel"); } #endif #endif /* SIGKCHKP */ #ifdef SIGRSTA /* SX-4 */ if (mesg[SIGRSTA].pname == NULL) { mesg[SIGRSTA].iname = "RSTA"; mesg[SIGRSTA].pname = CSAVS(2, 102, "restart start"); } #endif /* SIGRSTA */ #ifdef SIGKRSTA #if 0 /* SX-4 */ if (mesg[SIGKRSTA].pname == NULL) { mesg[SIGKRSTA].iname = "KRSTA"; mesg[SIGKRSTA].pname = CSAVS(2, 103, "restart of kernel"); } #endif #endif /* SIGKRSTA */ #ifdef SIGXXMU /* SX-4 */ if (mesg[SIGXXMU].pname == NULL) { mesg[SIGXXMU].iname = "XXMU"; mesg[SIGXXMU].pname = CSAVS(2, 104, "exeeded XMU size limit"); } #endif /* SIGXXMU */ #ifdef SIGXRLG0 /* SX-4 */ if (mesg[SIGXRLG0].pname == NULL) { mesg[SIGXRLG0].iname = "XRLG0"; mesg[SIGXRLG0].pname = CSAVS(2, 105, "exeeded RLG0 limit"); } #endif /* SIGXRLG0 */ #ifdef SIGXRLG1 /* SX-4 */ if (mesg[SIGXRLG1].pname == NULL) { mesg[SIGXRLG1].iname = "XRLG1"; mesg[SIGXRLG1].pname = CSAVS(2, 106, "exeeded RLG1 limit"); } #endif /* SIGXRLG1 */ #ifdef SIGXRLG2 /* SX-4 */ if (mesg[SIGXRLG2].pname == NULL) { mesg[SIGXRLG2].iname = "XRLG2"; mesg[SIGXRLG2].pname = CSAVS(2, 107, "exeeded RLG2 limit"); } #endif /* SIGXRLG2 */ #ifdef SIGXRLG3 /* SX-4 */ if (mesg[SIGXRLG3].pname == NULL) { mesg[SIGXRLG3].iname = "XRLG3"; mesg[SIGXRLG3].pname = CSAVS(2, 108, "exeeded RLG3 limit"); } #endif /* SIGXRLG3 */ } diff --git a/contrib/tcsh/sh.lex.c b/contrib/tcsh/sh.lex.c index 46cc96d0937c..d22e4f45616d 100644 --- a/contrib/tcsh/sh.lex.c +++ b/contrib/tcsh/sh.lex.c @@ -1,1862 +1,1862 @@ /* * sh.lex.c: Lexical analysis into tokens */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include /* #define DEBUG_INP */ /* #define DEBUG_SEEK */ /* * C shell */ #define FLAG_G 1 #define FLAG_A 2 /* * These lexical routines read input and form lists of words. * There is some involved processing here, because of the complications * of input buffering, and especially because of history substitution. */ static Char *word (int); static eChar getC1 (int); static void getdol (void); static void getexcl (Char); static struct Hist *findev (Char *, int); static void setexclp (Char *); static eChar bgetc (void); static void balloc (int); static void bfree (void); static struct wordent *gethent (Char); static int matchs (const Char *, const Char *); static int getsel (int *, int *, int); static struct wordent *getsub (struct wordent *); static Char *subword (Char *, Char, int *, size_t *); static struct wordent *dosub (Char, struct wordent *, int); /* * Peekc is a peek character for getC, peekread for readc. * There is a subtlety here in many places... history routines * will read ahead and then insert stuff into the input stream. * If they push back a character then they must push it behind * the text substituted by the history substitution. On the other * hand in several places we need 2 peek characters. To make this * all work, the history routines read with getC, and make use both * of ungetC and unreadc. The key observation is that the state * of getC at the call of a history reference is such that calls * to getC from the history routines will always yield calls of * readc, unless this peeking is involved. That is to say that during * getexcl the variables lap, exclp, and exclnxt are all zero. * * Getdol invokes history substitution, hence the extra peek, peekd, * which it can ungetD to be before history substitutions. */ static Char peekc = 0, peekd = 0; static Char peekread = 0; /* (Tail of) current word from ! subst */ static Char *exclp = NULL; /* The rest of the ! subst words */ static struct wordent *exclnxt = NULL; /* Count of remaining words in ! subst */ static int exclc = 0; /* "Globp" for alias resubstitution */ int aret = TCSH_F_SEEK; /* * Labuf implements a general buffer for lookahead during lexical operations. * Text which is to be placed in the input stream can be stuck here. * We stick parsed ahead $ constructs during initial input, * process id's from `$$', and modified variable values (from qualifiers * during expansion in sh.dol.c) here. */ struct Strbuf labuf; /* = Strbuf_INIT; */ /* * Lex returns to its caller not only a wordlist (as a "var" parameter) * but also whether a history substitution occurred. This is used in * the main (process) routine to determine whether to echo, and also * when called by the alias routine to determine whether to keep the * argument list. */ static int hadhist = 0; /* * Avoid alias expansion recursion via \!# */ int hleft; struct Strbuf histline; /* = Strbuf_INIT; last line input */ int histvalid = 0; /* is histline valid */ static Char getCtmp; #define getC(f) (((getCtmp = peekc) != '\0') ? (peekc = 0, (eChar)getCtmp) : getC1(f)) #define ungetC(c) peekc = (Char) c #define ungetD(c) peekd = (Char) c /* Use Htime to store timestamps picked up from history file for enthist() * if reading saved history (sg) */ time_t Htime = (time_t)0; static time_t a2time_t (Char *); /* * special parsing rules apply for source -h */ extern int enterhist; extern int postcmd_active; int lex(struct wordent *hp) { struct wordent *wdp; eChar c; int parsehtime = enterhist; int toolong = 0; histvalid = 0; histline.len = 0; if (!postcmd_active) btell(&lineloc); hp->next = hp->prev = hp; hp->word = STRNULL; hadhist = 0; do c = readc(0); while (c == ' ' || c == '\t'); if (c == (eChar)HISTSUB && intty) /* ^lef^rit from tty is short !:s^lef^rit */ getexcl(c); else unreadc(c); cleanup_push(hp, lex_cleanup); wdp = hp; /* * The following loop is written so that the links needed by freelex will * be ready and rarin to go even if it is interrupted. */ do { struct wordent *new; new = xmalloc(sizeof(*new)); new->word = NULL; new->prev = wdp; new->next = hp; wdp->next = new; hp->prev = new; wdp = new; wdp->word = word(parsehtime); parsehtime = 0; if (enterhist && toolong++ > 10 * 1024) { stderror(ERR_LTOOLONG); } } while (wdp->word[0] != '\n'); cleanup_ignore(hp); cleanup_until(hp); Strbuf_terminate(&histline); if (histline.len != 0 && histline.s[histline.len - 1] == '\n') histline.s[histline.len - 1] = '\0'; histvalid = 1; return (hadhist); } static time_t a2time_t(Char *wordx) { /* Attempt to distinguish timestamps from other possible entries. * Format: "+NNNNNNNNNN" (10 digits, left padded with ascii '0') */ time_t ret; Char *s; int ct; if (!wordx || *(s = wordx) != '+') return (time_t)0; for (++s, ret = 0, ct = 0; *s; ++s, ++ct) { if (!isdigit((unsigned char)*s)) return (time_t)0; ret = ret * 10 + (time_t)((unsigned char)*s - '0'); } if (ct != 10) return (time_t)0; return ret; } void prlex(struct wordent *sp0) { struct wordent *sp = sp0->next; for (;;) { xprintf("%S", sp->word); sp = sp->next; if (sp == sp0) break; if (sp->word[0] != '\n') xputchar(' '); } } void copylex(struct wordent *hp, struct wordent *fp) { struct wordent *wdp; wdp = hp; fp = fp->next; do { struct wordent *new; new = xmalloc(sizeof(*new)); new->word = NULL; new->prev = wdp; new->next = hp; wdp->next = new; hp->prev = new; wdp = new; wdp->word = Strsave(fp->word); fp = fp->next; } while (wdp->word[0] != '\n'); } void initlex(struct wordent *vp) { vp->word = STRNULL; vp->prev = vp; vp->next = vp; } void freelex(struct wordent *vp) { struct wordent *fp; while (vp->next != vp) { fp = vp->next; vp->next = fp->next; xfree(fp->word); xfree(fp); } vp->prev = vp; } void lex_cleanup(void *xvp) { struct wordent *vp; vp = xvp; freelex(vp); } static Char * word(int parsehtime) { eChar c, c1; struct Strbuf wbuf = Strbuf_INIT; Char hbuf[12]; int h; int dolflg; int toolong = 0; cleanup_push(&wbuf, Strbuf_cleanup); loop: if (enterhist && toolong++ > 256 * 1024) { stderror(ERR_WTOOLONG); } while ((c = getC(DOALL)) == ' ' || c == '\t') continue; if (cmap(c, _META | _ESC)) switch (c) { case '&': case '|': case '<': case '>': Strbuf_append1(&wbuf, c); c1 = getC(DOALL); if (c1 == c) Strbuf_append1(&wbuf, c1); else ungetC(c1); goto ret; case '#': if (intty || (enterhist && !parsehtime)) break; c = 0; h = 0; do { c1 = c; c = getC(0); if (h < 11 && parsehtime) hbuf[h++] = c; } while (c != '\n'); if (parsehtime) { hbuf[11] = '\0'; - Htime = a2time_t(hbuf); + Htime = a2time_t(hbuf); } if (c1 == '\\') goto loop; /*FALLTHROUGH*/ case ';': case '(': case ')': case '\n': Strbuf_append1(&wbuf, c); goto ret; case '\\': c = getC(0); if (c == '\n') { if (onelflg == 1) onelflg = 2; goto loop; } if (c != (eChar)HIST) Strbuf_append1(&wbuf, '\\'); c |= QUOTE; default: break; } c1 = 0; dolflg = DOALL; for (;;) { if (enterhist && toolong++ > 256 * 1024) { stderror(ERR_WTOOLONG); } if (c1) { if (c == c1) { c1 = 0; dolflg = DOALL; } else if (c == '\\') { c = getC(0); /* * PWP: this is dumb, but how all of the other shells work. If \ quotes * a character OUTSIDE of a set of ''s, why shouldn't it quote EVERY * following character INSIDE a set of ''s. * * Actually, all I really want to be able to say is 'foo\'bar' --> foo'bar */ if (c == (eChar)HIST) c |= QUOTE; else { if (bslash_quote && ((c == '\'') || (c == '"') || (c == '\\') || (c == '$'))) { c |= QUOTE; } else { if (c == '\n') /* * if (c1 == '`') c = ' '; else */ c |= QUOTE; ungetC(c); c = '\\' | QUOTE; } } } else if (c == '\n') { seterror(ERR_UNMATCHED, c1); ungetC(c); break; } } else if (cmap(c, _META | _QF | _QB | _ESC)) { if (c == '\\') { c = getC(0); if (c == '\n') { if (onelflg == 1) onelflg = 2; break; } if (c != (eChar)HIST) Strbuf_append1(&wbuf, '\\'); c |= QUOTE; } else if (cmap(c, _QF | _QB)) { /* '"` */ c1 = c; dolflg = c == '"' ? DOALL : DOEXCL; } else if (c != '#' || (!intty && !enterhist)) { ungetC(c); break; } } Strbuf_append1(&wbuf, c); c = getC(dolflg); } ret: cleanup_ignore(&wbuf); cleanup_until(&wbuf); return Strbuf_finish(&wbuf); } static eChar getC1(int flag) { eChar c; for (;;) { if ((c = peekc) != 0) { peekc = 0; return (c); } if (lap < labuf.len) { c = labuf.s[lap++]; if (cmap(c, _META | _QF | _QB)) c |= QUOTE; return (c); } if ((c = peekd) != 0) { peekd = 0; return (c); } if (exclp) { if ((c = *exclp++) != 0) return (c); if (exclnxt && --exclc >= 0) { exclnxt = exclnxt->next; setexclp(exclnxt->word); return (' '); } exclp = 0; exclnxt = 0; /* this will throw away the dummy history entries */ savehist(NULL, 0); } if (exclnxt) { exclnxt = exclnxt->next; if (--exclc < 0) exclnxt = 0; else setexclp(exclnxt->word); continue; } c = readc(1); /* Catch EOF in the middle of a line. (An EOF at the beginning of * a line would have been processed by the readc(0) in lex().) */ if (c == CHAR_ERR) c = '\n'; if (c == '$' && (flag & DODOL)) { getdol(); continue; } if (c == (eChar)HIST && (flag & DOEXCL)) { getexcl(0); continue; } break; } return (c); } static void getdol(void) { struct Strbuf name = Strbuf_INIT; eChar c; eChar sc; int special = 0; c = sc = getC(DOEXCL); if (any("\t \n", c)) { ungetD(c); ungetC('$' | QUOTE); return; } cleanup_push(&name, Strbuf_cleanup); Strbuf_append1(&name, '$'); if (c == '{') Strbuf_append1(&name, c), c = getC(DOEXCL); if (c == '#' || c == '?' || c == '%') special++, Strbuf_append1(&name, c), c = getC(DOEXCL); Strbuf_append1(&name, c); switch (c) { case '<': case '$': case '!': if (special) seterror(ERR_SPDOLLT); goto end; case '\n': ungetD(c); name.len--; if (!special) seterror(ERR_NEWLINE); goto end; case '*': if (special) seterror(ERR_SPSTAR); goto end; default: if (Isdigit(c)) { #ifdef notdef /* let $?0 pass for now */ if (special) { seterror(ERR_DIGIT); goto end; } #endif while ((c = getC(DOEXCL)) != 0) { if (!Isdigit(c)) break; Strbuf_append1(&name, c); } } else if (letter(c)) { while ((c = getC(DOEXCL)) != 0) { /* Bugfix for ${v123x} from Chris Torek, DAS DEC-90. */ if (!letter(c) && !Isdigit(c)) break; Strbuf_append1(&name, c); } } else { if (!special) seterror(ERR_VARILL); else { ungetD(c); name.len--; } goto end; } break; } if (c == '[') { Strbuf_append1(&name, c); do { /* * Michael Greim: Allow $ expansion to take place in selector * expressions. (limits the number of characters returned) */ c = getC(DOEXCL | DODOL); if (c == '\n') { ungetD(c); name.len--; seterror(ERR_NLINDEX); goto end; } Strbuf_append1(&name, c); } while (c != ']'); c = getC(DOEXCL); } if (c == ':') { /* * if the :g modifier is followed by a newline, then error right away! * -strike */ int gmodflag = 0, amodflag = 0; do { Strbuf_append1(&name, c), c = getC(DOEXCL), gmodflag = 0, amodflag = 0; if (c == 'g' || c == 'a') { if (c == 'g') gmodflag++; else amodflag++; Strbuf_append1(&name, c); c = getC(DOEXCL); } if ((c == 'g' && !gmodflag) || (c == 'a' && !amodflag)) { if (c == 'g') gmodflag++; else amodflag++; Strbuf_append1(&name, c); c = getC(DOEXCL); } Strbuf_append1(&name, c); /* scan s// [eichin:19910926.0512EST] */ if (c == 's') { int delimcnt = 2; eChar delim = getC(0); Strbuf_append1(&name, delim); if (!delim || letter(delim) || Isdigit(delim) || any(" \t\n", delim)) { seterror(ERR_BADSUBST); break; } while ((c = getC(0)) != CHAR_ERR) { Strbuf_append1(&name, c); if (c == delim) delimcnt--; if (!delimcnt) break; } if (delimcnt) { seterror(ERR_BADSUBST); break; } c = 's'; } if (!any(TCSH_MODIFIERS, c)) { if ((amodflag || gmodflag) && c == '\n') stderror(ERR_VARSYN); /* strike */ seterror(ERR_BADMOD, c); goto end; } } while ((c = getC(DOEXCL)) == ':'); ungetD(c); } else ungetD(c); if (sc == '{') { c = getC(DOEXCL); if (c != '}') { ungetD(c); seterror(ERR_MISSING, '}'); goto end; } Strbuf_append1(&name, c); } end: cleanup_ignore(&name); cleanup_until(&name); addla(Strbuf_finish(&name)); } /* xfree()'s its argument */ void addla(Char *cp) { static struct Strbuf buf; /* = Strbuf_INIT; */ buf.len = 0; Strbuf_appendn(&buf, labuf.s + lap, labuf.len - lap); labuf.len = 0; Strbuf_append(&labuf, cp); Strbuf_terminate(&labuf); Strbuf_appendn(&labuf, buf.s, buf.len); xfree(cp); lap = 0; } /* left-hand side of last :s or search string of last ?event? */ static struct Strbuf lhsb; /* = Strbuf_INIT; */ static struct Strbuf slhs; /* = Strbuf_INIT; left-hand side of last :s */ static struct Strbuf rhsb; /* = Strbuf_INIT; right-hand side of last :s */ static int quesarg; static void getexcl(Char sc) { struct wordent *hp, *ip; int left, right, dol; eChar c; if (sc == 0) { c = getC(0); if (c == '{') sc = (Char) c; else ungetC(c); } quesarg = -1; lastev = eventno; hp = gethent(sc); if (hp == 0) return; hadhist = 1; dol = 0; if (hp == alhistp) for (ip = hp->next->next; ip != alhistt; ip = ip->next) dol++; else for (ip = hp->next->next; ip != hp->prev; ip = ip->next) dol++; left = 0, right = dol; if (sc == HISTSUB && HISTSUB != '\0') { ungetC('s'), unreadc(HISTSUB), c = ':'; goto subst; } c = getC(0); if (!any(":^$*-%", c)) goto subst; left = right = -1; if (c == ':') { c = getC(0); unreadc(c); if (letter(c) || c == '&') { c = ':'; left = 0, right = dol; goto subst; } } else ungetC(c); if (!getsel(&left, &right, dol)) return; c = getC(0); if (c == '*') ungetC(c), c = '-'; if (c == '-') { if (!getsel(&left, &right, dol)) return; c = getC(0); } subst: exclc = right - left + 1; while (--left >= 0) hp = hp->next; if ((sc == HISTSUB && HISTSUB != '\0') || c == ':') { do { hp = getsub(hp); c = getC(0); } while (c == ':'); } unreadc(c); if (sc == '{') { c = getC(0); if (c != '}') seterror(ERR_BADBANG); } exclnxt = hp; } static struct wordent * getsub(struct wordent *en) { eChar delim; eChar c; eChar sc; int global; do { exclnxt = 0; global = 0; sc = c = getC(0); while (c == 'g' || c == 'a') { global |= (c == 'g') ? FLAG_G : FLAG_A; sc = c = getC(0); } switch (c) { case 'p': justpr++; return (en); case 'x': case 'q': global |= FLAG_G; /*FALLTHROUGH*/ case 'h': case 'r': case 't': case 'e': case 'u': case 'l': break; case '&': if (slhs.len == 0) { seterror(ERR_NOSUBST); return (en); } lhsb.len = 0; Strbuf_append(&lhsb, slhs.s); Strbuf_terminate(&lhsb); break; #ifdef notdef case '~': if (lhsb.len == 0) goto badlhs; break; #endif case 's': delim = getC(0); if (letter(delim) || Isdigit(delim) || any(" \t\n", delim)) { unreadc(delim); lhsb.len = 0; seterror(ERR_BADSUBST); return (en); } Strbuf_terminate(&lhsb); lhsb.len = 0; for (;;) { c = getC(0); if (c == '\n') { unreadc(c); break; } if (c == delim) break; if (c == '\\') { c = getC(0); if (c != delim && c != '\\') Strbuf_append1(&lhsb, '\\'); } Strbuf_append1(&lhsb, c); } if (lhsb.len != 0) Strbuf_terminate(&lhsb); else if (lhsb.s[0] == 0) { seterror(ERR_LHS); return (en); } else lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */ rhsb.len = 0; for (;;) { c = getC(0); if (c == '\n') { unreadc(c); break; } if (c == delim) break; if (c == '\\') { c = getC(0); if (c != delim /* && c != '~' */ ) Strbuf_append1(&rhsb, '\\'); } Strbuf_append1(&rhsb, c); } Strbuf_terminate(&rhsb); break; default: if (c == '\n') unreadc(c); seterror(ERR_BADBANGMOD, (int)c); return (en); } slhs.len = 0; if (lhsb.s != NULL && lhsb.len != 0) Strbuf_append(&slhs, lhsb.s); Strbuf_terminate(&slhs); if (exclc) en = dosub(sc, en, global); } while ((c = getC(0)) == ':'); unreadc(c); return (en); } /* - * + * * From Beto Appleton (beto@aixwiz.austin.ibm.com) * * when using history substitution, and the variable * 'history' is set to a value higher than 1000, * the shell might either freeze (hang) or core-dump. * We raise the limit to 50000000 */ #define HIST_PURGE -50000000 static struct wordent * dosub(Char sc, struct wordent *en, int global) { struct wordent lexi; int didsub = 0, didone = 0; struct wordent *hp = &lexi; struct wordent *wdp; int i = exclc; struct Hist *hst; wdp = hp; while (--i >= 0) { struct wordent *new = xcalloc(1, sizeof *wdp); new->word = 0; new->prev = wdp; new->next = hp; wdp->next = new; wdp = new; en = en->next; if (en->word) { Char *tword, *otword; if ((global & FLAG_G) || didsub == 0) { size_t pos; pos = 0; tword = subword(en->word, sc, &didone, &pos); if (didone) didsub = 1; if (global & FLAG_A) { while (didone && tword != STRNULL) { otword = tword; tword = subword(otword, sc, &didone, &pos); if (Strcmp(tword, otword) == 0) { xfree(otword); break; } else xfree(otword); } } } else tword = Strsave(en->word); wdp->word = tword; } } if (didsub == 0) seterror(ERR_MODFAIL); hp->prev = wdp; - /* + /* * ANSI mode HP/UX compiler chokes on * return &enthist(HIST_PURGE, &lexi, 0)->Hlex; */ hst = enthist(HIST_PURGE, &lexi, 0, 0, -1); return &(hst->Hlex); } /* Return a newly allocated result of one modification of CP using the operation TYPE. Set ADID to 1 if a modification was performed. If TYPE == 's', perform substitutions only from *START_POS on and set *START_POS to the position of next substitution attempt. */ static Char * subword(Char *cp, Char type, int *adid, size_t *start_pos) { Char *wp; const Char *mp, *np; switch (type) { case 'r': case 'e': case 'h': case 't': case 'q': case 'x': case 'u': case 'l': wp = domod(cp, type); if (wp == 0) { *adid = 0; return (Strsave(cp)); } *adid = 1; return (wp); default: for (mp = cp + *start_pos; *mp; mp++) { if (matchs(mp, lhsb.s)) { struct Strbuf wbuf = Strbuf_INIT; Strbuf_appendn(&wbuf, cp, mp - cp); for (np = rhsb.s; *np; np++) switch (*np) { case '\\': if (np[1] == '&') np++; - /* fall into ... */ + /* FALLTHROUGH */ default: Strbuf_append1(&wbuf, *np); continue; case '&': Strbuf_append(&wbuf, lhsb.s); continue; } *start_pos = wbuf.len; Strbuf_append(&wbuf, mp + lhsb.len); *adid = 1; return Strbuf_finish(&wbuf); } } *adid = 0; return (Strsave(cp)); } } Char * domod(Char *cp, Char type) { Char *wp, *xp; int c; switch (type) { case 'Q': if (*cp == '\0') return Strsave(STRQNULL); /*FALLTHROUGH*/ case 'q': case 'x': wp = Strsave(cp); for (xp = wp; (c = *xp) != 0; xp++) if ((c != ' ' && c != '\t') || type == 'q' || type == 'Q') *xp |= QUOTE; return (wp); case 'l': wp = NLSChangeCase(cp, 1); return wp ? wp : Strsave(cp); case 'u': wp = NLSChangeCase(cp, 0); return wp ? wp : Strsave(cp); case 'h': case 't': wp = Strrchr(cp, '/'); if (wp == NULL) return NULL; if (type == 't') xp = Strsave(wp + 1); else xp = Strnsave(cp, wp - cp); return (xp); case 'e': case 'r': wp = Strend(cp); for (wp--; wp >= cp && *wp != '/'; wp--) if (*wp == '.') { if (type == 'e') xp = Strsave(wp + 1); else xp = Strnsave(cp, wp - cp); return (xp); } return (Strsave(type == 'e' ? STRNULL : cp)); default: break; } return (0); } static int matchs(const Char *str, const Char *pat) { while (*str && *pat && *str == *pat) str++, pat++; return (*pat == 0); } static int getsel(int *al, int *ar, int dol) { eChar c = getC(0); int i; int first = *al < 0; switch (c) { case '%': if (quesarg == -1) { seterror(ERR_BADBANGARG); return (0); } if (*al < 0) *al = quesarg; *ar = quesarg; break; case '-': if (*al < 0) { *al = 0; *ar = dol - 1; unreadc(c); } return (1); case '^': if (*al < 0) *al = 1; *ar = 1; break; case '$': if (*al < 0) *al = dol; *ar = dol; break; case '*': if (*al < 0) *al = 1; *ar = dol; if (*ar < *al) { *ar = 0; *al = 1; return (1); } break; default: if (Isdigit(c)) { i = 0; while (Isdigit(c)) { i = i * 10 + c - '0'; c = getC(0); } if (i < 0) i = dol + 1; if (*al < 0) *al = i; *ar = i; } else if (*al < 0) *al = 0, *ar = dol; else *ar = dol - 1; unreadc(c); break; } if (first) { c = getC(0); unreadc(c); if (any("-$*", c)) return (1); } if (*al > *ar || *ar > dol) { seterror(ERR_BADBANGARG); return (0); } return (1); } static struct wordent * gethent(Char sc) { struct Hist *hp; Char *np; eChar c; int event; int back = 0; c = (sc == HISTSUB && HISTSUB != '\0') ? (eChar)HIST : getC(0); if (c == (eChar)HIST) { if (alhistp) return (alhistp); event = eventno; } else switch (c) { case ':': case '^': case '$': case '*': case '%': ungetC(c); if (lastev == eventno && alhistp) return (alhistp); event = lastev; break; case '#': /* !# is command being typed in (mrh) */ if (--hleft == 0) { seterror(ERR_HISTLOOP); return (0); } else return (¶ml); /* NOTREACHED */ case '-': back = 1; c = getC(0); - /* FALLSTHROUGH */ + /* FALLTHROUGH */ default: if (any("(=~", c)) { unreadc(c); ungetC(HIST); return (0); } Strbuf_terminate(&lhsb); lhsb.len = 0; event = 0; while (!cmap(c, _ESC | _META | _QF | _QB) && !any("^*-%${}:#", c)) { if (event != -1 && Isdigit(c)) event = event * 10 + c - '0'; else event = -1; Strbuf_append1(&lhsb, c); c = getC(0); } unreadc(c); if (lhsb.len == 0) { lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */ ungetC(HIST); return (0); } Strbuf_terminate(&lhsb); if (event != -1) { /* * History had only digits */ if (back) event = eventno + (alhistp == 0) - event; break; } if (back) { Strbuf_append1(&lhsb, '\0'); /* Allocate space */ Strbuf_terminate(&lhsb); memmove(lhsb.s + 1, lhsb.s, (lhsb.len - 1) * sizeof (*lhsb.s)); lhsb.s[0] = '-'; } hp = findev(lhsb.s, 0); if (hp) lastev = hp->Hnum; return (&hp->Hlex); case '?': Strbuf_terminate(&lhsb); lhsb.len = 0; for (;;) { c = getC(0); if (c == '\n') { unreadc(c); break; } if (c == '?') break; Strbuf_append1(&lhsb, c); } if (lhsb.len == 0) { lhsb.len = Strlen(lhsb.s); /* lhsb.s wasn't changed */ if (lhsb.len == 0) { seterror(ERR_NOSEARCH); return (0); } } else Strbuf_terminate(&lhsb); hp = findev(lhsb.s, 1); if (hp) lastev = hp->Hnum; return (&hp->Hlex); } for (hp = Histlist.Hnext; hp; hp = hp->Hnext) if (hp->Hnum == event) { hp->Href = eventno; lastev = hp->Hnum; return (&hp->Hlex); } np = putn((tcsh_number_t)event); seterror(ERR_NOEVENT, short2str(np)); xfree(np); return (0); } static struct Hist * findev(Char *cp, int anyarg) { struct Hist *hp; for (hp = Histlist.Hnext; hp; hp = hp->Hnext) { Char *dp; Char *p, *q; struct wordent *lp = hp->Hlex.next; int argno = 0; /* * The entries added by alias substitution don't have a newline but do * have a negative event number. Savehist() trims off these entries, * but it happens before alias expansion, too early to delete those * from the previous command. */ if (hp->Hnum < 0) continue; if (lp->word[0] == '\n') continue; if (!anyarg) { p = cp; q = lp->word; do if (!*p) return (hp); while (*p++ == *q++); continue; } do { for (dp = lp->word; *dp; dp++) { p = cp; q = dp; do if (!*p) { quesarg = argno; return (hp); } while (*p++ == *q++); } lp = lp->next; argno++; } while (lp->word[0] != '\n'); } seterror(ERR_NOEVENT, short2str(cp)); return (0); } static void setexclp(Char *cp) { if (cp && cp[0] == '\n') return; exclp = cp; } void unreadc(Char c) { peekread = (Char) c; } eChar readc(int wanteof) { eChar c; static int sincereal; /* Number of real EOFs we've seen */ #ifdef DEBUG_INP xprintf("readc\n"); #endif if ((c = peekread) != 0) { peekread = 0; return (c); } top: aret = TCSH_F_SEEK; if (alvecp) { arun = 1; #ifdef DEBUG_INP xprintf("alvecp %c\n", *alvecp & 0xff); #endif aret = TCSH_A_SEEK; if ((c = *alvecp++) != 0) return (c); if (alvec && *alvec) { alvecp = *alvec++; return (' '); } else { alvecp = NULL; aret = TCSH_F_SEEK; return('\n'); } } if (alvec) { arun = 1; if ((alvecp = *alvec) != 0) { alvec++; goto top; } /* Infinite source! */ return ('\n'); } arun = 0; if (evalp) { aret = TCSH_E_SEEK; if ((c = *evalp++) != 0) return (c); if (evalvec && *evalvec) { evalp = *evalvec++; return (' '); } aret = TCSH_F_SEEK; evalp = 0; } if (evalvec) { if (evalvec == INVPPTR) { doneinp = 1; reset(); } if ((evalp = *evalvec) != 0) { evalvec++; goto top; } evalvec = INVPPTR; return ('\n'); } do { if (arginp == INVPTR || onelflg == 1) { if (wanteof) return CHAR_ERR; exitstat(); } if (arginp) { if ((c = *arginp++) == 0) { arginp = INVPTR; return ('\n'); } return (c); } #ifdef BSDJOBS reread: #endif /* BSDJOBS */ c = bgetc(); if (c == CHAR_ERR) { #ifndef WINNT_NATIVE # ifndef POSIX # ifdef TERMIO struct termio tty; # else /* SGTTYB */ struct sgttyb tty; # endif /* TERMIO */ # else /* POSIX */ struct termios tty; # endif /* POSIX */ #endif /* !WINNT_NATIVE */ if (wanteof) return CHAR_ERR; /* was isatty but raw with ignoreeof yields problems */ #ifndef WINNT_NATIVE # ifndef POSIX # ifdef TERMIO if (ioctl(SHIN, TCGETA, (ioctl_t) & tty) == 0 && (tty.c_lflag & ICANON)) # else /* GSTTYB */ if (ioctl(SHIN, TIOCGETP, (ioctl_t) & tty) == 0 && (tty.sg_flags & RAW) == 0) # endif /* TERMIO */ # else /* POSIX */ if (tcgetattr(SHIN, &tty) == 0 && (tty.c_lflag & ICANON)) # endif /* POSIX */ #else /* WINNT_NATIVE */ if (isatty(SHIN)) #endif /* !WINNT_NATIVE */ { #ifdef BSDJOBS pid_t ctpgrp; #endif /* BSDJOBS */ if (numeof != 0 && ++sincereal >= numeof) /* Too many EOFs? Bye! */ goto oops; #ifdef BSDJOBS if (tpgrp != -1 && (ctpgrp = tcgetpgrp(FSHTTY)) != -1 && tpgrp != ctpgrp) { (void) tcsetpgrp(FSHTTY, tpgrp); # ifdef _SEQUENT_ if (ctpgrp) # endif /* _SEQUENT */ (void) killpg(ctpgrp, SIGHUP); # ifdef notdef /* * With the walking process group fix, this message * is now obsolete. As the foreground process group * changes, the shell needs to adjust. Well too bad. */ xprintf(CGETS(16, 1, "Reset tty pgrp from %d to %d\n"), (int)ctpgrp, (int)tpgrp); # endif /* notdef */ goto reread; } #endif /* BSDJOBS */ /* What follows is complicated EOF handling -- sterling@netcom.com */ /* First, we check to see if we have ignoreeof set */ if (adrof(STRignoreeof)) { /* If so, we check for any stopped jobs only on the first EOF */ if ((sincereal == 1) && (chkstop == 0)) { panystop(1); } } else { /* If we don't have ignoreeof set, always check for stopped jobs */ if (chkstop == 0) { panystop(1); } } /* At this point, if there were stopped jobs, we would have already * called reset(). If we got this far, assume we can print an * exit/logout message if we ignoreeof, or just exit. */ if (adrof(STRignoreeof)) { /* If so, tell the user to use exit or logout */ if (loginsh) { xprintf("%s", CGETS(16, 2, "\nUse \"logout\" to logout.\n")); } else { xprintf(CGETS(16, 3, "\nUse \"exit\" to leave %s.\n"), progname); } reset(); } else { /* If we don't have ignoreeof set, just fall through */ ; /* EMPTY */ } } oops: doneinp = 1; reset(); } sincereal = 0; if (c == '\n' && onelflg) onelflg--; } while (c == 0); Strbuf_append1(&histline, c); return (c); } static void balloc(int buf) { Char **nfbuf; while (buf >= fblocks) { nfbuf = xcalloc(fblocks + 2, sizeof(Char **)); if (fbuf) { (void) blkcpy(nfbuf, fbuf); xfree(fbuf); } fbuf = nfbuf; fbuf[fblocks] = xcalloc(BUFSIZE, sizeof(Char)); fblocks++; } } ssize_t wide_read(int fildes, Char *buf, size_t nchars, int use_fclens) { char cbuf[BUFSIZE + 1]; ssize_t res, r = 0; size_t partial; int err; if (nchars == 0) return 0; assert (nchars <= sizeof(cbuf) / sizeof(*cbuf)); USE(use_fclens); res = 0; partial = 0; do { size_t i; size_t len = nchars > partial ? nchars - partial : 1; if (partial + len >= sizeof(cbuf) / sizeof(*cbuf)) break; - + r = xread(fildes, cbuf + partial, len); - + if (partial == 0 && r <= 0) break; partial += r; i = 0; while (i < partial && nchars != 0) { int tlen; tlen = normal_mbtowc(buf + res, cbuf + i, partial - i); if (tlen == -1) { reset_mbtowc(); if ((partial - i) < MB_LEN_MAX && r > 0) /* Maybe a partial character and there is still a chance to read more */ break; buf[res] = (unsigned char)cbuf[i] | INVALID_BYTE; } if (tlen <= 0) tlen = 1; #ifdef WIDE_STRINGS if (use_fclens) fclens[res] = tlen; #endif i += tlen; res++; nchars--; } if (i != partial) memmove(cbuf, cbuf + i, partial - i); partial -= i; } while (partial != 0 && nchars > 0); /* Throwing away possible partial multibyte characters on error if the stream is not seekable */ err = errno; lseek(fildes, -(off_t)partial, L_INCR); errno = err; return res != 0 ? res : r; } static eChar bgetc(void) { Char ch; int c, off, buf; int numleft = 0, roomleft; if (cantell) { if (fseekp < fbobp || fseekp > feobp) { fbobp = feobp = fseekp; (void) lseek(SHIN, fseekp, L_SET); } if (fseekp == feobp) { #ifdef WIDE_STRINGS off_t bytes; size_t i; bytes = fbobp; for (i = 0; i < (size_t)(feobp - fbobp); i++) bytes += fclens[i]; fseekp = feobp = bytes; #endif fbobp = feobp; c = wide_read(SHIN, fbuf[0], BUFSIZE, 1); #ifdef convex if (c < 0) stderror(ERR_SYSTEM, progname, strerror(errno)); #endif /* convex */ if (c <= 0) return CHAR_ERR; feobp += c; } #if !defined(WINNT_NATIVE) && !defined(__CYGWIN__) ch = fbuf[0][fseekp - fbobp]; fseekp++; #else do { ch = fbuf[0][fseekp - fbobp]; fseekp++; } while (ch == '\r'); #endif /* !WINNT_NATIVE && !__CYGWIN__ */ return (ch); } while (fseekp >= feobp) { if ((editing #if defined(FILEC) && defined(TIOCSTI) || filec #endif /* FILEC && TIOCSTI */ ) && intty) { /* then use twenex routine */ fseekp = feobp; /* where else? */ #if defined(FILEC) && defined(TIOCSTI) if (!editing) c = numleft = tenex(InputBuf, BUFSIZE); else #endif /* FILEC && TIOCSTI */ c = numleft = Inputl(); /* PWP: get a line */ while (numleft > 0) { off = (int) feobp % BUFSIZE; buf = (int) feobp / BUFSIZE; balloc(buf); roomleft = BUFSIZE - off; if (roomleft > numleft) roomleft = numleft; (void) memcpy(fbuf[buf] + off, InputBuf + c - numleft, roomleft * sizeof(Char)); numleft -= roomleft; feobp += roomleft; } } else { off = (int) feobp % BUFSIZE; buf = (int) feobp / BUFSIZE; balloc(buf); roomleft = BUFSIZE - off; c = wide_read(SHIN, fbuf[buf] + off, roomleft, 0); if (c > 0) feobp += c; } if (c == 0 || (c < 0 && fixio(SHIN, errno) == -1)) return CHAR_ERR; } #ifdef SIG_WINDOW if (windowchg) (void) check_window_size(0); /* for window systems */ #endif /* SIG_WINDOW */ #if !defined(WINNT_NATIVE) && !defined(__CYGWIN__) ch = fbuf[(int) fseekp / BUFSIZE][(int) fseekp % BUFSIZE]; fseekp++; #else do { ch = fbuf[(int) fseekp / BUFSIZE][(int) fseekp % BUFSIZE]; fseekp++; } while (ch == '\r'); #endif /* !WINNT_NATIVE && !__CYGWIN__ */ return (ch); } static void bfree(void) { int sb, i; if (cantell) return; if (whyles) return; sb = (int) (fseekp - 1) / BUFSIZE; if (sb > 0) { for (i = 0; i < sb; i++) xfree(fbuf[i]); (void) blkcpy(fbuf, &fbuf[sb]); fseekp -= BUFSIZE * sb; feobp -= BUFSIZE * sb; fblocks -= sb; } } void bseek(struct Ain *l) { switch (aret = l->type) { case TCSH_E_SEEK: evalvec = l->a_seek; evalp = l->c_seek; #ifdef DEBUG_SEEK xprintf(CGETS(16, 4, "seek to eval %x %x\n"), evalvec, evalp); #endif return; case TCSH_A_SEEK: alvec = l->a_seek; alvecp = l->c_seek; #ifdef DEBUG_SEEK xprintf(CGETS(16, 5, "seek to alias %x %x\n"), alvec, alvecp); #endif return; - case TCSH_F_SEEK: + case TCSH_F_SEEK: #ifdef DEBUG_SEEK xprintf(CGETS(16, 6, "seek to file %x\n"), fseekp); #endif fseekp = l->f_seek; #ifdef WIDE_STRINGS if (cantell) { if (fseekp >= fbobp && feobp >= fbobp) { size_t i; off_t o; o = fbobp; for (i = 0; i < (size_t)(feobp - fbobp); i++) { if (fseekp == o) { fseekp = fbobp + i; return; } o += fclens[i]; } if (fseekp == o) { fseekp = feobp; return; } } fbobp = feobp = fseekp + 1; /* To force lseek() */ } #endif return; default: xprintf(CGETS(16, 7, "Bad seek type %d\n"), aret); abort(); } } /* any similarity to bell telephone is purely accidental */ void btell(struct Ain *l) { switch (l->type = aret) { case TCSH_E_SEEK: l->a_seek = evalvec; l->c_seek = evalp; #ifdef DEBUG_SEEK xprintf(CGETS(16, 8, "tell eval %x %x\n"), evalvec, evalp); #endif return; case TCSH_A_SEEK: l->a_seek = alvec; l->c_seek = alvecp; #ifdef DEBUG_SEEK xprintf(CGETS(16, 9, "tell alias %x %x\n"), alvec, alvecp); #endif return; case TCSH_F_SEEK: #ifdef WIDE_STRINGS if (cantell && fseekp >= fbobp && fseekp <= feobp) { size_t i; l->f_seek = fbobp; for (i = 0; i < (size_t)(fseekp - fbobp); i++) l->f_seek += fclens[i]; } else #endif /*SUPPRESS 112*/ l->f_seek = fseekp; l->a_seek = NULL; #ifdef DEBUG_SEEK xprintf(CGETS(16, 10, "tell file %x\n"), fseekp); #endif return; default: xprintf(CGETS(16, 7, "Bad seek type %d\n"), aret); abort(); } } void btoeof(void) { (void) lseek(SHIN, (off_t) 0, L_XTND); aret = TCSH_F_SEEK; fseekp = feobp; alvec = NULL; alvecp = NULL; evalvec = NULL; evalp = NULL; wfree(); bfree(); } void settell(void) { off_t x; cantell = 0; if (arginp || onelflg || intty) return; if ((x = lseek(SHIN, (off_t) 0, L_INCR)) == -1) return; fbuf = xcalloc(2, sizeof(Char **)); fblocks = 1; fbuf[0] = xcalloc(BUFSIZE, sizeof(Char)); fseekp = fbobp = feobp = x; cantell = 1; } diff --git a/contrib/tcsh/sh.misc.c b/contrib/tcsh/sh.misc.c index bf6bcc994099..05b58d197a1d 100644 --- a/contrib/tcsh/sh.misc.c +++ b/contrib/tcsh/sh.misc.c @@ -1,723 +1,723 @@ /* * sh.misc.c: Miscelaneous functions */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" static int renum (int, int); static Char **blkend (Char **); static Char **blkcat (Char **, Char **); static int xdup2 (int, int); /* * C Shell */ int any(const char *s, Char c) { if (!s) return (0); /* Check for nil pointer */ while (*s) if ((Char)*s++ == c) return (1); return (0); } void setzero(void *p, size_t size) { memset(p, 0, size); } #ifndef SHORT_STRINGS char * strnsave(const char *s, size_t len) { char *r; r = xmalloc(len + 1); memcpy(r, s, len); r[len] = '\0'; return r; } #endif char * strsave(const char *s) { char *r; size_t size; if (s == NULL) s = ""; size = strlen(s) + 1; r = xmalloc(size); memcpy(r, s, size); return (r); } static Char ** blkend(Char **up) { while (*up) up++; return (up); } void blkpr(Char *const *av) { for (; *av; av++) { xprintf("%S", *av); if (av[1]) xprintf(" "); } } Char * blkexpand(Char *const *av) { struct Strbuf buf = Strbuf_INIT; for (; *av; av++) { Strbuf_append(&buf, *av); if (av[1]) Strbuf_append1(&buf, ' '); } return Strbuf_finish(&buf); } int blklen(Char **av) { int i = 0; while (*av++) i++; return (i); } Char ** blkcpy(Char **oav, Char **bv) { Char **av = oav; while ((*av++ = *bv++) != NULL) continue; return (oav); } static Char ** blkcat(Char **up, Char **vp) { (void) blkcpy(blkend(up), vp); return (up); } void blkfree(Char **av0) { Char **av = av0; if (!av0) return; for (; *av; av++) xfree(*av); xfree(av0); } void blk_cleanup(void *ptr) { blkfree(ptr); } void blk_indirect_cleanup(void *xptr) { Char ***ptr; ptr = xptr; blkfree(*ptr); xfree(ptr); } Char ** saveblk(Char **v) { Char **newv, **onewv; if (v == NULL) return NULL; onewv = newv = xcalloc(blklen(v) + 1, sizeof(Char **)); while (*v) *newv++ = Strsave(*v++); return (onewv); } #ifndef HAVE_STRSTR char * strstr(const char *s, const char *t) { do { const char *ss = s; const char *tt = t; do if (*tt == '\0') return (s); while (*ss++ == *tt++); } while (*s++ != '\0'); return (NULL); } #endif /* !HAVE_STRSTR */ char * strspl(const char *cp, const char *dp) { char *ep; size_t cl, dl; if (!cp) cp = ""; if (!dp) dp = ""; cl = strlen(cp); dl = strlen(dp); ep = xmalloc((cl + dl + 1) * sizeof(char)); memcpy(ep, cp, cl); memcpy(ep + cl, dp, dl + 1); return (ep); } Char ** blkspl(Char **up, Char **vp) { Char **wp = xcalloc(blklen(up) + blklen(vp) + 1, sizeof(Char **)); (void) blkcpy(wp, up); return (blkcat(wp, vp)); } Char lastchr(Char *cp) { if (!cp) return (0); if (!*cp) return (0); while (cp[1]) cp++; return (*cp); } /* * This routine is called after an error to close up * any units which may have been left open accidentally. */ void closem(void) { int f, num_files; #ifdef S_ISSOCK struct stat st; #endif /*S_ISSOCK*/ #ifdef NLS_BUGS #ifdef NLS_CATALOGS nlsclose(); #endif /* NLS_CATALOGS */ #endif /* NLS_BUGS */ #ifdef YPBUGS /* suggested by Justin Bur; thanks to Karl Kleinpaste */ fix_yp_bugs(); #endif /* YPBUGS */ num_files = NOFILE; for (f = 0; f < num_files; f++) if (f != SHIN && f != SHOUT && f != SHDIAG && f != OLDSTD && - f != FSHTTY + f != FSHTTY #ifdef MALLOC_TRACE && f != 25 #endif /* MALLOC_TRACE */ #ifdef S_ISSOCK /* NSS modules (e.g. Linux nss_ldap) might keep sockets open. * If we close such a socket, both the NSS module and tcsh think * they "own" the descriptor. * * Not closing sockets does not make the cleanup use of closem() * less reliable because tcsh never creates sockets. */ - && fstat(f, &st) == 0 && !S_ISSOCK(st.st_mode) + && fstat(f, &st) == 0 && !S_ISSOCK(st.st_mode) #endif ) { xclose(f); #ifdef NISPLUS if (f < 3) (void) xopen(_PATH_DEVNULL, O_RDONLY|O_LARGEFILE); #endif /* NISPLUS */ } #ifdef NLS_BUGS #ifdef NLS_CATALOGS nlsinit(); #endif /* NLS_CATALOGS */ #endif /* NLS_BUGS */ } #ifndef CLOSE_ON_EXEC /* * Close files before executing a file. * We could be MUCH more intelligent, since (on a version 7 system) * we need only close files here during a source, the other * shell fd's being in units 16-19 which are closed automatically! */ void closech(void) { int f, num_files; if (didcch) return; didcch = 1; SHIN = 0; SHOUT = 1; SHDIAG = 2; OLDSTD = 0; isoutatty = isatty(SHOUT); isdiagatty = isatty(SHDIAG); num_files = NOFILE; for (f = 3; f < num_files; f++) xclose(f); } #endif /* CLOSE_ON_EXEC */ void donefds(void) { xclose(0); xclose(1); xclose(2); didfds = 0; #ifdef NISPLUS { int fd = xopen(_PATH_DEVNULL, O_RDONLY|O_LARGEFILE); (void)dcopy(fd, 1); (void)dcopy(fd, 2); (void)dmove(fd, 0); } -#endif /*NISPLUS*/ +#endif /*NISPLUS*/ } /* * Move descriptor i to j. * If j is -1 then we just want to get i to a safe place, * i.e. to a unit > FSAFE. This also happens in dcopy. */ int dmove(int i, int j) { if (i == j || i < 0) return (i); #ifdef HAVE_DUP2 if (j >= 0) { (void) xdup2(i, j); if (j != i) xclose(i); return (j); } #endif j = dcopy(i, j); if (j != i) xclose(i); return (j); } int dcopy(int i, int j) { if (i == j || i < 0 || (j < 0 && i > FSAFE)) return (i); if (j >= 0) { #ifdef HAVE_DUP2 (void) xdup2(i, j); return (j); #else xclose(j); #endif } return (renum(i, j)); } static int renum(int i, int j) { int k = dup(i); if (k < 0) return (-1); if (j == -1 && k > FSAFE) return (k); if (k != j) { j = renum(k, j); xclose(k); return (j); } return (k); } /* * Left shift a command argument list, discarding * the first c arguments. Used in "shift" commands * as well as by commands like "repeat". */ void lshift(Char **v, int c) { Char **u; for (u = v; *u && --c >= 0; u++) xfree(*u); (void) blkcpy(v, u); } int number(Char *cp) { if (!cp) return (0); if (*cp == '-') { cp++; if (!Isdigit(*cp)) return (0); cp++; } while (*cp && Isdigit(*cp)) cp++; return (*cp == 0); } Char ** copyblk(Char **v) { Char **nv = xcalloc(blklen(v) + 1, sizeof(Char **)); return (blkcpy(nv, v)); } char * strend(const char *cp) { if (!cp) return ((char *)(intptr_t)cp); while (*cp) cp++; return ((char *)(intptr_t)cp); } Char * strip(Char *cp) { Char *dp = cp; if (!cp) return (cp); while (*dp != '\0') { #if INVALID_BYTE != 0 if ((*dp & INVALID_BYTE) != INVALID_BYTE) /* *dp < INVALID_BYTE */ #endif *dp &= TRIM; dp++; } return (cp); } Char * quote(Char *cp) { Char *dp = cp; if (!cp) return (cp); while (*dp != '\0') { #ifdef WIDE_STRINGS if ((*dp & 0xffffff80) == 0) /* *dp < 0x80 */ #elif defined SHORT_STRINGS if ((*dp & 0xff80) == 0) /* *dp < 0x80 */ #else if ((*dp & 0x80) == 0) /* *dp < 0x80 */ #endif *dp |= QUOTE; dp++; } return (cp); } const Char * quote_meta(struct Strbuf *buf, const Char *s) { buf->len = 0; while (*s != '\0') { if (cmap(*s, _META | _DOL | _QF | _QB | _ESC | _GLOB)) Strbuf_append1(buf, '\\'); Strbuf_append1(buf, *s++); } Strbuf_terminate(buf); return buf->s; } void udvar(Char *name) { setname(short2str(name)); stderror(ERR_NAME | ERR_UNDVAR); } int prefix(const Char *sub, const Char *str) { for (;;) { if (*sub == 0) return (1); if (*str == 0) return (0); if ((*sub++ & TRIM) != (*str++ & TRIM)) return (0); } } #ifndef WINNT_NATIVE char * areadlink(const char *path) { char *buf; size_t size; ssize_t res; #ifdef __IBMC__ /* * Prevent infinite recursion. Someone should tell me how to expand * these... */ size_t i; static const char *vars[] = { "/$VERSION", "/$SYSNAME", "/$SYSSYMR", "/$SYSSYMA", }; for (i = 0; i < sizeof(vars) / sizeof(vars[0]); i++) { if (strcmp(vars[i], path) == 0) { return NULL; } } #endif size = MAXPATHLEN + 1; buf = xmalloc(size); while ((size_t)(res = readlink(path, buf, size)) == size) { size *= 2; buf = xrealloc(buf, size); } if (res == -1) { int err; err = errno; xfree(buf); errno = err; return NULL; } buf[res] = '\0'; return xrealloc(buf, res + 1); } #endif /*!WINNT_NATIVE*/ void xclose(int fildes) { if (fildes < 0) return; while (close(fildes) == -1 && errno == EINTR) if (handle_pending_signals()) break; } void xclosedir(DIR *dirp) { while (closedir(dirp) == -1 && errno == EINTR) if (handle_pending_signals()) break; } int xcreat(const char *path, mode_t mode) { int res; while ((res = creat(path, mode)) == -1 && errno == EINTR) if (handle_pending_signals()) break; return res; } #ifdef HAVE_DUP2 static int xdup2(int fildes, int fildes2) { int res; while ((res = dup2(fildes, fildes2)) == -1 && errno == EINTR) if (handle_pending_signals()) break; return res; } #endif struct group * xgetgrgid(gid_t xgid) { struct group *res; errno = 0; while ((res = getgrgid(xgid)) == NULL && errno == EINTR) { if (handle_pending_signals()) break; errno = 0; } return res; } struct passwd * xgetpwnam(const char *name) { struct passwd *res; errno = 0; while ((res = getpwnam(name)) == NULL && errno == EINTR) { if (handle_pending_signals()) break; errno = 0; } return res; } struct passwd * xgetpwuid(uid_t xuid) { struct passwd *res; errno = 0; while ((res = getpwuid(xuid)) == NULL && errno == EINTR) { if (handle_pending_signals()) break; errno = 0; } return res; } int xopen(const char *path, int oflag, ...) { int res; if ((oflag & O_CREAT) == 0) { while ((res = open(path, oflag)) == -1 && errno == EINTR) if (handle_pending_signals()) break; } else { va_list ap; mode_t mode; va_start(ap, oflag); /* "int" should actually be "mode_t after default argument promotions". "int" is the best guess we have, "mode_t" used to be "unsigned short", which we obviously can't use. */ mode = va_arg(ap, int); va_end(ap); while ((res = open(path, oflag, mode)) == -1 && errno == EINTR) if (handle_pending_signals()) break; } return res; } ssize_t xread(int fildes, void *buf, size_t nbyte) { ssize_t res = -1; /* This is where we will be blocked most of the time, so handle signals that didn't interrupt any system call. */ do if (handle_pending_signals()) break; while ((res = read(fildes, buf, nbyte)) == -1 && errno == EINTR); return res; } #ifdef POSIX int xtcsetattr(int fildes, int optional_actions, const struct termios *termios_p) { int res; while ((res = tcsetattr(fildes, optional_actions, termios_p)) == -1 && errno == EINTR) if (handle_pending_signals()) break; return res; } #endif ssize_t xwrite(int fildes, const void *buf, size_t nbyte) { ssize_t res = -1; /* This is where we will be blocked most of the time, so handle signals that didn't interrupt any system call. */ do if (handle_pending_signals()) break; while ((res = write(fildes, buf, nbyte)) == -1 && errno == EINTR); return res; } diff --git a/contrib/tcsh/sh.parse.c b/contrib/tcsh/sh.parse.c index 6a3d742d746a..211a1012b9a8 100644 --- a/contrib/tcsh/sh.parse.c +++ b/contrib/tcsh/sh.parse.c @@ -1,690 +1,691 @@ /* * sh.parse.c: Interpret a list of tokens */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" /* * C shell */ static int asyntax (struct wordent *, struct wordent *); static int asyn0 (struct wordent *, struct wordent *); static int asyn3 (struct wordent *, struct wordent *); static struct wordent *freenod (struct wordent *, struct wordent *); static struct command *syn0 (const struct wordent *, const struct wordent *, int); static struct command *syn1 (const struct wordent *, const struct wordent *, int); static struct command *syn1a (const struct wordent *, const struct wordent *, int); static struct command *syn1b (const struct wordent *, const struct wordent *, int); static struct command *syn2 (const struct wordent *, const struct wordent *, int); static struct command *syn3 (const struct wordent *, const struct wordent *, int); #define ALEFT 51 /* max of 50 alias expansions */ #define HLEFT 11 /* max of 10 history expansions */ /* * Perform aliasing on the word list lexp * Do a (very rudimentary) parse to separate into commands. * If word 0 of a command has an alias, do it. * Repeat a maximum of 50 times. */ extern int hleft; void alias(struct wordent *lexp) { int aleft; aleft = ALEFT; hleft = HLEFT; do { if (--aleft == 0) stderror(ERR_ALIASLOOP); } while (asyntax(lexp->next, lexp) != 0); } static int asyntax(struct wordent *p1, struct wordent *p2) { while (p1 != p2) { if (!any(";&\n", p1->word[0])) return asyn0(p1, p2); p1 = p1->next; } return 0; } static int asyn0(struct wordent *p1, struct wordent *p2) { struct wordent *p; int l = 0; for (p = p1; p != p2; p = p->next) switch (p->word[0]) { case '(': l++; continue; case ')': l--; if (l < 0) stderror(ERR_TOOMANYRP); continue; case '>': if (p->next != p2 && eq(p->next->word, STRand)) p = p->next; continue; case '&': case '|': case ';': case '\n': if (l != 0) continue; if (asyn3(p1, p) != 0) return 1; return asyntax(p->next, p2); default: break; } if (l == 0) return asyn3(p1, p2); return 0; } static void alvec_cleanup(void *dummy) { USE(dummy); alhistp = NULL; alhistt = NULL; alvec = NULL; } static int asyn3(struct wordent *p1, struct wordent *p2) { struct varent *ap; struct wordent alout; int redid; if (p1 == p2) return 0; if (p1->word[0] == '(') { for (p2 = p2->prev; p2->word[0] != ')'; p2 = p2->prev) if (p2 == p1) return 0; if (p2 == p1->next) return 0; return asyn0(p1->next, p2); } ap = adrof1(p1->word, &aliases); if (ap == 0) return 0; alhistp = p1->prev; alhistt = p2; alvec = ap->vec; cleanup_push(&alvec, alvec_cleanup); redid = lex(&alout); cleanup_until(&alvec); if (seterr) { freelex(&alout); stderror(ERR_OLD); } if (p1->word[0] && eq(p1->word, alout.next->word)) { Char *cp = alout.next->word; alout.next->word = Strspl(STRQNULL, cp); xfree(cp); } p1 = freenod(p1, redid ? p2 : p1->next); if (alout.next != &alout) { p1->next->prev = alout.prev->prev; alout.prev->prev->next = p1->next; alout.next->prev = p1; p1->next = alout.next; xfree(alout.prev->word); xfree(alout.prev); } return 1; } static struct wordent * freenod(struct wordent *p1, struct wordent *p2) { struct wordent *retp = p1->prev; while (p1 != p2) { xfree(p1->word); p1 = p1->next; xfree(p1->prev); } retp->next = p2; p2->prev = retp; return (retp); } #define P_HERE 1 #define P_IN 2 #define P_OUT 4 #define P_DIAG 8 /* * syntax * empty * syn0 */ struct command * syntax(const struct wordent *p1, const struct wordent *p2, int flags) { while (p1 != p2) if (any(";&\n", p1->word[0])) p1 = p1->next; else return (syn0(p1, p2, flags)); return (0); } /* * syn0 * syn1 * syn1 & syntax */ static struct command * syn0(const struct wordent *p1, const struct wordent *p2, int flags) { const struct wordent *p; struct command *t, *t1; int l; l = 0; for (p = p1; p != p2; p = p->next) switch (p->word[0]) { case '(': l++; continue; case ')': l--; if (l < 0) seterror(ERR_TOOMANYRP); continue; case '|': if (p->word[1] == '|') continue; /*FALLTHROUGH*/ case '>': if (p->next != p2 && eq(p->next->word, STRand)) p = p->next; continue; case '&': if (l != 0) break; if (p->word[1] == '&') continue; t1 = syn1(p1, p, flags); if (t1->t_dtyp == NODE_LIST || t1->t_dtyp == NODE_AND || t1->t_dtyp == NODE_OR) { t = xcalloc(1, sizeof(*t)); t->t_dtyp = NODE_PAREN; t->t_dflg = F_AMPERSAND | F_NOINTERRUPT; t->t_dspr = t1; t1 = t; } else t1->t_dflg |= F_AMPERSAND | F_NOINTERRUPT; t = xcalloc(1, sizeof(*t)); t->t_dtyp = NODE_LIST; t->t_dflg = 0; t->t_dcar = t1; t->t_dcdr = syntax(p, p2, flags); return (t); default: break; } if (l == 0) return (syn1(p1, p2, flags)); seterror(ERR_TOOMANYLP); return (0); } /* * syn1 * syn1a * syn1a ; syntax */ static struct command * syn1(const struct wordent *p1, const struct wordent *p2, int flags) { const struct wordent *p; struct command *t; int l; l = 0; for (p = p1; p != p2; p = p->next) switch (p->word[0]) { case '(': l++; continue; case ')': l--; continue; case ';': case '\n': if (l != 0) break; t = xcalloc(1, sizeof(*t)); t->t_dtyp = NODE_LIST; t->t_dcar = syn1a(p1, p, flags); t->t_dcdr = syntax(p->next, p2, flags); if (t->t_dcdr == 0) t->t_dcdr = t->t_dcar, t->t_dcar = 0; return (t); default: break; } return (syn1a(p1, p2, flags)); } /* * syn1a * syn1b * syn1b || syn1a */ static struct command * syn1a(const struct wordent *p1, const struct wordent *p2, int flags) { const struct wordent *p; struct command *t; int l = 0; for (p = p1; p != p2; p = p->next) switch (p->word[0]) { case '(': l++; continue; case ')': l--; continue; case '|': if (p->word[1] != '|') continue; if (l == 0) { t = xcalloc(1, sizeof(*t)); t->t_dtyp = NODE_OR; t->t_dcar = syn1b(p1, p, flags); t->t_dcdr = syn1a(p->next, p2, flags); t->t_dflg = 0; return (t); } continue; default: break; } return (syn1b(p1, p2, flags)); } /* * syn1b * syn2 * syn2 && syn1b */ static struct command * syn1b(const struct wordent *p1, const struct wordent *p2, int flags) { const struct wordent *p; struct command *t; int l = 0; for (p = p1; p != p2; p = p->next) switch (p->word[0]) { case '(': l++; continue; case ')': l--; continue; case '&': if (p->word[1] == '&' && l == 0) { t = xcalloc(1, sizeof(*t)); t->t_dtyp = NODE_AND; t->t_dcar = syn2(p1, p, flags); t->t_dcdr = syn1b(p->next, p2, flags); t->t_dflg = 0; return (t); } continue; default: break; } return (syn2(p1, p2, flags)); } /* * syn2 * syn3 * syn3 | syn2 * syn3 |& syn2 */ static struct command * syn2(const struct wordent *p1, const struct wordent *p2, int flags) { const struct wordent *p, *pn; struct command *t; int l = 0; int f; for (p = p1; p != p2; p = p->next) switch (p->word[0]) { case '(': l++; continue; case ')': l--; continue; case '|': if (l != 0) continue; t = xcalloc(1, sizeof(*t)); f = flags | P_OUT; pn = p->next; if (pn != p2 && pn->word[0] == '&') { f |= P_DIAG; t->t_dflg |= F_STDERR; } t->t_dtyp = NODE_PIPE; t->t_dcar = syn3(p1, p, f); if (pn != p2 && pn->word[0] == '&') p = pn; t->t_dcdr = syn2(p->next, p2, flags | P_IN); return (t); default: break; } return (syn3(p1, p2, flags)); } static const char RELPAR[] = {'<', '>', '(', ')', '\0'}; /* * syn3 * ( syn0 ) [ < in ] [ > out ] * word word* [ < in ] [ > out ] * KEYWORD ( word* ) word* [ < in ] [ > out ] * * KEYWORD = (@ exit foreach if set switch test while) */ static struct command * syn3(const struct wordent *p1, const struct wordent *p2, int flags) { const struct wordent *p; const struct wordent *lp, *rp; struct command *t; int l; Char **av; int n, c; int specp = 0; if (p1 != p2) { p = p1; again: switch (srchx(p->word)) { case TC_ELSE: p = p->next; if (p != p2) goto again; break; case TC_EXIT: case TC_FOREACH: case TC_IF: case TC_LET: case TC_SET: case TC_SWITCH: case TC_WHILE: specp = 1; break; default: break; } } n = 0; l = 0; for (p = p1; p != p2; p = p->next) switch (p->word[0]) { case '(': if (specp) n++; l++; continue; case ')': if (specp) n++; l--; continue; case '>': case '<': if (l != 0) { if (specp) n++; continue; } if (p->next == p2) continue; if (any(RELPAR, p->next->word[0])) continue; n--; continue; default: if (!specp && l != 0) continue; n++; continue; } if (n < 0) n = 0; t = xcalloc(1, sizeof(*t)); av = xcalloc(n + 1, sizeof(Char **)); t->t_dcom = av; n = 0; if (p2->word[0] == ')') t->t_dflg = F_NOFORK; lp = 0; rp = 0; l = 0; for (p = p1; p != p2; p = p->next) { c = p->word[0]; switch (c) { case '(': if (l == 0) { if (lp != 0 && !specp) seterror(ERR_BADPLP); lp = p->next; } l++; goto savep; case ')': l--; if (l == 0) rp = p; goto savep; case '>': if (l != 0) goto savep; if (p->word[1] == '>') t->t_dflg |= F_APPEND; if (p->next != p2 && eq(p->next->word, STRand)) { t->t_dflg |= F_STDERR, p = p->next; if (flags & (P_OUT | P_DIAG)) { seterror(ERR_OUTRED); continue; } } if (p->next != p2 && eq(p->next->word, STRbang)) t->t_dflg |= F_OVERWRITE, p = p->next; if (p->next == p2) { seterror(ERR_MISRED); continue; } p = p->next; if (any(RELPAR, p->word[0])) { seterror(ERR_MISRED); continue; } if (((flags & P_OUT) && (flags & P_DIAG) == 0) || t->t_drit) seterror(ERR_OUTRED); else t->t_drit = Strsave(p->word); continue; case '<': if (l != 0) goto savep; if (p->word[1] == '<') t->t_dflg |= F_READ; if (p->next == p2) { seterror(ERR_MISRED); continue; } p = p->next; if (any(RELPAR, p->word[0])) { seterror(ERR_MISRED); continue; } if ((flags & P_HERE) && (t->t_dflg & F_READ)) seterror(ERR_REDPAR); else if ((flags & P_IN) || t->t_dlef) seterror(ERR_INRED); else t->t_dlef = Strsave(p->word); continue; savep: if (!specp) continue; + /* FALLTHROUGH */ default: if (l != 0 && !specp) continue; if (seterr == 0) av[n] = Strsave(p->word); n++; continue; } } if (lp != 0 && !specp) { if (n != 0) seterror(ERR_BADPLPS); t->t_dtyp = NODE_PAREN; t->t_dspr = syn0(lp, rp, P_HERE); } else { if (n == 0) seterror(ERR_NULLCOM); t->t_dtyp = NODE_COMMAND; } return (t); } void freesyn(struct command *t) { Char **v; if (t == 0) return; switch (t->t_dtyp) { case NODE_COMMAND: for (v = t->t_dcom; *v; v++) xfree(*v); xfree(t->t_dcom); xfree(t->t_dlef); xfree(t->t_drit); break; case NODE_PAREN: freesyn(t->t_dspr); xfree(t->t_dlef); xfree(t->t_drit); break; case NODE_AND: case NODE_OR: case NODE_PIPE: case NODE_LIST: freesyn(t->t_dcar), freesyn(t->t_dcdr); break; default: break; } #ifdef DEBUG memset(t, 0, sizeof(*t)); #endif xfree(t); } void syntax_cleanup(void *xt) { struct command *t; t = xt; freesyn(t); } diff --git a/contrib/tcsh/sh.print.c b/contrib/tcsh/sh.print.c index bfdae125b62c..df0b92b6453b 100644 --- a/contrib/tcsh/sh.print.c +++ b/contrib/tcsh/sh.print.c @@ -1,311 +1,311 @@ /* * sh.print.c: Primitive Output routines. */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" extern int Tty_eight_bit; int lbuffed = 1; /* true if line buffered */ static void p2dig (unsigned int); /* * C Shell */ #if defined(BSDLIMIT) || defined(RLIMIT_CPU) void psecs(unsigned long l) { int i; i = (int) (l / 3600); if (i) { xprintf("%d:", i); i = (int) (l % 3600); p2dig(i / 60); goto minsec; } i = (int) l; xprintf("%d", i / 60); minsec: i %= 60; xprintf(":"); p2dig(i); } #endif void /* PWP: print mm:ss.dd, l is in sec*100 */ #ifdef BSDTIMES pcsecs(unsigned long l) #else /* BSDTIMES */ # ifndef POSIX pcsecs(time_t l) # else /* POSIX */ pcsecs(clock_t l) # endif /* POSIX */ #endif /* BSDTIMES */ { int i; i = (int) (l / 360000); if (i) { xprintf("%d:", i); i = (int) ((l % 360000) / 100); p2dig(i / 60); goto minsec; } i = (int) (l / 100); xprintf("%d", i / 60); minsec: i %= 60; xprintf(":"); p2dig(i); xprintf("."); p2dig((int) (l % 100)); } -static void +static void p2dig(unsigned i) { xprintf("%u%u", i / 10, i % 10); } char linbuf[2048]; /* was 128 */ char *linp = linbuf; int output_raw = 0; /* PWP */ int xlate_cr = 0; /* HE */ /* For cleanup_push() */ void output_raw_restore(void *xorig) { int *orig; orig = xorig; output_raw = *orig; } #ifdef WIDE_STRINGS void putwraw(Char c) { char buf[MB_LEN_MAX]; size_t i, len; - + len = one_wctomb(buf, c & CHAR); for (i = 0; i < len; i++) putraw((unsigned char)buf[i] | (c & ~CHAR)); } void xputwchar(Char c) { char buf[MB_LEN_MAX]; size_t i, len; - + len = one_wctomb(buf, c & CHAR); for (i = 0; i < len; i++) xputchar((unsigned char)buf[i] | (c & ~CHAR)); } #endif void xputchar(int c) { int atr; atr = c & ATTRIBUTES & TRIM; c &= CHAR | QUOTE; if (!output_raw && (c & QUOTE) == 0) { if (iscntrl(c) && (ASC(c) < 0x80 || MB_CUR_MAX == 1)) { if (c != '\t' && c != '\n' #ifdef COLORCAT && !(adrof(STRcolorcat) && c == CTL_ESC('\033')) #endif && (xlate_cr || c != '\r')) { xputchar('^' | atr); if (c == CTL_ESC('\177')) c = '?'; else /* Note: for IS_ASCII, this compiles to: c = c | 0100 */ c = CTL_ESC(ASC(c)|0100); } } else if (!isprint(c) && (ASC(c) < 0x80 || MB_CUR_MAX == 1)) { xputchar('\\' | atr); xputchar((((c >> 6) & 7) + '0') | atr); xputchar((((c >> 3) & 7) + '0') | atr); c = (c & 7) + '0'; } (void) putraw(c | atr); } else { c &= TRIM; if (haderr ? (didfds ? is2atty : isdiagatty) : (didfds ? is1atty : isoutatty)) SetAttributes(c | atr); (void) putpure(c); } if (lbuffed && (c & CHAR) == '\n') flush(); } int putraw(int c) { if (haderr ? (didfds ? is2atty : isdiagatty) : (didfds ? is1atty : isoutatty)) { if (Tty_eight_bit == -1) ed_set_tty_eight_bit(); if (!Tty_eight_bit && (c & META)) { c = (c & ~META) | STANDOUT; } SetAttributes(c); } return putpure(c); } int putpure(int c) { c &= CHAR; *linp++ = (char) c; if (linp >= &linbuf[sizeof linbuf - 10]) flush(); return (1); } void drainoline(void) { linp = linbuf; } void flush(void) { int unit, oldexitset = exitset; static int interrupted = 0; /* int lmode; */ if (linp == linbuf) return; if (GettingInput && !Tty_raw_mode && linp < &linbuf[sizeof linbuf - 10]) return; if (handle_interrupt) exitset = 1; if (interrupted) { interrupted = 0; linp = linbuf; /* avoid recursion as stderror calls flush */ if (handle_interrupt) fixerror(); else stderror(ERR_SILENT); } interrupted = 1; if (haderr) unit = didfds ? 2 : SHDIAG; else unit = didfds ? 1 : SHOUT; #ifdef COMMENT #ifdef TIOCLGET if (didfds == 0 && ioctl(unit, TIOCLGET, (ioctl_t) & lmode) == 0 && lmode & LFLUSHO) { lmode = LFLUSHO; (void) ioctl(unit, TIOCLBIC, (ioclt_t) & lmode); (void) xwrite(unit, "\n", 1); } #endif #endif if (xwrite(unit, linbuf, linp - linbuf) == -1) switch (errno) { #ifdef EIO /* We lost our tty */ case EIO: #endif #ifdef ENXIO /* * Deal with Digital Unix 4.0D bogocity, returning ENXIO when * we lose our tty. */ case ENXIO: #endif /* * IRIX 6.4 bogocity? */ #ifdef ENOTTY case ENOTTY: #endif #ifdef EBADF case EBADF: #endif #ifdef ESTALE /* * Lost our file descriptor, exit (IRIS4D) */ case ESTALE: #endif #ifdef ENOENT /* * Deal with SoFS bogocity: returns ENOENT instead of ESTALE. */ case ENOENT: #endif /* * Over our quota, writing the history file */ #ifdef EDQUOT case EDQUOT: #endif /* Nothing to do, but die */ if (handle_interrupt == 0) xexit(1); /*FALLTHROUGH*/ default: if (handle_interrupt) fixerror(); else stderror(ERR_SILENT); break; } exitset = oldexitset; linp = linbuf; interrupted = 0; } diff --git a/contrib/tcsh/sh.proc.c b/contrib/tcsh/sh.proc.c index caf7362a3e77..2d2a61e33ca9 100644 --- a/contrib/tcsh/sh.proc.c +++ b/contrib/tcsh/sh.proc.c @@ -1,2057 +1,2057 @@ /* * sh.proc.c: Job manipulations */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include "tc.h" #include "tc.wait.h" #ifdef WINNT_NATIVE #undef POSIX #define POSIX #endif /* WINNT_NATIVE */ #ifdef aiws # undef HZ # define HZ 16 #endif /* aiws */ #if defined(_BSD) || (defined(IRIS4D) && __STDC__) || defined(__lucid) # define BSDWAIT #endif /* _BSD || (IRIS4D && __STDC__) || __lucid */ #ifndef WTERMSIG # define WTERMSIG(w) (((union wait *) &(w))->w_termsig) # ifndef BSDWAIT # define BSDWAIT # endif /* !BSDWAIT */ #endif /* !WTERMSIG */ #ifndef WEXITSTATUS # define WEXITSTATUS(w) (((union wait *) &(w))->w_retcode) #endif /* !WEXITSTATUS */ #ifndef WSTOPSIG # define WSTOPSIG(w) (((union wait *) &(w))->w_stopsig) #endif /* !WSTOPSIG */ #ifdef __osf__ # ifndef WCOREDUMP # define WCOREDUMP(x) (_W_INT(x) & WCOREFLAG) # endif #endif #ifndef WCOREDUMP # ifdef BSDWAIT # define WCOREDUMP(w) (((union wait *) &(w))->w_coredump) # else /* !BSDWAIT */ # define WCOREDUMP(w) ((w) & 0200) # endif /* !BSDWAIT */ #endif /* !WCOREDUMP */ #ifndef JOBDEBUG # define jobdebug_xprintf(x) (void)0 # define jobdebug_flush() (void)0 #else # define jobdebug_xprintf(s) xprintf s # define jobdebug_flush() flush() #endif /* * C Shell - functions that manage processes, handling hanging, termination */ #define BIGINDEX 9 /* largest desirable job index */ #ifdef BSDTIMES # ifdef convex /* use 'cvxrusage' to get parallel statistics */ static struct cvxrusage zru = {{0L, 0L}, {0L, 0L}, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, {0L, 0L}, 0LL, 0LL, 0LL, 0LL, 0L, 0L, 0L, 0LL, 0LL, {0L, 0L, 0L, 0L, 0L}}; # else static struct rusage zru; # endif /* convex */ #else /* !BSDTIMES */ # ifdef _SEQUENT_ static struct process_stats zru = {{0L, 0L}, {0L, 0L}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; # else /* !_SEQUENT_ */ # ifdef _SX static struct tms zru = {0, 0, 0, 0}, lru = {0, 0, 0, 0}; # else /* !_SX */ static struct tms zru = {0L, 0L, 0L, 0L}, lru = {0L, 0L, 0L, 0L}; # endif /* !_SX */ # endif /* !_SEQUENT_ */ #endif /* !BSDTIMES */ #ifndef BSDTIMES static int timesdone; /* shtimes buffer full ? */ #endif /* BSDTIMES */ #ifndef RUSAGE_CHILDREN # define RUSAGE_CHILDREN -1 #endif /* RUSAGE_CHILDREN */ static void pflushall (void); static void pflush (struct process *); static void pfree (struct process *); static void pclrcurr (struct process *); static void morecommand (size_t); static void padd (struct command *); static int pprint (struct process *, int); static void ptprint (struct process *); static void pads (Char *); static void pkill (Char **, int); static struct process *pgetcurr (struct process *); static void okpcntl (void); static void setttypgrp (int); /* * pchild - call queued by the SIGCHLD signal * indicating that at least one child has terminated or stopped * thus at least one wait system call will definitely return a * childs status. Top level routines (like pwait) must be sure * to mask interrupts when playing with the proclist data structures! */ void pchild(void) { struct process *pp; struct process *fp; pid_t pid; #ifdef BSDWAIT union wait w; #else /* !BSDWAIT */ int w; #endif /* !BSDWAIT */ int jobflags; #ifdef BSDTIMES struct sysrusage ru; #else /* !BSDTIMES */ # ifdef _SEQUENT_ struct process_stats ru; struct process_stats cpst1, cpst2; timeval_t tv; # else /* !_SEQUENT_ */ struct tms proctimes; if (!timesdone) { timesdone++; (void) times(&shtimes); } # endif /* !_SEQUENT_ */ #endif /* !BSDTIMES */ jobdebug_xprintf(("pchild()\n")); loop: jobdebug_xprintf(("Waiting...\n")); jobdebug_flush(); errno = 0; /* reset, just in case */ #ifndef WINNT_NATIVE # ifdef BSDJOBS # ifdef BSDTIMES # ifdef convex /* use 'cvxwait' to get parallel statistics */ pid = cvxwait(&w, (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru); # else /* both a wait3 and rusage */ # if !defined(BSDWAIT) || defined(NeXT) || defined(MACH) || defined(__linux__) || defined(__GNU__) || defined(__GLIBC__) || (defined(IRIS4D) && SYSVREL <= 3) || defined(__lucid) || defined(__osf__) #ifdef __ANDROID__ /* no wait3, only wait4 */ pid = wait4(-1, &w, (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru); #else pid = wait3(&w, (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru); #endif /* __ANDROID__ */ # else /* BSDWAIT */ pid = wait3(&w.w_status, (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), &ru); # endif /* BSDWAIT */ # endif /* convex */ # else /* !BSDTIMES */ # ifdef _SEQUENT_ (void) get_process_stats(&tv, PS_SELF, 0, &cpst1); pid = waitpid(-1, &w, (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG)); (void) get_process_stats(&tv, PS_SELF, 0, &cpst2); pr_stat_sub(&cpst2, &cpst1, &ru); # else /* !_SEQUENT_ */ # ifndef POSIX /* we have a wait3, but no rusage stuff */ pid = wait3(&w.w_status, (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), 0); # else /* POSIX */ pid = waitpid(-1, &w, (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG)); # endif /* POSIX */ # endif /* !_SEQUENT_ */ # endif /* !BSDTIMES */ # else /* !BSDJOBS */ # ifdef BSDTIMES # define HAVEwait3 /* both a wait3 and rusage */ # ifdef hpux pid = wait3(&w.w_status, WNOHANG, 0); # else /* !hpux */ # ifndef BSDWAIT pid = wait3(&w, WNOHANG, &ru); # else pid = wait3(&w.w_status, WNOHANG, &ru); # endif /* BSDWAIT */ # endif /* !hpux */ # else /* !BSDTIMES */ # ifdef ODT /* For Sco Unix 3.2.0 or ODT 1.0 */ # define HAVEwait3 pid = waitpid(-1, &w, (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG)); -# endif /* ODT */ +# endif /* ODT */ # if defined(aiws) || defined(uts) # define HAVEwait3 - pid = wait3(&w.w_status, + pid = wait3(&w.w_status, (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG), 0); # endif /* aiws || uts */ # ifndef HAVEwait3 # ifndef BSDWAIT /* no wait3, therefore no rusage */ /* on Sys V, this may hang. I hope it's not going to be a problem */ pid = wait(&w); # else /* BSDWAIT */ - /* - * XXX: for greater than 3 we should use waitpid(). + /* + * XXX: for greater than 3 we should use waitpid(). * but then again, SVR4 falls into the POSIX/BSDJOBS category. */ pid = wait(&w.w_status); # endif /* BSDWAIT */ # endif /* !HAVEwait3 */ # endif /* !BSDTIMES */ # endif /* !BSDJOBS */ #else /* WINNT_NATIVE */ pid = waitpid(-1, &w, (setintr && (intty || insource) ? WNOHANG | WUNTRACED : WNOHANG)); #endif /* WINNT_NATIVE */ jobdebug_xprintf(("parent %d pid %d, retval %x termsig %x retcode %x\n", (int)getpid(), (int)pid, w, WTERMSIG(w), WEXITSTATUS(w))); jobdebug_flush(); if ((pid == 0) || (pid == -1)) { (void)handle_pending_signals(); jobdebug_xprintf(("errno == %d\n", errno)); if (errno == EINTR) goto loop; goto end; } for (pp = proclist.p_next; pp != NULL; pp = pp->p_next) if (pid == pp->p_procid) goto found; #if !defined(BSDJOBS) && !defined(WINNT_NATIVE) /* this should never have happened */ stderror(ERR_SYNC, pid); xexit(0); #else /* BSDJOBS || WINNT_NATIVE */ goto loop; #endif /* !BSDJOBS && !WINNT_NATIVE */ found: pp->p_flags &= ~(PRUNNING | PSTOPPED | PREPORTED); if (WIFSTOPPED(w)) { pp->p_flags |= PSTOPPED; pp->p_reason = WSTOPSIG(w); } else { if (pp->p_flags & (PTIME | PPTIME) || adrof(STRtime)) #ifndef BSDTIMES # ifdef _SEQUENT_ (void) get_process_stats(&pp->p_etime, PS_SELF, NULL, NULL); # else /* !_SEQUENT_ */ pp->p_etime = times(&proctimes); # endif /* !_SEQUENT_ */ #else /* BSDTIMES */ (void) gettimeofday(&pp->p_etime, NULL); #endif /* BSDTIMES */ #if defined(BSDTIMES) || defined(_SEQUENT_) pp->p_rusage = ru; #else /* !BSDTIMES && !_SEQUENT_ */ (void) times(&proctimes); pp->p_utime = proctimes.tms_cutime - shtimes.tms_cutime; pp->p_stime = proctimes.tms_cstime - shtimes.tms_cstime; shtimes = proctimes; #endif /* !BSDTIMES && !_SEQUENT_ */ if (WIFSIGNALED(w)) { if (WTERMSIG(w) == SIGINT) pp->p_flags |= PINTERRUPTED; else pp->p_flags |= PSIGNALED; if (WCOREDUMP(w)) pp->p_flags |= PDUMPED; pp->p_reason = WTERMSIG(w); } else { pp->p_reason = WEXITSTATUS(w); if (pp->p_reason != 0) pp->p_flags |= PAEXITED; else pp->p_flags |= PNEXITED; } } jobflags = 0; fp = pp; do { if ((fp->p_flags & (PPTIME | PRUNNING | PSTOPPED)) == 0 && !child && adrof(STRtime) && #ifdef BSDTIMES fp->p_rusage.ru_utime.tv_sec + fp->p_rusage.ru_stime.tv_sec #else /* !BSDTIMES */ # ifdef _SEQUENT_ fp->p_rusage.ps_utime.tv_sec + fp->p_rusage.ps_stime.tv_sec # else /* !_SEQUENT_ */ # ifndef POSIX (fp->p_utime + fp->p_stime) / HZ # else /* POSIX */ (fp->p_utime + fp->p_stime) / clk_tck # endif /* POSIX */ # endif /* !_SEQUENT_ */ #endif /* !BSDTIMES */ >= atoi(short2str(varval(STRtime)))) fp->p_flags |= PTIME; jobflags |= fp->p_flags; } while ((fp = fp->p_friends) != pp); pp->p_flags &= ~PFOREGND; if (pp == pp->p_friends && (pp->p_flags & PPTIME)) { pp->p_flags &= ~PPTIME; pp->p_flags |= PTIME; } if ((jobflags & (PRUNNING | PREPORTED)) == 0) { fp = pp; do { if (fp->p_flags & PSTOPPED) fp->p_flags |= PREPORTED; } while ((fp = fp->p_friends) != pp); while (fp->p_procid != fp->p_jobid) fp = fp->p_friends; if (jobflags & PSTOPPED) { if (pcurrent && pcurrent != fp) pprevious = pcurrent; pcurrent = fp; } else pclrcurr(fp); if (jobflags & PFOREGND) { if (!(jobflags & (PSIGNALED | PSTOPPED | PPTIME) || #ifdef notdef jobflags & PAEXITED || #endif /* notdef */ fp->p_cwd == NULL || !eq(dcwd->di_name, fp->p_cwd->di_name))) { /* PWP: print a newline after ^C */ if (jobflags & PINTERRUPTED) { xputchar('\r' | QUOTE); xputchar('\n'); } #ifdef notdef else if ((jobflags & (PTIME|PSTOPPED)) == PTIME) ptprint(fp); #endif /* notdef */ } } else { if (jobflags & PNOTIFY || adrof(STRnotify)) { xputchar('\r' | QUOTE); xputchar('\n'); (void) pprint(pp, NUMBER | NAME | REASON); if ((jobflags & PSTOPPED) == 0) pflush(pp); if (GettingInput) { errno = 0; (void) Rawmode(); #ifdef notdef /* * don't really want to do that, because it * will erase our message in case of multi-line * input */ ClearLines(); #endif /* notdef */ ClearDisp(); Refresh(); } } else { fp->p_flags |= PNEEDNOTE; neednote = 1; } } } #if defined(BSDJOBS) || defined(HAVEwait3) ||defined(WINNT_NATIVE) goto loop; #endif /* BSDJOBS || HAVEwait3 */ end: ; } void pnote(void) { struct process *pp; int flags; neednote = 0; for (pp = proclist.p_next; pp != NULL; pp = pp->p_next) { if (pp->p_flags & PNEEDNOTE) { pchild_disabled++; cleanup_push(&pchild_disabled, disabled_cleanup); pp->p_flags &= ~PNEEDNOTE; flags = pprint(pp, NUMBER | NAME | REASON); if ((flags & (PRUNNING | PSTOPPED)) == 0) pflush(pp); cleanup_until(&pchild_disabled); } } } static void pfree(struct process *pp) -{ +{ xfree(pp->p_command); if (pp->p_cwd && --pp->p_cwd->di_count == 0) if (pp->p_cwd->di_next == 0) dfree(pp->p_cwd); xfree(pp); } /* * pwait - wait for current job to terminate, maintaining integrity * of current and previous job indicators. */ void pwait(void) { struct process *fp, *pp; /* * Here's where dead procs get flushed. */ for (pp = (fp = &proclist)->p_next; pp != NULL; pp = (fp = pp)->p_next) if (pp->p_procid == 0) { fp->p_next = pp->p_next; pfree(pp); pp = fp; } pjwait(pcurrjob); } /* * pjwait - wait for a job to finish or become stopped * It is assumed to be in the foreground state (PFOREGND) */ void pjwait(struct process *pp) { struct process *fp; int jobflags, reason; sigset_t oset, set, pause_mask; Char *reason_str; while (pp->p_procid != pp->p_jobid) pp = pp->p_friends; fp = pp; do { if ((fp->p_flags & (PFOREGND | PRUNNING)) == PRUNNING) xprintf("%s", CGETS(17, 1, "BUG: waiting for background job!\n")); } while ((fp = fp->p_friends) != pp); /* * Now keep pausing as long as we are not interrupted (SIGINT), and the * target process, or any of its friends, are running */ fp = pp; sigemptyset(&set); sigaddset(&set, SIGINT); sigaddset(&set, SIGCHLD); (void)sigprocmask(SIG_BLOCK, &set, &oset); cleanup_push(&oset, sigprocmask_cleanup); pause_mask = oset; sigdelset(&pause_mask, SIGCHLD); sigaddset(&pause_mask, SIGINT); for (;;) { (void)handle_pending_signals(); jobflags = 0; do jobflags |= fp->p_flags; while ((fp = (fp->p_friends)) != pp); if ((jobflags & PRUNNING) == 0) break; jobdebug_xprintf(("%d starting to sigsuspend for SIGCHLD on %d\n", getpid(), fp->p_procid)); sigsuspend(&pause_mask); } cleanup_until(&oset); jobdebug_xprintf(("%d returned from sigsuspend loop\n", getpid())); #ifdef BSDJOBS if (tpgrp > 0) /* get tty back */ (void) tcsetpgrp(FSHTTY, tpgrp); #endif /* BSDJOBS */ if ((jobflags & (PSIGNALED | PSTOPPED | PTIME)) || fp->p_cwd == NULL || !eq(dcwd->di_name, fp->p_cwd->di_name)) { if (jobflags & PSTOPPED) { xputchar('\n'); if (adrof(STRlistjobs)) { Char *jobcommand[3]; jobcommand[0] = STRjobs; if (eq(varval(STRlistjobs), STRlong)) jobcommand[1] = STRml; else jobcommand[1] = NULL; jobcommand[2] = NULL; dojobs(jobcommand, NULL); (void) pprint(pp, SHELLDIR); } else (void) pprint(pp, AREASON | SHELLDIR); } else (void) pprint(pp, AREASON | SHELLDIR); } if ((jobflags & (PINTERRUPTED | PSTOPPED)) && setintr && (!gointr || !eq(gointr, STRminus))) { if ((jobflags & PSTOPPED) == 0) pflush(pp); pintr1(0); /* NOTREACHED */ } reason = 0; fp = pp; do { /* In case of pipelines only the result of the last * command should be taken in account */ if (!anyerror && !(fp->p_flags & PBRACE) && ((fp->p_flags & PPOU) || (fp->p_flags & PBACKQ))) continue; if (fp->p_reason) reason = fp->p_flags & (PSIGNALED | PINTERRUPTED) ? fp->p_reason | META : fp->p_reason; } while ((fp = fp->p_friends) != pp); /* - * Don't report on backquoted jobs, cause it will mess up + * Don't report on backquoted jobs, cause it will mess up * their output. */ - if ((reason != 0) && (adrof(STRprintexitvalue)) && + if ((reason != 0) && (adrof(STRprintexitvalue)) && (pp->p_flags & PBACKQ) == 0) xprintf(CGETS(17, 2, "Exit %d\n"), reason); reason_str = putn((tcsh_number_t)reason); cleanup_push(reason_str, xfree); setv(STRstatus, reason_str, VAR_READWRITE); cleanup_ignore(reason_str); cleanup_until(reason_str); if (reason && exiterr) exitstat(); pflush(pp); } /* * dowait - wait for all processes to finish */ /*ARGSUSED*/ void dowait(Char **v, struct command *c) { struct process *pp; /* the current block mask to be able to restore */ sigset_t old_mask; /* block mask for critical section: OLD_MASK U {SIGCHLD} */ sigset_t block_mask; /* ignore those during blocking sigsuspend: OLD_MASK / {SIGCHLD, possibly(SIGINT)} */ sigset_t pause_mask; int opintr_disabled, gotsig; USE(c); USE(v); pjobs++; sigprocmask(SIG_BLOCK, NULL, &pause_mask); sigdelset(&pause_mask, SIGCHLD); if (setintr) sigdelset(&pause_mask, SIGINT); /* critical section, block also SIGCHLD */ sigprocmask(SIG_BLOCK, NULL, &block_mask); sigaddset(&block_mask, SIGCHLD); sigprocmask(SIG_BLOCK, &block_mask, &old_mask); /* detect older SIGCHLDs and remove PRUNNING flag from proclist */ (void)handle_pending_signals(); loop: for (pp = proclist.p_next; pp; pp = pp->p_next) if (pp->p_procid && /* pp->p_procid == pp->p_jobid && */ pp->p_flags & PRUNNING) { /* wait for (or pick up alredy blocked) SIGCHLD */ sigsuspend(&pause_mask); /* make the 'wait' interuptable by CTRL-C */ opintr_disabled = pintr_disabled; pintr_disabled = 0; gotsig = handle_pending_signals(); pintr_disabled = opintr_disabled; if (gotsig) break; goto loop; } pjobs = 0; sigprocmask(SIG_SETMASK, &old_mask, NULL); } /* * pflushall - flush all jobs from list (e.g. at fork()) */ static void pflushall(void) { struct process *pp; for (pp = proclist.p_next; pp != NULL; pp = pp->p_next) if (pp->p_procid) pflush(pp); } /* * pflush - flag all process structures in the same job as the * the argument process for deletion. The actual free of the * space is not done here since pflush is called at interrupt level. */ static void pflush(struct process *pp) { struct process *np; int idx; if (pp->p_procid == 0) { xprintf("%s", CGETS(17, 3, "BUG: process flushed twice")); return; } while (pp->p_procid != pp->p_jobid) pp = pp->p_friends; pclrcurr(pp); if (pp == pcurrjob) pcurrjob = 0; idx = pp->p_index; np = pp; do { np->p_index = np->p_procid = 0; np->p_flags &= ~PNEEDNOTE; } while ((np = np->p_friends) != pp); if (idx == pmaxindex) { for (np = proclist.p_next, idx = 0; np; np = np->p_next) if (np->p_index > idx) idx = np->p_index; pmaxindex = idx; } } /* * pclrcurr - make sure the given job is not the current or previous job; * pp MUST be the job leader */ static void pclrcurr(struct process *pp) { if (pp == pcurrent) { if (pprevious != NULL) { pcurrent = pprevious; pprevious = pgetcurr(pp); } else { pcurrent = pgetcurr(pp); pprevious = pgetcurr(pp); } } else if (pp == pprevious) pprevious = pgetcurr(pp); } /* +4 here is 1 for '\0', 1 ea for << >& >> */ static Char *cmdstr; static size_t cmdmax; static size_t cmdlen; static Char *cmdp; #define CMD_INIT 1024 #define CMD_INCR 64 static void morecommand(size_t s) { Char *ncmdstr; ptrdiff_t d; cmdmax += s; ncmdstr = xrealloc(cmdstr, cmdmax * sizeof(*cmdstr)); d = ncmdstr - cmdstr; cmdstr = ncmdstr; cmdp += d; } /* GrP - * unparse - Export padd() functionality + * unparse - Export padd() functionality */ Char * unparse(struct command *t) { if (cmdmax == 0) morecommand(CMD_INIT); cmdp = cmdstr; cmdlen = 0; padd(t); *cmdp++ = '\0'; return Strsave(cmdstr); } /* * palloc - allocate a process structure and fill it up. * an important assumption is made that the process is running. */ void palloc(pid_t pid, struct command *t) { struct process *pp; int i; pp = xcalloc(1, sizeof(struct process)); pp->p_procid = pid; pp->p_parentid = shpgrp; pp->p_flags = ((t->t_dflg & F_AMPERSAND) ? 0 : PFOREGND) | PRUNNING; if (t->t_dflg & F_TIME) pp->p_flags |= PPTIME; if (t->t_dflg & F_BACKQ) pp->p_flags |= PBACKQ; if (t->t_dflg & F_HUP) pp->p_flags |= PHUP; if (t->t_dcom && t->t_dcom[0] && (*t->t_dcom[0] == '{')) pp->p_flags |= PBRACE; if (cmdmax == 0) morecommand(CMD_INIT); cmdp = cmdstr; cmdlen = 0; padd(t); *cmdp++ = 0; if (t->t_dflg & F_PIPEOUT) { pp->p_flags |= PPOU; if (t->t_dflg & F_STDERR) pp->p_flags |= PDIAG; } pp->p_command = Strsave(cmdstr); if (pcurrjob) { struct process *fp; /* careful here with interrupt level */ pp->p_cwd = 0; pp->p_index = pcurrjob->p_index; pp->p_friends = pcurrjob; pp->p_jobid = pcurrjob->p_procid; for (fp = pcurrjob; fp->p_friends != pcurrjob; fp = fp->p_friends) continue; fp->p_friends = pp; } else { pcurrjob = pp; pp->p_jobid = pid; pp->p_friends = pp; pp->p_cwd = dcwd; dcwd->di_count++; if (pmaxindex < BIGINDEX) pp->p_index = ++pmaxindex; else { struct process *np; for (i = 1;; i++) { for (np = proclist.p_next; np; np = np->p_next) if (np->p_index == i) goto tryagain; pp->p_index = i; if (i > pmaxindex) pmaxindex = i; break; tryagain:; } } if (pcurrent == NULL) pcurrent = pp; else if (pprevious == NULL) pprevious = pp; } pp->p_next = proclist.p_next; proclist.p_next = pp; #ifdef BSDTIMES (void) gettimeofday(&pp->p_btime, NULL); #else /* !BSDTIMES */ # ifdef _SEQUENT_ (void) get_process_stats(&pp->p_btime, PS_SELF, NULL, NULL); # else /* !_SEQUENT_ */ { struct tms tmptimes; pp->p_btime = times(&tmptimes); } # endif /* !_SEQUENT_ */ #endif /* !BSDTIMES */ } static void padd(struct command *t) { Char **argp; if (t == 0) return; switch (t->t_dtyp) { case NODE_PAREN: pads(STRLparensp); padd(t->t_dspr); pads(STRspRparen); break; case NODE_COMMAND: for (argp = t->t_dcom; *argp; argp++) { pads(*argp); if (argp[1]) pads(STRspace); } break; case NODE_OR: case NODE_AND: case NODE_PIPE: case NODE_LIST: padd(t->t_dcar); switch (t->t_dtyp) { case NODE_OR: pads(STRspor2sp); break; case NODE_AND: pads(STRspand2sp); break; case NODE_PIPE: pads(STRsporsp); break; case NODE_LIST: pads(STRsemisp); break; default: break; } padd(t->t_dcdr); return; default: break; } if ((t->t_dflg & F_PIPEIN) == 0 && t->t_dlef) { pads((t->t_dflg & F_READ) ? STRspLarrow2sp : STRspLarrowsp); pads(t->t_dlef); } if ((t->t_dflg & F_PIPEOUT) == 0 && t->t_drit) { pads((t->t_dflg & F_APPEND) ? STRspRarrow2 : STRspRarrow); if (t->t_dflg & F_STDERR) pads(STRand); pads(STRspace); pads(t->t_drit); } } static void pads(Char *cp) { size_t i, len; /* * Avoid the Quoted Space alias hack! Reported by: * sam@john-bigboote.ICS.UCI.EDU (Sam Horrocks) */ if (cp[0] == STRQNULL[0]) cp++; i = Strlen(cp); len = cmdlen + i + CMD_INCR; if (len >= cmdmax) morecommand(len); (void) Strcpy(cmdp, cp); cmdp += i; cmdlen += i; } /* * psavejob - temporarily save the current job on a one level stack * so another job can be created. Used for { } in exp6 * and `` in globbing. */ void psavejob(void) { pholdjob = pcurrjob; pcurrjob = NULL; } void psavejob_cleanup(void *dummy) { USE(dummy); pcurrjob = pholdjob; pholdjob = NULL; } /* * pendjob - indicate that a job (set of commands) has been completed * or is about to begin. */ void pendjob(void) { struct process *pp, *tp; if (pcurrjob && (pcurrjob->p_flags & (PFOREGND | PSTOPPED)) == 0) { pp = pcurrjob; pcurrjob = NULL; while (pp->p_procid != pp->p_jobid) pp = pp->p_friends; xprintf("[%d]", pp->p_index); tp = pp; do { xprintf(" %d", pp->p_procid); pp = pp->p_friends; } while (pp != tp); xputchar('\n'); } pholdjob = pcurrjob = 0; } /* * pprint - print a job */ /* * Hacks have been added for SVR4 to deal with pipe's being spawned in * reverse order * * David Dawes (dawes@physics.su.oz.au) Oct 1991 */ static int pprint(struct process *pp, int flag) { int status, reason; struct process *tp; int jobflags, pstatus, pcond; const char *format; int ohaderr; #ifdef BACKPIPE struct process *pipehead = NULL, *pipetail = NULL, *pmarker = NULL; int inpipe = 0; #endif /* BACKPIPE */ while (pp->p_procid != pp->p_jobid) pp = pp->p_friends; if (pp == pp->p_friends && (pp->p_flags & PPTIME)) { pp->p_flags &= ~PPTIME; pp->p_flags |= PTIME; } tp = pp; status = reason = -1; jobflags = 0; ohaderr = haderr; /* Print status to stderr, except for jobs built-in */ haderr = !(flag & JOBLIST); do { #ifdef BACKPIPE /* * The pipeline is reversed, so locate the real head of the pipeline * if pp is at the tail of a pipe (and not already in a pipeline) */ if ((pp->p_friends->p_flags & PPOU) && !inpipe && (flag & NAME)) { inpipe = 1; pipetail = pp; - do + do pp = pp->p_friends; while (pp->p_friends->p_flags & PPOU); pipehead = pp; pmarker = pp; /* * pmarker is used to hold the place of the proc being processed, so * we can search for the next one downstream later. */ } pcond = (tp != pp || (inpipe && tp == pp)); #else /* !BACKPIPE */ pcond = (tp != pp); -#endif /* BACKPIPE */ +#endif /* BACKPIPE */ jobflags |= pp->p_flags; pstatus = (int) (pp->p_flags & PALLSTATES); if (pcond && linp != linbuf && !(flag & FANCY) && ((pstatus == status && pp->p_reason == reason) || !(flag & REASON))) xputchar(' '); else { if (pcond && linp != linbuf) xputchar('\n'); if (flag & NUMBER) { #ifdef BACKPIPE pcond = ((pp == tp && !inpipe) || (inpipe && pipetail == tp && pp == pipehead)); #else /* BACKPIPE */ pcond = (pp == tp); #endif /* BACKPIPE */ if (pcond) xprintf("[%d]%s %c ", pp->p_index, pp->p_index < 10 ? " " : "", pp == pcurrent ? '+' : (pp == pprevious ? '-' : ' ')); else xprintf(" "); } if (flag & FANCY) { xprintf("%5d ", pp->p_procid); #ifdef TCF xprintf("%11s ", sitename(pp->p_procid)); #endif /* TCF */ } if (flag & (REASON | AREASON)) { if (flag & NAME) format = "%-30s"; else format = "%s"; if (pstatus == status) { if (pp->p_reason == reason) { xprintf(format, ""); goto prcomd; } else reason = (int) pp->p_reason; } else { status = pstatus; reason = (int) pp->p_reason; } switch (status) { case PRUNNING: xprintf(format, CGETS(17, 4, "Running ")); break; case PINTERRUPTED: case PSTOPPED: case PSIGNALED: /* * tell what happened to the background job * From: Michael Schroeder * */ if ((flag & REASON) || ((flag & AREASON) && reason != SIGINT && (reason != SIGPIPE || (pp->p_flags & PPOU) == 0))) { char *ptr; int free_ptr; free_ptr = 0; ptr = (char *)(intptr_t)mesg[pp->p_reason & 0177].pname; if (ptr == NULL) { ptr = xasprintf("%s %d", CGETS(17, 5, "Signal"), pp->p_reason & 0177); cleanup_push(ptr, xfree); free_ptr = 1; } xprintf(format, ptr); if (free_ptr != 0) cleanup_until(ptr); } else reason = -1; break; case PNEXITED: case PAEXITED: if (flag & REASON) { if (pp->p_reason) xprintf(CGETS(17, 6, "Exit %-25d"), pp->p_reason); else xprintf(format, CGETS(17, 7, "Done")); } break; default: xprintf(CGETS(17, 8, "BUG: status=%-9o"), status); } } } prcomd: if (flag & NAME) { xprintf("%S", pp->p_command); if (pp->p_flags & PPOU) xprintf(" |"); if (pp->p_flags & PDIAG) xprintf("&"); } if (flag & (REASON | AREASON) && pp->p_flags & PDUMPED) xprintf("%s", CGETS(17, 9, " (core dumped)")); if (tp == pp->p_friends) { if (flag & AMPERSAND) xprintf(" &"); if (flag & JOBDIR && !eq(tp->p_cwd->di_name, dcwd->di_name)) { xprintf("%s", CGETS(17, 10, " (wd: ")); dtildepr(tp->p_cwd->di_name); xprintf(")"); } } if (pp->p_flags & PPTIME && !(status & (PSTOPPED | PRUNNING))) { if (linp != linbuf) xprintf("\n\t"); #if defined(BSDTIMES) || defined(_SEQUENT_) prusage(&zru, &pp->p_rusage, &pp->p_etime, &pp->p_btime); #else /* !BSDTIMES && !SEQUENT */ lru.tms_utime = pp->p_utime; lru.tms_stime = pp->p_stime; lru.tms_cutime = 0; lru.tms_cstime = 0; prusage(&zru, &lru, pp->p_etime, pp->p_btime); #endif /* !BSDTIMES && !SEQUENT */ } #ifdef BACKPIPE pcond = ((tp == pp->p_friends && !inpipe) || (inpipe && pipehead->p_friends == tp && pp == pipetail)); #else /* !BACKPIPE */ pcond = (tp == pp->p_friends); #endif /* BACKPIPE */ if (pcond) { if (linp != linbuf) xputchar('\n'); if (flag & SHELLDIR && !eq(tp->p_cwd->di_name, dcwd->di_name)) { xprintf("%s", CGETS(17, 11, "(wd now: ")); dtildepr(dcwd->di_name); xprintf(")\n"); } } #ifdef BACKPIPE if (inpipe) { /* * if pmaker == pipetail, we are finished that pipeline, and * can now skip to past the head */ if (pmarker == pipetail) { inpipe = 0; pp = pipehead; } else { /* * set pp to one before the one we want next, so the while below * increments to the correct spot. */ do pp = pp->p_friends; while (pp->p_friends->p_friends != pmarker); pmarker = pp->p_friends; } } pcond = ((pp = pp->p_friends) != tp || inpipe); #else /* !BACKPIPE */ pcond = ((pp = pp->p_friends) != tp); #endif /* BACKPIPE */ } while (pcond); if (jobflags & PTIME && (jobflags & (PSTOPPED | PRUNNING)) == 0) { if (jobflags & NUMBER) xprintf(" "); ptprint(tp); } haderr = ohaderr; return (jobflags); } /* * All 4.3 BSD derived implementations are buggy and I've had enough. * The following implementation produces similar code and works in all * cases. The 4.3BSD one works only for <, >, != */ # undef timercmp # define timercmp(tvp, uvp, cmp) \ (((tvp)->tv_sec == (uvp)->tv_sec) ? \ ((tvp)->tv_usec cmp (uvp)->tv_usec) : \ ((tvp)->tv_sec cmp (uvp)->tv_sec)) static void ptprint(struct process *tp) { #ifdef BSDTIMES struct timeval tetime, diff; static struct timeval ztime; struct sysrusage ru; struct process *pp = tp; ru = zru; tetime = ztime; do { ruadd(&ru, &pp->p_rusage); tvsub(&diff, &pp->p_etime, &pp->p_btime); if (timercmp(&diff, &tetime, >)) tetime = diff; } while ((pp = pp->p_friends) != tp); prusage(&zru, &ru, &tetime, &ztime); #else /* !BSDTIMES */ # ifdef _SEQUENT_ timeval_t tetime, diff; static timeval_t ztime; struct process_stats ru; struct process *pp = tp; ru = zru; tetime = ztime; do { ruadd(&ru, &pp->p_rusage); tvsub(&diff, &pp->p_etime, &pp->p_btime); if (timercmp(&diff, &tetime, >)) tetime = diff; } while ((pp = pp->p_friends) != tp); prusage(&zru, &ru, &tetime, &ztime); # else /* !_SEQUENT_ */ # ifndef POSIX static time_t ztime = 0; static time_t zu_time = 0; static time_t zs_time = 0; time_t tetime, diff; time_t u_time, s_time; # else /* POSIX */ static clock_t ztime = 0; static clock_t zu_time = 0; static clock_t zs_time = 0; clock_t tetime, diff; clock_t u_time, s_time; # endif /* POSIX */ struct tms zts, rts; struct process *pp = tp; u_time = zu_time; s_time = zs_time; tetime = ztime; do { u_time += pp->p_utime; s_time += pp->p_stime; diff = pp->p_etime - pp->p_btime; if (diff > tetime) tetime = diff; } while ((pp = pp->p_friends) != tp); zts.tms_utime = zu_time; zts.tms_stime = zs_time; zts.tms_cutime = 0; zts.tms_cstime = 0; rts.tms_utime = u_time; rts.tms_stime = s_time; rts.tms_cutime = 0; rts.tms_cstime = 0; prusage(&zts, &rts, tetime, ztime); # endif /* !_SEQUENT_ */ #endif /* !BSDTIMES */ } /* * dojobs - print all jobs */ /*ARGSUSED*/ void dojobs(Char **v, struct command *c) { struct process *pp; int flag = NUMBER | NAME | REASON | JOBLIST; int i; USE(c); if (chkstop) chkstop = 2; if (*++v) { if (v[1] || !eq(*v, STRml)) stderror(ERR_JOBS); flag |= FANCY | JOBDIR; } for (i = 1; i <= pmaxindex; i++) for (pp = proclist.p_next; pp; pp = pp->p_next) if (pp->p_index == i && pp->p_procid == pp->p_jobid) { pp->p_flags &= ~PNEEDNOTE; if (!(pprint(pp, flag) & (PRUNNING | PSTOPPED))) pflush(pp); break; } } /* * dofg - builtin - put the job into the foreground */ /*ARGSUSED*/ void dofg(Char **v, struct command *c) { struct process *pp; USE(c); okpcntl(); ++v; do { pp = pfind(*v); if (!pstart(pp, 1)) { pp->p_procid = 0; stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno)); continue; } pjwait(pp); } while (*v && *++v); } /* * %... - builtin - put the job into the foreground */ /*ARGSUSED*/ void dofg1(Char **v, struct command *c) { struct process *pp; USE(c); okpcntl(); pp = pfind(v[0]); if (!pstart(pp, 1)) { pp->p_procid = 0; stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno)); return; } pjwait(pp); } /* * dobg - builtin - put the job into the background */ /*ARGSUSED*/ void dobg(Char **v, struct command *c) { struct process *pp; USE(c); okpcntl(); ++v; do { pp = pfind(*v); if (!pstart(pp, 0)) { pp->p_procid = 0; stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno)); } } while (*v && *++v); } /* * %... & - builtin - put the job into the background */ /*ARGSUSED*/ void dobg1(Char **v, struct command *c) { struct process *pp; USE(c); pp = pfind(v[0]); if (!pstart(pp, 0)) { pp->p_procid = 0; stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno)); } } /* * dostop - builtin - stop the job */ /*ARGSUSED*/ void dostop(Char **v, struct command *c) { USE(c); #ifdef BSDJOBS pkill(++v, SIGSTOP); #endif /* BSDJOBS */ } /* * dokill - builtin - superset of kill (1) */ /*ARGSUSED*/ void dokill(Char **v, struct command *c) { int signum, len = 0; const char *name; Char *sigptr; USE(c); v++; if (v[0] && v[0][0] == '-') { if (v[0][1] == 'l') { for (signum = 0; signum <= nsig; signum++) { if ((name = mesg[signum].iname) != NULL) { len += strlen(name) + 1; if (len >= TermH - 1) { xputchar('\n'); len = strlen(name) + 1; } xprintf("%s ", name); } } xputchar('\n'); return; } sigptr = &v[0][1]; if (v[0][1] == 's') { if (v[1]) { v++; sigptr = &v[0][0]; } else { stderror(ERR_NAME | ERR_TOOFEW); } } if (Isdigit(*sigptr)) { char *ep; signum = strtoul(short2str(sigptr), &ep, 0); if (*ep || signum < 0 || signum > (MAXSIG-1)) stderror(ERR_NAME | ERR_BADSIG); } else { for (signum = 0; signum <= nsig; signum++) if (mesg[signum].iname && eq(sigptr, str2short(mesg[signum].iname))) goto gotsig; setname(short2str(sigptr)); stderror(ERR_NAME | ERR_UNKSIG); } gotsig: v++; } else signum = SIGTERM; pkill(v, signum); } static void pkill(Char **v, int signum) { struct process *pp, *np; int jobflags = 0, err1 = 0; pid_t pid; Char *cp, **vp, **globbed; /* Avoid globbing %?x patterns */ for (vp = v; vp && *vp; vp++) if (**vp == '%') (void) quote(*vp); v = glob_all_or_error(v); globbed = v; cleanup_push(globbed, blk_cleanup); pchild_disabled++; cleanup_push(&pchild_disabled, disabled_cleanup); if (setintr) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); } while (v && (cp = *v)) { if (*cp == '%') { np = pp = pfind(cp); do jobflags |= np->p_flags; while ((np = np->p_friends) != pp); #ifdef BSDJOBS switch (signum) { case SIGSTOP: case SIGTSTP: case SIGTTIN: case SIGTTOU: if ((jobflags & PRUNNING) == 0) { # ifdef SUSPENDED xprintf(CGETS(17, 12, "%S: Already suspended\n"), cp); # else /* !SUSPENDED */ xprintf(CGETS(17, 13, "%S: Already stopped\n"), cp); # endif /* !SUSPENDED */ err1++; goto cont; } break; /* * suspend a process, kill -CONT %, then type jobs; the shell * says it is suspended, but it is running; thanks jaap.. */ case SIGCONT: if (!pstart(pp, 0)) { pp->p_procid = 0; stderror(ERR_NAME|ERR_BADJOB, pp->p_command, strerror(errno)); } goto cont; default: break; } #endif /* BSDJOBS */ if (killpg(pp->p_jobid, signum) < 0) { xprintf("%S: %s\n", cp, strerror(errno)); err1++; } #ifdef BSDJOBS if (signum == SIGTERM || signum == SIGHUP) (void) killpg(pp->p_jobid, SIGCONT); #endif /* BSDJOBS */ } else if (!(Isdigit(*cp) || *cp == '-')) stderror(ERR_NAME | ERR_JOBARGS); else { char *ep; #ifndef WINNT_NATIVE pid = strtol(short2str(cp), &ep, 10); #else pid = strtoul(short2str(cp), &ep, 0); #endif /* WINNT_NATIVE */ if (*ep) stderror(ERR_NAME | ERR_JOBARGS); else if (kill(pid, signum) < 0) { xprintf("%d: %s\n", pid, strerror(errno)); err1++; goto cont; } #ifdef BSDJOBS if (signum == SIGTERM || signum == SIGHUP) (void) kill(pid, SIGCONT); #endif /* BSDJOBS */ } cont: v++; } cleanup_until(&pchild_disabled); if (err1) stderror(ERR_SILENT); } /* * pstart - start the job in foreground/background */ int pstart(struct process *pp, int foregnd) { int rv = 0; struct process *np; /* We don't use jobflags in this function right now (see below) */ /* long jobflags = 0; */ pchild_disabled++; cleanup_push(&pchild_disabled, disabled_cleanup); np = pp; do { /* We don't use jobflags in this function right now (see below) */ /* jobflags |= np->p_flags; */ if (np->p_flags & (PRUNNING | PSTOPPED)) { np->p_flags |= PRUNNING; np->p_flags &= ~PSTOPPED; if (foregnd) np->p_flags |= PFOREGND; else np->p_flags &= ~PFOREGND; } } while ((np = np->p_friends) != pp); if (!foregnd) pclrcurr(pp); (void) pprint(pp, foregnd ? NAME | JOBDIR : NUMBER | NAME | AMPERSAND); /* GrP run jobcmd hook if foregrounding */ if (foregnd) { job_cmd(pp->p_command); } #ifdef BSDJOBS if (foregnd) { rv = tcsetpgrp(FSHTTY, pp->p_jobid); } /* * 1. child process of csh (shell script) receives SIGTTIN/SIGTTOU * 2. parent process (csh) receives SIGCHLD * 3. The "csh" signal handling function pchild() is invoked * with a SIGCHLD signal. * 4. pchild() calls wait3(WNOHANG) which returns 0. * The child process is NOT ready to be waited for at this time. * pchild() returns without picking-up the correct status * for the child process which generated the SIGCHLD. * 5. CONSEQUENCE : csh is UNaware that the process is stopped * 6. THIS LINE HAS BEEN COMMENTED OUT : if (jobflags&PSTOPPED) * (beto@aixwiz.austin.ibm.com - aug/03/91) * 7. I removed the line completely and added extra checks for * pstart, so that if a job gets attached to and dies inside * a debugger it does not confuse the shell. [christos] * 8. on the nec sx-4 there seems to be a problem, which requires * a syscall(151, getpid(), getpid()) in osinit. Don't ask me * what this is doing. [schott@rzg.mpg.de] */ if (rv != -1) rv = killpg(pp->p_jobid, SIGCONT); #endif /* BSDJOBS */ cleanup_until(&pchild_disabled); return rv != -1; } void panystop(int neednl) { struct process *pp; chkstop = 2; for (pp = proclist.p_next; pp; pp = pp->p_next) if (pp->p_flags & PSTOPPED) stderror(ERR_STOPPED, neednl ? "\n" : ""); } struct process * pfind(Char *cp) { struct process *pp, *np; if (cp == 0 || cp[1] == 0 || eq(cp, STRcent2) || eq(cp, STRcentplus)) { if (pcurrent == NULL) stderror(ERR_NAME | ERR_JOBCUR); return (pcurrent); } if (eq(cp, STRcentminus) || eq(cp, STRcenthash)) { if (pprevious == NULL) stderror(ERR_NAME | ERR_JOBPREV); return (pprevious); } if (Isdigit(cp[1])) { int idx = atoi(short2str(cp + 1)); for (pp = proclist.p_next; pp; pp = pp->p_next) if (pp->p_index == idx && pp->p_procid == pp->p_jobid) return (pp); stderror(ERR_NAME | ERR_NOSUCHJOB); } np = NULL; for (pp = proclist.p_next; pp; pp = pp->p_next) if (pp->p_procid == pp->p_jobid) { if (cp[1] == '?') { Char *dp; for (dp = pp->p_command; *dp; dp++) { if (*dp != cp[2]) continue; if (prefix(cp + 2, dp)) goto match; } } else if (prefix(cp + 1, pp->p_command)) { match: if (np) stderror(ERR_NAME | ERR_AMBIG); np = pp; } } if (np) return (np); stderror(ERR_NAME | (cp[1] == '?' ? ERR_JOBPAT : ERR_NOSUCHJOB)); /* NOTREACHED */ return (0); } /* * pgetcurr - find most recent job that is not pp, preferably stopped */ static struct process * pgetcurr(struct process *pp) { struct process *np; struct process *xp = NULL; for (np = proclist.p_next; np; np = np->p_next) if (np != pcurrent && np != pp && np->p_procid && np->p_procid == np->p_jobid) { if (np->p_flags & PSTOPPED) return (np); if (xp == NULL) xp = np; } return (xp); } /* * donotify - flag the job so as to report termination asynchronously */ /*ARGSUSED*/ void donotify(Char **v, struct command *c) { struct process *pp; USE(c); pp = pfind(*++v); pp->p_flags |= PNOTIFY; } #ifdef SIGSYNCH static void synch_handler(int sno) { USE(sno); } #endif /* SIGSYNCH */ /* * Do the fork and whatever should be done in the child side that * should not be done if we are not forking at all (like for simple builtin's) * Also do everything that needs any signals fiddled with in the parent side * * Wanttty tells whether process and/or tty pgrps are to be manipulated: * -1: leave tty alone; inherit pgrp from parent * 0: already have tty; manipulate process pgrps only * 1: want to claim tty; manipulate process and tty pgrps * It is usually just the value of tpgrp. */ pid_t pfork(struct command *t, int wanttty) { pid_t pid; int ignint = 0; pid_t pgrp; #ifdef SIGSYNCH struct sigaction osa, nsa; #endif /* SIGSYNCH */ /* * A child will be uninterruptible only under very special conditions. * Remember that the semantics of '&' is implemented by disconnecting the * process from the tty so signals do not need to ignored just for '&'. * Thus signals are set to default action for children unless: we have had * an "onintr -" (then specifically ignored) we are not playing with * signals (inherit action) */ if (setintr) ignint = (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT)) || (gointr && eq(gointr, STRminus)); /* * Check for maximum nesting of 16 processes to avoid Forking loops */ if (child == 16) stderror(ERR_NESTING, 16); #ifdef SIGSYNCH nsa.sa_handler = synch_handler; sigfillset(&nsa.sa_mask); nsa.sa_flags = SA_RESTART; if (sigaction(SIGSYNCH, &nsa, &osa)) stderror(ERR_SYSTEM, "pfork: sigaction set", strerror(errno)); #endif /* SIGSYNCH */ /* * Hold pchild() until we have the process installed in our table. */ if (wanttty < 0) { pchild_disabled++; cleanup_push(&pchild_disabled, disabled_cleanup); } while ((pid = fork()) == -1) if (setintr == 0) (void) sleep(FORKSLEEP); else stderror(ERR_NOPROC); if (pid == 0) { (void)cleanup_push_mark(); /* Never to be popped */ pchild_disabled = 0; settimes(); pgrp = pcurrjob ? pcurrjob->p_jobid : getpid(); pflushall(); pcurrjob = NULL; -#if !defined(BSDTIMES) && !defined(_SEQUENT_) +#if !defined(BSDTIMES) && !defined(_SEQUENT_) timesdone = 0; #endif /* !defined(BSDTIMES) && !defined(_SEQUENT_) */ child++; if (setintr) { setintr = 0; /* until I think otherwise */ /* * Children just get blown away on SIGINT, SIGQUIT unless "onintr * -" seen. */ (void) signal(SIGINT, ignint ? SIG_IGN : SIG_DFL); (void) signal(SIGQUIT, ignint ? SIG_IGN : SIG_DFL); #ifdef BSDJOBS if (wanttty >= 0) { /* make stoppable */ (void) signal(SIGTSTP, SIG_DFL); (void) signal(SIGTTIN, SIG_DFL); (void) signal(SIGTTOU, SIG_DFL); } #endif /* BSDJOBS */ sigaction(SIGTERM, &parterm, NULL); } else if (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT)) { (void) signal(SIGINT, SIG_IGN); (void) signal(SIGQUIT, SIG_IGN); } #ifdef OREO signal(SIGIO, SIG_IGN); /* ignore SIGIO in child too */ #endif /* OREO */ pgetty(wanttty, pgrp); /* * Nohup and nice apply only to NODE_COMMAND's but it would be nice * (?!?) if you could say "nohup (foo;bar)" Then the parser would have * to know about nice/nohup/time */ if (t->t_dflg & F_NOHUP) (void) signal(SIGHUP, SIG_IGN); if (t->t_dflg & F_NICE) { int nval = SIGN_EXTEND_CHAR(t->t_nice); #if defined(HAVE_SETPRIORITY) && defined(PRIO_PROCESS) if (setpriority(PRIO_PROCESS, 0, nval) == -1 && errno) stderror(ERR_SYSTEM, "setpriority", strerror(errno)); #else /* !HAVE_SETPRIORITY || !PRIO_PROCESS */ (void) nice(nval); #endif /* HAVE_SETPRIORITY && PRIO_PROCESS */ } #ifdef F_VER if (t->t_dflg & F_VER) { tsetenv(STRSYSTYPE, t->t_systype ? STRbsd43 : STRsys53); dohash(NULL, NULL); } #endif /* F_VER */ #ifdef SIGSYNCH /* rfw 8/89 now parent can continue */ if (kill(getppid(), SIGSYNCH)) stderror(ERR_SYSTEM, "pfork child: kill", strerror(errno)); #endif /* SIGSYNCH */ } else { #ifdef POSIXJOBS if (wanttty >= 0) { /* * `Walking' process group fix from Beto Appleton. * (beto@aixwiz.austin.ibm.com) * If setpgid fails at this point that means that * our process leader has died. We flush the current * job and become the process leader ourselves. * The parent will figure that out later. */ pgrp = pcurrjob ? pcurrjob->p_jobid : pid; if (setpgid(pid, pgrp) == -1 && errno == EPERM) { pcurrjob = NULL; - /* + /* * We don't care if this causes an error here; * then we are already in the right process group */ (void) setpgid(pid, pgrp = pid); } } #endif /* POSIXJOBS */ palloc(pid, t); #ifdef SIGSYNCH { sigset_t pause_mask; /* * rfw 8/89 Wait for child to own terminal. Solves half of ugly * synchronization problem. With this change, we know that the only * reason setpgrp to a previous process in a pipeline can fail is that * the previous process has already exited. Without this hack, he may * either have exited or not yet started to run. Two uglies become * one. */ sigprocmask(SIG_BLOCK, NULL, &pause); sigdelset(&pause_mask, SIGCHLD); sigdelset(&pause_mask, SIGSYNCH); sigsuspend(&pause_mask); (void)handle_pending_signals(); if (sigaction(SIGSYNCH, &osa, NULL)) stderror(ERR_SYSTEM, "pfork parent: sigaction restore", strerror(errno)); } #endif /* SIGSYNCH */ if (wanttty < 0) cleanup_until(&pchild_disabled); } return (pid); } static void okpcntl(void) { if (tpgrp == -1) stderror(ERR_JOBCONTROL); if (tpgrp == 0) stderror(ERR_JOBCTRLSUB); } static void setttypgrp(int pgrp) { /* * If we are piping out a builtin, eg. 'echo | more' things can go * out of sequence, i.e. the more can run before the echo. This * can happen even if we have vfork, since the echo will be forked * with the regular fork. In this case, we need to set the tty * pgrp ourselves. If that happens, then the process will be still * alive. And the tty process group will already be set. * This should fix the famous sequent problem as a side effect: * The controlling terminal is lost if all processes in the * terminal process group are zombies. In this case tcgetpgrp() * returns 0. If this happens we must set the terminal process * group again. */ if (tcgetpgrp(FSHTTY) != pgrp) { #ifdef POSIXJOBS struct sigaction old; /* - * tcsetpgrp will set SIGTTOU to all the the processes in + * tcsetpgrp will set SIGTTOU to all the the processes in * the background according to POSIX... We ignore this here. */ sigaction(SIGTTOU, NULL, &old); signal(SIGTTOU, SIG_IGN); #endif (void) tcsetpgrp(FSHTTY, pgrp); # ifdef POSIXJOBS sigaction(SIGTTOU, &old, NULL); # endif } } /* * if we don't have vfork(), things can still go in the wrong order * resulting in the famous 'Stopped (tty output)'. But some systems * don't permit the setpgid() call, (these are more recent secure - * systems such as ibm's aix), when they do. Then we'd rather print + * systems such as ibm's aix), when they do. Then we'd rather print * an error message than hang the shell! * I am open to suggestions how to fix that. */ void pgetty(int wanttty, pid_t pgrp) { #ifdef BSDJOBS # ifdef POSIXJOBS sigset_t oset, set; # endif /* POSIXJOBS */ jobdebug_xprintf(("wanttty %d pid %d opgrp%d pgrp %d tpgrp %d\n", wanttty, (int)getpid(), (int)pgrp, (int)mygetpgrp(), (int)tcgetpgrp(FSHTTY))); # ifdef POSIXJOBS /* * christos: I am blocking the tty signals till I've set things * correctly.... */ if (wanttty > 0) { sigemptyset(&set); sigaddset(&set, SIGTSTP); sigaddset(&set, SIGTTIN); (void)sigprocmask(SIG_BLOCK, &set, &oset); cleanup_push(&oset, sigprocmask_cleanup); } # endif /* POSIXJOBS */ # ifndef POSIXJOBS if (wanttty > 0) setttypgrp(pgrp); # endif /* !POSIXJOBS */ /* * From: Michael Schroeder * Don't check for tpgrp >= 0 so even non-interactive shells give * background jobs process groups Same for the comparison in the other part * of the #ifdef */ if (wanttty >= 0) { if (setpgid(0, pgrp) == -1) { # ifdef POSIXJOBS /* Walking process group fix; see above */ if (setpgid(0, pgrp = getpid()) == -1) { # endif /* POSIXJOBS */ stderror(ERR_SYSTEM, "setpgid child:\n", strerror(errno)); xexit(0); # ifdef POSIXJOBS } wanttty = pgrp; /* Now we really want the tty, since we became the * the process group leader */ # endif /* POSIXJOBS */ } } # ifdef POSIXJOBS if (wanttty > 0) { setttypgrp(pgrp); cleanup_until(&oset); } # endif /* POSIXJOBS */ jobdebug_xprintf(("wanttty %d pid %d pgrp %d tpgrp %d\n", wanttty, getpid(), mygetpgrp(), tcgetpgrp(FSHTTY))); if (tpgrp > 0) tpgrp = 0; /* gave tty away */ #endif /* BSDJOBS */ } diff --git a/contrib/tcsh/sh.sem.c b/contrib/tcsh/sh.sem.c index 473663eeb56f..3850331b5656 100644 --- a/contrib/tcsh/sh.sem.c +++ b/contrib/tcsh/sh.sem.c @@ -1,995 +1,995 @@ /* * sh.sem.c: I/O redirections and job forking. A touchy issue! * Most stuff with builtins is incorrect */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "tc.h" #include "tw.h" #ifdef WINNT_NATIVE #include "nt.const.h" #endif /*WINNT_NATIVE*/ #ifdef CLOSE_ON_EXEC # ifndef SUNOS4 # ifndef CLEX_DUPS # define CLEX_DUPS # endif /* CLEX_DUPS */ # endif /* !SUNOS4 */ #endif /* CLOSE_ON_EXEC */ #if defined(__sparc__) || defined(sparc) # if !defined(MACH) && SYSVREL == 0 && !defined(Lynx) && !defined(BSD4_4) && !defined(__linux__) && !defined(__GNU__) && !defined(__GLIBC__) # include # endif /* !MACH && SYSVREL == 0 && !Lynx && !BSD4_4 && !glibc */ #endif /* __sparc__ || sparc */ #ifdef VFORK static void vffree (int); -#endif +#endif static Char *splicepipe (struct command *, Char *); static void doio (struct command *, int *, int *); static void chkclob (const char *); /* * C shell */ /* * For SVR4, there are problems with pipelines having the first process as * the group leader. The problem occurs when the first process exits before * the others have a chance to setpgid(). This is because in SVR4 you can't * have a zombie as a group leader. The solution I have used is to reverse * the order in which pipelines are started, making the last process the * group leader. (Note I am not using 'pipeline' in the generic sense -- I * mean processes connected by '|'.) I don't know yet if this causes other * problems. * - * All the changes for this are in execute(), and are enclosed in + * All the changes for this are in execute(), and are enclosed in * '#ifdef BACKPIPE' * * David Dawes (dawes@physics.su.oz.au) Oct 1991 */ /*VARARGS 1*/ void execute(struct command *t, volatile int wanttty, int *pipein, int *pipeout, int do_glob) { int forked = 0; const struct biltins * volatile bifunc; pid_t pid = 0; int pv[2]; sigset_t set; static sigset_t csigset; #ifdef VFORK static int onosigchld = 0; #endif /* VFORK */ static int nosigchld = 0; (void) &wanttty; (void) &forked; (void) &bifunc; - if (t == 0) + if (t == 0) return; #ifdef WINNT_NATIVE { if ((varval(STRNTslowexec) == STRNULL) && !t->t_dcdr && !t->t_dcar && !t->t_dflg && !didfds && (intty || intact) && (t->t_dtyp == NODE_COMMAND) && !isbfunc(t)) { if ((t->t_dcom[0][0] & (QUOTE | TRIM)) == QUOTE) (void) Strcpy(t->t_dcom[0], t->t_dcom[0] + 1); Dfix(t); if (nt_try_fast_exec(t) == 0) return; } } #endif /* WINNT_NATIVE */ /* * Ed hutchins@sgi.com & Dominic dbg@sgi.com * Sat Feb 25 03:13:11 PST 1995 - * try implicit cd if we have a 1 word command + * try implicit cd if we have a 1 word command */ if (implicit_cd && (intty || intact) && t->t_dcom && t->t_dcom[0] && t->t_dcom[0][0] && (blklen(t->t_dcom) == 1) && !noexec) { Char *sCName; struct stat stbuf; char *pathname; sCName = dollar(t->t_dcom[0]); if (sCName != NULL && sCName[0] == '~') { struct Strbuf buf = Strbuf_INIT; const Char *name_end; for (name_end = sCName + 1; *name_end != '\0' && *name_end != '/'; name_end++) continue; if (name_end != sCName + 1) { Char *name, *home; name = Strnsave(sCName + 1, name_end - (sCName + 1)); home = gethdir(name); if (home != NULL) { Strbuf_append(&buf, home); xfree(home); } else Strbuf_append(&buf, name); xfree(name); } else Strbuf_append(&buf, varval(STRhome)); Strbuf_append(&buf, name_end); xfree(sCName); sCName = Strbuf_finish(&buf); } pathname = short2str(sCName); xfree(sCName); /* if this is a dir, tack a "cd" on as the first arg */ if (pathname != NULL && ((stat(pathname, &stbuf) != -1 && S_ISDIR(stbuf.st_mode)) #ifdef WINNT_NATIVE || (pathname[0] && pathname[1] == ':' && pathname[2] == '\0') #endif /* WINNT_NATIVE */ )) { Char *vCD[2]; Char **ot_dcom = t->t_dcom; - + vCD[0] = Strsave(STRcd); vCD[1] = NULL; t->t_dcom = blkspl(vCD, ot_dcom); xfree(ot_dcom); if (implicit_cd > 1) { blkpr(t->t_dcom); xputchar( '\n' ); } } } /* * From: Michael Schroeder * Don't check for wantty > 0... */ if (t->t_dflg & F_AMPERSAND) wanttty = 0; switch (t->t_dtyp) { case NODE_COMMAND: if ((t->t_dcom[0][0] & (QUOTE | TRIM)) == QUOTE) memmove(t->t_dcom[0], t->t_dcom[0] + 1, (Strlen(t->t_dcom[0] + 1) + 1) * sizeof (*t->t_dcom[0])); if ((t->t_dflg & F_REPEAT) == 0) Dfix(t); /* $ " ' \ */ if (t->t_dcom[0] == 0) { return; } /*FALLTHROUGH*/ case NODE_PAREN: #ifdef BACKPIPE if (t->t_dflg & F_PIPEIN) mypipe(pipein); #else /* !BACKPIPE */ if (t->t_dflg & F_PIPEOUT) mypipe(pipeout); #endif /* BACKPIPE */ /* * Must do << early so parent will know where input pointer should be. * If noexec then this is all we do. */ if (t->t_dflg & F_READ) { int old_pintr_disabled; xclose(0); if (setintr) pintr_push_enable(&old_pintr_disabled); heredoc(t->t_dlef); if (setintr) cleanup_until(&old_pintr_disabled); if (noexec) xclose(0); } setcopy(STRstatus, STR0, VAR_READWRITE); /* * This mess is the necessary kludge to handle the prefix builtins: * nice, nohup, time. These commands can also be used by themselves, * and this is not handled here. This will also work when loops are * parsed. */ while (t->t_dtyp == NODE_COMMAND) if (eq(t->t_dcom[0], STRnice)) { if (t->t_dcom[1]) { if (strchr("+-", t->t_dcom[1][0])) { if (t->t_dcom[2]) { setname("nice"); t->t_nice = (unsigned char)getn(t->t_dcom[1]); lshift(t->t_dcom, 2); t->t_dflg |= F_NICE; } else break; } else { t->t_nice = 4; lshift(t->t_dcom, 1); t->t_dflg |= F_NICE; } } else break; } else if (eq(t->t_dcom[0], STRnohup)) { if (t->t_dcom[1]) { t->t_dflg |= F_NOHUP; lshift(t->t_dcom, 1); } else break; } else if (eq(t->t_dcom[0], STRhup)) { if (t->t_dcom[1]) { t->t_dflg |= F_HUP; lshift(t->t_dcom, 1); } else break; } else if (eq(t->t_dcom[0], STRtime)) { if (t->t_dcom[1]) { t->t_dflg |= F_TIME; lshift(t->t_dcom, 1); } else break; } #ifdef F_VER else if (eq(t->t_dcom[0], STRver)) if (t->t_dcom[1] && t->t_dcom[2]) { setname("ver"); t->t_systype = getv(t->t_dcom[1]); lshift(t->t_dcom, 2); t->t_dflg |= F_VER; } else break; #endif /* F_VER */ else break; /* is it a command */ if (t->t_dtyp == NODE_COMMAND) { /* * Check if we have a builtin function and remember which one. */ bifunc = isbfunc(t); if (noexec) { /* * Continue for builtins that are part of the scripting language */ if (bifunc == NULL) break; if (bifunc->bfunct != (bfunc_t)dobreak && bifunc->bfunct != (bfunc_t)docontin && bifunc->bfunct != (bfunc_t)doelse && bifunc->bfunct != (bfunc_t)doend && bifunc->bfunct != (bfunc_t)doforeach&& bifunc->bfunct != (bfunc_t)dogoto && bifunc->bfunct != (bfunc_t)doif && bifunc->bfunct != (bfunc_t)dorepeat && bifunc->bfunct != (bfunc_t)doswbrk && bifunc->bfunct != (bfunc_t)doswitch && bifunc->bfunct != (bfunc_t)dowhile && bifunc->bfunct != (bfunc_t)dozip) break; } } else { /* not a command */ bifunc = NULL; if (noexec) break; } - /* + /* * GrP Executing a command - run jobcmd hook * Don't run for builtins * Don't run if we're not in a tty - * Don't run if we're not really executing + * Don't run if we're not really executing */ /* * CR - Charles Ross Aug 2005 * added "isoutatty". * The new behavior is that the jobcmd won't be executed * if stdout (SHOUT) isnt attached to a tty.. IE when * redirecting, or using backquotes etc.. */ if (t->t_dtyp == NODE_COMMAND && !bifunc && !noexec && intty && isoutatty) { Char *cmd = unparse(t); cleanup_push(cmd, xfree); job_cmd(cmd); cleanup_until(cmd); } - + /* * We fork only if we are timed, or are not the end of a parenthesized * list and not a simple builtin function. Simple meaning one that is * not pipedout, niced, nohupped, or &'d. It would be nice(?) to not * fork in some of these cases. */ #ifdef BACKPIPE /* * Can't have NOFORK for the tail of a pipe - because it is not the * last command spawned (even if it is at the end of a parenthesised * list). */ if (t->t_dflg & F_PIPEIN) t->t_dflg &= ~(F_NOFORK); #else /* * "command | builtin" may cause major misbehaviour as noted in * in the BUGS file entry * Subject: Redirected input to built-in functions misbehaves badly * forking when the builtin is the end of the pipe corrects the * problem. */ if (bifunc && (t->t_dflg & F_PIPEIN)) t->t_dflg &= ~(F_NOFORK); #endif /* BACKPIPE */ /* * Prevent forking cd, pushd, popd, chdir cause this will cause the * shell not to change dir! (XXX: but only for nice?) */ if (bifunc && (bifunc->bfunct == (bfunc_t)dochngd || bifunc->bfunct == (bfunc_t)dopushd || bifunc->bfunct == (bfunc_t)dopopd)) t->t_dflg &= ~(F_NICE); if (((t->t_dflg & F_TIME) || ((t->t_dflg & F_NOFORK) == 0 && (!bifunc || t->t_dflg & (F_PIPEOUT | F_AMPERSAND | F_NICE | F_NOHUP | F_HUP)))) || /* * We have to fork for eval too. */ (bifunc && (t->t_dflg & F_PIPEIN) != 0 && bifunc->bfunct == (bfunc_t)doeval)) { #ifdef VFORK if (t->t_dtyp == NODE_PAREN || t->t_dflg & (F_REPEAT | F_AMPERSAND) || bifunc) #endif /* VFORK */ { forked++; /* * We need to block SIGCHLD here, so that if the process does * not die before we can set the process group */ if (wanttty >= 0 && !nosigchld) { sigemptyset(&set); sigaddset(&set, SIGCHLD); (void)sigprocmask(SIG_BLOCK, &set, &csigset); nosigchld = 1; } pid = pfork(t, wanttty); if (pid == 0 && nosigchld) { sigprocmask(SIG_SETMASK, &csigset, NULL); nosigchld = 0; } else if (pid != 0 && (t->t_dflg & F_AMPERSAND)) backpid = pid; } #ifdef VFORK else { int ochild, osetintr, ohaderr, odidfds; int oSHIN, oSHOUT, oSHDIAG, oOLDSTD, otpgrp; int oisoutatty, oisdiagatty; sigset_t oset, ocsigset; # ifndef CLOSE_ON_EXEC int odidcch; # endif /* !CLOSE_ON_EXEC */ /* * Prepare for the vfork by saving everything that the child * corrupts before it exec's. Note that in some signal * implementations which keep the signal info in user space * (e.g. Sun's) it will also be necessary to save and restore * the current sigvec's for the signals the child touches * before it exec's. */ /* * Sooooo true... If this is a Sun, save the sigvec's. (Skip * Gilbrech - 11/22/87) */ # ifdef SAVESIGVEC struct sigaction savesv[NSIGSAVED]; sigset_t savesm; # endif /* SAVESIGVEC */ if (wanttty >= 0 && !nosigchld && !noexec) { sigemptyset(&set); sigaddset(&set, SIGCHLD); (void)sigprocmask(SIG_BLOCK, &set, &csigset); nosigchld = 1; } sigemptyset(&set); sigaddset(&set, SIGCHLD); sigaddset(&set, SIGINT); (void)sigprocmask(SIG_BLOCK, &set, &oset); ochild = child; osetintr = setintr; ohaderr = haderr; odidfds = didfds; # ifndef CLOSE_ON_EXEC odidcch = didcch; # endif /* !CLOSE_ON_EXEC */ oSHIN = SHIN; oSHOUT = SHOUT; oSHDIAG = SHDIAG; oOLDSTD = OLDSTD; otpgrp = tpgrp; oisoutatty = isoutatty; oisdiagatty = isdiagatty; ocsigset = csigset; onosigchld = nosigchld; Vsav = Vdp = 0; Vexpath = 0; Vt = 0; # ifdef SAVESIGVEC savesigvec(savesv, savesm); # endif /* SAVESIGVEC */ if (use_fork) pid = fork(); else pid = vfork(); if (pid < 0) { # ifdef SAVESIGVEC restoresigvec(savesv, savesm); # endif /* SAVESIGVEC */ sigprocmask(SIG_SETMASK, &oset, NULL); stderror(ERR_NOPROC); } forked++; if (pid) { /* parent */ # ifdef SAVESIGVEC restoresigvec(savesv, savesm); # endif /* SAVESIGVEC */ child = ochild; setintr = osetintr; haderr = ohaderr; didfds = odidfds; SHIN = oSHIN; # ifndef CLOSE_ON_EXEC didcch = odidcch; # endif /* !CLOSE_ON_EXEC */ SHOUT = oSHOUT; SHDIAG = oSHDIAG; OLDSTD = oOLDSTD; tpgrp = otpgrp; isoutatty = oisoutatty; isdiagatty = oisdiagatty; csigset = ocsigset; nosigchld = onosigchld; xfree(Vsav); Vsav = 0; xfree(Vdp); Vdp = 0; xfree(Vexpath); Vexpath = 0; blk_cleanup(Vt); Vt = 0; /* this is from pfork() */ palloc(pid, t); sigprocmask(SIG_SETMASK, &oset, NULL); } else { /* child */ /* this is from pfork() */ pid_t pgrp; int ignint = 0; if (nosigchld) { sigprocmask(SIG_SETMASK, &csigset, NULL); nosigchld = 0; } if (setintr) ignint = (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT)) || (gointr && eq(gointr, STRminus)); pgrp = pcurrjob ? pcurrjob->p_jobid : getpid(); child++; if (setintr) { setintr = 0; /* * casts made right for SunOS 4.0 by Douglas C. Schmidt * * (thanks! -- PWP) * * ignint ifs cleaned by Johan Widen * (thanks again) */ if (ignint) { (void) signal(SIGINT, SIG_IGN); (void) signal(SIGQUIT, SIG_IGN); } else { (void) signal(SIGINT, vffree); (void) signal(SIGQUIT, SIG_DFL); } # ifdef BSDJOBS if (wanttty >= 0) { (void) signal(SIGTSTP, SIG_DFL); (void) signal(SIGTTIN, SIG_DFL); (void) signal(SIGTTOU, SIG_DFL); } # endif /* BSDJOBS */ sigaction(SIGTERM, &parterm, NULL); } else if (tpgrp == -1 && (t->t_dflg & F_NOINTERRUPT)) { (void) signal(SIGINT, SIG_IGN); (void) signal(SIGQUIT, SIG_IGN); } pgetty(wanttty, pgrp); if (t->t_dflg & F_NOHUP) (void) signal(SIGHUP, SIG_IGN); if (t->t_dflg & F_HUP) (void) signal(SIGHUP, SIG_DFL); if (t->t_dflg & F_NICE) { int nval = SIGN_EXTEND_CHAR(t->t_nice); # if defined(HAVE_SETPRIORITY) && defined(PRIO_PROCESS) if (setpriority(PRIO_PROCESS, 0, nval) == -1 && errno) stderror(ERR_SYSTEM, "setpriority", strerror(errno)); # else /* !HAVE_SETPRIORITY || !PRIO_PROCESS */ (void) nice(nval); # endif /* HAVE_SETPRIORITY && PRIO_PROCESS */ } # ifdef F_VER if (t->t_dflg & F_VER) { tsetenv(STRSYSTYPE, t->t_systype ? STRbsd43 : STRsys53); dohash(NULL, NULL); } # endif /* F_VER */ } } #endif /* VFORK */ } if (pid != 0) { /* * It would be better if we could wait for the whole job when we * knew the last process had been started. Pwait, in fact, does * wait for the whole job anyway, but this test doesn't really * express our intentions. */ #ifdef BACKPIPE if (didfds == 0 && t->t_dflg & F_PIPEOUT) { xclose(pipeout[0]); xclose(pipeout[1]); } if ((t->t_dflg & F_PIPEIN) != 0) break; #else /* !BACKPIPE */ if (didfds == 0 && t->t_dflg & F_PIPEIN) { xclose(pipein[0]); xclose(pipein[1]); } if ((t->t_dflg & F_PIPEOUT) != 0) break; #endif /* BACKPIPE */ if (nosigchld) { sigprocmask(SIG_SETMASK, &csigset, NULL); nosigchld = 0; } if ((t->t_dflg & F_AMPERSAND) == 0) pwait(); break; } doio(t, pipein, pipeout); #ifdef BACKPIPE if (t->t_dflg & F_PIPEIN) { xclose(pipein[0]); xclose(pipein[1]); } #else /* !BACKPIPE */ if (t->t_dflg & F_PIPEOUT) { xclose(pipeout[0]); xclose(pipeout[1]); } #endif /* BACKPIPE */ /* * Perform a builtin function. If we are not forked, arrange for * possible stopping */ if (bifunc) { if (forked) { func(t, bifunc); exitstat(); } else { jmp_buf_t oldexit; int ohaderr = haderr; getexit(oldexit); if (setexit() == 0) func(t, bifunc); resexit(oldexit); haderr = ohaderr; if (adrof(STRprintexitvalue)) { int rv = getn(varval(STRstatus)); if (rv != 0) xprintf(CGETS(17, 2, "Exit %d\n"), rv); } } break; } if (t->t_dtyp != NODE_PAREN) { doexec(t, do_glob); /* NOTREACHED */ } /* * For () commands must put new 0,1,2 in FSH* and recurse */ if ((OLDSTD = dcopy(0, FOLDSTD)) >= 0) (void)close_on_exec(OLDSTD, 1); if ((SHOUT = dcopy(1, FSHOUT)) >= 0) { (void)close_on_exec(SHOUT, 1); isoutatty = isatty(SHOUT); } if ((SHDIAG = dcopy(2, FSHDIAG)) >= 0) { (void)close_on_exec(SHDIAG, 1); isdiagatty = isatty(SHDIAG); } xclose(SHIN); SHIN = -1; #ifndef CLOSE_ON_EXEC didcch = 0; #else (void) close_on_exec(FSHOUT, 1); (void) close_on_exec(FSHDIAG, 1); (void) close_on_exec(FOLDSTD, 1); #endif /* !CLOSE_ON_EXEC */ didfds = 0; wanttty = -1; t->t_dspr->t_dflg |= t->t_dflg & (F_NOINTERRUPT | F_BACKQ); execute(t->t_dspr, wanttty, NULL, NULL, do_glob); exitstat(); case NODE_PIPE: #ifdef BACKPIPE t->t_dcdr->t_dflg |= F_PIPEIN | (t->t_dflg & (F_PIPEOUT | F_AMPERSAND | F_NOFORK | F_NOINTERRUPT | F_BACKQ)); execute(t->t_dcdr, wanttty, pv, pipeout, do_glob); t->t_dcar->t_dflg |= F_PIPEOUT | (t->t_dflg & (F_PIPEIN | F_AMPERSAND | F_STDERR | F_NOINTERRUPT | F_BACKQ)); execute(t->t_dcar, wanttty, pipein, pv, do_glob); #else /* !BACKPIPE */ t->t_dcar->t_dflg |= F_PIPEOUT | (t->t_dflg & (F_PIPEIN | F_AMPERSAND | F_STDERR | F_NOINTERRUPT | F_BACKQ)); execute(t->t_dcar, wanttty, pipein, pv, do_glob); t->t_dcdr->t_dflg |= F_PIPEIN | (t->t_dflg & (F_PIPEOUT | F_AMPERSAND | F_NOFORK | F_NOINTERRUPT | F_BACKQ)); execute(t->t_dcdr, wanttty, pv, pipeout, do_glob); #endif /* BACKPIPE */ break; case NODE_LIST: if (t->t_dcar) { t->t_dcar->t_dflg |= t->t_dflg & (F_NOINTERRUPT | F_BACKQ); execute(t->t_dcar, wanttty, NULL, NULL, do_glob); /* * In strange case of A&B make a new job after A */ if (t->t_dcar->t_dflg & F_AMPERSAND && t->t_dcdr && (t->t_dcdr->t_dflg & F_AMPERSAND) == 0) pendjob(); } if (t->t_dcdr) { t->t_dcdr->t_dflg |= t->t_dflg & (F_NOFORK | F_NOINTERRUPT | F_BACKQ); execute(t->t_dcdr, wanttty, NULL, NULL, do_glob); } break; case NODE_OR: case NODE_AND: if (t->t_dcar) { t->t_dcar->t_dflg |= t->t_dflg & (F_NOINTERRUPT | F_BACKQ); execute(t->t_dcar, wanttty, NULL, NULL, do_glob); if ((getn(varval(STRstatus)) == 0) != (t->t_dtyp == NODE_AND)) { return; } } if (t->t_dcdr) { t->t_dcdr->t_dflg |= t->t_dflg & (F_NOFORK | F_NOINTERRUPT | F_BACKQ); execute(t->t_dcdr, wanttty, NULL, NULL, do_glob); } break; default: break; } /* * Fall through for all breaks from switch - * + * * If there will be no more executions of this command, flush all file * descriptors. Places that turn on the F_REPEAT bit are responsible for * doing donefds after the last re-execution */ if (didfds && !(t->t_dflg & F_REPEAT)) donefds(); } #ifdef VFORK static void /*ARGSUSED*/ vffree(int snum) { USE(snum); _exit(1); } #endif /* VFORK */ /* * Expand and glob the words after an i/o redirection. * If more than one word is generated, then update the command vector. * * This is done differently in all the shells: * 1. in the bourne shell and ksh globbing is not performed * 2. Bash/csh say ambiguous * 3. zsh does i/o to/from all the files * 4. itcsh concatenates the words. * * I don't know what is best to do. I think that Ambiguous is better * than restructuring the command vector, because the user can get - * unexpected results. In any case, the command vector restructuring + * unexpected results. In any case, the command vector restructuring * code is present and the user can choose it by setting noambiguous */ static Char * splicepipe(struct command *t, Char *cp) { Char *blk[2]; if (adrof(STRnoambiguous)) { Char **pv; int gflag; blk[0] = Dfix1(cp); /* expand $ */ blk[1] = NULL; gflag = tglob(blk); if (gflag) { pv = globall(blk, gflag); if (pv == NULL) { setname(short2str(blk[0])); xfree(blk[0]); stderror(ERR_NAME | ERR_NOMATCH); } if (pv[1] != NULL) { /* we need to fix the command vector */ Char **av = blkspl(t->t_dcom, &pv[1]); xfree(t->t_dcom); t->t_dcom = av; } xfree(blk[0]); blk[0] = pv[0]; xfree(pv); } } else { Char *buf; buf = Dfix1(cp); cleanup_push(buf, xfree); blk[0] = globone(buf, G_ERROR); cleanup_until(buf); } return(blk[0]); } - + /* * Perform io redirection. * We may or maynot be forked here. */ static void doio(struct command *t, int *pipein, int *pipeout) { int fd; Char *cp; unsigned long flags = t->t_dflg; if (didfds || (flags & F_REPEAT)) return; if ((flags & F_READ) == 0) {/* F_READ already done */ if (t->t_dlef) { char *tmp; /* * so < /dev/std{in,out,err} work */ (void) dcopy(SHIN, 0); (void) dcopy(SHOUT, 1); (void) dcopy(SHDIAG, 2); cp = splicepipe(t, t->t_dlef); tmp = strsave(short2str(cp)); xfree(cp); cleanup_push(tmp, xfree); if ((fd = xopen(tmp, O_RDONLY|O_LARGEFILE)) < 0) stderror(ERR_SYSTEM, tmp, strerror(errno)); cleanup_until(tmp); /* allow input files larger than 2Gb */ #ifndef WINNT_NATIVE (void) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_LARGEFILE); #endif /*!WINNT_NATIVE*/ (void) dmove(fd, 0); } else if (flags & F_PIPEIN) { xclose(0); TCSH_IGNORE(dup(pipein[0])); xclose(pipein[0]); xclose(pipein[1]); } else if ((flags & F_NOINTERRUPT) && tpgrp == -1) { xclose(0); (void) xopen(_PATH_DEVNULL, O_RDONLY|O_LARGEFILE); } else { xclose(0); TCSH_IGNORE(dup(OLDSTD)); #if defined(CLOSE_ON_EXEC) && defined(CLEX_DUPS) /* * PWP: Unlike Bezerkeley 4.3, FIONCLEX for Pyramid is preserved * across dup()s, so we have to UNSET it here or else we get a * command with NO stdin, stdout, or stderr at all (a bad thing * indeed) */ (void) close_on_exec(0, 0); #endif /* CLOSE_ON_EXEC && CLEX_DUPS */ } } if (t->t_drit) { char *tmp; cp = splicepipe(t, t->t_drit); tmp = strsave(short2str(cp)); xfree(cp); cleanup_push(tmp, xfree); /* * so > /dev/std{out,err} work */ (void) dcopy(SHOUT, 1); (void) dcopy(SHDIAG, 2); if ((flags & F_APPEND) != 0) { #ifdef O_APPEND fd = xopen(tmp, O_WRONLY|O_APPEND|O_LARGEFILE); #else /* !O_APPEND */ fd = xopen(tmp, O_WRONLY|O_LARGEFILE); (void) lseek(fd, (off_t) 0, L_XTND); #endif /* O_APPEND */ } else fd = 0; if ((flags & F_APPEND) == 0 || fd == -1) { if (!(flags & F_OVERWRITE) && no_clobber) { if (flags & F_APPEND) stderror(ERR_SYSTEM, tmp, strerror(errno)); chkclob(tmp); } if ((fd = xcreat(tmp, 0666)) < 0) stderror(ERR_SYSTEM, tmp, strerror(errno)); /* allow input files larger than 2Gb */ #ifndef WINNT_NATIVE (void) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_LARGEFILE); #endif /*!WINNT_NATIVE*/ } cleanup_until(tmp); (void) dmove(fd, 1); is1atty = isatty(1); } else if (flags & F_PIPEOUT) { xclose(1); TCSH_IGNORE(dup(pipeout[1])); is1atty = 0; } else { xclose(1); TCSH_IGNORE(dup(SHOUT)); is1atty = isoutatty; # if defined(CLOSE_ON_EXEC) && defined(CLEX_DUPS) (void) close_on_exec(1, 0); # endif /* CLOSE_ON_EXEC && CLEX_DUPS */ } xclose(2); if (flags & F_STDERR) { TCSH_IGNORE(dup(1)); is2atty = is1atty; } else { TCSH_IGNORE(dup(SHDIAG)); is2atty = isdiagatty; # if defined(CLOSE_ON_EXEC) && defined(CLEX_DUPS) (void) close_on_exec(2, 0); # endif /* CLOSE_ON_EXEC && CLEX_DUPS */ } didfds = 1; } void mypipe(int *pv) { if (pipe(pv) < 0) goto oops; (void)close_on_exec(pv[0] = dmove(pv[0], -1), 1); (void)close_on_exec(pv[1] = dmove(pv[1], -1), 1); if (pv[0] >= 0 && pv[1] >= 0) return; if (pv[0] >= 0) xclose(pv[0]); if (pv[1] >= 0) xclose(pv[1]); oops: stderror(ERR_PIPE); } static void chkclob(const char *cp) { struct stat stb; if (stat(cp, &stb) < 0) return; if (S_ISCHR(stb.st_mode)) return; if (no_clobber & NOCLOBBER_NOTEMPTY && stb.st_size == 0) return; if (no_clobber & NOCLOBBER_ASK) { if (getYN(CGETS(22, 15, "Do you really want to overwrite an existing file? [N/y] "))) return; } stderror(ERR_EXISTS, cp); } diff --git a/contrib/tcsh/sh.set.c b/contrib/tcsh/sh.set.c index e51fdae11cc1..e714cc726bc0 100644 --- a/contrib/tcsh/sh.set.c +++ b/contrib/tcsh/sh.set.c @@ -1,1352 +1,1352 @@ /* * sh.set.c: Setting and Clearing of variables */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include "tw.h" #ifdef HAVE_NL_LANGINFO #include #endif extern int GotTermCaps; int numeof = 0; static void update_vars (Char *); static Char *getinx (Char *, int *); static void asx (Char *, int, Char *); static struct varent *getvx (Char *, int); static Char *xset (Char *, Char ***); static Char *operate (int, Char *, Char *); static void putn1 (tcsh_number_t); static struct varent *madrof (Char *, struct varent *); static void unsetv1 (struct varent *); static void exportpath (Char **); static void balance (struct varent *, int, int); static int set_noclobber (Char **); /* * C Shell */ static void update_vars(Char *vp) { if (eq(vp, STRpath)) { - struct varent *p = adrof(STRpath); + struct varent *p = adrof(STRpath); if (p == NULL) stderror(ERR_NAME | ERR_UNDVAR); else { exportpath(p->vec); dohash(NULL, NULL); } } else if (eq(vp, STRnoclobber)) { struct varent *p = adrof(STRnoclobber); if (p == NULL) stderror(ERR_NAME | ERR_UNDVAR); else no_clobber = set_noclobber(p->vec); } else if (eq(vp, STRhistchars)) { Char *pn = varval(vp); HIST = *pn++; if (HIST) HISTSUB = *pn; else HISTSUB = HIST; } else if (eq(vp, STRpromptchars)) { Char *pn = varval(vp); PRCH = *pn++; if (PRCH) PRCHROOT = *pn; else PRCHROOT = PRCH; } else if (eq(vp, STRhistlit)) { HistLit = 1; } else if (eq(vp, STRuser)) { tsetenv(STRKUSER, varval(vp)); tsetenv(STRLOGNAME, varval(vp)); } else if (eq(vp, STRgroup)) { tsetenv(STRKGROUP, varval(vp)); } else if (eq(vp, STRwordchars)) { word_chars = varval(vp); } else if (eq(vp, STRloginsh)) { loginsh = 1; } else if (eq(vp, STRanyerror)) { anyerror = 1; } else if (eq(vp, STRsymlinks)) { Char *pn = varval(vp); if (eq(pn, STRignore)) symlinks = SYM_IGNORE; else if (eq(pn, STRexpand)) symlinks = SYM_EXPAND; else if (eq(pn, STRchase)) symlinks = SYM_CHASE; else symlinks = 0; } else if (eq(vp, STRterm)) { Char *cp = varval(vp); tsetenv(STRKTERM, cp); #ifdef DOESNT_WORK_RIGHT cp = getenv("TERMCAP"); if (cp && (*cp != '/')) /* if TERMCAP and not a path */ Unsetenv(STRTERMCAP); #endif /* DOESNT_WORK_RIGHT */ GotTermCaps = 0; if (noediting && Strcmp(cp, STRnetwork) != 0 && Strcmp(cp, STRunknown) != 0 && Strcmp(cp, STRdumb) != 0) { editing = 1; noediting = 0; setNS(STRedit); } ed_Init(); /* reset the editor */ } else if (eq(vp, STRhome)) { Char *cp, *canon; cp = Strsave(varval(vp)); /* get the old value back */ /* * convert to cononical pathname (possibly resolving symlinks) */ canon = dcanon(cp, cp); cleanup_push(canon, xfree); setcopy(vp, canon, VAR_READWRITE); /* have to save the new val */ /* and now mirror home with HOME */ tsetenv(STRKHOME, canon); /* fix directory stack for new tilde home */ dtilde(); cleanup_until(canon); } else if (eq(vp, STRedit)) { editing = 1; noediting = 0; /* PWP: add more stuff in here later */ } else if (eq(vp, STRvimode)) { VImode = 1; update_wordchars(); } else if (eq(vp, STRshlvl)) { tsetenv(STRKSHLVL, varval(vp)); } else if (eq(vp, STRignoreeof)) { Char *cp; numeof = 0; for ((cp = varval(STRignoreeof)); cp && *cp; cp++) { if (!Isdigit(*cp)) { numeof = 0; break; } numeof = numeof * 10 + *cp - '0'; } if (numeof <= 0) numeof = 26; /* Sanity check */ - } + } else if (eq(vp, STRbackslash_quote)) { bslash_quote = 1; } else if (eq(vp, STRcompat_expr)) { compat_expr = 1; } else if (eq(vp, STRdirstack)) { dsetstack(); } else if (eq(vp, STRrecognize_only_executables)) { tw_cmd_free(); } else if (eq(vp, STRkillring)) { SetKillRing((int)getn(varval(vp))); } else if (eq(vp, STRhistory)) { sethistory((int)getn(varval(vp))); } #ifndef HAVENOUTMP else if (eq(vp, STRwatch)) { resetwatch(); } #endif /* HAVENOUTMP */ else if (eq(vp, STRimplicitcd)) { implicit_cd = ((eq(varval(vp), STRverbose)) ? 2 : 1); } else if (eq(vp, STRcdtohome)) { cdtohome = 1; } #ifdef COLOR_LS_F else if (eq(vp, STRcolor)) { set_color_context(); } #endif /* COLOR_LS_F */ #if defined(KANJI) && defined(SHORT_STRINGS) && defined(DSPMBYTE) else if (eq(vp, CHECK_MBYTEVAR) || eq(vp, STRnokanji)) { update_dspmbyte_vars(); } #endif #ifdef NLS_CATALOGS else if (eq(vp, STRcatalog)) { nlsclose(); nlsinit(); } #if defined(FILEC) && defined(TIOCSTI) else if (eq(vp, STRfilec)) filec = 1; #endif #endif /* NLS_CATALOGS */ } /*ARGSUSED*/ void doset(Char **v, struct command *c) { Char *p; Char *vp; Char **vecp; int hadsub; int subscr; int flags = VAR_READWRITE; int first_match = 0; int last_match = 0; int changed = 0; USE(c); v++; do { changed = 0; /* * Readonly addition From: Tim P. Starrin */ if (*v && eq(*v, STRmr)) { flags = VAR_READONLY; v++; changed = 1; } if (*v && eq(*v, STRmf) && !last_match) { first_match = 1; v++; changed = 1; } if (*v && eq(*v, STRml) && !first_match) { last_match = 1; v++; changed = 1; } } while (changed); p = *v++; if (p == 0) { plist(&shvhed, flags); return; } do { hadsub = 0; vp = p; if (!letter(*p)) stderror(ERR_NAME | ERR_VARBEGIN); do { p++; } while (alnum(*p)); if (*p == '[') { hadsub++; p = getinx(p, &subscr); } if (*p != '\0' && *p != '=') stderror(ERR_NAME | ERR_VARALNUM); if (*p == '=') { *p++ = '\0'; if (*p == '\0' && *v != NULL && **v == '(') p = *v++; } else if (*v && eq(*v, STRequal)) { if (*++v != NULL) p = *v++; } if (eq(p, STRLparen)) { Char **e = v; if (hadsub) stderror(ERR_NAME | ERR_SYNTAX); for (;;) { if (!*e) stderror(ERR_NAME | ERR_MISSING, ')'); if (**e == ')') break; e++; } p = *e; *e = 0; vecp = saveblk(v); if (first_match) flags |= VAR_FIRST; else if (last_match) flags |= VAR_LAST; set1(vp, vecp, &shvhed, flags); *e = p; v = e + 1; } else if (hadsub) { Char *copy; copy = Strsave(p); cleanup_push(copy, xfree); asx(vp, subscr, copy); cleanup_ignore(copy); cleanup_until(copy); } else setv(vp, Strsave(p), flags); update_vars(vp); } while ((p = *v++) != NULL); } static Char * getinx(Char *cp, int *ip) { *ip = 0; *cp++ = 0; while (*cp && Isdigit(*cp)) *ip = *ip * 10 + *cp++ - '0'; if (*cp++ != ']') stderror(ERR_NAME | ERR_SUBSCRIPT); return (cp); } static void asx(Char *vp, int subscr, Char *p) { struct varent *v = getvx(vp, subscr); Char *prev; if (v->v_flags & VAR_READONLY) stderror(ERR_READONLY|ERR_NAME, v->v_name); prev = v->vec[subscr - 1]; cleanup_push(prev, xfree); v->vec[subscr - 1] = globone(p, G_APPEND); cleanup_until(prev); } static struct varent * getvx(Char *vp, int subscr) { struct varent *v = adrof(vp); if (v == 0) udvar(vp); if (subscr < 1 || subscr > blklen(v->vec)) stderror(ERR_NAME | ERR_RANGE); return (v); } /*ARGSUSED*/ void dolet(Char **v, struct command *dummy) { Char *p; Char *vp, c, op; int hadsub; int subscr; USE(dummy); v++; p = *v++; if (p == 0) { prvars(); return; } do { hadsub = 0; vp = p; if (letter(*p)) for (; alnum(*p); p++) continue; if (vp == p || !letter(*vp)) stderror(ERR_NAME | ERR_VARBEGIN); if (*p == '[') { hadsub++; p = getinx(p, &subscr); } if (*p == 0 && *v) p = *v++; if ((op = *p) != 0) *p++ = 0; else stderror(ERR_NAME | ERR_ASSIGN); /* * if there is no expression after the '=' then print a "Syntax Error" * message - strike */ if (*p == '\0' && *v == NULL) stderror(ERR_NAME | ERR_ASSIGN); vp = Strsave(vp); cleanup_push(vp, xfree); if (op == '=') { c = '='; p = xset(p, &v); } else { c = *p++; if (any("+-", c)) { if (c != op || *p) stderror(ERR_NAME | ERR_UNKNOWNOP); p = Strsave(STR1); } else { if (any("<>", op)) { if (c != op) stderror(ERR_NAME | ERR_UNKNOWNOP); stderror(ERR_NAME | ERR_SYNTAX); } if (c != '=') stderror(ERR_NAME | ERR_UNKNOWNOP); p = xset(p, &v); } } cleanup_push(p, xfree); if (op == '=') { if (hadsub) asx(vp, subscr, p); else setv(vp, p, VAR_READWRITE); cleanup_ignore(p); } else if (hadsub) { struct varent *gv = getvx(vp, subscr); Char *val; val = operate(op, gv->vec[subscr - 1], p); cleanup_push(val, xfree); asx(vp, subscr, val); cleanup_ignore(val); cleanup_until(val); } else { Char *val; val = operate(op, varval(vp), p); cleanup_push(val, xfree); setv(vp, val, VAR_READWRITE); cleanup_ignore(val); cleanup_until(val); } update_vars(vp); cleanup_until(vp); } while ((p = *v++) != NULL); } static Char * xset(Char *cp, Char ***vp) { Char *dp; if (*cp) { dp = Strsave(cp); --(*vp); xfree(** vp); **vp = dp; } return (putn(expr(vp))); } static Char * operate(int op, Char *vp, Char *p) { Char opr[2]; Char *vec[5]; Char **v = vec; Char **vecp = v; tcsh_number_t i; if (op != '=') { if (*vp) *v++ = vp; opr[0] = op; opr[1] = 0; *v++ = opr; if (op == '<' || op == '>') *v++ = opr; } *v++ = p; *v++ = 0; i = expr(&vecp); if (*vecp) stderror(ERR_NAME | ERR_EXPRESSION); return (putn(i)); } static Char *putp; Char * putn(tcsh_number_t n) { Char nbuf[1024]; /* Enough even for octal */ putp = nbuf; if (n < 0) { n = -n; *putp++ = '-'; } putn1(n); *putp = 0; return (Strsave(nbuf)); } static void putn1(tcsh_number_t n) { if (n > 9) putn1(n / 10); *putp++ = (Char)(n % 10 + '0'); } tcsh_number_t getn(const Char *cp) { tcsh_number_t n; int sign; int base; if (!cp) /* PWP: extra error checking */ stderror(ERR_NAME | ERR_BADNUM); sign = 0; if (cp[0] == '+' && cp[1]) cp++; if (*cp == '-') { sign++; cp++; if (!Isdigit(*cp)) stderror(ERR_NAME | ERR_BADNUM); } if (cp[0] == '0' && cp[1] && is_set(STRparseoctal)) base = 8; else base = 10; n = 0; while (Isdigit(*cp)) { if (base == 8 && *cp >= '8') stderror(ERR_NAME | ERR_BADNUM); n = n * base + *cp++ - '0'; } if (*cp) stderror(ERR_NAME | ERR_BADNUM); return (sign ? -n : n); } Char * value1(Char *var, struct varent *head) { struct varent *vp; if (!var || !head) /* PWP: extra error checking */ return (STRNULL); vp = adrof1(var, head); return ((vp == NULL || vp->vec == NULL || vp->vec[0] == NULL) ? STRNULL : vp->vec[0]); } static struct varent * madrof(Char *pat, struct varent *vp) { struct varent *vp1; for (vp = vp->v_left; vp; vp = vp->v_right) { if (vp->v_left && (vp1 = madrof(pat, vp)) != NULL) return vp1; if (Gmatch(vp->v_name, pat)) return vp; } return vp; } struct varent * adrof1(const Char *name, struct varent *v) { int cmp; v = v->v_left; - while (v && ((cmp = *name - *v->v_name) != 0 || + while (v && ((cmp = *name - *v->v_name) != 0 || (cmp = Strcmp(name, v->v_name)) != 0)) if (cmp < 0) v = v->v_left; else v = v->v_right; return v; } void setcopy(const Char *var, const Char *val, int flags) { Char *copy; copy = Strsave(val); cleanup_push(copy, xfree); setv(var, copy, flags); cleanup_ignore(copy); cleanup_until(copy); } /* * The caller is responsible for putting value in a safe place */ void setv(const Char *var, Char *val, int flags) { Char **vec = xmalloc(2 * sizeof(Char **)); vec[0] = val; vec[1] = 0; set1(var, vec, &shvhed, flags); } void set1(const Char *var, Char **vec, struct varent *head, int flags) { Char **oldv = vec; if ((flags & VAR_NOGLOB) == 0) { int gflag; gflag = tglob(oldv); if (gflag) { vec = globall(oldv, gflag); if (vec == NULL) { blkfree(oldv); stderror(ERR_NAME | ERR_NOMATCH); } blkfree(oldv); } } /* * Uniqueness addition from: Michael Veksler */ if ( flags & (VAR_FIRST | VAR_LAST) ) { /* * Code for -f (VAR_FIRST) and -l (VAR_LAST) options. * Method: * Delete all duplicate words leaving "holes" in the word array (vec). * Then remove the "holes", keeping the order of the words unchanged. */ if (vec[0] && vec[1]) { /* more than one word ? */ int i, j; int num_items; for (num_items = 0; vec[num_items]; num_items++) continue; if (flags & VAR_FIRST) { /* delete duplications, keeping first occurance */ for (i = 1; i < num_items; i++) for (j = 0; j < i; j++) /* If have earlier identical item, remove i'th item */ if (vec[i] && vec[j] && Strcmp(vec[j], vec[i]) == 0) { xfree(vec[i]); vec[i] = NULL; break; } } else if (flags & VAR_LAST) { /* delete duplications, keeping last occurance */ for (i = 0; i < num_items - 1; i++) for (j = i + 1; j < num_items; j++) /* If have later identical item, remove i'th item */ if (vec[i] && vec[j] && Strcmp(vec[j], vec[i]) == 0) { /* remove identical item (the first) */ xfree(vec[i]); vec[i] = NULL; } } /* Compress items - remove empty items */ for (j = i = 0; i < num_items; i++) - if (vec[i]) + if (vec[i]) vec[j++] = vec[i]; /* NULL-fy remaining items */ for (; j < num_items; j++) vec[j] = NULL; } /* don't let the attribute propagate */ flags &= ~(VAR_FIRST|VAR_LAST); - } + } setq(var, vec, head, flags); } void setq(const Char *name, Char **vec, struct varent *p, int flags) { struct varent *c; int f; f = 0; /* tree hangs off the header's left link */ while ((c = p->v_link[f]) != 0) { if ((f = *name - *c->v_name) == 0 && (f = Strcmp(name, c->v_name)) == 0) { if (c->v_flags & VAR_READONLY) stderror(ERR_READONLY|ERR_NAME, c->v_name); blkfree(c->vec); c->v_flags = flags; trim(c->vec = vec); return; } p = c; f = f > 0; } p->v_link[f] = c = xmalloc(sizeof(struct varent)); c->v_name = Strsave(name); c->v_flags = flags; c->v_bal = 0; c->v_left = c->v_right = 0; c->v_parent = p; balance(p, f, 0); trim(c->vec = vec); } /*ARGSUSED*/ void unset(Char **v, struct command *c) { int did_roe, did_edit; USE(c); did_roe = adrof(STRrecognize_only_executables) != NULL; did_edit = adrof(STRedit) != NULL; unset1(v, &shvhed); #if defined(FILEC) && defined(TIOCSTI) if (adrof(STRfilec) == 0) filec = 0; #endif /* FILEC && TIOCSTI */ if (adrof(STRhistchars) == 0) { HIST = '!'; HISTSUB = '^'; } if (adrof(STRignoreeof) == 0) numeof = 0; if (adrof(STRpromptchars) == 0) { PRCH = tcsh ? '>' : '%'; PRCHROOT = '#'; } if (adrof(STRnoclobber) == 0) no_clobber = 0; if (adrof(STRhistlit) == 0) HistLit = 0; if (adrof(STRloginsh) == 0) loginsh = 0; if (adrof(STRanyerror) == 0) anyerror = 0; if (adrof(STRwordchars) == 0) word_chars = STR_WORD_CHARS; if (adrof(STRedit) == 0) editing = 0; if (adrof(STRbackslash_quote) == 0) bslash_quote = 0; if (adrof(STRcompat_expr) == 0) compat_expr = 0; if (adrof(STRsymlinks) == 0) symlinks = 0; if (adrof(STRimplicitcd) == 0) implicit_cd = 0; if (adrof(STRcdtohome) == 0) cdtohome = 0; if (adrof(STRkillring) == 0) SetKillRing(0); if (did_edit && noediting && adrof(STRedit) == 0) noediting = 0; if (adrof(STRvimode) == 0) VImode = 0; if (did_roe && adrof(STRrecognize_only_executables) == 0) tw_cmd_free(); if (adrof(STRhistory) == 0) sethistory(0); #ifdef COLOR_LS_F if (adrof(STRcolor) == 0) set_color_context(); #endif /* COLOR_LS_F */ #if defined(KANJI) && defined(SHORT_STRINGS) && defined(DSPMBYTE) update_dspmbyte_vars(); #endif update_wordchars(); #ifdef NLS_CATALOGS nlsclose(); nlsinit(); #endif /* NLS_CATALOGS */ } void unset1(Char *v[], struct varent *head) { struct varent *vp; int cnt; while (*++v) { cnt = 0; while ((vp = madrof(*v, head)) != NULL) if (vp->v_flags & VAR_READONLY) stderror(ERR_READONLY|ERR_NAME, vp->v_name); else unsetv1(vp), cnt++; if (cnt == 0) setname(short2str(*v)); } } void unsetv(Char *var) { struct varent *vp; if ((vp = adrof1(var, &shvhed)) == 0) udvar(var); unsetv1(vp); } static void unsetv1(struct varent *p) { struct varent *c, *pp; int f; /* * Free associated memory first to avoid complications. */ blkfree(p->vec); xfree(p->v_name); /* * If p is missing one child, then we can move the other into where p is. * Otherwise, we find the predecessor of p, which is guaranteed to have no * right child, copy it into p, and move it's left child into it. */ if (p->v_right == 0) c = p->v_left; else if (p->v_left == 0) c = p->v_right; else { for (c = p->v_left; c->v_right; c = c->v_right) continue; p->v_name = c->v_name; p->v_flags = c->v_flags; p->vec = c->vec; p = c; c = p->v_left; } /* * Move c into where p is. */ pp = p->v_parent; f = pp->v_right == p; if ((pp->v_link[f] = c) != 0) c->v_parent = pp; /* * Free the deleted node, and rebalance. */ xfree(p); balance(pp, f, 1); } /* Set variable name to NULL. */ void setNS(const Char *varName) { setcopy(varName, STRNULL, VAR_READWRITE); } /*ARGSUSED*/ void shift(Char **v, struct command *c) { struct varent *argv; Char *name; USE(c); v++; name = *v; if (name == 0) name = STRargv; else (void) strip(name); argv = adrof(name); if (argv == NULL || argv->vec == NULL) udvar(name); if (argv->vec[0] == 0) stderror(ERR_NAME | ERR_NOMORE); lshift(argv->vec, 1); update_vars(name); } static void exportpath(Char **val) { struct Strbuf buf = Strbuf_INIT; Char *exppath; if (val) while (*val) { Strbuf_append(&buf, *val++); if (*val == 0 || eq(*val, STRRparen)) break; Strbuf_append1(&buf, PATHSEP); } exppath = Strbuf_finish(&buf); cleanup_push(exppath, xfree); tsetenv(STRKPATH, exppath); cleanup_until(exppath); } static int set_noclobber(Char **val) { Char *option; int nc = NOCLOBBER_DEFAULT; if (val == NULL) return nc; while (*val) { if (*val == 0 || eq(*val, STRRparen)) return nc; option = *val++; if (eq(option, STRnotempty)) nc |= NOCLOBBER_NOTEMPTY; else if (eq(option, STRask)) nc |= NOCLOBBER_ASK; } return nc; } #ifndef lint /* * Lint thinks these have null effect */ /* macros to do single rotations on node p */ # define rright(p) (\ t = (p)->v_left,\ (t)->v_parent = (p)->v_parent,\ (((p)->v_left = t->v_right) != NULL) ?\ (t->v_right->v_parent = (p)) : 0,\ (t->v_right = (p))->v_parent = t,\ (p) = t) # define rleft(p) (\ t = (p)->v_right,\ ((t)->v_parent = (p)->v_parent,\ ((p)->v_right = t->v_left) != NULL) ? \ (t->v_left->v_parent = (p)) : 0,\ (t->v_left = (p))->v_parent = t,\ (p) = t) #else static struct varent * rleft(struct varent *p) { return (p); } static struct varent * rright(struct varent *p) { return (p); } #endif /* ! lint */ /* * Rebalance a tree, starting at p and up. * F == 0 means we've come from p's left child. * D == 1 means we've just done a delete, otherwise an insert. */ static void balance(struct varent *p, int f, int d) { struct varent *pp; #ifndef lint struct varent *t; /* used by the rotate macros */ #endif /* !lint */ int ff; #ifdef lint ff = 0; /* Sun's lint is dumb! */ #endif /* * Ok, from here on, p is the node we're operating on; pp is it's parent; f * is the branch of p from which we have come; ff is the branch of pp which * is p. */ for (; (pp = p->v_parent) != 0; p = pp, f = ff) { ff = pp->v_right == p; if (f ^ d) { /* right heavy */ switch (p->v_bal) { case -1: /* was left heavy */ p->v_bal = 0; break; case 0: /* was balanced */ p->v_bal = 1; break; case 1: /* was already right heavy */ switch (p->v_right->v_bal) { case 1: /* single rotate */ pp->v_link[ff] = rleft(p); p->v_left->v_bal = 0; p->v_bal = 0; break; case 0: /* single rotate */ pp->v_link[ff] = rleft(p); p->v_left->v_bal = 1; p->v_bal = -1; break; case -1: /* double rotate */ (void) rright(p->v_right); pp->v_link[ff] = rleft(p); p->v_left->v_bal = p->v_bal < 1 ? 0 : -1; p->v_right->v_bal = p->v_bal > -1 ? 0 : 1; p->v_bal = 0; break; default: break; } break; default: break; } } else { /* left heavy */ switch (p->v_bal) { case 1: /* was right heavy */ p->v_bal = 0; break; case 0: /* was balanced */ p->v_bal = -1; break; case -1: /* was already left heavy */ switch (p->v_left->v_bal) { case -1: /* single rotate */ pp->v_link[ff] = rright(p); p->v_right->v_bal = 0; p->v_bal = 0; break; case 0: /* single rotate */ pp->v_link[ff] = rright(p); p->v_right->v_bal = -1; p->v_bal = 1; break; case 1: /* double rotate */ (void) rleft(p->v_left); pp->v_link[ff] = rright(p); p->v_left->v_bal = p->v_bal < 1 ? 0 : -1; p->v_right->v_bal = p->v_bal > -1 ? 0 : 1; p->v_bal = 0; break; default: break; } break; default: break; } } /* * If from insert, then we terminate when p is balanced. If from * delete, then we terminate when p is unbalanced. */ if ((p->v_bal == 0) ^ d) break; } } void plist(struct varent *p, int what) { struct varent *c; int len; for (;;) { while (p->v_left) p = p->v_left; x: if (p->v_parent == 0) /* is it the header? */ break; if ((p->v_flags & what) != 0) { if (setintr) { int old_pintr_disabled; pintr_push_enable(&old_pintr_disabled); cleanup_until(&old_pintr_disabled); } len = blklen(p->vec); xprintf("%S\t", p->v_name); if (len != 1) xputchar('('); blkpr(p->vec); if (len != 1) xputchar(')'); xputchar('\n'); } if (p->v_right) { p = p->v_right; continue; } do { c = p; p = p->v_parent; } while (p->v_right == c); goto x; } } #if defined(KANJI) # if defined(SHORT_STRINGS) && defined(DSPMBYTE) extern int dspmbyte_ls; void update_dspmbyte_vars(void) { int lp, iskcode; Char *dstr1; struct varent *vp; - + /* if variable "nokanji" is set, multi-byte display is disabled */ if ((vp = adrof(CHECK_MBYTEVAR)) && !adrof(STRnokanji)) { _enable_mbdisp = 1; dstr1 = vp->vec[0]; if (eq (dstr1, STRsjis)) iskcode = 1; else if (eq(dstr1, STReuc)) iskcode = 2; else if (eq(dstr1, STRbig5)) iskcode = 3; else if (eq(dstr1, STRutf8)) iskcode = 4; else if ((dstr1[0] - '0') >= 0 && (dstr1[0] - '0') <= 3) { iskcode = 0; } else { xprintf(CGETS(18, 2, "Warning: unknown multibyte display; using default(euc(JP))\n")); iskcode = 2; } if (dstr1 && vp->vec[1] && eq(vp->vec[1], STRls)) dspmbyte_ls = 1; else dspmbyte_ls = 0; for (lp = 0; lp < 256 && iskcode > 0; lp++) { switch (iskcode) { case 1: /* Shift-JIS */ _cmap[lp] = _cmap_mbyte[lp]; _mbmap[lp] = _mbmap_sjis[lp]; break; case 2: /* 2 ... euc */ _cmap[lp] = _cmap_mbyte[lp]; _mbmap[lp] = _mbmap_euc[lp]; break; case 3: /* 3 ... big5 */ _cmap[lp] = _cmap_mbyte[lp]; _mbmap[lp] = _mbmap_big5[lp]; break; case 4: /* 4 ... utf8 */ _cmap[lp] = _cmap_mbyte[lp]; _mbmap[lp] = _mbmap_utf8[lp]; break; default: xprintf(CGETS(18, 3, "Warning: unknown multibyte code %d; multibyte disabled\n"), iskcode); _cmap[lp] = _cmap_c[lp]; _mbmap[lp] = 0; /* Default map all 0 */ _enable_mbdisp = 0; break; } } if (iskcode == 0) { /* check original table */ if (Strlen(dstr1) != 256) { xprintf(CGETS(18, 4, "Warning: Invalid multibyte table length (%d); multibyte disabled\n"), Strlen(dstr1)); _enable_mbdisp = 0; } for (lp = 0; lp < 256 && _enable_mbdisp == 1; lp++) { if (!((dstr1[lp] - '0') >= 0 && (dstr1[lp] - '0') <= 3)) { xprintf(CGETS(18, 4, "Warning: bad multibyte code at offset +%d; multibyte diabled\n"), lp); _enable_mbdisp = 0; break; } } /* set original table */ for (lp = 0; lp < 256; lp++) { if (_enable_mbdisp == 1) { _cmap[lp] = _cmap_mbyte[lp]; _mbmap[lp] = (unsigned short) ((dstr1[lp] - '0') & 0x0f); } else { _cmap[lp] = _cmap_c[lp]; _mbmap[lp] = 0; /* Default map all 0 */ } } } } else { for (lp = 0; lp < 256; lp++) { _cmap[lp] = _cmap_c[lp]; _mbmap[lp] = 0; /* Default map all 0 */ } _enable_mbdisp = 0; dspmbyte_ls = 0; } #ifdef MBYTEDEBUG /* Sorry, use for beta testing */ { Char mbmapstr[300]; for (lp = 0; lp < 256; lp++) mbmapstr[lp] = _mbmap[lp] + '0'; mbmapstr[lp] = 0; setcopy(STRmbytemap, mbmapstr, VAR_READWRITE); } #endif /* MBYTEMAP */ } /* dspkanji/dspmbyte autosetting */ /* PATCH IDEA FROM Issei.Suzuki VERY THANKS */ void autoset_dspmbyte(const Char *pcp) { int i; static const struct dspm_autoset_Table { Char *n; Char *v; } dspmt[] = { { STRLANGEUCJP, STReuc }, { STRLANGEUCKR, STReuc }, { STRLANGEUCZH, STReuc }, { STRLANGEUCJPB, STReuc }, { STRLANGEUCKRB, STReuc }, { STRLANGEUCZHB, STReuc }, #ifdef __linux__ { STRLANGEUCJPC, STReuc }, #endif { STRLANGSJIS, STRsjis }, { STRLANGSJISB, STRsjis }, { STRLANGBIG5, STRbig5 }, { STRstarutfstar8, STRutf8 }, { NULL, NULL } }; #if defined(HAVE_NL_LANGINFO) && defined(CODESET) static const struct dspm_autoset_Table dspmc[] = { { STRstarutfstar8, STRutf8 }, { STReuc, STReuc }, { STRGB2312, STReuc }, { STRLANGBIG5, STRbig5 }, { NULL, NULL } }; Char *codeset; codeset = str2short(nl_langinfo(CODESET)); if (*codeset != '\0') { for (i = 0; dspmc[i].n; i++) { const Char *estr; if (dspmc[i].n[0] && t_pmatch(pcp, dspmc[i].n, &estr, 0) > 0) { setcopy(CHECK_MBYTEVAR, dspmc[i].v, VAR_READWRITE); update_dspmbyte_vars(); return; } } } #endif - + if (*pcp == '\0') return; for (i = 0; dspmt[i].n; i++) { const Char *estr; if (dspmt[i].n[0] && t_pmatch(pcp, dspmt[i].n, &estr, 0) > 0) { setcopy(CHECK_MBYTEVAR, dspmt[i].v, VAR_READWRITE); update_dspmbyte_vars(); break; } } } # elif defined(AUTOSET_KANJI) void autoset_kanji(void) { char *codeset = nl_langinfo(CODESET); - + if (*codeset == '\0') { if (adrof(STRnokanji) == NULL) setNS(STRnokanji); return; } if (strcasestr(codeset, "SHIFT_JIS") == (char*)0) { if (adrof(STRnokanji) == NULL) setNS(STRnokanji); return; } if (adrof(STRnokanji) != NULL) unsetv(STRnokanji); } #endif #endif void update_wordchars(void) { if ((word_chars == STR_WORD_CHARS) || (word_chars == STR_WORD_CHARS_VI)) { word_chars = (VImode ? STR_WORD_CHARS_VI : STR_WORD_CHARS); } } diff --git a/contrib/tcsh/sh.time.c b/contrib/tcsh/sh.time.c index 4add2a71dd5a..33ea4f498369 100644 --- a/contrib/tcsh/sh.time.c +++ b/contrib/tcsh/sh.time.c @@ -1,741 +1,741 @@ /* * sh.time.c: Shell time keeping and printing. */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #ifdef SUNOS4 # include #endif /* SUNOS4 */ /* * C Shell - routines handling process timing and niceing */ #ifdef BSDTIMES # ifndef RUSAGE_SELF # define RUSAGE_SELF 0 # define RUSAGE_CHILDREN -1 # endif /* RUSAGE_SELF */ #else /* BSDTIMES */ struct tms times0; #endif /* BSDTIMES */ #if !defined(BSDTIMES) && !defined(_SEQUENT_) # ifdef POSIX static void pdtimet (clock_t, clock_t); # else /* ! POSIX */ static void pdtimet (time_t, time_t); # endif /* ! POSIX */ #else /* BSDTIMES || _SEQUENT_ */ static void tvadd (timeval_t *, timeval_t *); static void pdeltat (timeval_t *, timeval_t *); #endif /* BSDTIMES || _SEQUENT_ */ void settimes(void) { #ifdef BSDTIMES struct sysrusage ruch; #ifdef convex memset(&ru0, 0, sizeof(ru0)); memset(&ruch, 0, sizeof(ruch)); #endif /* convex */ (void) gettimeofday(&time0, NULL); (void) getrusage(RUSAGE_SELF, (struct rusage *) &ru0); (void) getrusage(RUSAGE_CHILDREN, (struct rusage *) &ruch); ruadd(&ru0, &ruch); #else # ifdef _SEQUENT_ struct process_stats ruch; (void) get_process_stats(&time0, PS_SELF, &ru0, &ruch); ruadd(&ru0, &ruch); # else /* _SEQUENT_ */ seconds0 = time(NULL); time0 = times(×0); times0.tms_stime += times0.tms_cstime; times0.tms_utime += times0.tms_cutime; times0.tms_cstime = 0; times0.tms_cutime = 0; # endif /* _SEQUENT_ */ #endif /* BSDTIMES */ } /* * dotime is only called if it is truly a builtin function and not a * prefix to another command */ /*ARGSUSED*/ void dotime(Char **v, struct command *c) { #ifdef BSDTIMES timeval_t timedol; struct sysrusage ru1, ruch; #ifdef convex memset(&ru1, 0, sizeof(ru1)); memset(&ruch, 0, sizeof(ruch)); #endif /* convex */ (void) getrusage(RUSAGE_SELF, (struct rusage *) &ru1); (void) getrusage(RUSAGE_CHILDREN, (struct rusage *) &ruch); ruadd(&ru1, &ruch); (void) gettimeofday(&timedol, NULL); prusage(&ru0, &ru1, &timedol, &time0); #else # ifdef _SEQUENT_ timeval_t timedol; struct process_stats ru1, ruch; (void) get_process_stats(&timedol, PS_SELF, &ru1, &ruch); ruadd(&ru1, &ruch); prusage(&ru0, &ru1, &timedol, &time0); # else /* _SEQUENT_ */ # ifndef POSIX time_t timedol; # else /* POSIX */ clock_t timedol; # endif /* POSIX */ struct tms times_dol; timedol = times(×_dol); times_dol.tms_stime += times_dol.tms_cstime; times_dol.tms_utime += times_dol.tms_cutime; times_dol.tms_cstime = 0; times_dol.tms_cutime = 0; prusage(×0, ×_dol, timedol, time0); # endif /* _SEQUENT_ */ #endif /* BSDTIMES */ USE(c); USE(v); } /* * donice is only called when it on the line by itself or with a +- value */ /*ARGSUSED*/ void donice(Char **v, struct command *c) { Char *cp; int nval = 0; USE(c); v++, cp = *v++; if (cp == 0) nval = 4; else if (*v == 0 && any("+-", cp[0])) nval = getn(cp); #if defined(HAVE_SETPRIORITY) && defined(PRIO_PROCESS) if (setpriority(PRIO_PROCESS, 0, nval) == -1 && errno) stderror(ERR_SYSTEM, "setpriority", strerror(errno)); #else /* !HAVE_SETPRIORITY || !PRIO_PROCESS */ (void) nice(nval); #endif /* HAVE_SETPRIORITY && PRIO_PROCESS */ } #ifdef BSDTIMES void ruadd(struct sysrusage *ru, struct sysrusage *ru2) { tvadd(&ru->ru_utime, &ru2->ru_utime); tvadd(&ru->ru_stime, &ru2->ru_stime); #ifndef _OSD_POSIX if (ru2->ru_maxrss > ru->ru_maxrss) ru->ru_maxrss = ru2->ru_maxrss; ru->ru_ixrss += ru2->ru_ixrss; ru->ru_idrss += ru2->ru_idrss; ru->ru_isrss += ru2->ru_isrss; ru->ru_minflt += ru2->ru_minflt; ru->ru_majflt += ru2->ru_majflt; ru->ru_nswap += ru2->ru_nswap; ru->ru_inblock += ru2->ru_inblock; ru->ru_oublock += ru2->ru_oublock; ru->ru_msgsnd += ru2->ru_msgsnd; ru->ru_msgrcv += ru2->ru_msgrcv; ru->ru_nsignals += ru2->ru_nsignals; ru->ru_nvcsw += ru2->ru_nvcsw; ru->ru_nivcsw += ru2->ru_nivcsw; #endif /*bs2000*/ # ifdef convex tvadd(&ru->ru_exutime, &ru2->ru_exutime); ru->ru_utotal += ru2->ru_utotal; ru->ru_usamples += ru2->ru_usamples; ru->ru_stotal += ru2->ru_stotal; ru->ru_ssamples += ru2->ru_ssamples; # endif /* convex */ } #else /* BSDTIMES */ # ifdef _SEQUENT_ void ruadd(struct process_stats *ru, struct process_stats *ru2) { tvadd(&ru->ps_utime, &ru2->ps_utime); tvadd(&ru->ps_stime, &ru2->ps_stime); if (ru2->ps_maxrss > ru->ps_maxrss) ru->ps_maxrss = ru2->ps_maxrss; ru->ps_pagein += ru2->ps_pagein; ru->ps_reclaim += ru2->ps_reclaim; ru->ps_zerofill += ru2->ps_zerofill; ru->ps_pffincr += ru2->ps_pffincr; ru->ps_pffdecr += ru2->ps_pffdecr; ru->ps_swap += ru2->ps_swap; ru->ps_syscall += ru2->ps_syscall; ru->ps_volcsw += ru2->ps_volcsw; ru->ps_involcsw += ru2->ps_involcsw; ru->ps_signal += ru2->ps_signal; ru->ps_lread += ru2->ps_lread; ru->ps_lwrite += ru2->ps_lwrite; ru->ps_bread += ru2->ps_bread; ru->ps_bwrite += ru2->ps_bwrite; ru->ps_phread += ru2->ps_phread; ru->ps_phwrite += ru2->ps_phwrite; } # endif /* _SEQUENT_ */ #endif /* BSDTIMES */ #ifdef BSDTIMES /* * PWP: the LOG1024 and pagetok stuff taken from the top command, * written by William LeFebvre */ /* Log base 2 of 1024 is 10 (2^10 == 1024) */ #define LOG1024 10 /* Convert clicks (kernel pages) to kbytes ... */ /* If there is no PGSHIFT defined, assume it is 11 */ /* Is this needed for compatability with some old flavor of 4.2 or 4.1? */ #ifdef SUNOS4 # ifndef PGSHIFT # define pagetok(size) ((size) << 1) # else # if PGSHIFT>10 # define pagetok(size) ((size) << (PGSHIFT - LOG1024)) # else # define pagetok(size) ((size) >> (LOG1024 - PGSHIFT)) # endif # endif #endif /* * if any other machines return wierd values in the ru_i* stuff, put * the adjusting macro here: */ #ifdef SUNOS4 # define IADJUST(i) (pagetok(i)/2) #else /* SUNOS4 */ # ifdef convex /* * convex has megabytes * CLK_TCK * multiply by 100 since we use time in 100ths of a second in prusage */ # define IADJUST(i) (((i) << 10) / CLK_TCK * 100) # else /* convex */ # define IADJUST(i) (i) # endif /* convex */ #endif /* SUNOS4 */ void prusage(struct sysrusage *r0, struct sysrusage *r1, timeval_t *e, timeval_t *b) #else /* BSDTIMES */ # ifdef _SEQUENT_ void prusage(struct process_stats *r0, struct process_stats *r1, timeval_t e, timeval_t b) # else /* _SEQUENT_ */ # ifndef POSIX void prusage(struct tms *bs, struct tms *es, time_t e, time_t b) # else /* POSIX */ void prusage(struct tms *bs, struct tms *es, clock_t e, clock_t b) # endif /* POSIX */ # endif /* _SEQUENT_ */ #endif /* BSDTIMES */ { int ohaderr = haderr; #ifdef BSDTIMES time_t t = (r1->ru_utime.tv_sec - r0->ru_utime.tv_sec) * 100 + (r1->ru_utime.tv_usec - r0->ru_utime.tv_usec) / 10000 + (r1->ru_stime.tv_sec - r0->ru_stime.tv_sec) * 100 + (r1->ru_stime.tv_usec - r0->ru_stime.tv_usec) / 10000; #else # ifdef _SEQUENT_ time_t t = (r1->ps_utime.tv_sec - r0->ps_utime.tv_sec) * 100 + (r1->ps_utime.tv_usec - r0->ps_utime.tv_usec) / 10000 + (r1->ps_stime.tv_sec - r0->ps_stime.tv_sec) * 100 + (r1->ps_stime.tv_usec - r0->ps_stime.tv_usec) / 10000; # else /* _SEQUENT_ */ # ifndef POSIX time_t t = (es->tms_utime - bs->tms_utime + es->tms_stime - bs->tms_stime) * 100 / HZ; # else /* POSIX */ clock_t t = (es->tms_utime - bs->tms_utime + es->tms_stime - bs->tms_stime) * 100 / clk_tck; # endif /* POSIX */ # endif /* _SEQUENT_ */ #endif /* BSDTIMES */ const char *cp; long i; struct varent *vp = adrof(STRtime); #ifdef BSDTIMES # ifdef convex static struct system_information sysinfo; long long memtmp; /* let memory calculations exceede 2Gb */ # endif /* convex */ int ms = (int) ((e->tv_sec - b->tv_sec) * 100 + (e->tv_usec - b->tv_usec) / 10000); cp = "%Uu %Ss %E %P %X+%Dk %I+%Oio %Fpf+%Ww"; haderr = 0; #else /* !BSDTIMES */ # ifdef _SEQUENT_ int ms = (int) ((e->tv_sec - b->tv_sec) * 100 + (e->tv_usec - b->tv_usec) / 10000); cp = "%Uu %Ss %E %P %I+%Oio %Fpf+%Ww"; haderr = 0; # else /* !_SEQUENT_ */ # ifndef POSIX time_t ms = ((time_t)((e - b) / HZ) * 100) + (time_t)(((e - b) % HZ) * 100) / HZ; # else /* POSIX */ clock_t ms = ((clock_t)((e - b) / clk_tck) * 100) + (clock_t)(((e - b) % clk_tck) * 100) / clk_tck; # endif /* POSIX */ cp = "%Uu %Ss %E %P"; haderr = 0; /* * the tms stuff is not very precise, so we fudge it. - * granularity fix: can't be more than 100% + * granularity fix: can't be more than 100% * this breaks in multi-processor systems... - * maybe I should take it out and let people see more then 100% + * maybe I should take it out and let people see more then 100% * utilizations. */ # if 0 if (ms < t && ms != 0) ms = t; # endif # endif /*! _SEQUENT_ */ #endif /* !BSDTIMES */ #ifdef TDEBUG xprintf("es->tms_utime %lu bs->tms_utime %lu\n", (unsigned long)es->tms_utime, (unsigned long)bs->tms_utime); xprintf("es->tms_stime %lu bs->tms_stime %lu\n", (unsigned long)es->tms_stime, (unsigned long)bs->tms_stime); xprintf("ms %llu e %p b %p\n", (unsigned long long)ms, e, b); xprintf("t %llu\n", (unsigned long long)t); #endif /* TDEBUG */ if (vp && vp->vec && vp->vec[0] && vp->vec[1]) cp = short2str(vp->vec[1]); for (; *cp; cp++) if (*cp != '%') xputchar(*cp); else if (cp[1]) switch (*++cp) { case 'U': /* user CPU time used */ #ifdef BSDTIMES pdeltat(&r1->ru_utime, &r0->ru_utime); #else # ifdef _SEQUENT_ pdeltat(&r1->ps_utime, &r0->ps_utime); # else /* _SEQUENT_ */ # ifndef POSIX pdtimet(es->tms_utime, bs->tms_utime); # else /* POSIX */ pdtimet(es->tms_utime, bs->tms_utime); # endif /* POSIX */ # endif /* _SEQUENT_ */ #endif /* BSDTIMES */ break; case 'S': /* system CPU time used */ #ifdef BSDTIMES pdeltat(&r1->ru_stime, &r0->ru_stime); #else # ifdef _SEQUENT_ pdeltat(&r1->ps_stime, &r0->ps_stime); # else /* _SEQUENT_ */ # ifndef POSIX pdtimet(es->tms_stime, bs->tms_stime); # else /* POSIX */ pdtimet(es->tms_stime, bs->tms_stime); # endif /* POSIX */ # endif /* _SEQUENT_ */ #endif /* BSDTIMES */ break; case 'E': /* elapsed (wall-clock) time */ #ifdef BSDTIMES pcsecs((long) ms); #else /* BSDTIMES */ pcsecs(ms); #endif /* BSDTIMES */ break; case 'P': /* percent time spent running */ /* check if the process did not run */ #ifdef convex /* * scale the cpu %- ages by the number of processors * available on this machine */ if ((sysinfo.cpu_count == 0) && (getsysinfo(SYSINFO_SIZE, &sysinfo) < 0)) sysinfo.cpu_count = 1; i = (ms == 0) ? 0 : (t * 1000.0 / (ms * sysinfo.cpu_count)); #else /* convex */ i = (ms == 0) ? 0 : (long)(t * 1000.0 / ms); #endif /* convex */ xprintf("%ld.%01ld%%", i / 10, i % 10); /* nn.n% */ break; #ifdef BSDTIMES case 'W': /* number of swaps */ #ifdef _OSD_POSIX i = 0; #else i = r1->ru_nswap - r0->ru_nswap; #endif xprintf("%ld", i); break; - + #ifdef convex case 'X': /* (average) shared text size */ memtmp = (t == 0 ? 0LL : IADJUST((long long)r1->ru_ixrss - (long long)r0->ru_ixrss) / (long long)t); xprintf("%lu", (unsigned long)memtmp); break; case 'D': /* (average) unshared data size */ memtmp = (t == 0 ? 0LL : IADJUST((long long)r1->ru_idrss + (long long)r1->ru_isrss - ((long long)r0->ru_idrss + (long long)r0->ru_isrss)) / (long long)t); xprintf("%lu", (unsigned long)memtmp); break; case 'K': /* (average) total data memory used */ memtmp = (t == 0 ? 0LL : IADJUST(((long long)r1->ru_ixrss + (long long)r1->ru_isrss + (long long)r1->ru_idrss) - ((long long)r0->ru_ixrss + (long long)r0->ru_idrss + (long long)r0->ru_isrss)) / (long long)t); xprintf("%lu", (unsigned long)memtmp); break; #else /* !convex */ case 'X': /* (average) shared text size */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%lld", (long long)(t == 0 ? 0L : IADJUST(r1->ru_ixrss - r0->ru_ixrss) / t)); #endif break; case 'D': /* (average) unshared data size */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%lld", (long long)(t == 0 ? 0L : IADJUST(r1->ru_idrss + r1->ru_isrss - (r0->ru_idrss + r0->ru_isrss)) / t)); #endif break; case 'K': /* (average) total data memory used */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%lld", (long long)(t == 0 ? 0L : IADJUST((r1->ru_ixrss + r1->ru_isrss + r1->ru_idrss) - (r0->ru_ixrss + r0->ru_idrss + r0->ru_isrss)) / t)); #endif break; #endif /* convex */ case 'M': /* max. Resident Set Size */ #ifdef SUNOS4 xprintf("%ld", (long)pagetok(r1->ru_maxrss)); #else # ifdef convex xprintf("%ld", (long)(r1->ru_maxrss * 4L)); # else /* !convex */ # ifdef _OSD_POSIX xprintf("0",0); # else xprintf("%ld", (long)r1->ru_maxrss); # endif # endif /* convex */ #endif /* SUNOS4 */ break; case 'F': /* page faults */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%ld", (long)(r1->ru_majflt - r0->ru_majflt)); #endif break; case 'R': /* page reclaims */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%ld", (long)(r1->ru_minflt - r0->ru_minflt)); #endif break; case 'I': /* FS blocks in */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%ld", (long)(r1->ru_inblock - r0->ru_inblock)); #endif break; case 'O': /* FS blocks out */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%ld", (long)(r1->ru_oublock - r0->ru_oublock)); #endif break; # ifdef convex case 'C': /* CPU parallelization factor */ if (r1->ru_usamples != 0LL) { long long parr = ((r1->ru_utotal * 100LL) / r1->ru_usamples); xprintf("%d.%02d", (int)(parr/100), (int)(parr%100)); } else xprintf("?"); break; # endif /* convex */ case 'r': /* PWP: socket messages recieved */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%ld", (long)(r1->ru_msgrcv - r0->ru_msgrcv)); #endif break; case 's': /* PWP: socket messages sent */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%ld", (long)(r1->ru_msgsnd - r0->ru_msgsnd)); #endif break; case 'k': /* PWP: signals received */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%ld", (long)(r1->ru_nsignals - r0->ru_nsignals)); #endif break; case 'w': /* PWP: voluntary context switches (waits) */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%ld", (long)(r1->ru_nvcsw - r0->ru_nvcsw)); #endif break; case 'c': /* PWP: involuntary context switches */ #ifdef _OSD_POSIX xprintf("0",0); #else xprintf("%ld", (long)(r1->ru_nivcsw - r0->ru_nivcsw)); #endif break; #else /* BSDTIMES */ # ifdef _SEQUENT_ case 'W': /* number of swaps */ i = r1->ps_swap - r0->ps_swap; xprintf("%ld", (long)i); break; case 'M': xprintf("%ld", (long)r1->ps_maxrss); break; case 'F': xprintf("%ld", (long)(r1->ps_pagein - r0->ps_pagein)); break; case 'R': xprintf("%ld", (long)(r1->ps_reclaim - r0->ps_reclaim)); break; case 'I': xprintf("%ld", (long)(r1->ps_bread - r0->ps_bread)); break; case 'O': xprintf("%ld", (long)(r1->ps_bwrite - r0->ps_bwrite)); break; case 'k': xprintf("%ld", (long)(r1->ps_signal - r0->ps_signal)); break; case 'w': xprintf("%ld", (long)(r1->ps_volcsw - r0->ps_volcsw)); break; case 'c': xprintf("%ld", r1->ps_involcsw - r0->ps_involcsw); break; case 'Z': xprintf("%ld", (long)(r1->ps_zerofill - r0->ps_zerofill)); break; case 'i': xprintf("%ld", (long)(r1->ps_pffincr - r0->ps_pffincr)); break; case 'd': xprintf("%ld", (long)(r1->ps_pffdecr - r0->ps_pffdecr)); break; case 'Y': xprintf("%ld", (long)(r1->ps_syscall - r0->ps_syscall)); break; case 'l': xprintf("%ld", (long)(r1->ps_lread - r0->ps_lread)); break; case 'm': xprintf("%ld", (long)(r1->ps_lwrite - r0->ps_lwrite)); break; case 'p': xprintf("%ld", (long)(r1->ps_phread - r0->ps_phread)); break; case 'q': xprintf("%ld", (long)(r1->ps_phwrite - r0->ps_phwrite)); break; # endif /* _SEQUENT_ */ #endif /* BSDTIMES */ default: break; } xputchar('\n'); haderr = ohaderr; } #if defined(BSDTIMES) || defined(_SEQUENT_) static void pdeltat(timeval_t *t1, timeval_t *t0) { timeval_t td; tvsub(&td, t1, t0); xprintf("%lld.%03ld", (long long)td.tv_sec, (long)td.tv_usec / 1000L); } static void tvadd(timeval_t *tsum, timeval_t *t0) { tsum->tv_sec += t0->tv_sec; tsum->tv_usec += t0->tv_usec; if (tsum->tv_usec >= 1000000) tsum->tv_sec++, tsum->tv_usec -= 1000000; } void tvsub(timeval_t *tdiff, timeval_t *t1, timeval_t *t0) { tdiff->tv_sec = t1->tv_sec - t0->tv_sec; tdiff->tv_usec = t1->tv_usec - t0->tv_usec; if (tdiff->tv_usec < 0) tdiff->tv_sec--, tdiff->tv_usec += 1000000; } #else /* !BSDTIMES && !_SEQUENT_ */ static void #ifndef POSIX pdtimet(time_t eval, time_t bval) #else /* POSIX */ pdtimet(clock_t eval, clock_t bval) #endif /* POSIX */ { #ifndef POSIX time_t val; #else /* POSIX */ clock_t val; #endif /* POSIX */ #ifndef POSIX val = (eval - bval) * 100 / HZ; #else /* POSIX */ val = (eval - bval) * 100 / clk_tck; #endif /* POSIX */ xprintf("%lld.%02ld", (long long)(val / 100), (long long)(val - (val / 100 * 100))); } #endif /* BSDTIMES || _SEQUENT_ */ diff --git a/contrib/tcsh/sh.types.h b/contrib/tcsh/sh.types.h index 13efcff3d32b..a7ceda7ac38f 100644 --- a/contrib/tcsh/sh.types.h +++ b/contrib/tcsh/sh.types.h @@ -1,396 +1,396 @@ /* sh.types.h: Do the necessary typedefs for each system. * Up till now I avoided making this into a separate file * But I just wanted to eliminate the whole mess from sh.h * In reality this should not be here! It is OS and MACHINE * dependent, even between different revisions of OS's... * Ideally there should be a way in c, to find out if something * was typedef'ed, but unfortunately we rely in cpp kludges. - * Someday, this file will be removed... - * + * Someday, this file will be removed... + * * christos */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _h_sh_types #define _h_sh_types /*** *** LynxOS 2.1 ***/ #ifdef Lynx # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /*** - *** MachTen + *** MachTen ***/ #ifdef __MACHTEN__ # ifndef _PID_T # define _PID_T # endif #endif /*** *** Suns running sunos3.x - sunos4.1.x ***/ #if (defined(sun) || defined(__sun__)) && SYSVREL == 0 # ifndef _PTR_T -# define _PTR_T +# define _PTR_T # ifdef __GNUC__ typedef void * ptr_t; # else typedef char * ptr_t; # endif /* __GNUC__ */ # endif /* _PTR_T */ # ifndef __sys_stdtypes_h # define __sys_stdtypes_h # ifndef __lucid typedef int pid_t; typedef unsigned int speed_t; # endif # endif /* __sys_stdtypes.h */ # ifndef _PID_T # define _PID_T # endif /* _PID_T */ # ifndef _SPEED_T # define _SPEED_T # endif /* _SPEED_T */ #endif /* (sun || __sun__) && SYSVREL == 0 */ /*** *** Hp's running hpux 7.0 or 8.0 ***/ #ifdef __hpux # ifndef _PTR_T -# define _PTR_T +# define _PTR_T typedef void * ptr_t; # endif /* _PTR_T */ # ifndef _PID_T # define _PID_T typedef long pid_t; # endif /* _PID_T */ # ifndef _SPEED_T /* I thought POSIX was supposed to protect all typedefs! */ # define _SPEED_T # endif /* _SPEED_T */ # if HPUXVERSION < 1100 /* XXX: Not true for 11.0 */ extern uid_t getuid(), geteuid(); extern gid_t getgid(), getegid(); extern pid_t getpid(); extern pid_t fork(); extern void perror(); extern void _exit(); extern void abort(); extern void qsort(); extern void free(); extern unsigned int alarm(); extern unsigned int sleep(); # endif /* HPUXVERSION < 1100 */ # if HPUXVERSION < 800 /* XXX: Not true for 8.0 */ extern char *sbrk(); # endif /* HPUXVERSION < 800 */ #endif /* __hpux */ #if (defined(_MINIX) && !defined(_MINIX_VMD)) || defined(__EMX__) typedef char * caddr_t; #endif /* (_MINIX && !_MINIX_VMD) || __EMX__ */ /*** *** hp9000s500 running hpux-5.2 ***/ #ifdef hp9000s500 # ifndef _PTR_T # define _PTR_T typedef char * ptr_t; # endif /* _PTR_T */ #endif /* hp9000s500 */ /*** *** Data General AViiON 88000 or Pentium, running dgux 5.4R3 or R4.11 ***/ #ifdef DGUX # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /* DGUX */ /*** *** BSD RENO advertises itself as POSIX, but - *** it is missing speed_t + *** it is missing speed_t ***/ #ifdef RENO # ifndef _SPEED_T # define _SPEED_T - typedef unsigned int speed_t; + typedef unsigned int speed_t; # endif /* _SPEED_T */ #endif /* RENO */ /*** *** NeXT OS 3.x - ***/ + ***/ #ifdef NeXT # ifndef _SPEED_T # define _SPEED_T - typedef unsigned int speed_t; + typedef unsigned int speed_t; # endif /* _SPEED_T */ #endif /* NeXT */ /*** *** Utah's HPBSD *** some posix & 4.4 BSD changes (pid_t is a short) ***/ #ifdef HPBSD # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /* HPBSD */ /*** *** Pyramid, BSD universe *** In addition to the size_t ***/ #ifdef pyr # ifndef _PID_T # define _PID_T typedef short pid_t; # endif /* _PID_T */ #endif /* pyr */ /*** *** rs6000, ibm370, ps2, rt: running flavors of aix. ***/ #ifdef IBMAIX # ifndef aiws # ifndef _PID_T # define _PID_T # endif /* _PID_T */ # endif /* !aiws */ # ifdef _IBMR2 -# ifndef _SPEED_T +# ifndef _SPEED_T # define _SPEED_T # endif /* _SPEED_T */ # endif /* _IBMR2 */ #endif /* IBMAIX */ /*** *** Ultrix... ***/ #if defined(ultrix) || defined(__ultrix) # ifndef _PID_T # define _PID_T # endif /* _PID_T */ # ifndef _PTR_T # define _PTR_T typedef void * ptr_t; # endif /* _PTR_T */ #endif /* ultrix || __ultrix */ /*** *** Silicon graphics IRIS4D running IRIX3_3 ***/ #if defined(IRIS4D) && defined(IRIX3_3) # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /* IRIS4D && IRIX3_3 */ /*** *** Apple AUX. ***/ #ifdef OREO # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /* OREO */ /*** - *** Concurrent (Masscomp) running RTU 4.1A & RTU 5.0. + *** Concurrent (Masscomp) running RTU 4.1A & RTU 5.0. **** [RTU 6.0 from mike connor] *** Added, DAS DEC-90. ***/ #ifdef masscomp # ifdef RTU6 # ifndef _PID_T # define _PID_T # endif /* _PID_T */ # ifndef _SPEED_T # define _SPEED_T # endif /* _SPEED_T */ #endif /* RTU6 */ #endif /* masscomp */ -/* +/* * Motorola MPC running R32V2 (sysV88) */ #ifdef sysV88 # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /* sysV88 */ - -/* + +/* * Amdahl running UTS (Sys V3) */ #ifdef uts # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /* uts */ -/* +/* * Tektronix XD88/10 running UTekV (Sys V3) */ #ifdef UTekV # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /* UTekV*/ /* * BBN Butterfly gp1000 */ #ifdef butterfly # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /* butterfly */ /* * Alliant FX-2800/FX-80 */ #ifdef alliant # ifndef _PID_T # define _PID_T # endif /* _PID_T */ # ifdef mc68000 typedef int pid_t; /* FX-80 */ # else typedef short pid_t; /* FX-2800 */ -# endif +# endif #endif /* alliant */ /* * DNIX */ #ifdef DNIX # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /* DNIX */ /* * Apollo running Domain/OS SR10.3 or greater */ #ifdef apollo # ifndef _PID_T # define _PID_T typedef int pid_t; /* Older versions might not like that */ # endif /* _PID_T */ #endif /* apollo */ /*** *** a pdp/11, running 2BSD ***/ #ifdef pdp11 # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /* pdp11 */ /*** *** a Harris, running CX/UX ***/ #ifdef _CX_UX # ifndef _PID_T # define _PID_T # endif /* _PID_T */ #endif /* _CX_UX */ /*** *** Catch all for non POSIX and/or non ANSI systems. *** Systems up to spec *should* define these automatically *** I am open to suggestions on how to do this correctly! ***/ #ifndef POSIX # ifndef _PID_T # define _PID_T typedef int pid_t; # endif /* _PID_T */ # ifndef _SPEED_T # define _SPEED_T typedef unsigned int speed_t; # endif /* _SPEED_T */ # ifndef _PTR_T -# define _PTR_T +# define _PTR_T typedef char * ptr_t; #endif /* _PTR_T */ # ifndef _IOCTL_T # define _IOCTL_T typedef char * ioctl_t; /* Third arg of ioctl */ # endif /* _IOCTL_T */ #endif /* ! POSIX */ /*** *** This is our own junk types. ***/ #ifndef _PTR_T -# define _PTR_T +# define _PTR_T typedef void * ptr_t; #endif /* _PTR_T */ #ifndef _IOCTL_T # define _IOCTL_T typedef void * ioctl_t; /* Third arg of ioctl */ #endif /* _IOCTL_T */ #endif /* _h_sh_types */ diff --git a/contrib/tcsh/tc.alloc.c b/contrib/tcsh/tc.alloc.c index cbe218f4c086..6464279fc3ee 100644 --- a/contrib/tcsh/tc.alloc.c +++ b/contrib/tcsh/tc.alloc.c @@ -1,667 +1,667 @@ /* * tc.alloc.c (Caltech) 2/21/82 * Chris Kingsley, kingsley@cit-20. * * This is a very fast storage allocator. It allocates blocks of a small * number of different sizes, and keeps free lists of each size. Blocks that * don't exactly fit are passed up to the next larger size. In this * implementation, the available sizes are 2^n-4 (or 2^n-12) bytes long. * This is designed for use in a program that uses vast quantities of memory, * but bombs when it runs out. */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #ifdef HAVE_MALLINFO #include #endif #if defined(HAVE_SBRK) && !defined(__APPLE__) #define USE_SBRK #endif #define RCHECK #define DEBUG static char *memtop = NULL; /* PWP: top of current memory */ static char *membot = NULL; /* PWP: bottom of allocatable memory */ int dont_free = 0; #ifdef WINNT_NATIVE # define malloc fmalloc # define free ffree # define calloc fcalloc # define realloc frealloc #endif /* WINNT_NATIVE */ #if !defined(DEBUG) || defined(SYSMALLOC) static void out_of_memory (void) { static const char msg[] = "Out of memory\n"; TCSH_IGNORE(write(didfds ? 2 : SHDIAG, msg, strlen(msg))); _exit(1); } #endif #ifndef SYSMALLOC #ifdef SX extern void* sbrk(); #endif /* - * Lots of os routines are busted and try to free invalid pointers. - * Although our free routine is smart enough and it will pick bad + * Lots of os routines are busted and try to free invalid pointers. + * Although our free routine is smart enough and it will pick bad * pointers most of the time, in cases where we know we are going to get * a bad pointer, we'd rather leak. */ #ifndef NULL #define NULL 0 #endif typedef unsigned char U_char; /* we don't really have signed chars */ typedef unsigned int U_int; typedef unsigned short U_short; typedef unsigned long U_long; /* * The overhead on a block is at least 4 bytes. When free, this space * contains a pointer to the next free block, and the bottom two bits must * be zero. When in use, the first byte is set to MAGIC, and the second * byte is the size index. The remaining bytes are for alignment. * If range checking is enabled and the size of the block fits * in two bytes, then the top two bytes hold the size of the requested block * plus the range checking words, and the header word MINUS ONE. */ #define MEMALIGN(a) (((a) + ROUNDUP) & ~ROUNDUP) union overhead { union overhead *ov_next; /* when free */ struct { U_char ovu_magic; /* magic number */ U_char ovu_index; /* bucket # */ #ifdef RCHECK U_short ovu_size; /* actual block size */ U_int ovu_rmagic; /* range magic number */ #endif } ovu; #define ov_magic ovu.ovu_magic #define ov_index ovu.ovu_index #define ov_size ovu.ovu_size #define ov_rmagic ovu.ovu_rmagic }; #define MAGIC 0xfd /* magic # on accounting info */ #define RMAGIC 0x55555555 /* magic # on range info */ #ifdef RCHECK #define RSLOP sizeof (U_int) #else #define RSLOP 0 #endif #ifdef _LP64 #define ROUNDUP 15 #else #define ROUNDUP 7 #endif /* * nextf[i] is the pointer to the next free block of size 2^(i+3). The * smallest allocatable block is 8 bytes. The overhead information * precedes the data area returned to the user. */ #define NBUCKETS ((sizeof(long) << 3) - 3) static union overhead *nextf[NBUCKETS] IZERO_STRUCT; /* * nmalloc[i] is the difference between the number of mallocs and frees * for a given block size. */ static U_int nmalloc[NBUCKETS] IZERO_STRUCT; #ifndef lint static int findbucket (union overhead *, int); static void morecore (int); #endif #ifdef DEBUG # define CHECK(a, str, p) \ if (a) { \ xprintf(str, p); \ xprintf(" (memtop = %p membot = %p)\n", memtop, membot); \ abort(); \ } #else # define CHECK(a, str, p) \ if (a) { \ xprintf(str, p); \ xprintf(" (memtop = %p membot = %p)\n", memtop, membot); \ return; \ } #endif memalign_t malloc(size_t nbytes) { #ifndef lint union overhead *p; int bucket = 0; unsigned shiftr; /* * Convert amount of memory requested into closest block size stored in * hash buckets which satisfies request. Account for space used per block * for accounting. */ #ifdef SUNOS4 /* * SunOS localtime() overwrites the 9th byte on an 8 byte malloc().... * so we get one more... - * From Michael Schroeder: This is not true. It depends on the + * From Michael Schroeder: This is not true. It depends on the * timezone string. In Europe it can overwrite the 13th byte on a * 12 byte malloc. * So we punt and we always allocate an extra byte. */ nbytes++; #endif nbytes = MEMALIGN(MEMALIGN(sizeof(union overhead)) + nbytes + RSLOP); shiftr = (nbytes - 1) >> 2; /* apart from this loop, this is O(1) */ while ((shiftr >>= 1) != 0) bucket++; /* * If nothing in hash bucket right now, request more memory from the * system. */ if (nextf[bucket] == NULL) morecore(bucket); if ((p = nextf[bucket]) == NULL) { child++; #ifndef DEBUG out_of_memory(); #else showall(NULL, NULL); xprintf(CGETS(19, 1, "nbytes=%zu: Out of memory\n"), nbytes); abort(); #endif /* fool lint */ return ((memalign_t) 0); } /* remove from linked list */ nextf[bucket] = nextf[bucket]->ov_next; p->ov_magic = MAGIC; p->ov_index = bucket; nmalloc[bucket]++; #ifdef RCHECK /* * Record allocated size of block and bound space with magic numbers. */ p->ov_size = (p->ov_index <= 13) ? (U_short)nbytes - 1 : 0; p->ov_rmagic = RMAGIC; *((U_int *) (((caddr_t) p) + nbytes - RSLOP)) = RMAGIC; #endif return ((memalign_t) (((caddr_t) p) + MEMALIGN(sizeof(union overhead)))); #else if (nbytes) return ((memalign_t) 0); else return ((memalign_t) 0); #endif /* !lint */ } #ifndef lint /* * Allocate more memory to the indicated bucket. */ static void morecore(int bucket) { union overhead *op; int rnu; /* 2^rnu bytes will be requested */ int nblks; /* become nblks blocks of the desired size */ int siz; if (nextf[bucket]) return; /* * Insure memory is allocated on a page boundary. Should make getpageize * call? */ op = (union overhead *) sbrk(0); memtop = (char *) op; if (membot == NULL) membot = memtop; if ((long) op & 0x3ff) { memtop = sbrk((int) (1024 - ((long) op & 0x3ff))); memtop += (long) (1024 - ((long) op & 0x3ff)); } /* take 2k unless the block is bigger than that */ rnu = (bucket <= 8) ? 11 : bucket + 3; nblks = 1 << (rnu - (bucket + 3)); /* how many blocks to get */ memtop = sbrk(1 << rnu); /* PWP */ op = (union overhead *) memtop; /* no more room! */ if ((long) op == -1) return; memtop += (long) (1 << rnu); /* * Round up to minimum allocation size boundary and deduct from block count * to reflect. */ if (((U_long) op) & ROUNDUP) { op = (union overhead *) (((U_long) op + (ROUNDUP + 1)) & ~ROUNDUP); nblks--; } /* * Add new memory allocated to that on free list for this hash bucket. */ nextf[bucket] = op; siz = 1 << (bucket + 3); while (--nblks > 0) { op->ov_next = (union overhead *) (((caddr_t) op) + siz); op = (union overhead *) (((caddr_t) op) + siz); } op->ov_next = NULL; } #endif void free(ptr_t cp) { #ifndef lint int size; union overhead *op; /* * the don't free flag is there so that we avoid os bugs in routines * that free invalid pointers! */ if (cp == NULL || dont_free) return; CHECK(!memtop || !membot, CGETS(19, 2, "free(%p) called before any allocations."), cp); CHECK(cp > (ptr_t) memtop, CGETS(19, 3, "free(%p) above top of memory."), cp); CHECK(cp < (ptr_t) membot, CGETS(19, 4, "free(%p) below bottom of memory."), cp); op = (union overhead *) (((caddr_t) cp) - MEMALIGN(sizeof(union overhead))); CHECK(op->ov_magic != MAGIC, CGETS(19, 5, "free(%p) bad block."), cp); #ifdef RCHECK if (op->ov_index <= 13) CHECK(*(U_int *) ((caddr_t) op + op->ov_size + 1 - RSLOP) != RMAGIC, CGETS(19, 6, "free(%p) bad range check."), cp); #endif CHECK(op->ov_index >= NBUCKETS, CGETS(19, 7, "free(%p) bad block index."), cp); size = op->ov_index; op->ov_next = nextf[size]; nextf[size] = op; nmalloc[size]--; #else if (cp == NULL) return; #endif } memalign_t calloc(size_t i, size_t j) { #ifndef lint char *cp; volatile size_t k; i *= j; cp = xmalloc(i); /* Stop gcc 5.x from optimizing malloc+memset = calloc */ k = i; memset(cp, 0, k); return ((memalign_t) cp); #else if (i && j) return ((memalign_t) 0); else return ((memalign_t) 0); #endif } /* * When a program attempts "storage compaction" as mentioned in the * old malloc man page, it realloc's an already freed block. Usually * this is the last block it freed; occasionally it might be farther * back. We have to search all the free lists for the block in order * to determine its bucket: 1st we make one pass thru the lists * checking only the first block in each; if that fails we search * ``realloc_srchlen'' blocks in each list for a match (the variable * is extern so the caller can modify it). If that fails we just copy * however many bytes was given to realloc() and hope it's not huge. */ #ifndef lint /* 4 should be plenty, -1 =>'s whole list */ -static int realloc_srchlen = 4; +static int realloc_srchlen = 4; #endif /* lint */ memalign_t realloc(ptr_t cp, size_t nbytes) { #ifndef lint U_int onb; union overhead *op; ptr_t res; int i; int was_alloced = 0; if (cp == NULL) return (malloc(nbytes)); op = (union overhead *) (((caddr_t) cp) - MEMALIGN(sizeof(union overhead))); if (op->ov_magic == MAGIC) { was_alloced++; i = op->ov_index; } else /* * Already free, doing "compaction". - * + * * Search for the old block of memory on the free list. First, check the * most common case (last element free'd), then (this failing) the last * ``realloc_srchlen'' items free'd. If all lookups fail, then assume * the size of the memory block being realloc'd is the smallest * possible. */ if ((i = findbucket(op, 1)) < 0 && (i = findbucket(op, realloc_srchlen)) < 0) i = 0; onb = MEMALIGN(nbytes + MEMALIGN(sizeof(union overhead)) + RSLOP); /* avoid the copy if same size block */ - if (was_alloced && (onb <= (U_int) (1 << (i + 3))) && + if (was_alloced && (onb <= (U_int) (1 << (i + 3))) && (onb > (U_int) (1 << (i + 2)))) { #ifdef RCHECK /* JMR: formerly this wasn't updated ! */ nbytes = MEMALIGN(MEMALIGN(sizeof(union overhead))+nbytes+RSLOP); *((U_int *) (((caddr_t) op) + nbytes - RSLOP)) = RMAGIC; op->ov_rmagic = RMAGIC; op->ov_size = (op->ov_index <= 13) ? (U_short)nbytes - 1 : 0; #endif return ((memalign_t) cp); } if ((res = malloc(nbytes)) == NULL) return ((memalign_t) NULL); if (cp != res) { /* common optimization */ - /* - * christos: this used to copy nbytes! It should copy the + /* + * christos: this used to copy nbytes! It should copy the * smaller of the old and new size */ onb = (1 << (i + 3)) - MEMALIGN(sizeof(union overhead)) - RSLOP; (void) memmove(res, cp, onb < nbytes ? onb : nbytes); } if (was_alloced) free(cp); return ((memalign_t) res); #else if (cp && nbytes) return ((memalign_t) 0); else return ((memalign_t) 0); #endif /* !lint */ } /* * On linux, _nss_nis_setnetgrent() calls this function to determine * the usable size of the pointer passed, but this is not a portable * API, so we cannot use our malloc replacement without providing one. * Thanks a lot glibc! */ #ifdef __linux__ #define M_U_S_CONST #else #define M_U_S_CONST #endif size_t malloc_usable_size(M_U_S_CONST void *); size_t malloc_usable_size(M_U_S_CONST void *ptr) { const union overhead *op = (const union overhead *) (((const char *) ptr) - MEMALIGN(sizeof(*op))); if (op->ov_magic == MAGIC) return 1 << (op->ov_index + 3); else return 0; } #ifndef lint /* * Search ``srchlen'' elements of each free list for a block whose * header starts at ``freep''. If srchlen is -1 search the whole list. * Return bucket number, or -1 if not found. */ static int findbucket(union overhead *freep, int srchlen) { union overhead *p; size_t i; int j; for (i = 0; i < NBUCKETS; i++) { j = 0; for (p = nextf[i]; p && j != srchlen; p = p->ov_next) { if (p == freep) return (i); j++; } } return (-1); } #endif #else /* SYSMALLOC */ /** ** ``Protected versions'' of malloc, realloc, calloc, and free ** ** On many systems: ** ** 1. malloc(0) is bad ** 2. free(0) is bad ** 3. realloc(0, n) is bad ** 4. realloc(n, 0) is bad ** ** Also we call our error routine if we run out of memory. **/ memalign_t smalloc(size_t n) { ptr_t ptr; n = n ? n : 1; #ifdef USE_SBRK if (membot == NULL) membot = sbrk(0); #endif /* USE_SBRK */ if ((ptr = malloc(n)) == NULL) out_of_memory(); #ifndef USE_SBRK if (memtop < ((char *) ptr) + n) memtop = ((char *) ptr) + n; if (membot == NULL) membot = ptr; #endif /* !USE_SBRK */ return ((memalign_t) ptr); } memalign_t srealloc(ptr_t p, size_t n) { ptr_t ptr; n = n ? n : 1; #ifdef USE_SBRK if (membot == NULL) membot = sbrk(0); #endif /* USE_SBRK */ if ((ptr = (p ? realloc(p, n) : malloc(n))) == NULL) out_of_memory(); #ifndef USE_SBRK if (memtop < ((char *) ptr) + n) memtop = ((char *) ptr) + n; if (membot == NULL) membot = ptr; #endif /* !USE_SBRK */ return ((memalign_t) ptr); } memalign_t scalloc(size_t s, size_t n) { ptr_t ptr; n *= s; n = n ? n : 1; #ifdef USE_SBRK if (membot == NULL) membot = sbrk(0); #endif /* USE_SBRK */ if ((ptr = malloc(n)) == NULL) out_of_memory(); memset (ptr, 0, n); #ifndef USE_SBRK if (memtop < ((char *) ptr) + n) memtop = ((char *) ptr) + n; if (membot == NULL) membot = ptr; #endif /* !USE_SBRK */ return ((memalign_t) ptr); } void sfree(ptr_t p) { if (p && !dont_free) free(p); } #endif /* SYSMALLOC */ /* * mstats - print out statistics about malloc * * Prints two lines of numbers, one showing the length of the free list * for each size category, the second showing the number of mallocs - * frees for each size category. */ /*ARGSUSED*/ void showall(Char **v, struct command *c) { #ifndef SYSMALLOC size_t i, j; union overhead *p; int totfree = 0, totused = 0; xprintf(CGETS(19, 8, "%s current memory allocation:\nfree:\t"), progname); for (i = 0; i < NBUCKETS; i++) { for (j = 0, p = nextf[i]; p; p = p->ov_next, j++) continue; xprintf(" %4zd", j); totfree += j * (1 << (i + 3)); } xprintf("\n%s:\t", CGETS(19, 9, "used")); for (i = 0; i < NBUCKETS; i++) { xprintf(" %4d", nmalloc[i]); totused += nmalloc[i] * (1 << (i + 3)); } xprintf(CGETS(19, 10, "\n\tTotal in use: %d, total free: %d\n"), totused, totfree); xprintf(CGETS(19, 11, "\tAllocated memory from 0x%lx to 0x%lx. Real top at 0x%lx\n"), (unsigned long) membot, (unsigned long) memtop, (unsigned long) sbrk(0)); #else /* SYSMALLOC */ #ifndef HAVE_MALLINFO #ifdef USE_SBRK memtop = sbrk(0); #endif /* USE_SBRK */ xprintf(CGETS(19, 12, "Allocated memory from 0x%lx to 0x%lx (%ld).\n"), - (unsigned long) membot, (unsigned long) memtop, + (unsigned long) membot, (unsigned long) memtop, (unsigned long) (memtop - membot)); #else /* HAVE_MALLINFO */ struct mallinfo mi; mi = mallinfo(); xprintf(CGETS(19, 13, "%s current memory allocation:\n"), progname); xprintf(CGETS(19, 14, "Total space allocated from system: %d\n"), mi.arena); xprintf(CGETS(19, 15, "Number of non-inuse chunks: %d\n"), mi.ordblks); xprintf(CGETS(19, 16, "Number of mmapped regions: %d\n"), mi.hblks); xprintf(CGETS(19, 17, "Total space in mmapped regions: %d\n"), mi.hblkhd); xprintf(CGETS(19, 18, "Total allocated space: %d\n"), mi.uordblks); xprintf(CGETS(19, 19, "Total non-inuse space: %d\n"), mi.fordblks); xprintf(CGETS(19, 20, "Top-most, releasable space: %d\n"), mi.keepcost); #endif /* HAVE_MALLINFO */ #endif /* SYSMALLOC */ USE(c); USE(v); } #ifndef SYSMALLOC /* jemalloc defines these */ void _malloc_prefork(void); void _malloc_postfork(void); void _malloc_postfork_child(void); void _malloc_prefork(void) {} void _malloc_postfork(void) {} void _malloc_postfork_child(void) {} #endif diff --git a/contrib/tcsh/tc.bind.c b/contrib/tcsh/tc.bind.c index 5361997dca6e..33312f478522 100644 --- a/contrib/tcsh/tc.bind.c +++ b/contrib/tcsh/tc.bind.c @@ -1,538 +1,538 @@ /* * tc.bind.c: Key binding functions */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include "ed.defns.h" static void printkey (const KEYCMD *, CStr *); static KEYCMD parsecmd (Char *); static void bad_spec (const Char *); static CStr *parsestring (const Char *, CStr *); static CStr *parsebind (const Char *, CStr *); static void print_all_keys (void); static void printkeys (KEYCMD *, int, int); static void bindkey_usage (void); static void list_functions (void); extern int MapsAreInited; /*ARGSUSED*/ void dobindkey(Char **v, struct command *c) { KEYCMD *map; int ntype, no, removeb, key, bindk; Char *par; Char p; KEYCMD cmd; CStr in; CStr out; uChar ch; USE(c); if (!MapsAreInited) ed_InitMaps(); map = CcKeyMap; ntype = XK_CMD; key = removeb = bindk = 0; - for (no = 1, par = v[no]; + for (no = 1, par = v[no]; par != NULL && (*par++ & CHAR) == '-'; no++, par = v[no]) { if ((p = (*par & CHAR)) == '-') { no++; break; } - else + else switch (p) { case 'b': bindk = 1; break; case 'k': key = 1; break; case 'a': map = CcAltMap; break; case 's': ntype = XK_STR; break; case 'c': ntype = XK_EXE; break; case 'r': removeb = 1; break; case 'v': ed_InitVIMaps(); return; case 'e': ed_InitEmacsMaps(); return; case 'd': #ifdef VIDEFAULT ed_InitVIMaps(); #else /* EMACSDEFAULT */ ed_InitEmacsMaps(); #endif /* VIDEFAULT */ return; case 'l': list_functions(); return; default: bindkey_usage(); return; } } if (!v[no]) { print_all_keys(); return; } if (key) { if (!IsArrowKey(v[no])) xprintf(CGETS(20, 1, "Invalid key name `%S'\n"), v[no]); in.buf = Strsave(v[no++]); in.len = Strlen(in.buf); } else { if (bindk) { if (parsebind(v[no++], &in) == NULL) return; } else { if (parsestring(v[no++], &in) == NULL) return; } } cleanup_push(in.buf, xfree); #ifndef WINNT_NATIVE if (in.buf[0] > 0xFF) { bad_spec(in.buf); cleanup_until(in.buf); return; } #endif ch = (uChar) in.buf[0]; if (removeb) { if (key) (void) ClearArrowKeys(&in); else if (in.len > 1) { (void) DeleteXkey(&in); } else if (map[ch] == F_XKEY) { (void) DeleteXkey(&in); map[ch] = F_UNASSIGNED; } else { map[ch] = F_UNASSIGNED; } cleanup_until(in.buf); return; } if (!v[no]) { if (key) PrintArrowKeys(&in); else printkey(map, &in); cleanup_until(in.buf); return; } if (v[no + 1]) { bindkey_usage(); cleanup_until(in.buf); return; } switch (ntype) { case XK_STR: case XK_EXE: if (parsestring(v[no], &out) == NULL) { cleanup_until(in.buf); return; } cleanup_push(out.buf, xfree); if (key) { if (SetArrowKeys(&in, XmapStr(&out), ntype) == -1) xprintf(CGETS(20, 2, "Bad key name: %S\n"), in.buf); else cleanup_ignore(out.buf); } else AddXkey(&in, XmapStr(&out), ntype); map[ch] = F_XKEY; break; case XK_CMD: if ((cmd = parsecmd(v[no])) == 0) { cleanup_until(in.buf); return; } if (key) (void) SetArrowKeys(&in, XmapCmd((int) cmd), ntype); else { if (in.len > 1) { AddXkey(&in, XmapCmd((int) cmd), ntype); map[ch] = F_XKEY; } else { ClearXkey(map, &in); map[ch] = cmd; } } break; default: abort(); break; } cleanup_until(in.buf); if (key) BindArrowKeys(); } static void printkey(const KEYCMD *map, CStr *in) { struct KeyFuncs *fp; if (in->len < 2) { unsigned char *unparsed; unparsed = unparsestring(in, STRQQ); cleanup_push(unparsed, xfree); for (fp = FuncNames; fp->name; fp++) { if (fp->func == map[(uChar) *(in->buf)]) { xprintf("%s\t->\t%s\n", unparsed, fp->name); } } cleanup_until(unparsed); } else PrintXkey(in); } static KEYCMD parsecmd(Char *str) { struct KeyFuncs *fp; for (fp = FuncNames; fp->name; fp++) { if (strcmp(short2str(str), fp->name) == 0) { return (KEYCMD) fp->func; } } xprintf(CGETS(20, 3, "Bad command name: %S\n"), str); return 0; } static void bad_spec(const Char *str) { xprintf(CGETS(20, 4, "Bad key spec %S\n"), str); } static CStr * parsebind(const Char *s, CStr *str) { struct Strbuf b = Strbuf_INIT; cleanup_push(&b, Strbuf_cleanup); if (Iscntrl(*s)) { Strbuf_append1(&b, *s); goto end; } switch (*s) { case '^': s++; #ifdef IS_ASCII Strbuf_append1(&b, (*s == '?') ? '\177' : ((*s & CHAR) & 0237)); #else Strbuf_append1(&b, (*s == '?') ? CTL_ESC('\177') : _toebcdic[_toascii[*s & CHAR] & 0237]); #endif break; case 'F': case 'M': case 'X': case 'C': #ifdef WINNT_NATIVE case 'N': #endif /* WINNT_NATIVE */ if (s[1] != '-' || s[2] == '\0') goto bad_spec; s += 2; switch (s[-2]) { case 'F': case 'f': /* Turn into ^[str */ Strbuf_append1(&b, CTL_ESC('\033')); Strbuf_append(&b, s); break; case 'C': case 'c': /* Turn into ^c */ #ifdef IS_ASCII Strbuf_append1(&b, (*s == '?') ? '\177' : ((*s & CHAR) & 0237)); #else Strbuf_append1(&b, (*s == '?') ? CTL_ESC('\177') : _toebcdic[_toascii[*s & CHAR] & 0237]); #endif break; case 'X' : case 'x': /* Turn into ^Xc */ #ifdef IS_ASCII Strbuf_append1(&b, 'X' & 0237); #else Strbuf_append1(&b, _toebcdic[_toascii['X'] & 0237]); #endif Strbuf_append1(&b, *s); break; case 'M' : case 'm': /* Turn into 0x80|c */ if (!NoNLSRebind) { Strbuf_append1(&b, CTL_ESC('\033')); Strbuf_append1(&b, *s); } else { #ifdef IS_ASCII Strbuf_append1(&b, *s | 0x80); #else Strbuf_append1(&b, _toebcdic[_toascii[*s] | 0x80]); #endif } break; #ifdef WINNT_NATIVE case 'N' : case 'n': /* NT */ { Char bnt; bnt = nt_translate_bindkey(s); if (bnt != 0) Strbuf_append1(&b, bnt); else bad_spec(s); } break; #endif /* WINNT_NATIVE */ default: abort(); } break; default: goto bad_spec; } end: cleanup_ignore(&b); cleanup_until(&b); Strbuf_terminate(&b); str->buf = xrealloc(b.s, (b.len + 1) * sizeof (*str->buf)); str->len = b.len; return str; bad_spec: bad_spec(s); cleanup_until(&b); return NULL; } static CStr * parsestring(const Char *str, CStr *buf) { struct Strbuf b = Strbuf_INIT; const Char *p; eChar es; if (*str == 0) { xprintf("%s", CGETS(20, 5, "Null string specification\n")); return NULL; } cleanup_push(&b, Strbuf_cleanup); for (p = str; *p != 0; p++) { if ((*p & CHAR) == '\\' || (*p & CHAR) == '^') { if ((es = parseescape(&p)) == CHAR_ERR) { cleanup_until(&b); return 0; } else Strbuf_append1(&b, es); } else Strbuf_append1(&b, *p & CHAR); } cleanup_ignore(&b); cleanup_until(&b); Strbuf_terminate(&b); buf->buf = xrealloc(b.s, (b.len + 1) * sizeof (*buf->buf)); buf->len = b.len; return buf; } static void print_all_keys(void) { int prev, i; CStr nilstr; nilstr.buf = NULL; nilstr.len = 0; xprintf("%s", CGETS(20, 6, "Standard key bindings\n")); prev = 0; for (i = 0; i < 256; i++) { if (CcKeyMap[prev] == CcKeyMap[i]) continue; printkeys(CcKeyMap, prev, i - 1); prev = i; } printkeys(CcKeyMap, prev, i - 1); xprintf("%s", CGETS(20, 7, "Alternative key bindings\n")); prev = 0; for (i = 0; i < 256; i++) { if (CcAltMap[prev] == CcAltMap[i]) continue; printkeys(CcAltMap, prev, i - 1); prev = i; } printkeys(CcAltMap, prev, i - 1); xprintf("%s", CGETS(20, 8, "Multi-character bindings\n")); PrintXkey(NULL); /* print all Xkey bindings */ xprintf("%s", CGETS(20, 9, "Arrow key bindings\n")); PrintArrowKeys(&nilstr); } static void printkeys(KEYCMD *map, int first, int last) { struct KeyFuncs *fp; Char firstbuf[2], lastbuf[2]; CStr fb, lb; unsigned char *unparsed; fb.buf = firstbuf; lb.buf = lastbuf; firstbuf[0] = (Char) first; firstbuf[1] = 0; lastbuf[0] = (Char) last; lastbuf[1] = 0; fb.len = 1; lb.len = 1; unparsed = unparsestring(&fb, STRQQ); cleanup_push(unparsed, xfree); if (map[first] == F_UNASSIGNED) { if (first == last) xprintf(CGETS(20, 10, "%-15s-> is undefined\n"), unparsed); cleanup_until(unparsed); return; } for (fp = FuncNames; fp->name; fp++) { if (fp->func == map[first]) { if (first == last) xprintf("%-15s-> %s\n", unparsed, fp->name); else { unsigned char *p; p = unparsestring(&lb, STRQQ); cleanup_push(p, xfree); xprintf("%-4s to %-7s-> %s\n", unparsed, p, fp->name); } cleanup_until(unparsed); return; } } xprintf(CGETS(20, 11, "BUG!!! %s isn't bound to anything.\n"), unparsed); if (map == CcKeyMap) xprintf("CcKeyMap[%d] == %d\n", first, CcKeyMap[first]); else xprintf("CcAltMap[%d] == %d\n", first, CcAltMap[first]); cleanup_until(unparsed); } static void bindkey_usage(void) { xprintf("%s", CGETS(20, 12, "Usage: bindkey [options] [--] [KEY [COMMAND]]\n")); xprintf("%s", CGETS(20, 13, " -a list or bind KEY in alternative key map\n")); xprintf("%s", CGETS(20, 14, " -b interpret KEY as a C-, M-, F- or X- key name\n")); xprintf("%s", CGETS(20, 15, " -s interpret COMMAND as a literal string to be output\n")); xprintf("%s", CGETS(20, 16, " -c interpret COMMAND as a builtin or external command\n")); xprintf("%s", CGETS(20, 17, " -v bind all keys to vi bindings\n")); xprintf("%s", CGETS(20, 18, " -e bind all keys to emacs bindings\n")); xprintf(CGETS(20, 19, " -d bind all keys to default editor's bindings (%s)\n"), #ifdef VIDEFAULT "vi" #else /* EMACSDEFAULT */ "emacs" #endif /* VIDEFAULT */ ); xprintf("%s", CGETS(20, 20, " -l list editor commands with descriptions\n")); xprintf("%s", CGETS(20, 21, " -r remove KEY's binding\n")); xprintf("%s", CGETS(20, 22, " -k interpret KEY as a symbolic arrow-key name\n")); xprintf("%s", CGETS(20, 23, " -- force a break from option processing\n")); xprintf("%s", CGETS(20, 24, " -u (or any invalid option) this message\n")); xprintf("\n"); xprintf("%s", CGETS(20, 25, "Without KEY or COMMAND, prints all bindings\n")); xprintf("%s", CGETS(20, 26, "Without COMMAND, prints the binding for KEY.\n")); } static void list_functions(void) { struct KeyFuncs *fp; for (fp = FuncNames; fp->name; fp++) { xprintf("%s\n %s\n", fp->name, fp->desc); } } diff --git a/contrib/tcsh/tc.const.c b/contrib/tcsh/tc.const.c index b19d012d5a1d..664897c9c0fd 100644 --- a/contrib/tcsh/tc.const.c +++ b/contrib/tcsh/tc.const.c @@ -1,522 +1,522 @@ /* * sh.const.c: String constants for tcsh. */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" Char STRlogout[] = { 'l', 'o', 'g', 'o', 'u', 't', '\0' }; -Char STRautologout[] = { 'a', 'u', 't', 'o', 'l', 'o', 'g', 'o', 'u', 't', +Char STRautologout[] = { 'a', 'u', 't', 'o', 'l', 'o', 'g', 'o', 'u', 't', '\0' }; Char STRdefautologout[] = { '6', '0', '\0' }; #ifdef convex Char STRrootdefautologout[] = { '1', '5', '\0' }; #endif Char STRautomatic[] = { 'a', 'u', 't', 'o', 'm', 'a', 't', 'i', 'c', '\0' }; Char STRanyerror[] = { 'a', 'n', 'y', 'e', 'r', 'r', 'o', 'r', '\0' }; Char STRhangup[] = { 'h', 'a', 'n', 'g', 'u', 'p', '\0' }; Char STRaout[] = { 'a', '.', 'o', 'u', 't', '\0' }; Char STRtty[] = { 't', 't', 'y', '\0' }; Char STRptssl[] = { 'p', 't', 's', '/', '\0' }; Char STRany[] = { 'a', 'n', 'y', '\0' }; Char STRstatus[] = { 's', 't', 'a', 't', 'u', 's', '\0' }; Char STR0[] = { '0', '\0' }; Char STR1[] = { '1', '\0' }; /* STRm1 would look too much like STRml IMHO */ Char STRminus1[] = { '-', '1', '\0' }; Char STRmaxint[] = { '0', 'x', '7', 'f', 'f', 'f', 'f', 'f', 'f', 'f', '\0' }; Char STRcolon[] = { ':', '\0' }; Char STR_[] = { '_', '\0' }; Char STRNULL[] = { '\0' }; Char STRtcsh[] = { 't', 'c', 's', 'h', '\0' }; Char STRhome[] = { 'h', 'o', 'm', 'e', '\0' }; Char STReuser[] = { 'e', 'u', 's', 'e', 'r', '\0'}; Char STRuser[] = { 'u', 's', 'e', 'r', '\0' }; Char STRgroup[] = { 'g', 'r', 'o', 'u', 'p', '\0' }; #ifdef AFS Char STRafsuser[] = { 'a', 'f', 's', 'u', 's', 'e', 'r', '\0' }; #endif /* AFS */ Char STRterm[] = { 't', 'e', 'r', 'm', '\0' }; Char STRversion[] = { 'v', 'e', 'r', 's', 'i', 'o', 'n', '\0' }; Char STReuid[] = { 'e', 'u', 'i', 'd', '\0' }; Char STRuid[] = { 'u', 'i', 'd', '\0' }; Char STRgid[] = { 'g', 'i', 'd', '\0' }; Char STRunknown[] = { 'u', 'n', 'k', 'n', 'o', 'w', 'n', '\0' }; Char STRnetwork[] = { 'n', 'e', 't', 'w', 'o', 'r', 'k', '\0' }; Char STRdumb[] = { 'd', 'u', 'm', 'b', '\0' }; Char STRHOST[] = { 'H', 'O', 'S', 'T', '\0' }; #ifdef REMOTEHOST -Char STRREMOTEHOST[] = { 'R', 'E', 'M', 'O', 'T', 'E', 'H', +Char STRREMOTEHOST[] = { 'R', 'E', 'M', 'O', 'T', 'E', 'H', 'O', 'S', 'T', '\0' }; #endif /* REMOTEHOST */ Char STRHOSTTYPE[] = { 'H', 'O', 'S', 'T', 'T', 'Y', 'P', 'E', '\0' }; Char STRVENDOR[] = { 'V', 'E', 'N', 'D', 'O', 'R', '\0' }; Char STRMACHTYPE[] = { 'M', 'A', 'C', 'H', 'T', 'Y', 'P', 'E', '\0' }; Char STROSTYPE[] = { 'O', 'S', 'T', 'Y', 'P', 'E', '\0' }; Char STRedit[] = { 'e', 'd', 'i', 't', '\0' }; Char STReditors[] = { 'e', 'd', 'i', 't', 'o', 'r', 's', '\0' }; Char STRvimode[] = { 'v', 'i', 'm', 'o', 'd', 'e', '\0' }; Char STRaddsuffix[] = { 'a', 'd', 'd', 's', 'u', 'f', 'f', 'i', 'x', '\0' }; Char STRcsubstnonl[] = { 'c', 's', 'u', 'b', 's', 't', 'n', 'o', 'n', 'l', '\0' }; Char STRnostat[] = { 'n', 'o', 's', 't', 'a', 't', '\0' }; Char STRshell[] = { 's', 'h', 'e', 'l', 'l', '\0' }; Char STRtmpsh[] = { '/', 't', 'm', 'p', '/', 's', 'h', '\0' }; Char STRverbose[] = { 'v', 'e', 'r', 'b', 'o', 's', 'e', '\0' }; Char STRecho[] = { 'e', 'c', 'h', 'o', '\0' }; Char STRpath[] = { 'p', 'a', 't', 'h', '\0' }; Char STRprompt[] = { 'p', 'r', 'o', 'm', 'p', 't', '\0' }; Char STRprompt2[] = { 'p', 'r', 'o', 'm', 'p', 't', '2', '\0' }; Char STRprompt3[] = { 'p', 'r', 'o', 'm', 'p', 't', '3', '\0' }; Char STRrprompt[] = { 'r', 'p', 'r', 'o', 'm', 'p', 't', '\0' }; Char STRellipsis[] = { 'e', 'l', 'l', 'i', 'p', 's', 'i', 's', '\0' }; Char STRcwd[] = { 'c', 'w', 'd', '\0' }; Char STRowd[] = { 'o', 'w', 'd', '\0' }; Char STRstar[] = { '*', '\0' }; Char STRdot[] = { '.', '\0' }; Char STRhistory[] = { 'h', 'i', 's', 't', 'o', 'r', 'y', '\0' }; Char STRhistdup[] = { 'h', 'i', 's', 't', 'd', 'u', 'p', '\0' }; Char STRhistfile[] = { 'h', 'i', 's', 't', 'f', 'i', 'l', 'e', '\0' }; Char STRsource[] = { 's', 'o', 'u', 'r', 'c', 'e', '\0' }; Char STRmh[] = { '-', 'h', '\0' }; Char STRmhT[] = { '-', 'h', 'T', '\0' }; Char STRmm[] = { '-', 'm', '\0' }; Char STRmr[] = { '-', 'r', '\0' }; Char STRmerge[] = { 'm', 'e', 'r', 'g', 'e', '\0' }; Char STRlock[] = { 'l', 'o', 'c', 'k', '\0' }; -Char STRtildothist[] = { '~', '/', '.', 'h', 'i', 's', 't', 'o', 'r', +Char STRtildothist[] = { '~', '/', '.', 'h', 'i', 's', 't', 'o', 'r', 'y', '\0' }; #ifdef NLS_CATALOGS Char STRcatalog[] = { 'c', 'a', 't', 'a', 'l', 'o', 'g', '\0' }; Char STRNLSPATH[] = { 'N', 'L', 'S', 'P', 'A', 'T', 'H', '\0' }; #endif /* NLS_CATALOGS */ #ifdef KANJI Char STRnokanji[] = { 'n', 'o', 'k', 'a', 'n', 'j', 'i', '\0' }; # ifdef DSPMBYTE Char STRdspmbyte[] = { 'd', 's', 'p', 'm', 'b', 'y', 't', 'e', '\0' }; # ifdef BSDCOLORLS Char STRmmliteral[] = { '-', 'G', '\0' }; # else Char STRmmliteral[] = { '-', '-', 'l', 'i', 't', 'e', 'r', 'a', 'l', '\0' }; # endif Char STReuc[] = { 'e', 'u', 'c', '\0' }; Char STRsjis[] = { 's', 'j', 'i', 's', '\0' }; Char STRbig5[] = { 'b', 'i', 'g', '5', '\0' }; Char STRutf8[] = { 'u', 't', 'f', '8', '\0' }; Char STRstarutfstar8[] = { '*', 'u', 't', 'f', '*', '8', '\0' }; Char STRGB2312[] = { 'g', 'b', '2', '3', '1', '2', '\0' }; # ifdef MBYTEDEBUG /* Sorry, use for beta testing */ Char STRmbytemap[] = { 'm', 'b', 'y', 't', 'e', 'm', 'a', 'p', '\0' }; # endif /* MBYTEMAP */ /* PATCH IDEA FROM Issei.Suzuki VERY THANKS */ /* dspmbyte autoset trap */ /* STRLANGEUCJP,STRLANGEUCJPB(,STRLANGEUCJPC) = EUCJP Trap */ /* STRLANGEUCKR,STRLANGEUCKRB = EUCKR Trap */ /* STRLANGEUCZH,STRLANGEUCZHB = EUCZH Trap */ /* STRLANGSJIS,STRLANGSJISB = SJIS Trap */ # if defined(__uxps__) || defined(sgi) || defined(aix) || defined(__CYGWIN__) Char STRLANGEUCJP[] = { 'j', 'a', '_', 'J', 'P', '.', 'E', 'U', 'C', '\0' }; Char STRLANGEUCKR[] = { 'k', 'o', '_', 'K', 'R', '.', 'E', 'U', 'C', '\0' }; # if defined(__uxps__) Char STRLANGEUCJPB[] = { 'j', 'a', 'p', 'a', 'n', '\0' }; Char STRLANGEUCKRB[] = { 'k', 'o', 'r', 'e', 'a', '\0' }; # elif defined(aix) Char STRLANGEUCJPB[] = { 'j', 'a', '_', 'J', 'P', '\0' }; Char STRLANGEUCKRB[] = { 'k', 'o', '_', 'K', 'R', '\0' }; # else Char STRLANGEUCJPB[] = { '\0' }; Char STRLANGEUCKRB[] = { '\0' }; # endif Char STRLANGSJIS[] = { 'j', 'a', '_', 'J', 'P', '.', 'S', 'J', 'I', 'S', '\0' }; Char STRLANGSJISB[] = { '\0' }; Char STRLANGBIG5[] = { 'z', 'h', '_', 'T', 'W', '.', 'B', 'i', 'g', '5', '\0' }; Char STRLANGEUCZH[] = { '\0' }; Char STRLANGEUCZHB[] = { '\0' }; # elif defined(__linux__) || defined(__GNU__) || defined(__GLIBC__) Char STRLANGEUCJP[] = { 'j', 'a', '_', 'J', 'P', '.', 'E', 'U', 'C', '-', 'J', 'P', '\0' }; Char STRLANGEUCKR[] = { 'k', 'o', '_', 'K', 'R', '.', 'E', 'U', 'C', '\0' }; Char STRLANGEUCJPB[] = { 'j', 'a', '_', 'J', 'P', '.', 'e', 'u', 'c', 'J', 'P', '\0' }; Char STRLANGEUCKRB[] = { 'k', 'o', '_', 'K', 'R', '.', 'e', 'u', 'c', '\0' }; Char STRLANGEUCJPC[] = { 'j', 'a', '_', 'J', 'P', '.', 'u', 'j', 'i', 's', '\0' }; Char STRLANGSJIS[] = { 'j', 'a', '_', 'J', 'P', '.', 'S', 'J', 'I', 'S', '\0' }; Char STRLANGSJISB[] = { '\0' }; Char STRLANGBIG5[] = { 'z', 'h', '_', 'T', 'W', '.', 'B', 'i', 'g', '5', '\0' }; Char STRLANGEUCZH[] = { '\0' }; Char STRLANGEUCZHB[] = { '\0' }; # elif (defined(__FreeBSD__) || defined(__NetBSD__)) || defined(__MidnightBSD__) Char STRLANGEUCJP[] = { 'j', 'a', '_', 'J', 'P', '.', 'e', 'u', 'c', 'J', 'P', '\0' }; Char STRLANGEUCJPB[] = { 'j', 'a', '_', 'J', 'P', '.', 'E', 'U', 'C', '\0' }; Char STRLANGEUCKR[] = { 'k', 'o', '_', 'K', 'R', '.', 'e', 'u', 'c', 'K', 'R', '\0' }; Char STRLANGEUCKRB[] = { 'k', 'o', '_', 'K', 'R', '.', 'E', 'U', 'C', '\0' }; Char STRLANGEUCZH[] = { 'z', 'h', '_', 'C', 'N', '.', 'e', 'u', 'c', 'C', 'N', '\0' }; Char STRLANGEUCZHB[] = { 'z', 'h', '_', 'C', 'N', '.', 'E', 'U', 'C', '\0' }; Char STRLANGSJIS[] = { 'j', 'a', '_', 'J', 'P', '.', 'S', 'J', 'I', 'S', '\0' }; Char STRLANGSJISB[] = { 'j', 'a', '_', 'J', 'P', '.', 'S', 'h', 'i', 'f', 't', '_', 'J', 'I', 'S', '\0' }; Char STRLANGBIG5[] = { 'z', 'h', '_', 'T', 'W', '.', 'B', 'i', 'g', '5', '\0' }; # elif defined(__uxpm__) Char STRLANGEUCJP[] = { 'j', 'a', 'p', 'a', 'n', '\0' }; Char STRLANGEUCKR[] = { 'k', 'o', 'r', 'e', 'a', '\0' }; Char STRLANGEUCZH[] = { '\0' }; Char STRLANGEUCJPB[] = { '\0' }; Char STRLANGEUCKRB[] = { '\0' }; Char STRLANGEUCZHB[] = { '\0' }; Char STRLANGSJIS[] = { '\0' }; Char STRLANGSJISB[] = { '\0' }; Char STRLANGBIG5[] = { '\0' }; # elif defined(SOLARIS2) Char STRLANGEUCJP[] = { 'j', 'a', '\0' }; Char STRLANGEUCKR[] = { 'k', 'o', '\0' }; Char STRLANGEUCZH[] = { '\0' }; Char STRLANGEUCJPB[] = { 'j', 'a', 'p', 'a', 'n', 'e', 's', 'e', '\0' }; Char STRLANGEUCKRB[] = { 'k', 'o', 'r', 'e', 'a', 'n', '\0' }; Char STRLANGEUCZHB[] = { '\0' }; Char STRLANGSJIS[] = { '\0' }; Char STRLANGSJISB[] = { '\0' }; Char STRLANGBIG5[] = { '\0' }; # elif defined(hpux) Char STRLANGEUCJP[] = { 'j', 'a', '_', 'J', 'P', '.', 'e', 'u', 'c', 'J', 'P' }; Char STRLANGEUCKR[] = { 'k', 'o', '_', 'K', 'R', '.', 'e', 'u', 'c', 'K', 'R' }; Char STRLANGEUCZH[] = { '\0' }; Char STRLANGEUCJPB[] = { '\0' }; Char STRLANGEUCKRB[] = { '\0' }; Char STRLANGEUCZHB[] = { '\0' }; Char STRLANGSJIS[] = { '\0' }; Char STRLANGSJISB[] = { '\0' }; Char STRLANGBIG5[] = { '\0' }; # else Char STRLANGEUCJP[] = { '\0' }; Char STRLANGEUCKR[] = { '\0' }; Char STRLANGEUCZH[] = { '\0' }; Char STRLANGEUCJPB[] = { '\0' }; Char STRLANGEUCKRB[] = { '\0' }; Char STRLANGEUCZHB[] = { '\0' }; Char STRLANGSJIS[] = { '\0' }; Char STRLANGSJISB[] = { '\0' }; Char STRLANGBIG5[] = { '\0' }; # endif # endif /* defined(DSPMBYTE) */ #endif Char STRtildotdirs[] = { '~', '/', '.', 'c', 's', 'h', 'd', 'i', 'r', 's', '\0' }; Char STRdirsfile[] = { 'd', 'i', 'r', 's', 'f', 'i', 'l', 'e', '\0' }; Char STRsavedirs[] = { 's', 'a', 'v', 'e', 'd', 'i', 'r', 's', '\0' }; Char STRloginsh[] = { 'l', 'o', 'g', 'i', 'n', 's', 'h', '\0' }; Char STRdirstack[] = { 'd', 'i', 'r', 's', 't', 'a', 'c', 'k', '\0' }; Char STRargv[] = { 'a', 'r', 'g', 'v', '\0' }; Char STRcommand[] = { 'c', 'o', 'm', 'm', 'a', 'n', 'd', '\0' }; Char STRsavehist[] = { 's', 'a', 'v', 'e', 'h', 'i', 's', 't', '\0' }; Char STRnormal[] = { 'n', 'o', 'r', 'm', 'a', 'l', '\0' }; Char STRsldtlogout[] = { '/', '.', 'l', 'o', 'g', 'o', 'u', 't', '\0' }; Char STRjobs[] = { 'j', 'o', 'b', 's', '\0' }; Char STRdefprompt[] = { '%', '#', ' ', '\0' }; Char STRmquestion[] = { '%', 'R', (Char)('?' | QUOTE), ' ', '\0' }; -Char STRKCORRECT[] = { 'C', 'O', 'R', 'R', 'E', 'C', 'T', '>', '%', 'R', - ' ', '(', 'y', '|', 'n', '|', 'e', '|', 'a', ')', +Char STRKCORRECT[] = { 'C', 'O', 'R', 'R', 'E', 'C', 'T', '>', '%', 'R', + ' ', '(', 'y', '|', 'n', '|', 'e', '|', 'a', ')', (Char)('?' | QUOTE), ' ', '\0' }; Char STRunalias[] = { 'u', 'n', 'a', 'l', 'i', 'a', 's', '\0' }; Char STRalias[] = { 'a', 'l', 'i', 'a', 's', '\0' }; Char STRprecmd[] = { 'p', 'r', 'e', 'c', 'm', 'd', '\0' }; Char STRjobcmd[] = { 'j', 'o', 'b', 'c', 'm', 'd', '\0' }; /*GrP*/ Char STRpostcmd[] = { 'p', 'o', 's', 't', 'c', 'm', 'd', '\0' }; Char STRcwdcmd[] = { 'c', 'w', 'd', 'c', 'm', 'd', '\0' }; Char STRperiodic[] = { 'p', 'e', 'r', 'i', 'o', 'd', 'i', 'c', '\0' }; Char STRtperiod[] = { 't', 'p', 'e', 'r', 'i', 'o', 'd', '\0' }; Char STRmf[] = { '-', 'f', '\0' }; Char STRml[] = { '-', 'l', '\0' }; Char STRslash[] = { '/', '\0' }; Char STRdotsl[] = { '.', '/', '\0' }; Char STRdotdotsl[] = { '.', '.', '/', '\0' }; Char STRcdpath[] = { 'c', 'd', 'p', 'a', 't', 'h', '\0' }; Char STRcd[] = { 'c', 'd', '\0' }; Char STRpushdtohome[] = { 'p', 'u', 's', 'h', 'd', 't', 'o', 'h', 'o', 'm', 'e', '\0' }; Char STRpushdsilent[] = { 'p', 'u', 's', 'h', 'd', 's', 'i', 'l', 'e', 'n', 't', '\0' }; Char STRdextract[] = { 'd', 'e', 'x', 't', 'r', 'a', 'c', 't', '\0' }; Char STRdunique[] = { 'd', 'u', 'n', 'i', 'q', 'u', 'e', '\0' }; Char STRsymlinks[] = { 's', 'y', 'm', 'l', 'i', 'n', 'k', 's', '\0' }; Char STRignore[] = { 'i', 'g', 'n', 'o', 'r', 'e', '\0' }; Char STRchase[] = { 'c', 'h', 'a', 's', 'e', '\0' }; Char STRexpand[] = { 'e', 'x', 'p', 'a', 'n', 'd', '\0' }; -Char STRecho_style[] = { 'e', 'c', 'h', 'o', '_', 's', 't', 'y', 'l', 'e', +Char STRecho_style[] = { 'e', 'c', 'h', 'o', '_', 's', 't', 'y', 'l', 'e', '\0' }; Char STRbsd[] = { 'b', 's', 'd', '\0' }; Char STRsysv[] = { 's', 'y', 's', 'v', '\0' }; Char STRboth[] = { 'b', 'o', 't', 'h', '\0' }; Char STRnone[] = { 'n', 'o', 'n', 'e', '\0' }; Char STRPWD[] = { 'P', 'W', 'D', '\0' }; Char STRor2[] = { '|', '|', '\0' }; Char STRand2[] = { '&', '&', '\0' }; Char STRor[] = { '|', '\0' }; Char STRcaret[] = { '^', '\0' }; Char STRand[] = { '&', '\0' }; Char STRequal[] = { '=', '\0' }; Char STRbang[] = { '!', '\0' }; Char STRtilde[] = { '~', '\0' }; Char STRLparen[] = { '(', '\0' }; Char STRLbrace[] = { '{', '\0' }; Char STRfakecom[] = { '{', ' ', '.', '.', '.', ' ', '}', '\0' }; Char STRRbrace[] = { '}', '\0' }; Char STRKPATH[] = { 'P', 'A', 'T', 'H', '\0' }; Char STRdefault[] = { 'd', 'e', 'f', 'a', 'u', 'l', 't', '\0' }; Char STRmn[] = { '-', 'n', '\0' }; Char STRminus[] = { '-', '\0' }; Char STRnoglob[] = { 'n', 'o', 'g', 'l', 'o', 'b', '\0' }; Char STRnonomatch[] = { 'n', 'o', 'n', 'o', 'm', 'a', 't', 'c', 'h', '\0' }; Char STRglobstar[] = { 'g', 'l', 'o', 'b', 's', 't', 'a', 'r', '\0' }; Char STRglobdot[] = { 'g', 'l', 'o', 'b', 'd', 'o', 't', '\0' }; Char STRfakecom1[] = { '`', ' ', '.', '.', '.', ' ', '`', '\0' }; Char STRampm[] = { 'a', 'm', 'p', 'm', '\0' }; Char STRtime[] = { 't', 'i', 'm', 'e', '\0' }; Char STRnotify[] = { 'n', 'o', 't', 'i', 'f', 'y', '\0' }; -Char STRprintexitvalue[] = { 'p', 'r', 'i', 'n', 't', 'e', 'x', 'i', 't', 'v', +Char STRprintexitvalue[] = { 'p', 'r', 'i', 'n', 't', 'e', 'x', 'i', 't', 'v', 'a', 'l', 'u', 'e', '\0' }; Char STRLparensp[] = { '(', ' ', '\0' }; Char STRspRparen[] = { ' ', ')', '\0' }; Char STRspace[] = { ' ', '\0' }; Char STRspor2sp[] = { ' ', '|', '|', ' ', '\0' }; Char STRspand2sp[] = { ' ', '&', '&', ' ', '\0' }; Char STRsporsp[] = { ' ', '|', ' ', '\0' }; Char STRsemisp[] = { ';', ' ', '\0' }; Char STRsemi[] = { ';', '\0' }; Char STRQQ[] = { '"', '"', '\0' }; Char STRBB[] = { '[', ']', '\0' }; Char STRspLarrow2sp[] = { ' ', '<', '<', ' ', '\0' }; Char STRspLarrowsp[] = { ' ', '<', ' ', '\0' }; Char STRspRarrow2[] = { ' ', '>', '>', '\0' }; Char STRspRarrow[] = { ' ', '>', '\0' }; Char STRgt[] = { '>', '\0' }; Char STRcent2[] = { '%', '%', '\0' }; Char STRcentplus[] = { '%', '+', '\0' }; Char STRcentminus[] = { '%', '-', '\0' }; Char STRcenthash[] = { '%', '#', '\0' }; #ifdef BSDJOBS Char STRcontinue[] = { 'c', 'o', 'n', 't', 'i', 'n', 'u', 'e', '\0' }; Char STRcontinue_args[] = { 'c', 'o', 'n', 't', 'i', 'n', 'u', 'e', '_', 'a', 'r', 'g', 's', '\0' }; Char STRunderpause[] = { '_', 'p', 'a', 'u', 's', 'e', '\0' }; #endif Char STRbackqpwd[] = { '`', 'p', 'w', 'd', '`', '\0' }; #if defined(FILEC) && defined(TIOCSTI) Char STRfilec[] = { 'f', 'i', 'l', 'e', 'c', '\0' }; #endif /* FILEC && TIOCSTI */ Char STRhistchars[] = { 'h', 'i', 's', 't', 'c', 'h', 'a', 'r', 's', '\0' }; Char STRpromptchars[] = { 'p', 'r', 'o', 'm', 'p', 't', 'c', 'h', 'a', 'r', 's', '\0' }; Char STRhistlit[] = { 'h', 'i', 's', 't', 'l', 'i', 't', '\0' }; Char STRKUSER[] = { 'U', 'S', 'E', 'R', '\0' }; Char STRLOGNAME[] = { 'L', 'O', 'G', 'N', 'A', 'M', 'E', '\0' }; Char STRKGROUP[] = { 'G', 'R', 'O', 'U', 'P', '\0' }; Char STRwordchars[] = { 'w', 'o', 'r', 'd', 'c', 'h', 'a', 'r', 's', '\0' }; Char STRKTERM[] = { 'T', 'E', 'R', 'M', '\0' }; Char STRKHOME[] = { 'H', 'O', 'M', 'E', '\0' }; Char STRbackslash_quote[] = { 'b', 'a', 'c', 'k', 's', 'l', 'a', 's', 'h', '_', 'q', 'u', 'o', 't', 'e', '\0' }; Char STRcompat_expr[] = { 'c', 'o', 'm', 'p', 'a', 't', '_', 'e', 'x', 'p', 'r', '\0' }; Char STRRparen[] = { ')', '\0' }; Char STRmail[] = { 'm', 'a', 'i', 'l', '\0' }; #ifndef HAVENOUTMP Char STRwatch[] = { 'w', 'a', 't', 'c', 'h', '\0' }; #endif /* HAVENOUTMP */ Char STRsldottcshrc[] = { '/', '.', 't', 'c', 's', 'h', 'r', 'c', '\0' }; Char STRsldotcshrc[] = { '/', '.', 'c', 's', 'h', 'r', 'c', '\0' }; Char STRsldotlogin[] = { '/', '.', 'l', 'o', 'g', 'i', 'n', '\0' }; Char STRignoreeof[] = { 'i', 'g', 'n', 'o', 'r', 'e', 'e', 'o', 'f', '\0' }; Char STRnoclobber[] = { 'n', 'o', 'c', 'l', 'o', 'b', 'b', 'e', 'r', '\0' }; Char STRnotempty[] = { 'n', 'o', 't', 'e', 'm', 'p', 't', 'y', '\0' }; Char STRask[] = { 'a', 's', 'k', '\0' }; -Char STRhelpcommand[] = { 'h', 'e', 'l', 'p', 'c', 'o', 'm', 'm', 'a', 'n', +Char STRhelpcommand[] = { 'h', 'e', 'l', 'p', 'c', 'o', 'm', 'm', 'a', 'n', 'd', '\0' }; Char STRfignore[] = { 'f', 'i', 'g', 'n', 'o', 'r', 'e', '\0' }; Char STRrecexact[] = { 'r', 'e', 'c', 'e', 'x', 'a', 'c', 't', '\0' }; Char STRlistmaxrows[] = { 'l', 'i', 's', 't', 'm', 'a', 'x', 'r', 'o', 'w', 's', '\0' }; Char STRlistmax[] = { 'l', 'i', 's', 't', 'm', 'a', 'x', '\0' }; Char STRlistlinks[] = { 'l', 'i', 's', 't', 'l', 'i', 'n', 'k', 's', '\0' }; Char STRDING[] = { 'D', 'I', 'N', 'G', '!', '\0' }; Char STRQNULL[] = { (Char)('\0' | QUOTE), '\0' }; Char STRcorrect[] = { 'c', 'o', 'r', 'r', 'e', 'c', 't', '\0' }; Char STRcmd[] = { 'c', 'm', 'd', '\0' }; Char STRall[] = { 'a', 'l', 'l', '\0' }; Char STRalways[] = { 'a', 'l', 'w', 'a', 'y', 's', '\0' }; Char STRerase[] = { 'e', 'r', 'a', 's', 'e', '\0' }; Char STRprev[] = { 'p', 'r', 'e', 'v', '\0' }; Char STRcomplete[] = { 'c', 'o', 'm', 'p', 'l', 'e', 't', 'e', '\0' }; Char STREnhance[] = { 'E', 'n', 'h', 'a', 'n', 'c', 'e', '\0' }; Char STRenhance[] = { 'e', 'n', 'h', 'a', 'n', 'c', 'e', '\0' }; Char STRigncase[] = { 'i', 'g', 'n', 'c', 'a', 's', 'e', '\0' }; Char STRautoexpand[] = { 'a', 'u', 't', 'o', 'e', 'x', 'p', 'a', 'n', 'd', '\0' }; Char STRautocorrect[] = { 'a', 'u', 't', 'o', 'c', 'o', 'r', 'r', 'e', 'c', 't', '\0' }; Char STRautolist[] = { 'a', 'u', 't', 'o', 'l', 'i', 's', 't', '\0' }; Char STRautorehash[] = { 'a', 'u', 't', 'o', 'r', 'e', 'h', 'a', 's', 'h', '\0' }; Char STRbeepcmd[] = { 'b', 'e', 'e', 'p', 'c', 'm', 'd', '\0' }; Char STRmatchbeep[] = { 'm', 'a', 't', 'c', 'h', 'b', 'e', 'e', 'p', '\0' }; Char STRnomatch[] = { 'n', 'o', 'm', 'a', 't', 'c', 'h', '\0' }; Char STRambiguous[] = { 'a', 'm', 'b', 'i', 'g', 'u', 'o', 'u', 's', '\0' }; Char STRnotunique[] = { 'n', 'o', 't', 'u', 'n', 'i', 'q', 'u', 'e', '\0' }; Char STRret[] = { '\n', '\0' }; Char STRnobeep[] = { 'n', 'o', 'b', 'e', 'e', 'p', '\0' }; Char STRnoding[] = { 'n', 'o', 'd', 'i', 'n', 'g', '\0' }; Char STRpadhour[] = { 'p', 'a', 'd', 'h', 'o', 'u', 'r', '\0' }; -Char STRnoambiguous[] = { 'n', 'o', 'a', 'm', 'b', 'i', 'g', 'u', 'o', 'u', +Char STRnoambiguous[] = { 'n', 'o', 'a', 'm', 'b', 'i', 'g', 'u', 'o', 'u', 's', '\0' }; -Char STRvisiblebell[] = { 'v', 'i', 's', 'i', 'b', 'l', 'e', 'b', 'e', 'l', +Char STRvisiblebell[] = { 'v', 'i', 's', 'i', 'b', 'l', 'e', 'b', 'e', 'l', 'l', '\0' }; Char STRrecognize_only_executables[] = { 'r', 'e', 'c', 'o', 'g', 'n', 'i', 'z', 'e', '_', 'o', 'n', 'l', 'y', '_', 'e', 'x', 'e', 'c', 'u', 't', 'a', 'b', 'l', 'e', 's', '\0' }; Char STRinputmode[] = { 'i', 'n', 'p', 'u', 't', 'm', 'o', 'd', 'e', '\0' }; Char STRoverwrite[] = { 'o', 'v', 'e', 'r', 'w', 'r', 'i', 't', 'e', '\0' }; Char STRinsert[] = { 'i', 'n', 's', 'e', 'r', 't', '\0' }; Char STRnohup[] = { 'n', 'o', 'h', 'u', 'p', '\0' }; Char STRhup[] = { 'h', 'u', 'p', '\0' }; Char STRnice[] = { 'n', 'i', 'c', 'e', '\0' }; Char STRthen[] = { 't', 'h', 'e', 'n', '\0' }; Char STRlistjobs[] = { 'l', 'i', 's', 't', 'j', 'o', 'b', 's', '\0' }; Char STRlistflags[] = { 'l', 'i', 's', 't', 'f', 'l', 'a', 'g', 's', '\0' }; Char STRlong[] = { 'l', 'o', 'n', 'g', '\0' }; Char STRwho[] = { 'w', 'h', 'o', '\0' }; Char STRsched[] = { 's', 'c', 'h', 'e', 'd', '\0' }; Char STRrmstar[] = { 'r', 'm', 's', 't', 'a', 'r', '\0' }; Char STRrm[] = { 'r', 'm', '\0' }; Char STRhighlight[] = { 'h', 'i', 'g', 'h', 'l', 'i', 'g', 'h', 't', '\0' }; Char STRimplicitcd[] = { 'i', 'm', 'p', 'l', 'i', 'c', 'i', 't', 'c', 'd', '\0' }; Char STRcdtohome[] = { 'c', 'd', 't', 'o', 'h', 'o', 'm', 'e', '\0' }; Char STRkillring[] = { 'k', 'i', 'l', 'l', 'r', 'i', 'n', 'g', '\0' }; Char STRkilldup[] = { 'k', 'i', 'l', 'l', 'd', 'u', 'p', '\0' }; Char STRshlvl[] = { 's', 'h', 'l', 'v', 'l', '\0' }; Char STRKSHLVL[] = { 'S', 'H', 'L', 'V', 'L', '\0' }; Char STRLANG[] = { 'L', 'A', 'N', 'G', '\0' }; Char STRLC_ALL[] = { 'L', 'C', '_', 'A', 'L', 'L', '\0' }; Char STRLC_CTYPE[] = { 'L', 'C', '_', 'C', 'T', 'Y', 'P', 'E' ,'\0' }; Char STRLC_NUMERIC[] = { 'L', 'C', '_', 'N', 'U', 'M', 'E', 'R', 'I', 'C', '\0' }; Char STRLC_TIME[] = { 'L', 'C', '_', 'T', 'I', 'M', 'E', '\0' }; Char STRLC_COLLATE[] = { 'L', 'C', '_', 'C', 'O', 'L', 'L', 'A', 'T', 'E', '\0' }; Char STRLC_MESSAGES[] = { 'L', 'C', '_', 'M', 'E', 'S', 'S', 'A', 'G', 'E', 'S', '\0' }; Char STRLC_MONETARY[] = { 'L', 'C', '_', 'M', 'O', 'N', 'E', 'T', 'A', 'R', 'Y', '\0' }; Char STRNOREBIND[] = { 'N', 'O', 'R', 'E', 'B', 'I', 'N', 'D', '\0' }; #if defined(SIG_WINDOW) || defined(SIGWINCH) || defined(SIGWINDOW) || defined (_VMS_POSIX) || defined(_SIGWINCH) /* atp - problem with declaration of str{lines,columns} in sh.func.c (1277) */ Char STRLINES[] = { 'L', 'I', 'N', 'E', 'S', '\0'}; Char STRCOLUMNS[] = { 'C', 'O', 'L', 'U', 'M', 'N', 'S', '\0'}; Char STRTERMCAP[] = { 'T', 'E', 'R', 'M', 'C', 'A', 'P', '\0'}; #endif /* SIG_WINDOW || SIGWINCH || SIGWINDOW || _VMS_POSIX */ #if defined (_OSD_POSIX) /* BS2000 needs this variable set to "SHELL" */ Char STRPROGRAM_ENVIRONMENT[] = { 'P', 'R', 'O', 'G', 'R', 'A', 'M', '_', 'E', 'N', 'V', 'I', 'R', 'O', 'N', 'M', 'E', 'N', 'T', '\0'}; #endif /* _OSD_POSIX */ Char STRCOMMAND_LINE[] = { 'C', 'O', 'M', 'M', 'A', 'N', 'D', '_', 'L', 'I', 'N', 'E', '\0' }; #ifdef WARP Char STRwarp[] = { 'w', 'a', 'r', 'p', '\0' }; #endif /* WARP */ #ifdef apollo Char STRSYSTYPE[] = { 'S', 'Y', 'S', 'T', 'Y', 'P', 'E', '\0' }; Char STRoid[] = { 'o', 'i', 'd', '\0' }; Char STRbsd43[] = { 'b', 's', 'd', '4', '.', '3', '\0' }; Char STRsys53[] = { 's', 'y', 's', '5', '.', '3', '\0' }; Char STRver[] = { 'v', 'e', 'r', '\0' }; #endif /* apollo */ #ifndef IS_ASCII Char STRwarnebcdic[] = { 'w', 'a', 'r', 'n', 'e', 'b', 'c', 'd', 'i', 'c', '\0' }; #endif Char STRmCF[] = { '-', 'C', 'F', '\0', '\0' }; #ifdef COLOR_LS_F Char STRlsmF[] = { 'l', 's', '-', 'F', '\0' }; Char STRcolor[] = { 'c', 'o', 'l', 'o', 'r', '\0' }; #ifdef BSD_STYLE_COLORLS Char STRmmcolormauto[] = { '-', 'G', '\0' }; #else Char STRmmcolormauto[] = { '-', '-', 'c', 'o', 'l', 'o', 'r', '=', 'a', 'u', 't', 'o', '\0' }; #endif /* BSD_STYLE_COLORLS */ Char STRLS_COLORS[] = { 'L', 'S', '_', 'C', 'O', 'L', 'O', 'R', 'S', '\0' }; Char STRLSCOLORS[] = { 'L', 'S', 'C', 'O', 'L', 'O', 'R', 'S', '\0' }; #endif /* COLOR_LS_F */ Char STRls[] = { 'l', 's', '\0' }; Char STRup[] = { 'u', 'p', '\0' }; Char STRdown[] = { 'd', 'o', 'w', 'n', '\0' }; Char STRleft[] = { 'l', 'e', 'f', 't', '\0' }; Char STRright[] = { 'r', 'i', 'g', 'h', 't', '\0' }; Char STRend[] = { 'e', 'n', 'd', '\0' }; #ifdef COLORCAT Char STRcolorcat[] = { 'c', 'o', 'l', 'o', 'r', 'c', 'a', 't', '\0' }; #endif Char STRshwspace[] = { ' ', '\t', '\0' }; Char STRshwordsep[] = { ' ', '\t', '&', '|', ';', '<', '>', '(', ')', '\0' }; Char STRrepeat[] = { 'r', 'e', 'p', 'e', 'a', 't', '\0' }; Char STReof[] = { '^', 'D', '\b', '\b', '\0' }; Char STRonlyhistory[] = { 'o', 'n', 'l', 'y', 'h', 'i', 's', 't', 'o', 'r', 'y', '\0' }; Char STRparseoctal[] = { 'p', 'a', 'r', 's', 'e', 'o', 'c', 't', 'a', 'l', '\0' }; Char STRli[] = { 'l', 'i', '#', '\0' }; Char STRco[] = { 'c', 'o', '#', '\0' }; diff --git a/contrib/tcsh/tc.decls.h b/contrib/tcsh/tc.decls.h index 4925ca585770..ee116a1d656c 100644 --- a/contrib/tcsh/tc.decls.h +++ b/contrib/tcsh/tc.decls.h @@ -1,344 +1,344 @@ /* * tc.decls.h: Function declarations from all the tcsh modules */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _h_tc_decls #define _h_tc_decls struct blk_buf; struct strbuf; struct Strbuf; /* * tc.alloc.c */ #ifndef SYSMALLOC #ifndef WINNT_NATIVE #ifndef __linux__ extern void free (ptr_t); extern memalign_t malloc (size_t); extern memalign_t realloc (ptr_t, size_t); extern memalign_t calloc (size_t, size_t); #endif #endif /* !WINNT_NATIVE */ #else /* SYSMALLOC */ extern void sfree (ptr_t); extern memalign_t smalloc (size_t); extern memalign_t srealloc (ptr_t, size_t); extern memalign_t scalloc (size_t, size_t); #endif /* SYSMALLOC */ extern void showall (Char **, struct command *); /* * tc.bind.c */ extern void dobindkey (Char **, struct command *); /* * tc.defs.c: */ extern void getmachine (void); /* * tc.disc.c */ extern int setdisc (int); extern int resetdisc (int); /* * tc.func.c */ extern Char *expand_lex (const struct wordent *, int, int); extern Char *sprlex (const struct wordent *); extern Char *Itoa (int, size_t, Char); extern void dolist (Char **, struct command *); extern void dotermname (Char **, struct command *); extern void dotelltc (Char **, struct command *); extern void doechotc (Char **, struct command *); extern void dosettc (Char **, struct command *); extern int cmd_expand (Char *, Char **); extern void dowhich (Char **, struct command *); extern struct process *find_stop_ed (void); extern void fg_proc_entry (struct process *); extern void alrmcatch (void); extern void precmd (void); extern void postcmd (void); extern void cwd_cmd (void); extern void beep_cmd (void); extern void period_cmd (void); extern void job_cmd (Char *); extern void aliasrun (int, Char *, Char *); extern void setalarm (int); extern void rmstar (struct wordent *); extern void continue_jobs (struct wordent *); extern Char *gettilde (const Char *); extern Char *getusername (Char **); #ifdef OBSOLETE extern void doaliases (Char **, struct command *); #endif /* OBSOLETE */ extern void shlvl (int); extern int fixio (int, int); extern int collate (const Char *, const Char *); #ifdef HASHBANG extern int hashbang (int, Char ***); #endif /* HASHBANG */ #ifdef REMOTEHOST extern void remotehost (void); #endif /* REMOTEHOST */ /* * tc.os.c */ #ifdef MACH extern void dosetpath (Char **, struct command *); #endif /* MACH */ #ifdef TCF extern void dogetxvers (Char **, struct command *); extern void dosetxvers (Char **, struct command *); extern void dogetspath (Char **, struct command *); extern void dosetspath (Char **, struct command *); extern char *sitename (pid_t); extern void domigrate (Char **, struct command *); #endif /* TCF */ #ifdef WARP extern void dowarp (Char **, struct command *); #endif /* WARP */ #if defined(_CRAY) && !defined(_CRAYMPP) extern void dodmmode (Char **, struct command *); #endif /* _CRAY && !_CRAYMPP */ #if defined(masscomp) || defined(hcx) extern void douniverse (Char **, struct command *); #endif /* masscomp */ #if defined(_OSD_POSIX) /* BS2000 */ extern void dobs2cmd (Char **, struct command *); #endif /* _OSD_POSIX */ #if defined(hcx) extern void doatt (Char **, struct command *); extern void doucb (Char **, struct command *); #endif /* hcx */ #ifdef _SEQUENT_ -extern void pr_stat_sub (struct process_stats *, - struct process_stats *, +extern void pr_stat_sub (struct process_stats *, + struct process_stats *, struct process_stats *); #endif /* _SEQUENT_ */ #ifdef NEEDtcgetpgrp extern pid_t xtcgetpgrp (int); extern int xtcsetpgrp (int, int); # undef tcgetpgrp # define tcgetpgrp(a) xtcgetpgrp(a) # undef tcsetpgrp # define tcsetpgrp(a, b) xtcsetpgrp((a), (b)) #endif /* NEEDtcgetpgrp */ #ifdef YPBUGS extern void fix_yp_bugs (void); #endif /* YPBUGS */ #ifdef STRCOLLBUG extern void fix_strcoll_bug (void); #endif /* STRCOLLBUG */ extern void osinit (void); #ifndef HAVE_MEMMOVE extern void *xmemmove (void *, const void *, size_t); # define memmove(a, b, c) xmemmove(a, b, c) #endif /* !HAVE_MEMMOVE */ #ifndef HAVE_MEMSET extern void *xmemset (void *, int, size_t); # define memset(a, b, c) xmemset(a, b, c) #endif /* !HAVE_MEMSET */ #ifndef HAVE_GETCWD extern char *xgetcwd (char *, size_t); # undef getcwd # define getcwd(a, b) xgetcwd(a, b) #endif /* !HAVE_GETCWD */ #ifndef HAVE_GETHOSTNAME extern int xgethostname (char *, int); # undef gethostname # define gethostname(a, b) xgethostname(a, b) #endif /* !HAVE_GETHOSTNAME */ #ifndef HAVE_NICE extern int xnice (int); # undef nice # define nice(a) xnice(a) #endif /* !HAVE_NICE */ #ifndef HAVE_STRERROR extern char *xstrerror (int); # undef strerror # define strerror(a) xstrerror(a) #endif /* !HAVE_STRERROR */ #ifdef apollo extern void doinlib (Char **, struct command *); extern void dover (Char **, struct command *); extern void dorootnode (Char **, struct command *); extern int getv (Char *); #endif /* apollo */ /* * tc.printf.h */ #ifndef __GNUC__ #define __attribute__(a) #endif extern int xprintf (const char *, ...) __attribute__((__format__(__printf__, 1, 2))); extern int xsnprintf (char *, size_t, const char *, ...) __attribute__((__format__(__printf__, 3, 4))); extern char *xasprintf (const char *, ...) __attribute__((__format__(__printf__, 1, 2))); extern int xvprintf (const char *, va_list) __attribute__((__format__(__printf__, 1, 0))); extern int xvsnprintf (char *, size_t, const char *, va_list) __attribute__((__format__(__printf__, 3, 0))); extern char *xvasprintf (const char *, va_list) __attribute__((__format__(__printf__, 1, 0))); /* * tc.prompt.c */ extern void dateinit (void); extern void printprompt (int, const char *); extern int expdollar (struct Strbuf *, const Char **, Char); extern Char *tprintf (int, const Char *, const char *, time_t, ptr_t); /* * tc.sched.c */ extern time_t sched_next (void); extern void dosched (Char **, struct command *); extern void sched_run (void); /* * tc.str.c: */ #ifdef WIDE_STRINGS extern size_t one_mbtowc (Char *, const char *, size_t); extern size_t one_wctomb (char *, Char); extern int rt_mbtowc (Char *, const char *, size_t); #else #define one_mbtowc(PWC, S, N) \ ((void)(N), *(PWC) = (unsigned char)*(S), (size_t)1) #define one_wctomb(S, WCHAR) (*(S) = (char)(WCHAR), (size_t)1) #endif #ifdef SHORT_STRINGS extern Char *s_strchr (const Char *, int); extern Char *s_strrchr (const Char *, int); extern Char *s_strcat (Char *, const Char *); # ifdef NOTUSED extern Char *s_strncat (Char *, const Char *, size_t); # endif /* NOTUSED */ extern Char *s_strcpy (Char *, const Char *); extern Char *s_strncpy (Char *, const Char *, size_t); extern Char *s_strspl (const Char *, const Char *); extern size_t s_strlen (const Char *); extern int s_strcmp (const Char *, const Char *); extern int s_strncmp (const Char *, const Char *, size_t); extern int s_strcasecmp (const Char *, const Char *); extern Char *s_strnsave (const Char *, size_t); extern Char *s_strsave (const Char *); extern Char *s_strend (const Char *); extern Char *s_strstr (const Char *, const Char *); extern Char *str2short (const char *); extern Char **blk2short (char **); extern char *short2str (const Char *); extern char **short2blk (Char **); #else /* !SHORT_STRINGS */ extern char *caching_strip (const char *); #endif extern char *short2qstr (const Char *); extern struct blk_buf *bb_alloc (void); extern void bb_append (struct blk_buf *, Char *); extern void bb_cleanup (void *); extern Char **bb_finish (struct blk_buf *); extern void bb_free (void *); extern struct strbuf *strbuf_alloc(void); extern void strbuf_terminate(struct strbuf *); extern void strbuf_append1(struct strbuf *, char); extern void strbuf_appendn(struct strbuf *, const char *, size_t); extern void strbuf_append (struct strbuf *, const char *); extern char *strbuf_finish (struct strbuf *); extern void strbuf_cleanup(void *); extern void strbuf_free(void *); extern struct Strbuf *Strbuf_alloc(void); extern void Strbuf_terminate(struct Strbuf *); extern void Strbuf_append1(struct Strbuf *, Char); extern void Strbuf_appendn(struct Strbuf *, const Char *, size_t); extern void Strbuf_append (struct Strbuf *, const Char *); extern Char *Strbuf_finish (struct Strbuf *); extern void Strbuf_cleanup(void *); extern void Strbuf_free(void *); /* * tc.vers.c: */ extern void fix_version (void); /* * tc.who.c */ #if defined (HAVE_UTMP_H) || defined (HAVE_UTMPX_H) || defined (WINNT_NATIVE) extern void initwatch (void); extern void resetwatch (void); extern void watch_login (int); extern char *who_info (ptr_t, int); extern void dolog (Char **, struct command *); # ifdef HAVE_STRUCT_UTMP_UT_HOST extern char *utmphost (void); extern size_t utmphostsize (void); # endif /* HAVE_STRUCT_UTMP_UT_HOST */ #else # define HAVENOUTMP #endif #endif /* _h_tc_decls */ diff --git a/contrib/tcsh/tc.func.c b/contrib/tcsh/tc.func.c index d4cfaa6a1ff6..9f2b1a29f4eb 100644 --- a/contrib/tcsh/tc.func.c +++ b/contrib/tcsh/tc.func.c @@ -1,2125 +1,2125 @@ /* * tc.func.c: New tcsh builtins. */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include "ed.defns.h" /* for the function names */ #include "tw.h" #include "tc.h" #ifdef WINNT_NATIVE #include "nt.const.h" #else /* WINNT_NATIVE */ #include #endif /* WINNT_NATIVE */ #ifdef AFS #include #include long ka_UserAuthenticateGeneral(); #endif /* AFS */ #ifdef TESLA extern int do_logout; #endif /* TESLA */ extern time_t t_period; extern int just_signaled; static int precmd_active = 0; static int jobcmd_active = 0; /* GrP */ int postcmd_active = 0; static int periodic_active = 0; static int cwdcmd_active = 0; /* PWP: for cwd_cmd */ static int beepcmd_active = 0; static void (*alm_fun)(void) = NULL; static void auto_logout (void); static char *xgetpass (const char *); static void auto_lock (void); #ifdef BSDJOBS static void insert (struct wordent *, int); static void insert_we (struct wordent *, struct wordent *); static int inlist (Char *, Char *); #endif /* BSDJOBS */ static int tildecompare (const void *, const void *); static Char *gethomedir (const Char *); #ifdef REMOTEHOST static void palarm (int); static void getremotehost (int); #endif /* REMOTEHOST */ /* * Tops-C shell */ /* * expand_lex: Take the given lex and return an expanded version of it. * First guy in lex list is ignored; last guy is ^J which we ignore. * Only take lex'es from position 'from' to position 'to' inclusive * * Note: csh sometimes sets bit 8 in characters which causes all kinds * of problems if we don't mask it here. Note: excl's in lexes have been * un-back-slashed and must be re-back-slashed * */ /* PWP: this is a combination of the old sprlex() and the expand_lex from the magic-space stuff */ Char * expand_lex(const struct wordent *sp0, int from, int to) { struct Strbuf buf = Strbuf_INIT; const struct wordent *sp; Char *s; Char prev_c; int i; prev_c = '\0'; if (!sp0 || (sp = sp0->next) == sp0 || sp == (sp0 = sp0->prev)) return Strbuf_finish(&buf); /* null lex */ for (i = 0; ; i++) { if ((i >= from) && (i <= to)) { /* if in range */ for (s = sp->word; *s; s++) { /* * bugfix by Michael Bloom: anything but the current history * character {(PWP) and backslash} seem to be dealt with * elsewhere. */ if ((*s & QUOTE) && (((*s & TRIM) == HIST && HIST != '\0') || (((*s & TRIM) == '\'') && (prev_c != '\\')) || (((*s & TRIM) == '\"') && (prev_c != '\\')))) { Strbuf_append1(&buf, '\\'); } #if INVALID_BYTE != 0 if ((*s & INVALID_BYTE) != INVALID_BYTE) /* *s < INVALID_BYTE */ Strbuf_append1(&buf, *s & TRIM); else Strbuf_append1(&buf, *s); #else Strbuf_append1(&buf, *s & TRIM); #endif prev_c = *s; } Strbuf_append1(&buf, ' '); } sp = sp->next; if (sp == sp0) break; } if (buf.len != 0) buf.len--; /* get rid of trailing space */ return Strbuf_finish(&buf); } Char * sprlex(const struct wordent *sp0) { return expand_lex(sp0, 0, INT_MAX); } Char * Itoa(int n, size_t min_digits, Char attributes) { /* * The array size here is derived from * log8(UINT_MAX) * which is guaranteed to be enough for a decimal * representation. We add 1 because integer divide * rounds down. */ #ifndef CHAR_BIT # define CHAR_BIT 8 #endif Char buf[CHAR_BIT * sizeof(int) / 3 + 1], *res, *p, *s; unsigned int un; /* handle most negative # too */ int pad = (min_digits != 0); if (sizeof(buf) - 1 < min_digits) min_digits = sizeof(buf) - 1; un = n; if (n < 0) un = -n; p = buf; do { *p++ = un % 10 + '0'; un /= 10; } while ((pad && (ssize_t)--min_digits > 0) || un != 0); res = xmalloc((p - buf + 2) * sizeof(*res)); s = res; if (n < 0) *s++ = '-'; while (p > buf) *s++ = *--p | attributes; *s = '\0'; return res; } /*ARGSUSED*/ void dolist(Char **v, struct command *c) { Char **globbed; int i, k, ret = 0; struct stat st; USE(c); if (*++v == NULL) { struct Strbuf word = Strbuf_INIT; Strbuf_terminate(&word); cleanup_push(&word, Strbuf_cleanup); (void) t_search(&word, LIST, TW_ZERO, 0, STRNULL, 0); cleanup_until(&word); return; } v = glob_all_or_error(v); globbed = v; cleanup_push(globbed, blk_cleanup); for (k = 0; v[k] != NULL && v[k][0] != '-'; k++) continue; if (v[k]) { /* * We cannot process a flag therefore we let ls do it right. */ Char *lspath; struct command *t; struct wordent cmd, *nextword, *lastword; Char *cp; struct varent *vp; if (setintr) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); } if (seterr) { xfree(seterr); seterr = NULL; } lspath = STRls; STRmCF[1] = 'C'; STRmCF[3] = '\0'; /* Look at listflags, to add -A to the flags, to get a path of ls if necessary */ if ((vp = adrof(STRlistflags)) != NULL && vp->vec != NULL && vp->vec[0] != STRNULL) { if (vp->vec[1] != NULL && vp->vec[1][0] != '\0') lspath = vp->vec[1]; for (cp = vp->vec[0]; *cp; cp++) switch (*cp) { case 'x': STRmCF[1] = 'x'; break; case 'a': STRmCF[3] = 'a'; break; case 'A': STRmCF[3] = 'A'; break; default: break; } } cmd.word = STRNULL; lastword = &cmd; nextword = xcalloc(1, sizeof cmd); nextword->word = Strsave(lspath); lastword->next = nextword; nextword->prev = lastword; lastword = nextword; nextword = xcalloc(1, sizeof cmd); nextword->word = Strsave(STRmCF); lastword->next = nextword; nextword->prev = lastword; #if defined(KANJI) && defined(SHORT_STRINGS) && defined(DSPMBYTE) if (dspmbyte_ls) { lastword = nextword; nextword = xcalloc(1, sizeof cmd); nextword->word = Strsave(STRmmliteral); lastword->next = nextword; nextword->prev = lastword; } #endif #ifdef COLOR_LS_F if (color_context_ls) { lastword = nextword; nextword = xcalloc(1, sizeof cmd); nextword->word = Strsave(STRmmcolormauto); lastword->next = nextword; nextword->prev = lastword; } #endif /* COLOR_LS_F */ lastword = nextword; for (cp = *v; cp; cp = *++v) { nextword = xcalloc(1, sizeof cmd); nextword->word = quote(Strsave(cp)); lastword->next = nextword; nextword->prev = lastword; lastword = nextword; } lastword->next = &cmd; cmd.prev = lastword; cleanup_push(&cmd, lex_cleanup); /* build a syntax tree for the command. */ t = syntax(cmd.next, &cmd, 0); cleanup_push(t, syntax_cleanup); if (seterr) stderror(ERR_OLD); /* expand aliases like process() does */ /* alias(&cmd); */ /* execute the parse tree. */ execute(t, tpgrp > 0 ? tpgrp : -1, NULL, NULL, FALSE); /* done. free the lex list and parse tree. */ cleanup_until(&cmd); if (setintr) cleanup_until(&pintr_disabled); } else { Char *dp, *tmp; struct Strbuf buf = Strbuf_INIT; cleanup_push(&buf, Strbuf_cleanup); for (k = 0, i = 0; v[k] != NULL; k++) { tmp = dnormalize(v[k], symlinks == SYM_IGNORE); cleanup_push(tmp, xfree); dp = Strend(tmp) - 1; if (*dp == '/' && dp != tmp) #ifdef apollo if (dp != &tmp[1]) #endif /* apollo */ *dp = '\0'; if (stat(short2str(tmp), &st) == -1) { int err; err = errno; if (k != i) { if (i != 0) xputchar('\n'); print_by_column(STRNULL, &v[i], k - i, FALSE); } haderr = 1; xprintf("%S: %s.\n", tmp, strerror(err)); haderr = 0; i = k + 1; ret = 1; } else if (S_ISDIR(st.st_mode)) { Char *cp; if (k != i) { if (i != 0) xputchar('\n'); print_by_column(STRNULL, &v[i], k - i, FALSE); } if (k != 0 && v[1] != NULL) xputchar('\n'); xprintf("%S:\n", tmp); buf.len = 0; for (cp = tmp; *cp; cp++) Strbuf_append1(&buf, (*cp | QUOTE)); Strbuf_terminate(&buf); dp = &buf.s[buf.len - 1]; if ( #ifdef WINNT_NATIVE (*dp != (Char) (':' | QUOTE)) && #endif /* WINNT_NATIVE */ (*dp != (Char) ('/' | QUOTE))) { Strbuf_append1(&buf, '/'); Strbuf_terminate(&buf); - } else + } else *dp &= TRIM; (void) t_search(&buf, LIST, TW_ZERO, 0, STRNULL, 0); i = k + 1; } cleanup_until(tmp); } cleanup_until(&buf); if (k != i) { if (i != 0) xputchar('\n'); print_by_column(STRNULL, &v[i], k - i, FALSE); } if (ret) stderror(ERR_SILENT); } cleanup_until(globbed); } extern int GotTermCaps; /*ARGSUSED*/ void dotelltc(Char **v, struct command *c) { USE(v); USE(c); if (!GotTermCaps) GetTermCaps(); TellTC(); } /*ARGSUSED*/ void doechotc(Char **v, struct command *c) { USE(c); if (!GotTermCaps) GetTermCaps(); EchoTC(++v); } /*ARGSUSED*/ void dosettc(Char **v, struct command *c) { char *tv[2]; USE(c); if (!GotTermCaps) GetTermCaps(); tv[0] = strsave(short2str(v[1])); cleanup_push(tv[0], xfree); tv[1] = strsave(short2str(v[2])); cleanup_push(tv[1], xfree); SetTC(tv[0], tv[1]); cleanup_until(tv[0]); } /* The dowhich() is by: * Andreas Luik * I S A GmbH - Informationssysteme fuer computerintegrierte Automatisierung * Azenberstr. 35 * D-7000 Stuttgart 1 * West-Germany * Thanks!! */ int cmd_expand(Char *cmd, Char **str) { struct wordent lexp[3]; struct varent *vp; int rv = TRUE; lexp[0].next = &lexp[1]; lexp[1].next = &lexp[2]; lexp[2].next = &lexp[0]; lexp[0].prev = &lexp[2]; lexp[1].prev = &lexp[0]; lexp[2].prev = &lexp[1]; lexp[0].word = STRNULL; lexp[2].word = STRret; if ((vp = adrof1(cmd, &aliases)) != NULL && vp->vec != NULL) { if (str == NULL) { xprintf(CGETS(22, 1, "%S: \t aliased to "), cmd); blkpr(vp->vec); xputchar('\n'); } else *str = blkexpand(vp->vec); } else { lexp[1].word = cmd; rv = tellmewhat(lexp, str); } return rv; } /*ARGSUSED*/ void dowhich(Char **v, struct command *c) { int rv = TRUE; USE(c); /* * We don't want to glob dowhich args because we lose quoteing * E.g. which \ls if ls is aliased will not work correctly if * we glob here. */ - while (*++v) + while (*++v) rv &= cmd_expand(*v, NULL); if (!rv) setcopy(STRstatus, STR1, VAR_READWRITE); } static int findvv(Char **vv, const char *cp) { for (; vv && *vv; vv++) { size_t i; for (i = 0; (*vv)[i] && (*vv)[i] == cp[i]; i++) continue; if ((*vv)[i] == '\0' && cp[i] == '\0') return 1; } return 0; } /* PWP: a hack to start up your stopped editor on a single keystroke */ /* jbs - fixed hack so it worked :-) 3/28/89 */ struct process * find_stop_ed(void) { struct process *pp, *retp; const char *ep = NULL, *vp = NULL; char *cp, *p; size_t epl = 0, vpl = 0; int pstatus; struct varent *varp; Char **vv; if (pcurrent == NULL) /* see if we have any jobs */ return NULL; /* nope */ if ((varp = adrof(STReditors)) != NULL) vv = varp->vec; else vv = NULL; if (! vv) { if ((ep = getenv("EDITOR")) != NULL) { /* if we have a value */ if ((p = strrchr(ep, '/')) != NULL) /* if it has a path */ ep = p + 1; /* then we want only the last part */ } else ep = "ed"; if ((vp = getenv("VISUAL")) != NULL) { /* if we have a value */ if ((p = strrchr(vp, '/')) != NULL) /* and it has a path */ vp = p + 1; /* then we want only the last part */ } else vp = "vi"; for (vpl = 0; vp[vpl] && !isspace((unsigned char)vp[vpl]); vpl++) continue; for (epl = 0; ep[epl] && !isspace((unsigned char)ep[epl]); epl++) continue; } retp = NULL; for (pp = proclist.p_next; pp; pp = pp->p_next) if (pp->p_procid == pp->p_jobid) { /* * Only foreground an edit session if it is suspended. Some GUI * editors have may be happily running in a separate window, no * point in foregrounding these if they're already running - webb */ pstatus = (int) (pp->p_flags & PALLSTATES); if (pstatus != PINTERRUPTED && pstatus != PSTOPPED && pstatus != PSIGNALED) continue; p = short2str(pp->p_command); /* get the first word */ for (cp = p; *cp && !isspace((unsigned char) *cp); cp++) continue; *cp = '\0'; - + if ((cp = strrchr(p, '/')) != NULL) /* and it has a path */ cp = cp + 1; /* then we want only the last part */ else cp = p; /* else we get all of it */ /* * If we find the current name in the $editors array (if set) * or as $EDITOR or $VISUAL (if $editors not set), fg it. */ if ((vv && findvv(vv, cp)) || (epl && strncmp(ep, cp, epl) == 0 && cp[epl] == '\0') || (vpl && strncmp(vp, cp, vpl) == 0 && cp[vpl] == '\0')) { /* * If there is a choice, then choose the current process if * available, or the previous process otherwise, or else * anything will do - Robert Webb (robertw@mulga.cs.mu.oz.au). */ if (pp == pcurrent) return pp; else if (retp == NULL || pp == pprevious) retp = pp; } } return retp; /* Will be NULL if we didn't find a job */ } void fg_proc_entry(struct process *pp) { jmp_buf_t osetexit; int ohaderr; Char oGettingInput; size_t omark; getexit(osetexit); pintr_disabled++; oGettingInput = GettingInput; GettingInput = 0; ohaderr = haderr; /* we need to ignore setting of haderr due to * process getting stopped by a signal */ omark = cleanup_push_mark(); if (setexit() == 0) { /* come back here after pjwait */ pendjob(); (void) alarm(0); /* No autologout */ alrmcatch_disabled = 1; if (!pstart(pp, 1)) { pp->p_procid = 0; stderror(ERR_BADJOB, pp->p_command, strerror(errno)); } pjwait(pp); } setalarm(1); /* Autologout back on */ cleanup_pop_mark(omark); resexit(osetexit); haderr = ohaderr; GettingInput = oGettingInput; disabled_cleanup(&pintr_disabled); } static char * xgetpass(const char *prm) { static struct strbuf pass; /* = strbuf_INIT; */ int fd; sigset_t oset, set; struct sigaction sa, osa; sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; (void)sigaction(SIGINT, &sa, &osa); sigemptyset(&set); sigaddset(&set, SIGINT); (void)sigprocmask(SIG_UNBLOCK, &set, &oset); cleanup_push(&osa, sigint_cleanup); cleanup_push(&oset, sigprocmask_cleanup); (void) Rawmode(); /* Make sure, cause we want echo off */ fd = xopen("/dev/tty", O_RDWR|O_LARGEFILE); if (fd == -1) fd = SHIN; else cleanup_push(&fd, open_cleanup); xprintf("%s", prm); flush(); pass.len = 0; for (;;) { char c; - if (xread(fd, &c, 1) < 1 || c == '\n') + if (xread(fd, &c, 1) < 1 || c == '\n') break; strbuf_append1(&pass, c); } strbuf_terminate(&pass); cleanup_until(&osa); return pass.s; } #ifndef NO_CRYPT #if !HAVE_DECL_CRYPT extern char *crypt (); #endif #ifdef HAVE_CRYPT_H #include #endif #endif /* * Ask the user for his login password to continue working - * On systems that have a shadow password, this will only + * On systems that have a shadow password, this will only * work for root, but what can we do? * * If we fail to get the password, then we log the user out * immediately */ /*ARGSUSED*/ static void auto_lock(void) { #ifndef NO_CRYPT int i; char *srpp = NULL; struct passwd *pw; #undef XCRYPT #if defined(HAVE_AUTH_H) && defined(HAVE_GETAUTHUID) struct authorization *apw; extern char *crypt16 (const char *, const char *); # define XCRYPT(pw, a, b) crypt16(a, b) if ((pw = xgetpwuid(euid)) != NULL && /* effective user passwd */ (apw = getauthuid(euid)) != NULL) /* enhanced ultrix passwd */ srpp = apw->a_password; #elif defined(HAVE_SHADOW_H) struct spwd *spw; # define XCRYPT(pw, a, b) crypt(a, b) if ((pw = xgetpwuid(euid)) != NULL) { /* effective user passwd */ errno = 0; while ((spw = getspnam(pw->pw_name)) == NULL && errno == EINTR) { handle_pending_signals(); errno = 0; } if (spw != NULL) /* shadowed passwd */ srpp = spw->sp_pwdp; } #else #ifdef __CYGWIN__ # define XCRYPT(pw, a, b) cygwin_xcrypt(pw, a, b) #else # define XCRYPT(pw, a, b) crypt(a, b) #endif #if !defined(__MVS__) if ((pw = xgetpwuid(euid)) != NULL) /* effective user passwd */ srpp = pw->pw_passwd; #endif /* !MVS */ #endif if (srpp == NULL) { auto_logout(); /*NOTREACHED*/ return; } setalarm(0); /* Not for locking any more */ xputchar('\n'); for (i = 0; i < 5; i++) { const char *crpp; char *pp; #ifdef AFS char *afsname; Char *safs; if ((safs = varval(STRafsuser)) != STRNULL) afsname = short2str(safs); else if ((afsname = getenv("AFSUSER")) == NULL) afsname = pw->pw_name; #endif pp = xgetpass("Password:"); crpp = XCRYPT(pw, pp, srpp); if ((crpp && strcmp(crpp, srpp) == 0) #ifdef AFS || (ka_UserAuthenticateGeneral(KA_USERAUTH_VERSION, afsname, /* name */ NULL, /* instance */ NULL, /* realm */ pp, /* password */ 0, /* lifetime */ 0, 0, /* spare */ NULL) /* reason */ == 0) #endif /* AFS */ ) { (void) memset(pp, 0, strlen(pp)); if (GettingInput && !just_signaled) { (void) Rawmode(); ClearLines(); ClearDisp(); Refresh(); } just_signaled = 0; return; } xprintf(CGETS(22, 2, "\nIncorrect passwd for %s\n"), pw->pw_name); } #endif /* NO_CRYPT */ auto_logout(); } static void auto_logout(void) { xprintf("auto-logout\n"); /* Don't leave the tty in raw mode */ if (editing) (void) Cookedmode(); xclose(SHIN); setcopy(STRlogout, STRautomatic, VAR_READWRITE); child = 1; #ifdef TESLA do_logout = 1; #endif /* TESLA */ GettingInput = FALSE; /* make flush() work to write hist files. Huber*/ goodbye(NULL, NULL); } void alrmcatch(void) { (*alm_fun)(); setalarm(1); } /* * Karl Kleinpaste, 21oct1983. * Added precmd(), which checks for the alias * precmd in aliases. If it's there, the alias * is executed as a command. This is done * after mailchk() and just before print- * ing the prompt. Useful for things like printing * one's current directory just before each command. */ void precmd(void) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); if (precmd_active) { /* an error must have been caught */ aliasrun(2, STRunalias, STRprecmd); xprintf("%s", CGETS(22, 3, "Faulty alias 'precmd' removed.\n")); goto leave; } precmd_active = 1; if (!whyles && adrof1(STRprecmd, &aliases)) aliasrun(1, STRprecmd, NULL); leave: precmd_active = 0; cleanup_until(&pintr_disabled); } void postcmd(void) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); if (postcmd_active) { /* an error must have been caught */ aliasrun(2, STRunalias, STRpostcmd); xprintf("%s", CGETS(22, 3, "Faulty alias 'postcmd' removed.\n")); goto leave; } postcmd_active = 1; if (!whyles && adrof1(STRpostcmd, &aliases)) aliasrun(1, STRpostcmd, NULL); leave: postcmd_active = 0; cleanup_until(&pintr_disabled); } /* * Paul Placeway 11/24/87 Added cwd_cmd by hacking precmd() into * submission... Run every time $cwd is set (after it is set). Useful * for putting your machine and cwd (or anything else) in an xterm title * space. */ void cwd_cmd(void) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); if (cwdcmd_active) { /* an error must have been caught */ aliasrun(2, STRunalias, STRcwdcmd); xprintf("%s", CGETS(22, 4, "Faulty alias 'cwdcmd' removed.\n")); goto leave; } cwdcmd_active = 1; if (!whyles && adrof1(STRcwdcmd, &aliases)) aliasrun(1, STRcwdcmd, NULL); leave: cwdcmd_active = 0; cleanup_until(&pintr_disabled); } /* - * Joachim Hoenig 07/16/91 Added beep_cmd, run every time tcsh wishes + * Joachim Hoenig 07/16/91 Added beep_cmd, run every time tcsh wishes * to beep the terminal bell. Useful for playing nice sounds instead. */ void beep_cmd(void) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); if (beepcmd_active) { /* an error must have been caught */ aliasrun(2, STRunalias, STRbeepcmd); xprintf("%s", CGETS(22, 5, "Faulty alias 'beepcmd' removed.\n")); goto leave; } beepcmd_active = 1; if (!whyles && adrof1(STRbeepcmd, &aliases)) aliasrun(1, STRbeepcmd, NULL); leave: beepcmd_active = 0; cleanup_until(&pintr_disabled); } /* * Karl Kleinpaste, 18 Jan 1984. * Added period_cmd(), which executes the alias "periodic" every * $tperiod minutes. Useful for occasional checking of msgs and such. */ void period_cmd(void) { Char *vp; time_t t, interval; if (whyles) return; pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); if (periodic_active) { /* an error must have been caught */ aliasrun(2, STRunalias, STRperiodic); xprintf("%s", CGETS(22, 6, "Faulty alias 'periodic' removed.\n")); goto leave; } periodic_active = 1; if (!whyles && adrof1(STRperiodic, &aliases)) { vp = varval(STRtperiod); if (vp == STRNULL) { aliasrun(1, STRperiodic, NULL); goto leave; } interval = getn(vp); (void) time(&t); if (t - t_period >= interval * 60) { t_period = t; aliasrun(1, STRperiodic, NULL); } } leave: periodic_active = 0; cleanup_until(&pintr_disabled); } -/* +/* * GrP Greg Parker May 2001 - * Added job_cmd(), which is run every time a job is started or - * foregrounded. The command is passed a single argument, the string - * used to start the job originally. With precmd, useful for setting + * Added job_cmd(), which is run every time a job is started or + * foregrounded. The command is passed a single argument, the string + * used to start the job originally. With precmd, useful for setting * xterm titles. * Cloned from cwd_cmd(). */ void job_cmd(Char *args) { if (whyles) return; pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); if (jobcmd_active) { /* an error must have been caught */ aliasrun(2, STRunalias, STRjobcmd); xprintf("%s", CGETS(22, 14, "Faulty alias 'jobcmd' removed.\n")); goto leave; } jobcmd_active = 1; if (!whyles && adrof1(STRjobcmd, &aliases)) { struct process *pp = pcurrjob; /* put things back after the hook */ aliasrun(2, STRjobcmd, args); pcurrjob = pp; } leave: jobcmd_active = 0; cleanup_until(&pintr_disabled); } /* * Karl Kleinpaste, 21oct1983. * Set up a one-word alias command, for use for special things. * This code is based on the mainline of process(). */ void aliasrun(int cnt, Char *s1, Char *s2) { struct wordent w, *new1, *new2; /* for holding alias name */ struct command *t = NULL; jmp_buf_t osetexit; int status; size_t omark; getexit(osetexit); if (seterr) { xfree(seterr); seterr = NULL; /* don't repeatedly print err msg. */ } w.word = STRNULL; new1 = xcalloc(1, sizeof w); new1->word = Strsave(s1); if (cnt == 1) { /* build a lex list with one word. */ w.next = w.prev = new1; new1->next = new1->prev = &w; } else { /* build a lex list with two words. */ new2 = xcalloc(1, sizeof w); new2->word = Strsave(s2); w.next = new2->prev = new1; new1->next = w.prev = new2; new1->prev = new2->next = &w; } cleanup_push(&w, lex_cleanup); /* Save the old status */ status = getn(varval(STRstatus)); /* expand aliases like process() does. */ alias(&w); /* build a syntax tree for the command. */ t = syntax(w.next, &w, 0); cleanup_push(t, syntax_cleanup); if (seterr) stderror(ERR_OLD); psavejob(); cleanup_push(&cnt, psavejob_cleanup); /* cnt is used only as a marker */ /* catch any errors here */ omark = cleanup_push_mark(); if (setexit() == 0) /* execute the parse tree. */ /* * From: Michael Schroeder * was execute(t, tpgrp); */ execute(t, tpgrp > 0 ? tpgrp : -1, NULL, NULL, TRUE); /* reset the error catcher to the old place */ cleanup_pop_mark(omark); resexit(osetexit); if (haderr) { haderr = 0; /* * Either precmd, or cwdcmd, or periodic had an error. Call it again so * that it is removed */ if (precmd_active) precmd(); if (postcmd_active) postcmd(); #ifdef notdef /* * XXX: On the other hand, just interrupting them causes an error too. * So if we hit ^C in the middle of cwdcmd or periodic the alias gets * removed. We don't want that. Note that we want to remove precmd * though, cause that could lead into an infinite loop. This should be * fixed correctly, but then haderr should give us the whole exit * status not just true or false. */ else if (cwdcmd_active) cwd_cmd(); else if (beepcmd_active) beep_cmd(); else if (periodic_active) period_cmd(); #endif /* notdef */ } cleanup_until(&w); pendjob(); /* Restore status */ setv(STRstatus, putn((tcsh_number_t)status), VAR_READWRITE); } void setalarm(int lck) { struct varent *vp; Char *cp; unsigned alrm_time = 0, logout_time, lock_time; time_t cl, nl, sched_dif; if ((vp = adrof(STRautologout)) != NULL && vp->vec != NULL) { if ((cp = vp->vec[0]) != 0) { if ((logout_time = (unsigned) atoi(short2str(cp)) * 60) > 0) { #ifdef SOLARIS2 /* * Solaris alarm(2) uses a timer based in clock ticks * internally so it multiplies our value with CLK_TCK... * Of course that can overflow leading to unexpected * results, so we clip it here. Grr. Where is that * documented folks? */ if (logout_time >= 0x7fffffff / CLK_TCK) logout_time = 0x7fffffff / CLK_TCK; #endif /* SOLARIS2 */ alrm_time = logout_time; alm_fun = auto_logout; } } if ((cp = vp->vec[1]) != 0) { if ((lock_time = (unsigned) atoi(short2str(cp)) * 60) > 0) { if (lck) { if (alrm_time == 0 || lock_time < alrm_time) { alrm_time = lock_time; alm_fun = auto_lock; } } else /* lock_time always < alrm_time */ if (alrm_time) alrm_time -= lock_time; } } } if ((nl = sched_next()) != -1) { (void) time(&cl); sched_dif = nl > cl ? nl - cl : 0; if ((alrm_time == 0) || ((unsigned) sched_dif < alrm_time)) { alrm_time = ((unsigned) sched_dif) + 1; alm_fun = sched_run; } } alrmcatch_disabled = 0; (void) alarm(alrm_time); /* Autologout ON */ } #undef RMDEBUG /* For now... */ void rmstar(struct wordent *cp) { struct wordent *we, *args; struct wordent *tmp, *del; #ifdef RMDEBUG static Char STRrmdebug[] = {'r', 'm', 'd', 'e', 'b', 'u', 'g', '\0'}; Char *tag; #endif /* RMDEBUG */ Char *charac; int ask, doit, star = 0, silent = 0, opintr_disabled; if (!adrof(STRrmstar)) return; #ifdef RMDEBUG tag = varval(STRrmdebug); #endif /* RMDEBUG */ we = cp->next; while (*we->word == ';' && we != cp) we = we->next; opintr_disabled = pintr_disabled; pintr_disabled = 0; while (we != cp) { Char *cmd = we->word; if (cmd[0] == STRQNULL[0]) cmd++; #ifdef RMDEBUG if (*tag) xprintf(CGETS(22, 7, "parsing command line [%S]\n"), cmd); #endif /* RMDEBUG */ if (!StrQcmp(cmd, STRrm)) { args = we->next; ask = (*args->word != '-'); while (*args->word == '-' && !silent) { /* check options */ for (charac = (args->word + 1); *charac && !silent; charac++) silent = (*charac == 'i' || *charac == 'f'); args = args->next; } ask = (ask || (!ask && !silent)); if (ask) { for (; !star && *args->word != ';' && args != cp; args = args->next) if (!Strcmp(args->word, STRstar)) star = 1; if (ask && star) { doit = getYN(CGETS(22, 8, "Do you really want to delete all files? [N/y] ")); if (!doit) { /* remove the command instead */ #ifdef RMDEBUG if (*tag) xprintf(CGETS(22, 9, "skipping deletion of files!\n")); #endif /* RMDEBUG */ for (tmp = we; *tmp->word != '\n' && *tmp->word != ';' && tmp != cp;) { tmp->prev->next = tmp->next; tmp->next->prev = tmp->prev; xfree(tmp->word); del = tmp; tmp = tmp->next; xfree(del); } if (*tmp->word == ';') { tmp->prev->next = tmp->next; tmp->next->prev = tmp->prev; xfree(tmp->word); del = tmp; tmp = tmp->next; xfree(del); } we = tmp; continue; } } } } for (we = we->next; *we->word != ';' && we != cp; we = we->next) continue; if (*we->word == ';') we = we->next; } #ifdef RMDEBUG if (*tag) { xprintf(CGETS(22, 10, "command line now is:\n")); for (we = cp->next; we != cp; we = we->next) xprintf("[%S] ", we->word); } #endif /* RMDEBUG */ pintr_disabled = opintr_disabled; return; } #ifdef BSDJOBS /* Check if command is in continue list and do a "aliasing" if it exists as a job in background */ #undef CNDEBUG /* For now */ void continue_jobs(struct wordent *cp) { struct wordent *we; struct process *pp, *np; Char *cmd, *continue_list, *continue_args_list; #ifdef CNDEBUG Char *tag; static Char STRcndebug[] = {'c', 'n', 'd', 'e', 'b', 'u', 'g', '\0'}; #endif /* CNDEBUG */ int in_cont_list, in_cont_arg_list; #ifdef CNDEBUG tag = varval(STRcndebug); #endif /* CNDEBUG */ continue_list = varval(STRcontinue); continue_args_list = varval(STRcontinue_args); if (*continue_list == '\0' && *continue_args_list == '\0') return; we = cp->next; while (*we->word == ';' && we != cp) we = we->next; while (we != cp) { #ifdef CNDEBUG if (*tag) xprintf(CGETS(22, 11, "parsing command line\n")); #endif /* CNDEBUG */ cmd = we->word; in_cont_list = inlist(continue_list, cmd); in_cont_arg_list = inlist(continue_args_list, cmd); if (in_cont_list || in_cont_arg_list) { #ifdef CNDEBUG if (*tag) xprintf(CGETS(22, 12, "in one of the lists\n")); #endif /* CNDEBUG */ np = NULL; for (pp = proclist.p_next; pp; pp = pp->p_next) { if (prefix(cmd, pp->p_command)) { if (pp->p_index) { np = pp; break; } } } if (np) { insert(we, in_cont_arg_list); } } for (we = we->next; *we->word != ';' && we != cp; we = we->next) continue; if (*we->word == ';') we = we->next; } #ifdef CNDEBUG if (*tag) { xprintf(CGETS(22, 13, "command line now is:\n")); for (we = cp->next; we != cp; we = we->next) xprintf("%S ", we->word); } #endif /* CNDEBUG */ return; } /* The actual "aliasing" of for backgrounds() is done here with the aid of insert_we(). */ static void insert(struct wordent *pl, int file_args) { struct wordent *now, *last; Char *cmd, *bcmd, *cp1, *cp2; size_t cmd_len; Char *upause = STRunderpause; size_t p_len = Strlen(upause); cmd_len = Strlen(pl->word); cmd = xcalloc(1, (cmd_len + 1) * sizeof(Char)); (void) Strcpy(cmd, pl->word); /* Do insertions at beginning, first replace command word */ if (file_args) { now = pl; xfree(now->word); now->word = xcalloc(1, 5 * sizeof(Char)); (void) Strcpy(now->word, STRecho); now = xcalloc(1, sizeof(struct wordent)); now->word = xcalloc(1, 6 * sizeof(Char)); (void) Strcpy(now->word, STRbackqpwd); insert_we(now, pl); for (last = now; *last->word != '\n' && *last->word != ';'; last = last->next) continue; now = xcalloc(1, sizeof(struct wordent)); now->word = xcalloc(1, 2 * sizeof(Char)); (void) Strcpy(now->word, STRgt); insert_we(now, last->prev); now = xcalloc(1, sizeof(struct wordent)); now->word = xcalloc(1, 2 * sizeof(Char)); (void) Strcpy(now->word, STRbang); insert_we(now, last->prev); now = xcalloc(1, sizeof(struct wordent)); now->word = xcalloc(1, (cmd_len + p_len + 4) * sizeof(Char)); cp1 = now->word; cp2 = cmd; *cp1++ = '~'; *cp1++ = '/'; *cp1++ = '.'; while ((*cp1++ = *cp2++) != '\0') continue; cp1--; cp2 = upause; while ((*cp1++ = *cp2++) != '\0') continue; insert_we(now, last->prev); now = xcalloc(1, sizeof(struct wordent)); now->word = xcalloc(1, 2 * sizeof(Char)); (void) Strcpy(now->word, STRsemi); insert_we(now, last->prev); bcmd = xcalloc(1, (cmd_len + 2) * sizeof(Char)); *bcmd = '%'; Strcpy(bcmd + 1, cmd); now = xcalloc(1, sizeof(struct wordent)); now->word = bcmd; insert_we(now, last->prev); } else { struct wordent *del; now = pl; xfree(now->word); now->word = xcalloc(1, (cmd_len + 2) * sizeof(Char)); *now->word = '%'; Strcpy(now->word + 1, cmd); for (now = now->next; *now->word != '\n' && *now->word != ';' && now != pl;) { now->prev->next = now->next; now->next->prev = now->prev; xfree(now->word); del = now; now = now->next; xfree(del); } } } static void insert_we(struct wordent *new, struct wordent *where) { new->prev = where; new->next = where->next; where->next = new; new->next->prev = new; } static int inlist(Char *list, Char *name) { Char *l, *n; l = list; n = name; while (*l && *n) { if (*l == *n) { l++; n++; if (*n == '\0' && (*l == ' ' || *l == '\0')) return (1); else continue; } else { while (*l && *l != ' ') l++; /* skip to blank */ while (*l && *l == ' ') l++; /* and find first nonblank character */ n = name; } } return (0); } #endif /* BSDJOBS */ /* * Implement a small cache for tilde names. This is used primarily * to expand tilde names to directories, but also * we can find users from their home directories for the tilde * prompt, on machines where yp lookup is slow this can be a big win... * As with any cache this can run out of sync, rehash can sync it again. */ static struct tildecache { Char *user; Char *home; size_t hlen; } *tcache = NULL; #define TILINCR 10 size_t tlength = 0; static size_t tsize = TILINCR; static int tildecompare(const void *xp1, const void *xp2) { const struct tildecache *p1, *p2; p1 = xp1; p2 = xp2; return Strcmp(p1->user, p2->user); } static Char * gethomedir(const Char *us) { struct passwd *pp; #ifdef HESIOD char **res, **res1, *cp; Char *rp; #endif /* HESIOD */ - + pp = xgetpwnam(short2str(us)); #ifdef YPBUGS fix_yp_bugs(); #endif /* YPBUGS */ if (pp != NULL) { #if 0 /* Don't return if root */ if (pp->pw_dir[0] == '/' && pp->pw_dir[1] == '\0') return NULL; else #endif return Strsave(str2short(pp->pw_dir)); } #ifdef HESIOD res = hes_resolve(short2str(us), "filsys"); rp = NULL; if (res != NULL) { if ((*res) != NULL) { /* * Look at the first token to determine how to interpret * the rest of it. * Yes, strtok is evil (it's not thread-safe), but it's also * easy to use. */ cp = strtok(*res, " "); if (strcmp(cp, "AFS") == 0) { /* next token is AFS pathname.. */ cp = strtok(NULL, " "); if (cp != NULL) rp = Strsave(str2short(cp)); } else if (strcmp(cp, "NFS") == 0) { cp = NULL; if ((strtok(NULL, " ")) && /* skip remote pathname */ (strtok(NULL, " ")) && /* skip host */ (strtok(NULL, " ")) && /* skip mode */ (cp = strtok(NULL, " "))) { rp = Strsave(str2short(cp)); } } } for (res1 = res; *res1; res1++) free(*res1); #if 0 /* Don't return if root */ if (rp != NULL && rp[0] == '/' && rp[1] == '\0') { xfree(rp); rp = NULL; } #endif return rp; } #endif /* HESIOD */ return NULL; } Char * gettilde(const Char *us) { struct tildecache *bp1, *bp2, *bp; Char *hd; /* Ignore NIS special names */ if (*us == '+' || *us == '-') return NULL; if (tcache == NULL) tcache = xmalloc(TILINCR * sizeof(struct tildecache)); /* * Binary search */ for (bp1 = tcache, bp2 = tcache + tlength; bp1 < bp2;) { int i; bp = bp1 + ((bp2 - bp1) >> 1); if ((i = *us - *bp->user) == 0 && (i = Strcmp(us, bp->user)) == 0) return (bp->home); if (i < 0) bp2 = bp; else bp1 = bp + 1; } /* * Not in the cache, try to get it from the passwd file */ hd = gethomedir(us); if (hd == NULL) return NULL; /* * Update the cache */ tcache[tlength].user = Strsave(us); tcache[tlength].home = hd; tcache[tlength++].hlen = Strlen(hd); qsort(tcache, tlength, sizeof(struct tildecache), tildecompare); if (tlength == tsize) { tsize += TILINCR; tcache = xrealloc(tcache, tsize * sizeof(struct tildecache)); } return (hd); } /* * Return the username if the directory path passed contains a * user's home directory in the tilde cache, otherwise return NULL * hm points to the place where the path became different. * Special case: Our own home directory. * If we are passed a null pointer, then we flush the cache. */ Char * getusername(Char **hm) { Char *h, *p; size_t i, j; if (hm == NULL) { for (i = 0; i < tlength; i++) { xfree(tcache[i].home); xfree(tcache[i].user); } xfree(tcache); tlength = 0; tsize = TILINCR; tcache = NULL; return NULL; } p = *hm; if (((h = varval(STRhome)) != STRNULL) && (Strncmp(p, h, j = Strlen(h)) == 0) && (p[j] == '/' || p[j] == '\0')) { *hm = &p[j]; return STRNULL; } for (i = 0; i < tlength; i++) if ((Strncmp(p, tcache[i].home, (j = tcache[i].hlen)) == 0) && (p[j] == '/' || p[j] == '\0')) { *hm = &p[j]; return tcache[i].user; } return NULL; } /* * set the shell-level var to 1 or apply change to it. */ void shlvl(int val) { char *cp; if ((cp = getenv("SHLVL")) != NULL) { if (loginsh) val = 1; else val += atoi(cp); if (val <= 0) { if (adrof(STRshlvl) != NULL) unsetv(STRshlvl); Unsetenv(STRKSHLVL); } else { Char *p; p = Itoa(val, 0, 0); cleanup_push(p, xfree); setv(STRshlvl, p, VAR_READWRITE); cleanup_ignore(p); cleanup_until(p); tsetenv(STRKSHLVL, p); } } else { setcopy(STRshlvl, STR1, VAR_READWRITE); tsetenv(STRKSHLVL, STR1); } } /* fixio(): * Try to recover from a read error */ int fixio(int fd, int e) { switch (e) { case -1: /* Make sure that the code is reachable */ #ifdef EWOULDBLOCK case EWOULDBLOCK: # define FDRETRY #endif /* EWOULDBLOCK */ #if defined(POSIX) && defined(EAGAIN) # if !defined(EWOULDBLOCK) || EWOULDBLOCK != EAGAIN case EAGAIN: # define FDRETRY # endif /* !EWOULDBLOCK || EWOULDBLOCK != EAGAIN */ #endif /* POSIX && EAGAIN */ e = -1; #ifdef FDRETRY # ifdef F_SETFL /* * Great! we have on suns 3 flavors and 5 names... * I hope that will cover everything. * I added some more defines... many systems have different defines. * Rather than dealing with getting the right includes, we'll just * cover all the known possibilities here. -- sterling@netcom.com */ # ifndef O_NONBLOCK # define O_NONBLOCK 0 # endif /* O_NONBLOCK */ # ifndef O_NDELAY # define O_NDELAY 0 # endif /* O_NDELAY */ # ifndef FNBIO # define FNBIO 0 # endif /* FNBIO */ # ifndef _FNBIO # define _FNBIO 0 # endif /* _FNBIO */ # ifndef FNONBIO # define FNONBIO 0 # endif /* FNONBIO */ # ifndef FNONBLOCK # define FNONBLOCK 0 # endif /* FNONBLOCK */ # ifndef _FNONBLOCK # define _FNONBLOCK 0 # endif /* _FNONBLOCK */ # ifndef FNDELAY # define FNDELAY 0 # endif /* FNDELAY */ # ifndef _FNDELAY # define _FNDELAY 0 # endif /* _FNDELAY */ # ifndef FNDLEAY /* Some linux versions have this typo */ # define FNDLEAY 0 # endif /* FNDLEAY */ if ((e = fcntl(fd, F_GETFL, 0)) == -1) return -1; e &= ~(O_NDELAY|O_NONBLOCK|FNBIO|_FNBIO|FNONBIO|FNONBLOCK|_FNONBLOCK| FNDELAY|_FNDELAY|FNDLEAY); /* whew! */ if (fcntl(fd, F_SETFL, e) == -1) return -1; - else + else e = 0; # endif /* F_SETFL */ # ifdef FIONBIO e = 0; if (ioctl(fd, FIONBIO, (ioctl_t) &e) == -1) return -1; # endif /* FIONBIO */ #endif /* FDRETRY */ return e; case EINTR: return 0; default: return -1; } } /* collate(): * String collation */ int collate(const Char *a, const Char *b) { int rv; #ifdef SHORT_STRINGS /* This strips the quote bit as a side effect */ char *sa = strsave(short2str(a)); char *sb = strsave(short2str(b)); #else char *sa = strip(strsave(a)); char *sb = strip(strsave(b)); #endif /* SHORT_STRINGS */ #if defined(NLS) && defined(HAVE_STRCOLL) errno = 0; /* strcoll sets errno, another brain-damage */ rv = strcoll(sa, sb); /* * We should be checking for errno != 0, but some systems - * forget to reset errno to 0. So we only check for the + * forget to reset errno to 0. So we only check for the * only documented valid errno value for strcoll [EINVAL] */ if (errno == EINVAL) { xfree(sa); xfree(sb); stderror(ERR_SYSTEM, "strcoll", strerror(errno)); } #else rv = strcmp(sa, sb); #endif /* NLS && HAVE_STRCOLL */ xfree(sa); xfree(sb); return rv; } #ifdef HASHBANG /* * From: peter@zeus.dialix.oz.au (Peter Wemm) * If exec() fails look first for a #! [word] [word] .... * If it is, splice the header into the argument list and retry. */ #define HACKBUFSZ 1024 /* Max chars in #! vector */ int hashbang(int fd, Char ***vp) { struct blk_buf sarg = BLK_BUF_INIT; char lbuf[HACKBUFSZ], *p, *ws; #ifdef WINNT_NATIVE int fw = 0; /* found at least one word */ int first_word = 1; char *real; #endif /* WINNT_NATIVE */ if (xread(fd, lbuf, HACKBUFSZ) <= 0) return -1; ws = 0; /* word started = 0 */ for (p = lbuf; p < &lbuf[HACKBUFSZ]; ) { switch (*p) { case ' ': case '\t': #if defined(WINNT_NATIVE) || defined (__CYGWIN__) case '\r': #endif /* WINNT_NATIVE || __CYGWIN__ */ if (ws) { /* a blank after a word.. save it */ *p = '\0'; #ifdef WINNT_NATIVE if (first_word) { real = hb_subst(ws); if (real != NULL) ws = real; } fw = 1; first_word = 0; #endif /* WINNT_NATIVE */ bb_append(&sarg, SAVE(ws)); ws = NULL; } p++; continue; case '\0': /* Whoa!! what the hell happened */ goto err; case '\n': /* The end of the line. */ if ( #ifdef WINNT_NATIVE fw || #endif /* WINNT_NATIVE */ ws) { /* terminate the last word */ *p = '\0'; #ifdef WINNT_NATIVE /* deal with the 1-word case */ if (first_word) { real = hb_subst(ws); if (real != NULL) ws = real; } #endif /* !WINNT_NATIVE */ if (ws) bb_append(&sarg, SAVE(ws)); } if (sarg.len > 0) { *vp = bb_finish(&sarg); return 0; } else goto err; default: if (!ws) /* Start a new word? */ - ws = p; + ws = p; p++; break; } } err: bb_cleanup(&sarg); return -1; } #endif /* HASHBANG */ #ifdef REMOTEHOST static void palarm(int snum) { USE(snum); _exit(1); } static void getremotehost(int dest_fd) { const char *host = NULL; #ifdef INET6 struct sockaddr_storage saddr; static char hbuf[NI_MAXHOST]; #else struct hostent* hp; struct sockaddr_in saddr; #endif socklen_t len = sizeof(saddr); #ifdef INET6 if (getpeername(SHIN, (struct sockaddr *) &saddr, &len) != -1 && (saddr.ss_family == AF_INET6 || saddr.ss_family == AF_INET)) { int flag = NI_NUMERICHOST; #ifdef NI_WITHSCOPEID flag |= NI_WITHSCOPEID; #endif getnameinfo((struct sockaddr *)&saddr, len, hbuf, sizeof(hbuf), NULL, 0, flag); host = hbuf; #else if (getpeername(SHIN, (struct sockaddr *) &saddr, &len) != -1 && saddr.sin_family == AF_INET) { #if 0 if ((hp = gethostbyaddr((char *)&saddr.sin_addr, sizeof(struct in_addr), AF_INET)) != NULL) host = hp->h_name; else #endif host = inet_ntoa(saddr.sin_addr); #endif } #ifdef HAVE_STRUCT_UTMP_UT_HOST else { char *ptr; char *name = utmphost(); /* Avoid empty names and local X displays */ if (name != NULL && *name != '\0' && *name != ':') { struct in_addr addr; char *sptr; /* Look for host:display.screen */ /* * There is conflict with IPv6 address and X DISPLAY. So, * we assume there is no IPv6 address in utmp and don't * touch here. */ if ((sptr = strchr(name, ':')) != NULL) *sptr = '\0'; /* Leave IPv4 address as is */ /* * we use inet_addr here, not inet_aton because many systems * have not caught up yet. */ addr.s_addr = inet_addr(name); if (addr.s_addr != (unsigned int)~0) host = name; else { if (sptr != name) { #ifdef INET6 char *s, *domain; char dbuf[MAXHOSTNAMELEN]; struct addrinfo hints, *res = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE | AI_CANONNAME; if (strlen(name) < utmphostsize()) { if (getaddrinfo(name, NULL, &hints, &res) != 0) res = NULL; } else if (gethostname(dbuf, sizeof(dbuf)) == 0 && (dbuf[sizeof(dbuf)-1] = '\0', /*FIXME: ugly*/ (domain = strchr(dbuf, '.')) != NULL)) { for (s = strchr(name, '.'); s != NULL; s = strchr(s + 1, '.')) { if (*(s + 1) != '\0' && (ptr = strstr(domain, s)) != NULL) { char *cbuf; cbuf = strspl(name, ptr + strlen(s)); if (getaddrinfo(cbuf, NULL, &hints, &res) != 0) res = NULL; xfree(cbuf); break; } } } if (res != NULL) { if (res->ai_canonname != NULL) { strncpy(hbuf, res->ai_canonname, sizeof(hbuf)); hbuf[sizeof(hbuf) - 1] = '\0'; host = hbuf; } freeaddrinfo(res); } #else if ((hp = gethostbyname(name)) == NULL) { /* Try again eliminating the trailing domain */ if ((ptr = strchr(name, '.')) != NULL) { *ptr = '\0'; if ((hp = gethostbyname(name)) != NULL) host = hp->h_name; *ptr = '.'; } } else host = hp->h_name; #endif } } } } #endif if (host) { size_t left; left = strlen(host); while (left != 0) { ssize_t res; res = xwrite(dest_fd, host, left); if (res < 0) _exit(1); host += res; left -= res; } } _exit(0); } /* * From: (Lennart Svensson) */ void remotehost(void) { struct sigaction sa; struct strbuf hostname = strbuf_INIT; int fds[2], wait_options, status; pid_t pid, wait_res; sa.sa_handler = SIG_DFL; /* Make sure a zombie is created */ sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGCHLD, &sa, NULL); mypipe(fds); pid = fork(); if (pid == 0) { sigset_t set; xclose(fds[0]); /* Don't get stuck if the resolver does not work! */ signal(SIGALRM, palarm); sigemptyset(&set); sigaddset(&set, SIGALRM); (void)sigprocmask(SIG_UNBLOCK, &set, NULL); (void)alarm(2); getremotehost(fds[1]); /*NOTREACHED*/ } xclose(fds[1]); for (;;) { char buf[BUFSIZE]; ssize_t res; res = xread(fds[0], buf, sizeof(buf)); if (res == -1) { hostname.len = 0; wait_options = WNOHANG; goto done; } if (res == 0) break; strbuf_appendn(&hostname, buf, res); } wait_options = 0; done: cleanup_push(&hostname, strbuf_cleanup); xclose(fds[0]); while ((wait_res = waitpid(pid, &status, wait_options)) == -1 && errno == EINTR) handle_pending_signals(); if (hostname.len > 0 && wait_res == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0) { strbuf_terminate(&hostname); tsetenv(STRREMOTEHOST, str2short(hostname.s)); } cleanup_until(&hostname); #ifdef YPBUGS /* From: casper@fwi.uva.nl (Casper H.S. Dik), for Solaris 2.3 */ fix_yp_bugs(); #endif /* YPBUGS */ } #endif /* REMOTEHOST */ #ifndef WINNT_NATIVE /* * indicate if a terminal type is defined in terminfo/termcap * (by default the current term type). This allows ppl to look * for a working term type automatically in their login scripts * when using a terminal known as different things on different * platforms */ void dotermname(Char **v, struct command *c) { char *termtype; /* * Maximum size of a termcap record. We make it twice as large. */ char termcap_buffer[2048]; USE(c); /* try to find which entry we should be looking for */ termtype = (v[1] == NULL ? getenv("TERM") : short2str(v[1])); if (termtype == NULL) { - /* no luck - the user didn't provide one and none is + /* no luck - the user didn't provide one and none is * specified in the environment */ setcopy(STRstatus, STR1, VAR_READWRITE); return; } /* - * we use the termcap function - if we are using terminfo we + * we use the termcap function - if we are using terminfo we * will end up with it's compatibility function * terminfo/termcap will be initialized with the new * type but we don't care because tcsh has cached all the things * it needs. */ if (tgetent(termcap_buffer, termtype) == 1) { xprintf("%s\n", termtype); setcopy(STRstatus, STR0, VAR_READWRITE); } else setcopy(STRstatus, STR1, VAR_READWRITE); } #endif /* WINNT_NATIVE */ diff --git a/contrib/tcsh/tc.os.c b/contrib/tcsh/tc.os.c index 3ec512245603..63a92de9ad0f 100644 --- a/contrib/tcsh/tc.os.c +++ b/contrib/tcsh/tc.os.c @@ -1,1599 +1,1599 @@ /* * tc.os.c: OS Dependent builtin functions */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "tw.h" #include "ed.h" #include "ed.defns.h" /* for the function names */ #include "sh.decls.h" #ifdef _UWIN #define TIOCGPGRP TIOCGETPGRP #define TIOCSPGRP TIOCSETPGRP #endif /*** *** MACH ***/ #ifdef MACH /* dosetpath -- setpath built-in command * ********************************************************************** * HISTORY * 08-May-88 Richard Draves (rpd) at Carnegie-Mellon University * Major changes to remove artificial limits on sizes and numbers * of paths. * ********************************************************************** */ #ifdef MACH static Char STRCPATH[] = {'C', 'P', 'A', 'T', 'H', '\0'}; static Char STRLPATH[] = {'L', 'P', 'A', 'T', 'H', '\0'}; static Char STRMPATH[] = {'M', 'P', 'A', 'T', 'H', '\0'}; # if EPATH static Char STREPATH[] = {'E', 'P', 'A', 'T', 'H', '\0'}; # endif #endif /* MACH */ -static Char *syspaths[] = {STRKPATH, STRCPATH, STRLPATH, STRMPATH, +static Char *syspaths[] = {STRKPATH, STRCPATH, STRLPATH, STRMPATH, #if EPATH STREPATH, #endif 0}; #define LOCALSYSPATH "/usr/local" /*ARGSUSED*/ void dosetpath(Char **arglist, struct command *c) { extern char *getenv(); Char **pathvars, **cmdargs; char **spaths, **cpaths, **cmds; char *tcp; unsigned int npaths, ncmds; int i, sysflag; pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); /* * setpath(3) uses stdio and we want 0, 1, 2 to work... */ if (!didfds) { (void) dcopy(SHIN, 0); (void) dcopy(SHOUT, 1); (void) dcopy(SHDIAG, 2); didfds = 1; } for (i = 1; arglist[i] && (arglist[i][0] != '-'); i++); npaths = i - 1; cmdargs = &arglist[i]; for (; arglist[i]; i++); ncmds = i - npaths - 1; if (npaths) { sysflag = 0; pathvars = &arglist[1]; } else { sysflag = 1; npaths = (sizeof syspaths / sizeof *syspaths) - 1; pathvars = syspaths; } /* note that npaths != 0 */ spaths = xmalloc(npaths * sizeof *spaths); setzero(spaths, npaths * sizeof *spaths); cpaths = xmalloc((npaths + 1) * sizeof *cpaths); setzero(cpaths, (npaths + 1) * sizeof *cpaths); cmds = xmalloc((ncmds + 1) * sizeof *cmds); setzero(cmds, (ncmds + 1) * sizeof *cmds); for (i = 0; i < npaths; i++) { char *val = getenv(short2str(pathvars[i])); if (val == NULL) val = ""; spaths[i] = xmalloc((Strlen(pathvars[i]) + strlen(val) + 2) * sizeof **spaths); (void) strcpy(spaths[i], short2str(pathvars[i])); (void) strcat(spaths[i], "="); (void) strcat(spaths[i], val); cpaths[i] = spaths[i]; } for (i = 0; i < ncmds; i++) { Char *val = globone(cmdargs[i], G_ERROR);/*FIXRESET*/ if (val == NULL) goto abortpath; cmds[i] = strsave(short2str(val)); } if (setpath(cpaths, cmds, LOCALSYSPATH, sysflag, 1) < 0) { abortpath: if (spaths) { for (i = 0; i < npaths; i++) xfree(spaths[i]); xfree(spaths); } xfree(cpaths); if (cmds) { for (i = 0; i < ncmds; i++) xfree(cmds[i]); xfree(cmds); } cleanup_until(&pintr_disabled); donefds(); return; } for (i = 0; i < npaths; i++) { Char *val, *name; name = str2short(cpaths[i]); for (val = str2short(cpaths[i]); val && *val && *val != '='; val++); if (val && *val == '=') { *val++ = '\0'; tsetenv(name, val);/*FIXRESET*/ if (Strcmp(name, STRKPATH) == 0) { importpath(val);/*FIXRESET*/ if (havhash) dohash(NULL, NULL);/*FIXRESET*/ } *--val = '='; } } cleanup_until(&pintr_disabled); donefds(); } #endif /* MACH */ /*** *** AIX ***/ #ifdef TCF /* ARGSUSED */ void dogetxvers(Char **v, struct command *c) { char xvers[MAXPATHLEN]; if (getxvers(xvers, MAXPATHLEN) == -1) stderror(ERR_SYSTEM, "getxvers", strerror(errno)); xprintf("%s\n", xvers); flush(); } /*ARGSUSED*/ void dosetxvers(Char **v, struct command *c) { char *xvers; ++v; if (!*v || *v[0] == '\0') xvers = ""; else xvers = short2str(*v); if (setxvers(xvers) == -1) stderror(ERR_SYSTEM, "setxvers", strerror(errno)); } #include #ifdef _AIXPS2 # define XC_PDP11 0x01 # define XC_23 0x02 # define XC_Z8K 0x03 # define XC_8086 0x04 # define XC_68K 0x05 # define XC_Z80 0x06 # define XC_VAX 0x07 # define XC_16032 0x08 # define XC_286 0x09 # define XC_386 0x0a # define XC_S370 0x0b #else # include #endif /* _AIXPS2 */ static struct xc_cpu_t { short xc_id; char *xc_name; } xcpu[] = { { XC_PDP11, "pdp11" }, { XC_23, "i370" }, { XC_Z8K, "z8000" }, { XC_8086, "i86" }, { XC_68K, "mc68000" }, { XC_Z80, "x80" }, { XC_VAX, "vax" }, { XC_16032, "ns16032" }, { XC_286, "i286" }, { XC_386, "i386" }, { XC_S370, "xa370" }, { 0, NULL } }; /* * our local hack table, stolen from x.out.h */ static char * getxcode(short xcid) { int i; for (i = 0; xcpu[i].xc_name != NULL; i++) if (xcpu[i].xc_id == xcid) return (xcpu[i].xc_name); return (NULL); } static short getxid(char *xcname) { int i; for (i = 0; xcpu[i].xc_name != NULL; i++) if (strcmp(xcpu[i].xc_name, xcname) == 0) return (xcpu[i].xc_id); return ((short) -1); } /*ARGSUSED*/ void dogetspath(Char **v, struct command *c) { int i, j; sitepath_t p[MAXSITE]; struct sf *st; static char *local = "LOCAL "; if ((j = getspath(p, MAXSITE)) == -1) stderror(ERR_SYSTEM, "getspath", strerror(errno)); for (i = 0; i < j && (p[i] & SPATH_CPU) != NOSITE; i++) { if (p[i] & SPATH_CPU) { if ((p[i] & SPATH_MASK) == NULLSITE) xprintf(local); else if ((st = sfxcode((short) (p[i] & SPATH_MASK))) != NULL) xprintf("%s ", st->sf_ctype); else { char *xc = getxcode(p[i] & SPATH_MASK); if (xc != NULL) xprintf("%s ", xc); else xprintf("*cpu %d* ", (int) (p[i] & SPATH_MASK)); - /* + /* * BUG in the aix code... needs that cause if - * sfxcode fails once it fails for ever + * sfxcode fails once it fails for ever */ - endsf(); + endsf(); } } else { if (p[i] == NULLSITE) xprintf(local); else if ((st = sfnum(p[i])) != NULL) xprintf("%s ", st->sf_sname); else xprintf("*site %d* ", (int) (p[i] & SPATH_MASK)); } } xputchar('\n'); flush(); } /*ARGSUSED*/ void dosetspath(Char **v, struct command *c) { int i; short j; char *s; sitepath_t p[MAXSITE]; struct sf *st; /* * sfname() on AIX G9.9 at least, mallocs too pointers p, q * then does the equivalent of while (*p++ == *q++) continue; * and then tries to free(p,q) them! Congrats to the wizard who * wrote that one. I bet he tested it really well too. * Sooo, we set dont_free :-) */ dont_free = 1; for (i = 0, v++; *v && *v[0] != '\0'; v++, i++) { s = short2str(*v); if (isdigit(*s)) p[i] = atoi(s); else if (strcmp(s, "LOCAL") == 0) p[i] = NULLSITE; else if ((st = sfctype(s)) != NULL) p[i] = SPATH_CPU | st->sf_ccode; else if ((j = getxid(s)) != -1) p[i] = SPATH_CPU | j; else if ((st = sfname(s)) != NULL) p[i] = st->sf_id; else { setname(s); stderror(ERR_NAME | ERR_STRING, CGETS(23, 1, "Bad cpu/site name")); } if (i == MAXSITE - 1) stderror(ERR_NAME | ERR_STRING, CGETS(23, 2, "Site path too long")); } if (setspath(p, i) == -1) stderror(ERR_SYSTEM, "setspath", strerror(errno)); dont_free = 0; } /* sitename(): * Return the site name where the process is running */ char * sitename(pid_t pid) { siteno_t ss; struct sf *st; if ((ss = site(pid)) == -1 || (st = sfnum(ss)) == NULL) return CGETS(23, 3, "unknown"); else return st->sf_sname; } static int migratepid(pit_t pid, siteno_t new_site) { struct sf *st; int need_local; need_local = (pid == 0) || (pid == getpid()); if (kill3(pid, SIGMIGRATE, new_site) < 0) { xprintf("%d: %s\n", pid, strerror(errno)); return (-1); } if (need_local) { if ((new_site = site(0)) == -1) { xprintf(CGETS(23, 4, "site: %s\n"), strerror(errno)); return (-1); } if ((st = sfnum(new_site)) == NULL) { xprintf(CGETS(23, 5, "%d: Site not found\n"), new_site); return (-1); } if (setlocal(st->sf_local, strlen(st->sf_local)) == -1) { xprintf(CGETS(23, 6, "setlocal: %s: %s\n"), st->sf_local, strerror(errno)); return (-1); } } return (0); } /*ARGSUSED*/ void domigrate(Char **v, struct command *c) { struct sf *st; char *s; Char *cp; struct process *pp; int err1 = 0; int pid = 0; siteno_t new_site = 0; pchild_disabled++; cleanup_push(&pchild_disabled, disabled_cleanup); if (setintr) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); } ++v; if (*v[0] == '-') { /* * Do the -site. */ s = short2str(&v[0][1]); /* * see comment in setspath() */ dont_free = 1; if ((st = sfname(s)) == NULL) { dont_free = 0; setname(s); stderror(ERR_NAME | ERR_STRING, CGETS(23, 7, "Site not found")); } dont_free = 0; new_site = st->sf_id; ++v; } if (!*v || *v[0] == '\0') { if (migratepid(0, new_site) == -1) err1++; } else { Char **globbed; v = glob_all_or_error(v); globbed = v; cleanup_push(globbed, blk_cleanup); while (v && (cp = *v)) { if (*cp == '%') { pp = pfind(cp); if (kill3(- pp->p_jobid, SIGMIGRATE, new_site) < 0) { xprintf("%S: %s\n", cp, strerror(errno)); err1++; } } else if (!(Isdigit(*cp) || *cp == '-')) stderror(ERR_NAME | ERR_JOBARGS); else { pid = atoi(short2str(cp)); if (migratepid(pid, new_site) == -1) err1++; } v++; } cleanup_until(globbed); } done: cleanup_until(&pchild_disabled); if (err1) stderror(ERR_SILENT); } #endif /* TCF */ /*** *** CRAY ddmode (Martin Ouwehand EPFL-SIC/SE) ***/ #if defined(_CRAY) && !defined(_CRAYMPP) void dodmmode(Char **v, struct command *c) { Char *cp = v[1]; USE(c); if ( !cp ) { int mode; mode = dmmode(0); dmmode(mode); xprintf("%d\n",mode); } else { if (cp[1] != '\0') stderror(ERR_NAME | ERR_STRING, CGETS(23, 30, "Too many arguments")); else switch(*cp) { case '0': dmmode(0); break; case '1': dmmode(1); break; default: stderror(ERR_NAME | ERR_STRING, CGETS(23, 31, "Invalid argument")); } } } #endif /* _CRAY && !_CRAYMPP */ /*** *** CONVEX Warps. ***/ #ifdef WARP /* * handle the funky warping of symlinks */ #include #include static jmp_buf sigsys_buf; static void catch_sigsys(void) { sigset_t set; sigemptyset(&set, SIGSYS); (void)sigprocmask(SIG_UNBLOCK, &set, NULL); longjmp(sigsys_buf, 1); } /*ARGSUSED*/ void -dowarp(Char **v, struct command *c) +dowarp(Char **v, struct command *c) { int warp, oldwarp; struct warpent *we; volatile struct sigaction old_sigsys_handler; char *newwarp; if (setjmp(sigsys_buf)) { sigaction(SIGSYS, &old_sigsys_handler, NULL); stderror(ERR_NAME | ERR_STRING, CGETS(23, 8, "You're trapped in a universe you never made")); return; } sigaction(SIGSYS, NULL, &old_sigsys_handler); signal(SIGSYS, catch_sigsys); warp = getwarp(); v++; if (*v == 0) { /* display warp value */ if (warp < 0) stderror(ERR_NAME | ERR_STRING, CGETS(23, 9, "Getwarp failed")); we = getwarpbyvalue(warp); if (we) printf("%s\n", we->w_name); else printf("%d\n", warp); } else { /* set warp value */ oldwarp = warp; newwarp = short2str(*v); if (Isdigit(*v[0])) warp = atoi(newwarp); else { we = getwarpbyname(newwarp); if (we) warp = we->w_value; else warp = -1; } if ((warp < 0) || (warp >= WARP_MAXLINK)) stderror(ERR_NAME | ERR_STRING, CGETS(23, 10, "Invalid warp")); if ((setwarp(warp) < 0) || (getwarp() != warp)) { (void) setwarp(oldwarp); stderror(ERR_NAME | ERR_STRING, CGETS(23, 11, "Setwarp failed")); } } sigaction(SIGSYS, &old_sigsys_handler, NULL); } #endif /* WARP */ /*** *** Masscomp or HCX ***/ /* Added, DAS DEC-90. */ #if defined(masscomp) || defined(_CX_UX) static void setuniverse_cleanup(void *xbuf) { char *buf; buf = xbuf; setuniverse(buf); } /*ARGSUSED*/ void -douniverse(Char **v, struct command *c) +douniverse(Char **v, struct command *c) { Char *cp = v[1]; Char *cp2; /* dunno how many elements v comes in with */ char ubuf[100]; if (cp == 0) { (void) getuniverse(ubuf); xprintf("%s\n", ubuf); } else { cp2 = v[2]; if (cp2 == 0) { if (*cp == '\0' || setuniverse(short2str(cp)) != 0) stderror(ERR_NAME | ERR_STRING, CGETS(23, 12, "Illegal universe")); } else { (void) getuniverse(ubuf); if (*cp == '\0' || setuniverse(short2str(cp)) != 0) stderror(ERR_NAME | ERR_STRING, CGETS(23, 12, "Illegal universe")); cleanup_push(ubuf, setuniverse_cleanup); if (setintr) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); } lshift(v, 2); if (setintr) cleanup_until(&pintr_disabled); reexecute(c); cleanup_until(ubuf); } } } #endif /* masscomp || _CX_UX */ /*** *** BS2000/OSD POSIX (Fujitsu Siemens Computers) ***/ #if defined(_OSD_POSIX) static int bs2upcase(char *str) { enum { outside = ' ', singlequote='\'', doublequote='"'} string = outside; char *white; for (white = str + strlen(str) - 1; isspace(*white) && white > str; --white) *white = '\0'; for (; *str != '\0'; ++str) { if (string == outside) { *str = toupper (*str); } if (*str == '\'') { if (string == outside) string = singlequote; else if (string != doublequote) string = outside; } else if (*str == '"') { if (string == outside) string = doublequote; else if (string != singlequote) string = outside; } } if (string != outside) { stderror(ERR_NAME | ERR_UNMATCHED, (Char) string); return 1; } return 0; } static int bs2cmdlist(char *str) { char *str_beg = NULL; int ret = 0; enum { outside = ' ', singlequote='\'', doublequote='"'} string = outside; while (*str != '\0') { while (isspace(*str)) ++str; if (*str == '\0') break; str_beg = str; - + for (; *str != '\0'; ++str) { if (string == outside && *str == ';') /* End of command */ { *str++ = '\0'; break; /* continue with next command */ } if (*str == '\'') { if (string == outside) string = singlequote; else if (string != doublequote) string = outside; } else if (*str == '"') { if (string == outside) string = doublequote; else if (string != singlequote) string = outside; } } if (strlen(str_beg) != 0) { ret = bs2system(str_beg); flush(); if (ret != 0 /*&& !option.err_ignore*/) break; /* do not continue after errors */ } } if (string != outside) { stderror(ERR_NAME | ERR_UNMATCHED, (Char) string); return -1; } return ret; } /*ARGSUSED*/ void dobs2cmd(Char **v, struct command *c) { Char *cp, **globbed; int i = 0, len = 0; char *cmd = NULL; int pvec[2]; struct command faket; Char *fakecom[2]; char tibuf[BUFSIZE]; int icnt, old_pintr_disabled; static const Char STRbs2cmd[] = { 'b','s','2','c','m','d','\0' }; v++; if (setintr) pintr_push_enable(&old_pintr_disabled); v = glob_all_or_error(v); if (setintr) cleanup_until(&old_pintr_disabled); globbed = v; cleanup_push(globbed, blk_cleanup); /* First round: count the string lengths */ for (i=0; v[i]; ++i) { len += Strlen(v[i]) + (v[i+1] != NULL); } cmd = xmalloc(len+1); /* 1 for the final '\0' *//* FIXME: memory leak? */ /* 2nd round: fill cmd buffer */ i = 0; while ((cp = *v++) != 0) { int c; while (c = *cp++) cmd[i++] = (char)c; if (*v) cmd[i++] = ' '; } cmd[i] = '\0'; /* Make upper case */ bs2upcase(cmd); faket.t_dtyp = NODE_COMMAND; faket.t_dflg = F_BACKQ|F_STDERR; faket.t_dlef = 0; faket.t_drit = 0; faket.t_dspr = 0; faket.t_dcom = fakecom; fakecom[0] = (Char *)STRbs2cmd; fakecom[1] = 0; mypipe(pvec); cleanup_push(&pvec[0], open_cleanup); cleanup_push(&pvec[1], open_cleanup); if (pfork(&faket, -1) == 0) { sigset_t set; /* child */ xclose(pvec[0]); (void) dmove(pvec[1], 1); (void) dmove(SHDIAG, 2); initdesc(); sigemptyset(&set); sigaddset(&set, SIGINT); (void)sigprocmask(SIG_UNBLOCK, &set, NULL); #ifdef SIGTSTP signal(SIGTSTP, SIG_IGN); #endif #ifdef SIGTTIN signal(SIGTTIN, SIG_IGN); #endif #ifdef SIGTTOU signal(SIGTTOU, SIG_IGN); #endif xexit(bs2cmdlist(cmd)); } cleanup_until(&pvec[1]); for (;;) { int old_pintr_disabled; if (setintr) pintr_push_enable(&old_pintr_disabled); icnt = xread(pvec[0], tibuf, sizeof(tibuf)); if (setintr) cleanup_until(&old_pintr_disabled); if (icnt <= 0) break; for (i = 0; i < icnt; i++) xputchar((unsigned char) tibuf[i]); } cleanup_until(&pvec[0]); pwait(); flush(); cleanup_until(globbed); } #endif /* _OSD_POSIX */ #if defined(_CX_UX) static void setuniverse_cleanup(void *xbuf) { char *buf; buf = xbuf; setuniverse(buf); } /*ARGSUSED*/ void doatt(Char **v, struct command *c) { Char *cp = v[1]; char ubuf[100]; if (cp == 0) (void) setuniverse("att"); else { (void) getuniverse(ubuf); (void) setuniverse("att"); cleanup_push(ubuf, setuniverse_cleanup); if (setintr) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); } lshift(v, 1); if (setintr) cleanup_until(&pintr_disabled); reexecute(c); cleanup_until(ubuf); } } /*ARGSUSED*/ void doucb(Char **v, struct command *c) { Char *cp = v[1]; char ubuf[100]; if (cp == 0) (void) setuniverse("ucb"); else { (void) getuniverse(ubuf); (void) setuniverse("ucb"); cleanup_push(ubuf, setuniverse_cleanup); if (setintr) { pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); } lshift(v, 1); if (setintr) cleanup_until(&pintr_disabled); reexecute(c); cleanup_until(ubuf); } } #endif /* _CX_UX */ #ifdef _SEQUENT_ /* * Compute the difference in process stats. */ void pr_stat_sub(struct process_stats *p2, struct process_stats *p1, struct process_stats *pr) { pr->ps_utime.tv_sec = p2->ps_utime.tv_sec - p1->ps_utime.tv_sec; pr->ps_utime.tv_usec = p2->ps_utime.tv_usec - p1->ps_utime.tv_usec; if (pr->ps_utime.tv_usec < 0) { pr->ps_utime.tv_sec -= 1; pr->ps_utime.tv_usec += 1000000; } pr->ps_stime.tv_sec = p2->ps_stime.tv_sec - p1->ps_stime.tv_sec; pr->ps_stime.tv_usec = p2->ps_stime.tv_usec - p1->ps_stime.tv_usec; if (pr->ps_stime.tv_usec < 0) { pr->ps_stime.tv_sec -= 1; pr->ps_stime.tv_usec += 1000000; } pr->ps_maxrss = p2->ps_maxrss - p1->ps_maxrss; pr->ps_pagein = p2->ps_pagein - p1->ps_pagein; pr->ps_reclaim = p2->ps_reclaim - p1->ps_reclaim; pr->ps_zerofill = p2->ps_zerofill - p1->ps_zerofill; pr->ps_pffincr = p2->ps_pffincr - p1->ps_pffincr; pr->ps_pffdecr = p2->ps_pffdecr - p1->ps_pffdecr; pr->ps_swap = p2->ps_swap - p1->ps_swap; pr->ps_syscall = p2->ps_syscall - p1->ps_syscall; pr->ps_volcsw = p2->ps_volcsw - p1->ps_volcsw; pr->ps_involcsw = p2->ps_involcsw - p1->ps_involcsw; pr->ps_signal = p2->ps_signal - p1->ps_signal; pr->ps_lread = p2->ps_lread - p1->ps_lread; pr->ps_lwrite = p2->ps_lwrite - p1->ps_lwrite; pr->ps_bread = p2->ps_bread - p1->ps_bread; pr->ps_bwrite = p2->ps_bwrite - p1->ps_bwrite; pr->ps_phread = p2->ps_phread - p1->ps_phread; pr->ps_phwrite = p2->ps_phwrite - p1->ps_phwrite; } #endif /* _SEQUENT_ */ #ifndef HAVE_MEMSET /* This is a replacement for a missing memset function */ void *xmemset(void *loc, int value, size_t len) { char *ptr = loc; while (len--) *ptr++ = value; return loc; } #endif /* !HAVE_MEMSET */ #ifndef HAVE_MEMMOVE /* memmove(): * This is the ANSI form of bcopy() with the arguments backwards... - * Unlike memcpy(), it handles overlaps between source and + * Unlike memcpy(), it handles overlaps between source and * destination memory */ void * xmemmove(void *vdst, const void *vsrc, size_t len) { const char *src = vsrc; char *dst = vdst; if (src == dst) return vdst; if (src > dst) { - while (len--) + while (len--) *dst++ = *src++; } else { src += len; dst += len; - while (len--) + while (len--) *--dst = *--src; } return vdst; } #endif /* HAVE_MEMMOVE */ #ifndef WINNT_NATIVE #ifdef NEEDtcgetpgrp pid_t xtcgetpgrp(int fd) { int pgrp; /* ioctl will handle setting errno correctly. */ if (ioctl(fd, TIOCGPGRP, (ioctl_t) & pgrp) < 0) return (-1); return (pgrp); } /* * XXX: tcsetpgrp is not a macro any more cause on some systems, * pid_t is a short, but the ioctl() takes a pointer to int (pyr) * Thanks to Simon Day (simon@pharaoh.cyborg.bt.co.uk) for pointing * this out. */ int xtcsetpgrp(int fd, int pgrp) { return ioctl(fd, TIOCSPGRP, (ioctl_t) &pgrp); } #endif /* NEEDtcgetpgrp */ #endif /* WINNT_NATIVE */ #ifdef YPBUGS void fix_yp_bugs(void) { char *mydomain; extern int yp_get_default_domain (char **); /* * PWP: The previous version assumed that yp domain was the same as the * internet name domain. This isn't allways true. (Thanks to Mat Landau * for the original version of this.) */ if (yp_get_default_domain(&mydomain) == 0) { /* if we got a name */ extern void yp_unbind (const char *); yp_unbind(mydomain); } } #endif /* YPBUGS */ #ifdef STRCOLLBUG void fix_strcoll_bug(void) { #if defined(NLS) && defined(HAVE_STRCOLL) /* * SunOS4 checks the file descriptor from openlocale() for <= 0 * instead of == -1. Someone should tell sun that file descriptor 0 * is valid! Our portable hack: open one so we call it with 0 used... * We have to call this routine every time the locale changes... * * Of course it also tries to free the constant locale "C" it initially - * had allocated, with the sequence + * had allocated, with the sequence * > setenv LANG "fr" * > ls^D * > unsetenv LANG * But we are smarter than that and just print a warning message. */ int fd = -1; static char *root = "/"; if (!didfds) fd = xopen(root, O_RDONLY|O_LARGEFILE); (void) strcoll(root, root); if (fd != -1) xclose(fd); #endif } #endif /* STRCOLLBUG */ #ifdef OREO #include #endif /* OREO */ void osinit(void) { #ifdef OREO set42sig(); setcompat(getcompat() & ~COMPAT_EXEC); signal(SIGIO, SIG_IGN); /* ignore SIGIO */ #endif /* OREO */ #ifdef aiws { struct sigstack inst; inst.ss_sp = xmalloc(4192) + 4192; inst.ss_onstack = 0; sigstack(&inst, NULL); } #endif /* aiws */ #ifdef apollo (void) isapad(); #endif #ifdef _SX - /* + /* * kill(SIGCONT) problems, don't know what this syscall does * [schott@rzg.mpg.de] */ syscall(151, getpid(), getpid()); #endif /* _SX */ } #ifndef HAVE_STRERROR extern int sys_nerr; extern char *sys_errlist[]; char * xstrerror(int i) { if (i >= 0 && i < sys_nerr) { return sys_errlist[i]; } else { static char *errbuf; /* = NULL; */ xfree(errbuf); errbuf = xasprintf(CGETS(23, 13, "Unknown Error: %d"), i); return errbuf; } } #endif /* !HAVE_STRERROR */ - + #ifndef HAVE_GETHOSTNAME # if !defined(_MINIX) && !defined(__EMX__) && !defined(WINNT_NATIVE) # include # endif /* !_MINIX && !__EMX__ && !WINNT_NATIVE */ int xgethostname(char *name, int namlen) { # if !defined(_MINIX) && !defined(__EMX__) && !defined(WINNT_NATIVE) int i, retval; struct utsname uts; retval = uname(&uts); # ifdef DEBUG xprintf(CGETS(23, 14, "sysname: %s\n"), uts.sysname); xprintf(CGETS(23, 15, "nodename: %s\n"), uts.nodename); xprintf(CGETS(23, 16, "release: %s\n"), uts.release); xprintf(CGETS(23, 17, "version: %s\n"), uts.version); xprintf(CGETS(23, 18, "machine: %s\n"), uts.machine); # endif /* DEBUG */ i = strlen(uts.nodename) + 1; (void) strncpy(name, uts.nodename, i < namlen ? i : namlen); return retval; # else /* !_MINIX && !__EMX__ */ if (namlen > 0) { # ifdef __EMX__ (void) strncpy(name, "OS/2", namlen); # else /* _MINIX */ (void) strncpy(name, "minix", namlen); # endif /* __EMX__ */ name[namlen-1] = '\0'; } return(0); #endif /* _MINIX && !__EMX__ */ } /* end xgethostname */ #endif /* !HAVE_GETHOSTNAME */ #ifndef HAVE_NICE # if defined(_MINIX) && defined(NICE) # undef _POSIX_SOURCE /* redefined in */ # undef _MINIX /* redefined in */ # undef HZ /* redefined in */ # include # endif /* _MINIX && NICE */ -int +int xnice(int incr) { #if defined(_MINIX) && defined(NICE) return callm1(MM, NICE, incr, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); #else return /* incr ? 0 : */ 0; #endif /* _MINIX && NICE */ } /* end xnice */ #endif /* !HAVE_NICE */ #ifndef HAVE_GETCWD static char *strnrcpy (char *, char *, size_t); /* xgetcwd(): * Return the pathname of the current directory, or return * an error message in pathname. */ # ifdef hp9000s500 /* * From: Bernd Mohr * I also ported the tcsh to the HP9000 Series 500. This computer * is a little bit different than the other HP 9000 computer. It has * a HP Chip instead of a Motorola CPU and it is no "real" UNIX. It runs * HP-UX which is emulated in top of a HP operating system. So, the last * supported version of HP-UX is 5.2 on the HP9000s500. This has two * consequences: it supports no job control and it has a filesystem * without "." and ".." !!! */ char * xgetcwd(char *pathname, size_t pathlen) { char pathbuf[MAXPATHLEN]; /* temporary pathname buffer */ char *pnptr = &pathbuf[(sizeof pathbuf)-1]; /* pathname pointer */ dev_t rdev; /* root device number */ DIR *dirp = NULL; /* directory stream */ ino_t rino; /* root inode number */ off_t rsize; /* root size */ struct direct *dir; /* directory entry struct */ struct stat d, dd; /* file status struct */ int serrno; *pnptr = '\0'; (void) stat("/.", &d); rdev = d.st_dev; rino = d.st_ino; rsize = d.st_size; for (;;) { if (stat(".", &d) == -1) { (void) xsnprintf(pathname, pathlen, CGETS(23, 24, "getcwd: Cannot stat \".\" (%s)"), strerror(errno)); goto fail; } if (d.st_ino == rino && d.st_dev == rdev && d.st_size == rsize) break; /* reached root directory */ if ((dirp = opendir("..")) == NULL) { (void) xsnprintf(pathname, pathlen, CGETS(23, 19, "getcwd: Cannot open \"..\" (%s)"), strerror(errno)); goto fail; } if (chdir("..") == -1) { (void) xsnprintf(pathname, pathlen, CGETS(23, 20, "getcwd: Cannot chdir to \"..\" (%s)"), strerror(errno)); goto fail; } do { if ((dir = readdir(dirp)) == NULL) { - (void) xsnprintf(pathname, pathlen, + (void) xsnprintf(pathname, pathlen, CGETS(23, 21, "getcwd: Read error in \"..\" (%s)"), strerror(errno)); goto fail; } if (stat(dir->d_name, &dd) == -1) { (void) xsnprintf(pathname, pathlen, CGETS(23, 25, "getcwd: Cannot stat directory \"%s\" (%s)"), dir->d_name, strerror(errno)); goto fail; } } while (dd.st_ino != d.st_ino || dd.st_dev != d.st_dev || dd.st_size != d.st_size); closedir(dirp); dirp = NULL; pnptr = strnrcpy(dirp->d_name, pnptr, pnptr - pathbuf); pnptr = strnrcpy("/", pnptr, pnptr - pathbuf); } if (*pnptr == '\0') /* current dir == root dir */ (void) strncpy(pathname, "/", pathlen); else { (void) strncpy(pathname, pnptr, pathlen); pathname[pathlen - 1] = '\0'; if (chdir(pnptr) == -1) { (void) xsnprintf(pathname, MAXPATHLEN, CGETS(23, 22, "getcwd: Cannot change back to \".\" (%s)"), strerror(errno)); return NULL; } } return pathname; fail: serrno = errno; (void) chdir(strnrcpy(".", pnptr, pnptr - pathbuf)); errno = serrno; return NULL; } # else /* ! hp9000s500 */ char * xgetcwd(char *pathname, size_t pathlen) { DIR *dp; struct dirent *d; struct stat st_root, st_cur, st_next, st_dotdot; char pathbuf[MAXPATHLEN], nextpathbuf[MAXPATHLEN * 2]; char *pathptr, *nextpathptr, *cur_name_add; int save_errno = 0; /* find the inode of root */ if (stat("/", &st_root) == -1) { - (void) xsnprintf(pathname, pathlen, CGETS(23, 23, + (void) xsnprintf(pathname, pathlen, CGETS(23, 23, "getcwd: Cannot stat \"/\" (%s)"), strerror(errno)); return NULL; } pathbuf[MAXPATHLEN - 1] = '\0'; pathptr = &pathbuf[MAXPATHLEN - 1]; nextpathbuf[MAXPATHLEN - 1] = '\0'; cur_name_add = nextpathptr = &nextpathbuf[MAXPATHLEN - 1]; /* find the inode of the current directory */ if (lstat(".", &st_cur) == -1) { (void) xsnprintf(pathname, pathlen, CGETS(23, 24, "getcwd: Cannot stat \".\" (%s)"), strerror(errno)); return NULL; } nextpathptr = strnrcpy(nextpathptr, "../", nextpathptr - nextpathbuf); /* Descend to root */ for (;;) { /* look if we found root yet */ if (st_cur.st_ino == st_root.st_ino && DEV_DEV_COMPARE(st_cur.st_dev, st_root.st_dev)) { (void) strncpy(pathname, *pathptr != '/' ? "/" : pathptr, pathlen); pathname[pathlen - 1] = '\0'; return pathname; } /* open the parent directory */ if (stat(nextpathptr, &st_dotdot) == -1) { (void) xsnprintf(pathname, pathlen, CGETS(23, 25, "getcwd: Cannot stat directory \"%s\" (%s)"), nextpathptr, strerror(errno)); return NULL; } if ((dp = opendir(nextpathptr)) == NULL) { (void) xsnprintf(pathname, pathlen, CGETS(23, 26, "getcwd: Cannot open directory \"%s\" (%s)"), nextpathptr, strerror(errno)); return NULL; } /* look in the parent for the entry with the same inode */ if (DEV_DEV_COMPARE(st_dotdot.st_dev, st_cur.st_dev)) { /* Parent has same device. No need to stat every member */ for (d = readdir(dp); d != NULL; d = readdir(dp)) { #ifdef __clipper__ if (((unsigned long)d->d_ino & 0xffff) == st_cur.st_ino) break; #else if (d->d_ino == st_cur.st_ino) break; #endif } } else { - /* - * Parent has a different device. This is a mount point so we - * need to stat every member + /* + * Parent has a different device. This is a mount point so we + * need to stat every member */ for (d = readdir(dp); d != NULL; d = readdir(dp)) { if (ISDOT(d->d_name) || ISDOTDOT(d->d_name)) continue; (void)strncpy(cur_name_add, d->d_name, (size_t) (&nextpathbuf[sizeof(nextpathbuf) - 1] - cur_name_add)); if (lstat(nextpathptr, &st_next) == -1) { /* * We might not be able to stat() some path components * if we are using afs, but this is not an error as * long as we find the one we need; we also save the * first error to report it if we don't finally succeed. */ if (save_errno == 0) save_errno = errno; continue; } /* check if we found it yet */ if (st_next.st_ino == st_cur.st_ino && - DEV_DEV_COMPARE(st_next.st_dev, st_cur.st_dev)) + DEV_DEV_COMPARE(st_next.st_dev, st_cur.st_dev)) break; } } if (d == NULL) { (void) xsnprintf(pathname, pathlen, CGETS(23, 27, "getcwd: Cannot find \".\" in \"..\" (%s)"), strerror(save_errno ? save_errno : ENOENT)); closedir(dp); return NULL; } else save_errno = 0; st_cur = st_dotdot; pathptr = strnrcpy(pathptr, d->d_name, pathptr - pathbuf); pathptr = strnrcpy(pathptr, "/", pathptr - pathbuf); nextpathptr = strnrcpy(nextpathptr, "../", nextpathptr - nextpathbuf); *cur_name_add = '\0'; closedir(dp); } } /* end getcwd */ # endif /* hp9000s500 */ /* strnrcpy(): * Like strncpy, going backwards and returning the new pointer */ static char * strnrcpy(char *ptr, char *str, size_t siz) { int len = strlen(str); if (siz == 0) return ptr; while (len && siz--) *--ptr = str[--len]; return (ptr); } /* end strnrcpy */ #endif /* !HAVE_GETCWD */ #ifdef apollo /*** *** Domain/OS ***/ #include #include #include static char * apperr(status_$t *st) { static char *buf; /* = NULL */ short e_subl, e_modl, e_codel; error_$string_t e_sub, e_mod, e_code; error_$get_text(*st, e_sub, &e_subl, e_mod, &e_modl, e_code, &e_codel); e_sub[e_subl] = '\0'; e_code[e_codel] = '\0'; e_mod[e_modl] = '\0'; xfree(buf); buf = xasprintf("%s (%s/%s)", e_code, e_sub, e_mod); return(buf); } static int llib(Char *s) { short len = Strlen(s); status_$t st; char *t; loader_$inlib(t = short2str(s), len, &st); - if (st.all != status_$ok) + if (st.all != status_$ok) stderror(ERR_SYSTEM, t, apperr(&st)); } /*ARGSUSED*/ void doinlib(Char **v, struct command *c) { Char **globbed; setname(short2str(*v++)); v = glob_all_or_error(v); globbed = v; cleanup_push(globbed, blk_cleanup); - while (v && *v) + while (v && *v) llib(*v++); cleanup_until(globbed); } int getv(Char *v) { if (eq(v, STRbsd43)) return(1); else if (eq(v, STRsys53)) return(0); - else + else stderror(ERR_NAME | ERR_SYSTEM, short2str(v), CGETS(23, 28, "Invalid system type")); /*NOTREACHED*/ return(0); } /*ARGSUSED*/ void dover(Char **v, struct command *c) { Char *p; setname(short2str(*v++)); if (!*v) { if (!(p = tgetenv(STRSYSTYPE))) stderror(ERR_NAME | ERR_STRING, CGETS(23, 29, "System type is not set")); xprintf("%S\n", p); } else { tsetenv(STRSYSTYPE, getv(*v) ? STRbsd43 : STRsys53); dohash(NULL, NULL); } } /* * Many thanks to rees@citi.umich.edu (Jim Rees) and * mathys@ssdt-tempe.sps.mot.com (Yves Mathys) * For figuring out how to do this... I could have never done * it without their help. */ typedef short enum { name_$wdir_type, name_$ndir_type, name_$node_dir_type, } name_$dir_type_t; /*ARGSUSED*/ void dorootnode(Char **v, struct command *c) { name_$dir_type_t dirtype = name_$node_dir_type; uid_$t uid; status_$t st; char *name; short namelen; setname(short2str(*v++)); name = short2str(*v); namelen = strlen(name); name_$resolve(name, &namelen, &uid, &st); - if (st.all != status_$ok) + if (st.all != status_$ok) stderror(ERR_SYSTEM, name, apperr(&st)); namelen = 0; name_$set_diru(&uid, "", &namelen, &dirtype, &st); - if (st.all != status_$ok) + if (st.all != status_$ok) stderror(ERR_SYSTEM, name, apperr(&st)); dohash(NULL, NULL); } int isapad(void) { static int res = -1; static status_$t st; if (res == -1) { int strm; if (isatty(0)) strm = 0; if (isatty(1)) strm = 1; if (isatty(2)) strm = 2; else { res = 0; st.all = status_$ok; return(res); } res = stream_$isavt(&strm, &st); res = res ? 1 : 0; } else { - if (st.all != status_$ok) + if (st.all != status_$ok) stderror(ERR_SYSTEM, "stream_$isavt", apperr(&st)); } return(res); } #endif #if defined(__CYGWIN__) && !defined(NO_CRYPT) #undef CHAR /* Collides with Win32 API */ #define WIN32_LEAN_AND_MEAN #include #include char * cygwin_xcrypt(struct passwd *pw, const char *password, const char *expected_pwd) { static char invalid_password[] = "\377"; HANDLE token = cygwin_logon_user(pw, password); if (token == INVALID_HANDLE_VALUE) return invalid_password; CloseHandle(token); return (char *) expected_pwd; } #endif /* __CYGWIN__ && !NO_CRYPT */ diff --git a/contrib/tcsh/tc.os.h b/contrib/tcsh/tc.os.h index 3847da549fc2..83be8c1d243d 100644 --- a/contrib/tcsh/tc.os.h +++ b/contrib/tcsh/tc.os.h @@ -1,619 +1,619 @@ /* * tc.os.h: Shell os dependent defines */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _h_tc_os #define _h_tc_os -#ifdef notdef +#ifdef notdef /* - * for SVR4 and linux we used to fork pipelines backwards. + * for SVR4 and linux we used to fork pipelines backwards. * This should not be needed any more. * more info in sh.sem.c */ # define BACKPIPE #endif /* notdef */ #ifdef __CYGWIN__ # undef NOFILE # define NOFILE sysconf(_SC_OPEN_MAX) #endif #ifdef _VMS_POSIX -# ifndef NOFILE +# ifndef NOFILE # define NOFILE 64 # endif /* NOFILE */ # define nice(a) setprio((getpid()),a) # include /* for time stuff in tc.prompt.c */ # include #endif /* atp vmsposix */ #if defined(DECOSF1) || defined(HPUXVERSION) # include #endif /* DECOSF1 || HPUXVERSION */ #ifdef DECOSF1 # include #endif /* DECOSF1 */ #if defined(OPEN_MAX) && !defined(NOFILE) # define NOFILE OPEN_MAX #endif /* OPEN_MAX && !NOFILE */ #if defined(USR_NFDS) && !defined(NOFILE) # define NOFILE USR_NFDS #endif /* USR_NFDS && !NOFILE */ #ifndef NOFILE # define NOFILE 256 #endif /* NOFILE */ #ifdef OREO # include # ifdef notdef /* Don't include it, because it defines things we don't really have */ -# include +# include # endif /* notdef */ # ifdef POSIX # include # include # endif /* POSIX */ #endif /* OREO */ #ifdef __QNXNTO__ #include #include #undef O_TEXT #undef O_BINARY #endif #ifdef convex # include #endif /* convex */ #ifdef titan extern int end; #endif /* titan */ #ifdef hpux # ifdef lint /* * Hpux defines struct ucred, in , but if I include that * then I need to include the *world* * [all this to pass lint cleanly!!!] * so I define struct ucred here... */ struct ucred { int foo; }; # endif /* lint */ /* * hpux 7.0 does not define it */ # ifndef CSUSP # define CSUSP 032 # endif /* CSUSP */ # include # if !defined(hp9000s500) && !(defined(SIGRTMAX) || defined(SIGRTMIN)) /* * hpux < 7 */ # include # endif /* !hp9000s500 && !(SIGRTMAX || SIGRTMIN) */ # ifndef TIOCSTI # include # endif #endif /* hpux */ /* * ISC does not define CSUSP */ #ifdef ISC # ifndef CSUSP # define CSUSP 032 # endif /* CSUSP */ # if defined(POSIX) && !defined(TIOCGWINSZ) /* * ISC defines this only in termio.h. If we are using POSIX and include * termios.h, then we define it ourselves so that window resizing works. */ # define TIOCGWINSZ (('T'<<8)|104) # endif /* POSIX && !TIOCGWINSZ */ #endif /* ISC */ #ifdef ISC202 # undef TIOCGWINSZ #endif /* ISC202 */ /* - * XXX: This will be changed soon to + * XXX: This will be changed soon to * #if (SYSVREL > 0) && defined(TIOCGWINSZ) * If that breaks on your machine, let me know. * * It would break on glibc, where all this is * defined in . Wrapper added. */ #if !defined(__linux__) && !defined(__GNU__) && !defined(__GLIBC__) && !defined(_VMS_POSIX) # if defined(INTEL) || defined(u3b2) || defined (u3b5) || defined(ub15) || defined(u3b20d) || defined(ISC) || defined(SCO) || defined(tower32) # ifdef TIOCGWINSZ /* * for struct winsiz */ # include # include # endif /* TIOCGWINSZ */ # endif /* INTEL || u3b2 || u3b5 || ub15 || u3b20d || ISC || SCO || tower32 */ #endif /* !glibc && !_VMS_POSIX */ #ifdef IRIS4D # include # include #endif /* IRIS4D */ /* - * For some versions of system V software, specially ones that use the + * For some versions of system V software, specially ones that use the * Wollongong Software TCP/IP, the FIOCLEX, FIONCLEX, FIONBIO calls * might not work correctly for file descriptors [they work only for * sockets]. So we try to use first the fcntl() and we only use the * ioctl() form, only if we don't have the fcntl() one. * * From: scott@craycos.com (Scott Bolte) */ #ifndef WINNT_NATIVE # ifdef F_SETFD # ifndef FD_CLOEXEC # define FD_CLOEXEC 1 # endif # define close_on_exec(fd, v) fcntl((fd), F_SETFD, ((v) ? FD_CLOEXEC : 0)) # else /* !F_SETFD */ # ifdef FIOCLEX # define close_on_exec(fd, v) ioctl((fd), ((v) ? FIOCLEX : FIONCLEX), NULL) # else /* !FIOCLEX */ # define close_on_exec(fd, v) /* Nothing */ # endif /* FIOCLEX */ # endif /* F_SETFD */ #else /* WINNT_NATIVE */ # define close_on_exec(fd, v) nt_close_on_exec((fd),(v)) #endif /* !WINNT_NATIVE */ /* * Stat */ #ifdef ISC /* these are not defined for _POSIX_SOURCE under ISC 2.2 */ # ifndef S_IFMT # define S_IFMT 0170000 /* type of file */ # define S_IFDIR 0040000 /* directory */ # define S_IFCHR 0020000 /* character special */ # define S_IFBLK 0060000 /* block special */ # define S_IFREG 0100000 /* regular */ # define S_IFIFO 0010000 /* fifo */ # define S_IFNAM 0050000 /* special named file */ # ifndef ISC202 # define S_IFLNK 0120000 /* symbolic link */ # endif /* ISC202 */ # endif /* S_IFMT */ #endif /* ISC */ #ifdef STAT_MACROS_BROKEN # undef S_ISDIR # undef S_ISCHR # undef S_ISBLK # undef S_ISREG # undef S_ISFIFO # undef S_ISNAM # undef S_ISLNK # undef S_ISSOCK #endif /* STAT_MACROS_BROKEN */ #ifdef S_IFMT # if !defined(S_ISDIR) && defined(S_IFDIR) # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR) # endif /* ! S_ISDIR && S_IFDIR */ # if !defined(S_ISCHR) && defined(S_IFCHR) # define S_ISCHR(a) (((a) & S_IFMT) == S_IFCHR) # endif /* ! S_ISCHR && S_IFCHR */ # if !defined(S_ISBLK) && defined(S_IFBLK) # define S_ISBLK(a) (((a) & S_IFMT) == S_IFBLK) # endif /* ! S_ISBLK && S_IFBLK */ # if !defined(S_ISREG) && defined(S_IFREG) # define S_ISREG(a) (((a) & S_IFMT) == S_IFREG) # endif /* ! S_ISREG && S_IFREG */ # if !defined(S_ISFIFO) && defined(S_IFIFO) # define S_ISFIFO(a) (((a) & S_IFMT) == S_IFIFO) # endif /* ! S_ISFIFO && S_IFIFO */ # if !defined(S_ISNAM) && defined(S_IFNAM) # define S_ISNAM(a) (((a) & S_IFMT) == S_IFNAM) # endif /* ! S_ISNAM && S_IFNAM */ # if !defined(S_ISLNK) && defined(S_IFLNK) # define S_ISLNK(a) (((a) & S_IFMT) == S_IFLNK) # endif /* ! S_ISLNK && S_IFLNK */ # if !defined(S_ISSOCK) && defined(S_IFSOCK) # define S_ISSOCK(a) (((a) & S_IFMT) == S_IFSOCK) # endif /* ! S_ISSOCK && S_IFSOCK */ #endif /* S_IFMT */ #ifdef tower32 /* The header files lie; we really don't have symlinks */ # undef S_ISLNK # undef S_IFLNK #endif /* tower32 */ #ifndef S_IREAD # define S_IREAD 0000400 #endif /* S_IREAD */ #ifndef S_IROTH # define S_IROTH (S_IREAD >> 6) #endif /* S_IROTH */ #ifndef S_IRGRP # define S_IRGRP (S_IREAD >> 3) #endif /* S_IRGRP */ #ifndef S_IRUSR # define S_IRUSR S_IREAD #endif /* S_IRUSR */ #ifndef S_IWRITE # define S_IWRITE 0000200 #endif /* S_IWRITE */ #ifndef S_IWOTH # define S_IWOTH (S_IWRITE >> 6) #endif /* S_IWOTH */ #ifndef S_IWGRP # define S_IWGRP (S_IWRITE >> 3) #endif /* S_IWGRP */ #ifndef S_IWUSR # define S_IWUSR S_IWRITE #endif /* S_IWUSR */ #ifndef S_IEXEC # define S_IEXEC 0000100 #endif /* S_IEXEC */ #ifndef S_IXOTH # define S_IXOTH (S_IEXEC >> 6) #endif /* S_IXOTH */ #ifndef S_IXGRP # define S_IXGRP (S_IEXEC >> 3) #endif /* S_IXGRP */ #ifndef S_IXUSR # define S_IXUSR S_IEXEC #endif /* S_IXUSR */ #ifndef S_ISUID # define S_ISUID 0004000 /* setuid */ #endif /* S_ISUID */ -#ifndef S_ISGID +#ifndef S_ISGID # define S_ISGID 0002000 /* setgid */ #endif /* S_ISGID */ #ifndef S_ISVTX # define S_ISVTX 0001000 /* sticky */ #endif /* S_ISVTX */ #ifndef S_ENFMT # define S_ENFMT S_ISGID /* record locking enforcement flag */ #endif /* S_ENFMT */ /* the following macros are for POSIX conformance */ #ifndef S_IRWXU # define S_IRWXU (S_IRUSR | S_IWUSR | S_IXUSR) #endif /* S_IRWXU */ #ifndef S_IRWXG # define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP) #endif /* S_IRWXG */ #ifndef S_IRWXO # define S_IRWXO (S_IROTH | S_IWOTH | S_IXOTH) #endif /* S_IRWXO */ /* * Access() */ #ifndef F_OK # define F_OK 0 #endif /* F_OK */ #ifndef X_OK # define X_OK 1 #endif /* X_OK */ #ifndef W_OK # define W_OK 2 #endif /* W_OK */ #ifndef R_OK # define R_OK 4 #endif /* R_OK */ /* * Open() */ #ifndef O_RDONLY # define O_RDONLY 0 #endif /* O_RDONLY */ #ifndef O_WRONLY # define O_WRONLY 1 #endif /* O_WRONLY */ #ifndef O_RDWR # define O_RDWR 2 #endif /* O_RDWR */ #ifndef O_TEMPORARY # define O_TEMPORARY 0 #endif /* O_TEMPORARY */ #ifndef O_EXCL # define O_EXCL 0 #endif /* O_EXCL */ #ifndef O_LARGEFILE # define O_LARGEFILE 0 #endif /* O_LARGEFILE */ #ifndef O_CREAT # define O_CREAT 0 #endif /* O_CREAT */ /* * Lseek() */ #ifndef L_SET # ifdef SEEK_SET # define L_SET SEEK_SET # else /* !SEEK_SET */ # define L_SET 0 # endif /* SEEK_SET */ #endif /* L_SET */ #ifndef L_INCR # ifdef SEEK_CUR # define L_INCR SEEK_CUR # else /* !SEEK_CUR */ # define L_INCR 1 # endif /* SEEK_CUR */ #endif /* L_INCR */ #ifndef L_XTND # ifdef SEEK_END # define L_XTND SEEK_END # else /* !SEEK_END */ # define L_XTND 2 # endif /* SEEK_END */ #endif /* L_XTND */ #if !defined (HAVE_SETPGID) && !defined (SETPGRP_VOID) # define setpgid(pid, pgrp) setpgrp(pid, pgrp) #endif #if defined(BSDJOBS) && !(defined(POSIX) && defined(POSIXJOBS)) # define NEEDtcgetpgrp #endif /* BSDJOBS && !(POSIX && POSIXJOBS) */ -#ifdef RENO +#ifdef RENO /* * RENO has this broken. It is fixed on 4.4BSD */ # define NEEDtcgetpgrp #endif /* RENO */ #ifdef SXA # ifndef _BSDX_ /* * Only needed in the system V environment. */ # define setrlimit bsd_setrlimit # define getrlimit bsd_getrlimit # endif /* _BSDX_ */ #endif /* SXA */ #if defined(_MINIX) || defined(__EMX__) # define HAVENOLIMIT /* * Minix does not have these, so... */ # define getpgrp getpid #endif /* _MINIX || __EMX__ */ #ifdef __EMX__ /* XXX: How can we get the tty name in emx? */ # define ttyname(fd) (isatty(fd) ? "/dev/tty" : NULL) #endif /* __EMX__ */ #ifndef S_IFLNK # define lstat stat #endif /* S_IFLNK */ #if defined(BSDTIMES) && !defined(_SEQUENT_) typedef struct timeval timeval_t; #endif /* BSDTIMES && ! _SEQUENT_ */ #ifdef NeXT /* * From Tony_Mason@transarc.com, override NeXT's malloc stuff. */ # define malloc tcsh_malloc # define calloc tcsh_calloc # define realloc tcsh_realloc # define free tcsh_free #endif /* NeXT */ #if defined(HAVE_GETHOSTNAME) && !HAVE_DECL_GETHOSTNAME extern int gethostname (char *, int); #endif #ifndef GETPGRP_VOID # define mygetpgrp() getpgrp(0) #else # define mygetpgrp() getpgrp() #endif #if !defined(POSIX) || defined(SUNOS4) || defined(UTekV) || defined(sysV88) extern time_t time(); extern char *getenv(); extern int atoi(); # ifndef __EMX__ extern char *ttyname(); # endif /* __EMX__ */ # if defined(SUNOS4) # ifndef toupper extern int toupper (int); # endif /* toupper */ # ifndef tolower extern int tolower (int); # endif /* tolower */ extern caddr_t sbrk (int); # else /* !SUNOS4 */ # ifndef WINNT_NATIVE # ifdef hpux extern void abort(); extern void qsort(); # endif /* hpux */ # endif /* !WINNT_NATIVE */ # endif /* SUNOS4 */ #ifndef _CX_UX extern void perror(); #endif # ifdef BSD extern uid_t getuid(), geteuid(); extern gid_t getgid(), getegid(); # endif /* BSD */ # ifdef SYSMALLOC extern memalign_t malloc(); extern memalign_t realloc(); extern memalign_t calloc(); extern void free(); # endif /* SYSMALLOC */ # ifdef BSDJOBS # ifdef BSDTIMES # ifdef __MACHTEN__ extern pid_t wait3(); # endif /* __MACHTEN__ */ # endif /* BSDTIMES */ # endif /* BSDJOBS */ # if (!defined(fps500) && !defined(apollo) && !defined(__lucid) && !defined(HPBSD) && !defined(DECOSF1)) extern void setpwent(); extern void endpwent(); # endif /* !fps500 && !apollo && !__lucid && !HPBSD && !DECOSF1 */ # ifndef __STDC__ extern struct passwd *getpwuid(), *getpwnam(), *getpwent(); # ifdef HAVE_SHADOW_H extern struct spwd *getspnam(), *getspent(); # endif /* HAVE_SHADOW_H */ # if defined(HAVE_AUTH_H) && defined(HAVE_GETAUTHUID) extern struct authorization *getauthuid(); # endif /* HAVE_AUTH_H && HAVE_GETAUTHUID */ # endif /* __STDC__ */ # ifndef getcwd extern char *getcwd(); # endif /* getcwd */ #else /* POSIX || !SUNOS4 || !UTekV || !sysV88 */ # if (defined(SUNOS4) && !defined(__GNUC__)) || defined(_IBMR2) || defined(_IBMESA) extern char *getvwd(); # endif /* (SUNOS4 && ! __GNUC__) || _IBMR2 || _IBMESA */ # ifdef SCO -extern char *ttyname(); +extern char *ttyname(); # endif /* SCO */ # ifdef __clipper__ -extern char *ttyname(); +extern char *ttyname(); # endif /* __clipper__ */ #endif /* !POSIX || SUNOS4 || UTekV || sysV88 */ #if defined(SUNOS4) && __GNUC__ == 2 /* * Somehow these are missing */ extern int ioctl (int, int, ...); extern int readlink (const char *, char *, size_t); extern void setgrent (void); extern void endgrent (void); # ifdef REMOTEHOST # ifndef _SOCKLEN_T /* Avoid Solaris 2.7 bogosity. */ struct sockaddr; extern int getpeername (int, struct sockaddr *, int *); # endif /* _SOCKLEN_T */ # endif /* REMOTEHOST */ #endif /* SUNOS4 && __GNUC__ == 2 */ -#if (defined(BSD) && !defined(BSD4_4)) || defined(SUNOS4) +#if (defined(BSD) && !defined(BSD4_4)) || defined(SUNOS4) # if defined(__alpha) && defined(__osf__) && DECOSF1 < 200 extern void bcopy (const void *, void *, size_t); # define memmove(a, b, c) (bcopy((char *) (b), (char *) (a), (int) (c)), a) # endif /* __alpha && __osf__ && DECOSF1 < 200 */ #endif /* (BSD && !BSD4_4) || SUNOS4 */ #ifdef SUNOS4 # include /* memset should be declared in but isn't */ #endif /* SUNOS4 */ #if SYSVREL == 4 # ifdef REMOTEHOST /* Irix6 defines getpeername(int, void *, int *) which conflicts with the definition below. */ # if !defined(__sgi) && !defined(_OSD_POSIX) && !defined(__MVS__) # ifndef _SOCKLEN_T /* Avoid Solaris 2.7 bogosity. */ struct sockaddr; extern int getpeername (int, struct sockaddr *, int *); # endif /* _SOCKLEN_T */ # endif /* !__sgi && !_OSD_POSIX && !__MVS__ */ # endif /* REMOTEHOST */ # ifndef BSDTIMES extern int getrlimit (int, struct rlimit *); extern int setrlimit (int, const struct rlimit *); # endif /* !BSDTIMES */ # if defined(SOLARIS2) extern char *strerror (int); # endif /* SOLARIS2 */ #endif /* SYSVREL == 4 */ #if defined(__alpha) && defined(__osf__) && DECOSF1 < 200 /* These are ok for 1.3, but conflict with the header files for 2.0 */ extern char *sbrk (ssize_t); extern int ioctl (int, unsigned long, char *); extern pid_t vfork (void); extern int killpg (pid_t, int); #endif /* __osf__ && __alpha && DECOSF1 < 200 */ #ifndef va_copy # ifdef __va_copy # define va_copy(DEST, SRC) __va_copy(DEST, SRC) # else # define va_copy(DEST, SRC) memcpy(&(DEST), &(SRC), sizeof(va_list)) # endif #endif #if defined(__CYGWIN__) && !defined(NO_CRYPT) extern char *cygwin_xcrypt(struct passwd *, const char *, const char *); #endif /* __CYGWIN__ && !NO_CRYPT */ #endif /* _h_tc_os */ diff --git a/contrib/tcsh/tc.printf.c b/contrib/tcsh/tc.printf.c index 658758e29221..dca375a89019 100644 --- a/contrib/tcsh/tc.printf.c +++ b/contrib/tcsh/tc.printf.c @@ -1,477 +1,477 @@ /* * tc.printf.c: A public-domain, minimal printf/sprintf routine that prints * through the putchar() routine. Feel free to use for * anything... -- 7/17/87 Paul Placeway */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #ifdef lint #undef va_arg #define va_arg(a, b) (a ? (b) 0 : (b) 0) #endif #define INF INT_MAX /* should be bigger than any field to print */ static char snil[] = "(nil)"; static void xaddchar (int); static int doprnt (void (*) (int), const char *, va_list); static int doprnt(void (*addchar) (int), const char *sfmt, va_list ap) { char *bp; const char *f; #ifdef SHORT_STRINGS const Char *Bp; #endif /* SHORT_STRINGS */ #ifdef HAVE_LONG_LONG long long l; unsigned long long u; #else long l; unsigned long u; #endif char buf[(CHAR_BIT * sizeof (l) + 2) / 3 + 1]; /* Octal: 3 bits per char */ int i; int fmt; unsigned char pad = ' '; int flush_left = 0, f_width = 0, prec = INF, hash = 0; int do_long = 0, do_size_t = 0, do_ptrdiff_t = 0; int sign = 0, count = 0; int attributes = 0; f = sfmt; for (; *f; f++) { if (*f != '%') { /* then just out the char */ (*addchar) (((unsigned char)*f) | attributes); count++; } else { f++; /* skip the % */ if (*f == '-') { /* minus: flush left */ flush_left = 1; f++; } if (*f == '0' || *f == '.') { /* padding with 0 rather than blank */ pad = '0'; f++; } if (*f == '*') { /* field width */ f_width = va_arg(ap, int); f++; } else if (isdigit((unsigned char) *f)) { f_width = atoi(f); while (isdigit((unsigned char) *f)) f++; /* skip the digits */ } if (*f == '.') { /* precision */ f++; if (*f == '*') { prec = va_arg(ap, int); f++; } else if (isdigit((unsigned char) *f)) { prec = atoi(f); while (isdigit((unsigned char) *f)) f++; /* skip the digits */ } } if (*f == '#') { /* alternate form */ hash = 1; f++; } if (*f == 'l') { /* long format */ do_long++; f++; if (*f == 'l') { do_long++; f++; } } if (*f == 'z') { /* size_t format */ do_size_t++; f++; } if (*f == 't') { /* ptrdiff_t format */ do_ptrdiff_t++; f++; } fmt = (unsigned char) *f; if (fmt != 'S' && fmt != 'Q' && isupper(fmt)) { do_long = 1; fmt = tolower(fmt); } bp = buf; switch (fmt) { /* do the format */ case 'd': switch (do_long) { case 0: if (do_size_t) l = (long) (va_arg(ap, size_t)); else l = (long) (va_arg(ap, int)); break; case 1: #ifndef HAVE_LONG_LONG default: #endif l = va_arg(ap, long); break; #ifdef HAVE_LONG_LONG default: l = va_arg(ap, long long); break; #endif } if (l < 0) { sign = 1; l = -l; } do { *bp++ = (char) (l % 10) + '0'; } while ((l /= 10) > 0); if (sign) *bp++ = '-'; f_width = f_width - (int) (bp - buf); if (!flush_left) while (f_width-- > 0) { (*addchar) (pad | attributes); count++; } for (bp--; bp >= buf; bp--) { (*addchar) (((unsigned char) *bp) | attributes); count++; } if (flush_left) while (f_width-- > 0) { (*addchar) (' ' | attributes); count++; } break; case 'p': do_long = 1; hash = 1; fmt = 'x'; /*FALLTHROUGH*/ case 'o': case 'x': case 'u': switch (do_long) { case 0: if (do_size_t) u = va_arg(ap, size_t); else if (do_ptrdiff_t) u = va_arg(ap, ptrdiff_t); else u = va_arg(ap, unsigned int); break; case 1: #ifndef HAVE_LONG_LONG default: #endif u = va_arg(ap, unsigned long); break; #ifdef HAVE_LONG_LONG default: u = va_arg(ap, unsigned long long); break; #endif } if (fmt == 'u') { /* unsigned decimal */ do { *bp++ = (char) (u % 10) + '0'; } while ((u /= 10) > 0); } else if (fmt == 'o') { /* octal */ do { *bp++ = (char) (u % 8) + '0'; } while ((u /= 8) > 0); if (hash) *bp++ = '0'; } else if (fmt == 'x') { /* hex */ do { i = (int) (u % 16); if (i < 10) *bp++ = i + '0'; else *bp++ = i - 10 + 'a'; } while ((u /= 16) > 0); if (hash) { *bp++ = 'x'; *bp++ = '0'; } } i = f_width - (int) (bp - buf); if (!flush_left) while (i-- > 0) { (*addchar) (pad | attributes); count++; } for (bp--; bp >= buf; bp--) (*addchar) (((unsigned char) *bp) | attributes); if (flush_left) while (i-- > 0) { (*addchar) (' ' | attributes); count++; } break; case 'c': i = va_arg(ap, int); (*addchar) (i | attributes); count++; break; case 'S': case 'Q': #ifdef SHORT_STRINGS Bp = va_arg(ap, Char *); if (!Bp) { bp = NULL; goto lcase_s; } f_width = f_width - Strlen(Bp); if (!flush_left) while (f_width-- > 0) { (*addchar) ((int) (pad | attributes)); count++; } for (i = 0; *Bp && i < prec; i++) { char cbuf[MB_LEN_MAX]; size_t pos, len; if (fmt == 'Q' && *Bp & QUOTE) { (*addchar) ('\\' | attributes); count++; } len = one_wctomb(cbuf, *Bp); for (pos = 0; pos < len; pos++) { (*addchar) ((unsigned char)cbuf[pos] | attributes | (*Bp & ATTRIBUTES)); count++; } Bp++; } if (flush_left) while (f_width-- > 0) { (*addchar) (' ' | attributes); count++; } break; #endif /* SHORT_STRINGS */ case 's': case 'q': bp = va_arg(ap, char *); lcase_s: if (!bp) bp = snil; f_width = f_width - strlen(bp); if (!flush_left) while (f_width-- > 0) { (*addchar) (pad | attributes); count++; } for (i = 0; *bp && i < prec; i++) { if (fmt == 'q' && *bp & QUOTE) { (*addchar) ('\\' | attributes); count++; } (*addchar) (((unsigned char) *bp & TRIM) | attributes); count++; bp++; } if (flush_left) while (f_width-- > 0) { (*addchar) (' ' | attributes); count++; } break; case 'a': attributes = va_arg(ap, int); break; case '%': (*addchar) ('%' | attributes); count++; break; default: break; } flush_left = 0, f_width = 0, prec = INF, hash = 0; do_ptrdiff_t = 0, do_size_t = 0, do_long = 0; sign = 0; pad = ' '; } } return count; } static char *xstring, *xestring; static void xaddchar(int c) { if (xestring == xstring) *xstring = '\0'; else *xstring++ = (char) c; } int /*VARARGS*/ xsnprintf(char *str, size_t size, const char *fmt, ...) { int count; va_list va; va_start(va, fmt); xstring = str; xestring = str + size - 1; count = doprnt(xaddchar, fmt, va); va_end(va); *xstring++ = '\0'; return count; } int /*VARARGS*/ xprintf(const char *fmt, ...) { int count; va_list va; va_start(va, fmt); count = doprnt(xputchar, fmt, va); va_end(va); return count; } int xvprintf(const char *fmt, va_list va) { return doprnt(xputchar, fmt, va); } int xvsnprintf(char *str, size_t size, const char *fmt, va_list va) { int count; xstring = str; xestring = str + size - 1; count = doprnt(xaddchar, fmt, va); *xstring++ = '\0'; return count; } char * xvasprintf(const char *fmt, va_list va) { size_t size; char *buf; buf = NULL; size = 2048; /* Arbitrary */ for (;;) { va_list copy; buf = xrealloc(buf, size); xstring = buf; xestring = buf + size - 1; va_copy(copy, va); doprnt(xaddchar, fmt, copy); va_end(copy); if (xstring < xestring) break; size *= 2; } *xstring++ = '\0'; return xrealloc(buf, xstring - buf); } char * xasprintf(const char *fmt, ...) { va_list va; char *ret; va_start (va, fmt); ret = xvasprintf(fmt, va); va_end(va); return ret; } #ifdef PURIFY /* Purify uses (some of..) the following functions to output memory-use * debugging info. Given all the messing with file descriptors that * tcsh does, the easiest way I could think of to get it (Purify) to * print anything was by replacing some standard functions with * ones that do tcsh output directly - see dumb hook in doreaddirs() * (sh.dir.c) -sg */ #ifndef FILE #define FILE int #endif -int +int fprintf(FILE *fp, const char* fmt, ...) { int count; va_list va; va_start(va, fmt); count = doprnt(xputchar, fmt, va); va_end(va); return count; } -int +int vfprintf(FILE *fp, const char *fmt, va_list va) { return doprnt(xputchar, fmt, va); } #endif /* PURIFY */ diff --git a/contrib/tcsh/tc.prompt.c b/contrib/tcsh/tc.prompt.c index f06b9596c138..8ab6da958a2d 100644 --- a/contrib/tcsh/tc.prompt.c +++ b/contrib/tcsh/tc.prompt.c @@ -1,668 +1,668 @@ /* * tc.prompt.c: Prompt printing stuff */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "ed.h" #include "tw.h" /* * kfk 21oct1983 -- add @ (time) and / ($cwd) in prompt. * PWP 4/27/87 -- rearange for tcsh. * mrdch@com.tau.edu.il 6/26/89 - added ~, T and .# - rearanged to switch() * instead of if/elseif * Luke Mewburn, * 6-Sep-91 changed date format * 16-Feb-94 rewrote directory prompt code, added $ellipsis * 29-Dec-96 added rprompt support */ static const char *month_list[12]; static const char *day_list[7]; void dateinit(void) { #ifdef notyet int i; setlocale(LC_TIME, ""); for (i = 0; i < 12; i++) xfree((ptr_t) month_list[i]); month_list[0] = strsave(_time_info->abbrev_month[0]); month_list[1] = strsave(_time_info->abbrev_month[1]); month_list[2] = strsave(_time_info->abbrev_month[2]); month_list[3] = strsave(_time_info->abbrev_month[3]); month_list[4] = strsave(_time_info->abbrev_month[4]); month_list[5] = strsave(_time_info->abbrev_month[5]); month_list[6] = strsave(_time_info->abbrev_month[6]); month_list[7] = strsave(_time_info->abbrev_month[7]); month_list[8] = strsave(_time_info->abbrev_month[8]); month_list[9] = strsave(_time_info->abbrev_month[9]); month_list[10] = strsave(_time_info->abbrev_month[10]); month_list[11] = strsave(_time_info->abbrev_month[11]); for (i = 0; i < 7; i++) xfree((ptr_t) day_list[i]); day_list[0] = strsave(_time_info->abbrev_wkday[0]); day_list[1] = strsave(_time_info->abbrev_wkday[1]); day_list[2] = strsave(_time_info->abbrev_wkday[2]); day_list[3] = strsave(_time_info->abbrev_wkday[3]); day_list[4] = strsave(_time_info->abbrev_wkday[4]); day_list[5] = strsave(_time_info->abbrev_wkday[5]); day_list[6] = strsave(_time_info->abbrev_wkday[6]); #else month_list[0] = "Jan"; month_list[1] = "Feb"; month_list[2] = "Mar"; month_list[3] = "Apr"; month_list[4] = "May"; month_list[5] = "Jun"; month_list[6] = "Jul"; month_list[7] = "Aug"; month_list[8] = "Sep"; month_list[9] = "Oct"; month_list[10] = "Nov"; month_list[11] = "Dec"; day_list[0] = "Sun"; day_list[1] = "Mon"; day_list[2] = "Tue"; day_list[3] = "Wed"; day_list[4] = "Thu"; day_list[5] = "Fri"; day_list[6] = "Sat"; #endif } void printprompt(int promptno, const char *str) { static const Char *ocp = NULL; static const char *ostr = NULL; time_t lclock = time(NULL); const Char *cp; switch (promptno) { default: case 0: cp = varval(STRprompt); break; case 1: cp = varval(STRprompt2); break; case 2: cp = varval(STRprompt3); break; case 3: if (ocp != NULL) { cp = ocp; str = ostr; } - else + else cp = varval(STRprompt); break; } if (promptno < 2) { ocp = cp; ostr = str; } xfree(Prompt); Prompt = NULL; Prompt = tprintf(FMT_PROMPT, cp, str, lclock, NULL); if (!editing) { for (cp = Prompt; *cp ; ) (void) putwraw(*cp++); SetAttributes(0); flush(); } xfree(RPrompt); RPrompt = NULL; if (promptno == 0) { /* determine rprompt if using main prompt */ cp = varval(STRrprompt); RPrompt = tprintf(FMT_PROMPT, cp, NULL, lclock, NULL); /* if not editing, put rprompt after prompt */ if (!editing && RPrompt[0] != '\0') { for (cp = RPrompt; *cp ; ) (void) putwraw(*cp++); SetAttributes(0); putraw(' '); flush(); } } } static void tprintf_append_mbs(struct Strbuf *buf, const char *mbs, Char attributes) { while (*mbs != 0) { Char wc; mbs += one_mbtowc(&wc, mbs, MB_LEN_MAX); Strbuf_append1(buf, wc | attributes); } } Char * tprintf(int what, const Char *fmt, const char *str, time_t tim, ptr_t info) { struct Strbuf buf = Strbuf_INIT; Char *z, *q; Char attributes = 0; static int print_prompt_did_ding = 0; char *cz; Char *p; const Char *cp = fmt; Char Scp; struct tm *t = localtime(&tim); /* prompt stuff */ static Char *olduser = NULL; int updirs; size_t pdirs; cleanup_push(&buf, Strbuf_cleanup); for (; *cp; cp++) { if ((*cp == '%') && ! (cp[1] == '\0')) { cp++; switch (*cp) { case 'R': if (what == FMT_HISTORY) { cz = fmthist('R', info); tprintf_append_mbs(&buf, cz, attributes); xfree(cz); } else { if (str != NULL) tprintf_append_mbs(&buf, str, attributes); } break; case '#': #ifdef __CYGWIN__ /* Check for being member of the Administrators group */ { gid_t grps[NGROUPS_MAX]; int grp, gcnt; gcnt = getgroups(NGROUPS_MAX, grps); # define DOMAIN_GROUP_RID_ADMINS 544 for (grp = 0; grp < gcnt; ++grp) if (grps[grp] == DOMAIN_GROUP_RID_ADMINS) break; Scp = (grp < gcnt) ? PRCHROOT : PRCH; } #else Scp = (uid == 0 || euid == 0) ? PRCHROOT : PRCH; #endif if (Scp != '\0') Strbuf_append1(&buf, attributes | Scp); break; case '!': case 'h': switch (what) { case FMT_HISTORY: cz = fmthist('h', info); break; case FMT_SCHED: cz = xasprintf("%d", *(int *)info); break; default: cz = xasprintf("%d", eventno + 1); break; } tprintf_append_mbs(&buf, cz, attributes); xfree(cz); break; case 'T': /* 24 hour format */ case '@': case 't': /* 12 hour am/pm format */ case 'p': /* With seconds */ case 'P': { char ampm = 'a'; int hr = t->tm_hour; /* addition by Hans J. Albertsson */ /* and another adapted from Justin Bur */ if (adrof(STRampm) || (*cp != 'T' && *cp != 'P')) { if (hr >= 12) { if (hr > 12) hr -= 12; ampm = 'p'; } else if (hr == 0) hr = 12; } /* else do a 24 hour clock */ /* "DING!" stuff by Hans also */ - if (t->tm_min || print_prompt_did_ding || + if (t->tm_min || print_prompt_did_ding || what != FMT_PROMPT || adrof(STRnoding)) { if (t->tm_min) print_prompt_did_ding = 0; /* * Pad hour to 2 characters if padhour is set, * by ADAM David Alan Martin */ p = Itoa(hr, adrof(STRpadhour) ? 2 : 0, attributes); Strbuf_append(&buf, p); xfree(p); Strbuf_append1(&buf, attributes | ':'); p = Itoa(t->tm_min, 2, attributes); Strbuf_append(&buf, p); xfree(p); if (*cp == 'p' || *cp == 'P') { Strbuf_append1(&buf, attributes | ':'); p = Itoa(t->tm_sec, 2, attributes); Strbuf_append(&buf, p); xfree(p); } if (adrof(STRampm) || (*cp != 'T' && *cp != 'P')) { Strbuf_append1(&buf, attributes | ampm); Strbuf_append1(&buf, attributes | 'm'); } } else { /* we need to ding */ size_t i; for (i = 0; STRDING[i] != 0; i++) Strbuf_append1(&buf, attributes | STRDING[i]); print_prompt_did_ding = 1; } } break; case 'M': #ifndef HAVENOUTMP if (what == FMT_WHO) cz = who_info(info, 'M'); - else + else #endif /* HAVENOUTMP */ cz = getenv("HOST"); /* * Bug pointed out by Laurent Dami : don't * derefrence that NULL (if HOST is not set)... */ if (cz != NULL) tprintf_append_mbs(&buf, cz, attributes); if (what == FMT_WHO) xfree(cz); break; case 'm': { char *scz = NULL; #ifndef HAVENOUTMP if (what == FMT_WHO) scz = cz = who_info(info, 'm'); else #endif /* HAVENOUTMP */ cz = getenv("HOST"); if (cz != NULL) while (*cz != 0 && (what == FMT_WHO || *cz != '.')) { Char wc; cz += one_mbtowc(&wc, cz, MB_LEN_MAX); Strbuf_append1(&buf, wc | attributes); } if (scz) xfree(scz); break; } /* lukem: new directory prompt code */ case '~': case '/': case '.': case 'c': case 'C': Scp = *cp; if (Scp == 'c') /* store format type (c == .) */ Scp = '.'; if ((z = varval(STRcwd)) == STRNULL) break; /* no cwd, so don't do anything */ /* show ~ whenever possible - a la dirs */ if (Scp == '~' || Scp == '.' ) { static Char *olddir = NULL; if (tlength == 0 || olddir != z) { olddir = z; /* have we changed dir? */ olduser = getusername(&olddir); } if (olduser) z = olddir; } updirs = pdirs = 0; /* option to determine fixed # of dirs from path */ if (Scp == '.' || Scp == 'C') { int skip; #ifdef WINNT_NATIVE Char *oldz = z; if (z[1] == ':') { Strbuf_append1(&buf, attributes | *z++); Strbuf_append1(&buf, attributes | *z++); } if (*z == '/' && z[1] == '/') { Strbuf_append1(&buf, attributes | *z++); Strbuf_append1(&buf, attributes | *z++); do { Strbuf_append1(&buf, attributes | *z++); } while (*z != '/'); } #endif /* WINNT_NATIVE */ q = z; while (*z) /* calc # of /'s */ if (*z++ == '/') updirs++; #ifdef WINNT_NATIVE /* * for format type c, prompt will be following... * c:/path => c:/path * c:/path/to => c:to * //machine/share => //machine/share * //machine/share/folder => //machine:folder */ if (oldz[0] == '/' && oldz[1] == '/' && updirs > 1) Strbuf_append1(&buf, attributes | ':'); #endif /* WINNT_NATIVE */ if ((Scp == 'C' && *q != '/')) updirs++; if (cp[1] == '0') { /* print or ... */ pdirs = 1; cp++; } if (cp[1] >= '1' && cp[1] <= '9') { /* calc # to skip */ skip = cp[1] - '0'; cp++; } else skip = 1; updirs -= skip; while (skip-- > 0) { while ((z > q) && (*z != '/')) z--; /* back up */ if (skip && z > q) z--; } if (*z == '/' && z != q) z++; } /* . || C */ /* print ~[user] */ if ((olduser) && ((Scp == '~') || (Scp == '.' && (pdirs || (!pdirs && updirs <= 0))) )) { Strbuf_append1(&buf, attributes | '~'); for (q = olduser; *q; q++) Strbuf_append1(&buf, attributes | *q); } /* RWM - tell you how many dirs we've ignored */ /* and add '/' at front of this */ if (updirs > 0 && pdirs) { if (adrof(STRellipsis)) { Strbuf_append1(&buf, attributes | '.'); Strbuf_append1(&buf, attributes | '.'); Strbuf_append1(&buf, attributes | '.'); } else { Strbuf_append1(&buf, attributes | '/'); Strbuf_append1(&buf, attributes | '<'); if (updirs > 9) { Strbuf_append1(&buf, attributes | '9'); Strbuf_append1(&buf, attributes | '+'); } else Strbuf_append1(&buf, attributes | ('0' + updirs)); Strbuf_append1(&buf, attributes | '>'); } } while (*z) Strbuf_append1(&buf, attributes | *z++); break; /* lukem: end of new directory prompt code */ case 'n': #ifndef HAVENOUTMP if (what == FMT_WHO) { cz = who_info(info, 'n'); tprintf_append_mbs(&buf, cz, attributes); xfree(cz); } - else + else #endif /* HAVENOUTMP */ { if ((z = varval(STRuser)) != STRNULL) while (*z) Strbuf_append1(&buf, attributes | *z++); } break; case 'N': if ((z = varval(STReuser)) != STRNULL) while (*z) Strbuf_append1(&buf, attributes | *z++); break; case 'l': #ifndef HAVENOUTMP if (what == FMT_WHO) { cz = who_info(info, 'l'); tprintf_append_mbs(&buf, cz, attributes); xfree(cz); } - else + else #endif /* HAVENOUTMP */ { if ((z = varval(STRtty)) != STRNULL) while (*z) Strbuf_append1(&buf, attributes | *z++); } break; case 'd': tprintf_append_mbs(&buf, day_list[t->tm_wday], attributes); break; case 'D': p = Itoa(t->tm_mday, 2, attributes); Strbuf_append(&buf, p); xfree(p); break; case 'w': tprintf_append_mbs(&buf, month_list[t->tm_mon], attributes); break; case 'W': p = Itoa(t->tm_mon + 1, 2, attributes); Strbuf_append(&buf, p); xfree(p); break; case 'y': p = Itoa(t->tm_year % 100, 2, attributes); Strbuf_append(&buf, p); xfree(p); break; case 'Y': p = Itoa(t->tm_year + 1900, 4, attributes); Strbuf_append(&buf, p); xfree(p); break; case 'S': /* start standout */ attributes |= STANDOUT; break; case 'B': /* start bold */ attributes |= BOLD; break; case 'U': /* start underline */ attributes |= UNDER; break; case 's': /* end standout */ attributes &= ~STANDOUT; break; case 'b': /* end bold */ attributes &= ~BOLD; break; case 'u': /* end underline */ attributes &= ~UNDER; break; case 'L': ClearToBottom(); break; case 'j': { int njobs = -1; struct process *pp; for (pp = proclist.p_next; pp; pp = pp->p_next) njobs++; if (njobs == -1) njobs++; p = Itoa(njobs, 1, attributes); Strbuf_append(&buf, p); xfree(p); break; } case '?': if ((z = varval(STRstatus)) != STRNULL) while (*z) Strbuf_append1(&buf, attributes | *z++); break; case '$': expdollar(&buf, &cp, attributes); /* cp should point the last char of current % sequence */ cp--; break; case '%': Strbuf_append1(&buf, attributes | '%'); break; case '{': /* literal characters start */ #if LITERAL == 0 /* * No literal capability, so skip all chars in the literal * string */ while (*cp != '\0' && (cp[-1] != '%' || *cp != '}')) cp++; #endif /* LITERAL == 0 */ attributes |= LITERAL; break; case '}': /* literal characters end */ attributes &= ~LITERAL; break; default: #ifndef HAVENOUTMP if (*cp == 'a' && what == FMT_WHO) { cz = who_info(info, 'a'); tprintf_append_mbs(&buf, cz, attributes); xfree(cz); } else #endif /* HAVENOUTMP */ { Strbuf_append1(&buf, attributes | '%'); Strbuf_append1(&buf, attributes | *cp); } break; } } else if (*cp == '\\' || *cp == '^') Strbuf_append1(&buf, attributes | parseescape(&cp)); else if (*cp == HIST) { /* EGS: handle '!'s in prompts */ if (what == FMT_HISTORY) cz = fmthist('h', info); else cz = xasprintf("%d", eventno + 1); tprintf_append_mbs(&buf, cz, attributes); xfree(cz); } else Strbuf_append1(&buf, attributes | *cp); /* normal character */ } cleanup_ignore(&buf); cleanup_until(&buf); return Strbuf_finish(&buf); } int expdollar(struct Strbuf *buf, const Char **srcp, Char attr) { struct varent *vp; const Char *src = *srcp; Char *var, *val; size_t i; int curly = 0; /* found a variable, expand it */ var = xmalloc((Strlen(src) + 1) * sizeof (*var)); for (i = 0; ; i++) { var[i] = *++src & TRIM; if (i == 0 && var[i] == '{') { curly = 1; var[i] = *++src & TRIM; } if (!alnum(var[i]) && var[i] != '_') { var[i] = '\0'; break; } } if (curly && (*src & TRIM) == '}') src++; vp = adrof(var); if (vp && vp->vec) { for (i = 0; vp->vec[i] != NULL; i++) { for (val = vp->vec[i]; *val; val++) if (*val != '\n' && *val != '\r') Strbuf_append1(buf, *val | attr); if (vp->vec[i+1]) Strbuf_append1(buf, ' ' | attr); } } else { val = (!vp) ? tgetenv(var) : NULL; if (val) { for (; *val; val++) if (*val != '\n' && *val != '\r') Strbuf_append1(buf, *val | attr); } else { *srcp = src; xfree(var); return 0; } } *srcp = src; xfree(var); return 1; } diff --git a/contrib/tcsh/tc.str.c b/contrib/tcsh/tc.str.c index 88c4e8cb689e..0ad79404c769 100644 --- a/contrib/tcsh/tc.str.c +++ b/contrib/tcsh/tc.str.c @@ -1,710 +1,710 @@ /* * tc.str.c: Short string package * This has been a lesson of how to write buggy code! */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include #include #define MALLOC_INCR 128 #ifdef WIDE_STRINGS #define MALLOC_SURPLUS MB_LEN_MAX /* Space for one multibyte character */ #else #define MALLOC_SURPLUS 0 #endif #ifdef WIDE_STRINGS size_t one_mbtowc(Char *pwc, const char *s, size_t n) { int len; len = rt_mbtowc(pwc, s, n); if (len == -1) { reset_mbtowc(); *pwc = (unsigned char)*s | INVALID_BYTE; } if (len <= 0) len = 1; return len; } size_t one_wctomb(char *s, Char wchar) { int len; #if INVALID_BYTE != 0 if ((wchar & INVALID_BYTE) == INVALID_BYTE) { /* wchar >= INVALID_BYTE */ /* invalid char * exmaple) * if wchar = f0000090(=90|INVALID_BYTE), then *s = ffffff90 */ *s = (char)wchar; len = 1; #else if (wchar & (CHAR & INVALID_BYTE)) { s[0] = wchar & (CHAR & 0xFF); len = 1; #endif } else { #if INVALID_BYTE != 0 wchar &= MAX_UTF32; #else wchar &= CHAR; #endif #ifdef UTF16_STRINGS if (wchar >= 0x10000) { /* UTF-16 systems can't handle these values directly in calls to wctomb. Convert value to UTF-16 surrogate and call wcstombs to convert the "string" to the correct multibyte representation, if any. */ wchar_t ws[3]; wchar -= 0x10000; ws[0] = 0xd800 | (wchar >> 10); ws[1] = 0xdc00 | (wchar & 0x3ff); ws[2] = 0; /* The return value of wcstombs excludes the trailing 0, so len is the correct number of multibytes for the Unicode char. */ len = wcstombs (s, ws, MB_CUR_MAX + 1); } else #endif len = wctomb(s, (wchar_t) wchar); if (len == -1) s[0] = wchar; if (len <= 0) len = 1; } return len; } int rt_mbtowc(Char *pwc, const char *s, size_t n) { int ret; char back[MB_LEN_MAX]; wchar_t tmp; #if defined(UTF16_STRINGS) && defined(HAVE_MBRTOWC) # if defined(AUTOSET_KANJI) static mbstate_t mb_zero, mb; /* * Workaround the Shift-JIS endcoding that translates unshifted 7 bit ASCII! */ if (!adrof(STRnokanji) && n && pwc && s && (*s == '\\' || *s == '~') && !memcmp(&mb, &mb_zero, sizeof(mb))) { *pwc = *s; return 1; } # else mbstate_t mb; # endif memset (&mb, 0, sizeof mb); ret = mbrtowc(&tmp, s, n, &mb); #else ret = mbtowc(&tmp, s, n); #endif if (ret > 0) { *pwc = tmp; #if defined(UTF16_STRINGS) && defined(HAVE_MBRTOWC) if (tmp >= 0xd800 && tmp <= 0xdbff) { /* UTF-16 surrogate pair. Fetch second half and compute UTF-32 value. Dispense with the inverse test in this case. */ size_t n2 = mbrtowc(&tmp, s + ret, n - ret, &mb); if (n2 == 0 || n2 == (size_t)-1 || n2 == (size_t)-2) ret = -1; else { *pwc = (((*pwc & 0x3ff) << 10) | (tmp & 0x3ff)) + 0x10000; ret += n2; } } else #endif if (wctomb(back, *pwc) != ret || memcmp(s, back, ret) != 0) ret = -1; } else if (ret == -2) ret = -1; else if (ret == 0) *pwc = '\0'; return ret; } #endif #ifdef SHORT_STRINGS Char ** blk2short(char **src) { size_t n; Char **sdst, **dst; /* * Count */ for (n = 0; src[n] != NULL; n++) continue; sdst = dst = xmalloc((n + 1) * sizeof(Char *)); for (; *src != NULL; src++) *dst++ = SAVE(*src); *dst = NULL; return (sdst); } char ** short2blk(Char **src) { size_t n; char **sdst, **dst; /* * Count */ for (n = 0; src[n] != NULL; n++) continue; sdst = dst = xmalloc((n + 1) * sizeof(char *)); for (; *src != NULL; src++) *dst++ = strsave(short2str(*src)); *dst = NULL; return (sdst); } Char * str2short(const char *src) { static struct Strbuf buf; /* = Strbuf_INIT; */ if (src == NULL) return (NULL); buf.len = 0; while (*src) { Char wc; src += one_mbtowc(&wc, src, MB_LEN_MAX); Strbuf_append1(&buf, wc); } Strbuf_terminate(&buf); return buf.s; } char * short2str(const Char *src) { static char *sdst = NULL; static size_t dstsize = 0; char *dst, *edst; if (src == NULL) return (NULL); if (sdst == NULL) { dstsize = MALLOC_INCR; sdst = xmalloc((dstsize + MALLOC_SURPLUS) * sizeof(char)); } dst = sdst; edst = &dst[dstsize]; while (*src) { dst += one_wctomb(dst, *src); src++; if (dst >= edst) { char *wdst = dst; char *wedst = edst; dstsize += MALLOC_INCR; sdst = xrealloc(sdst, (dstsize + MALLOC_SURPLUS) * sizeof(char)); edst = &sdst[dstsize]; dst = &edst[-MALLOC_INCR]; while (wdst > wedst) { dst++; wdst--; } } } *dst = 0; return (sdst); } #if !defined (WIDE_STRINGS) || defined (UTF16_STRINGS) Char * s_strcpy(Char *dst, const Char *src) { Char *sdst; sdst = dst; while ((*dst++ = *src++) != '\0') continue; return (sdst); } Char * s_strncpy(Char *dst, const Char *src, size_t n) { Char *sdst; if (n == 0) return(dst); sdst = dst; - do + do if ((*dst++ = *src++) == '\0') { while (--n != 0) *dst++ = '\0'; return(sdst); } while (--n != 0); return (sdst); } Char * s_strcat(Char *dst, const Char *src) { Strcpy(Strend(dst), src); return dst; } #ifdef NOTUSED Char * s_strncat(Char *dst, const Char *src, size_t n) { Char *sdst; - if (n == 0) + if (n == 0) return (dst); sdst = dst; while (*dst) dst++; - do + do if ((*dst++ = *src++) == '\0') return(sdst); while (--n != 0) continue; *dst = '\0'; return (sdst); } #endif Char * s_strchr(const Char *str, int ch) { do if (*str == ch) return ((Char *)(intptr_t)str); while (*str++); return (NULL); } Char * s_strrchr(const Char *str, int ch) { const Char *rstr; rstr = NULL; do if (*str == ch) rstr = str; while (*str++); return ((Char *)(intptr_t)rstr); } size_t s_strlen(const Char *str) { size_t n; for (n = 0; *str++; n++) continue; return (n); } int s_strcmp(const Char *str1, const Char *str2) { for (; *str1 && *str1 == *str2; str1++, str2++) continue; /* * The following case analysis is necessary so that characters which look * negative collate low against normal characters but high against the * end-of-string NUL. */ if (*str1 == '\0' && *str2 == '\0') return (0); else if (*str1 == '\0') return (-1); else if (*str2 == '\0') return (1); else return (*str1 - *str2); } int s_strncmp(const Char *str1, const Char *str2, size_t n) { if (n == 0) return (0); do { if (*str1 != *str2) { /* - * The following case analysis is necessary so that characters + * The following case analysis is necessary so that characters * which look negative collate low against normal characters * but high against the end-of-string NUL. */ if (*str1 == '\0') return (-1); else if (*str2 == '\0') return (1); else return (*str1 - *str2); } if (*str1 == '\0') return(0); str1++, str2++; } while (--n != 0); return(0); } #endif /* not WIDE_STRINGS */ int s_strcasecmp(const Char *str1, const Char *str2) { #ifdef WIDE_STRINGS wint_t l1 = 0, l2 = 0; for (; *str1; str1++, str2++) if (*str1 == *str2) l1 = l2 = 0; else if ((l1 = towlower(*str1)) != (l2 = towlower(*str2))) break; #else unsigned char l1 = 0, l2 = 0; for (; *str1; str1++, str2++) if (*str1 == *str2) l1 = l2 = 0; else if ((l1 = tolower((unsigned char)*str1)) != (l2 = tolower((unsigned char)*str2))) break; #endif /* * The following case analysis is necessary so that characters which look * negative collate low against normal characters but high against the * end-of-string NUL. */ if (*str1 == '\0' && *str2 == '\0') return (0); else if (*str1 == '\0') return (-1); else if (*str2 == '\0') return (1); else if (l1 == l2) /* They are zero when they are equal */ return (*str1 - *str2); else return (l1 - l2); } Char * s_strnsave(const Char *s, size_t len) { Char *n; n = xmalloc((len + 1) * sizeof (*n)); memcpy(n, s, len * sizeof (*n)); n[len] = '\0'; return n; } Char * s_strsave(const Char *s) { Char *n; size_t size; if (s == NULL) s = STRNULL; size = (Strlen(s) + 1) * sizeof(*n); n = xmalloc(size); memcpy(n, s, size); return (n); } Char * s_strspl(const Char *cp, const Char *dp) { Char *res, *ep; const Char *p, *q; if (!cp) cp = STRNULL; if (!dp) dp = STRNULL; for (p = cp; *p++;) continue; for (q = dp; *q++;) continue; res = xmalloc(((p - cp) + (q - dp) - 1) * sizeof(Char)); for (ep = res, q = cp; (*ep++ = *q++) != '\0';) continue; for (ep--, q = dp; (*ep++ = *q++) != '\0';) continue; return (res); } Char * s_strend(const Char *cp) { if (!cp) return ((Char *)(intptr_t) cp); while (*cp) cp++; return ((Char *)(intptr_t) cp); } Char * s_strstr(const Char *s, const Char *t) { do { const Char *ss = s; const Char *tt = t; do if (*tt == '\0') return ((Char *)(intptr_t) s); while (*ss++ == *tt++); } while (*s++ != '\0'); return (NULL); } #else /* !SHORT_STRINGS */ char * caching_strip(const char *s) { static char *buf = NULL; static size_t buf_size = 0; size_t size; if (s == NULL) return NULL; size = strlen(s) + 1; if (buf_size < size) { buf = xrealloc(buf, size); buf_size = size; } memcpy(buf, s, size); strip(buf); return buf; } #endif char * short2qstr(const Char *src) { static char *sdst = NULL; static size_t dstsize = 0; char *dst, *edst; if (src == NULL) return (NULL); if (sdst == NULL) { dstsize = MALLOC_INCR; sdst = xmalloc((dstsize + MALLOC_SURPLUS) * sizeof(char)); } dst = sdst; edst = &dst[dstsize]; while (*src) { if (*src & QUOTE) { *dst++ = '\\'; if (dst == edst) { dstsize += MALLOC_INCR; sdst = xrealloc(sdst, (dstsize + MALLOC_SURPLUS) * sizeof(char)); edst = &sdst[dstsize]; dst = &edst[-MALLOC_INCR]; } } dst += one_wctomb(dst, *src); src++; if (dst >= edst) { ptrdiff_t i = dst - edst; dstsize += MALLOC_INCR; sdst = xrealloc(sdst, (dstsize + MALLOC_SURPLUS) * sizeof(char)); edst = &sdst[dstsize]; dst = &edst[-MALLOC_INCR + i]; } } *dst = 0; return (sdst); } struct blk_buf * bb_alloc(void) { return xcalloc(1, sizeof(struct blk_buf)); } static void bb_store(struct blk_buf *bb, Char *str) { if (bb->len == bb->size) { /* Keep space for terminating NULL */ if (bb->size == 0) bb->size = 16; /* Arbitrary */ else bb->size *= 2; bb->vec = xrealloc(bb->vec, bb->size * sizeof (*bb->vec)); } bb->vec[bb->len] = str; } void bb_append(struct blk_buf *bb, Char *str) { bb_store(bb, str); bb->len++; } void bb_cleanup(void *xbb) { struct blk_buf *bb; size_t i; bb = (struct blk_buf *)xbb; if (bb->vec) { for (i = 0; i < bb->len; i++) xfree(bb->vec[i]); xfree(bb->vec); } bb->vec = NULL; bb->len = 0; } void bb_free(void *bb) { bb_cleanup(bb); xfree(bb); } Char ** bb_finish(struct blk_buf *bb) { bb_store(bb, NULL); return xrealloc(bb->vec, (bb->len + 1) * sizeof (*bb->vec)); } #define DO_STRBUF(STRBUF, CHAR, STRLEN) \ \ struct STRBUF * \ STRBUF##_alloc(void) \ { \ return xcalloc(1, sizeof(struct STRBUF)); \ } \ \ static void \ STRBUF##_store1(struct STRBUF *buf, CHAR c) \ { \ if (buf->size == buf->len) { \ if (buf->size == 0) \ buf->size = 64; /* Arbitrary */ \ else \ buf->size *= 2; \ buf->s = xrealloc(buf->s, buf->size * sizeof(*buf->s)); \ } \ assert(buf->s); \ buf->s[buf->len] = c; \ } \ \ /* Like strbuf_append1(buf, '\0'), but don't advance len */ \ void \ STRBUF##_terminate(struct STRBUF *buf) \ { \ STRBUF##_store1(buf, '\0'); \ } \ \ void \ STRBUF##_append1(struct STRBUF *buf, CHAR c) \ { \ STRBUF##_store1(buf, c); \ buf->len++; \ } \ \ void \ STRBUF##_appendn(struct STRBUF *buf, const CHAR *s, size_t len) \ { \ if (buf->size < buf->len + len) { \ if (buf->size == 0) \ buf->size = 64; /* Arbitrary */ \ while (buf->size < buf->len + len) \ buf->size *= 2; \ buf->s = xrealloc(buf->s, buf->size * sizeof(*buf->s)); \ } \ memcpy(buf->s + buf->len, s, len * sizeof(*buf->s)); \ buf->len += len; \ } \ \ void \ STRBUF##_append(struct STRBUF *buf, const CHAR *s) \ { \ STRBUF##_appendn(buf, s, STRLEN(s)); \ } \ \ CHAR * \ STRBUF##_finish(struct STRBUF *buf) \ { \ STRBUF##_append1(buf, 0); \ return xrealloc(buf->s, buf->len * sizeof(*buf->s)); \ } \ \ void \ STRBUF##_cleanup(void *xbuf) \ { \ struct STRBUF *buf; \ \ buf = xbuf; \ xfree(buf->s); \ } \ \ void \ STRBUF##_free(void *xbuf) \ { \ STRBUF##_cleanup(xbuf); \ xfree(xbuf); \ } \ \ const struct STRBUF STRBUF##_init /* = STRBUF##_INIT; */ DO_STRBUF(strbuf, char, strlen); DO_STRBUF(Strbuf, Char, Strlen); diff --git a/contrib/tcsh/tc.vers.c b/contrib/tcsh/tc.vers.c index c6aeb1292e85..6b739e5cb2ce 100644 --- a/contrib/tcsh/tc.vers.c +++ b/contrib/tcsh/tc.vers.c @@ -1,171 +1,171 @@ /* * tc.vers.c: Version dependent stuff */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "tw.h" #include "patchlevel.h" /* fix_version(): * Print a reasonable version string, printing all compile time * options that might affect the user. */ void fix_version(void) { #ifdef WIDE_STRINGS # define SSSTR "wide" #elif defined (SHORT_STRINGS) # define SSSTR "8b" #else # define SSSTR "7b" -#endif +#endif #ifdef NLS # define NLSSTR ",nls" #else # define NLSSTR "" -#endif +#endif #ifdef LOGINFIRST # define LFSTR ",lf" #else # define LFSTR "" -#endif +#endif #ifdef DOTLAST # define DLSTR ",dl" #else # define DLSTR "" -#endif +#endif #ifdef VIDEFAULT # define VISTR ",vi" #else # define VISTR "" -#endif +#endif #ifdef TESLA # define DTRSTR ",dtr" #else # define DTRSTR "" -#endif +#endif #ifdef KAI # define BYESTR ",bye" #else # define BYESTR "" -#endif +#endif #ifdef AUTOLOGOUT # define ALSTR ",al" #else # define ALSTR "" -#endif +#endif #ifdef KANJI # define KANSTR ",kan" #else # define KANSTR "" -#endif +#endif #ifdef SYSMALLOC # define SMSTR ",sm" #else # define SMSTR "" -#endif +#endif #ifdef HASHBANG # define HBSTR ",hb" #else # define HBSTR "" -#endif +#endif #ifdef NEWGRP # define NGSTR ",ng" #else # define NGSTR "" #endif #ifdef REMOTEHOST # define RHSTR ",rh" #else # define RHSTR "" #endif #ifdef AFS # define AFSSTR ",afs" #else # define AFSSTR "" #endif #ifdef NODOT # define NDSTR ",nd" #else # define NDSTR "" #endif #ifdef COLOR_LS_F # define COLORSTR ",color" #else /* ifndef COLOR_LS_F */ # define COLORSTR "" #endif /* COLOR_LS_F */ #ifdef DSPMBYTE # define DSPMSTR ",dspm" #else # define DSPMSTR "" #endif #ifdef COLORCAT # define CCATSTR ",ccat" #else # define CCATSTR "" #endif #if defined(FILEC) && defined(TIOCSTI) # define FILECSTR ",filec" #else # define FILECSTR "" #endif /* if you want your local version to say something */ #ifndef LOCALSTR # define LOCALSTR "" #endif /* LOCALSTR */ char *version; const Char *machtype = tgetenv(STRMACHTYPE); const Char *vendor = tgetenv(STRVENDOR); const Char *ostype = tgetenv(STROSTYPE); if (vendor == NULL) vendor = STRunknown; if (machtype == NULL) machtype = STRunknown; if (ostype == NULL) ostype = STRunknown; version = xasprintf( "tcsh %d.%.2d.%.2d (%s) %s (%S-%S-%S) options %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", REV, VERS, PATCHLEVEL, ORIGIN, DATE, machtype, vendor, ostype, SSSTR, NLSSTR, LFSTR, DLSTR, VISTR, DTRSTR, BYESTR, ALSTR, KANSTR, SMSTR, HBSTR, NGSTR, RHSTR, AFSSTR, NDSTR, COLORSTR, DSPMSTR, CCATSTR, FILECSTR, LOCALSTR); cleanup_push(version, xfree); setcopy(STRversion, str2short(version), VAR_READWRITE); cleanup_until(version); version = xasprintf("%d.%.2d.%.2d", REV, VERS, PATCHLEVEL); cleanup_push(version, xfree); setcopy(STRtcsh, str2short(version), VAR_READWRITE); cleanup_until(version); } diff --git a/contrib/tcsh/tc.who.c b/contrib/tcsh/tc.who.c index a42284db122c..d1d0ce56c327 100644 --- a/contrib/tcsh/tc.who.c +++ b/contrib/tcsh/tc.who.c @@ -1,645 +1,645 @@ /* * tc.who.c: Watch logins and logouts... */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "tc.h" #ifndef HAVENOUTMP /* * kfk 26 Jan 1984 - for login watch functions. */ #include #ifdef HAVE_UTMPX_H # include # define UTNAMLEN sizeof(((struct utmpx *) 0)->ut_name) # define UTLINLEN sizeof(((struct utmpx *) 0)->ut_line) # ifdef HAVE_STRUCT_UTMPX_UT_HOST # define UTHOSTLEN sizeof(((struct utmpx *) 0)->ut_host) # endif /* I just redefine a few words here. Changing every occurrence below * seems like too much of work. All UTMP functions have equivalent * UTMPX counterparts, so they can be added all here when needed. * Kimmo Suominen, Oct 14 1991 */ # if defined(__UTMPX_FILE) && !defined(UTMPX_FILE) # define TCSH_PATH_UTMP __UTMPX_FILE # elif defined(_PATH_UTMPX) # define TCSH_PATH_UTMP _PATH_UTMPX # elif defined(UTMPX_FILE) # define TCSH_PATH_UTMP UTMPX_FILE # elif __FreeBSD_version >= 900000 # /* Why isn't this defined somewhere? */ # define TCSH_PATH_UTMP "/var/run/utx.active" # elif defined(__hpux) # define TCSH_PATH_UTMP "/etc/utmpx" # elif defined(IBMAIX) && defined(UTMP_FILE) # define TCSH_PATH_UTMP UTMP_FILE # endif # if defined(TCSH_PATH_UTMP) || !defined(HAVE_UTMP_H) # define utmp utmpx # define TCSH_USE_UTMPX # if defined(HAVE_GETUTENT) || defined(HAVE_GETUTXENT) # define getutent getutxent # define setutent setutxent # define endutent endutxent # endif /* HAVE_GETUTENT || HAVE_GETUTXENT */ # if defined(HAVE_STRUCT_UTMPX_UT_TV) # define ut_time ut_tv.tv_sec # elif defined(HAVE_STRUCT_UTMPX_UT_XTIME) # define ut_time ut_xtime # endif # if defined(HAVE_STRUCT_UTMPX_UT_USER) # define ut_name ut_user # endif # endif /* TCSH_PATH_UTMP || !HAVE_UTMP_H */ #endif /* HAVE_UTMPX_H */ #if !defined(TCSH_USE_UTMPX) && defined(HAVE_UTMP_H) # include # if defined(HAVE_STRUCT_UTMP_UT_TV) # define ut_time ut_tv.tv_sec # elif defined(HAVE_STRUCT_UTMP_UT_XTIME) # define ut_time ut_xtime # endif # if defined(HAVE_STRUCT_UTMP_UT_USER) # define ut_name ut_user # endif # ifndef BROKEN_CC # define UTNAMLEN sizeof(((struct utmp *) 0)->ut_name) # define UTLINLEN sizeof(((struct utmp *) 0)->ut_line) # ifdef HAVE_STRUCT_UTMP_UT_HOST # ifdef _SEQUENT_ # define UTHOSTLEN 100 # else # define UTHOSTLEN sizeof(((struct utmp *) 0)->ut_host) # endif # endif /* HAVE_STRUCT_UTMP_UT_HOST */ # else /* give poor cc a little help if it needs it */ struct utmp __ut; # define UTNAMLEN sizeof(__ut.ut_name) # define UTLINLEN sizeof(__ut.ut_line) # ifdef HAVE_STRUCT_UTMP_UT_HOST # ifdef _SEQUENT_ # define UTHOSTLEN 100 # else # define UTHOSTLEN sizeof(__ut.ut_host) # endif # endif /* HAVE_STRUCT_UTMP_UT_HOST */ # endif /* BROKEN_CC */ # ifndef TCSH_PATH_UTMP # ifdef UTMP_FILE # define TCSH_PATH_UTMP UTMP_FILE # elif defined(_PATH_UTMP) # define TCSH_PATH_UTMP _PATH_UTMP # else # define TCSH_PATH_UTMP "/etc/utmp" # endif /* UTMP_FILE */ # endif /* TCSH_PATH_UTMP */ #endif /* !TCSH_USE_UTMPX && HAVE_UTMP_H */ #ifndef UTNAMLEN #define UTNAMLEN 64 #endif #ifndef UTLINLEN #define UTLINLEN 64 #endif struct who { struct who *who_next; struct who *who_prev; char who_name[UTNAMLEN + 1]; char who_new[UTNAMLEN + 1]; char who_tty[UTLINLEN + 1]; #ifdef UTHOSTLEN char who_host[UTHOSTLEN + 1]; #endif /* UTHOSTLEN */ time_t who_time; int who_status; }; static struct who whohead, whotail; static time_t watch_period = 0; static time_t stlast = 0; #ifdef WHODEBUG static void debugwholist (struct who *, struct who *); #endif static void print_who (struct who *); #define ONLINE 01 #define OFFLINE 02 #define CHANGED 04 #define STMASK 07 #define ANNOUNCE 010 #define CLEARED 020 /* * Karl Kleinpaste, 26 Jan 1984. * Initialize the dummy tty list for login watch. * This dummy list eliminates boundary conditions * when doing pointer-chase searches. */ void initwatch(void) { whohead.who_next = &whotail; whotail.who_prev = &whohead; stlast = 1; #ifdef WHODEBUG debugwholist(NULL, NULL); #endif /* WHODEBUG */ } void resetwatch(void) { watch_period = 0; stlast = 0; } /* * Karl Kleinpaste, 26 Jan 1984. * Watch /etc/utmp for login/logout changes. */ void watch_login(int force) { int comp = -1, alldone; int firsttime = stlast == 1; #if defined(HAVE_GETUTENT) || defined(HAVE_GETUTXENT) struct utmp *uptr; #else int utmpfd; #endif struct utmp utmp; struct who *wp, *wpnew; struct varent *v; Char **vp = NULL; time_t t, interval = MAILINTVL; struct stat sta; #if defined(HAVE_STRUCT_UTMP_UT_HOST) && defined(_SEQUENT_) char *host, *ut_find_host(); #endif -#ifdef WINNT_NATIVE +#ifdef WINNT_NATIVE USE(utmp); USE(utmpfd); USE(sta); USE(wpnew); #endif /* WINNT_NATIVE */ /* stop SIGINT, lest our login list get trashed. */ pintr_disabled++; cleanup_push(&pintr_disabled, disabled_cleanup); v = adrof(STRwatch); if ((v == NULL || v->vec == NULL) && !force) { cleanup_until(&pintr_disabled); return; /* no names to watch */ } if (!force) { trim(vp = v->vec); if (blklen(vp) % 2) /* odd # args: 1st == # minutes. */ interval = (number(*vp)) ? (getn(*vp++) * 60) : MAILINTVL; } else interval = 0; - + (void) time(&t); if (t - watch_period < interval) { cleanup_until(&pintr_disabled); return; /* not long enough yet... */ } watch_period = t; #ifndef WINNT_NATIVE /* * From: Michael Schroeder * Don't open utmp all the time, stat it first... */ if (stat(TCSH_PATH_UTMP, &sta)) { if (!force) xprintf(CGETS(26, 1, "cannot stat %s. Please \"unset watch\".\n"), TCSH_PATH_UTMP); cleanup_until(&pintr_disabled); return; } if (stlast == sta.st_mtime) { cleanup_until(&pintr_disabled); return; } stlast = sta.st_mtime; #if defined(HAVE_GETUTENT) || defined(HAVE_GETUTXENT) setutent(); #else if ((utmpfd = xopen(TCSH_PATH_UTMP, O_RDONLY|O_LARGEFILE)) < 0) { if (!force) xprintf(CGETS(26, 2, "%s cannot be opened. Please \"unset watch\".\n"), TCSH_PATH_UTMP); cleanup_until(&pintr_disabled); return; } cleanup_push(&utmpfd, open_cleanup); #endif /* * xterm clears the entire utmp entry - mark everyone on the status list * OFFLINE or we won't notice X "logouts" */ for (wp = whohead.who_next; wp->who_next != NULL; wp = wp->who_next) wp->who_status = OFFLINE | CLEARED; /* * Read in the utmp file, sort the entries, and update existing entries or * add new entries to the status list. */ #if defined(HAVE_GETUTENT) || defined(HAVE_GETUTXENT) while ((uptr = getutent()) != NULL) { memcpy(&utmp, uptr, sizeof (utmp)); #else while (xread(utmpfd, &utmp, sizeof utmp) == sizeof utmp) { #endif # ifdef DEAD_PROCESS # ifndef IRIS4D if (utmp.ut_type != USER_PROCESS) continue; # else /* Why is that? Cause the utmp file is always corrupted??? */ if (utmp.ut_type != USER_PROCESS && utmp.ut_type != DEAD_PROCESS) continue; # endif /* IRIS4D */ # endif /* DEAD_PROCESS */ if (utmp.ut_name[0] == '\0' && utmp.ut_line[0] == '\0') continue; /* completely void entry */ # ifdef DEAD_PROCESS if (utmp.ut_type == DEAD_PROCESS && utmp.ut_line[0] == '\0') continue; # endif /* DEAD_PROCESS */ wp = whohead.who_next; while (wp->who_next && (comp = strncmp(wp->who_tty, utmp.ut_line, UTLINLEN)) < 0) wp = wp->who_next;/* find that tty! */ if (wp->who_next && comp == 0) { /* found the tty... */ if (utmp.ut_time < wp->who_time) continue; # ifdef DEAD_PROCESS if (utmp.ut_type == DEAD_PROCESS) { wp->who_time = utmp.ut_time; wp->who_status = OFFLINE; } else # endif /* DEAD_PROCESS */ if (utmp.ut_name[0] == '\0') { wp->who_time = utmp.ut_time; wp->who_status = OFFLINE; } else if (strncmp(utmp.ut_name, wp->who_name, UTNAMLEN) == 0) { - /* someone is logged in */ + /* someone is logged in */ wp->who_time = utmp.ut_time; wp->who_status = ONLINE | ANNOUNCE; /* same guy */ } else { (void) strncpy(wp->who_new, utmp.ut_name, UTNAMLEN); # ifdef UTHOSTLEN # ifdef _SEQUENT_ host = ut_find_host(wp->who_tty); if (host) (void) strncpy(wp->who_host, host, UTHOSTLEN); else wp->who_host[0] = 0; # else (void) strncpy(wp->who_host, utmp.ut_host, UTHOSTLEN); # endif # endif /* UTHOSTLEN */ wp->who_time = utmp.ut_time; if (wp->who_name[0] == '\0') wp->who_status = ONLINE; else wp->who_status = CHANGED; } } else { /* new tty in utmp */ wpnew = xcalloc(1, sizeof *wpnew); (void) strncpy(wpnew->who_tty, utmp.ut_line, UTLINLEN); # ifdef UTHOSTLEN # ifdef _SEQUENT_ host = ut_find_host(wpnew->who_tty); if (host) (void) strncpy(wpnew->who_host, host, UTHOSTLEN); else wpnew->who_host[0] = 0; # else (void) strncpy(wpnew->who_host, utmp.ut_host, UTHOSTLEN); # endif # endif /* UTHOSTLEN */ wpnew->who_time = utmp.ut_time; # ifdef DEAD_PROCESS if (utmp.ut_type == DEAD_PROCESS) wpnew->who_status = OFFLINE; else # endif /* DEAD_PROCESS */ if (utmp.ut_name[0] == '\0') wpnew->who_status = OFFLINE; else { (void) strncpy(wpnew->who_new, utmp.ut_name, UTNAMLEN); wpnew->who_status = ONLINE; } # ifdef WHODEBUG debugwholist(wpnew, wp); # endif /* WHODEBUG */ wpnew->who_next = wp; /* link in a new 'who' */ wpnew->who_prev = wp->who_prev; wpnew->who_prev->who_next = wpnew; wp->who_prev = wpnew; /* linked in now */ } } #if defined(HAVE_GETUTENT) || defined(HAVE_GETUTXENT) endutent(); #else cleanup_until(&utmpfd); #endif #endif /* !WINNT_NATIVE */ if (force || vp == NULL) { cleanup_until(&pintr_disabled); return; } /* * The state of all logins is now known, so we can search the user's list * of watchables to print the interesting ones. */ for (alldone = 0; !alldone && *vp != NULL && **vp != '\0' && *(vp + 1) != NULL && **(vp + 1) != '\0'; vp += 2) { /* args used in pairs... */ if (eq(*vp, STRany) && eq(*(vp + 1), STRany)) alldone = 1; for (wp = whohead.who_next; wp->who_next != NULL; wp = wp->who_next) { if (wp->who_status & ANNOUNCE || (!eq(STRany, vp[0]) && !Gmatch(str2short(wp->who_name), vp[0]) && !Gmatch(str2short(wp->who_new), vp[0])) || (!Gmatch(str2short(wp->who_tty), vp[1]) && !eq(STRany, vp[1]))) continue; /* entry doesn't qualify */ /* already printed or not right one to print */ if (wp->who_status & CLEARED) {/* utmp entry was cleared */ wp->who_time = watch_period; wp->who_status &= ~CLEARED; } if ((wp->who_status & OFFLINE) && (wp->who_name[0] != '\0')) { if (!firsttime) print_who(wp); wp->who_name[0] = '\0'; wp->who_status |= ANNOUNCE; continue; } if (wp->who_status & ONLINE) { if (!firsttime) print_who(wp); (void) strcpy(wp->who_name, wp->who_new); wp->who_status |= ANNOUNCE; continue; } if (wp->who_status & CHANGED) { if (!firsttime) print_who(wp); (void) strcpy(wp->who_name, wp->who_new); wp->who_status |= ANNOUNCE; continue; } } } cleanup_until(&pintr_disabled); } #ifdef WHODEBUG static void debugwholist(struct who *new, struct who *wp) { struct who *a; a = whohead.who_next; while (a->who_next != NULL) { xprintf("%s/%s -> ", a->who_name, a->who_tty); a = a->who_next; } xprintf("TAIL\n"); if (a != &whotail) { xprintf(CGETS(26, 3, "BUG! last element is not whotail!\n")); abort(); } a = whotail.who_prev; xprintf(CGETS(26, 4, "backward: ")); while (a->who_prev != NULL) { xprintf("%s/%s -> ", a->who_name, a->who_tty); a = a->who_prev; } xprintf("HEAD\n"); if (a != &whohead) { xprintf(CGETS(26, 5, "BUG! first element is not whohead!\n")); abort(); } if (new) xprintf(CGETS(26, 6, "new: %s/%s\n"), new->who_name, new->who_tty); if (wp) xprintf("wp: %s/%s\n", wp->who_name, wp->who_tty); } #endif /* WHODEBUG */ static void print_who(struct who *wp) { #ifdef UTHOSTLEN Char *cp = str2short(CGETS(26, 7, "%n has %a %l from %m.")); #else Char *cp = str2short(CGETS(26, 8, "%n has %a %l.")); #endif /* UTHOSTLEN */ struct varent *vp = adrof(STRwho); Char *str; if (vp && vp->vec && vp->vec[0]) cp = vp->vec[0]; str = tprintf(FMT_WHO, cp, NULL, wp->who_time, wp); cleanup_push(str, xfree); for (cp = str; *cp;) xputwchar(*cp++); cleanup_until(str); xputchar('\n'); } /* end print_who */ char * who_info(ptr_t ptr, int c) { struct who *wp = ptr; char *wbuf; #ifdef UTHOSTLEN char *wb; int flg; char *pb; #endif /* UTHOSTLEN */ switch (c) { case 'n': /* user name */ switch (wp->who_status & STMASK) { case ONLINE: case CHANGED: return strsave(wp->who_new); case OFFLINE: return strsave(wp->who_name); default: break; } break; case 'a': switch (wp->who_status & STMASK) { case ONLINE: return strsave(CGETS(26, 9, "logged on")); case OFFLINE: return strsave(CGETS(26, 10, "logged off")); case CHANGED: return xasprintf(CGETS(26, 11, "replaced %s on"), wp->who_name); default: break; } break; #ifdef UTHOSTLEN case 'm': if (wp->who_host[0] == '\0') return strsave(CGETS(26, 12, "local")); else { pb = wp->who_host; wbuf = xmalloc(strlen(pb) + 1); wb = wbuf; /* the ':' stuff is for :. */ for (flg = isdigit((unsigned char)*pb) ? '\0' : '.'; *pb != '\0' && (*pb != flg || ((pb = strchr(pb, ':')) != 0)); pb++) { if (*pb == ':') flg = '\0'; *wb++ = isupper((unsigned char)*pb) ? tolower((unsigned char)*pb) : *pb; } *wb = '\0'; return wbuf; } case 'M': if (wp->who_host[0] == '\0') return strsave(CGETS(26, 12, "local")); else { pb = wp->who_host; wbuf = xmalloc(strlen(pb) + 1); wb = wbuf; for (; *pb != '\0'; pb++) *wb++ = isupper((unsigned char)*pb) ? tolower((unsigned char)*pb) : *pb; *wb = '\0'; return wbuf; } #endif /* UTHOSTLEN */ case 'l': return strsave(wp->who_tty); default: wbuf = xmalloc(3); wbuf[0] = '%'; wbuf[1] = (char) c; wbuf[2] = '\0'; return wbuf; } return NULL; } void /*ARGSUSED*/ dolog(Char **v, struct command *c) { struct who *wp; struct varent *vp; USE(v); USE(c); vp = adrof(STRwatch); /* lint insists vp isn't used unless we */ if (vp == NULL) /* unless we assign it outside the if */ stderror(ERR_NOWATCH); resetwatch(); wp = whohead.who_next; while (wp->who_next != NULL) { wp->who_name[0] = '\0'; wp = wp->who_next; } } # ifdef UTHOSTLEN size_t utmphostsize(void) { return UTHOSTLEN; } char * utmphost(void) { char *tty = short2str(varval(STRtty)); struct who *wp; char *host = NULL; watch_login(1); - + for (wp = whohead.who_next; wp->who_next != NULL; wp = wp->who_next) { if (strcmp(tty, wp->who_tty) == 0) host = wp->who_host; wp->who_name[0] = '\0'; } resetwatch(); return host; } # endif /* UTHOSTLEN */ #endif /* HAVENOUTMP */ diff --git a/contrib/tcsh/tcsh.man b/contrib/tcsh/tcsh.man index b01d07e0881a..e348756e8411 100644 --- a/contrib/tcsh/tcsh.man +++ b/contrib/tcsh/tcsh.man @@ -1,5534 +1,5534 @@ .\" .\" Copyright (c) 1980, 1990, 1993 .\" The Regents of the University of California. All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" Style notes for the tcsh man page: .\" .\" - Tags in lists are bold, except in the FILES section where they are .\" italic. .\" .\" - References are bold for section headings and environment and shell .\" variables and italic for commands (externals, builtins, aliases, and .\" editor commands) and arguments to commands. .\" .\" - Be careful with the .B and .I macros: they handle only a limited number .\" of words. Work around this with \fB and \fI, but only if absolutely .\" necessary, because tcsh.man2html uses .B/.I to find name anchors. .\" .\" - Indent in multiples of 4, usually 8. .\" .\" - Use `', not '' or "", except of course in shell syntax examples. .\" '' at the beginning of a line will vanish! .\" .\" - Use \` for literal back-quote (`). .\" .\" - Use \e for literal backslash (\). .\" .\" - Use \-, not -. .\" .\" - Include the tilde when naming dot files. `~/.login', not `.login'. .\" .\" - Refer to external commands in man page format, e.g., `csh(1)'. However, .\" tcsh is `tcsh', not `tcsh(1)', because this is the tcsh man page (and .\" see the next note anyway). .\" .\" - Say `the shell', not `tcsh', unless distinguishing between tcsh and csh. .\" .\" - Say `shell variable'/`environment variable' instead of `variable' .\" and `builtin command'/`editor command' instead of `builtin' or `command' .\" unless the distinction is absolutely clear from context. .\" .\" - Use the simple present tense. `The shell uses', not `The shell will use'. .\" .\" - IMPORTANT: Cross-reference as much as possible. Commands, variables, .\" etc. in the reference section should be mentioned in the appropriate .\" descriptive section, or at least in the reference-section description .\" of another command (or whatever) which is mentioned in a description .\" section. Remember to note OS-specific things in "OS variant support", .\" new features in NEW FEATURES and referenced external commands in SEE .\" ALSO. .\" .\" - tcsh.man2html depends heavily on the specific nroff commands used in the .\" man page when the script was written. Please stick closely to the style .\" used here if you can. In particular, please don't use nroff commands .\" which aren't already used herein. .\" -.TH TCSH 1 "11 Nov 2020" "Astron 6.22.03" +.TH TCSH 1 "26 Apr 2021" "Astron 6.22.04" .SH NAME tcsh \- C shell with file name completion and command line editing .SH SYNOPSIS .B tcsh \fR[\fB\-bcdefFimnqstvVxX\fR] [\fB\-Dname\fR[\fB=value\fR]] [arg ...] .br .B tcsh \-l .SH DESCRIPTION \fItcsh\fR is an enhanced but completely compatible version of the Berkeley UNIX C shell, \fIcsh\fR(1). It is a command language interpreter usable both as an interactive login shell and a shell script command processor. It includes a command-line editor (see \fBThe command-line editor\fR), programmable word completion (see \fBCompletion and listing\fR), spelling correction (see \fBSpelling correction\fR), a history mechanism (see \fBHistory substitution\fR), job control (see \fBJobs\fR) and a C-like syntax. The \fBNEW FEATURES\fR section describes major enhancements of \fItcsh\fR over \fIcsh\fR(1). Throughout this manual, features of \fItcsh\fR not found in most \fIcsh\fR(1) implementations (specifically, the 4.4BSD \fIcsh\fR) are labeled with `(+)', and features which are present in \fIcsh\fR(1) but not usually documented are labeled with `(u)'. .SS "Argument list processing" If the first argument (argument 0) to the shell is `\-' then it is a login shell. A login shell can be also specified by invoking the shell with the \fB\-l\fR flag as the only argument. .PP The rest of the flag arguments are interpreted as follows: .TP 4 .B \-b Forces a ``break'' from option processing, causing any further shell arguments to be treated as non-option arguments. The remaining arguments will not be interpreted as shell options. This may be used to pass options to a shell script without confusion or possible subterfuge. The shell will not run a set-user ID script without this option. .TP 4 .B \-c Commands are read from the following argument (which must be present, and must be a single argument), stored in the \fBcommand\fR shell variable for reference, and executed. Any remaining arguments are placed in the \fBargv\fR shell variable. .TP 4 .B \-d The shell loads the directory stack from \fI~/.cshdirs\fR as described under \fBStartup and shutdown\fR, whether or not it is a login shell. (+) .TP 4 .B \-D\fIname\fR[=\fIvalue\fR] Sets the environment variable \fIname\fR to \fIvalue\fR. (Domain/OS only) (+) .TP 4 .B \-e The shell exits if any invoked command terminates abnormally or yields a non-zero exit status. .TP 4 .B \-f The shell does not load any resource or startup files, or perform any command hashing, and thus starts faster. .TP 4 .B \-F The shell uses \fIfork\fR(2) instead of \fIvfork\fR(2) to spawn processes. (+) .TP 4 .B \-i The shell is interactive and prompts for its top-level input, even if it appears to not be a terminal. Shells are interactive without this option if their inputs and outputs are terminals. .TP 4 .B \-l The shell is a login shell. Applicable only if \fB\-l\fR is the only flag specified. .TP 4 .B \-m The shell loads \fI~/.tcshrc\fR even if it does not belong to the effective user. Newer versions of \fIsu\fR(1) can pass \fB\-m\fR to the shell. (+) .TP 4 .B \-n The shell parses commands but does not execute them. This aids in debugging shell scripts. .TP 4 .B \-q The shell accepts SIGQUIT (see \fBSignal handling\fR) and behaves when it is used under a debugger. Job control is disabled. (u) .TP 4 .B \-s Command input is taken from the standard input. .TP 4 .B \-t The shell reads and executes a single line of input. A `\e' may be used to escape the newline at the end of this line and continue onto another line. .TP 4 .B \-v Sets the \fBverbose\fR shell variable, so that command input is echoed after history substitution. .TP 4 .B \-x Sets the \fBecho\fR shell variable, so that commands are echoed immediately before execution. .TP 4 .B \-V Sets the \fBverbose\fR shell variable even before executing \fI~/.tcshrc\fR. .TP 4 .B \-X Is to \fB\-x\fR as \fB\-V\fR is to \fB\-v\fR. .TP 4 .B \-\-help Print a help message on the standard output and exit. (+) .TP 4 .B \-\-version Print the version/platform/compilation options on the standard output and exit. This information is also contained in the \fBversion\fR shell variable. (+) .PP After processing of flag arguments, if arguments remain but none of the \fB\-c\fR, \fB\-i\fR, \fB\-s\fR, or \fB\-t\fR options were given, the first argument is taken as the name of a file of commands, or ``script'', to be executed. The shell opens this file and saves its name for possible resubstitution by `$0'. Because many systems use either the standard version 6 or version 7 shells whose shell scripts are not compatible with this shell, the shell uses such a `standard' shell to execute a script whose first character is not a `#', i.e., that does not start with a comment. .PP Remaining arguments are placed in the \fBargv\fR shell variable. .SS "Startup and shutdown" A login shell begins by executing commands from the system files \fI/etc/csh.cshrc\fR and \fI/etc/csh.login\fR. It then executes commands from files in the user's \fBhome\fR directory: first \fI~/.tcshrc\fR (+) or, if \fI~/.tcshrc\fR is not found, \fI~/.cshrc\fR, then the contents of \fI~/.history\fR (or the value of the \fBhistfile\fR shell variable) are loaded into memory, then \fI~/.login\fR, and finally \fI~/.cshdirs\fR (or the value of the \fBdirsfile\fR shell variable) (+). The shell may read \fI/etc/csh.login\fR before instead of after \fI/etc/csh.cshrc\fR, and \fI~/.login\fR before instead of after \fI~/.tcshrc\fR or \fI~/.cshrc\fR and \fI~/.history\fR, if so compiled; see the \fBversion\fR shell variable. (+) .PP Non-login shells read only \fI/etc/csh.cshrc\fR and \fI~/.tcshrc\fR or \fI~/.cshrc\fR on startup. .PP For examples of startup files, please consult \fIhttp://tcshrc.sourceforge.net\fR. .PP Commands like \fIstty\fR(1) and \fItset\fR(1), which need be run only once per login, usually go in one's \fI~/.login\fR file. Users who need to use the same set of files with both \fIcsh\fR(1) and \fItcsh\fR can have only a \fI~/.cshrc\fR which checks for the existence of the \fBtcsh\fR shell variable (q.v.) before using \fItcsh\fR-specific commands, or can have both a \fI~/.cshrc\fR and a \fI~/.tcshrc\fR which \fIsource\fRs (see the builtin command) \fI~/.cshrc\fR. The rest of this manual uses `\fI~/.tcshrc\fR' to mean `\fI~/.tcshrc\fR or, if \fI~/.tcshrc\fR is not found, \fI~/.cshrc\fR'. .PP In the normal case, the shell begins reading commands from the terminal, prompting with `> '. (Processing of arguments and the use of the shell to process files containing command scripts are described later.) The shell repeatedly reads a line of command input, breaks it into words, places it on the command history list, parses it and executes each command in the line. .PP One can log out by typing `^D' on an empty line, `logout' or `login' or via the shell's autologout mechanism (see the \fBautologout\fR shell variable). When a login shell terminates it sets the \fBlogout\fR shell variable to `normal' or `automatic' as appropriate, then executes commands from the files \fI/etc/csh.logout\fR and \fI~/.logout\fR. The shell may drop DTR on logout if so compiled; see the \fBversion\fR shell variable. .PP The names of the system login and logout files vary from system to system for compatibility with different \fIcsh\fR(1) variants; see \fBFILES\fR. .SS Editing We first describe \fBThe command-line editor\fR. The \fBCompletion and listing\fR and \fBSpelling correction\fR sections describe two sets of functionality that are implemented as editor commands but which deserve their own treatment. Finally, \fBEditor commands\fR lists and describes the editor commands specific to the shell and their default bindings. .SS "The command-line editor (+)" Command-line input can be edited using key sequences much like those used in \fIemacs\fR(1) or \fIvi\fR(1). The editor is active only when the \fBedit\fR shell variable is set, which it is by default in interactive shells. The \fIbindkey\fR builtin can display and change key bindings. \fIemacs\fR(1)\-style key bindings are used by default (unless the shell was compiled otherwise; see the \fBversion\fR shell variable), but \fIbindkey\fR can change the key bindings to \fIvi\fR(1)\-style bindings en masse. .PP The shell always binds the arrow keys (as defined in the \fBTERMCAP\fR environment variable) to .PP .PD 0 .RS +4 .TP 8 down \fIdown-history\fR .TP 8 up \fIup-history\fR .TP 8 left \fIbackward-char\fR .TP 8 right \fIforward-char\fR .PD .RE .PP unless doing so would alter another single-character binding. One can set the arrow key escape sequences to the empty string with \fIsettc\fR to prevent these bindings. The ANSI/VT100 sequences for arrow keys are always bound. .PP Other key bindings are, for the most part, what \fIemacs\fR(1) and \fIvi\fR(1) users would expect and can easily be displayed by \fIbindkey\fR, so there is no need to list them here. Likewise, \fIbindkey\fR can list the editor commands with a short description of each. Certain key bindings have different behavior depending if \fIemacs\fR(1) or \fIvi\fR(1) style bindings are being used; see \fBvimode\fR for more information. .PP Note that editor commands do not have the same notion of a ``word'' as does the shell. The editor delimits words with any non-alphanumeric characters not in the shell variable \fBwordchars\fR, while the shell recognizes only whitespace and some of the characters with special meanings to it, listed under \fBLexical structure\fR. .SS "Completion and listing (+)" The shell is often able to complete words when given a unique abbreviation. Type part of a word (for example `ls /usr/lost') and hit the tab key to run the \fIcomplete-word\fR editor command. The shell completes the filename `/usr/lost' to `/usr/lost+found/', replacing the incomplete word with the complete word in the input buffer. (Note the terminal `/'; completion adds a `/' to the end of completed directories and a space to the end of other completed words, to speed typing and provide a visual indicator of successful completion. The \fBaddsuffix\fR shell variable can be unset to prevent this.) If no match is found (perhaps `/usr/lost+found' doesn't exist), the terminal bell rings. If the word is already complete (perhaps there is a `/usr/lost' on your system, or perhaps you were thinking too far ahead and typed the whole thing) a `/' or space is added to the end if it isn't already there. .PP Completion works anywhere in the line, not at just the end; completed text pushes the rest of the line to the right. Completion in the middle of a word often results in leftover characters to the right of the cursor that need to be deleted. .PP Commands and variables can be completed in much the same way. For example, typing `em[tab]' would complete `em' to `emacs' if \fIemacs\fR were the only command on your system beginning with `em'. Completion can find a command in any directory in \fBpath\fR or if given a full pathname. Typing `echo $ar[tab]' would complete `$ar' to `$argv' if no other variable began with `ar'. .PP The shell parses the input buffer to determine whether the word you want to complete should be completed as a filename, command or variable. The first word in the buffer and the first word following `;', `|', `|&', `&&' or `||' is considered to be a command. A word beginning with `$' is considered to be a variable. Anything else is a filename. An empty line is `completed' as a filename. .PP You can list the possible completions of a word at any time by typing `^D' to run the \fIdelete-char-or-list-or-eof\fR editor command. The shell lists the possible completions using the \fIls\-F\fR builtin (q.v.) and reprints the prompt and unfinished command line, for example: .IP "" 4 > ls /usr/l[^D] .br lbin/ lib/ local/ lost+found/ .br > ls /usr/l .PP If the \fBautolist\fR shell variable is set, the shell lists the remaining choices (if any) whenever completion fails: .IP "" 4 > set autolist .br > nm /usr/lib/libt[tab] .br libtermcap.a@ libtermlib.a@ .br > nm /usr/lib/libterm .PP If \fBautolist\fR is set to `ambiguous', choices are listed only when completion fails and adds no new characters to the word being completed. .PP A filename to be completed can contain variables, your own or others' home directories abbreviated with `~' (see \fBFilename substitution\fR) and directory stack entries abbreviated with `=' (see \fBDirectory stack substitution\fR). For example, .IP "" 4 > ls ~k[^D] .br kahn kas kellogg .br > ls ~ke[tab] .br > ls ~kellogg/ .PP or .IP "" 4 > set local = /usr/local .br > ls $lo[tab] .br > ls $local/[^D] .br bin/ etc/ lib/ man/ src/ .br > ls $local/ .PP Note that variables can also be expanded explicitly with the \fIexpand-variables\fR editor command. .PP \fIdelete-char-or-list-or-eof\fR lists at only the end of the line; in the middle of a line it deletes the character under the cursor and on an empty line it logs one out or, if \fBignoreeof\fR is set, does nothing. `M-^D', bound to the editor command \fIlist-choices\fR, lists completion possibilities anywhere on a line, and \fIlist-choices\fR (or any one of the related editor commands that do or don't delete, list and/or log out, listed under \fIdelete-char-or-list-or-eof\fR) can be bound to `^D' with the \fIbindkey\fR builtin command if so desired. .PP The \fIcomplete-word-fwd\fR and \fIcomplete-word-back\fR editor commands (not bound to any keys by default) can be used to cycle up and down through the list of possible completions, replacing the current word with the next or previous word in the list. .PP The shell variable \fBfignore\fR can be set to a list of suffixes to be ignored by completion. Consider the following: .IP "" 4 > ls .br Makefile condiments.h~ main.o side.c .br README main.c meal side.o .br condiments.h main.c~ .br > set fignore = (.o \e~) .br > emacs ma[^D] .br main.c main.c~ main.o .br > emacs ma[tab] .br > emacs main.c .PP `main.c~' and `main.o' are ignored by completion (but not listing), because they end in suffixes in \fBfignore\fR. Note that a `\e' was needed in front of `~' to prevent it from being expanded to \fBhome\fR as described under \fBFilename substitution\fR. \fBfignore\fR is ignored if only one completion is possible. .PP If the \fBcomplete\fR shell variable is set to `enhance', completion 1) ignores case and 2) considers periods, hyphens and underscores (`.', `\-' and `_') to be word separators and hyphens and underscores to be equivalent. If you had the following files .IP "" 4 comp.lang.c comp.lang.perl comp.std.c++ .br comp.lang.c++ comp.std.c .PP and typed `mail \-f c.l.c[tab]', it would be completed to `mail \-f comp.lang.c', and ^D would list `comp.lang.c' and `comp.lang.c++'. `mail \-f c..c++[^D]' would list `comp.lang.c++' and `comp.std.c++'. Typing `rm a\-\-file[^D]' in the following directory .IP "" 4 A_silly_file a-hyphenated-file another_silly_file .PP would list all three files, because case is ignored and hyphens and underscores are equivalent. Periods, however, are not equivalent to hyphens or underscores. .PP If the \fBcomplete\fR shell variable is set to `Enhance', completion ignores case and differences between a hyphen and an underscore word separator only when the user types a lowercase character or a hyphen. Entering an uppercase character or an underscore will not match the corresponding lowercase character or hyphen word separator. Typing `rm a\-\-file[^D]' in the directory of the previous example would still list all three files, but typing `rm A\-\-file' would match only `A_silly_file' and typing `rm a__file[^D]' would match just `A_silly_file' and `another_silly_file' because the user explicitly used an uppercase or an underscore character. .PP Completion and listing are affected by several other shell variables: \fBrecexact\fR can be set to complete on the shortest possible unique match, even if more typing might result in a longer match: .IP "" 4 > ls .br fodder foo food foonly .br > set recexact .br > rm fo[tab] .PP just beeps, because `fo' could expand to `fod' or `foo', but if we type another `o', .IP "" 4 > rm foo[tab] .br > rm foo .PP the completion completes on `foo', even though `food' and `foonly' also match. \fBautoexpand\fR can be set to run the \fIexpand-history\fR editor command before each completion attempt, \fBautocorrect\fR can be set to spelling-correct the word to be completed (see \fBSpelling correction\fR) before each completion attempt and \fBcorrect\fR can be set to complete commands automatically after one hits `return'. \fBmatchbeep\fR can be set to make completion beep or not beep in a variety of situations, and \fBnobeep\fR can be set to never beep at all. \fBnostat\fR can be set to a list of directories and/or patterns that match directories to prevent the completion mechanism from \fIstat\fR(2)ing those directories. \fBlistmax\fR and \fBlistmaxrows\fR can be set to limit the number of items and rows (respectively) that are listed without asking first. \fBrecognize_only_executables\fR can be set to make the shell list only executables when listing commands, but it is quite slow. .PP Finally, the \fIcomplete\fR builtin command can be used to tell the shell how to complete words other than filenames, commands and variables. Completion and listing do not work on glob-patterns (see \fBFilename substitution\fR), but the \fIlist-glob\fR and \fIexpand-glob\fR editor commands perform equivalent functions for glob-patterns. .SS "Spelling correction (+)" The shell can sometimes correct the spelling of filenames, commands and variable names as well as completing and listing them. .PP Individual words can be spelling-corrected with the \fIspell-word\fR editor command (usually bound to M-s and M-S) and the entire input buffer with \fIspell-line\fR (usually bound to M-$). The \fBcorrect\fR shell variable can be set to `cmd' to correct the command name or `all' to correct the entire line each time return is typed, and \fBautocorrect\fR can be set to correct the word to be completed before each completion attempt. .PP When spelling correction is invoked in any of these ways and the shell thinks that any part of the command line is misspelled, it prompts with the corrected line: .IP "" 4 > set correct = cmd .br > lz /usr/bin .br CORRECT>ls /usr/bin (y|n|e|a)? .PP One can answer `y' or space to execute the corrected line, `e' to leave the uncorrected command in the input buffer, `a' to abort the command as if `^C' had been hit, and anything else to execute the original line unchanged. .PP Spelling correction recognizes user-defined completions (see the \fIcomplete\fR builtin command). If an input word in a position for which a completion is defined resembles a word in the completion list, spelling correction registers a misspelling and suggests the latter word as a correction. However, if the input word does not match any of the possible completions for that position, spelling correction does not register a misspelling. .PP Like completion, spelling correction works anywhere in the line, pushing the rest of the line to the right and possibly leaving extra characters to the right of the cursor. .SS "Editor commands (+)" `bindkey' lists key bindings and `bindkey \-l' lists and briefly describes editor commands. Only new or especially interesting editor commands are described here. See \fIemacs\fR(1) and \fIvi\fR(1) for descriptions of each editor's key bindings. .PP The character or characters to which each command is bound by default is given in parentheses. `^\fIcharacter\fR' means a control character and `M-\fIcharacter\fR' a meta character, typed as escape-\fIcharacter\fR on terminals without a meta key. Case counts, but commands that are bound to letters by default are bound to both lower- and uppercase letters for convenience. .TP 8 .B backward-char \fR(^B, left) Move back a character. Cursor behavior modified by \fBvimode\fR. .TP 8 .B backward-delete-word \fR(M-^H, M-^?) Cut from beginning of current word to cursor \- saved in cut buffer. Word boundary behavior modified by \fBvimode\fR. .TP 8 .B backward-word \fR(M-b, M-B) Move to beginning of current word. Word boundary and cursor behavior modified by \fBvimode\fR. .TP 8 .B beginning-of-line \fR(^A, home) Move to beginning of line. Cursor behavior modified by \fBvimode\fR. .TP 8 .B capitalize-word \fR(M-c, M-C) Capitalize the characters from cursor to end of current word. Word boundary behavior modified by \fBvimode\fR. .TP 8 .B complete-word \fR(tab) Completes a word as described under \fBCompletion and listing\fR. .TP 8 .B complete-word-back \fR(not bound) Like \fIcomplete-word-fwd\fR, but steps up from the end of the list. .TP 8 .B complete-word-fwd \fR(not bound) Replaces the current word with the first word in the list of possible completions. May be repeated to step down through the list. At the end of the list, beeps and reverts to the incomplete word. .TP 8 .B complete-word-raw \fR(^X-tab) Like \fIcomplete-word\fR, but ignores user-defined completions. .TP 8 .B copy-prev-word \fR(M-^_) Copies the previous word in the current line into the input buffer. See also \fIinsert-last-word\fR. Word boundary behavior modified by \fBvimode\fR. .TP 8 .B dabbrev-expand \fR(M-/) Expands the current word to the most recent preceding one for which the current is a leading substring, wrapping around the history list (once) if necessary. Repeating \fIdabbrev-expand\fR without any intervening typing changes to the next previous word etc., skipping identical matches much like \fIhistory-search-backward\fR does. .TP 8 .B delete-char \fR(not bound) Deletes the character under the cursor. See also \fIdelete-char-or-list-or-eof\fR. Cursor behavior modified by \fBvimode\fR. .TP 8 .B delete-char-or-eof \fR(not bound) Does \fIdelete-char\fR if there is a character under the cursor or \fIend-of-file\fR on an empty line. See also \fIdelete-char-or-list-or-eof\fR. Cursor behavior modified by \fBvimode\fR. .TP 8 .B delete-char-or-list \fR(not bound) Does \fIdelete-char\fR if there is a character under the cursor or \fIlist-choices\fR at the end of the line. See also \fIdelete-char-or-list-or-eof\fR. .TP 8 .B delete-char-or-list-or-eof \fR(^D) Does \fIdelete-char\fR if there is a character under the cursor, \fIlist-choices\fR at the end of the line or \fIend-of-file\fR on an empty line. See also those three commands, each of which does only a single action, and \fIdelete-char-or-eof\fR, \fIdelete-char-or-list\fR and \fIlist-or-eof\fR, each of which does a different two out of the three. .TP 8 .B delete-word \fR(M-d, M-D) Cut from cursor to end of current word \- save in cut buffer. Word boundary behavior modified by \fBvimode\fR. .TP 8 .B down-history \fR(down-arrow, ^N) Like \fIup-history\fR, but steps down, stopping at the original input line. .TP 8 .B downcase-word \fR(M-l, M-L) Lowercase the characters from cursor to end of current word. Word boundary behavior modified by \fBvimode\fR. .TP 8 .B end-of-file \fR(not bound) Signals an end of file, causing the shell to exit unless the \fBignoreeof\fR shell variable (q.v.) is set to prevent this. See also \fIdelete-char-or-list-or-eof\fR. .TP 8 .B end-of-line \fR(^E, end) Move cursor to end of line. Cursor behavior modified by \fBvimode\fR. .TP 8 .B expand-history \fR(M-space) Expands history substitutions in the current word. See \fBHistory substitution\fR. See also \fImagic-space\fR, \fItoggle-literal-history\fR and the \fBautoexpand\fR shell variable. .TP 8 .B expand-glob \fR(^X-*) Expands the glob-pattern to the left of the cursor. See \fBFilename substitution\fR. .TP 8 .B expand-line \fR(not bound) Like \fIexpand-history\fR, but expands history substitutions in each word in the input buffer. .TP 8 .B expand-variables \fR(^X-$) Expands the variable to the left of the cursor. See \fBVariable substitution\fR. .TP 8 .B forward-char \fR(^F, right) Move forward one character. Cursor behavior modified by \fBvimode\fR. .TP 8 .B forward-word \fR(M-f, M-F) Move forward to end of current word. Word boundary and cursor behavior modified by \fBvimode\fR. .TP 8 .B history-search-backward \fR(M-p, M-P) Searches backwards through the history list for a command beginning with the current contents of the input buffer up to the cursor and copies it into the input buffer. The search string may be a glob-pattern (see \fBFilename substitution\fR) containing `*', `?', `[]' or `{}'. \fIup-history\fR and \fIdown-history\fR will proceed from the appropriate point in the history list. Emacs mode only. See also \fIhistory-search-forward\fR and \fIi-search-back\fR. .TP 8 .B history-search-forward \fR(M-n, M-N) Like \fIhistory-search-backward\fR, but searches forward. .TP 8 .B i-search-back \fR(not bound) Searches backward like \fIhistory-search-backward\fR, copies the first match into the input buffer with the cursor positioned at the end of the pattern, and prompts with `bck: ' and the first match. Additional characters may be typed to extend the search, \fIi-search-back\fR may be typed to continue searching with the same pattern, wrapping around the history list if necessary, (\fIi-search-back\fR must be bound to a single character for this to work) or one of the following special characters may be typed: .PP .RS +8 .RS +4 .PD 0 .TP 8 ^W Appends the rest of the word under the cursor to the search pattern. .TP 8 delete (or any character bound to \fIbackward-delete-char\fR) Undoes the effect of the last character typed and deletes a character from the search pattern if appropriate. .TP 8 ^G If the previous search was successful, aborts the entire search. If not, goes back to the last successful search. .TP 8 escape Ends the search, leaving the current line in the input buffer. .RE .PD .PP Any other character not bound to \fIself-insert-command\fR terminates the search, leaving the current line in the input buffer, and is then interpreted as normal input. In particular, a carriage return causes the current line to be executed. See also \fIi-search-fwd\fR and \fIhistory-search-backward\fR. Word boundary behavior modified by \fBvimode\fR. .RE .TP 8 .B i-search-fwd \fR(not bound) Like \fIi-search-back\fR, but searches forward. Word boundary behavior modified by \fBvimode\fR. .TP 8 .B insert-last-word \fR(M-_) Inserts the last word of the previous input line (`!$') into the input buffer. See also \fIcopy-prev-word\fR. .TP 8 .B list-choices \fR(M-^D) Lists completion possibilities as described under \fBCompletion and listing\fR. See also \fIdelete-char-or-list-or-eof\fR and \fIlist-choices-raw\fR. .TP 8 .B list-choices-raw \fR(^X-^D) Like \fIlist-choices\fR, but ignores user-defined completions. .TP 8 .B list-glob \fR(^X-g, ^X-G) Lists (via the \fIls\-F\fR builtin) matches to the glob-pattern (see \fBFilename substitution\fR) to the left of the cursor. .TP 8 .B list-or-eof \fR(not bound) Does \fIlist-choices\fR or \fIend-of-file\fR on an empty line. See also \fIdelete-char-or-list-or-eof\fR. .TP 8 .B magic-space \fR(not bound) Expands history substitutions in the current line, like \fIexpand-history\fR, and inserts a space. \fImagic-space\fR is designed to be bound to the space bar, but is not bound by default. .TP 8 .B normalize-command \fR(^X-?) Searches for the current word in PATH and, if it is found, replaces it with the full path to the executable. Special characters are quoted. Aliases are expanded and quoted but commands within aliases are not. This command is useful with commands that take commands as arguments, e.g., `dbx' and `sh \-x'. .TP 8 .B normalize-path \fR(^X-n, ^X-N) Expands the current word as described under the `expand' setting of the \fBsymlinks\fR shell variable. .TP 8 .B overwrite-mode \fR(unbound) Toggles between input and overwrite modes. .TP 8 .B run-fg-editor \fR(M-^Z) Saves the current input line and looks for a stopped job where the file name portion of its first word is found in the \fBeditors\fR shell variable. If \fBeditors\fR is not set, then the file name portion of the \fBEDITOR\fR environment variable (`ed' if unset) and the \fBVISUAL\fR environment variable (`vi' if unset) will be used. If such a job is found, it is restarted as if `fg %\fIjob\fR' had been typed. This is used to toggle back and forth between an editor and the shell easily. Some people bind this command to `^Z' so they can do this even more easily. .TP .B run-help \fR(M-h, M-H) Searches for documentation on the current command, using the same notion of `current command' as the completion routines, and prints it. There is no way to use a pager; \fIrun-help\fR is designed for short help files. If the special alias \fBhelpcommand\fR is defined, it is run with the command name as a sole argument. Else, documentation should be in a file named \fIcommand\fR.help, \fIcommand\fR.1, \fIcommand\fR.6, \fIcommand\fR.8 or \fIcommand\fR, which should be in one of the directories listed in the \fBHPATH\fR environment variable. If there is more than one help file only the first is printed. .TP 8 .B self-insert-command \fR(text characters) In insert mode (the default), inserts the typed character into the input line after the character under the cursor. In overwrite mode, replaces the character under the cursor with the typed character. The input mode is normally preserved between lines, but the \fBinputmode\fR shell variable can be set to `insert' or `overwrite' to put the editor in that mode at the beginning of each line. See also \fIoverwrite-mode\fR. .TP 8 .B sequence-lead-in \fR(arrow prefix, meta prefix, ^X) Indicates that the following characters are part of a multi-key sequence. Binding a command to a multi-key sequence really creates two bindings: the first character to \fIsequence-lead-in\fR and the whole sequence to the command. All sequences beginning with a character bound to \fIsequence-lead-in\fR are effectively bound to \fIundefined-key\fR unless bound to another command. .TP 8 .B spell-line \fR(M-$) Attempts to correct the spelling of each word in the input buffer, like \fIspell-word\fR, but ignores words whose first character is one of `\-', `!', `^' or `%', or which contain `\e', `*' or `?', to avoid problems with switches, substitutions and the like. See \fBSpelling correction\fR. .TP 8 .B spell-word \fR(M-s, M-S) Attempts to correct the spelling of the current word as described under \fBSpelling correction\fR. Checks each component of a word which appears to be a pathname. .TP 8 .B toggle-literal-history \fR(M-r, M-R) Expands or `unexpands' history substitutions in the input buffer. See also \fIexpand-history\fR and the \fBautoexpand\fR shell variable. .TP 8 .B undefined-key \fR(any unbound key) Beeps. .TP 8 .B up-history \fR(up-arrow, ^P) Copies the previous entry in the history list into the input buffer. If \fBhistlit\fR is set, uses the literal form of the entry. May be repeated to step up through the history list, stopping at the top. .TP 8 .B upcase-word \fR(M-u, M-U) Uppercase the characters from cursor to end of current word. Word boundary behavior modified by \fBvimode\fR. .TP 8 .B vi-beginning-of-next-word \fR(not bound) Vi goto the beginning of next word. Word boundary and cursor behavior modified by \fBvimode\fR. .TP 8 .B vi-eword \fR(not bound) Vi move to the end of the current word. Word boundary behavior modified by \fBvimode\fR. .TP 8 .B vi-search-back \fR(?) Prompts with `?' for a search string (which may be a glob-pattern, as with \fIhistory-search-backward\fR), searches for it and copies it into the input buffer. The bell rings if no match is found. Hitting return ends the search and leaves the last match in the input buffer. Hitting escape ends the search and executes the match. \fIvi\fR mode only. .TP 8 .B vi-search-fwd \fR(/) Like \fIvi-search-back\fR, but searches forward. .TP 8 .B which-command \fR(M-?) Does a \fIwhich\fR (see the description of the builtin command) on the first word of the input buffer. .TP 8 .B yank-pop \fR(M-y) When executed immediately after a \fIyank\fR or another \fIyank-pop\fR, replaces the yanked string with the next previous string from the killring. This also has the effect of rotating the killring, such that this string will be considered the most recently killed by a later \fIyank\fR command. Repeating \fIyank-pop\fR will cycle through the killring any number of times. .SS "Lexical structure" The shell splits input lines into words at blanks and tabs. The special characters `&', `|', `;', `<', `>', `(', and `)' and the doubled characters `&&', `||', `<<' and `>>' are always separate words, whether or not they are surrounded by whitespace. .PP When the shell's input is not a terminal, the character `#' is taken to begin a comment. Each `#' and the rest of the input line on which it appears is discarded before further parsing. .PP A special character (including a blank or tab) may be prevented from having its special meaning, and possibly made part of another word, by preceding it with a backslash (`\e') or enclosing it in single (`''), double (`"') or backward (`\`') quotes. When not otherwise quoted a newline preceded by a `\e' is equivalent to a blank, but inside quotes this sequence results in a newline. .PP Furthermore, all \fBSubstitutions\fR (see below) except \fBHistory substitution\fR can be prevented by enclosing the strings (or parts of strings) in which they appear with single quotes or by quoting the crucial character(s) (e.g., `$' or `\`' for \fBVariable substitution\fR or \fBCommand substitution\fR respectively) with `\e'. (\fBAlias substitution\fR is no exception: quoting in any way any character of a word for which an \fIalias\fR has been defined prevents substitution of the alias. The usual way of quoting an alias is to precede it with a backslash.) \fBHistory substitution\fR is prevented by backslashes but not by single quotes. Strings quoted with double or backward quotes undergo \fBVariable substitution\fR and \fBCommand substitution\fR, but other substitutions are prevented. .PP Text inside single or double quotes becomes a single word (or part of one). Metacharacters in these strings, including blanks and tabs, do not form separate words. Only in one special case (see \fBCommand substitution\fR below) can a double-quoted string yield parts of more than one word; single-quoted strings never do. Backward quotes are special: they signal \fBCommand substitution\fR (q.v.), which may result in more than one word. .PP Quoting complex strings, particularly strings which themselves contain quoting characters, can be confusing. Remember that quotes need not be used as they are in human writing! It may be easier to quote not an entire string, but only those parts of the string which need quoting, using different types of quoting to do so if appropriate. .PP The \fBbackslash_quote\fR shell variable (q.v.) can be set to make backslashes always quote `\e', `'', and `"'. (+) This may make complex quoting tasks easier, but it can cause syntax errors in \fIcsh\fR(1) scripts. .SS Substitutions We now describe the various transformations the shell performs on the input in the order in which they occur. We note in passing the data structures involved and the commands and variables which affect them. Remember that substitutions can be prevented by quoting as described under \fBLexical structure\fR. .SS "History substitution" Each command, or ``event'', input from the terminal is saved in the history list. The previous command is always saved, and the \fBhistory\fR shell variable can be set to a number to save that many commands. The \fBhistdup\fR shell variable can be set to not save duplicate events or consecutive duplicate events. .PP Saved commands are numbered sequentially from 1 and stamped with the time. It is not usually necessary to use event numbers, but the current event number can be made part of the prompt by placing an `!' in the \fBprompt\fR shell variable. .PP By default history entries are displayed by printing each parsed token separated by space; thus the redirection operator `>&!' will be displayed as `> & !'. .PP The shell actually saves history in expanded and literal (unexpanded) forms. If the \fBhistlit\fR shell variable is set, commands that display and store history use the literal form. .PP The \fIhistory\fR builtin command can print, store in a file, restore and clear the history list at any time, and the \fBsavehist\fR and \fBhistfile\fR shell variables can be set to store the history list automatically on logout and restore it on login. .PP History substitutions introduce words from the history list into the input stream, making it easy to repeat commands, repeat arguments of a previous command in the current command, or fix spelling mistakes in the previous command with little typing and a high degree of confidence. .PP History substitutions begin with the character `!'. They may begin anywhere in the input stream, but they do not nest. The `!' may be preceded by a `\e' to prevent its special meaning; for convenience, a `!' is passed unchanged when it is followed by a blank, tab, newline, `=' or `('. History substitutions also occur when an input line begins with `^'. This special abbreviation will be described later. The characters used to signal history substitution (`!' and `^') can be changed by setting the \fBhistchars\fR shell variable. Any input line which contains a history substitution is printed before it is executed. .PP A history substitution may have an ``event specification'', which indicates the event from which words are to be taken, a ``word designator'', which selects particular words from the chosen event, and/or a ``modifier'', which manipulates the selected words. .PP An event specification can be .PP .PD 0 .RS +4 .TP 8 .I n A number, referring to a particular event .TP 8 \-\fIn\fR An offset, referring to the event \fIn\fR before the current event .TP 8 # The current event. This should be used carefully in \fIcsh\fR(1), where there is no check for recursion. \fItcsh\fR allows 10 levels of recursion. (+) .TP 8 ! The previous event (equivalent to `\-1') .TP 8 .I s The most recent event whose first word begins with the string \fIs\fR .TP 8 ?\fIs\fR? The most recent event which contains the string \fIs\fR. The second `?' can be omitted if it is immediately followed by a newline. .RE .PD .PP For example, consider this bit of someone's history list: .IP "" 4 \ 9 8:30 nroff \-man wumpus.man .br 10 8:31 cp wumpus.man wumpus.man.old .br 11 8:36 vi wumpus.man .br 12 8:37 diff wumpus.man.old wumpus.man .PP The commands are shown with their event numbers and time stamps. The current event, which we haven't typed in yet, is event 13. `!11' and `!\-2' refer to event 11. `!!' refers to the previous event, 12. `!!' can be abbreviated `!' if it is followed by `:' (`:' is described below). `!n' refers to event 9, which begins with `n'. `!?old?' also refers to event 12, which contains `old'. Without word designators or modifiers history references simply expand to the entire event, so we might type `!cp' to redo the copy command or `!!|more' if the `diff' output scrolled off the top of the screen. .PP History references may be insulated from the surrounding text with braces if necessary. For example, `!vdoc' would look for a command beginning with `vdoc', and, in this example, not find one, but `!{v}doc' would expand unambiguously to `vi wumpus.mandoc'. Even in braces, history substitutions do not nest. .PP (+) While \fIcsh\fR(1) expands, for example, `!3d' to event 3 with the letter `d' appended to it, \fItcsh\fR expands it to the last event beginning with `3d'; only completely numeric arguments are treated as event numbers. This makes it possible to recall events beginning with numbers. To expand `!3d' as in \fIcsh\fR(1) say `!{3}d'. .PP To select words from an event we can follow the event specification by a `:' and a designator for the desired words. The words of an input line are numbered from 0, the first (usually command) word being 0, the second word (first argument) being 1, etc. The basic word designators are: .PP .PD 0 .RS +4 .TP 8 0 The first (command) word .TP 8 .I n The \fIn\fRth argument .TP 8 ^ The first argument, equivalent to `1' .TP 8 $ The last argument .TP 8 % The word matched by an ?\fIs\fR? search .TP 8 .I x\-y A range of words .TP 8 .I \-y Equivalent to \fI`0\-y'\fR .TP 8 * Equivalent to `^\-$', but returns nothing if the event contains only 1 word .TP 8 .I x* Equivalent to \fI`x\-$'\fR .TP 8 .I x\- Equivalent to \fI`x*'\fR, but omitting the last word (`$') .PD .RE .PP Selected words are inserted into the command line separated by single blanks. For example, the `diff' command in the previous example might have been typed as `diff !!:1.old !!:1' (using `:1' to select the first argument from the previous event) or `diff !\-2:2 !\-2:1' to select and swap the arguments from the `cp' command. If we didn't care about the order of the `diff' we might have said `diff !\-2:1\-2' or simply `diff !\-2:*'. The `cp' command might have been written `cp wumpus.man !#:1.old', using `#' to refer to the current event. `!n:\- hurkle.man' would reuse the first two words from the `nroff' command to say `nroff \-man hurkle.man'. .PP The `:' separating the event specification from the word designator can be omitted if the argument selector begins with a `^', `$', `*', `%' or `\-'. For example, our `diff' command might have been `diff !!^.old !!^' or, equivalently, `diff !!$.old !!$'. However, if `!!' is abbreviated `!', an argument selector beginning with `\-' will be interpreted as an event specification. .PP A history reference may have a word designator but no event specification. It then references the previous command. Continuing our `diff' example, we could have said simply `diff !^.old !^' or, to get the arguments in the opposite order, just `diff !*'. .PP The word or words in a history reference can be edited, or ``modified'', by following it with one or more modifiers, each preceded by a `:': .PP .PD 0 .RS +4 .TP 8 h Remove a trailing pathname component, leaving the head. .TP 8 t Remove all leading pathname components, leaving the tail. .TP 8 r Remove a filename extension `.xxx', leaving the root name. .TP 8 e Remove all but the extension. .TP 8 u Uppercase the first lowercase letter. .TP 8 l Lowercase the first uppercase letter. .TP 8 s\fI/l/r/\fR Substitute \fIl\fR for \fIr\fR. \fIl\fR is simply a string like \fIr\fR, not a regular expression as in the eponymous \fIed\fR(1) command. Any character may be used as the delimiter in place of `/'; a `\e' can be used to quote the delimiter inside \fIl\fR and \fIr\fR. The character `&' in the \fIr\fR is replaced by \fIl\fR; `\e' also quotes `&'. If \fIl\fR is empty (``''), the \fIl\fR from a previous substitution or the \fIs\fR from a previous search or event number in event specification is used. The trailing delimiter may be omitted if it is immediately followed by a newline. .TP 8 & Repeat the previous substitution. .TP 8 g Apply the following modifier once to each word. .TP 8 a (+) Apply the following modifier as many times as possible to a single word. `a' and `g' can be used together to apply a modifier globally. With the `s' modifier, only the patterns contained in the original word are substituted, not patterns that contain any substitution result. .TP 8 p Print the new command line but do not execute it. .TP 8 q Quote the substituted words, preventing further substitutions. .TP 8 Q Same as q but in addition preserve empty variables as a string containing a NUL. This is useful to preserve positional arguments for example: .IP "" 12 > set args=('arg 1' '' 'arg 3') .br > tcsh -f -c 'echo ${#argv}' $args:gQ .br 3 .br .TP 8 x Like q, but break into words at blanks, tabs and newlines. .PD .RE .PP Modifiers are applied to only the first modifiable word (unless `g' is used). It is an error for no word to be modifiable. .PP For example, the `diff' command might have been written as `diff wumpus.man.old !#^:r', using `:r' to remove `.old' from the first argument on the same line (`!#^'). We could say `echo hello out there', then `echo !*:u' to capitalize `hello', `echo !*:au' to say it out loud, or `echo !*:agu' to really shout. We might follow `mail \-s "I forgot my password" rot' with `!:s/rot/root' to correct the spelling of `root' (but see \fBSpelling correction\fR for a different approach). .PP There is a special abbreviation for substitutions. `^', when it is the first character on an input line, is equivalent to `!:s^'. Thus we might have said `^rot^root' to make the spelling correction in the previous example. This is the only history substitution which does not explicitly begin with `!'. .PP (+) In \fIcsh\fR as such, only one modifier may be applied to each history or variable expansion. In \fItcsh\fR, more than one may be used, for example .IP "" 4 % mv wumpus.man /usr/man/man1/wumpus.1 .br % man !$:t:r .br man wumpus .PP In \fIcsh\fR, the result would be `wumpus.1:r'. A substitution followed by a colon may need to be insulated from it with braces: .IP "" 4 > mv a.out /usr/games/wumpus .br > setenv PATH !$:h:$PATH .br Bad ! modifier: $. .br > setenv PATH !{\-2$:h}:$PATH .br setenv PATH /usr/games:/bin:/usr/bin:. .PP The first attempt would succeed in \fIcsh\fR but fails in \fItcsh\fR, because \fItcsh\fR expects another modifier after the second colon rather than `$'. .PP Finally, history can be accessed through the editor as well as through the substitutions just described. The \fIup-\fR and \fIdown-history\fR, \fIhistory-search-backward\fR and \fI-forward\fR, \fIi-search-back\fR and \fI-fwd\fR, \fIvi-search-back\fR and \fI-fwd\fR, \fIcopy-prev-word\fR and \fIinsert-last-word\fR editor commands search for events in the history list and copy them into the input buffer. The \fItoggle-literal-history\fR editor command switches between the expanded and literal forms of history lines in the input buffer. \fIexpand-history\fR and \fIexpand-line\fR expand history substitutions in the current word and in the entire input buffer respectively. .SS "Alias substitution" The shell maintains a list of aliases which can be set, unset and printed by the \fIalias\fR and \fIunalias\fR commands. After a command line is parsed into simple commands (see \fBCommands\fR) the first word of each command, left-to-right, is checked to see if it has an alias. If so, the first word is replaced by the alias. If the alias contains a history reference, it undergoes \fBHistory substitution\fR (q.v.) as though the original command were the previous input line. If the alias does not contain a history reference, the argument list is left untouched. .PP Thus if the alias for `ls' were `ls \-l' the command `ls /usr' would become `ls \-l /usr', the argument list here being undisturbed. If the alias for `lookup' were `grep !^ /etc/passwd' then `lookup bill' would become `grep bill /etc/passwd'. Aliases can be used to introduce parser metasyntax. For example, `alias print 'pr \e!* | lpr'' defines a ``command'' (`print') which \fIpr\fR(1)s its arguments to the line printer. .PP Alias substitution is repeated until the first word of the command has no alias. If an alias substitution does not change the first word (as in the previous example) it is flagged to prevent a loop. Other loops are detected and cause an error. .PP Some aliases are referred to by the shell; see \fBSpecial aliases\fR. .SS "Variable substitution" The shell maintains a list of variables, each of which has as value a list of zero or more words. The values of shell variables can be displayed and changed with the \fIset\fR and \fIunset\fR commands. The system maintains its own list of ``environment'' variables. These can be displayed and changed with \fIprintenv\fR, \fIsetenv\fR and \fIunsetenv\fR. .PP (+) Variables may be made read-only with `set \-r' (q.v.). Read-only variables may not be modified or unset; attempting to do so will cause an error. Once made read-only, a variable cannot be made writable, so `set \-r' should be used with caution. Environment variables cannot be made read-only. .PP Some variables are set by the shell or referred to by it. For instance, the \fBargv\fR variable is an image of the shell's argument list, and words of this variable's value are referred to in special ways. Some of the variables referred to by the shell are toggles; the shell does not care what their value is, only whether they are set or not. For instance, the \fBverbose\fR variable is a toggle which causes command input to be echoed. The \fB\-v\fR command line option sets this variable. \fBSpecial shell variables\fR lists all variables which are referred to by the shell. .PP Other operations treat variables numerically. The `@' command permits numeric calculations to be performed and the result assigned to a variable. Variable values are, however, always represented as (zero or more) strings. For the purposes of numeric operations, the null string is considered to be zero, and the second and subsequent words of multi-word values are ignored. .PP After the input line is aliased and parsed, and before each command is executed, variable substitution is performed keyed by `$' characters. This expansion can be prevented by preceding the `$' with a `\e' except within `"'s where it \fIalways\fR occurs, and within `''s where it \fInever\fR occurs. Strings quoted by `\`' are interpreted later (see \fBCommand substitution\fR below) so `$' substitution does not occur there until later, if at all. A `$' is passed unchanged if followed by a blank, tab, or end-of-line. .PP Input/output redirections are recognized before variable expansion, and are variable expanded separately. Otherwise, the command name and entire argument list are expanded together. It is thus possible for the first (command) word (to this point) to generate more than one word, the first of which becomes the command name, and the rest of which become arguments. .PP Unless enclosed in `"' or given the `:q' modifier the results of variable substitution may eventually be command and filename substituted. Within `"', a variable whose value consists of multiple words expands to a (portion of a) single word, with the words of the variable's value separated by blanks. When the `:q' modifier is applied to a substitution the variable will expand to multiple words with each word separated by a blank and quoted to prevent later command or filename substitution. .PP The following metasequences are provided for introducing variable values into the shell input. Except as noted, it is an error to reference a variable which is not set. .PP .PD 0 $\fIname\fR .TP 8 ${\fIname\fR} Substitutes the words of the value of variable \fIname\fR, each separated by a blank. Braces insulate \fIname\fR from following characters which would otherwise be part of it. Shell variables have names consisting of letters and digits starting with a letter. The underscore character is considered a letter. If \fIname\fR is not a shell variable, but is set in the environment, then that value is returned (but some of the other forms given below are not available in this case). .PP $\fIname\fR[\fIselector\fR] .TP 8 ${\fIname\fR[\fIselector\fR]} Substitutes only the selected words from the value of \fIname\fR. The \fIselector\fR is subjected to `$' substitution and may consist of a single number or two numbers separated by a `\-'. The first word of a variable's value is numbered `1'. If the first number of a range is omitted it defaults to `1'. If the last member of a range is omitted it defaults to `$#\fIname\fR'. The \fIselector\fR `*' selects all words. It is not an error for a range to be empty if the second argument is omitted or in range. .TP 8 $0 Substitutes the name of the file from which command input is being read. An error occurs if the name is not known. .PP $\fInumber\fR .TP 8 ${\fInumber\fR} Equivalent to `$argv[\fInumber\fR]'. .TP 8 $* Equivalent to `$argv', which is equivalent to `$argv[*]'. .PD .PP The `:' modifiers described under \fBHistory substitution\fR, except for `:p', can be applied to the substitutions above. More than one may be used. (+) Braces may be needed to insulate a variable substitution from a literal colon just as with \fBHistory substitution\fR (q.v.); any modifiers must appear within the braces. .PP The following substitutions can not be modified with `:' modifiers. .PP .PD 0 $?\fIname\fR .TP 8 ${?\fIname\fR} Substitutes the string `1' if \fIname\fR is set, `0' if it is not. .TP 8 $?0 Substitutes `1' if the current input filename is known, `0' if it is not. Always `0' in interactive shells. .PP $#\fIname\fR .TP 8 ${#\fIname\fR} Substitutes the number of words in \fIname\fR. .TP 8 $# Equivalent to `$#argv'. (+) .PP $%\fIname\fR .TP 8 ${%\fIname\fR} Substitutes the number of characters in \fIname\fR. (+) .PP $%\fInumber\fR .TP 8 ${%\fInumber\fR} Substitutes the number of characters in $argv[\fInumber\fR]. (+) .TP 8 $? Equivalent to `$status'. (+) .TP 8 $$ Substitutes the (decimal) process number of the (parent) shell. .TP 8 $! Substitutes the (decimal) process number of the last background process started by this shell. (+) .TP 8 $_ Substitutes the command line of the last command executed. (+) .TP 8 $< Substitutes a line from the standard input, with no further interpretation thereafter. It can be used to read from the keyboard in a shell script. (+) While \fIcsh\fR always quotes $<, as if it were equivalent to `$<:q', \fItcsh\fR does not. Furthermore, when \fItcsh\fR is waiting for a line to be typed the user may type an interrupt to interrupt the sequence into which the line is to be substituted, but \fIcsh\fR does not allow this. .PD .PP The editor command \fIexpand-variables\fR, normally bound to `^X-$', can be used to interactively expand individual variables. .SS "Command, filename and directory stack substitution" The remaining substitutions are applied selectively to the arguments of builtin commands. This means that portions of expressions which are not evaluated are not subjected to these expansions. For commands which are not internal to the shell, the command name is substituted separately from the argument list. This occurs very late, after input-output redirection is performed, and in a child of the main shell. .SS "Command substitution" Command substitution is indicated by a command enclosed in `\`'. The output from such a command is broken into separate words at blanks, tabs and newlines, and null words are discarded. The output is variable and command substituted and put in place of the original string. .PP Command substitutions inside double quotes (`"') retain blanks and tabs; only newlines force new words. The single final newline does not force a new word in any case. It is thus possible for a command substitution to yield only part of a word, even if the command outputs a complete line. .PP By default, the shell since version 6.12 replaces all newline and carriage return characters in the command by spaces. If this is switched off by unsetting \fBcsubstnonl\fR, newlines separate commands as usual. .SS "Filename substitution" If a word contains any of the characters `*', `?', `[' or `{' or begins with the character `~' it is a candidate for filename substitution, also known as ``globbing''. This word is then regarded as a pattern (``glob-pattern''), and replaced with an alphabetically sorted list of file names which match the pattern. .PP In matching filenames, the character `.' at the beginning of a filename or immediately following a `/', as well as the character `/' must be matched explicitly (unless either .B globdot or .B globstar or both are set(+)). The character `*' matches any string of characters, including the null string. The character `?' matches any single character. The sequence `[...]' matches any one of the characters enclosed. Within `[...]', a pair of characters separated by `\-' matches any character lexically between the two. .PP (+) Some glob-patterns can be negated: The sequence `[^...]' matches any single character \fInot\fR specified by the characters and/or ranges of characters in the braces. .PP An entire glob-pattern can also be negated with `^': .IP "" 4 > echo * .br bang crash crunch ouch .br > echo ^cr* .br bang ouch .PP Glob-patterns which do not use `?', `*', or `[]' or which use `{}' or `~' (below) are not negated correctly. .PP The metanotation `a{b,c,d}e' is a shorthand for `abe ace ade'. Left-to-right order is preserved: `/usr/source/s1/{oldls,ls}.c' expands to `/usr/source/s1/oldls.c /usr/source/s1/ls.c'. The results of matches are sorted separately at a low level to preserve this order: `../{memo,*box}' might expand to `../memo ../box ../mbox'. (Note that `memo' was not sorted with the results of matching `*box'.) It is not an error when this construct expands to files which do not exist, but it is possible to get an error from a command to which the expanded list is passed. This construct may be nested. As a special case the words `{', `}' and `{}' are passed undisturbed. .PP The character `~' at the beginning of a filename refers to home directories. Standing alone, i.e., `~', it expands to the invoker's home directory as reflected in the value of the \fBhome\fR shell variable. When followed by a name consisting of letters, digits and `\-' characters the shell searches for a user with that name and substitutes their home directory; thus `~ken' might expand to `/usr/ken' and `~ken/chmach' to `/usr/ken/chmach'. If the character `~' is followed by a character other than a letter or `/' or appears elsewhere than at the beginning of a word, it is left undisturbed. A command like `setenv MANPATH /usr/man:/usr/local/man:~/lib/man' does not, therefore, do home directory substitution as one might hope. .PP It is an error for a glob-pattern containing `*', `?', `[' or `~', with or without `^', not to match any files. However, only one pattern in a list of glob-patterns must match a file (so that, e.g., `rm *.a *.c *.o' would fail only if there were no files in the current directory ending in `.a', `.c', or `.o'), and if the \fBnonomatch\fR shell variable is set a pattern (or list of patterns) which matches nothing is left unchanged rather than causing an error. .PP The \fBglobstar\fR shell variable can be set to allow `**' or `***' as a file glob pattern that matches any string of characters including `/', recursively traversing any existing sub-directories. For example, `ls **.c' will list all the .c files in the current directory tree. If used by itself, it will match zero or more sub-directories (e.g. `ls /usr/include/**/time.h' will list any file named `time.h' in the /usr/include directory tree; `ls /usr/include/**time.h' will match any file in the /usr/include directory tree ending in `time.h'; and `ls /usr/include/**time**.h' will match any .h file with `time' either in a subdirectory name or in the filename itself). To prevent problems with recursion, the `**' glob-pattern will not descend into a symbolic link containing a directory. To override this, use `***' (+) .PP The \fBnoglob\fR shell variable can be set to prevent filename substitution, and the \fIexpand-glob\fR editor command, normally bound to `^X-*', can be used to interactively expand individual filename substitutions. .SS "Directory stack substitution (+)" The directory stack is a list of directories, numbered from zero, used by the \fIpushd\fR, \fIpopd\fR and \fIdirs\fR builtin commands (q.v.). \fIdirs\fR can print, store in a file, restore and clear the directory stack at any time, and the \fBsavedirs\fR and \fBdirsfile\fR shell variables can be set to store the directory stack automatically on logout and restore it on login. The \fBdirstack\fR shell variable can be examined to see the directory stack and set to put arbitrary directories into the directory stack. .PP The character `=' followed by one or more digits expands to an entry in the directory stack. The special case `=\-' expands to the last directory in the stack. For example, .IP "" 4 > dirs \-v .br 0 /usr/bin .br 1 /usr/spool/uucp .br 2 /usr/accts/sys .br > echo =1 .br /usr/spool/uucp .br > echo =0/calendar .br /usr/bin/calendar .br > echo =\- .br /usr/accts/sys .PP The \fBnoglob\fR and \fBnonomatch\fR shell variables and the \fIexpand-glob\fR editor command apply to directory stack as well as filename substitutions. .SS "Other substitutions (+)" There are several more transformations involving filenames, not strictly related to the above but mentioned here for completeness. \fIAny\fR filename may be expanded to a full path when the \fBsymlinks\fR variable (q.v.) is set to `expand'. Quoting prevents this expansion, and the \fInormalize-path\fR editor command does it on demand. The \fInormalize-command\fR editor command expands commands in PATH into full paths on demand. Finally, \fIcd\fR and \fIpushd\fR interpret `\-' as the old working directory (equivalent to the shell variable \fBowd\fR). This is not a substitution at all, but an abbreviation recognized by only those commands. Nonetheless, it too can be prevented by quoting. .SS Commands The next three sections describe how the shell executes commands and deals with their input and output. .SS Simple commands, pipelines and sequences A simple command is a sequence of words, the first of which specifies the command to be executed. A series of simple commands joined by `|' characters forms a pipeline. The output of each command in a pipeline is connected to the input of the next. .PP Simple commands and pipelines may be joined into sequences with `;', and will be executed sequentially. Commands and pipelines can also be joined into sequences with `||' or `&&', indicating, as in the C language, that the second is to be executed only if the first fails or succeeds respectively. .PP A simple command, pipeline or sequence may be placed in parentheses, `()', to form a simple command, which may in turn be a component of a pipeline or sequence. A command, pipeline or sequence can be executed without waiting for it to terminate by following it with an `&'. .SS "Builtin and non-builtin command execution" Builtin commands are executed within the shell. If any component of a pipeline except the last is a builtin command, the pipeline is executed in a subshell. .PP Parenthesized commands are always executed in a subshell. .IP "" 4 (cd; pwd); pwd .PP thus prints the \fBhome\fR directory, leaving you where you were (printing this after the home directory), while .IP "" 4 cd; pwd .PP leaves you in the \fBhome\fR directory. Parenthesized commands are most often used to prevent \fIcd\fR from affecting the current shell. .PP When a command to be executed is found not to be a builtin command the shell attempts to execute the command via \fIexecve\fR(2). Each word in the variable \fBpath\fR names a directory in which the shell will look for the command. If the shell is not given a \fB\-f\fR option, the shell hashes the names in these directories into an internal table so that it will try an \fIexecve\fR(2) in only a directory where there is a possibility that the command resides there. This greatly speeds command location when a large number of directories are present in the search path. This hashing mechanism is not used: .TP 4 .B 1. If hashing is turned explicitly off via \fIunhash\fR. .TP 4 .B 2. If the shell was given a \fB\-f\fR argument. .TP 4 .B 3. For each directory component of \fBpath\fR which does not begin with a `/'. .TP 4 .B 4. If the command contains a `/'. .PP In the above four cases the shell concatenates each component of the path vector with the given command name to form a path name of a file which it then attempts to execute it. If execution is successful, the search stops. .PP If the file has execute permissions but is not an executable to the system (i.e., it is neither an executable binary nor a script that specifies its interpreter), then it is assumed to be a file containing shell commands and a new shell is spawned to read it. The \fIshell\fR special alias may be set to specify an interpreter other than the shell itself. .PP On systems which do not understand the `#!' script interpreter convention the shell may be compiled to emulate it; see the \fBversion\fR shell variable. If so, the shell checks the first line of the file to see if it is of the form `#!\fIinterpreter\fR \fIarg\fR ...'. If it is, the shell starts \fIinterpreter\fR with the given \fIarg\fRs and feeds the file to it on standard input. .SS Input/output The standard input and standard output of a command may be redirected with the following syntax: .PP .PD 0 .TP 8 < \fIname Open file \fIname\fR (which is first variable, command and filename expanded) as the standard input. .TP 8 << \fIword Read the shell input up to a line which is identical to \fIword\fR. \fIword\fR is not subjected to variable, filename or command substitution, and each input line is compared to \fIword\fR before any substitutions are done on this input line. Unless a quoting `\e', `"', `' or `\`' appears in \fIword\fR variable and command substitution is performed on the intervening lines, allowing `\e' to quote `$', `\e' and `\`'. Commands which are substituted have all blanks, tabs, and newlines preserved, except for the final newline which is dropped. The resultant text is placed in an anonymous temporary file which is given to the command as standard input. .PP > \fIname .br >! \fIname .br >& \fIname .TP 8 >&! \fIname The file \fIname\fR is used as standard output. If the file does not exist then it is created; if the file exists, it is truncated, its previous contents being lost. .RS +8 .PD .PP If the shell variable \fBnoclobber\fR is set, then the file must not exist or be a character special file (e.g., a terminal or `/dev/null') or an error results. This helps prevent accidental destruction of files. In this case the `!' forms can be used to suppress this check. If \fBnotempty\fR is given in \fBnoclobber\fR, `>' is allowed on empty files; if \fBask\fR is set, an interacive confirmation is presented, rather than an error. .PP The forms involving `&' route the diagnostic output into the specified file as well as the standard output. \fIname\fR is expanded in the same way as `<' input filenames are. .PD 0 .RE .PP >> \fIname .br >>& \fIname .br >>! \fIname .TP 8 >>&! \fIname Like `>', but appends output to the end of \fIname\fR. If the shell variable \fBnoclobber\fR is set, then it is an error for the file \fInot\fR to exist, unless one of the `!' forms is given. .PD .PP A command receives the environment in which the shell was invoked as modified by the input-output parameters and the presence of the command in a pipeline. Thus, unlike some previous shells, commands run from a file of shell commands have no access to the text of the commands by default; rather they receive the original standard input of the shell. The `<<' mechanism should be used to present inline data. This permits shell command scripts to function as components of pipelines and allows the shell to block read its input. Note that the default standard input for a command run detached is \fInot\fR the empty file \fI/dev/null\fR, but the original standard input of the shell. If this is a terminal and if the process attempts to read from the terminal, then the process will block and the user will be notified (see \fBJobs\fR). .PP Diagnostic output may be directed through a pipe with the standard output. Simply use the form `|&' rather than just `|'. .PP The shell cannot presently redirect diagnostic output without also redirecting standard output, but `(\fIcommand\fR > \fIoutput-file\fR) >& \fIerror-file\fR' is often an acceptable workaround. Either \fIoutput-file\fR or \fIerror-file\fR may be `/dev/tty' to send output to the terminal. .SS Features Having described how the shell accepts, parses and executes command lines, we now turn to a variety of its useful features. .SS "Control flow" The shell contains a number of commands which can be used to regulate the flow of control in command files (shell scripts) and (in limited but useful ways) from terminal input. These commands all operate by forcing the shell to reread or skip in its input and, due to the implementation, restrict the placement of some of the commands. .PP The \fIforeach\fR, \fIswitch\fR, and \fIwhile\fR statements, as well as the \fIif-then-else\fR form of the \fIif\fR statement, require that the major keywords appear in a single simple command on an input line as shown below. .PP If the shell's input is not seekable, the shell buffers up input whenever a loop is being read and performs seeks in this internal buffer to accomplish the rereading implied by the loop. (To the extent that this allows, backward \fIgoto\fRs will succeed on non-seekable inputs.) .SS Expressions The \fIif\fR, \fIwhile\fR and \fIexit\fR builtin commands use expressions with a common syntax. The expressions can include any of the operators described in the next three sections. Note that the \fI@\fR builtin command (q.v.) has its own separate syntax. .SS "Logical, arithmetical and comparison operators" These operators are similar to those of C and have the same precedence. They include .IP "" 4 || && | ^ & == != =~ !~ <= >= .br < > << >> + \- * / % ! ~ ( ) .PP Here the precedence increases to the right, `==' `!=' `=~' and `!~', `<=' `>=' `<' and `>', `<<' and `>>', `+' and `\-', `*' `/' and `%' being, in groups, at the same level. The `==' `!=' `=~' and `!~' operators compare their arguments as strings; all others operate on numbers. The operators `=~' and `!~' are like `!=' and `==' except that the right hand side is a glob-pattern (see \fBFilename substitution\fR) against which the left hand operand is matched. This reduces the need for use of the \fIswitch\fR builtin command in shell scripts when all that is really needed is pattern matching. .PP Null or missing arguments are considered `0'. The results of all expressions are strings, which represent decimal numbers. It is important to note that no two components of an expression can appear in the same word; except when adjacent to components of expressions which are syntactically significant to the parser (`&' `|' `<' `>' `(' `)') they should be surrounded by spaces. .SS "Command exit status" Commands can be executed in expressions and their exit status returned by enclosing them in braces (`{}'). Remember that the braces should be separated from the words of the command by spaces. Command executions succeed, returning true, i.e., `1', if the command exits with status 0, otherwise they fail, returning false, i.e., `0'. If more detailed status information is required then the command should be executed outside of an expression and the \fBstatus\fR shell variable examined. .SS "File inquiry operators" Some of these operators perform true/false tests on files and related objects. They are of the form \fB\-\fIop file\fR, where \fIop\fR is one of .PP .PD 0 .RS +4 .TP 4 .B r Read access .TP 4 .B w Write access .TP 4 .B x Execute access .TP 4 .B X Executable in the path or shell builtin, e.g., `\-X ls' and `\-X ls\-F' are generally true, but `\-X /bin/ls' is not (+) .TP 4 .B e Existence .TP 4 .B o Ownership .TP 4 .B z Zero size .TP 4 .B s Non-zero size (+) .TP 4 .B f Plain file .TP 4 .B d Directory .TP 4 .B l Symbolic link (+) * .TP 4 .B b Block special file (+) .TP 4 .B c Character special file (+) .TP 4 .B p Named pipe (fifo) (+) * .TP 4 .B S Socket special file (+) * .TP 4 .B u Set-user-ID bit is set (+) .TP 4 .B g Set-group-ID bit is set (+) .TP 4 .B k Sticky bit is set (+) .TP 4 .B t \fIfile\fR (which must be a digit) is an open file descriptor for a terminal device (+) .TP 4 .B R Has been migrated (Convex only) (+) .TP 4 .B L Applies subsequent operators in a multiple-operator test to a symbolic link rather than to the file to which the link points (+) * .RE .PD .PP \fIfile\fR is command and filename expanded and then tested to see if it has the specified relationship to the real user. If \fIfile\fR does not exist or is inaccessible or, for the operators indicated by `*', if the specified file type does not exist on the current system, then all inquiries return false, i.e., `0'. .PP These operators may be combined for conciseness: `\-\fIxy file\fR' is equivalent to `\-\fIx file\fR && \-\fIy file\fR'. (+) For example, `\-fx' is true (returns `1') for plain executable files, but not for directories. .PP \fBL\fR may be used in a multiple-operator test to apply subsequent operators to a symbolic link rather than to the file to which the link points. For example, `\-lLo' is true for links owned by the invoking user. \fBLr\fR, \fBLw\fR and \fBLx\fR are always true for links and false for non-links. \fBL\fR has a different meaning when it is the last operator in a multiple-operator test; see below. .PP It is possible but not useful, and sometimes misleading, to combine operators which expect \fIfile\fR to be a file with operators which do not (e.g., \fBX\fR and \fBt\fR). Following \fBL\fR with a non-file operator can lead to particularly strange results. .PP Other operators return other information, i.e., not just `0' or `1'. (+) They have the same format as before; \fIop\fR may be one of .PP .PD 0 .RS +4 .TP 8 .B A Last file access time, as the number of seconds since the epoch .TP 8 .B A: Like \fBA\fR, but in timestamp format, e.g., `Fri May 14 16:36:10 1993' .TP 8 .B M Last file modification time .TP 8 .B M: Like \fBM\fR, but in timestamp format .TP 8 .B C Last inode modification time .TP 8 .B C: Like \fBC\fR, but in timestamp format .TP 8 .B D Device number .TP 8 .B I Inode number .TP 8 .B F Composite \fBf\fRile identifier, in the form \fIdevice\fR:\fIinode\fR .TP 8 .B L The name of the file pointed to by a symbolic link .TP 8 .B N Number of (hard) links .TP 8 .B P Permissions, in octal, without leading zero .TP 8 .B P: Like \fBP\fR, with leading zero .TP 8 .B P\fImode Equivalent to `\-P \fIfile\fR & \fImode\fR', e.g., `\-P22 \fIfile\fR' returns `22' if \fIfile\fR is writable by group and other, `20' if by group only, and `0' if by neither .TP 8 .B P\fImode\fB: Like \fBP\fImode\fR, with leading zero .TP 8 .B U Numeric userid .TP 8 .B U: Username, or the numeric userid if the username is unknown .TP 8 .B G Numeric groupid .TP 8 .B G: Groupname, or the numeric groupid if the groupname is unknown .TP 8 .B Z Size, in bytes .RE .PD .PP Only one of these operators may appear in a multiple-operator test, and it must be the last. Note that \fBL\fR has a different meaning at the end of and elsewhere in a multiple-operator test. Because `0' is a valid return value for many of these operators, they do not return `0' when they fail: most return `\-1', and \fBF\fR returns `:'. .PP If the shell is compiled with POSIX defined (see the \fBversion\fR shell variable), the result of a file inquiry is based on the permission bits of the file and not on the result of the \fIaccess\fR(2) system call. For example, if one tests a file with \fB\-w\fR whose permissions would ordinarily allow writing but which is on a file system mounted read-only, the test will succeed in a POSIX shell but fail in a non-POSIX shell. .PP File inquiry operators can also be evaluated with the \fIfiletest\fR builtin command (q.v.) (+). .SS Jobs The shell associates a \fIjob\fR with each pipeline. It keeps a table of current jobs, printed by the \fIjobs\fR command, and assigns them small integer numbers. When a job is started asynchronously with `&', the shell prints a line which looks like .IP "" 4 [1] 1234 .PP indicating that the job which was started asynchronously was job number 1 and had one (top-level) process, whose process id was 1234. .PP If you are running a job and wish to do something else you may hit the suspend key (usually `^Z'), which sends a STOP signal to the current job. The shell will then normally indicate that the job has been `Suspended' and print another prompt. If the \fBlistjobs\fR shell variable is set, all jobs will be listed like the \fIjobs\fR builtin command; if it is set to `long' the listing will be in long format, like `jobs \-l'. You can then manipulate the state of the suspended job. You can put it in the ``background'' with the \fIbg\fR command or run some other commands and eventually bring the job back into the ``foreground'' with \fIfg\fR. (See also the \fIrun-fg-editor\fR editor command.) A `^Z' takes effect immediately and is like an interrupt in that pending output and unread input are discarded when it is typed. The \fIwait\fR builtin command causes the shell to wait for all background jobs to complete. .PP The `^]' key sends a delayed suspend signal, which does not generate a STOP signal until a program attempts to \fIread\fR(2) it, to the current job. This can usefully be typed ahead when you have prepared some commands for a job which you wish to stop after it has read them. The `^Y' key performs this function in \fIcsh\fR(1); in \fItcsh\fR, `^Y' is an editing command. (+) .PP A job being run in the background stops if it tries to read from the terminal. Background jobs are normally allowed to produce output, but this can be disabled by giving the command `stty tostop'. If you set this tty option, then background jobs will stop when they try to produce output like they do when they try to read input. .PP There are several ways to refer to jobs in the shell. The character `%' introduces a job name. If you wish to refer to job number 1, you can name it as `%1'. Just naming a job brings it to the foreground; thus `%1' is a synonym for `fg %1', bringing job 1 back into the foreground. Similarly, saying `%1 &' resumes job 1 in the background, just like `bg %1'. A job can also be named by an unambiguous prefix of the string typed in to start it: `%ex' would normally restart a suspended \fIex\fR(1) job, if there were only one suspended job whose name began with the string `ex'. It is also possible to say `%?\fIstring\fR' to specify a job whose text contains \fIstring\fR, if there is only one such job. .PP The shell maintains a notion of the current and previous jobs. In output pertaining to jobs, the current job is marked with a `+' and the previous job with a `\-'. The abbreviations `%+', `%', and (by analogy with the syntax of the \fIhistory\fR mechanism) `%%' all refer to the current job, and `%\-' refers to the previous job. .PP The job control mechanism requires that the \fIstty\fR(1) option `new' be set on some systems. It is an artifact from a `new' implementation of the tty driver which allows generation of interrupt characters from the keyboard to tell jobs to stop. See \fIstty\fR(1) and the \fIsetty\fR builtin command for details on setting options in the new tty driver. .SS "Status reporting" The shell learns immediately whenever a process changes state. It normally informs you whenever a job becomes blocked so that no further progress is possible, but only right before it prints a prompt. This is done so that it does not otherwise disturb your work. If, however, you set the shell variable \fBnotify\fR, the shell will notify you immediately of changes of status in background jobs. There is also a shell command \fInotify\fR which marks a single process so that its status changes will be immediately reported. By default \fInotify\fR marks the current process; simply say `notify' after starting a background job to mark it. .PP When you try to leave the shell while jobs are stopped, you will be warned that `There are suspended jobs.' You may use the \fIjobs\fR command to see what they are. If you do this or immediately try to exit again, the shell will not warn you a second time, and the suspended jobs will be terminated. .SS "Automatic, periodic and timed events (+)" There are various ways to run commands and take other actions automatically at various times in the ``life cycle'' of the shell. They are summarized here, and described in detail under the appropriate \fBBuiltin commands\fR, \fBSpecial shell variables\fR and \fBSpecial aliases\fR. .PP The \fIsched\fR builtin command puts commands in a scheduled-event list, to be executed by the shell at a given time. .PP The \fIbeepcmd\fR, \fIcwdcmd\fR, \fIperiodic\fR, \fIprecmd\fR, \fIpostcmd\fR, and \fIjobcmd\fR \fBSpecial aliases\fR can be set, respectively, to execute commands when the shell wants to ring the bell, when the working directory changes, every \fBtperiod\fR minutes, before each prompt, before each command gets executed, after each command gets executed, and when a job is started or is brought into the foreground. .PP The \fBautologout\fR shell variable can be set to log out or lock the shell after a given number of minutes of inactivity. .PP The \fBmail\fR shell variable can be set to check for new mail periodically. .PP The \fBprintexitvalue\fR shell variable can be set to print the exit status of commands which exit with a status other than zero. .PP The \fBrmstar\fR shell variable can be set to ask the user, when `rm *' is typed, if that is really what was meant. .PP The \fBtime\fR shell variable can be set to execute the \fItime\fR builtin command after the completion of any process that takes more than a given number of CPU seconds. .PP The \fBwatch\fR and \fBwho\fR shell variables can be set to report when selected users log in or out, and the \fIlog\fR builtin command reports on those users at any time. .SS "Native Language System support (+)" The shell is eight bit clean (if so compiled; see the \fBversion\fR shell variable) and thus supports character sets needing this capability. NLS support differs depending on whether or not the shell was compiled to use the system's NLS (again, see \fBversion\fR). In either case, 7-bit ASCII is the default character code (e.g., the classification of which characters are printable) and sorting, and changing the \fBLANG\fR or \fBLC_CTYPE\fR environment variables causes a check for possible changes in these respects. .PP When using the system's NLS, the \fIsetlocale\fR(3) function is called to determine appropriate character code/classification and sorting (e.g., a 'en_CA.UTF-8' would yield "UTF-8" as a character code). This function typically examines the \fBLANG\fR and \fBLC_CTYPE\fR environment variables; refer to the system documentation for further details. When not using the system's NLS, the shell simulates it by assuming that the ISO 8859-1 character set is used whenever either of the \fBLANG\fR and \fBLC_CTYPE\fR variables are set, regardless of their values. Sorting is not affected for the simulated NLS. .PP In addition, with both real and simulated NLS, all printable characters in the range \e200\-\e377, i.e., those that have M-\fIchar\fR bindings, are automatically rebound to \fIself-insert-command\fR. The corresponding binding for the escape-\fIchar\fR sequence, if any, is left alone. These characters are not rebound if the \fBNOREBIND\fR environment variable is set. This may be useful for the simulated NLS or a primitive real NLS which assumes full ISO 8859-1. Otherwise, all M-\fIchar\fR bindings in the range \e240\-\e377 are effectively undone. Explicitly rebinding the relevant keys with \fIbindkey\fR is of course still possible. .PP Unknown characters (i.e., those that are neither printable nor control characters) are printed in the format \ennn. If the tty is not in 8 bit mode, other 8 bit characters are printed by converting them to ASCII and using standout mode. The shell never changes the 7/8 bit mode of the tty and tracks user-initiated changes of 7/8 bit mode. NLS users (or, for that matter, those who want to use a meta key) may need to explicitly set the tty in 8 bit mode through the appropriate \fIstty\fR(1) command in, e.g., the \fI~/.login\fR file. .SS "OS variant support (+)" A number of new builtin commands are provided to support features in particular operating systems. All are described in detail in the \fBBuiltin commands\fR section. .PP On systems that support TCF (aix-ibm370, aix-ps2), \fIgetspath\fR and \fIsetspath\fR get and set the system execution path, \fIgetxvers\fR and \fIsetxvers\fR get and set the experimental version prefix and \fImigrate\fR migrates processes between sites. The \fIjobs\fR builtin prints the site on which each job is executing. .PP Under BS2000, \fIbs2cmd\fR executes commands of the underlying BS2000/OSD operating system. .PP Under Domain/OS, \fIinlib\fR adds shared libraries to the current environment, \fIrootnode\fR changes the rootnode and \fIver\fR changes the systype. .PP Under Mach, \fIsetpath\fR is equivalent to Mach's \fIsetpath\fR(1). .PP Under Masscomp/RTU and Harris CX/UX, \fIuniverse\fR sets the universe. .PP Under Harris CX/UX, \fIucb\fR or \fIatt\fR runs a command under the specified universe. .PP Under Convex/OS, \fIwarp\fR prints or sets the universe. .PP The \fBVENDOR\fR, \fBOSTYPE\fR and \fBMACHTYPE\fR environment variables indicate respectively the vendor, operating system and machine type (microprocessor class or machine model) of the system on which the shell thinks it is running. These are particularly useful when sharing one's home directory between several types of machines; one can, for example, .IP "" 4 set path = (~/bin.$MACHTYPE /usr/ucb /bin /usr/bin .) .PP in one's \fI~/.login\fR and put executables compiled for each machine in the appropriate directory. .PP The \fBversion\fR shell variable indicates what options were chosen when the shell was compiled. .PP Note also the \fInewgrp\fR builtin, the \fBafsuser\fR and \fBecho_style\fR shell variables and the system-dependent locations of the shell's input files (see \fBFILES\fR). .SS "Signal handling" Login shells ignore interrupts when reading the file \fI~/.logout\fR. The shell ignores quit signals unless started with \fB\-q\fR. Login shells catch the terminate signal, but non-login shells inherit the terminate behavior from their parents. Other signals have the values which the shell inherited from its parent. .PP In shell scripts, the shell's handling of interrupt and terminate signals can be controlled with \fIonintr\fR, and its handling of hangups can be controlled with \fIhup\fR and \fInohup\fR. .PP The shell exits on a hangup (see also the \fBlogout\fR shell variable). By default, the shell's children do too, but the shell does not send them a hangup when it exits. \fIhup\fR arranges for the shell to send a hangup to a child when it exits, and \fInohup\fR sets a child to ignore hangups. .SS "Terminal management (+)" The shell uses three different sets of terminal (``tty'') modes: `edit', used when editing, `quote', used when quoting literal characters, and `execute', used when executing commands. The shell holds some settings in each mode constant, so commands which leave the tty in a confused state do not interfere with the shell. The shell also matches changes in the speed and padding of the tty. The list of tty modes that are kept constant can be examined and modified with the \fIsetty\fR builtin. Note that although the editor uses CBREAK mode (or its equivalent), it takes typed-ahead characters anyway. .PP The \fIechotc\fR, \fIsettc\fR and \fItelltc\fR commands can be used to manipulate and debug terminal capabilities from the command line. .PP On systems that support SIGWINCH or SIGWINDOW, the shell adapts to window resizing automatically and adjusts the environment variables \fBLINES\fR and \fBCOLUMNS\fR if set. If the environment variable \fBTERMCAP\fR contains li# and co# fields, the shell adjusts them to reflect the new window size. .SH REFERENCE The next sections of this manual describe all of the available \fBBuiltin commands\fR, \fBSpecial aliases\fR and \fBSpecial shell variables\fR. .SS "Builtin commands" .TP 8 .B %\fIjob A synonym for the \fIfg\fR builtin command. .TP 8 .B %\fIjob \fB& A synonym for the \fIbg\fR builtin command. .TP 8 .B : Does nothing, successfully. .PP .B @ .br .B @ \fIname\fB = \fIexpr .br .B @ \fIname\fR[\fIindex\fR]\fB = \fIexpr .br .B @ \fIname\fB++\fR|\fB-- .PD 0 .TP 8 .B @ \fIname\fR[\fIindex\fR]\fB++\fR|\fB-- The first form prints the values of all shell variables. .PD .RS +8 .PP The second form assigns the value of \fIexpr\fR to \fIname\fR. The third form assigns the value of \fIexpr\fR to the \fIindex\fR'th component of \fIname\fR; both \fIname\fR and its \fIindex\fR'th component must already exist. .PP \fIexpr\fR may contain the operators `*', `+', etc., as in C. If \fIexpr\fR contains `<', `>', `&' or `' then at least that part of \fIexpr\fR must be placed within `()'. Note that the syntax of \fIexpr\fR has nothing to do with that described under \fBExpressions\fR. .PP The fourth and fifth forms increment (`++') or decrement (`\-\-') \fIname\fR or its \fIindex\fR'th component. .PP The space between `@' and \fIname\fR is required. The spaces between \fIname\fR and `=' and between `=' and \fIexpr\fR are optional. Components of \fIexpr\fR must be separated by spaces. .RE .PD .TP 8 .B alias \fR[\fIname \fR[\fIwordlist\fR]] Without arguments, prints all aliases. With \fIname\fR, prints the alias for name. With \fIname\fR and \fIwordlist\fR, assigns \fIwordlist\fR as the alias of \fIname\fR. \fIwordlist\fR is command and filename substituted. \fIname\fR may not be `alias' or `unalias'. See also the \fIunalias\fR builtin command. .TP 8 .B alloc Shows the amount of dynamic memory acquired, broken down into used and free memory. With an argument shows the number of free and used blocks in each size category. The categories start at size 8 and double at each step. This command's output may vary across system types, because systems other than the VAX may use a different memory allocator. .TP 8 .B bg \fR[\fB%\fIjob\fR ...] Puts the specified jobs (or, without arguments, the current job) into the background, continuing each if it is stopped. \fIjob\fR may be a number, a string, `', `%', `+' or `\-' as described under \fBJobs\fR. .PP .B bindkey \fR[\fB\-l\fR|\fB\-d\fR|\fB\-e\fR|\fB\-v\fR|\fB\-u\fR] (+) .br \fBbindkey \fR[\fB\-a\fR] [\fB\-b\fR] [\fB\-k\fR] [\fB\-r\fR] [\fB\-\-\fR] \fIkey \fR(+) .PD 0 .TP 8 \fBbindkey \fR[\fB\-a\fR] [\fB\-b\fR] [\fB\-k\fR] [\fB\-c\fR|\fB\-s\fR] [\fB\-\-\fR] \fIkey command \fR(+) .\" .B macro can't take too many words, so I used \fB in the previous tags Without options, the first form lists all bound keys and the editor command to which each is bound, the second form lists the editor command to which \fIkey\fR is bound and the third form binds the editor command \fIcommand\fR to \fIkey\fR. Options include: .PD .PP .PD 0 .RS +8 .TP 4 .B \-l Lists all editor commands and a short description of each. .TP 4 .B \-d Binds all keys to the standard bindings for the default editor, as per \fB-e\fR and \fB-v\fR below. .TP 4 .B \-e Binds all keys to \fIemacs\fR(1)\-style bindings. Unsets \fBvimode\fR. .TP 4 .B \-v Binds all keys to \fIvi\fR(1)\-style bindings. Sets \fBvimode\fR. .TP 4 .B \-a Lists or changes key-bindings in the alternative key map. This is the key map used in \fBvimode\fR command mode. .TP 4 .B \-b \fIkey\fR is interpreted as a control character written ^\fIcharacter\fR (e.g., `^A') or C-\fIcharacter\fR (e.g., `C-A'), a meta character written M-\fIcharacter\fR (e.g., `M-A'), a function key written F-\fIstring\fR (e.g., `F-string'), or an extended prefix key written X-\fIcharacter\fR (e.g., `X-A'). .TP 4 .B \-k \fIkey\fR is interpreted as a symbolic arrow key name, which may be one of `down', `up', `left' or `right'. .TP 4 .B \-r Removes \fIkey\fR's binding. Be careful: `bindkey \-r' does \fInot\fR bind \fIkey\fR to \fIself-insert-command\fR (q.v.), it unbinds \fIkey\fR completely. .TP 4 .B \-c \fIcommand\fR is interpreted as a builtin or external command instead of an editor command. .TP 4 .B \-s \fIcommand\fR is taken as a literal string and treated as terminal input when \fIkey\fR is typed. Bound keys in \fIcommand\fR are themselves reinterpreted, and this continues for ten levels of interpretation. .TP 4 .B \-\- Forces a break from option processing, so the next word is taken as \fIkey\fR even if it begins with '\-'. .TP 4 .B \-u \fR(or any invalid option) Prints a usage message. .PD .PP \fIkey\fR may be a single character or a string. If a command is bound to a string, the first character of the string is bound to \fIsequence-lead-in\fR and the entire string is bound to the command. .PP Control characters in \fIkey\fR can be literal (they can be typed by preceding them with the editor command \fIquoted-insert\fR, normally bound to `^V') or written caret-character style, e.g., `^A'. Delete is written `^?' (caret-question mark). \fIkey\fR and \fIcommand\fR can contain backslashed escape sequences (in the style of System V \fIecho\fR(1)) as follows: .RS +4 .TP 8 .PD 0 .B \ea Bell .TP 8 .B \eb Backspace .TP 8 .B \ee Escape .TP 8 .B \ef Form feed .TP 8 .B \en Newline .TP 8 .B \er Carriage return .TP 8 .B \et Horizontal tab .TP 8 .B \ev Vertical tab .TP 8 .B \e\fInnn The ASCII character corresponding to the octal number \fInnn\fR .PD .RE .PP `\e' nullifies the special meaning of the following character, if it has any, notably `\e' and `^'. .RE .TP 8 .B bs2cmd \fIbs2000-command\fR (+) Passes \fIbs2000-command\fR to the BS2000 command interpreter for execution. Only non-interactive commands can be executed, and it is not possible to execute any command that would overlay the image of the current process, like /EXECUTE or /CALL-PROCEDURE. (BS2000 only) .TP 8 .B break Causes execution to resume after the \fIend\fR of the nearest enclosing \fIforeach\fR or \fIwhile\fR. The remaining commands on the current line are executed. Multi-level breaks are thus possible by writing them all on one line. .TP 8 .B breaksw Causes a break from a \fIswitch\fR, resuming after the \fIendsw\fR. .TP 8 .B builtins \fR(+) Prints the names of all builtin commands. .TP 8 .B bye \fR(+) A synonym for the \fIlogout\fR builtin command. Available only if the shell was so compiled; see the \fBversion\fR shell variable. .TP 8 .B case \fIlabel\fB: A label in a \fIswitch\fR statement as discussed below. .TP 8 .B cd \fR[\fB\-p\fR] [\fB\-l\fR] [\fB\-n\fR|\fB\-v\fR] [\I--\fR] [\fIname\fR] If a directory \fIname\fR is given, changes the shell's working directory to \fIname\fR. If not, changes to \fBhome\fR, unless the \fBcdtohome\fR variable is not set, in which case a \fIname\fR is required. If \fIname\fR is `\-' it is interpreted as the previous working directory (see \fBOther substitutions\fR). (+) If \fIname\fR is not a subdirectory of the current directory (and does not begin with `/', `./' or `../'), each component of the variable \fBcdpath\fR is checked to see if it has a subdirectory \fIname\fR. Finally, if all else fails but \fIname\fR is a shell variable whose value begins with `/' or '.', then this is tried to see if it is a directory, and the \fB\-p\fR option is implied. .RS +8 .PP With \fB\-p\fR, prints the final directory stack, just like \fIdirs\fR. The \fB\-l\fR, \fB\-n\fR and \fB\-v\fR flags have the same effect on \fIcd\fR as on \fIdirs\fR, and they imply \fB\-p\fR. (+) Using \fB\-\-\fR forces a break from option processing so the next word is taken as the directory \fIname\fR even if it begins with '\-'. (+) .PP See also the \fBimplicitcd\fR and \fBcdtohome\fR shell variables. .RE .TP 8 .B chdir A synonym for the \fIcd\fR builtin command. .TP 8 .B complete \fR[\fIcommand\fR [\fIword\fB/\fIpattern\fB/\fIlist\fR[\fB:\fIselect\fR]\fB/\fR[[\fIsuffix\fR]\fB/\fR] ...]] (+) Without arguments, lists all completions. With \fIcommand\fR, lists completions for \fIcommand\fR. With \fIcommand\fR and \fIword\fR etc., defines completions. .RS +8 .PP \fIcommand\fR may be a full command name or a glob-pattern (see \fBFilename substitution\fR). It can begin with `\-' to indicate that completion should be used only when \fIcommand\fR is ambiguous. .PP \fIword\fR specifies which word relative to the current word is to be completed, and may be one of the following: .PP .PD 0 .RS +4 .TP 4 .B c Current-word completion. \fIpattern\fR is a glob-pattern which must match the beginning of the current word on the command line. \fIpattern\fR is ignored when completing the current word. .TP 4 .B C Like \fBc\fR, but includes \fIpattern\fR when completing the current word. .TP 4 .B n Next-word completion. \fIpattern\fR is a glob-pattern which must match the beginning of the previous word on the command line. .TP 4 .B N Like \fBn\fR, but must match the beginning of the word two before the current word. .TP 4 .B p Position-dependent completion. \fIpattern\fR is a numeric range, with the same syntax used to index shell variables, which must include the current word. .PD .RE .PP \fIlist\fR, the list of possible completions, may be one of the following: .PP .PD 0 .RS +4 .TP 8 .B a Aliases .TP 8 .B b Bindings (editor commands) .TP 8 .B c Commands (builtin or external commands) .TP 8 .B C External commands which begin with the supplied path prefix .TP 8 .B d Directories .TP 8 .B D Directories which begin with the supplied path prefix .TP 8 .B e Environment variables .TP 8 .B f Filenames .TP 8 .B F Filenames which begin with the supplied path prefix .TP 8 .B g Groupnames .TP 8 .B j Jobs .TP 8 .B l Limits .TP 8 .B n Nothing .TP 8 .B s Shell variables .TP 8 .B S Signals .TP 8 .B t Plain (``text'') files .TP 8 .B T Plain (``text'') files which begin with the supplied path prefix .TP 8 .B v Any variables .TP 8 .B u Usernames .TP 8 .B x Like \fBn\fR, but prints \fIselect\fR when \fIlist-choices\fR is used. .TP 8 .B X Completions .TP 8 $\fIvar\fR Words from the variable \fIvar\fR .TP 8 (...) Words from the given list .TP 8 \`...\` Words from the output of command .PD .RE .PP \fIselect\fR is an optional glob-pattern. If given, words from only \fIlist\fR that match \fIselect\fR are considered and the \fBfignore\fR shell variable is ignored. The last three types of completion may not have a \fIselect\fR pattern, and \fBx\fR uses \fIselect\fR as an explanatory message when the \fIlist-choices\fR editor command is used. .PP \fIsuffix\fR is a single character to be appended to a successful completion. If null, no character is appended. If omitted (in which case the fourth delimiter can also be omitted), a slash is appended to directories and a space to other words. .PP \fIcommand\fR invoked from \`...\` version has additional environment variable set, the variable name is \%\fBCOMMAND_LINE\fR\% and contains (as its name indicates) contents of the current (already typed in) command line. One can examine and use contents of the \%\fBCOMMAND_LINE\fR\% variable in her custom script to build more sophisticated completions (see completion for svn(1) included in this package). .PP Now for some examples. Some commands take only directories as arguments, so there's no point completing plain files. .IP "" 4 > complete cd 'p/1/d/' .PP completes only the first word following `cd' (`p/1') with a directory. \fBp\fR-type completion can also be used to narrow down command completion: .IP "" 4 > co[^D] .br complete compress .br > complete \-co* 'p/0/(compress)/' .br > co[^D] .br > compress .PP This completion completes commands (words in position 0, `p/0') which begin with `co' (thus matching `co*') to `compress' (the only word in the list). The leading `\-' indicates that this completion is to be used with only ambiguous commands. .IP "" 4 > complete find 'n/\-user/u/' .PP is an example of \fBn\fR-type completion. Any word following `find' and immediately following `\-user' is completed from the list of users. .IP "" 4 > complete cc 'c/\-I/d/' .PP demonstrates \fBc\fR-type completion. Any word following `cc' and beginning with `\-I' is completed as a directory. `\-I' is not taken as part of the directory because we used lowercase \fBc\fR. .PP Different \fIlist\fRs are useful with different commands. .IP "" 4 > complete alias 'p/1/a/' .br > complete man 'p/*/c/' .br > complete set 'p/1/s/' .br > complete true 'p/1/x:Truth has no options./' .PP These complete words following `alias' with aliases, `man' with commands, and `set' with shell variables. `true' doesn't have any options, so \fBx\fR does nothing when completion is attempted and prints `Truth has no options.' when completion choices are listed. .PP Note that the \fIman\fR example, and several other examples below, could just as well have used 'c/*' or 'n/*' as 'p/*'. .PP Words can be completed from a variable evaluated at completion time, .IP "" 4 > complete ftp 'p/1/$hostnames/' .br > set hostnames = (rtfm.mit.edu tesla.ee.cornell.edu) .br > ftp [^D] .br rtfm.mit.edu tesla.ee.cornell.edu .br > ftp [^C] .br > set hostnames = (rtfm.mit.edu tesla.ee.cornell.edu uunet.uu.net) .br > ftp [^D] .br rtfm.mit.edu tesla.ee.cornell.edu uunet.uu.net .PP or from a command run at completion time: .IP "" 4 > complete kill 'p/*/\`ps | awk \e{print\e \e$1\e}\`/' .br > kill \-9 [^D] .br 23113 23377 23380 23406 23429 23529 23530 PID .PP Note that the \fIcomplete\fR command does not itself quote its arguments, so the braces, space and `$' in `{print $1}' must be quoted explicitly. .PP One command can have multiple completions: .IP "" 4 > complete dbx 'p/2/(core)/' 'p/*/c/' .PP completes the second argument to `dbx' with the word `core' and all other arguments with commands. Note that the positional completion is specified before the next-word completion. Because completions are evaluated from left to right, if the next-word completion were specified first it would always match and the positional completion would never be executed. This is a common mistake when defining a completion. .PP The \fIselect\fR pattern is useful when a command takes files with only particular forms as arguments. For example, .IP "" 4 > complete cc 'p/*/f:*.[cao]/' .PP completes `cc' arguments to files ending in only `.c', `.a', or `.o'. \fIselect\fR can also exclude files, using negation of a glob-pattern as described under \fBFilename substitution\fR. One might use .IP "" 4 > complete rm 'p/*/f:^*.{c,h,cc,C,tex,1,man,l,y}/' .PP to exclude precious source code from `rm' completion. Of course, one could still type excluded names manually or override the completion mechanism using the \fIcomplete-word-raw\fR or \fIlist-choices-raw\fR editor commands (q.v.). .PP The `C', `D', `F' and `T' \fIlist\fRs are like `c', `d', `f' and `t' respectively, but they use the \fIselect\fR argument in a different way: to restrict completion to files beginning with a particular path prefix. For example, the Elm mail program uses `=' as an abbreviation for one's mail directory. One might use .IP "" 4 > complete elm c@=@F:$HOME/Mail/@ .PP to complete `elm \-f =' as if it were `elm \-f ~/Mail/'. Note that we used `@' instead of `/' to avoid confusion with the \fIselect\fR argument, and we used `$HOME' instead of `~' because home directory substitution works at only the beginning of a word. .PP \fIsuffix\fR is used to add a nonstandard suffix (not space or `/' for directories) to completed words. .IP "" 4 > complete finger 'c/*@/$hostnames/' 'p/1/u/@' .PP completes arguments to `finger' from the list of users, appends an `@', and then completes after the `@' from the `hostnames' variable. Note again the order in which the completions are specified. .PP Finally, here's a complex example for inspiration: .IP "" 4 > complete find \e .br \&'n/\-name/f/' 'n/\-newer/f/' 'n/\-{,n}cpio/f/' \e .br \&\'n/\-exec/c/' 'n/\-ok/c/' 'n/\-user/u/' \e .br \&'n/\-group/g/' 'n/\-fstype/(nfs 4.2)/' \e .br \&'n/\-type/(b c d f l p s)/' \e .br \'c/\-/(name newer cpio ncpio exec ok user \e .br group fstype type atime ctime depth inum \e .br ls mtime nogroup nouser perm print prune \e .br size xdev)/' \e .br \&'p/*/d/' .PP This completes words following `\-name', `\-newer', `\-cpio' or `ncpio' (note the pattern which matches both) to files, words following `\-exec' or `\-ok' to commands, words following `user' and `group' to users and groups respectively and words following `\-fstype' or `\-type' to members of the given lists. It also completes the switches themselves from the given list (note the use of \fBc\fR-type completion) and completes anything not otherwise completed to a directory. Whew. .PP Remember that programmed completions are ignored if the word being completed is a tilde substitution (beginning with `~') or a variable (beginning with `$'). See also the \fIuncomplete\fR builtin command. .RE .TP 8 .B continue Continues execution of the nearest enclosing \fIwhile\fR or \fIforeach\fR. The rest of the commands on the current line are executed. .TP 8 .B default: Labels the default case in a \fIswitch\fR statement. It should come after all \fIcase\fR labels. .PP .B dirs \fR[\fB\-l\fR] [\fB\-n\fR|\fB\-v\fR] .br .B dirs \-S\fR|\fB\-L \fR[\fIfilename\fR] (+) .PD 0 .TP 8 .B dirs \-c \fR(+) The first form prints the directory stack. The top of the stack is at the left and the first directory in the stack is the current directory. With \fB\-l\fR, `~' or `~\fIname\fP' in the output is expanded explicitly to \fBhome\fR or the pathname of the home directory for user \fIname\fP. (+) With \fB\-n\fR, entries are wrapped before they reach the edge of the screen. (+) With \fB\-v\fR, entries are printed one per line, preceded by their stack positions. (+) If more than one of \fB\-n\fR or \fB\-v\fR is given, \fB\-v\fR takes precedence. \fB\-p\fR is accepted but does nothing. .PD .RS +8 .PP With \fB\-S\fR, the second form saves the directory stack to \fIfilename\fR as a series of \fIcd\fR and \fIpushd\fR commands. With \fB\-L\fR, the shell sources \fIfilename\fR, which is presumably a directory stack file saved by the \fB\-S\fR option or the \fBsavedirs\fR mechanism. In either case, \fBdirsfile\fR is used if \fIfilename\fR is not given and \fI~/.cshdirs\fR is used if \fBdirsfile\fR is unset. .PP Note that login shells do the equivalent of `dirs \-L' on startup and, if \fBsavedirs\fR is set, `dirs \-S' before exiting. Because only \fI~/.tcshrc\fR is normally sourced before \fI~/.cshdirs\fR, \fBdirsfile\fR should be set in \fI~/.tcshrc\fR rather than \fI~/.login\fR. .PP The last form clears the directory stack. .RE .TP 8 .B echo \fR[\fB\-n\fR] \fIword\fR ... Writes each \fIword\fR to the shell's standard output, separated by spaces and terminated with a newline. The \fBecho_style\fR shell variable may be set to emulate (or not) the flags and escape sequences of the BSD and/or System V versions of \fIecho\fR; see \fIecho\fR(1). .TP 8 .B echotc \fR[\fB\-sv\fR] \fIarg\fR ... (+) Exercises the terminal capabilities (see \fItermcap\fR(5)) in \fIargs\fR. For example, 'echotc home' sends the cursor to the home position, \&'echotc cm 3 10' sends it to column 3 and row 10, and \&'echotc ts 0; echo "This is a test."; echotc fs' prints "This is a test." in the status line. .RS +8 .PP If \fIarg\fR is 'baud', 'cols', 'lines', 'meta' or 'tabs', prints the value of that capability ("yes" or "no" indicating that the terminal does or does not have that capability). One might use this to make the output from a shell script less verbose on slow terminals, or limit command output to the number of lines on the screen: .IP "" 4 > set history=\`echotc lines\` .br > @ history\-\- .PP Termcap strings may contain wildcards which will not echo correctly. One should use double quotes when setting a shell variable to a terminal capability string, as in the following example that places the date in the status line: .IP "" 4 > set tosl="\`echotc ts 0\`" .br > set frsl="\`echotc fs\`" .br > echo \-n "$tosl";date; echo \-n "$frsl" .PP With \fB\-s\fR, nonexistent capabilities return the empty string rather than causing an error. With \fB\-v\fR, messages are verbose. .RE .PP .B else .br .B end .br .B endif .PD 0 .TP 8 .B endsw See the description of the \fIforeach\fR, \fIif\fR, \fIswitch\fR, and \fIwhile\fR statements below. .PD .TP 8 .B eval \fIarg\fR ... Treats the arguments as input to the shell and executes the resulting command(s) in the context of the current shell. This is usually used to execute commands generated as the result of command or variable substitution, because parsing occurs before these substitutions. See \fItset\fR(1) for a sample use of \fIeval\fR. .TP 8 .B exec \fIcommand\fR Executes the specified command in place of the current shell. .TP 8 .B exit \fR[\fIexpr\fR] The shell exits either with the value of the specified \fIexpr\fR (an expression, as described under \fBExpressions\fR) or, without \fIexpr\fR, with the value 0. .TP 8 .B fg \fR[\fB%\fIjob\fR ...] Brings the specified jobs (or, without arguments, the current job) into the foreground, continuing each if it is stopped. \fIjob\fR may be a number, a string, `', `%', `+' or `\-' as described under \fBJobs\fR. See also the \fIrun-fg-editor\fR editor command. .TP 8 .B filetest \-\fIop file\fR ... (+) Applies \fIop\fR (which is a file inquiry operator as described under \fBFile inquiry operators\fR) to each \fIfile\fR and returns the results as a space-separated list. .PP .B foreach \fIname \fB(\fIwordlist\fB) .br \&... .PD 0 .TP 8 .B end Successively sets the variable \fIname\fR to each member of \fIwordlist\fR and executes the sequence of commands between this command and the matching \fIend\fR. (Both \fIforeach\fR and \fIend\fR must appear alone on separate lines.) The builtin command \fIcontinue\fR may be used to continue the loop prematurely and the builtin command \fIbreak\fR to terminate it prematurely. When this command is read from the terminal, the loop is read once prompting with `foreach? ' (or \fBprompt2\fR) before any statements in the loop are executed. If you make a mistake typing in a loop at the terminal you can rub it out. .PD .TP 8 .B getspath \fR(+) Prints the system execution path. (TCF only) .TP 8 .B getxvers \fR(+) Prints the experimental version prefix. (TCF only) .TP 8 .B glob \fIwordlist Like \fIecho\fR, but the `-n' parameter is not recognized and words are delimited by null characters in the output. Useful for programs which wish to use the shell to filename expand a list of words. .TP 8 .B goto \fIword \fIword\fR is filename and command-substituted to yield a string of the form `label'. The shell rewinds its input as much as possible, searches for a line of the form `label:', possibly preceded by blanks or tabs, and continues execution after that line. .TP 8 .B hashstat Prints a statistics line indicating how effective the internal hash table has been at locating commands (and avoiding \fIexec\fR's). An \fIexec\fR is attempted for each component of the \fBpath\fR where the hash function indicates a possible hit, and in each component which does not begin with a `/'. .IP On machines without \fIvfork\fR(2), prints only the number and size of hash buckets. .PP .B history \fR[\fB\-hTr\fR] [\fIn\fR] .br .B history \-S\fR|\fB\-L|\fB\-M \fR[\fIfilename\fR] (+) .PD 0 .TP 8 .B history \-c \fR(+) The first form prints the history event list. If \fIn\fR is given only the \fIn\fR most recent events are printed or saved. With \fB\-h\fR, the history list is printed without leading numbers. If \fB-T\fR is specified, timestamps are printed also in comment form. (This can be used to produce files suitable for loading with 'history \-L' or 'source \-h'.) With \fB\-r\fR, the order of printing is most recent first rather than oldest first. .PD .RS +8 .PP With \fB\-S\fR, the second form saves the history list to \fIfilename\fR. If the first word of the \fBsavehist\fR shell variable is set to a number, at most that many lines are saved. If the second word of \fBsavehist\fR is set to `merge', the history list is merged with the existing history file instead of replacing it (if there is one) and sorted by time stamp. (+) Merging is intended for an environment like the X Window System with several shells in simultaneous use. If the second word of \fBsavehist\fR is `merge' and the third word is set to `lock', the history file update will be serialized with other shell sessions that would possibly like to merge history at exactly the same time. .PP With \fB\-L\fR, the shell appends \fIfilename\fR, which is presumably a history list saved by the \fB\-S\fR option or the \fBsavehist\fR mechanism, to the history list. \fB\-M\fR is like \fB\-L\fR, but the contents of \fIfilename\fR are merged into the history list and sorted by timestamp. In either case, \fBhistfile\fR is used if \fIfilename\fR is not given and \fI~/.history\fR is used if \fBhistfile\fR is unset. `history \-L' is exactly like 'source \-h' except that it does not require a filename. .PP Note that login shells do the equivalent of `history \-L' on startup and, if \fBsavehist\fR is set, `history \-S' before exiting. Because only \fI~/.tcshrc\fR is normally sourced before \fI~/.history\fR, \fBhistfile\fR should be set in \fI~/.tcshrc\fR rather than \fI~/.login\fR. .PP If \fBhistlit\fR is set, the first and second forms print and save the literal (unexpanded) form of the history list. .PP The last form clears the history list. .RE .TP 8 .B hup \fR[\fIcommand\fR] \fR(+) With \fIcommand\fR, runs \fIcommand\fR such that it will exit on a hangup signal and arranges for the shell to send it a hangup signal when the shell exits. Note that commands may set their own response to hangups, overriding \fIhup\fR. Without an argument, causes the non-interactive shell only to exit on a hangup for the remainder of the script. See also \fBSignal handling\fR and the \fInohup\fR builtin command. .TP 8 .B if (\fIexpr\fB) \fIcommand If \fIexpr\fR (an expression, as described under \fBExpressions\fR) evaluates true, then \fIcommand\fR is executed. Variable substitution on \fIcommand\fR happens early, at the same time it does for the rest of the \fIif\fR command. \fIcommand\fR must be a simple command, not an alias, a pipeline, a command list or a parenthesized command list, but it may have arguments. Input/output redirection occurs even if \fIexpr\fR is false and \fIcommand\fR is thus \fInot\fR executed; this is a bug. .PP .B if (\fIexpr\fB) then .br \&... .br .B else if (\fIexpr2\fB) then .br \&... .br .B else .br \&... .PD 0 .TP 8 .B endif If the specified \fIexpr\fR is true then the commands to the first \fIelse\fR are executed; otherwise if \fIexpr2\fR is true then the commands to the second \fIelse\fR are executed, etc. Any number of \fIelse-if\fR pairs are possible; only one \fIendif\fR is needed. The \fIelse\fR part is likewise optional. (The words \fIelse\fR and \fIendif\fR must appear at the beginning of input lines; the \fIif\fR must appear alone on its input line or after an \fIelse\fR.) .PD .TP 8 .B inlib \fIshared-library\fR ... (+) Adds each \fIshared-library\fR to the current environment. There is no way to remove a shared library. (Domain/OS only) .TP 8 .B jobs \fR[\fB\-l\fR] Lists the active jobs. With \fB\-l\fR, lists process IDs in addition to the normal information. On TCF systems, prints the site on which each job is executing. .PP .PD 0 .TP 8 .B kill \fR[\fB\-s \fIsignal\fR] \fB%\fIjob\fR|\fIpid\fR ... .PD 0 .TP 8 .B kill \-l The first and second forms sends the specified \fIsignal\fR (or, if none is given, the TERM (terminate) signal) to the specified jobs or processes. \fIjob\fR may be a number, a string, `', `%', `+' or `\-' as described under \fBJobs\fR. Signals are either given by number or by name (as given in \fI/usr/include/signal.h\fR, stripped of the prefix `SIG'). There is no default \fIjob\fR; saying just `kill' does not send a signal to the current job. If the signal being sent is TERM (terminate) or HUP (hangup), then the job or process is sent a CONT (continue) signal as well. The third form lists the signal names. .PD .TP 8 .B limit \fR[\fB\-h\fR] [\fIresource\fR [\fImaximum-use\fR]] Limits the consumption by the current process and each process it creates to not individually exceed \fImaximum-use\fR on the specified \fIresource\fR. If no \fImaximum-use\fR is given, then the current limit is printed; if no \fIresource\fR is given, then all limitations are given. If the \fB\-h\fR flag is given, the hard limits are used instead of the current limits. The hard limits impose a ceiling on the values of the current limits. Only the super-user may raise the hard limits, but a user may lower or raise the current limits within the legal range. .RS +8 .PP Controllable resources currently include (if supported by the OS): .TP \fIcputime\fR the maximum number of cpu-seconds to be used by each process .TP \fIfilesize\fR the largest single file which can be created .TP \fIdatasize\fR the maximum growth of the data+stack region via sbrk(2) beyond the end of the program text .TP \fIstacksize\fR the maximum size of the automatically-extended stack region .TP \fIcoredumpsize\fR the size of the largest core dump that will be created .TP \fImemoryuse\fR the maximum amount of physical memory a process may have allocated to it at a given time .TP \fIvmemoryuse\fR the maximum amount of virtual memory a process may have allocated to it at a given time (address space) .TP \fIvmemoryuse\fR the maximum amount of virtual memory a process may have allocated to it at a given time .TP \fIheapsize\fR the maximum amount of memory a process may allocate per \fIbrk()\fR system call .TP \fIdescriptors\fR or \fIopenfiles\fR the maximum number of open files for this process .TP \fIpseudoterminals\fR the maximum number of pseudo-terminals for this user .TP \fIkqueues\fR the maximum number of kqueues allocated for this process .TP \fIconcurrency\fR the maximum number of threads for this process .TP \fImemorylocked\fR the maximum size which a process may lock into memory using mlock(2) .TP \fImaxproc\fR the maximum number of simultaneous processes for this user id .TP \fImaxthread\fR the maximum number of simultaneous threads (lightweight processes) for this user id .TP \fIthreads\fR the maximum number of threads for this process .TP \fIsbsize\fR the maximum size of socket buffer usage for this user .TP \fIswapsize\fR the maximum amount of swap space reserved or used for this user .TP \fImaxlocks\fR the maximum number of locks for this user .TP \fIposixlocks\fR the maximum number of POSIX advisory locks for this user .TP \fImaxsignal\fR the maximum number of pending signals for this user .TP \fImaxmessage\fR the maximum number of bytes in POSIX mqueues for this user .TP \fImaxnice\fR the maximum nice priority the user is allowed to raise mapped from [19...-20] to [0...39] for this user .TP \fImaxrtprio\fR the maximum realtime priority for this user \fImaxrttime\fR the timeout for RT tasks in microseconds for this user. .PP \fImaximum-use\fR may be given as a (floating point or integer) number followed by a scale factor. For all limits other than \fIcputime\fR the default scale is `k' or `kilobytes' (1024 bytes); a scale factor of `m' or `megabytes' or `g' or `gigabytes' may also be used. For \fIcputime\fR the default scaling is `seconds', while `m' for minutes or `h' for hours, or a time of the form `mm:ss' giving minutes and seconds may be used. .PP If \fImaximum-use\fR is `unlimited', then the limitation on the specified \fIresource\fR is removed (this is equivalent to the \fIunlimit\fR builtin command). .PP For both \fIresource\fR names and scale factors, unambiguous prefixes of the names suffice. .RE .TP 8 .B log \fR(+) Prints the \fBwatch\fR shell variable and reports on each user indicated in \fBwatch\fR who is logged in, regardless of when they last logged in. See also \fIwatchlog\fR. .TP 8 .B login Terminates a login shell, replacing it with an instance of \fI/bin/login\fR. This is one way to log off, included for compatibility with \fIsh\fR(1). .TP 8 .B logout Terminates a login shell. Especially useful if \fBignoreeof\fR is set. .TP 8 .B ls\-F \fR[\-\fIswitch\fR ...] [\fIfile\fR ...] (+) Lists files like `ls \-F', but much faster. It identifies each type of special file in the listing with a special character: .PP .RS +8 .PD 0 .TP 4 / Directory .TP 4 * Executable .TP 4 # Block device .TP 4 % Character device .TP 4 | Named pipe (systems with named pipes only) .TP 4 = Socket (systems with sockets only) .TP 4 @ Symbolic link (systems with symbolic links only) .TP 4 + Hidden directory (AIX only) or context dependent (HP/UX only) .TP 4 : Network special (HP/UX only) .PD .PP If the \fBlistlinks\fR shell variable is set, symbolic links are identified in more detail (on only systems that have them, of course): .PP .PD 0 .TP 4 @ Symbolic link to a non-directory .TP 4 > Symbolic link to a directory .TP 4 & Symbolic link to nowhere .PD .PP \fBlistlinks\fR also slows down \fIls\-F\fR and causes partitions holding files pointed to by symbolic links to be mounted. .PP If the \fBlistflags\fR shell variable is set to `x', `a' or `A', or any combination thereof (e.g., `xA'), they are used as flags to \fIls\-F\fR, making it act like `ls \-xF', `ls \-Fa', `ls \-FA' or a combination (e.g., `ls \-FxA'). On machines where `ls \-C' is not the default, \fIls\-F\fR acts like `ls \-CF', unless \fBlistflags\fR contains an `x', in which case it acts like `ls \-xF'. \fIls\-F\fR passes its arguments to \fIls\fR(1) if it is given any switches, so `alias ls ls\-F' generally does the right thing. .PP The \fBls\-F\fR builtin can list files using different colors depending on the filetype or extension. See the \fBcolor\fR shell variable and the \fBLS_COLORS\fR environment variable. .RE .PP .B migrate \fR[\fB\-\fIsite\fR] \fIpid\fR|\fB%\fIjobid\fR ... (+) .PD 0 .TP 8 .B migrate \-\fIsite\fR (+) The first form migrates the process or job to the site specified or the default site determined by the system path. The second form is equivalent to `migrate \-\fIsite\fR $$': it migrates the current process to the specified site. Migrating the shell itself can cause unexpected behavior, because the shell does not like to lose its tty. (TCF only) .PD .TP 8 .B newgrp \fR[\fB\-\fR] \fI[group]\fR (+) Equivalent to `exec newgrp'; see \fInewgrp\fR(1). Available only if the shell was so compiled; see the \fBversion\fR shell variable. .TP 8 .B nice \fR[\fB+\fInumber\fR] [\fIcommand\fR] Sets the scheduling priority for the shell to \fInumber\fR, or, without \fInumber\fR, to 4. With \fIcommand\fR, runs \fIcommand\fR at the appropriate priority. The greater the \fInumber\fR, the less cpu the process gets. The super-user may specify negative priority by using `nice \-number ...'. Command is always executed in a sub-shell, and the restrictions placed on commands in simple \fIif\fR statements apply. .TP 8 .B nohup \fR[\fIcommand\fR] With \fIcommand\fR, runs \fIcommand\fR such that it will ignore hangup signals. Note that commands may set their own response to hangups, overriding \fInohup\fR. Without an argument, causes the non-interactive shell only to ignore hangups for the remainder of the script. See also \fBSignal handling\fR and the \fIhup\fR builtin command. .TP 8 .B notify \fR[\fB%\fIjob\fR ...] Causes the shell to notify the user asynchronously when the status of any of the specified jobs (or, without %\fIjob\fR, the current job) changes, instead of waiting until the next prompt as is usual. \fIjob\fR may be a number, a string, `', `%', `+' or `\-' as described under \fBJobs\fR. See also the \fBnotify\fR shell variable. .TP 8 .B onintr \fR[\fB\-\fR|\fIlabel\fR] Controls the action of the shell on interrupts. Without arguments, restores the default action of the shell on interrupts, which is to terminate shell scripts or to return to the terminal command input level. With `\-', causes all interrupts to be ignored. With \fIlabel\fR, causes the shell to execute a `goto \fIlabel\fR' when an interrupt is received or a child process terminates because it was interrupted. .IP "" 8 \fIonintr\fR is ignored if the shell is running detached and in system startup files (see \fBFILES\fR), where interrupts are disabled anyway. .TP 8 .B popd \fR[\fB\-p\fR] [\fB\-l\fR] [\fB\-n\fR|\fB\-v\fR] \fR[\fB+\fIn\fR] Without arguments, pops the directory stack and returns to the new top directory. With a number `+\fIn\fR', discards the \fIn\fR'th entry in the stack. .IP "" 8 Finally, all forms of \fIpopd\fR print the final directory stack, just like \fIdirs\fR. The \fBpushdsilent\fR shell variable can be set to prevent this and the \fB\-p\fR flag can be given to override \fBpushdsilent\fR. The \fB\-l\fR, \fB\-n\fR and \fB\-v\fR flags have the same effect on \fIpopd\fR as on \fIdirs\fR. (+) .TP 8 .B printenv \fR[\fIname\fR] (+) Prints the names and values of all environment variables or, with \fIname\fR, the value of the environment variable \fIname\fR. .TP 8 .B pushd \fR[\fB\-p\fR] [\fB\-l\fR] [\fB\-n\fR|\fB\-v\fR] [\fIname\fR|\fB+\fIn\fR] Without arguments, exchanges the top two elements of the directory stack. If \fBpushdtohome\fR is set, \fIpushd\fR without arguments does `pushd ~', like \fIcd\fR. (+) With \fIname\fR, pushes the current working directory onto the directory stack and changes to \fIname\fR. If \fIname\fR is `\-' it is interpreted as the previous working directory (see \fBFilename substitution\fR). (+) If \fBdunique\fR is set, \fIpushd\fR removes any instances of \fIname\fR from the stack before pushing it onto the stack. (+) With a number `+\fIn\fR', rotates the \fIn\fRth element of the directory stack around to be the top element and changes to it. If \fBdextract\fR is set, however, `pushd +\fIn\fR' extracts the \fIn\fRth directory, pushes it onto the top of the stack and changes to it. (+) .IP "" 8 Finally, all forms of \fIpushd\fR print the final directory stack, just like \fIdirs\fR. The \fBpushdsilent\fR shell variable can be set to prevent this and the \fB\-p\fR flag can be given to override \fBpushdsilent\fR. The \fB\-l\fR, \fB\-n\fR and \fB\-v\fR flags have the same effect on \fIpushd\fR as on \fIdirs\fR. (+) .TP 8 .B rehash Causes the internal hash table of the contents of the directories in the \fBpath\fR variable to be recomputed. This is needed if the \fBautorehash\fR shell variable is not set and new commands are added to directories in \fBpath\fR while you are logged in. With \fBautorehash\fR, a new command will be found automatically, except in the special case where another command of the same name which is located in a different directory already exists in the hash table. Also flushes the cache of home directories built by tilde expansion. .TP 8 .B repeat \fIcount command The specified \fIcommand\fR, which is subject to the same restrictions as the \fIcommand\fR in the one line \fIif\fR statement above, is executed \fIcount\fR times. I/O redirections occur exactly once, even if \fIcount\fR is 0. .TP 8 .B rootnode //\fInodename \fR(+) Changes the rootnode to //\fInodename\fR, so that `/' will be interpreted as `//\fInodename\fR'. (Domain/OS only) .PP .B sched \fR(+) .br .B sched \fR[\fB+\fR]\fIhh:mm command\fR \fR(+) .PD 0 .TP 8 .B sched \-\fIn\fR (+) The first form prints the scheduled-event list. The \fBsched\fR shell variable may be set to define the format in which the scheduled-event list is printed. The second form adds \fIcommand\fR to the scheduled-event list. For example, .PD .RS +8 .IP "" 4 > sched 11:00 echo It\e's eleven o\e'clock. .PP causes the shell to echo `It's eleven o'clock.' at 11 AM. The time may be in 12-hour AM/PM format .IP "" 4 .\" TODO > sched 5pm set prompt='[%h] It\e's after 5; go home: >' .PP or may be relative to the current time: .IP "" 4 > sched +2:15 /usr/lib/uucp/uucico \-r1 \-sother .PP A relative time specification may not use AM/PM format. The third form removes item \fIn\fR from the event list: .IP "" 4 > sched .br 1 Wed Apr 4 15:42 /usr/lib/uucp/uucico \-r1 \-sother .br 2 Wed Apr 4 17:00 set prompt=[%h] It's after 5; go home: > .br > sched \-2 .br > sched .br 1 Wed Apr 4 15:42 /usr/lib/uucp/uucico \-r1 \-sother .PP A command in the scheduled-event list is executed just before the first prompt is printed after the time when the command is scheduled. It is possible to miss the exact time when the command is to be run, but an overdue command will execute at the next prompt. A command which comes due while the shell is waiting for user input is executed immediately. However, normal operation of an already-running command will not be interrupted so that a scheduled-event list element may be run. .PP This mechanism is similar to, but not the same as, the \fIat\fR(1) command on some Unix systems. Its major disadvantage is that it may not run a command at exactly the specified time. Its major advantage is that because \fIsched\fR runs directly from the shell, it has access to shell variables and other structures. This provides a mechanism for changing one's working environment based on the time of day. .RE .PP .B set .br .B set \fIname\fR ... .br .B set \fIname\fR\fB=\fIword\fR ... .br .B set [\-r] [\-f|\-l] \fIname\fR\fB=(\fIwordlist\fB)\fR ... (+) .br .B set \fIname[index]\fR\fB=\fIword\fR ... .br .B set \-r \fR(+) .br .B set \-r \fIname\fR ... (+) .PD 0 .TP 8 .B set \-r \fIname\fR\fB=\fIword\fR ... (+) The first form of the command prints the value of all shell variables. Variables which contain more than a single word print as a parenthesized word list. The second form sets \fIname\fR to the null string. The third form sets \fIname\fR to the single \fIword\fR. The fourth form sets \fIname\fR to the list of words in \fIwordlist\fR. In all cases the value is command and filename expanded. If \fB\-r\fR is specified, the value is set read-only. If \fB\-f\fR or \fB\-l\fR are specified, set only unique words keeping their order. \fB\-f\fR prefers the first occurrence of a word, and \fB\-l\fR the last. The fifth form sets the \fIindex\fR'th component of \fIname\fR to \fIword\fR; this component must already exist. The sixth form lists only the names of all shell variables that are read-only. The seventh form makes \fIname\fR read-only, whether or not it has a value. The eighth form is the same as the third form, but make \fIname\fR read-only at the same time. .PD .IP "" 8 These arguments can be repeated to set and/or make read-only multiple variables in a single set command. Note, however, that variable expansion happens for all arguments before any setting occurs. Note also that `=' can be adjacent to both \fIname\fR and \fIword\fR or separated from both by whitespace, but cannot be adjacent to only one or the other. See also the \fIunset\fR builtin command. .TP 8 .B setenv \fR[\fIname \fR[\fIvalue\fR]] Without arguments, prints the names and values of all environment variables. Given \fIname\fR, sets the environment variable \fIname\fR to \fIvalue\fR or, without \fIvalue\fR, to the null string. .TP 8 .B setpath \fIpath \fR(+) Equivalent to \fIsetpath\fR(1). (Mach only) .TP 8 .B setspath\fR LOCAL|\fIsite\fR|\fIcpu\fR ... (+) Sets the system execution path. (TCF only) .TP 8 .B settc \fIcap value \fR(+) Tells the shell to believe that the terminal capability \fIcap\fR (as defined in \fItermcap\fR(5)) has the value \fIvalue\fR. No sanity checking is done. Concept terminal users may have to `settc xn no' to get proper wrapping at the rightmost column. .TP 8 .B setty \fR[\fB\-d\fR|\fB\-q\fR|\fB\-x\fR] [\fB\-a\fR] [[\fB+\fR|\fB\-\fR]\fImode\fR] (+) Controls which tty modes (see \fBTerminal management\fR) the shell does not allow to change. \fB\-d\fR, \fB\-q\fR or \fB\-x\fR tells \fIsetty\fR to act on the `edit', `quote' or `execute' set of tty modes respectively; without \fB\-d\fR, \fB\-q\fR or \fB\-x\fR, `execute' is used. .IP "" 8 Without other arguments, \fIsetty\fR lists the modes in the chosen set which are fixed on (`+mode') or off (`\-mode'). The available modes, and thus the display, vary from system to system. With \fB\-a\fR, lists all tty modes in the chosen set whether or not they are fixed. With \fB+\fImode\fR, \fB\-\fImode\fR or \fImode\fR, fixes \fImode\fR on or off or removes control from \fImode\fR in the chosen set. For example, `setty +echok echoe' fixes `echok' mode on and allows commands to turn `echoe' mode on or off, both when the shell is executing commands. .TP 8 .B setxvers\fR [\fIstring\fR] (+) Set the experimental version prefix to \fIstring\fR, or removes it if \fIstring\fR is omitted. (TCF only) .TP 8 .B shift \fR[\fIvariable\fR] Without arguments, discards \fBargv\fR[1] and shifts the members of \fBargv\fR to the left. It is an error for \fBargv\fR not to be set or to have less than one word as value. With \fIvariable\fR, performs the same function on \fIvariable\fR. .TP 8 .B source \fR[\fB\-h\fR] \fIname\fR [\fIargs\fR ...] The shell reads and executes commands from \fIname\fR. The commands are not placed on the history list. If any \fIargs\fR are given, they are placed in \fBargv\fR. (+) \fIsource\fR commands may be nested; if they are nested too deeply the shell may run out of file descriptors. An error in a \fIsource\fR at any level terminates all nested \fIsource\fR commands. With \fB\-h\fR, commands are placed on the history list instead of being executed, much like `history \-L'. .TP 8 .B stop \fB%\fIjob\fR|\fIpid\fR ... Stops the specified jobs or processes which are executing in the background. \fIjob\fR may be a number, a string, `', `%', `+' or `\-' as described under \fBJobs\fR. There is no default \fIjob\fR; saying just `stop' does not stop the current job. .TP 8 .B suspend Causes the shell to stop in its tracks, much as if it had been sent a stop signal with \fB^Z\fR. This is most often used to stop shells started by \fIsu\fR(1). .PP .B switch (\fIstring\fB) .br .B case \fIstr1\fB: .PD 0 .IP "" 4 \&... .br .B breaksw .PP \&... .PP .B default: .IP "" 4 \&... .br .B breaksw .TP 8 .B endsw Each case label is successively matched, against the specified \fIstring\fR which is first command and filename expanded. The file metacharacters `*', `?' and `[...]' may be used in the case labels, which are variable expanded. If none of the labels match before a `default' label is found, then the execution begins after the default label. Each case label and the default label must appear at the beginning of a line. The command \fIbreaksw\fR causes execution to continue after the \fIendsw\fR. Otherwise control may fall through case labels and default labels as in C. If no label matches and there is no default, execution continues after the \fIendsw\fR. .PD .TP 8 .B telltc \fR(+) Lists the values of all terminal capabilities (see \fItermcap\fR(5)). .TP 8 .B termname \fR[\fIterminal type\fR] \fR(+) Tests if \fIterminal type\fR (or the current value of \fBTERM\fR if no \fIterminal type\fR is given) has an entry in the hosts termcap(5) or terminfo(5) database. Prints the terminal type to stdout and returns 0 if an entry is present otherwise returns 1. .TP 8 .B time \fR[\fIcommand\fR] Executes \fIcommand\fR (which must be a simple command, not an alias, a pipeline, a command list or a parenthesized command list) and prints a time summary as described under the \fBtime\fR variable. If necessary, an extra shell is created to print the time statistic when the command completes. Without \fIcommand\fR, prints a time summary for the current shell and its children. .TP 8 .B umask \fR[\fIvalue\fR] Sets the file creation mask to \fIvalue\fR, which is given in octal. Common values for the mask are 002, giving all access to the group and read and execute access to others, and 022, giving read and execute access to the group and others. Without \fIvalue\fR, prints the current file creation mask. .TP 8 .B unalias \fIpattern\fR .br Removes all aliases whose names match \fIpattern\fR. `unalias *' thus removes all aliases. It is not an error for nothing to be \fIunalias\fRed. .TP 8 .B uncomplete \fIpattern\fR (+) Removes all completions whose names match \fIpattern\fR. `uncomplete *' thus removes all completions. It is not an error for nothing to be \fIuncomplete\fRd. .TP 8 .B unhash Disables use of the internal hash table to speed location of executed programs. .TP 8 .B universe \fIuniverse\fR (+) Sets the universe to \fIuniverse\fR. (Masscomp/RTU only) .TP 8 .B unlimit \fR[\fB\-hf\fR] [\fIresource\fR] Removes the limitation on \fIresource\fR or, if no \fIresource\fR is specified, all \fIresource\fR limitations. With \fB\-h\fR, the corresponding hard limits are removed. Only the super-user may do this. Note that \fBunlimit\fR may not exit successful, since most systems do not allow \fIdescriptors\fR to be unlimited. With \fB\-f\fR errors are ignored. .TP 8 .B unset \fIpattern Removes all variables whose names match \fIpattern\fR, unless they are read-only. `unset *' thus removes all variables unless they are read-only; this is a bad idea. It is not an error for nothing to be \fIunset\fR. .TP 8 .B unsetenv \fIpattern Removes all environment variables whose names match \fIpattern\fR. `unsetenv *' thus removes all environment variables; this is a bad idea. It is not an error for nothing to be \fIunsetenv\fRed. .TP 8 .B ver \fR[\fIsystype\fR [\fIcommand\fR]] (+) Without arguments, prints \fBSYSTYPE\fR. With \fIsystype\fR, sets \fBSYSTYPE\fR to \fIsystype\fR. With \fIsystype\fR and \fIcommand\fR, executes \fIcommand\fR under \fIsystype\fR. \fIsystype\fR may be `bsd4.3' or `sys5.3'. (Domain/OS only) .TP 8 .B wait The shell waits for all background jobs. If the shell is interactive, an interrupt will disrupt the wait and cause the shell to print the names and job numbers of all outstanding jobs. .TP 8 .B warp \fIuniverse\fR (+) Sets the universe to \fIuniverse\fR. (Convex/OS only) .TP 8 .B watchlog \fR(+) An alternate name for the \fIlog\fR builtin command (q.v.). Available only if the shell was so compiled; see the \fBversion\fR shell variable. .TP 8 .B where \fIcommand\fR (+) Reports all known instances of \fIcommand\fR, including aliases, builtins and executables in \fBpath\fR. .TP 8 .B which\fR \fIcommand\fR (+) Displays the command that will be executed by the shell after substitutions, \fBpath\fR searching, etc. The builtin command is just like \fIwhich\fR(1), but it correctly reports \fItcsh\fR aliases and builtins and is 10 to 100 times faster. See also the \fIwhich-command\fR editor command. .PP .B while (\fIexpr\fB)\fR .br \&... .PD 0 .TP 8 .B end Executes the commands between the \fIwhile\fR and the matching \fIend\fR while \fIexpr\fR (an expression, as described under \fBExpressions\fR) evaluates non-zero. \fIwhile\fR and \fIend\fR must appear alone on their input lines. \fIbreak\fR and \fIcontinue\fR may be used to terminate or continue the loop prematurely. If the input is a terminal, the user is prompted the first time through the loop as with \fIforeach\fR. .PD .SS "Special aliases (+)" If set, each of these aliases executes automatically at the indicated time. They are all initially undefined. .TP 8 .B beepcmd Runs when the shell wants to ring the terminal bell. .TP 8 .B cwdcmd Runs after every change of working directory. For example, if the user is working on an X window system using \fIxterm\fR(1) and a re-parenting window manager that supports title bars such as \fItwm\fR(1) and does .RS +8 .IP "" 4 > alias cwdcmd 'echo \-n "^[]2;${HOST}:$cwd ^G"' .PP then the shell will change the title of the running \fIxterm\fR(1) to be the name of the host, a colon, and the full current working directory. A fancier way to do that is .IP "" 4 > alias cwdcmd 'echo \-n "^[]2;${HOST}:$cwd^G^[]1;${HOST}^G"' .PP This will put the hostname and working directory on the title bar but only the hostname in the icon manager menu. .PP Note that putting a \fIcd\fR, \fIpushd\fR or \fIpopd\fR in \fIcwdcmd\fR may cause an infinite loop. It is the author's opinion that anyone doing so will get what they deserve. .RE .TP 8 .B jobcmd Runs before each command gets executed, or when the command changes state. This is similar to \fIpostcmd\fR, but it does not print builtins. .RS +8 .IP "" 4 > alias jobcmd 'echo \-n "^[]2\e;\e!#:q^G"' .PP then executing \fIvi foo.c\fR will put the command string in the xterm title bar. .RE .TP 8 .B helpcommand Invoked by the \fBrun-help\fR editor command. The command name for which help is sought is passed as sole argument. For example, if one does .RS +8 .IP "" 4 > alias helpcommand '\e!:1 --help' .PP then the help display of the command itself will be invoked, using the GNU help calling convention. Currently there is no easy way to account for various calling conventions (e.g., the customary Unix `-h'), except by using a table of many commands. .RE .TP 8 .B periodic Runs every \fBtperiod\fR minutes. This provides a convenient means for checking on common but infrequent changes such as new mail. For example, if one does .RS +8 .IP "" 4 > set tperiod = 30 .br > alias periodic checknews .PP then the \fIchecknews\fR(1) program runs every 30 minutes. If \fIperiodic\fR is set but \fBtperiod\fR is unset or set to 0, \fIperiodic\fR behaves like \fIprecmd\fR. .RE .TP 8 .B precmd Runs just before each prompt is printed. For example, if one does .RS +8 .IP "" 4 > alias precmd date .PP then \fIdate\fR(1) runs just before the shell prompts for each command. There are no limits on what \fIprecmd\fR can be set to do, but discretion should be used. .RE .TP 8 .B postcmd Runs before each command gets executed. .RS +8 .IP "" 4 > alias postcmd 'echo \-n "^[]2\e;\e!#:q^G"' .PP then executing \fIvi foo.c\fR will put the command string in the xterm title bar. .RE .TP 8 .B shell Specifies the interpreter for executable scripts which do not themselves specify an interpreter. The first word should be a full path name to the desired interpreter (e.g., `/bin/csh' or `/usr/local/bin/tcsh'). .SS "Special shell variables" The variables described in this section have special meaning to the shell. .PP The shell sets \fBaddsuffix\fR, \fBargv\fR, \fBautologout\fR, \fBcsubstnonl\fR, \fBcommand\fR, \fBecho_style\fR, \fBedit\fR, \fBgid\fR, \fBgroup\fR, \fBhome\fR, \fBloginsh\fR, \fBoid\fR, \fBpath\fR, \fBprompt\fR, \fBprompt2\fR, \fBprompt3\fR, \fBshell\fR, \fBshlvl\fR, \fBtcsh\fR, \fBterm\fR, \fBtty\fR, \fBuid\fR, \fBuser\fR and \fBversion\fR at startup; they do not change thereafter unless changed by the user. The shell updates \fBcwd\fR, \fBdirstack\fR, \fBowd\fR and \fBstatus\fR when necessary, and sets \fBlogout\fR on logout. .PP The shell synchronizes \fBgroup\fR, \fBhome\fR, \fBpath\fR, \fBshlvl\fR, \fBterm\fR and \fBuser\fR with the environment variables of the same names: whenever the environment variable changes the shell changes the corresponding shell variable to match (unless the shell variable is read-only) and vice versa. Note that although \fBcwd\fR and \fBPWD\fR have identical meanings, they are not synchronized in this manner, and that the shell automatically converts between the different formats of \fBpath\fR and \fBPATH\fR. .TP 8 .B addsuffix \fR(+) If set, filename completion adds `/' to the end of directories and a space to the end of normal files when they are matched exactly. Set by default. .TP 8 .B afsuser \fR(+) If set, \fBautologout\fR's autolock feature uses its value instead of the local username for kerberos authentication. .TP 8 .B ampm \fR(+) If set, all times are shown in 12-hour AM/PM format. .TP 8 .B anyerror \fR(+) This variable selects what is propagated to the value of the \fBstatus\fR variable. For more information see the description of the \fBstatus\fR variable below. .TP 8 .B argv The arguments to the shell. Positional parameters are taken from \fBargv\fR, i.e., `$1' is replaced by `$argv[1]', etc. Set by default, but usually empty in interactive shells. .TP 8 .B autocorrect \fR(+) If set, the \fIspell-word\fR editor command is invoked automatically before each completion attempt. .TP 8 .B autoexpand \fR(+) If set, the \fIexpand-history\fR editor command is invoked automatically before each completion attempt. If this is set to \fIonlyhistory\fR, then only history will be expanded and a second completion will expand filenames. .TP 8 .B autolist \fR(+) If set, possibilities are listed after an ambiguous completion. If set to `ambiguous', possibilities are listed only when no new characters are added by completion. .TP 8 .B autologout \fR(+) The first word is the number of minutes of inactivity before automatic logout. The optional second word is the number of minutes of inactivity before automatic locking. When the shell automatically logs out, it prints `auto-logout', sets the variable \fBlogout\fR to `automatic' and exits. When the shell automatically locks, the user is required to enter his password to continue working. Five incorrect attempts result in automatic logout. Set to `60' (automatic logout after 60 minutes, and no locking) by default in login and superuser shells, but not if the shell thinks it is running under a window system (i.e., the \fBDISPLAY\fR environment variable is set), the tty is a pseudo-tty (pty) or the shell was not so compiled (see the \fBversion\fR shell variable). Unset or set to `0' to disable automatic logout. See also the \fBafsuser\fR and \fBlogout\fR shell variables. .TP 8 .B autorehash \fR(+) If set, the internal hash table of the contents of the directories in the \fBpath\fR variable will be recomputed if a command is not found in the hash table. In addition, the list of available commands will be rebuilt for each command completion or spelling correction attempt if set to `complete' or `correct' respectively; if set to `always', this will be done for both cases. .TP 8 .B backslash_quote \fR(+) .\" TODO If set, backslashes (`\e') always quote `\e', `'', and `"'. This may make complex quoting tasks easier, but it can cause syntax errors in \fIcsh\fR(1) scripts. .TP 8 .B catalog The file name of the message catalog. If set, tcsh use `tcsh.${catalog}' as a message catalog instead of default `tcsh'. .TP 8 .B cdpath A list of directories in which \fIcd\fR should search for subdirectories if they aren't found in the current directory. .TP 8 .B cdtohome \fR(+) If not set, \fIcd\fR requires a directory \fIname\fR, and will not go to the \fBhome\fR directory if it's omitted. This is set by default. .TP 8 .B color If set, it enables color display for the builtin \fBls\-F\fR and it passes \fB\-\-color=auto\fR to \fBls\fR. Alternatively, it can be set to only \fBls\-F\fR or only \fBls\fR to enable color to only one command. Setting it to nothing is equivalent to setting it to \fB(ls\-F ls)\fR. .TP 8 .B colorcat If set, it enables color escape sequence for NLS message files. And display colorful NLS messages. .TP 8 .B command \fR(+) If set, the command which was passed to the shell with the \fB-c\fR flag (q.v.). .TP 8 .B compat_expr \fR(+) If set, the shell will evaluate expressions right to left, like the original \fIcsh\fR. .TP 8 .B complete \fR(+) If set to `igncase', the completion becomes case insensitive. If set to `enhance', completion ignores case and considers hyphens and underscores to be equivalent; it will also treat periods, hyphens and underscores (`.', `\-' and `_') as word separators. If set to `Enhance', completion matches uppercase and underscore characters explicitly and matches lowercase and hyphens in a case-insensitive manner; it will treat periods, hyphens and underscores as word separators. .TP 8 .B continue \fR(+) If set to a list of commands, the shell will continue the listed commands, instead of starting a new one. .TP 8 .B continue_args \fR(+) Same as continue, but the shell will execute: .RS +8 .IP "" 4 echo \`pwd\` $argv > ~/._pause; % .RE .TP 8 .B correct \fR(+) If set to `cmd', commands are automatically spelling-corrected. If set to `complete', commands are automatically completed. If set to `all', the entire command line is corrected. .TP 8 .B csubstnonl \fR(+) If set, newlines and carriage returns in command substitution are replaced by spaces. Set by default. .TP 8 .B cwd The full pathname of the current directory. See also the \fBdirstack\fR and \fBowd\fR shell variables. .TP 8 .B dextract \fR(+) If set, `pushd +\fIn\fR' extracts the \fIn\fRth directory from the directory stack rather than rotating it to the top. .TP 8 .B dirsfile \fR(+) The default location in which `dirs \-S' and `dirs \-L' look for a history file. If unset, \fI~/.cshdirs\fR is used. Because only \fI~/.tcshrc\fR is normally sourced before \fI~/.cshdirs\fR, \fBdirsfile\fR should be set in \fI~/.tcshrc\fR rather than \fI~/.login\fR. .TP 8 .B dirstack \fR(+) An array of all the directories on the directory stack. `$dirstack[1]' is the current working directory, `$dirstack[2]' the first directory on the stack, etc. Note that the current working directory is `$dirstack[1]' but `=0' in directory stack substitutions, etc. One can change the stack arbitrarily by setting \fBdirstack\fR, but the first element (the current working directory) is always correct. See also the \fBcwd\fR and \fBowd\fR shell variables. .TP 8 .B dspmbyte \fR(+) Has an effect iff 'dspm' is listed as part of the \fBversion\fR shell variable. If set to `euc', it enables display and editing EUC-kanji(Japanese) code. If set to `sjis', it enables display and editing Shift-JIS(Japanese) code. If set to `big5', it enables display and editing Big5(Chinese) code. If set to `utf8', it enables display and editing Utf8(Unicode) code. If set to the following format, it enables display and editing of original multi-byte code format: .RS +8 .IP "" 4 > set dspmbyte = 0000....(256 bytes)....0000 .PP The table requires \fBjust\fR 256 bytes. Each character of 256 characters corresponds (from left to right) to the ASCII codes 0x00, 0x01, ... 0xff. Each character .\" (position in this table?) is set to number 0,1,2 and 3. Each number has the following meaning: .br 0 ... not used for multi-byte characters. .br 1 ... used for the first byte of a multi-byte character. .br 2 ... used for the second byte of a multi-byte character. .br 3 ... used for both the first byte and second byte of a multi-byte character. .\" SHK: I tried my best to get the following to be grammatically correct. .\" However, I still don't understand what's going on here. In the .\" following example, there are three bytes, but the text seems to refer to .\" each nybble as a character. What's going on here? It this 3-byte code .\" in the table? The text above seems to imply that there are 256 .\" characters/bytes in the table. If I get some more info on this (perhaps .\" a complete example), I could fix the text to be grammatically correct. .\" (steve.kelem@xilinx.com 1999/09/13) .PP Example: .br If set to `001322', the first character (means 0x00 of the ASCII code) and second character (means 0x01 of ASCII code) are set to `0'. Then, it is not used for multi-byte characters. The 3rd character (0x02) is set to '1', indicating that it is used for the first byte of a multi-byte character. The 4th character(0x03) is set '3'. It is used for both the first byte and the second byte of a multi-byte character. The 5th and 6th characters (0x04,0x05) are set to '2', indicating that they are used for the second byte of a multi-byte character. .PP The GNU fileutils version of ls cannot display multi-byte filenames without the -N ( --literal ) option. If you are using this version, set the second word of dspmbyte to "ls". If not, for example, "ls-F -l" cannot display multi-byte filenames. .PP Note: .br This variable can only be used if KANJI and DSPMBYTE has been defined at compile time. .RE .TP 8 .B dunique \fR(+) If set, \fIpushd\fR removes any instances of \fIname\fR from the stack before pushing it onto the stack. .TP 8 .B echo If set, each command with its arguments is echoed just before it is executed. For non-builtin commands all expansions occur before echoing. Builtin commands are echoed before command and filename substitution, because these substitutions are then done selectively. Set by the \fB\-x\fR command line option. .TP 8 .B echo_style \fR(+) The style of the \fIecho\fR builtin. May be set to .PP .RS +8 .PD 0 .TP 8 bsd Don't echo a newline if the first argument is `\-n'; the default for \fIcsh\fR. .TP 8 sysv Recognize backslashed escape sequences in echo strings. .TP 8 both Recognize both the `\-n' flag and backslashed escape sequences; the default for \fItcsh\fR. .TP 8 none Recognize neither. .PD .PP Set by default to the local system default. The BSD and System V options are described in the \fIecho\fR(1) man pages on the appropriate systems. .RE .TP 8 .B edit \fR(+) If set, the command-line editor is used. Set by default in interactive shells. .TP 8 .B editors \fR(+) A list of command names for the \fIrun-fg-editor\fR editor command to match. If not set, the \fBEDITOR\fR (`ed' if unset) and \fBVISUAL\fR (`vi' if unset) environment variables will be used instead. .TP 8 .B ellipsis \fR(+) If set, the `%c'/`%.' and `%C' prompt sequences (see the \fBprompt\fR shell variable) indicate skipped directories with an ellipsis (`...') instead of `/'. .TP 8 .B euid \fR(+) The user's effective user ID. .TP 8 .B euser \fR(+) The first matching passwd entry name corresponding to the effective user ID. .TP 8 .B fignore \fR(+) Lists file name suffixes to be ignored by completion. .TP 8 .B filec In \fItcsh\fR, completion is always used and this variable is ignored by default. If .B edit is unset, then the traditional \fIcsh\fR completion is used. If set in \fIcsh\fR, filename completion is used. .TP 8 .B gid \fR(+) The user's real group ID. .TP 8 .B globdot \fR(+) If set, wild-card glob patterns will match files and directories beginning with `.' except for `.' and `..' .TP 8 .B globstar \fR(+) If set, the `**' and `***' file glob patterns will match any string of characters including `/' traversing any existing sub-directories. (e.g. `ls **.c' will list all the .c files in the current directory tree). If used by itself, it will match zero or more sub-directories (e.g. `ls /usr/include/**/time.h' will list any file named `time.h' in the /usr/include directory tree; whereas `ls /usr/include/**time.h' will match any file in the /usr/include directory tree ending in `time.h'). To prevent problems with recursion, the `**' glob-pattern will not descend into a symbolic link containing a directory. To override this, use `***' .TP 8 .B group \fR(+) The user's group name. .TP 8 .B highlight If set, the incremental search match (in \fIi-search-back\fR and \fIi-search-fwd\fR) and the region between the mark and the cursor are highlighted in reverse video. .IP "" 8 Highlighting requires more frequent terminal writes, which introduces extra overhead. If you care about terminal performance, you may want to leave this unset. .TP 8 .B histchars A string value determining the characters used in \fBHistory substitution\fR (q.v.). The first character of its value is used as the history substitution character, replacing the default character `!'. The second character of its value replaces the character `^' in quick substitutions. .TP 8 .B histdup \fR(+) Controls handling of duplicate entries in the history list. If set to `all' only unique history events are entered in the history list. If set to `prev' and the last history event is the same as the current command, then the current command is not entered in the history. If set to `erase' and the same event is found in the history list, that old event gets erased and the current one gets inserted. Note that the `prev' and `all' options renumber history events so there are no gaps. .TP 8 .B histfile \fR(+) The default location in which `history \-S' and `history \-L' look for a history file. If unset, \fI~/.history\fR is used. \fBhistfile\fR is useful when sharing the same home directory between different machines, or when saving separate histories on different terminals. Because only \fI~/.tcshrc\fR is normally sourced before \fI~/.history\fR, \fBhistfile\fR should be set in \fI~/.tcshrc\fR rather than \fI~/.login\fR. .TP 8 .B histlit \fR(+) If set, builtin and editor commands and the \fBsavehist\fR mechanism use the literal (unexpanded) form of lines in the history list. See also the \fItoggle-literal-history\fR editor command. .TP 8 .B history The first word indicates the number of history events to save. The optional second word (+) indicates the format in which history is printed; if not given, `%h\et%T\et%R\en' is used. The format sequences are described below under \fBprompt\fR; note the variable meaning of `%R'. Set to `100' by default. .TP 8 .B home Initialized to the home directory of the invoker. The filename expansion of `\fI~\fR' refers to this variable. .TP 8 .B ignoreeof If set to the empty string or `0' and the input device is a terminal, the \fIend-of-file\fR command (usually generated by the user by typing `^D' on an empty line) causes the shell to print `Use "exit" to leave tcsh.' instead of exiting. This prevents the shell from accidentally being killed. Historically this setting exited after 26 successive EOF's to avoid infinite loops. If set to a number \fIn\fR, the shell ignores \fIn - 1\fR consecutive \fIend-of-file\fRs and exits on the \fIn\fRth. (+) If unset, `1' is used, i.e., the shell exits on a single `^D'. .TP 8 .B implicitcd \fR(+) If set, the shell treats a directory name typed as a command as though it were a request to change to that directory. If set to \fIverbose\fR, the change of directory is echoed to the standard output. This behavior is inhibited in non-interactive shell scripts, or for command strings with more than one word. Changing directory takes precedence over executing a like-named command, but it is done after alias substitutions. Tilde and variable expansions work as expected. .TP 8 .B inputmode \fR(+) If set to `insert' or `overwrite', puts the editor into that input mode at the beginning of each line. .TP 8 .B killdup \fR(+) Controls handling of duplicate entries in the kill ring. If set to `all' only unique strings are entered in the kill ring. If set to `prev' and the last killed string is the same as the current killed string, then the current string is not entered in the ring. If set to `erase' and the same string is found in the kill ring, the old string is erased and the current one is inserted. .TP 8 .B killring \fR(+) Indicates the number of killed strings to keep in memory. Set to `30' by default. If unset or set to less than `2', the shell will only keep the most recently killed string. Strings are put in the killring by the editor commands that delete (kill) strings of text, e.g. \fIbackward-delete-word\fR, \fIkill-line\fR, etc, as well as the \fIcopy-region-as-kill\fR command. The \fIyank\fR editor command will yank the most recently killed string into the command-line, while \fIyank-pop\fR (see \fBEditor commands\fR) can be used to yank earlier killed strings. .TP 8 .B listflags \fR(+) If set to `x', `a' or `A', or any combination thereof (e.g., `xA'), they are used as flags to \fIls\-F\fR, making it act like `ls \-xF', `ls \-Fa', `ls \-FA' or a combination (e.g., `ls \-FxA'): `a' shows all files (even if they start with a `.'), `A' shows all files but `.' and `..', and `x' sorts across instead of down. If the second word of \fBlistflags\fR is set, it is used as the path to `ls(1)'. .TP 8 .B listjobs \fR(+) If set, all jobs are listed when a job is suspended. If set to `long', the listing is in long format. .TP 8 .B listlinks \fR(+) If set, the \fIls\-F\fR builtin command shows the type of file to which each symbolic link points. .TP 8 .B listmax \fR(+) The maximum number of items which the \fIlist-choices\fR editor command will list without asking first. .TP 8 .B listmaxrows \fR(+) The maximum number of rows of items which the \fIlist-choices\fR editor command will list without asking first. .TP 8 .B loginsh \fR(+) Set by the shell if it is a login shell. Setting or unsetting it within a shell has no effect. See also \fBshlvl\fR. .TP 8 .B logout \fR(+) Set by the shell to `normal' before a normal logout, `automatic' before an automatic logout, and `hangup' if the shell was killed by a hangup signal (see \fBSignal handling\fR). See also the \fBautologout\fR shell variable. .TP 8 .B mail A list of files and directories to check for incoming mail, optionally preceded by a numeric word. Before each prompt, if 10 minutes have passed since the last check, the shell checks each file and says `You have new mail.' (or, if \fBmail\fR contains multiple files, `You have new mail in \fIname\fR.') if the filesize is greater than zero in size and has a modification time greater than its access time. .PP .RS +8 .PD .PP If you are in a login shell, then no mail file is reported unless it has been modified after the time the shell has started up, to prevent redundant notifications. Most login programs will tell you whether or not you have mail when you log in. .PP If a file specified in \fBmail\fR is a directory, the shell will count each file within that directory as a separate message, and will report `You have \fIn\fR mails.' or `You have \fIn\fR mails in \fIname\fR.' as appropriate. This functionality is provided primarily for those systems which store mail in this manner, such as the Andrew Mail System. .PP If the first word of \fBmail\fR is numeric it is taken as a different mail checking interval, in seconds. .PP Under very rare circumstances, the shell may report `You have mail.' instead of `You have new mail.' .RE .TP 8 .B matchbeep \fR(+) If set to `never', completion never beeps. If set to `nomatch', it beeps only when there is no match. If set to `ambiguous', it beeps when there are multiple matches. If set to `notunique', it beeps when there is one exact and other longer matches. If unset, `ambiguous' is used. .TP 8 .B nobeep \fR(+) If set, beeping is completely disabled. See also \fBvisiblebell\fR. .TP 8 .B noclobber If set, restrictions are placed on output redirection to insure that files are not accidentally destroyed and that `>>' redirections refer to existing files, as described in the \fBInput/output\fR section. .TP 8 .B noding If set, disable the printing of `DING!' in the \fBprompt\fR time specifiers at the change of hour. .TP 8 .B noglob If set, \fBFilename substitution\fR and \fBDirectory stack substitution\fR (q.v.) are inhibited. This is most useful in shell scripts which do not deal with filenames, or after a list of filenames has been obtained and further expansions are not desirable. .TP 8 .B nokanji \fR(+) If set and the shell supports Kanji (see the \fBversion\fR shell variable), it is disabled so that the meta key can be used. .TP 8 .B nonomatch If set, a \fBFilename substitution\fR or \fBDirectory stack substitution\fR (q.v.) which does not match any existing files is left untouched rather than causing an error. It is still an error for the substitution to be malformed, e.g., `echo [' still gives an error. .TP 8 .B nostat \fR(+) A list of directories (or glob-patterns which match directories; see \fBFilename substitution\fR) that should not be \fIstat\fR(2)ed during a completion operation. This is usually used to exclude directories which take too much time to \fIstat\fR(2), for example \fI/afs\fR. .TP 8 .B notify If set, the shell announces job completions asynchronously. The default is to present job completions just before printing a prompt. .TP 8 .B oid \fR(+) The user's real organization ID. (Domain/OS only) .TP 8 .B owd \fR(+) The old working directory, equivalent to the `\-' used by \fIcd\fR and \fIpushd\fR. See also the \fBcwd\fR and \fBdirstack\fR shell variables. .TP 8 .B padhour If set, enable the printing of padding '0' for hours, in 24 and 12 hour formats. E.G.: 07:45:42 vs. 7:45:42. .TP 8 .B parseoctal To retain compatibily with older versions numeric variables starting with 0 are not interpreted as octal. Setting this variable enables proper octal parsing. .TP 8 .B path A list of directories in which to look for executable commands. A null word specifies the current directory. If there is no \fBpath\fR variable then only full path names will execute. \fBpath\fR is set by the shell at startup from the \fBPATH\fR environment variable or, if \fBPATH\fR does not exist, to a system-dependent default something like `(/usr/local/bin /usr/bsd /bin /usr/bin .)'. The shell may put `.' first or last in \fBpath\fR or omit it entirely depending on how it was compiled; see the \fBversion\fR shell variable. A shell which is given neither the \fB\-c\fR nor the \fB\-t\fR option hashes the contents of the directories in \fBpath\fR after reading \fI~/.tcshrc\fR and each time \fBpath\fR is reset. If one adds a new command to a directory in \fBpath\fR while the shell is active, one may need to do a \fIrehash\fR for the shell to find it. .TP 8 .B printexitvalue \fR(+) If set and an interactive program exits with a non-zero status, the shell prints `Exit \fBstatus\fR'. .TP 8 .B prompt The string which is printed before reading each command from the terminal. \fBprompt\fR may include any of the following formatting sequences (+), which are replaced by the given information: .PP .RS +8 .PD 0 .TP 4 %/ The current working directory. .TP 4 %~ The current working directory, but with one's home directory represented by `~' and other users' home directories represented by `~user' as per \fBFilename substitution\fR. `~user' substitution happens only if the shell has already used `~\fIuser\fR' in a pathname in the current session. .TP 4 %c[[0]\fIn\fR], %.[[0]\fIn\fR] The trailing component of the current working directory, or \fIn\fR trailing components if a digit \fIn\fR is given. If \fIn\fR begins with `0', the number of skipped components precede the trailing component(s) in the format `/<\fIskipped\fR>trailing'. If the \fBellipsis\fR shell variable is set, skipped components are represented by an ellipsis so the whole becomes `...trailing'. `~' substitution is done as in `%~' above, but the `~' component is ignored when counting trailing components. .TP 4 %C Like %c, but without `~' substitution. .TP 4 %h, %!, ! The current history event number. .TP 4 %M The full hostname. .TP 4 %m The hostname up to the first `.'. .TP 4 %S (%s) Start (stop) standout mode. .TP 4 %B (%b) Start (stop) boldfacing mode. .TP 4 %U (%u) Start (stop) underline mode. .TP 4 %t, %@ The time of day in 12-hour AM/PM format. .TP 4 %T Like `%t', but in 24-hour format (but see the \fBampm\fR shell variable). .TP 4 %p The `precise' time of day in 12-hour AM/PM format, with seconds. .TP 4 %P Like `%p', but in 24-hour format (but see the \fBampm\fR shell variable). .TP 4 \e\fIc\fR \fIc\fR is parsed as in \fIbindkey\fR. .TP 4 ^\fIc\fR \fIc\fR is parsed as in \fIbindkey\fR. .TP 4 %% A single `%'. .TP 4 %n The user name. .TP 4 %N The effective user name. .TP 4 %j The number of jobs. .TP 4 %d The weekday in `Day' format. .TP 4 %D The day in `dd' format. .TP 4 %w The month in `Mon' format. .TP 4 %W The month in `mm' format. .TP 4 %y The year in `yy' format. .TP 4 %Y The year in `yyyy' format. .TP 4 %l The shell's tty. .TP 4 %L Clears from the end of the prompt to end of the display or the end of the line. .TP 4 %$ Expands the shell or environment variable name immediately after the `$'. .TP 4 %# `>' (or the first character of the \fBpromptchars\fR shell variable) for normal users, `#' (or the second character of \fBpromptchars\fR) for the superuser. .TP 4 %{\fIstring\fR%} Includes \fIstring\fR as a literal escape sequence. It should be used only to change terminal attributes and should not move the cursor location. This cannot be the last sequence in \fBprompt\fR. .TP 4 %? The return code of the command executed just before the prompt. .TP 4 %R In \fBprompt2\fR, the status of the parser. In \fBprompt3\fR, the corrected string. In \fBhistory\fR, the history string. .PD .PP `%B', `%S', `%U' and `%{\fIstring\fR%}' are available in only eight-bit-clean shells; see the \fBversion\fR shell variable. .PP The bold, standout and underline sequences are often used to distinguish a superuser shell. For example, .IP "" 4 > set prompt = "%m [%h] %B[%@]%b [%/] you rang? " .br tut [37] \fB[2:54pm]\fR [/usr/accts/sys] you rang? _ .PP If `%t', `%@', `%T', `%p', or `%P' is used, and \fBnoding\fR is not set, then print `DING!' on the change of hour (i.e, `:00' minutes) instead of the actual time. .PP Set by default to `%# ' in interactive shells. .RE .TP 8 .B prompt2 \fR(+) The string with which to prompt in \fIwhile\fR and \fIforeach\fR loops and after lines ending in `\e'. The same format sequences may be used as in \fBprompt\fR (q.v.); note the variable meaning of `%R'. Set by default to `%R? ' in interactive shells. .TP 8 .B prompt3 \fR(+) The string with which to prompt when confirming automatic spelling correction. The same format sequences may be used as in \fBprompt\fR (q.v.); note the variable meaning of `%R'. Set by default to `CORRECT>%R (y|n|e|a)? ' in interactive shells. .TP 8 .B promptchars \fR(+) If set (to a two-character string), the `%#' formatting sequence in the \fBprompt\fR shell variable is replaced with the first character for normal users and the second character for the superuser. .TP 8 .B pushdtohome \fR(+) If set, \fIpushd\fR without arguments does `pushd ~', like \fIcd\fR. .TP 8 .B pushdsilent \fR(+) If set, \fIpushd\fR and \fIpopd\fR do not print the directory stack. .TP 8 .B recexact \fR(+) If set, completion completes on an exact match even if a longer match is possible. .TP 8 .B recognize_only_executables \fR(+) If set, command listing displays only files in the path that are executable. Slow. .TP 8 .B rmstar \fR(+) If set, the user is prompted before `rm *' is executed. .TP 8 .B rprompt \fR(+) The string to print on the right-hand side of the screen (after the command input) when the prompt is being displayed on the left. It recognizes the same formatting characters as \fBprompt\fR. It will automatically disappear and reappear as necessary, to ensure that command input isn't obscured, and will appear only if the prompt, command input, and itself will fit together on the first line. If \fBedit\fR isn't set, then \fBrprompt\fR will be printed after the prompt and before the command input. .TP 8 .B savedirs \fR(+) If set, the shell does `dirs \-S' before exiting. If the first word is set to a number, at most that many directory stack entries are saved. .TP 8 .B savehist If set, the shell does `history \-S' before exiting. If the first word is set to a number, at most that many lines are saved. (The number should be less than or equal to the number \fBhistory\fR entries; if it is set to greater than the number of \fBhistory\fR settings, only \fBhistory\fR entries will be saved) If the second word is set to `merge', the history list is merged with the existing history file instead of replacing it (if there is one) and sorted by time stamp and the most recent events are retained. If the second word of \fBsavehist\fR is `merge' and the third word is set to `lock', the history file update will be serialized with other shell sessions that would possibly like to merge history at exactly the same time. (+) .TP 8 .B sched \fR(+) The format in which the \fIsched\fR builtin command prints scheduled events; if not given, `%h\et%T\et%R\en' is used. The format sequences are described above under \fBprompt\fR; note the variable meaning of `%R'. .TP 8 .B shell The file in which the shell resides. This is used in forking shells to interpret files which have execute bits set, but which are not executable by the system. (See the description of \fBBuiltin and non-builtin command execution\fR.) Initialized to the (system-dependent) home of the shell. .TP 8 .B shlvl \fR(+) The number of nested shells. Reset to 1 in login shells. See also \fBloginsh\fR. .TP 8 .B status The exit status from the last command or backquote expansion, or any command in a pipeline is propagated to \fBstatus\fR. (This is also the default \fBcsh\fR behavior.) This default does not match what POSIX mandates (to return the status of the last command only). To match the POSIX behavior, you need to unset \fBanyerror\fR. .RS +8 .PP If the \fBanyerror\fR variable is unset, the exit status of a pipeline is determined only from the last command in the pipeline, and the exit status of a backquote expansion is \fInot\fR propagated to \fBstatus\fR. .PP If a command terminated abnormally, then 0200 is added to the status. Builtin commands which fail return exit status `1', all other builtin commands return status `0'. .RE .TP 8 .B symlinks \fR(+) Can be set to several different values to control symbolic link (`symlink') resolution: .RS +8 .PP If set to `chase', whenever the current directory changes to a directory containing a symbolic link, it is expanded to the real name of the directory to which the link points. This does not work for the user's home directory; this is a bug. .PP If set to `ignore', the shell tries to construct a current directory relative to the current directory before the link was crossed. This means that \fIcd\fRing through a symbolic link and then `cd ..'ing returns one to the original directory. This affects only builtin commands and filename completion. .PP If set to `expand', the shell tries to fix symbolic links by actually expanding arguments which look like path names. This affects any command, not just builtins. Unfortunately, this does not work for hard-to-recognize filenames, such as those embedded in command options. Expansion may be prevented by quoting. While this setting is usually the most convenient, it is sometimes misleading and sometimes confusing when it fails to recognize an argument which should be expanded. A compromise is to use `ignore' and use the editor command \fInormalize-path\fR (bound by default to ^X-n) when necessary. .PP Some examples are in order. First, let's set up some play directories: .IP "" 4 > cd /tmp .br > mkdir from from/src to .br > ln \-s from/src to/dst .PP Here's the behavior with \fBsymlinks\fR unset, .IP "" 4 > cd /tmp/to/dst; echo $cwd .br /tmp/to/dst .br > cd ..; echo $cwd .br /tmp/from .PP here's the behavior with \fBsymlinks\fR set to `chase', .IP "" 4 > cd /tmp/to/dst; echo $cwd .br /tmp/from/src .br > cd ..; echo $cwd .br /tmp/from .PP here's the behavior with \fBsymlinks\fR set to `ignore', .IP "" 4 > cd /tmp/to/dst; echo $cwd .br /tmp/to/dst .br > cd ..; echo $cwd .br /tmp/to .PP and here's the behavior with \fBsymlinks\fR set to `expand'. .IP "" 4 > cd /tmp/to/dst; echo $cwd .br /tmp/to/dst .br > cd ..; echo $cwd .br /tmp/to .br > cd /tmp/to/dst; echo $cwd .br /tmp/to/dst .br > cd ".."; echo $cwd .br /tmp/from .br > /bin/echo .. .br /tmp/to .br > /bin/echo ".." .br \&.. .PP Note that `expand' expansion 1) works just like `ignore' for builtins like \fIcd\fR, 2) is prevented by quoting, and 3) happens before filenames are passed to non-builtin commands. .RE .TP 8 .B tcsh \fR(+) The version number of the shell in the format `R.VV.PP', where `R' is the major release number, `VV' the current version and `PP' the patchlevel. .TP 8 .B term The terminal type. Usually set in \fI~/.login\fR as described under \fBStartup and shutdown\fR. .TP 8 .B time If set to a number, then the \fItime\fR builtin (q.v.) executes automatically after each command which takes more than that many CPU seconds. If there is a second word, it is used as a format string for the output of the \fItime\fR builtin. (u) The following sequences may be used in the format string: .PP .RS +8 .PD 0 .TP 4 %U The time the process spent in user mode in cpu seconds. .TP 4 %S The time the process spent in kernel mode in cpu seconds. .TP 4 %E The elapsed (wall clock) time in seconds. .TP 4 %P The CPU percentage computed as (%U + %S) / %E. .TP 4 %W Number of times the process was swapped. .TP 4 %X The average amount in (shared) text space used in Kbytes. .TP 4 %D The average amount in (unshared) data/stack space used in Kbytes. .TP 4 %K The total space used (%X + %D) in Kbytes. .TP 4 %M The maximum memory the process had in use at any time in Kbytes. .TP 4 %F The number of major page faults (page needed to be brought from disk). .TP 4 %R The number of minor page faults. .TP 4 %I The number of input operations. .TP 4 %O The number of output operations. .TP 4 %r The number of socket messages received. .TP 4 %s The number of socket messages sent. .TP 4 %k The number of signals received. .TP 4 %w The number of voluntary context switches (waits). .TP 4 %c The number of involuntary context switches. .PD .PP Only the first four sequences are supported on systems without BSD resource limit functions. The default time format is `%Uu %Ss %E %P %X+%Dk %I+%Oio %Fpf+%Ww' for systems that support resource usage reporting and `%Uu %Ss %E %P' for systems that do not. .PP Under Sequent's DYNIX/ptx, %X, %D, %K, %r and %s are not available, but the following additional sequences are: .PP .PD 0 .TP 4 %Y The number of system calls performed. .TP 4 %Z The number of pages which are zero-filled on demand. .TP 4 %i The number of times a process's resident set size was increased by the kernel. .TP 4 %d The number of times a process's resident set size was decreased by the kernel. .TP 4 %l The number of read system calls performed. .TP 4 %m The number of write system calls performed. .TP 4 %p The number of reads from raw disk devices. .TP 4 %q The number of writes to raw disk devices. .PD .PP and the default time format is `%Uu %Ss %E %P %I+%Oio %Fpf+%Ww'. Note that the CPU percentage can be higher than 100% on multi-processors. .RE .TP 8 .B tperiod \fR(+) The period, in minutes, between executions of the \fIperiodic\fR special alias. .TP 8 .B tty \fR(+) The name of the tty, or empty if not attached to one. .TP 8 .B uid \fR(+) The user's real user ID. .TP 8 .B user The user's login name. .TP 8 .B verbose If set, causes the words of each command to be printed, after history substitution (if any). Set by the \fB\-v\fR command line option. .TP 8 .B version \fR(+) The version ID stamp. It contains the shell's version number (see \fBtcsh\fR), origin, release date, vendor, operating system and machine (see \fBVENDOR\fR, \fBOSTYPE\fR and \fBMACHTYPE\fR) and a comma-separated list of options which were set at compile time. Options which are set by default in the distribution are noted. .PP .RS +8 .PD 0 .TP 6 8b The shell is eight bit clean; default .TP 6 7b The shell is not eight bit clean .TP 6 wide The shell is multibyte encoding clean (like UTF-8) .TP 6 nls The system's NLS is used; default for systems with NLS .TP 6 lf Login shells execute \fI/etc/csh.login\fR before instead of after \fI/etc/csh.cshrc\fR and \fI~/.login\fR before instead of after \fI~/.tcshrc\fR and \fI~/.history\fR. .TP 6 dl `.' is put last in \fBpath\fR for security; default .TP 6 nd `.' is omitted from \fBpath\fR for security .TP 6 vi \fIvi\fR(1)\-style editing is the default rather than \fIemacs\fR(1)\-style .TP 6 dtr Login shells drop DTR when exiting .TP 6 bye \fIbye\fR is a synonym for \fIlogout\fR and \fIlog\fR is an alternate name for \fIwatchlog\fR .TP 6 al \fBautologout\fR is enabled; default .TP 6 kan Kanji is used if appropriate according to locale settings, unless the \fBnokanji\fR shell variable is set .TP 6 sm The system's \fImalloc\fR(3) is used .TP 6 hb The `#! ' convention is emulated when executing shell scripts .TP 6 ng The \fInewgrp\fR builtin is available .TP 6 rh The shell attempts to set the \fBREMOTEHOST\fR environment variable .TP 6 afs The shell verifies your password with the kerberos server if local authentication fails. The \fBafsuser\fR shell variable or the \fBAFSUSER\fR environment variable override your local username if set. .PD .PP An administrator may enter additional strings to indicate differences in the local version. .RE .TP 8 .B vimode \fR(+) .RS +8 If unset, various key bindings change behavior to be more \fBemacs\fR(1)\-style: word boundaries are determined by \fBwordchars\fR versus other characters. .PP If set, various key bindings change behavior to be more \fBvi\fR(1)\-style: word boundaries are determined by \fBwordchars\fR versus whitespace versus other characters; cursor behavior depends upon current vi mode (command, delete, insert, replace). .PP This variable is unset by \fIbindkey\fR \fB-e\fR and set by \fIbindkey\fR \fB-v\fR. .B vimode may be explicitly set or unset by the user after those \fIbindkey\fR operations if required. .RE .TP 8 .B visiblebell \fR(+) If set, a screen flash is used rather than the audible bell. See also \fBnobeep\fR. .TP 8 .B watch \fR(+) A list of user/terminal pairs to watch for logins and logouts. If either the user is `any' all terminals are watched for the given user and vice versa. Setting \fBwatch\fR to `(any any)' watches all users and terminals. For example, .RS +8 .IP "" 4 set watch = (george ttyd1 any console $user any) .PP reports activity of the user `george' on ttyd1, any user on the console, and oneself (or a trespasser) on any terminal. .PP Logins and logouts are checked every 10 minutes by default, but the first word of \fBwatch\fR can be set to a number to check every so many minutes. For example, .IP "" 4 set watch = (1 any any) .PP reports any login/logout once every minute. For the impatient, the \fIlog\fR builtin command triggers a \fBwatch\fR report at any time. All current logins are reported (as with the \fIlog\fR builtin) when \fBwatch\fR is first set. .PP The \fBwho\fR shell variable controls the format of \fBwatch\fR reports. .RE .TP 8 .B who \fR(+) The format string for \fBwatch\fR messages. The following sequences are replaced by the given information: .PP .RS +8 .PD 0 .TP 4 %n The name of the user who logged in/out. .TP 4 %a The observed action, i.e., `logged on', `logged off' or `replaced \fIolduser\fR on'. .TP 4 %l The terminal (tty) on which the user logged in/out. .TP 4 %M The full hostname of the remote host, or `local' if the login/logout was from the local host. .TP 4 %m The hostname of the remote host up to the first `.'. The full name is printed if it is an IP address or an X Window System display. .PD .PP %M and %m are available on only systems that store the remote hostname in \fI/etc/utmp\fR. If unset, `%n has %a %l from %m.' is used, or `%n has %a %l.' on systems which don't store the remote hostname. .RE .TP 8 .B wordchars \fR(+) A list of non-alphanumeric characters to be considered part of a word by the \fIforward-word\fR, \fIbackward-word\fR etc., editor commands. If unset, the default value is determined based on the state of \fBvimode\fR: if \fBvimode\fR is unset, `*?_\-.[]~=' is used as the default; if \fBvimode\fR is set, `_' is used as the default. .SH ENVIRONMENT .TP 8 .B AFSUSER \fR(+) Equivalent to the \fBafsuser\fR shell variable. .TP 8 .B COLUMNS The number of columns in the terminal. See \fBTerminal management\fR. .TP 8 .B DISPLAY Used by X Window System (see \fIX\fR(1)). If set, the shell does not set \fBautologout\fR (q.v.). .TP 8 .B EDITOR The pathname to a default editor. Used by the \fIrun-fg-editor\fR editor command if the the \fBeditors\fR shell variable is unset. See also the \fBVISUAL\fR environment variable. .TP 8 .B GROUP \fR(+) Equivalent to the \fBgroup\fR shell variable. .TP 8 .B HOME Equivalent to the \fBhome\fR shell variable. .TP 8 .B HOST \fR(+) Initialized to the name of the machine on which the shell is running, as determined by the \fIgethostname\fR(2) system call. .TP 8 .B HOSTTYPE \fR(+) Initialized to the type of machine on which the shell is running, as determined at compile time. This variable is obsolete and will be removed in a future version. .TP 8 .B HPATH \fR(+) A colon-separated list of directories in which the \fIrun-help\fR editor command looks for command documentation. .TP 8 .B LANG Gives the preferred character environment. See \fBNative Language System support\fR. .TP 8 .B LC_CTYPE If set, only ctype character handling is changed. See \fBNative Language System support\fR. .TP 8 .B LINES The number of lines in the terminal. See \fBTerminal management\fR. .TP 8 .B LS_COLORS The format of this variable is reminiscent of the \fBtermcap(5)\fR file format; a colon-separated list of expressions of the form "\fIxx=string\fR", where "\fIxx\fR" is a two-character variable name. The variables with their associated defaults are: .PP .RS +8 .RS +4 .PD 0 .TP 12 no 0 Normal (non-filename) text .TP 12 fi 0 Regular file .TP 12 di 01;34 Directory .TP 12 ln 01;36 Symbolic link .TP 12 pi 33 Named pipe (FIFO) .TP 12 so 01;35 Socket .TP 12 do 01;35 Door .TP 12 bd 01;33 Block device .TP 12 cd 01;32 Character device .TP 12 ex 01;32 Executable file .TP 12 mi (none) Missing file (defaults to fi) .TP 12 or (none) Orphaned symbolic link (defaults to ln) .TP 12 lc ^[[ Left code .TP 12 rc m Right code .TP 12 ec (none) End code (replaces lc+no+rc) .PD .RE .PP You need to include only the variables you want to change from the default. .PP File names can also be colorized based on filename extension. This is specified in the \fBLS_COLORS\fR variable using the syntax \fB"*ext=string"\fR. For example, using ISO 6429 codes, to color all C\-language source files blue you would specify \fB"*.c=34"\fR. This would color all files ending in \fB.c\fR in blue (34) color. .PP Control characters can be written either in C\-style\-escaped notation, or in stty\-like ^\-notation. The C\-style notation adds \fB^[\fR for Escape, \fB\_\fR for a normal space character, and \fB?\fR for Delete. In addition, the \fB^[\fR escape character can be used to override the default interpretation of \fB^[\fR, \fB^\fR, \fB:\fR and \fB=\fR. .PP Each file will be written as \fB\fR \fB\fR \fB\fR \fB\fR \fB\fR. If the \fB\fR code is undefined, the sequence \fB\fR \fB \fB\fR will be used instead. This is generally more convenient to use, but less general. The left, right and end codes are provided so you don't have to type common parts over and over again and to support weird terminals; you will generally not need to change them at all unless your terminal does not use ISO 6429 color sequences but a different system. .PP If your terminal does use ISO 6429 color codes, you can compose the type codes (i.e., all except the \fBlc\fR, \fBrc\fR, and \fBec\fR codes) from numerical commands separated by semicolons. The most common commands are: .PP .RS +8 .PD 0 .TP 4 0 to restore default color .TP 4 1 for brighter colors .TP 4 4 for underlined text .TP 4 5 for flashing text .TP 4 30 for black foreground .TP 4 31 for red foreground .TP 4 32 for green foreground .TP 4 33 for yellow (or brown) foreground .TP 4 34 for blue foreground .TP 4 35 for purple foreground .TP 4 36 for cyan foreground .TP 4 37 for white (or gray) foreground .TP 4 40 for black background .TP 4 41 for red background .TP 4 42 for green background .TP 4 43 for yellow (or brown) background .TP 4 44 for blue background .TP 4 45 for purple background .TP 4 46 for cyan background .TP 4 47 for white (or gray) background .PD .RE .PP Not all commands will work on all systems or display devices. .PP A few terminal programs do not recognize the default end code properly. If all text gets colorized after you do a directory listing, try changing the \fBno\fR and \fBfi\fR codes from 0 to the numerical codes for your standard fore- and background colors. .RE .TP 8 .B MACHTYPE \fR(+) The machine type (microprocessor class or machine model), as determined at compile time. .TP 8 .B NOREBIND \fR(+) If set, printable characters are not rebound to \fIself-insert-command\fR. See \fBNative Language System support\fR. .TP 8 .B OSTYPE \fR(+) The operating system, as determined at compile time. .TP 8 .B PATH A colon-separated list of directories in which to look for executables. Equivalent to the \fBpath\fR shell variable, but in a different format. .TP 8 .B PWD \fR(+) Equivalent to the \fBcwd\fR shell variable, but not synchronized to it; updated only after an actual directory change. .TP 8 .B REMOTEHOST \fR(+) The host from which the user has logged in remotely, if this is the case and the shell is able to determine it. Set only if the shell was so compiled; see the \fBversion\fR shell variable. .TP 8 .B SHLVL \fR(+) Equivalent to the \fBshlvl\fR shell variable. .TP 8 .B SYSTYPE \fR(+) The current system type. (Domain/OS only) .TP 8 .B TERM Equivalent to the \fBterm\fR shell variable. .TP 8 .B TERMCAP The terminal capability string. See \fBTerminal management\fR. .TP 8 .B USER Equivalent to the \fBuser\fR shell variable. .TP 8 .B VENDOR \fR(+) The vendor, as determined at compile time. .TP 8 .B VISUAL The pathname to a default full-screen editor. Used by the \fIrun-fg-editor\fR editor command if the the \fBeditors\fR shell variable is unset. See also the \fBEDITOR\fR environment variable. .SH FILES .PD 0 .TP 16 .I /etc/csh.cshrc Read first by every shell. ConvexOS, Stellix and Intel use \fI/etc/cshrc\fR and NeXTs use \fI/etc/cshrc.std\fR. A/UX, AMIX, Cray and IRIX have no equivalent in \fIcsh\fR(1), but read this file in \fItcsh\fR anyway. Solaris 2.x does not have it either, but \fItcsh\fR reads \fI/etc/.cshrc\fR. (+) .TP 16 .I /etc/csh.login Read by login shells after \fI/etc/csh.cshrc\fR. ConvexOS, Stellix and Intel use \fI/etc/login\fR, NeXTs use \fI/etc/login.std\fR, Solaris 2.x uses \fI/etc/.login\fR and A/UX, AMIX, Cray and IRIX use \fI/etc/cshrc\fR. .TP 16 .I ~/.tcshrc \fR(+) Read by every shell after \fI/etc/csh.cshrc\fR or its equivalent. .TP 16 .I ~/.cshrc Read by every shell, if \fI~/.tcshrc\fR doesn't exist, after \fI/etc/csh.cshrc\fR or its equivalent. This manual uses `\fI~/.tcshrc\fR' to mean `\fI~/.tcshrc\fR or, if \fI~/.tcshrc\fR is not found, \fI~/.cshrc\fR'. .TP 16 .I ~/.history Read by login shells after \fI~/.tcshrc\fR if \fBsavehist\fR is set, but see also \fBhistfile\fR. .TP 16 .I ~/.login Read by login shells after \fI~/.tcshrc\fR or \fI~/.history\fR. The shell may be compiled to read \fI~/.login\fR before instead of after \fI~/.tcshrc\fR and \fI~/.history\fR; see the \fBversion\fR shell variable. .TP 16 .I ~/.cshdirs \fR(+) Read by login shells after \fI~/.login\fR if \fBsavedirs\fR is set, but see also \fBdirsfile\fR. .TP 16 .I /etc/csh.logout Read by login shells at logout. ConvexOS, Stellix and Intel use \fI/etc/logout\fR and NeXTs use \fI/etc/logout.std\fR. A/UX, AMIX, Cray and IRIX have no equivalent in \fIcsh\fR(1), but read this file in \fItcsh\fR anyway. Solaris 2.x does not have it either, but \fItcsh\fR reads \fI/etc/.logout\fR. (+) .TP 16 .I ~/.logout Read by login shells at logout after \fI/etc/csh.logout\fR or its equivalent. .TP 16 .I /bin/sh Used to interpret shell scripts not starting with a `#'. .TP 16 .I /tmp/sh* Temporary file for `<<'. .TP 16 .I /etc/passwd Source of home directories for `~name' substitutions. .PD .PP The order in which startup files are read may differ if the shell was so compiled; see \fBStartup and shutdown\fR and the \fBversion\fR shell variable. .SH "NEW FEATURES (+)" This manual describes \fItcsh\fR as a single entity, but experienced \fIcsh\fR(1) users will want to pay special attention to \fItcsh\fR's new features. .PP A command-line editor, which supports \fIemacs\fR(1)\-style or \fIvi\fR(1)\-style key bindings. See \fBThe command-line editor\fR and \fBEditor commands\fR. .PP Programmable, interactive word completion and listing. See \fBCompletion and listing\fR and the \fIcomplete\fR and \fIuncomplete\fR builtin commands. .PP \fBSpelling correction\fR (q.v.) of filenames, commands and variables. .PP \fBEditor commands\fR (q.v.) which perform other useful functions in the middle of typed commands, including documentation lookup (\fIrun-help\fR), quick editor restarting (\fIrun-fg-editor\fR) and command resolution (\fIwhich-command\fR). .PP An enhanced history mechanism. Events in the history list are time-stamped. See also the \fIhistory\fR command and its associated shell variables, the previously undocumented `#' event specifier and new modifiers under \fBHistory substitution\fR, the \fI*-history\fR, \fIhistory-search-*\fR, \fIi-search-*\fR, \fIvi-search-*\fR and \fItoggle-literal-history\fR editor commands and the \fBhistlit\fR shell variable. .PP Enhanced directory parsing and directory stack handling. See the \fIcd\fR, \fIpushd\fR, \fIpopd\fR and \fIdirs\fR commands and their associated shell variables, the description of \fBDirectory stack substitution\fR, the \fBdirstack\fR, \fBowd\fR and \fBsymlinks\fR shell variables and the \fInormalize-command\fR and \fInormalize-path\fR editor commands. .PP Negation in glob-patterns. See \fBFilename substitution\fR. .PP New \fBFile inquiry operators\fR (q.v.) and a \fIfiletest\fR builtin which uses them. .PP A variety of \fBAutomatic, periodic and timed events\fR (q.v.) including scheduled events, special aliases, automatic logout and terminal locking, command timing and watching for logins and logouts. .PP Support for the Native Language System (see \fBNative Language System support\fR), OS variant features (see \fBOS variant support\fR and the \fBecho_style\fR shell variable) and system-dependent file locations (see \fBFILES\fR). .PP Extensive terminal-management capabilities. See \fBTerminal management\fR. .PP New builtin commands including \fIbuiltins\fR, \fIhup\fR, \fIls\-F\fR, \fInewgrp\fR, \fIprintenv\fR, \fIwhich\fR and \fIwhere\fR (q.v.). .PP New variables that make useful information easily available to the shell. See the \fBgid\fR, \fBloginsh\fR, \fBoid\fR, \fBshlvl\fR, \fBtcsh\fR, \fBtty\fR, \fBuid\fR and \fBversion\fR shell variables and the \fBHOST\fR, \fBREMOTEHOST\fR, \fBVENDOR\fR, \fBOSTYPE\fR and \fBMACHTYPE\fR environment variables. .PP A new syntax for including useful information in the prompt string (see \fBprompt\fR), and special prompts for loops and spelling correction (see \fBprompt2\fR and \fBprompt3\fR). .PP Read-only variables. See \fBVariable substitution\fR. .SH BUGS When a suspended command is restarted, the shell prints the directory it started in if this is different from the current directory. This can be misleading (i.e., wrong) as the job may have changed directories internally. .PP Shell builtin functions are not stoppable/restartable. Command sequences of the form `a ; b ; c' are also not handled gracefully when stopping is attempted. If you suspend `b', the shell will then immediately execute `c'. This is especially noticeable if this expansion results from an \fIalias\fR. It suffices to place the sequence of commands in ()'s to force it to a subshell, i.e., `( a ; b ; c )'. .PP Control over tty output after processes are started is primitive; perhaps this will inspire someone to work on a good virtual terminal interface. In a virtual terminal interface much more interesting things could be done with output control. .PP Alias substitution is most often used to clumsily simulate shell procedures; shell procedures should be provided rather than aliases. .PP Control structures should be parsed rather than being recognized as built-in commands. This would allow control commands to be placed anywhere, to be combined with `|', and to be used with `&' and `;' metasyntax. .PP \fIforeach\fR doesn't ignore here documents when looking for its \fIend\fR. .PP It should be possible to use the `:' modifiers on the output of command substitutions. .PP The screen update for lines longer than the screen width is very poor if the terminal cannot move the cursor up (i.e., terminal type `dumb'). .PP \fBHPATH\fR and \fBNOREBIND\fR don't need to be environment variables. .PP Glob-patterns which do not use `?', `*' or `[]' or which use `{}' or `~' are not negated correctly. .PP The single-command form of \fIif\fR does output redirection even if the expression is false and the command is not executed. .PP \fIls\-F\fR includes file identification characters when sorting filenames and does not handle control characters in filenames well. It cannot be interrupted. .PP Command substitution supports multiple commands and conditions, but not cycles or backward \fIgoto\fRs. .PP Report bugs at https://bugs.astron.com/, preferably with fixes. If you want to help maintain and test tcsh, add yourself to the mailing list in https://mailman.astron.com/. .SH THE T IN TCSH In 1964, DEC produced the PDP-6. The PDP-10 was a later re-implementation. It was re-christened the DECsystem-10 in 1970 or so when DEC brought out the second model, the KI10. .PP TENEX was created at Bolt, Beranek & Newman (a Cambridge, Massachusetts think tank) in 1972 as an experiment in demand-paged virtual memory operating systems. They built a new pager for the DEC PDP-10 and created the OS to go with it. It was extremely successful in academia. .PP In 1975, DEC brought out a new model of the PDP-10, the KL10; they intended to have only a version of TENEX, which they had licensed from BBN, for the new box. They called their version TOPS-20 (their capitalization is trademarked). A lot of TOPS-10 users (`The OPerating System for PDP-10') objected; thus DEC found themselves supporting two incompatible systems on the same hardware--but then there were 6 on the PDP-11! .PP TENEX, and TOPS-20 to version 3, had command completion via a user-code-level subroutine library called ULTCMD. With version 3, DEC moved all that capability and more into the monitor (`kernel' for you Unix types), accessed by the COMND% JSYS (`Jump to SYStem' instruction, the supervisor call mechanism [are my IBM roots also showing?]). .PP The creator of tcsh was impressed by this feature and several others of TENEX and TOPS-20, and created a version of csh which mimicked them. .SH LIMITATIONS The system limits argument lists to ARG_MAX characters. .PP The number of arguments to a command which involves filename expansion is limited to 1/6th the number of characters allowed in an argument list. .PP Command substitutions may substitute no more characters than are allowed in an argument list. .PP To detect looping, the shell restricts the number of \fIalias\fR substitutions on a single line to 20. .SH "SEE ALSO" csh(1), emacs(1), ls(1), newgrp(1), sh(1), setpath(1), stty(1), su(1), tset(1), vi(1), x(1), access(2), execve(2), fork(2), killpg(2), pipe(2), setrlimit(2), sigvec(2), stat(2), umask(2), vfork(2), wait(2), malloc(3), setlocale(3), tty(4), a.out(5), termcap(5), environ(7), termio(7), Introduction to the C Shell .SH VERSION -This manual documents tcsh 6.22.03 (Astron) 2020-11-18. +This manual documents tcsh 6.22.04 (Astron) 2021-04-26. .SH AUTHORS .PD 0 .TP 2 William Joy Original author of \fIcsh\fR(1) .TP 2 J.E. Kulp, IIASA, Laxenburg, Austria Job control and directory stack features .TP 2 Ken Greer, HP Labs, 1981 File name completion .TP 2 Mike Ellis, Fairchild, 1983 Command name recognition/completion .TP 2 Paul Placeway, Ohio State CIS Dept., 1983-1993 Command line editor, prompt routines, new glob syntax and numerous fixes and speedups .TP 2 Karl Kleinpaste, CCI 1983-4 Special aliases, directory stack extraction stuff, login/logout watch, scheduled events, and the idea of the new prompt format .TP 2 Rayan Zachariassen, University of Toronto, 1984 \fIls\-F\fR and \fIwhich\fR builtins and numerous bug fixes, modifications and speedups .TP 2 Chris Kingsley, Caltech Fast storage allocator routines .TP 2 Chris Grevstad, TRW, 1987 Incorporated 4.3BSD \fIcsh\fR into \fItcsh\fR .TP 2 Christos S. Zoulas, Cornell U. EE Dept., 1987-94 Ports to HPUX, SVR2 and SVR3, a SysV version of getwd.c, SHORT_STRINGS support and a new version of sh.glob.c .TP 2 James J Dempsey, BBN, and Paul Placeway, OSU, 1988 A/UX port .TP 2 Daniel Long, NNSC, 1988 \fBwordchars\fR .TP 2 Patrick Wolfe, Kuck and Associates, Inc., 1988 \fIvi\fR mode cleanup .TP 2 David C Lawrence, Rensselaer Polytechnic Institute, 1989 \fBautolist\fR and ambiguous completion listing .TP 2 Alec Wolman, DEC, 1989 Newlines in the prompt .TP 2 Matt Landau, BBN, 1989 \fI~/.tcshrc\fR .TP 2 Ray Moody, Purdue Physics, 1989 Magic space bar history expansion .TP 2 Mordechai ????, Intel, 1989 printprompt() fixes and additions .TP 2 Kazuhiro Honda, Dept. of Computer Science, Keio University, 1989 Automatic spelling correction and \fBprompt3\fR .TP 2 Per Hedeland, Ellemtel, Sweden, 1990- Various bugfixes, improvements and manual updates .TP 2 Hans J. Albertsson (Sun Sweden) \fBampm\fR, \fIsettc\fR and \fItelltc\fR .TP 2 Michael Bloom Interrupt handling fixes .TP 2 Michael Fine, Digital Equipment Corp Extended key support .TP 2 Eric Schnoebelen, Convex, 1990 Convex support, lots of \fIcsh\fR bug fixes, save and restore of directory stack .TP 2 Ron Flax, Apple, 1990 A/UX 2.0 (re)port .TP 2 Dan Oscarsson, LTH Sweden, 1990 NLS support and simulated NLS support for non NLS sites, fixes .TP 2 Johan Widen, SICS Sweden, 1990 \fBshlvl\fR, Mach support, \fIcorrect-line\fR, 8-bit printing .TP 2 Matt Day, Sanyo Icon, 1990 POSIX termio support, SysV limit fixes .TP 2 Jaap Vermeulen, Sequent, 1990-91 Vi mode fixes, expand-line, window change fixes, Symmetry port .TP 2 Martin Boyer, Institut de recherche d'Hydro-Quebec, 1991 \fBautolist\fR beeping options, modified the history search to search for the whole string from the beginning of the line to the cursor. .TP 2 Scott Krotz, Motorola, 1991 Minix port .TP 2 David Dawes, Sydney U. Australia, Physics Dept., 1991 SVR4 job control fixes .TP 2 Jose Sousa, Interactive Systems Corp., 1991 Extended \fIvi\fR fixes and \fIvi\fR delete command .TP 2 Marc Horowitz, MIT, 1991 ANSIfication fixes, new exec hashing code, imake fixes, \fIwhere\fR .TP 2 Bruce Sterling Woodcock, sterling@netcom.com, 1991-1995 ETA and Pyramid port, Makefile and lint fixes, \fBignoreeof\fR=n addition, and various other portability changes and bug fixes .TP 2 Jeff Fink, 1992 \fIcomplete-word-fwd\fR and \fIcomplete-word-back\fR .TP 2 Harry C. Pulley, 1992 Coherent port .TP 2 Andy Phillips, Mullard Space Science Lab U.K., 1992 VMS-POSIX port .TP 2 Beto Appleton, IBM Corp., 1992 Walking process group fixes, \fIcsh\fR bug fixes, POSIX file tests, POSIX SIGHUP .TP 2 Scott Bolte, Cray Computer Corp., 1992 CSOS port .TP 2 Kaveh R. Ghazi, Rutgers University, 1992 Tek, m88k, Titan and Masscomp ports and fixes. Added autoconf support. .TP 2 Mark Linderman, Cornell University, 1992 OS/2 port .TP 2 Mika Liljeberg, liljeber@kruuna.Helsinki.FI, 1992 Linux port .TP 2 Tim P. Starrin, NASA Langley Research Center Operations, 1993 Read-only variables .TP 2 Dave Schweisguth, Yale University, 1993-4 New man page and tcsh.man2html .TP 2 Larry Schwimmer, Stanford University, 1993 AFS and HESIOD patches .TP 2 Luke Mewburn, RMIT University, 1994-6 Enhanced directory printing in prompt, added \fBellipsis\fR and \fBrprompt\fR. .TP 2 Edward Hutchins, Silicon Graphics Inc., 1996 Added implicit cd. .TP 2 Martin Kraemer, 1997 Ported to Siemens Nixdorf EBCDIC machine .TP 2 Amol Deshpande, Microsoft, 1997 Ported to WIN32 (Windows/95 and Windows/NT); wrote all the missing library and message catalog code to interface to Windows. .TP 2 Taga Nayuta, 1998 Color ls additions. .PD .PP .SH "THANKS TO" Bryan Dunlap, Clayton Elwell, Karl Kleinpaste, Bob Manson, Steve Romig, Diana Smetters, Bob Sutterfield, Mark Verber, Elizabeth Zwicky and all the other people at Ohio State for suggestions and encouragement .PP All the people on the net, for putting up with, reporting bugs in, and suggesting new additions to each and every version .PP Richard M. Alderson III, for writing the `T in tcsh' section diff --git a/contrib/tcsh/tw.color.c b/contrib/tcsh/tw.color.c index f0e0d59e96c9..9f12c36f160c 100644 --- a/contrib/tcsh/tw.color.c +++ b/contrib/tcsh/tw.color.c @@ -1,488 +1,490 @@ /* * tw.color.c: builtin color ls-F */ /*- * Copyright (c) 1998 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "tw.h" #include "ed.h" #include "tc.h" #ifdef COLOR_LS_F typedef struct { const char *s; size_t len; } Str; #define VAR(suffix,variable,defaultcolor) \ { \ suffix, variable, { defaultcolor, sizeof(defaultcolor) - 1 }, \ { defaultcolor, sizeof(defaultcolor) - 1 } \ } #define NOS '\0' /* no suffix */ typedef struct { const char suffix; const char *variable; Str color; Str defaultcolor; } Variable; static Variable variables[] = { VAR('/', "di", "01;34"), /* Directory */ VAR('@', "ln", "01;36"), /* Symbolic link */ VAR('&', "or", ""), /* Orphanned symbolic link (defaults to ln) */ VAR('|', "pi", "33"), /* Named pipe (FIFO) */ VAR('=', "so", "01;35"), /* Socket */ VAR('>', "do", "01;35"), /* Door (solaris fast ipc mechanism) */ VAR('#', "bd", "01;33"), /* Block device */ VAR('%', "cd", "01;33"), /* Character device */ VAR('*', "ex", "01;32"), /* Executable file */ VAR(NOS, "fi", "0"), /* Regular file */ VAR(NOS, "no", "0"), /* Normal (non-filename) text */ VAR(NOS, "mi", ""), /* Missing file (defaults to fi) */ #ifdef IS_ASCII VAR(NOS, "lc", "\033["), /* Left code (ASCII) */ #else VAR(NOS, "lc", "\x27["), /* Left code (EBCDIC)*/ #endif VAR(NOS, "rc", "m"), /* Right code */ VAR(NOS, "ec", ""), /* End code (replaces lc+no+rc) */ VAR(NOS, "su", ""), /* Setuid file (u+s) */ VAR(NOS, "sg", ""), /* Setgid file (g+s) */ VAR(NOS, "tw", ""), /* Sticky and other writable dir (+t,o+w) */ VAR(NOS, "ow", ""), /* Other writable dir (o+w) but not sticky */ VAR(NOS, "st", ""), /* Sticky dir (+t) but not other writable */ VAR(NOS, "rs", "0"), /* Reset to normal color */ VAR(NOS, "hl", "44;37"), /* Reg file extra hard links, obsolete? */ VAR(NOS, "mh", "44;37"), /* Reg file extra hard links */ VAR(NOS, "ca", "30;41"), /* File with capability */ }; #define nvariables (sizeof(variables)/sizeof(variables[0])) enum FileType { VDir, VSym, VOrph, VPipe, VSock, VDoor, VBlock, VChr, VExe, VFile, VNormal, VMiss, VLeft, VRight, VEnd, VSuid, VSgid, VSticky, VOther, Vstird, VReset, Vhard, Vhard2, VCap }; /* * Map from LSCOLORS entry index to Variable array index */ static const uint8_t map[] = { VDir, /* Directory */ VSym, /* Symbolic Link */ VSock, /* Socket */ VPipe, /* Named Pipe */ VExe, /* Executable */ VBlock, /* Block Special */ VChr, /* Character Special */ VSuid, /* Setuid Executable */ VSgid, /* Setgid Executable */ VSticky, /* Directory writable to others and sticky */ VOther, /* Directory writable to others but not sticky */ }; enum ansi { ANSI_RESET_ON = 0, /* reset colors/styles (white on black) */ ANSI_BOLD_ON = 1, /* bold on */ ANSI_ITALICS_ON = 3, /* italics on */ ANSI_UNDERLINE_ON = 4, /* underline on */ ANSI_INVERSE_ON = 7, /* inverse on */ ANSI_STRIKETHROUGH_ON = 9, /* strikethrough on */ ANSI_BOLD_OFF = 21, /* bold off */ ANSI_ITALICS_OFF = 23, /* italics off */ ANSI_UNDERLINE_OFF = 24, /* underline off */ ANSI_INVERSE_OFF = 27, /* inverse off */ ANSI_STRIKETHROUGH_OFF = 29,/* strikethrough off */ ANSI_FG_BLACK = 30, /* fg black */ ANSI_FG_RED = 31, /* fg red */ ANSI_FG_GREEN = 32, /* fg green */ ANSI_FG_YELLOW = 33, /* fg yellow */ ANSI_FG_BLUE = 34, /* fg blue */ ANSI_FG_MAGENTA = 35, /* fg magenta */ ANSI_FG_CYAN = 36, /* fg cyan */ ANSI_FG_WHITE = 37, /* fg white */ ANSI_FG_DEFAULT = 39, /* fg default (white) */ ANSI_BG_BLACK = 40, /* bg black */ ANSI_BG_RED = 41, /* bg red */ ANSI_BG_GREEN = 42, /* bg green */ ANSI_BG_YELLOW = 43, /* bg yellow */ ANSI_BG_BLUE = 44, /* bg blue */ ANSI_BG_MAGENTA = 45, /* bg magenta */ ANSI_BG_CYAN = 46, /* bg cyan */ ANSI_BG_WHITE = 47, /* bg white */ ANSI_BG_DEFAULT = 49, /* bg default (black) */ }; #define TCSH_BOLD 0x80 - + typedef struct { Str extension; /* file extension */ Str color; /* color string */ } Extension; static Extension *extensions = NULL; static size_t nextensions = 0; static char *colors = NULL; int color_context_ls = FALSE; /* do colored ls */ static int color_context_lsmF = FALSE; /* do colored ls-F */ static int getstring (char **, const Char **, Str *, int); static void put_color (const Str *); static void print_color (const Char *, size_t, Char); /* set_color_context(): */ void set_color_context(void) { struct varent *vp = adrof(STRcolor); if (vp == NULL || vp->vec == NULL) { color_context_ls = FALSE; color_context_lsmF = FALSE; } else if (!vp->vec[0] || vp->vec[0][0] == '\0') { color_context_ls = TRUE; color_context_lsmF = TRUE; } else { size_t i; color_context_ls = FALSE; color_context_lsmF = FALSE; for (i = 0; vp->vec[i]; i++) if (Strcmp(vp->vec[i], STRls) == 0) color_context_ls = TRUE; else if (Strcmp(vp->vec[i], STRlsmF) == 0) color_context_lsmF = TRUE; } } /* getstring(): */ static int getstring(char **dp, const Char **sp, Str *pd, int f) { const Char *s = *sp; char *d = *dp; eChar sc; while (*s && (*s & CHAR) != (Char)f && (*s & CHAR) != ':') { if ((*s & CHAR) == '\\' || (*s & CHAR) == '^') { if ((sc = parseescape(&s)) == CHAR_ERR) return 0; } else sc = *s++ & CHAR; d += one_wctomb(d, sc); } pd->s = *dp; pd->len = d - *dp; *sp = s; *dp = d; return *s == (Char)f; } static void init(size_t colorlen, size_t extnum) { size_t i; xfree(extensions); for (i = 0; i < nvariables; i++) variables[i].color = variables[i].defaultcolor; if (colorlen == 0 && extnum == 0) { extensions = NULL; colors = NULL; } else { extensions = xmalloc(colorlen + extnum * sizeof(*extensions)); colors = extnum * sizeof(*extensions) + (char *)extensions; } nextensions = 0; } static int color(Char x) { static const char ccolors[] = "abcdefghx"; char *p; if (Isupper(x)) { x = Tolower(x); } if (x == '\0' || (p = strchr(ccolors, x)) == NULL) return -1; return 30 + (p - ccolors); } static void makecolor(char **c, int fg, int bg, Str *v) { int l; - if (fg & 0x80) + if (fg & 0x80) { l = xsnprintf(*c, 12, "%.2d;%.2d;%.2d;%.2d", ANSI_BOLD_ON, fg & ~TCSH_BOLD, (10 + bg) & ~TCSH_BOLD, ANSI_BOLD_OFF); + } else { l = xsnprintf(*c, 6, "%.2d;%.2d", fg & ~TCSH_BOLD, (10 + bg) & ~TCSH_BOLD); + } v->s = *c; v->len = l; *c += l + 1; } /* parseLSCOLORS(): * Parse the LSCOLORS environment variable */ static const Char *xv; /* setjmp clobbering */ void parseLSCOLORS(const Char *value) { size_t i, len, clen; jmp_buf_t osetexit; size_t omark; xv = value; if (xv == NULL) { init(0, 0); return; } len = Strlen(xv); len >>= 1; clen = len * 12; /* "??;??;??;??\0" */ init(clen, 0); /* Prevent from crashing if unknown parameters are given. */ omark = cleanup_push_mark(); getexit(osetexit); /* init pointers */ if (setexit() == 0) { const Char *v = xv; char *c = colors; int fg, bg; for (i = 0; i < len; i++) { fg = color(*v++); if (fg == -1) stderror(ERR_BADCOLORVAR, v[-1], '?'); bg = color(*v++); if (bg == -1) stderror(ERR_BADCOLORVAR, '?', v[-1]); makecolor(&c, fg, bg, &variables[map[i]].color); } } cleanup_pop_mark(omark); resexit(osetexit); } /* parseLS_COLORS(): * Parse the LS_COLORS environment variable */ void parseLS_COLORS(const Char *value) { size_t i, len; const Char *v; /* pointer in value */ char *c; /* pointer in colors */ Extension *volatile e; /* pointer in extensions */ jmp_buf_t osetexit; size_t omark; (void) &e; if (value == NULL) { init(0, 0); return; } len = Strlen(value); /* allocate memory */ i = 1; for (v = value; *v; v++) if ((*v & CHAR) == ':') i++; init(len, i); /* init pointers */ v = value; c = colors; e = extensions; /* Prevent from crashing if unknown parameters are given. */ omark = cleanup_push_mark(); getexit(osetexit); if (setexit() == 0) { /* parse */ while (*v) { switch (*v & CHAR) { case ':': v++; continue; case '*': /* :*ext=color: */ v++; if (getstring(&c, &v, &e->extension, '=') && 0 < e->extension.len) { v++; getstring(&c, &v, &e->color, ':'); e++; continue; } break; default: /* :vl=color: */ if (v[0] && v[1] && (v[2] & CHAR) == '=') { for (i = 0; i < nvariables; i++) if ((Char)variables[i].variable[0] == (v[0] & CHAR) && (Char)variables[i].variable[1] == (v[1] & CHAR)) break; if (i < nvariables) { v += 3; getstring(&c, &v, &variables[i].color, ':'); continue; } else stderror(ERR_BADCOLORVAR, v[0], v[1]); } break; } while (*v && (*v & CHAR) != ':') v++; } } cleanup_pop_mark(omark); resexit(osetexit); nextensions = e - extensions; } /* put_color(): */ static void put_color(const Str *colorp) { size_t i; const char *c = colorp->s; int original_output_raw = output_raw; output_raw = TRUE; cleanup_push(&original_output_raw, output_raw_restore); for (i = colorp->len; 0 < i; i--) xputchar(*c++); cleanup_until(&original_output_raw); } /* print_color(): */ static void print_color(const Char *fname, size_t len, Char suffix) { size_t i; char *filename = short2str(fname); char *last = filename + len; Str *colorp = &variables[VFile].color; switch (suffix) { case '>': /* File is a symbolic link pointing to * a directory */ colorp = &variables[VDir].color; break; case '+': /* File is a hidden directory [aix] or * context dependent [hpux] */ case ':': /* File is network special [hpux] */ break; default: for (i = 0; i < nvariables; i++) if (variables[i].suffix != NOS && (Char)variables[i].suffix == suffix) { colorp = &variables[i].color; break; } if (i == nvariables) { for (i = 0; i < nextensions; i++) if (len >= extensions[i].extension.len && strncmp(last - extensions[i].extension.len, extensions[i].extension.s, extensions[i].extension.len) == 0) { colorp = &extensions[i].color; break; } } break; } put_color(&variables[VLeft].color); put_color(colorp); put_color(&variables[VRight].color); } /* print_with_color(): */ void print_with_color(const Char *filename, size_t len, Char suffix) { if (color_context_lsmF && (haderr ? (didfds ? is2atty : isdiagatty) : (didfds ? is1atty : isoutatty))) { print_color(filename, len, suffix); xprintf("%S", filename); if (0 < variables[VEnd].color.len) put_color(&variables[VEnd].color); else { put_color(&variables[VLeft].color); put_color(&variables[VNormal].color); put_color(&variables[VRight].color); } } else xprintf("%S", filename); xputwchar(suffix); } #endif /* COLOR_LS_F */ diff --git a/contrib/tcsh/tw.comp.c b/contrib/tcsh/tw.comp.c index bea72e39e59f..108004c4faab 100644 --- a/contrib/tcsh/tw.comp.c +++ b/contrib/tcsh/tw.comp.c @@ -1,643 +1,643 @@ /* * tw.comp.c: File completion builtin */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "tw.h" #include "ed.h" #include "tc.h" /* #define TDEBUG */ struct varent completions; static int tw_result (const Char *, Char **); static Char **tw_find (Char *, struct varent *, int); static Char *tw_tok (Char *); static int tw_pos (Char *, int); static void tw_pr (Char **); static int tw_match (const Char *, const Char *, int); static void tw_prlist (struct varent *); static const Char *tw_dollar (const Char *,Char **, size_t, Char **, Char, const char *); /* docomplete(): * Add or list completions in the completion list */ /*ARGSUSED*/ void docomplete(Char **v, struct command *t) { struct varent *vp; Char *p; Char **pp; USE(t); v++; p = *v++; if (p == 0) tw_prlist(&completions); else if (*v == 0) { vp = adrof1(strip(p), &completions); if (vp && vp->vec) tw_pr(vp->vec), xputchar('\n'); else { #ifdef TDEBUG xprintf("tw_find(%s) \n", short2str(strip(p))); #endif /* TDEBUG */ pp = tw_find(strip(p), &completions, FALSE); if (pp) tw_pr(pp), xputchar('\n'); } } else set1(strip(p), saveblk(v), &completions, VAR_READWRITE); } /* end docomplete */ /* douncomplete(): * Remove completions from the completion list */ /*ARGSUSED*/ void douncomplete(Char **v, struct command *t) { USE(t); unset1(v, &completions); } /* end douncomplete */ /* tw_prlist(): * Pretty print a list of variables */ static void tw_prlist(struct varent *p) { struct varent *c; for (;;) { while (p->v_left) p = p->v_left; x: if (p->v_parent == 0) /* is it the header? */ break; if (setintr) { int old_pintr_disabled; pintr_push_enable(&old_pintr_disabled); cleanup_until(&old_pintr_disabled); } xprintf("%s\t", short2str(p->v_name)); if (p->vec) tw_pr(p->vec); xputchar('\n'); if (p->v_right) { p = p->v_right; continue; } do { c = p; p = p->v_parent; } while (p->v_right == c); goto x; } } /* end tw_prlist */ /* tw_pr(): - * Pretty print a completion, adding single quotes around + * Pretty print a completion, adding single quotes around * a completion argument and collapsing multiple spaces to one. */ static void tw_pr(Char **cmp) { int sp, osp; Char *ptr; for (; *cmp; cmp++) { xputchar('\''); for (osp = 0, ptr = *cmp; *ptr; ptr++) { sp = Isspace(*ptr); if (sp && osp) continue; xputwchar(*ptr); osp = sp; } xputchar('\''); if (cmp[1]) xputchar(' '); } } /* end tw_pr */ /* tw_find(): - * Find the first matching completion. + * Find the first matching completion. * For commands we only look at names that start with - */ static Char ** tw_find(Char *nam, struct varent *vp, int cmd) { Char **rv; for (vp = vp->v_left; vp; vp = vp->v_right) { if (vp->v_left && (rv = tw_find(nam, vp, cmd)) != NULL) return rv; if (cmd) { if (vp->v_name[0] != '-') continue; if (Gmatch(nam, &vp->v_name[1]) && vp->vec != NULL) return vp->vec; } else if (Gmatch(nam, vp->v_name) && vp->vec != NULL) return vp->vec; } return NULL; } /* end tw_find */ /* tw_pos(): * Return true if the position is within the specified range */ static int tw_pos(Char *ran, int wno) { Char *p; if (ran[0] == '*' && ran[1] == '\0') return 1; for (p = ran; *p && *p != '-'; p++) continue; if (*p == '\0') /* range == */ return wno == getn(ran); - + if (ran == p) /* range = - */ return wno <= getn(&ran[1]); *p++ = '\0'; if (*p == '\0') /* range = - */ return getn(ran) <= wno; else /* range = - */ return (getn(ran) <= wno) && (wno <= getn(p)); } /* end tw_pos */ /* tw_tok(): * Return the next word from string, unquoteing it. */ static Char * tw_tok(Char *str) { static Char *bf = NULL; if (str != NULL) bf = str; - + /* skip leading spaces */ for (; *bf && Isspace(*bf); bf++) continue; for (str = bf; *bf && !Isspace(*bf); bf++) { if (ismetahash(*bf)) return INVPTR; *bf = *bf & ~QUOTE; } if (*bf != '\0') *bf++ = '\0'; return *str ? str : NULL; } /* end tw_tok */ /* tw_match(): * Match a string against the pattern given. * and return the number of matched characters * in a prefix of the string. */ static int tw_match(const Char *str, const Char *pat, int exact) { const Char *estr; int rv = exact ? Gmatch(estr = str, pat) : Gnmatch(str, pat, &estr); #ifdef TDEBUG xprintf("G%smatch(%s, ", exact ? "" : "n", short2str(str)); xprintf("%s, ", short2str(pat)); xprintf("%s) = %d [%" TCSH_PTRDIFF_T_FMT "d]\n", short2str(estr), rv, estr - str); #endif /* TDEBUG */ return (int) (rv ? estr - str : -1); } /* tw_result(): * Return what the completion action should be depending on the * string */ static int tw_result(const Char *act, Char **pat) { int looking; static Char* res = NULL; Char *p; if (res != NULL) xfree(res), res = NULL; switch (act[0] & ~QUOTE) { case 'X': looking = TW_COMPLETION; break; case 'S': looking = TW_SIGNAL; break; case 'a': looking = TW_ALIAS; break; case 'b': looking = TW_BINDING; break; case 'c': looking = TW_COMMAND; break; case 'C': looking = TW_PATH | TW_COMMAND; break; case 'd': looking = TW_DIRECTORY; break; case 'D': looking = TW_PATH | TW_DIRECTORY; break; case 'e': looking = TW_ENVVAR; break; case 'f': looking = TW_FILE; break; #ifdef COMPAT case 'p': #endif /* COMPAT */ case 'F': looking = TW_PATH | TW_FILE; break; case 'g': looking = TW_GRPNAME; break; case 'j': looking = TW_JOB; break; case 'l': looking = TW_LIMIT; break; case 'n': looking = TW_NONE; break; case 's': looking = TW_SHELLVAR; break; case 't': looking = TW_TEXT; break; case 'T': looking = TW_PATH | TW_TEXT; break; case 'v': looking = TW_VARIABLE; break; case 'u': looking = TW_USER; break; case 'x': looking = TW_EXPLAIN; break; case '$': *pat = res = Strsave(&act[1]); (void) strip(res); return(TW_VARLIST); case '(': *pat = res = Strsave(&act[1]); if ((p = Strchr(res, ')')) != NULL) *p = '\0'; (void) strip(res); return TW_WORDLIST; case '`': res = Strsave(act); if ((p = Strchr(&res[1], '`')) != NULL) *++p = '\0'; - + if (didfds == 0) { /* * Make sure that we have some file descriptors to * play with, so that the processes have at least 0, 1, 2 * open */ (void) dcopy(SHIN, 0); (void) dcopy(SHOUT, 1); (void) dcopy(SHDIAG, 2); } if ((p = globone(res, G_APPEND)) != NULL) { xfree(res), res = NULL; *pat = res = Strsave(p); xfree(p); return TW_WORDLIST; } return TW_ZERO; default: stderror(ERR_COMPCOM, short2str(act)); return TW_ZERO; } switch (act[1] & ~QUOTE) { case '\0': return looking; case ':': *pat = res = Strsave(&act[2]); (void) strip(res); return looking; default: stderror(ERR_COMPCOM, short2str(act)); return TW_ZERO; } } /* end tw_result */ /* tw_dollar(): * Expand $ args in buffer */ static const Char * tw_dollar(const Char *str, Char **wl, size_t nwl, Char **result, Char sep, const char *msg) { struct Strbuf buf = Strbuf_INIT; Char *res; const Char *sp; for (sp = str; *sp && *sp != sep;) if (sp[0] == '$' && sp[1] == ':' && Isdigit(sp[sp[2] == '-' ? 3 : 2])) { int num, neg = 0; sp += 2; if (*sp == '-') { neg = 1; sp++; } for (num = *sp++ - '0'; Isdigit(*sp); num += 10 * num + *sp++ - '0') continue; if (neg) num = nwl - num - 1; if (num >= 0 && (size_t)num < nwl) Strbuf_append(&buf, wl[num]); } else Strbuf_append1(&buf, *sp++); res = Strbuf_finish(&buf); if (*sp++ == sep) { *result = res; return sp; } xfree(res); /* Truncates data if WIDE_STRINGS */ stderror(ERR_COMPMIS, (int)sep, msg, short2str(str)); return --sp; } /* end tw_dollar */ /* tw_complete(): * Return the appropriate completion for the command * * valid completion strings are: * p///[/] positional * c///[/] current word ignore pattern * C///[/] current word with pattern * n///[/] next word * N///[/] next-next word */ int tw_complete(const Char *line, Char **word, Char **pat, int looking, eChar *suf) { Char *buf, **vec, **wl; static Char nomatch[2] = { (Char) ~0, 0x00 }; const Char *ptr; size_t wordno; int n; buf = Strsave(line); cleanup_push(buf, xfree); /* Single-character words, empty current word, terminating NULL */ wl = xmalloc(((Strlen(line) + 1) / 2 + 2) * sizeof (*wl)); cleanup_push(wl, xfree); /* find the command */ if ((wl[0] = tw_tok(buf)) == NULL || wl[0] == INVPTR) { cleanup_until(buf); return TW_ZERO; } /* * look for hardwired command completions using a globbing * search and for arguments using a normal search. */ if ((vec = tw_find(wl[0], &completions, (looking == TW_COMMAND))) == NULL) { cleanup_until(buf); return looking; } /* tokenize the line one more time :-( */ for (wordno = 1; (wl[wordno] = tw_tok(NULL)) != NULL && wl[wordno] != INVPTR; wordno++) continue; if (wl[wordno] == INVPTR) { /* Found a meta character */ cleanup_until(buf); return TW_ZERO; /* de-activate completions */ } #ifdef TDEBUG { size_t i; for (i = 0; i < wordno; i++) xprintf("'%s' ", short2str(wl[i])); xprintf("\n"); } #endif /* TDEBUG */ /* if the current word is empty move the last word to the next */ if (**word == '\0') { wl[wordno] = *word; wordno++; } wl[wordno] = NULL; - + #ifdef TDEBUG xprintf("\r\n"); xprintf(" w#: %lu\n", (unsigned long)wordno); xprintf("line: %s\n", short2str(line)); xprintf(" cmd: %s\n", short2str(wl[0])); xprintf("word: %s\n", short2str(*word)); xprintf("last: %s\n", wordno >= 2 ? short2str(wl[wordno-2]) : "n/a"); xprintf("this: %s\n", wordno >= 1 ? short2str(wl[wordno-1]) : "n/a"); #endif /* TDEBUG */ - + for (;vec != NULL && (ptr = vec[0]) != NULL; vec++) { Char *ran, /* The pattern or range X//XXXX/ */ *com, /* The completion X/XXXXX// */ *pos = NULL; /* scratch pointer */ int cmd, res; Char sep; /* the command and separator characters */ int exact; if (ptr[0] == '\0') continue; #ifdef TDEBUG xprintf("match %s\n", short2str(ptr)); #endif /* TDEBUG */ switch (cmd = ptr[0]) { case 'N': pos = (wordno < 3) ? nomatch : wl[wordno - 3]; break; case 'n': pos = (wordno < 2) ? nomatch : wl[wordno - 2]; break; case 'c': case 'C': pos = (wordno < 1) ? nomatch : wl[wordno - 1]; break; case 'p': break; default: stderror(ERR_COMPINV, CGETS(27, 1, "command"), cmd); return TW_ZERO; } sep = ptr[1]; if (!Ispunct(sep)) { /* Truncates data if WIDE_STRINGS */ stderror(ERR_COMPINV, CGETS(27, 2, "separator"), (int)sep); return TW_ZERO; } ptr = tw_dollar(&ptr[2], wl, wordno, &ran, sep, CGETS(27, 3, "pattern")); cleanup_push(ran, xfree); if (ran[0] == '\0') /* check for empty pattern (disallowed) */ { stderror(ERR_COMPINC, cmd == 'p' ? CGETS(27, 4, "range") : CGETS(27, 3, "pattern"), ""); return TW_ZERO; } ptr = tw_dollar(ptr, wl, wordno, &com, sep, CGETS(27, 5, "completion")); cleanup_push(com, xfree); if (*ptr != '\0') { if (*ptr == sep) *suf = CHAR_ERR; else *suf = *ptr; } else *suf = '\0'; #ifdef TDEBUG xprintf("command: %c\nseparator: %c\n", cmd, (int)sep); xprintf("pattern: %s\n", short2str(ran)); xprintf("completion: %s\n", short2str(com)); xprintf("suffix: "); switch (*suf) { case 0: xprintf("*auto suffix*\n"); break; case CHAR_ERR: xprintf("*no suffix*\n"); break; default: xprintf("%c\n", (int)*suf); break; } #endif /* TDEBUG */ exact = 0; switch (cmd) { case 'p': /* positional completion */ #ifdef TDEBUG xprintf("p: tw_pos(%s, %lu) = ", short2str(ran), (unsigned long)wordno - 1); xprintf("%d\n", tw_pos(ran, wordno - 1)); #endif /* TDEBUG */ if (!tw_pos(ran, wordno - 1)) { cleanup_until(ran); continue; } break; case 'N': /* match with the next-next word */ case 'n': /* match with the next word */ exact = 1; /*FALLTHROUGH*/ case 'c': /* match with the current word */ case 'C': #ifdef TDEBUG xprintf("%c: ", cmd); #endif /* TDEBUG */ if ((n = tw_match(pos, ran, exact)) < 0) { cleanup_until(ran); continue; } if (cmd == 'c') *word += n; break; default: abort(); /* Cannot happen */ } tsetenv(STRCOMMAND_LINE, line); res = tw_result(com, pat); Unsetenv(STRCOMMAND_LINE); cleanup_until(buf); return res; } cleanup_until(buf); *suf = '\0'; return TW_ZERO; } /* end tw_complete */ diff --git a/contrib/tcsh/tw.h b/contrib/tcsh/tw.h index e6f0a9c6b8bf..f297e869b922 100644 --- a/contrib/tcsh/tw.h +++ b/contrib/tcsh/tw.h @@ -1,109 +1,109 @@ /* * tw.h: TwENEX functions headers */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _h_tw #define _h_tw #define TW_PATH 0x1000 #define TW_ZERO 0x0fff #define TW_NONE 0x0000 #define TW_COMMAND 0x0001 #define TW_VARIABLE 0x0002 #define TW_LOGNAME 0x0003 #define TW_FILE 0x0004 #define TW_DIRECTORY 0x0005 #define TW_VARLIST 0x0006 #define TW_USER 0x0007 #define TW_COMPLETION 0x0008 #define TW_ALIAS 0x0009 #define TW_SHELLVAR 0x000a #define TW_ENVVAR 0x000b #define TW_BINDING 0x000c #define TW_WORDLIST 0x000d #define TW_LIMIT 0x000e #define TW_SIGNAL 0x000f #define TW_JOB 0x0010 #define TW_EXPLAIN 0x0011 #define TW_TEXT 0x0012 #define TW_GRPNAME 0x0013 #define TW_EXEC_CHK 0x01 #define TW_DIR_CHK 0x02 #define TW_TEXT_CHK 0x04 #define TW_DIR_OK 0x10 #define TW_PAT_OK 0x20 #define TW_IGN_OK 0x40 #ifndef TRUE # define TRUE 1 #endif #ifndef FALSE # define FALSE 0 #endif #define ON 1 #define OFF 0 #define ESC CTL_ESC('\033') #define is_set(var) adrof(var) #define ismetahash(a) (ismeta(a) && (a) != '#') #define SEARCHLIST "HPATH" /* Env. param for helpfile searchlist */ #define DEFAULTLIST ":/usr/man/cat1:/usr/man/cat8:/usr/man/cat6:/usr/local/man/cat1:/usr/local/man/cat8:/usr/local/man/cat6" /* if no HPATH */ typedef enum { - LIST, LIST_ALL, RECOGNIZE, RECOGNIZE_ALL, RECOGNIZE_SCROLL, + LIST, LIST_ALL, RECOGNIZE, RECOGNIZE_ALL, RECOGNIZE_SCROLL, PRINT_HELP, SPELL, GLOB, GLOB_EXPAND, VARS_EXPAND, PATH_NORMALIZE, COMMAND_NORMALIZE } COMMAND; struct scroll_tab_list { Char *element; struct scroll_tab_list *next; } ; extern struct scroll_tab_list *scroll_tab; extern int curchoice; extern int non_unique_match; extern int match_unique_match; extern int InsideCompletion; extern struct varent completions; extern int color_context_ls; #include "tw.decls.h" #endif /* _h_tw */ diff --git a/contrib/tcsh/tw.init.c b/contrib/tcsh/tw.init.c index 852b6c4d2704..2d5035109551 100644 --- a/contrib/tcsh/tw.init.c +++ b/contrib/tcsh/tw.init.c @@ -1,1026 +1,1026 @@ /* * tw.init.c: Handle lists of things to complete */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "tw.h" #include "ed.h" #include "tc.h" #include "sh.proc.h" #define TW_INCR 128 typedef struct { Char **list, /* List of command names */ *buff; /* Space holding command names */ size_t nlist, /* Number of items */ nbuff, /* Current space in name buf */ tlist, /* Total space in list */ tbuff; /* Total space in name buf */ } stringlist_t; static struct varent *tw_vptr = NULL; /* Current shell variable */ static Char **tw_env = NULL; /* Current environment variable */ static const Char *tw_word; /* Current word pointer */ static struct KeyFuncs *tw_bind = NULL; /* List of the bindings */ #ifndef HAVENOLIMIT static struct limits *tw_limit = NULL; /* List of the resource limits */ #endif /* HAVENOLIMIT */ static int tw_index = 0; /* signal and job index */ static DIR *tw_dir_fd = NULL; /* Current directory descriptor */ static int tw_cmd_got = 0; /* What we need to do */ static stringlist_t tw_cmd = { NULL, NULL, 0, 0, 0, 0 }; static stringlist_t tw_item = { NULL, NULL, 0, 0, 0, 0 }; #define TW_FL_CMD 0x01 #define TW_FL_ALIAS 0x02 #define TW_FL_BUILTIN 0x04 #define TW_FL_SORT 0x08 #define TW_FL_REL 0x10 static struct { /* Current element pointer */ size_t cur; /* Current element number */ Char **pathv; /* Current element in path */ DIR *dfd; /* Current directory descriptor */ } tw_cmd_state; #define SETDIR(dfd) \ { \ tw_dir_fd = dfd; \ if (tw_dir_fd != NULL) \ rewinddir(tw_dir_fd); \ } #define CLRDIR(dfd) \ if (dfd != NULL) { \ pintr_disabled++; \ xclosedir(dfd); \ dfd = NULL; \ disabled_cleanup(&pintr_disabled); \ } static Char *tw_str_add (stringlist_t *, size_t); static void tw_str_free (stringlist_t *); static int tw_dir_next (struct Strbuf *, DIR *); static void tw_cmd_add (const Char *name); static void tw_cmd_cmd (void); static void tw_cmd_builtin (void); static void tw_cmd_alias (void); static void tw_cmd_sort (void); static void tw_vptr_start (struct varent *); /* tw_str_add(): * Add an item to the string list */ static Char * tw_str_add(stringlist_t *sl, size_t len) { Char *ptr; if (sl->tlist <= sl->nlist) { pintr_disabled++; sl->tlist += TW_INCR; sl->list = xrealloc(sl->list, sl->tlist * sizeof(Char *)); disabled_cleanup(&pintr_disabled); } if (sl->tbuff <= sl->nbuff + len) { size_t i; ptr = sl->buff; pintr_disabled++; sl->tbuff += TW_INCR + len; sl->buff = xrealloc(sl->buff, sl->tbuff * sizeof(Char)); /* Re-thread the new pointer list, if changed */ if (ptr != NULL && ptr != sl->buff) { for (i = 0; i < sl->nlist; i++) sl->list[i] = sl->buff + (sl->list[i] - ptr); } disabled_cleanup(&pintr_disabled); } ptr = sl->list[sl->nlist++] = &sl->buff[sl->nbuff]; sl->nbuff += len; return ptr; } /* tw_str_add */ /* tw_str_free(): * Free a stringlist */ static void tw_str_free(stringlist_t *sl) { pintr_disabled++; if (sl->list) { xfree(sl->list); sl->list = NULL; sl->tlist = sl->nlist = 0; } if (sl->buff) { xfree(sl->buff); sl->buff = NULL; sl->tbuff = sl->nbuff = 0; } disabled_cleanup(&pintr_disabled); } /* end tw_str_free */ static int tw_dir_next(struct Strbuf *res, DIR *dfd) { struct dirent *dirp; if (dfd == NULL) return 0; if ((dirp = readdir(dfd)) != NULL) { Strbuf_append(res, str2short(dirp->d_name)); return 1; } return 0; } /* end tw_dir_next */ /* tw_cmd_add(): * Add the name to the command list */ static void tw_cmd_add(const Char *name) { size_t len; len = Strlen(name) + 2; (void) Strcpy(tw_str_add(&tw_cmd, len), name); } /* end tw_cmd_add */ /* tw_cmd_free(): * Free the command list */ void tw_cmd_free(void) { CLRDIR(tw_dir_fd) tw_str_free(&tw_cmd); tw_cmd_got = 0; } /* end tw_cmd_free */ /* tw_cmd_cmd(): * Add system commands to the command list */ static void tw_cmd_cmd(void) { DIR *dirp; struct dirent *dp; Char *dir = NULL, *name; Char **pv; struct varent *v = adrof(STRpath); struct varent *recexec = adrof(STRrecognize_only_executables); size_t len; if (v == NULL || v->vec == NULL) /* if no path */ return; for (pv = v->vec; *pv; pv++) { if (pv[0][0] != '/') { tw_cmd_got |= TW_FL_REL; continue; } if ((dirp = opendir(short2str(*pv))) == NULL) continue; cleanup_push(dirp, opendir_cleanup); if (recexec) { dir = Strspl(*pv, STRslash); cleanup_push(dir, xfree); } while ((dp = readdir(dirp)) != NULL) { #if defined(_UWIN) || defined(__CYGWIN__) /* Turn foo.{exe,com,bat} into foo since UWIN's readdir returns * the file with the .exe, .com, .bat extension * * Same for Cygwin, but only for .exe and .com extension. */ len = strlen(dp->d_name); if (len > 4 && (strcmp(&dp->d_name[len - 4], ".exe") == 0 || #ifndef __CYGWIN__ strcmp(&dp->d_name[len - 4], ".bat") == 0 || #endif /* !__CYGWIN__ */ strcmp(&dp->d_name[len - 4], ".com") == 0)) dp->d_name[len - 4] = '\0'; #endif /* _UWIN || __CYGWIN__ */ /* the call to executable() may make this a bit slow */ name = str2short(dp->d_name); if (dp->d_ino == 0 || (recexec && !executable(dir, name, 0))) continue; len = Strlen(name); if (name[0] == '#' || /* emacs temp files */ name[0] == '.' || /* .files */ name[len - 1] == '~' || /* emacs backups */ name[len - 1] == '%') /* textedit backups */ continue; /* Ignore! */ tw_cmd_add(name); } cleanup_until(dirp); } } /* end tw_cmd_cmd */ /* tw_cmd_builtin(): * Add builtins to the command list */ static void tw_cmd_builtin(void) { const struct biltins *bptr; for (bptr = bfunc; bptr < &bfunc[nbfunc]; bptr++) if (bptr->bname) tw_cmd_add(str2short(bptr->bname)); #ifdef WINNT_NATIVE for (bptr = nt_bfunc; bptr < &nt_bfunc[nt_nbfunc]; bptr++) if (bptr->bname) tw_cmd_add(str2short(bptr->bname)); #endif /* WINNT_NATIVE*/ } /* end tw_cmd_builtin */ /* tw_cmd_alias(): * Add aliases to the command list */ static void tw_cmd_alias(void) { struct varent *p; struct varent *c; p = &aliases; for (;;) { while (p->v_left) p = p->v_left; x: if (p->v_parent == 0) /* is it the header? */ return; if (p->v_name) tw_cmd_add(p->v_name); if (p->v_right) { p = p->v_right; continue; } do { c = p; p = p->v_parent; } while (p->v_right == c); goto x; } } /* end tw_cmd_alias */ /* tw_cmd_sort(): * Sort the command list removing duplicate elements */ static void tw_cmd_sort(void) { size_t fwd, i; pintr_disabled++; /* sort the list. */ qsort(tw_cmd.list, tw_cmd.nlist, sizeof(Char *), fcompare); /* get rid of multiple entries */ for (i = 0, fwd = 0; i + 1 < tw_cmd.nlist; i++) { if (Strcmp(tw_cmd.list[i], tw_cmd.list[i + 1]) == 0) /* garbage */ fwd++; /* increase the forward ref. count */ - else if (fwd) + else if (fwd) tw_cmd.list[i - fwd] = tw_cmd.list[i]; } /* Fix fencepost error -- Theodore Ts'o */ if (fwd) tw_cmd.list[i - fwd] = tw_cmd.list[i]; tw_cmd.nlist -= fwd; disabled_cleanup(&pintr_disabled); } /* end tw_cmd_sort */ /* tw_cmd_start(): * Get the command list and sort it, if not done yet. * Reset the current pointer to the beginning of the command list */ /*ARGSUSED*/ void tw_cmd_start(DIR *dfd, const Char *pat) { static Char *defpath[] = { STRNULL, 0 }; USE(pat); SETDIR(dfd) if ((tw_cmd_got & TW_FL_CMD) == 0) { tw_cmd_free(); tw_cmd_cmd(); tw_cmd_got |= TW_FL_CMD; } if ((tw_cmd_got & TW_FL_ALIAS) == 0) { tw_cmd_alias(); tw_cmd_got &= ~TW_FL_SORT; tw_cmd_got |= TW_FL_ALIAS; } if ((tw_cmd_got & TW_FL_BUILTIN) == 0) { tw_cmd_builtin(); tw_cmd_got &= ~TW_FL_SORT; tw_cmd_got |= TW_FL_BUILTIN; } if ((tw_cmd_got & TW_FL_SORT) == 0) { tw_cmd_sort(); tw_cmd_got |= TW_FL_SORT; } tw_cmd_state.cur = 0; CLRDIR(tw_cmd_state.dfd) if (tw_cmd_got & TW_FL_REL) { struct varent *vp = adrof(STRpath); if (vp && vp->vec) tw_cmd_state.pathv = vp->vec; else tw_cmd_state.pathv = defpath; } - else + else tw_cmd_state.pathv = defpath; } /* tw_cmd_start */ /* tw_cmd_next(): * Return the next element in the command list or * Look for commands in the relative path components */ int tw_cmd_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { int ret = 0; Char *ptr; if (tw_cmd_state.cur < tw_cmd.nlist) { *flags = TW_DIR_OK; Strbuf_append(res, tw_cmd.list[tw_cmd_state.cur++]); return 1; } /* * We need to process relatives in the path. */ while ((tw_cmd_state.dfd == NULL || (res->len = 0, ret = tw_dir_next(res, tw_cmd_state.dfd)) == 0) && *tw_cmd_state.pathv != NULL) { CLRDIR(tw_cmd_state.dfd) while (*tw_cmd_state.pathv && tw_cmd_state.pathv[0][0] == '/') tw_cmd_state.pathv++; if ((ptr = *tw_cmd_state.pathv) != 0) { res->len = 0; Strbuf_append(res, ptr); ret = 1; /* * We complete directories only on '.' should that * be changed? */ dir->len = 0; if (ptr[0] == '\0' || (ptr[0] == '.' && ptr[1] == '\0')) { tw_cmd_state.dfd = opendir("."); *flags = TW_DIR_OK | TW_EXEC_CHK; } else { Strbuf_append(dir, *tw_cmd_state.pathv); Strbuf_append1(dir, '/'); tw_cmd_state.dfd = opendir(short2str(*tw_cmd_state.pathv)); *flags = TW_EXEC_CHK; } Strbuf_terminate(dir); tw_cmd_state.pathv++; } } return ret; } /* end tw_cmd_next */ /* tw_vptr_start(): * Find the first variable in the variable list */ static void tw_vptr_start(struct varent *c) { tw_vptr = c; /* start at beginning of variable list */ for (;;) { while (tw_vptr->v_left) tw_vptr = tw_vptr->v_left; x: if (tw_vptr->v_parent == 0) { /* is it the header? */ tw_vptr = NULL; return; } if (tw_vptr->v_name) return; /* found first one */ if (tw_vptr->v_right) { tw_vptr = tw_vptr->v_right; continue; } do { c = tw_vptr; tw_vptr = tw_vptr->v_parent; } while (tw_vptr->v_right == c); goto x; } } /* end tw_shvar_start */ /* tw_shvar_next(): * Return the next shell variable */ /*ARGSUSED*/ int tw_shvar_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { struct varent *p; struct varent *c; USE(flags); USE(dir); if ((p = tw_vptr) == NULL) return 0; /* just in case */ Strbuf_append(res, p->v_name); /* we know that this name is here now */ /* now find the next one */ for (;;) { if (p->v_right) { /* if we can go right */ p = p->v_right; while (p->v_left) p = p->v_left; } else { /* else go up */ do { c = p; p = p->v_parent; } while (p->v_right == c); } if (p->v_parent == 0) { /* is it the header? */ tw_vptr = NULL; return 1; } if (p->v_name) { tw_vptr = p; /* save state for the next call */ return 1; } } } /* end tw_shvar_next */ /* tw_envvar_next(): * Return the next environment variable */ /*ARGSUSED*/ int tw_envvar_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { const Char *ps; USE(flags); USE(dir); if (tw_env == NULL || *tw_env == NULL) return 0; for (ps = *tw_env; *ps && *ps != '='; ps++) continue; Strbuf_appendn(res, *tw_env, ps - *tw_env); tw_env++; return 1; } /* end tw_envvar_next */ /* tw_var_start(): * Begin the list of the shell and environment variables */ /*ARGSUSED*/ void tw_var_start(DIR *dfd, const Char *pat) { USE(pat); SETDIR(dfd) tw_vptr_start(&shvhed); tw_env = STR_environ; } /* end tw_var_start */ /* tw_alias_start(): * Begin the list of the shell aliases */ /*ARGSUSED*/ void tw_alias_start(DIR *dfd, const Char *pat) { USE(pat); SETDIR(dfd) tw_vptr_start(&aliases); tw_env = NULL; } /* tw_alias_start */ /* tw_complete_start(): * Begin the list of completions */ /*ARGSUSED*/ void tw_complete_start(DIR *dfd, const Char *pat) { USE(pat); SETDIR(dfd) tw_vptr_start(&completions); tw_env = NULL; } /* end tw_complete_start */ /* tw_var_next(): * Return the next shell or environment variable */ int tw_var_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { int ret = 0; if (tw_vptr) ret = tw_shvar_next(res, dir, flags); if (ret == 0 && tw_env) ret = tw_envvar_next(res, dir, flags); return ret; } /* end tw_var_next */ /* tw_logname_start(): * Initialize lognames to the beginning of the list */ /*ARGSUSED*/ -void +void tw_logname_start(DIR *dfd, const Char *pat) { USE(pat); SETDIR(dfd) #ifdef HAVE_GETPWENT (void) setpwent(); /* Open passwd file */ #endif } /* end tw_logname_start */ /* tw_logname_next(): * Return the next entry from the passwd file */ /*ARGSUSED*/ int tw_logname_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { struct passwd *pw; /* * We don't want to get interrupted inside getpwent() * because the yellow pages code is not interruptible, * and if we call endpwent() immediatetely after * (in pintr()) we may be freeing an invalid pointer */ USE(flags); USE(dir); pintr_disabled++; #ifdef HAVE_GETPWENT pw = getpwent(); #else pw = NULL; #endif disabled_cleanup(&pintr_disabled); if (pw == NULL) { #ifdef YPBUGS fix_yp_bugs(); #endif return 0; } Strbuf_append(res, str2short(pw->pw_name)); return 1; } /* end tw_logname_next */ /* tw_logname_end(): * Close the passwd file to finish the logname list */ void tw_logname_end(void) { #ifdef YPBUGS fix_yp_bugs(); #endif #ifdef HAVE_GETPWENT (void) endpwent(); #endif } /* end tw_logname_end */ /* tw_grpname_start(): * Initialize grpnames to the beginning of the list */ /*ARGSUSED*/ -void +void tw_grpname_start(DIR *dfd, const Char *pat) { USE(pat); SETDIR(dfd) #if !defined(_VMS_POSIX) && !defined(_OSD_POSIX) && !defined(WINNT_NATIVE) && !defined (__ANDROID__) (void) setgrent(); /* Open group file */ #endif /* !_VMS_POSIX && !_OSD_POSIX && !WINNT_NATIVE */ } /* end tw_grpname_start */ /* tw_grpname_next(): * Return the next entry from the group file */ /*ARGSUSED*/ int tw_grpname_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { struct group *gr; /* * We don't want to get interrupted inside getgrent() * because the yellow pages code is not interruptible, * and if we call endgrent() immediatetely after * (in pintr()) we may be freeing an invalid pointer */ USE(flags); USE(dir); pintr_disabled++; #if !defined(_VMS_POSIX) && !defined(_OSD_POSIX) && !defined(WINNT_NATIVE) && !defined(__ANDROID__) errno = 0; while ((gr = getgrent()) == NULL && errno == EINTR) { handle_pending_signals(); errno = 0; } #else /* _VMS_POSIX || _OSD_POSIX || WINNT_NATIVE */ gr = NULL; #endif /* !_VMS_POSIX && !_OSD_POSIX && !WINNT_NATIVE */ disabled_cleanup(&pintr_disabled); if (gr == NULL) { #ifdef YPBUGS fix_yp_bugs(); #endif return 0; } Strbuf_append(res, str2short(gr->gr_name)); return 1; } /* end tw_grpname_next */ /* tw_grpname_end(): * Close the group file to finish the groupname list */ void tw_grpname_end(void) { #ifdef YPBUGS fix_yp_bugs(); #endif #if !defined(_VMS_POSIX) && !defined(_OSD_POSIX) && !defined(WINNT_NATIVE) && !defined (__ANDROID__) (void) endgrent(); #endif /* !_VMS_POSIX && !_OSD_POSIX && !WINNT_NATIVE */ } /* end tw_grpname_end */ /* tw_file_start(): * Initialize the directory for the file list */ /*ARGSUSED*/ void tw_file_start(DIR *dfd, const Char *pat) { struct varent *vp; USE(pat); SETDIR(dfd) if ((vp = adrof(STRcdpath)) != NULL) tw_env = vp->vec; } /* end tw_file_start */ /* tw_file_next(): - * Return the next file in the directory + * Return the next file in the directory */ int tw_file_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { int ret = tw_dir_next(res, tw_dir_fd); if (ret == 0 && (*flags & TW_DIR_OK) != 0) { CLRDIR(tw_dir_fd) while (tw_env && *tw_env) if ((tw_dir_fd = opendir(short2str(*tw_env))) != NULL) break; else tw_env++; if (tw_dir_fd) { dir->len = 0; Strbuf_append(dir, *tw_env++); Strbuf_append1(dir, '/'); Strbuf_terminate(dir); ret = tw_dir_next(res, tw_dir_fd); } } return ret; } /* end tw_file_next */ /* tw_dir_end(): * Clear directory related lists */ void tw_dir_end(void) { CLRDIR(tw_dir_fd) CLRDIR(tw_cmd_state.dfd) } /* end tw_dir_end */ /* tw_item_free(): * Free the item list */ void tw_item_free(void) { tw_str_free(&tw_item); } /* end tw_item_free */ -/* tw_item_get(): - * Return the list of items +/* tw_item_get(): + * Return the list of items */ Char ** tw_item_get(void) { return tw_item.list; } /* end tw_item_get */ /* tw_item_add(): * Return a new item for a Strbuf_terminate()'d s */ void tw_item_add(const struct Strbuf *s) { Char *p; p = tw_str_add(&tw_item, s->len + 1); Strcpy(p, s->s); } /* tw_item_add */ /* tw_item_find(): - * Find the string if it exists in the item list + * Find the string if it exists in the item list * end return it. */ Char * tw_item_find(Char *str) { size_t i; if (tw_item.list == NULL || str == NULL) return NULL; for (i = 0; i < tw_item.nlist; i++) if (tw_item.list[i] != NULL && Strcmp(tw_item.list[i], str) == 0) return tw_item.list[i]; return NULL; } /* end tw_item_find */ /* tw_vl_start(): * Initialize a variable list */ void tw_vl_start(DIR *dfd, const Char *pat) { SETDIR(dfd) if ((tw_vptr = adrof(pat)) != NULL) { tw_env = tw_vptr->vec; tw_vptr = NULL; } else tw_env = NULL; } /* end tw_vl_start */ /* * Initialize a word list */ void tw_wl_start(DIR *dfd, const Char *pat) { SETDIR(dfd); tw_word = pat; } /* end tw_wl_start */ /* * Return the next word from the word list */ /*ARGSUSED*/ int tw_wl_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { const Char *p; USE(dir); USE(flags); if (tw_word == NULL || tw_word[0] == '\0') return 0; while (*tw_word && Isspace(*tw_word)) tw_word++; for (p = tw_word; *tw_word && !Isspace(*tw_word); tw_word++) continue; if (tw_word == p) return 0; Strbuf_appendn(res, p, tw_word - p); if (*tw_word) tw_word++; return 1; } /* end tw_wl_next */ /* tw_bind_start(): * Begin the list of the shell bindings */ /*ARGSUSED*/ void tw_bind_start(DIR *dfd, const Char *pat) { USE(pat); SETDIR(dfd) tw_bind = FuncNames; } /* end tw_bind_start */ /* tw_bind_next(): * Begin the list of the shell bindings */ /*ARGSUSED*/ int tw_bind_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { USE(dir); USE(flags); if (tw_bind && tw_bind->name) { const char *ptr; for (ptr = tw_bind->name; *ptr != '\0'; ptr++) Strbuf_append1(res, *ptr); tw_bind++; return 1; } return 0; } /* end tw_bind_next */ /* tw_limit_start(): * Begin the list of the shell limitings */ /*ARGSUSED*/ void tw_limit_start(DIR *dfd, const Char *pat) { USE(pat); SETDIR(dfd) #ifndef HAVENOLIMIT tw_limit = limits; #endif /* ! HAVENOLIMIT */ } /* end tw_limit_start */ /* tw_limit_next(): * Begin the list of the shell limitings */ /*ARGSUSED*/ int tw_limit_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { USE(dir); USE(flags); #ifndef HAVENOLIMIT if (tw_limit && tw_limit->limname) { const char *ptr; for (ptr = tw_limit->limname; *ptr != '\0'; ptr++) Strbuf_append1(res, *ptr); tw_limit++; return 1; } #endif /* ! HAVENOLIMIT */ return 0; } /* end tw_limit_next */ /* tw_sig_start(): * Begin the list of the shell sigings */ /*ARGSUSED*/ void tw_sig_start(DIR *dfd, const Char *pat) { USE(pat); SETDIR(dfd) tw_index = 0; } /* end tw_sig_start */ /* tw_sig_next(): * Begin the list of the shell sigings */ /*ARGSUSED*/ int tw_sig_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { USE(dir); USE(flags); for (;tw_index < nsig; tw_index++) { const char *ptr; if (mesg[tw_index].iname == NULL) continue; for (ptr = mesg[tw_index].iname; *ptr != '\0'; ptr++) Strbuf_append1(res, *ptr); tw_index++; return 1; } return 0; } /* end tw_sig_next */ /* tw_job_start(): * Begin the list of the shell jobings */ /*ARGSUSED*/ void tw_job_start(DIR *dfd, const Char *pat) { USE(pat); SETDIR(dfd) tw_index = 1; } /* end tw_job_start */ /* tw_job_next(): * Begin the list of the shell jobings */ /*ARGSUSED*/ int tw_job_next(struct Strbuf *res, struct Strbuf *dir, int *flags) { struct process *j; USE(dir); USE(flags); for (;tw_index <= pmaxindex; tw_index++) { for (j = proclist.p_next; j != NULL; j = j->p_next) if (j->p_index == tw_index && j->p_procid == j->p_jobid) break; - if (j == NULL) + if (j == NULL) continue; Strbuf_append(res, j->p_command); tw_index++; return 1; } return 0; } /* end tw_job_next */ diff --git a/contrib/tcsh/tw.parse.c b/contrib/tcsh/tw.parse.c index ed019db5bd35..366a704c5915 100644 --- a/contrib/tcsh/tw.parse.c +++ b/contrib/tcsh/tw.parse.c @@ -1,2375 +1,2375 @@ /* * tw.parse.c: Everyone has taken a shot in this futile effort to * lexically analyze a csh line... Well we cannot good * a job as good as sh.lex.c; but we try. Amazing that * it works considering how many hands have touched this code */ /*- * Copyright (c) 1980, 1991 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sh.h" #include "tw.h" #include "ed.h" #include "tc.h" #include #ifdef WINNT_NATIVE #include "nt.const.h" #endif /* WINNT_NATIVE */ #define EVEN(x) (((x) & 1) != 1) #define DOT_NONE 0 /* Don't display dot files */ #define DOT_NOT 1 /* Don't display dot or dot-dot */ #define DOT_ALL 2 /* Display all dot files */ /* TW_NONE, TW_COMMAND, TW_VARIABLE, TW_LOGNAME, */ /* TW_FILE, TW_DIRECTORY, TW_VARLIST, TW_USER, */ /* TW_COMPLETION, TW_ALIAS, TW_SHELLVAR, TW_ENVVAR, */ /* TW_BINDING, TW_WORDLIST, TW_LIMIT, TW_SIGNAL */ /* TW_JOB, TW_EXPLAIN, TW_TEXT, TW_GRPNAME */ static void (*const tw_start_entry[]) (DIR *, const Char *) = { - tw_file_start, tw_cmd_start, tw_var_start, tw_logname_start, - tw_file_start, tw_file_start, tw_vl_start, tw_logname_start, - tw_complete_start, tw_alias_start, tw_var_start, tw_var_start, + tw_file_start, tw_cmd_start, tw_var_start, tw_logname_start, + tw_file_start, tw_file_start, tw_vl_start, tw_logname_start, + tw_complete_start, tw_alias_start, tw_var_start, tw_var_start, tw_bind_start, tw_wl_start, tw_limit_start, tw_sig_start, tw_job_start, tw_file_start, tw_file_start, tw_grpname_start }; static int (*const tw_next_entry[]) (struct Strbuf *, struct Strbuf *, int *) = { - tw_file_next, tw_cmd_next, tw_var_next, tw_logname_next, - tw_file_next, tw_file_next, tw_var_next, tw_logname_next, - tw_var_next, tw_var_next, tw_shvar_next, tw_envvar_next, + tw_file_next, tw_cmd_next, tw_var_next, tw_logname_next, + tw_file_next, tw_file_next, tw_var_next, tw_logname_next, + tw_var_next, tw_var_next, tw_shvar_next, tw_envvar_next, tw_bind_next, tw_wl_next, tw_limit_next, tw_sig_next, tw_job_next, tw_file_next, tw_file_next, tw_grpname_next }; static void (*const tw_end_entry[]) (void) = { tw_dir_end, tw_dir_end, tw_dir_end, tw_logname_end, - tw_dir_end, tw_dir_end, tw_dir_end, tw_logname_end, + tw_dir_end, tw_dir_end, tw_dir_end, tw_logname_end, tw_dir_end, tw_dir_end, tw_dir_end, tw_dir_end, tw_dir_end, tw_dir_end, tw_dir_end, tw_dir_end, tw_dir_end, tw_dir_end, tw_dir_end, tw_grpname_end }; /* #define TDEBUG */ /* Set to TRUE if recexact is set and an exact match is found * along with other, longer, matches. */ int curchoice = -1; int match_unique_match = FALSE; int non_unique_match = FALSE; static int SearchNoDirErr = 0; /* t_search returns -2 if dir is unreadable */ /* state so if a completion is interrupted, the input line doesn't get nuked */ int InsideCompletion = 0; /* do the expand or list on the command line -- SHOULD BE REPLACED */ static void extract_dir_and_name (const Char *, struct Strbuf *, Char **); static int insert_meta (const Char *, const Char *, const Char *, int); static int tilde (struct Strbuf *, Char *); static int expand_dir (const Char *, struct Strbuf *, DIR **, COMMAND); static int nostat (Char *); static Char filetype (Char *, Char *); static int t_glob (Char ***, int); static int c_glob (Char ***); static int is_prefix (Char *, Char *); static int is_prefixmatch (Char *, Char *, int); static int is_suffix (Char *, Char *); static int recognize (struct Strbuf *, const Char *, size_t, int, int, int); static int ignored (Char *); static int isadirectory (const Char *, const Char *); static int tw_collect_items (COMMAND, int, struct Strbuf *, struct Strbuf *, Char *, const Char *, int); static int tw_collect (COMMAND, int, struct Strbuf *, struct Strbuf *, Char *, Char *, int, DIR *); static Char tw_suffix (int, struct Strbuf *,const Char *, Char *); static void tw_fixword (int, struct Strbuf *, Char *, Char *); static void tw_list_items (int, int, int); static void add_scroll_tab (Char *); static void choose_scroll_tab (struct Strbuf *, int); static void free_scroll_tab (void); static int find_rows (Char *[], int, int); #ifdef notdef /* * If we find a set command, then we break a=b to a= and word becomes * b else, we don't break a=b. [don't use that; splits words badly and * messes up tw_complete()] */ #define isaset(c, w) ((w)[-1] == '=' && \ ((c)[0] == 's' && (c)[1] == 'e' && (c)[2] == 't' && \ ((c[3] == ' ' || (c)[3] == '\t')))) #endif /* TRUE if character must be quoted */ #define tricky(w) (cmap(w, _META | _DOL | _QF | _QB | _ESC | _GLOB) && w != '#') /* TRUE if double quotes don't protect character */ #define tricky_dq(w) (cmap(w, _DOL | _QB)) /* tenematch(): * Return: * > 1: No. of items found * = 1: Exactly one match / spelling corrected * = 0: No match / spelling was correct * < 0: Error (incl spelling correction impossible) */ int tenematch(Char *inputline, int num_read, COMMAND command) { struct Strbuf qline = Strbuf_INIT; Char qu = 0, *pat = STRNULL; size_t wp, word, wordp, cmd_start, oword = 0, ocmd_start = 0; Char *str_end, *cp; Char *word_start; Char *oword_start = NULL; eChar suf = 0; int looking; /* what we are looking for */ int search_ret; /* what search returned for debugging */ int backq = 0; str_end = &inputline[num_read]; cleanup_push(&qline, Strbuf_cleanup); word_start = inputline; word = cmd_start = 0; for (cp = inputline; cp < str_end; cp++) { if (!cmap(qu, _ESC)) { if (cmap(*cp, _QF|_ESC)) { if (qu == 0 || qu == *cp) { qu ^= *cp; continue; } } if (qu != '\'' && cmap(*cp, _QB)) { if ((backq ^= 1) != 0) { ocmd_start = cmd_start; oword_start = word_start; oword = word; word_start = cp + 1; word = cmd_start = qline.len + 1; } else { cmd_start = ocmd_start; word_start = oword_start; word = oword; } Strbuf_append1(&qline, *cp); continue; } } if (iscmdmeta(*cp)) cmd_start = qline.len + 1; /* Don't quote '/' to make the recognize stuff work easily */ /* Don't quote '$' in double quotes */ if (cmap(*cp, _ESC) && cp < str_end - 1 && cp[1] == HIST && HIST != '\0') Strbuf_append1(&qline, *++cp | QUOTE); else if (qu && (tricky(*cp) || *cp == '~') && !(qu == '\"' && tricky_dq(*cp))) Strbuf_append1(&qline, *cp | QUOTE); else Strbuf_append1(&qline, *cp); if (ismetahash(qline.s[qline.len - 1]) /* || isaset(qline.s + cmd_start, qline.s + qline.len) */) word = qline.len, word_start = cp + 1; if (cmap(qu, _ESC)) qu = 0; } Strbuf_terminate(&qline); wp = qline.len; /* * SPECIAL HARDCODED COMPLETIONS: * first word of command -> TW_COMMAND * everything else -> TW_ZERO * */ looking = starting_a_command(qline.s + word - 1, qline.s) ? TW_COMMAND : TW_ZERO; wordp = word; #ifdef TDEBUG { const Char *p; xprintf(CGETS(30, 1, "starting_a_command %d\n"), looking); xprintf("\ncmd_start:%S:\n", qline.s + cmd_start); xprintf("qline:%S:\n", qline.s); xprintf("qline:"); for (p = qline.s; *p; p++) xprintf("%c", *p & QUOTE ? '-' : ' '); xprintf(":\n"); xprintf("word:%S:\n", qline.s + word); xprintf("word:"); for (p = qline.s + word; *p; p++) xprintf("%c", *p & QUOTE ? '-' : ' '); xprintf(":\n"); } #endif if ((looking == TW_COMMAND || looking == TW_ZERO) && (command == RECOGNIZE || command == LIST || command == SPELL || command == RECOGNIZE_SCROLL)) { Char *p; #ifdef TDEBUG xprintf(CGETS(30, 2, "complete %d "), looking); #endif p = qline.s + wordp; looking = tw_complete(qline.s + cmd_start, &p, &pat, looking, &suf); wordp = p - qline.s; #ifdef TDEBUG xprintf(CGETS(30, 3, "complete %d %S\n"), looking, pat); #endif } switch (command) { Char *bptr; Char *items[2], **ptr; int i, count; case RECOGNIZE: case RECOGNIZE_SCROLL: case RECOGNIZE_ALL: { struct Strbuf wordbuf = Strbuf_INIT; Char *slshp; if (adrof(STRautocorrect)) { if ((slshp = Strrchr(qline.s + wordp, '/')) != NULL && slshp[1] != '\0') { SearchNoDirErr = 1; for (bptr = qline.s + wordp; bptr < slshp; bptr++) { /* * do not try to correct spelling of words containing * globbing characters */ if (isglob(*bptr)) { SearchNoDirErr = 0; break; } } } } else slshp = STRNULL; Strbuf_append(&wordbuf, qline.s + wordp); Strbuf_terminate(&wordbuf); cleanup_push(&wordbuf, Strbuf_cleanup); search_ret = t_search(&wordbuf, command, looking, 1, pat, suf); qline.len = wordp; Strbuf_append(&qline, wordbuf.s); Strbuf_terminate(&qline); cleanup_until(&wordbuf); SearchNoDirErr = 0; if (search_ret == -2) { Char *rword; rword = Strsave(slshp); cleanup_push(rword, xfree); if (slshp != STRNULL) *slshp = '\0'; wordbuf = Strbuf_init; Strbuf_append(&wordbuf, qline.s + wordp); Strbuf_terminate(&wordbuf); cleanup_push(&wordbuf, Strbuf_cleanup); search_ret = spell_me(&wordbuf, looking, pat, suf); if (search_ret == 1) { Strbuf_append(&wordbuf, rword); Strbuf_terminate(&wordbuf); wp = wordp + wordbuf.len; search_ret = t_search(&wordbuf, command, looking, 1, pat, suf); } qline.len = wordp; Strbuf_append(&qline, wordbuf.s); Strbuf_terminate(&qline); cleanup_until(rword); } if (qline.s[wp] != '\0' && insert_meta(word_start, str_end, qline.s + word, !qu) < 0) goto err; /* error inserting */ break; } case SPELL: { struct Strbuf wordbuf = Strbuf_INIT; for (bptr = word_start; bptr < str_end; bptr++) { /* * do not try to correct spelling of words containing globbing * characters */ if (isglob(*bptr)) { search_ret = 0; goto end; } } Strbuf_append(&wordbuf, qline.s + wordp); Strbuf_terminate(&wordbuf); cleanup_push(&wordbuf, Strbuf_cleanup); /* * Don't try to spell things that we know they are correct. * Trying to spell can hang when we have NFS mounted hung * volumes. */ if ((looking == TW_COMMAND) && Strchr(wordbuf.s, '/') != NULL) { if (executable(NULL, wordbuf.s, 0)) { cleanup_until(&wordbuf); search_ret = 0; goto end; } } search_ret = spell_me(&wordbuf, looking, pat, suf); qline.len = wordp; Strbuf_append(&qline, wordbuf.s); Strbuf_terminate(&qline); cleanup_until(&wordbuf); if (search_ret == 1) { if (insert_meta(word_start, str_end, qline.s + word, !qu) < 0) goto err; /* error inserting */ } break; } case PRINT_HELP: do_help(qline.s + cmd_start); search_ret = 1; break; case GLOB: case GLOB_EXPAND: items[0] = Strsave(qline.s + wordp); items[1] = NULL; cleanup_push(items[0], xfree); ptr = items; count = (looking == TW_COMMAND && Strchr(qline.s + wordp, '/') == 0) ? c_glob(&ptr) : t_glob(&ptr, looking == TW_COMMAND); cleanup_until(items[0]); if (ptr != items) cleanup_push(ptr, blk_cleanup); if (count > 0) { if (command == GLOB) print_by_column(STRNULL, ptr, count, 0); else { DeleteBack(str_end - word_start);/* get rid of old word */ for (i = 0; i < count; i++) if (ptr[i] && *ptr[i]) { (void) quote(ptr[i]); if (insert_meta(0, 0, ptr[i], 0) < 0 || InsertStr(STRspace) < 0) { if (ptr != items) cleanup_until(ptr); goto err; /* error inserting */ } } } } if (ptr != items) cleanup_until(ptr); search_ret = count; break; case VARS_EXPAND: bptr = dollar(qline.s + word); if (bptr != NULL) { if (insert_meta(word_start, str_end, bptr, !qu) < 0) { xfree(bptr); goto err; /* error inserting */ } xfree(bptr); search_ret = 1; break; } search_ret = 0; break; case PATH_NORMALIZE: if ((bptr = dnormalize(qline.s + wordp, symlinks == SYM_IGNORE || symlinks == SYM_EXPAND)) != NULL) { if (insert_meta(word_start, str_end, bptr, !qu) < 0) { xfree(bptr); goto err; /* error inserting */ } xfree(bptr); search_ret = 1; break; } search_ret = 0; break; case COMMAND_NORMALIZE: { Char *p; int found; found = cmd_expand(qline.s + wordp, &p); - + if (!found) { xfree(p); search_ret = 0; break; } if (insert_meta(word_start, str_end, p, !qu) < 0) { xfree(p); goto err; /* error inserting */ } xfree(p); search_ret = 1; break; } case LIST: case LIST_ALL: { struct Strbuf wordbuf = Strbuf_INIT; Strbuf_append(&wordbuf, qline.s + wordp); Strbuf_terminate(&wordbuf); cleanup_push(&wordbuf, Strbuf_cleanup); search_ret = t_search(&wordbuf, LIST, looking, 1, pat, suf); qline.len = wordp; Strbuf_append(&qline, wordbuf.s); Strbuf_terminate(&qline); cleanup_until(&wordbuf); break; } default: xprintf(CGETS(30, 4, "%s: Internal match error.\n"), progname); search_ret = 1; } end: cleanup_until(&qline); return search_ret; err: cleanup_until(&qline); return -1; } /* end tenematch */ /* t_glob(): * Return a list of files that match the pattern */ static int t_glob(Char ***v, int cmd) { jmp_buf_t osetexit; int gflag; if (**v == 0) return (0); gflag = tglob(*v); if (gflag) { size_t omark; getexit(osetexit); /* make sure to come back here */ omark = cleanup_push_mark(); if (setexit() == 0) *v = globall(*v, gflag); cleanup_pop_mark(omark); resexit(osetexit); if (haderr) { haderr = 0; NeedsRedraw = 1; return (-1); } if (*v == 0) return (0); } else return (0); if (cmd) { Char **av = *v, *p; int fwd, i; - for (i = 0, fwd = 0; av[i] != NULL; i++) + for (i = 0, fwd = 0; av[i] != NULL; i++) if (!executable(NULL, av[i], 0)) { - fwd++; + fwd++; p = av[i]; av[i] = NULL; xfree(p); } - else if (fwd) + else if (fwd) av[i - fwd] = av[i]; if (fwd) av[i - fwd] = av[i]; } return blklen(*v); } /* end t_glob */ /* c_glob(): * Return a list of commands that match the pattern */ static int c_glob(Char ***v) { struct blk_buf av = BLK_BUF_INIT; struct Strbuf cmd = Strbuf_INIT, dir = Strbuf_INIT; Char *pat = **v; int flag; if (pat == NULL) return (0); cleanup_push(&av, bb_cleanup); cleanup_push(&cmd, Strbuf_cleanup); cleanup_push(&dir, Strbuf_cleanup); tw_cmd_start(NULL, NULL); while (cmd.len = 0, tw_cmd_next(&cmd, &dir, &flag) != 0) { Strbuf_terminate(&cmd); if (Gmatch(cmd.s, pat)) bb_append(&av, Strsave(cmd.s)); } tw_dir_end(); *v = bb_finish(&av); cleanup_ignore(&av); cleanup_until(&av); return av.len; } /* end c_glob */ /* insert_meta(): * change the word before the cursor. * cp must point to the start of the unquoted word. * cpend to the end of it. * word is the text that has to be substituted. * strategy: * try to keep all the quote characters of the user's input. * change quote type only if necessary. */ static int insert_meta(const Char *cp, const Char *cpend, const Char *word, int closequotes) { struct Strbuf buffer = Strbuf_INIT; Char *bptr; const Char *wptr; int in_sync = (cp != NULL); Char qu = 0; int ndel = (int) (cp ? cpend - cp : 0); Char w, wq; int res; for (wptr = word;;) { if (cp >= cpend) in_sync = 0; if (in_sync && !cmap(qu, _ESC) && cmap(*cp, _QF|_ESC)) if (qu == 0 || qu == *cp) { qu ^= *cp; Strbuf_append1(&buffer, *cp++); continue; } w = *wptr; if (w == 0) break; wq = w & QUOTE; #if INVALID_BYTE != 0 /* add checking INVALID_BYTE for FIX UTF32 */ if ((w & INVALID_BYTE) != INVALID_BYTE) /* w < INVALID_BYTE */ #endif w &= ~QUOTE; if (cmap(w, _ESC | _QF)) wq = QUOTE; /* quotes are always quoted */ if (!wq && qu && tricky(w) && !(qu == '\"' && tricky_dq(w))) { /* We have to unquote the character */ in_sync = 0; if (cmap(qu, _ESC)) buffer.s[buffer.len - 1] = w; else { Strbuf_append1(&buffer, qu); Strbuf_append1(&buffer, w); if (wptr[1] == 0) qu = 0; else Strbuf_append1(&buffer, qu); } } else if (qu && w == qu) { in_sync = 0; if (buffer.len != 0 && buffer.s[buffer.len - 1] == qu) { /* User misunderstanding :) */ buffer.s[buffer.len - 1] = '\\'; Strbuf_append1(&buffer, w); qu = 0; } else { Strbuf_append1(&buffer, qu); Strbuf_append1(&buffer, '\\'); Strbuf_append1(&buffer, w); Strbuf_append1(&buffer, qu); } } else if (wq && qu == '\"' && tricky_dq(w)) { in_sync = 0; Strbuf_append1(&buffer, qu); Strbuf_append1(&buffer, '\\'); Strbuf_append1(&buffer, w); Strbuf_append1(&buffer, qu); } else if (wq && ((!qu && (tricky(w) || (w == HISTSUB && HISTSUB != '\0' && buffer.len == 0))) || (!cmap(qu, _ESC) && w == HIST && HIST != '\0'))) { in_sync = 0; Strbuf_append1(&buffer, '\\'); Strbuf_append1(&buffer, w); } else { if (in_sync && *cp++ != w) in_sync = 0; Strbuf_append1(&buffer, w); } wptr++; if (cmap(qu, _ESC)) qu = 0; } if (closequotes && qu && !cmap(qu, _ESC)) Strbuf_append1(&buffer, w); bptr = Strbuf_finish(&buffer); if (ndel) DeleteBack(ndel); res = InsertStr(bptr); xfree(bptr); return res; } /* end insert_meta */ /* is_prefix(): * return true if check matches initial chars in template * This differs from PWB imatch in that if check is null * it matches anything */ static int is_prefix(Char *check, Char *template) { for (; *check; check++, template++) if ((*check & TRIM) != (*template & TRIM)) return (FALSE); return (TRUE); } /* end is_prefix */ /* is_prefixmatch(): * return true if check matches initial chars in template * This differs from PWB imatch in that if check is null * it matches anything * and matches on shortening of commands */ static int is_prefixmatch(Char *check, Char *template, int enhanced) { Char MCH1, MCH2, LCH1, LCH2; for (; *check; check++, template++) { if ((*check & TRIM) != (*template & TRIM)) { MCH1 = (*check & TRIM); MCH2 = (*template & TRIM); - LCH1 = Isupper(MCH1) ? Tolower(MCH1) : + LCH1 = Isupper(MCH1) ? Tolower(MCH1) : enhanced == 2 && MCH1 == '_' ? '-' : MCH1; LCH2 = Isupper(MCH2) ? Tolower(MCH2) : enhanced == 2 && MCH2 == '_' ? '-' : MCH2; if (MCH1 != MCH2 && MCH1 != LCH2 && (LCH1 != MCH2 || enhanced == 2)) { - if (enhanced && ((*check & TRIM) == '-' || + if (enhanced && ((*check & TRIM) == '-' || (*check & TRIM) == '.' || (*check & TRIM) == '_')) { MCH1 = MCH2 = (*check & TRIM); if (MCH1 == '_' && enhanced != 2) { MCH2 = '-'; } else if (MCH1 == '-') { MCH2 = '_'; } for (; *template && (*template & TRIM) != MCH1 && (*template & TRIM) != MCH2; template++) continue; if (!*template) { return (FALSE); } } else { return (FALSE); } } } } return (TRUE); } /* end is_prefixmatch */ /* is_suffix(): * Return true if the chars in template appear at the * end of check, I.e., are it's suffix. */ static int is_suffix(Char *check, Char *template) { Char *t, *c; t = Strend(template); c = Strend(check); for (;;) { if (t == template) return 1; if (c == check || (*--t & TRIM) != (*--c & TRIM)) return 0; } } /* end is_suffix */ /* ignored(): * Return true if this is an ignored item */ static int ignored(Char *item) { struct varent *vp; Char **cp; if ((vp = adrof(STRfignore)) == NULL || (cp = vp->vec) == NULL) return (FALSE); for (; *cp != NULL; cp++) if (is_suffix(item, *cp)) return (TRUE); return (FALSE); } /* end ignored */ /* starting_a_command(): * return true if the command starting at wordstart is a command */ int starting_a_command(Char *wordstart, Char *inputline) { Char *ptr, *ncmdstart; int count, bsl; static Char cmdstart[] = {'`', ';', '&', '(', '|', '\0'}, cmdalive[] = {' ', '\t', '\'', '"', '<', '>', '\0'}; /* * Find if the number of backquotes is odd or even. */ for (ptr = wordstart, count = 0; ptr >= inputline; count += (*ptr-- == '`')) continue; /* * if the number of backquotes is even don't include the backquote char in * the list of command starting delimiters [if it is zero, then it does not * matter] */ ncmdstart = cmdstart + EVEN(count); /* * look for the characters previous to this word if we find a command * starting delimiter we break. if we find whitespace and another previous * word then we are not a command - * + * * count is our state machine: 0 looking for anything 1 found white-space * looking for non-ws */ for (count = 0; wordstart >= inputline; wordstart--) { if (*wordstart == '\0') continue; if (Strchr(ncmdstart, *wordstart)) { for (ptr = wordstart, bsl = 0; *(--ptr) == '\\'; bsl++); if (bsl & 1) { wordstart--; continue; } else break; } /* * found white space */ if ((ptr = Strchr(cmdalive, *wordstart)) != NULL) count = 1; if (count == 1 && !ptr) return (FALSE); } if (wordstart > inputline) switch (*wordstart) { case '&': /* Look for >& */ while (wordstart > inputline && (*--wordstart == ' ' || *wordstart == '\t')) continue; if (*wordstart == '>') return (FALSE); break; case '(': /* check for foreach, if etc. */ while (wordstart > inputline && (*--wordstart == ' ' || *wordstart == '\t')) continue; if (!iscmdmeta(*wordstart) && (*wordstart != ' ' && *wordstart != '\t')) return (FALSE); break; default: break; } return (TRUE); } /* end starting_a_command */ /* recognize(): * Object: extend what user typed up to an ambiguity. * Algorithm: * On first match, copy full item (assume it'll be the only match) * On subsequent matches, shorten exp_name to the first * character mismatch between exp_name and item. * If we shorten it back to the prefix length, stop searching. */ static int recognize(struct Strbuf *exp_name, const Char *item, size_t name_length, int numitems, int enhanced, int igncase) { Char MCH1, MCH2, LCH1, LCH2; Char *x; const Char *ent; size_t len = 0; if (numitems == 1) { /* 1st match */ exp_name->len = 0; Strbuf_append(exp_name, item); Strbuf_terminate(exp_name); return (0); } if (!enhanced && !igncase) { for (x = exp_name->s, ent = item; *x && (*x & TRIM) == (*ent & TRIM); x++, ent++) len++; } else { for (x = exp_name->s, ent = item; *x; x++, ent++) { MCH1 = *x & TRIM; MCH2 = *ent & TRIM; LCH1 = Isupper(MCH1) ? Tolower(MCH1) : MCH1; LCH2 = Isupper(MCH2) ? Tolower(MCH2) : MCH2; if (MCH1 != MCH2) { if (LCH1 == MCH2 || (MCH1 == '_' && MCH2 == '-')) *x = *ent; else if (LCH1 != LCH2) break; } len++; } } *x = '\0'; /* Shorten at 1st char diff */ exp_name->len = x - exp_name->s; if (!(match_unique_match || is_set(STRrecexact) || (enhanced && *ent)) && len == name_length) /* Ambiguous to prefix? */ return (-1); /* So stop now and save time */ return (0); } /* end recognize */ /* tw_collect_items(): * Collect items that match target. * SPELL command: * Returns the spelling distance of the closest match. * else * Returns the number of items found. * If none found, but some ignored items were found, * It returns the -number of ignored items. */ static int tw_collect_items(COMMAND command, int looking, struct Strbuf *exp_dir, struct Strbuf *exp_name, Char *target, const Char *pat, int flags) { int done = FALSE; /* Search is done */ int showdots; /* Style to show dot files */ int nignored = 0; /* Number of fignored items */ int numitems = 0; /* Number of matched items */ size_t name_length = Strlen(target); /* Length of prefix (file name) */ int exec_check = flags & TW_EXEC_CHK;/* need to check executability */ int dir_check = flags & TW_DIR_CHK; /* Need to check for directories */ int text_check = flags & TW_TEXT_CHK;/* Need to check for non-directories */ int dir_ok = flags & TW_DIR_OK; /* Ignore directories? */ int gpat = flags & TW_PAT_OK; /* Match against a pattern */ int ignoring = flags & TW_IGN_OK; /* Use fignore? */ int d = 4, nd; /* Spelling distance */ Char **cp; Char *ptr; struct varent *vp; struct Strbuf buf = Strbuf_INIT, item = Strbuf_INIT; int enhanced = 0; int cnt = 0; int igncase = 0; flags = 0; showdots = DOT_NONE; if ((ptr = varval(STRlistflags)) != STRNULL) - while (*ptr) + while (*ptr) switch (*ptr++) { case 'a': showdots = DOT_ALL; break; case 'A': showdots = DOT_NOT; break; default: break; } if (looking == TW_COMMAND && (vp = adrof(STRautorehash)) != NULL && vp->vec != NULL) for (cp = vp->vec; *cp; cp++) if (Strcmp(*cp, STRalways) == 0 || (Strcmp(*cp, STRcorrect) == 0 && command == SPELL) || (Strcmp(*cp, STRcomplete) == 0 && command != SPELL)) { tw_cmd_free(); tw_cmd_start(NULL, NULL); break; } cleanup_push(&item, Strbuf_cleanup); cleanup_push(&buf, Strbuf_cleanup); while (!done && (item.len = 0, tw_next_entry[looking](&item, exp_dir, &flags) != 0)) { Strbuf_terminate(&item); #ifdef TDEBUG xprintf("item = %S\n", item.s); #endif switch (looking) { case TW_FILE: case TW_DIRECTORY: case TW_TEXT: /* * Don't match . files on null prefix match */ if (showdots == DOT_NOT && (ISDOT(item.s) || ISDOTDOT(item.s))) done = TRUE; if (name_length == 0 && item.s[0] == '.' && showdots == DOT_NONE) done = TRUE; break; case TW_COMMAND: #if defined(_UWIN) || defined(__CYGWIN__) /* * Turn foo.{exe,com,bat,cmd} into foo since UWIN's readdir returns * the file with the .exe, .com, .bat, .cmd extension * * Same for Cygwin, but only for .exe and .com extension. */ { #ifdef __CYGWIN__ static const char *rext[] = { ".exe", ".com" }; #else static const char *rext[] = { ".exe", ".bat", ".com", ".cmd" }; #endif size_t exti = Strlen(item.s); if (exti > 4) { char *ext = short2str(&item.s[exti -= 4]); size_t i; for (i = 0; i < sizeof(rext) / sizeof(rext[0]); i++) if (strcasecmp(ext, rext[i]) == 0) { item.len = exti; Strbuf_terminate(&item); break; } } } #endif /* _UWIN || __CYGWIN__ */ exec_check = flags & TW_EXEC_CHK; dir_ok = flags & TW_DIR_OK; break; default: break; } if (done) { done = FALSE; continue; } switch (command) { case SPELL: /* correct the spelling of the last bit */ if (name_length == 0) {/* zero-length word can't be misspelled */ exp_name->len = 0; /* (not trying is important for ~) */ Strbuf_terminate(exp_name); d = 0; done = TRUE; break; } if (gpat && !Gmatch(item.s, pat)) break; /* * Swapped the order of the spdist() arguments as suggested * by eeide@asylum.cs.utah.edu (Eric Eide) */ nd = spdist(target, item.s); /* test the item against original */ if (nd <= d && nd != 4) { if (!(exec_check && !executable(exp_dir->s, item.s, dir_ok))) { exp_name->len = 0; Strbuf_append(exp_name, item.s); Strbuf_terminate(exp_name); d = nd; if (d == 0) /* if found it exactly */ done = TRUE; } } else if (nd == 4) { if (spdir(exp_name, exp_dir->s, item.s, target)) { if (exec_check && !executable(exp_dir->s, exp_name->s, dir_ok)) break; #ifdef notdef /* * We don't want to stop immediately, because * we might find an exact/better match later. */ d = 0; done = TRUE; #endif d = 3; } } break; case LIST: case RECOGNIZE: case RECOGNIZE_ALL: case RECOGNIZE_SCROLL: if ((vp = adrof(STRcomplete)) != NULL && vp->vec != NULL) for (cp = vp->vec; *cp; cp++) { if (Strcmp(*cp, STREnhance) == 0) enhanced = 2; else if (Strcmp(*cp, STRigncase) == 0) igncase = 1; else if (Strcmp(*cp, STRenhance) == 0) enhanced = 1; } if (enhanced || igncase) { if (!is_prefixmatch(target, item.s, enhanced)) break; } else { if (!is_prefix(target, item.s)) break; } if (exec_check && !executable(exp_dir->s, item.s, dir_ok)) break; if (dir_check && !isadirectory(exp_dir->s, item.s)) break; if (text_check && isadirectory(exp_dir->s, item.s)) break; /* * Only pattern match directories if we're checking * for directories. */ if (gpat && !Gmatch(item.s, pat) && (dir_check || !isadirectory(exp_dir->s, item.s))) break; /* * Remove duplicates in command listing and completion * AFEB added code for TW_LOGNAME and TW_USER cases */ if (looking == TW_COMMAND || looking == TW_LOGNAME || looking == TW_USER || command == LIST) { buf.len = 0; Strbuf_append(&buf, item.s); switch (looking) { case TW_COMMAND: if (!(dir_ok && exec_check)) break; if (filetype(exp_dir->s, item.s) == '/') Strbuf_append1(&buf, '/'); break; case TW_FILE: case TW_DIRECTORY: Strbuf_append1(&buf, filetype(exp_dir->s, item.s)); break; default: break; } Strbuf_terminate(&buf); if ((looking == TW_COMMAND || looking == TW_USER || looking == TW_LOGNAME) && tw_item_find(buf.s)) break; else { /* maximum length 1 (NULL) + 1 (~ or $) + 1 (filetype) */ tw_item_add(&buf); if (command == LIST) numitems++; } } - + if (command == RECOGNIZE || command == RECOGNIZE_ALL || command == RECOGNIZE_SCROLL) { if (ignoring && ignored(item.s)) { nignored++; break; } else if (command == RECOGNIZE_SCROLL) { add_scroll_tab(item.s); cnt++; } if (match_unique_match || is_set(STRrecexact)) { if (StrQcmp(target, item.s) == 0) { /* EXACT match */ exp_name->len = 0; Strbuf_append(exp_name, item.s); Strbuf_terminate(exp_name); numitems = 1; /* fake into expanding */ non_unique_match = TRUE; done = TRUE; break; } } if (recognize(exp_name, item.s, name_length, ++numitems, enhanced, igncase)) if (command != RECOGNIZE_SCROLL) done = TRUE; if (enhanced && exp_name->len < name_length) { exp_name->len = 0; Strbuf_append(exp_name, target); Strbuf_terminate(exp_name); } } break; default: break; } #ifdef TDEBUG xprintf("done item = %S\n", item.s); #endif } cleanup_until(&item); if (command == RECOGNIZE_SCROLL) { if ((cnt <= curchoice) || (curchoice == -1)) { curchoice = -1; nignored = 0; numitems = 0; } else if (numitems > 1) { if (curchoice < -1) curchoice = cnt - 1; choose_scroll_tab(exp_name, cnt); numitems = 1; } } free_scroll_tab(); if (command == SPELL) return d; else { - if (ignoring && numitems == 0 && nignored > 0) + if (ignoring && numitems == 0 && nignored > 0) return -nignored; else return numitems; } } /* tw_suffix(): * Find and return the appropriate suffix character */ /*ARGSUSED*/ static Char tw_suffix(int looking, struct Strbuf *word, const Char *exp_dir, Char *exp_name) { Char *ptr; Char *dol; struct varent *vp; (void) strip(exp_name); switch (looking) { case TW_LOGNAME: return '/'; case TW_VARIABLE: /* * Don't consider array variables or empty variables */ if ((vp = adrof(exp_name)) != NULL && vp->vec != NULL) { if ((ptr = vp->vec[0]) == NULL || *ptr == '\0' || - vp->vec[1] != NULL) + vp->vec[1] != NULL) return ' '; } else if ((ptr = tgetenv(exp_name)) == NULL || *ptr == '\0') return ' '; - if ((dol = Strrchr(word->s, '$')) != 0 && + if ((dol = Strrchr(word->s, '$')) != 0 && dol[1] == '{' && Strchr(dol, '}') == NULL) return '}'; return isadirectory(exp_dir, ptr) ? '/' : ' '; case TW_DIRECTORY: return '/'; case TW_COMMAND: case TW_FILE: return isadirectory(exp_dir, exp_name) ? '/' : ' '; case TW_ALIAS: case TW_VARLIST: case TW_WORDLIST: case TW_SHELLVAR: case TW_ENVVAR: case TW_USER: case TW_BINDING: case TW_LIMIT: case TW_SIGNAL: case TW_JOB: case TW_COMPLETION: case TW_TEXT: case TW_GRPNAME: return ' '; default: return '\0'; } } /* end tw_suffix */ /* tw_fixword(): * Repair a word after a spalling or a recognizwe */ static void tw_fixword(int looking, struct Strbuf *word, Char *dir, Char *exp_name) { Char *ptr; switch (looking) { case TW_LOGNAME: word->len = 0; Strbuf_append1(word, '~'); break; case TW_VARIABLE: if ((ptr = Strrchr(word->s, '$')) != NULL) { if (ptr[1] == '{') ptr++; word->len = ptr + 1 - word->s; /* Delete after the dollar */ } else word->len = 0; break; case TW_DIRECTORY: case TW_FILE: case TW_TEXT: word->len = 0; Strbuf_append(word, dir); /* put back dir part */ break; default: word->len = 0; break; } (void) quote(exp_name); Strbuf_append(word, exp_name); /* add extended name */ Strbuf_terminate(word); } /* end tw_fixword */ /* tw_collect(): * Collect items. Return -1 in case we were interrupted or * the return value of tw_collect * This is really a wrapper for tw_collect_items, serving two * purposes: * 1. Handles interrupt cleanups. * 2. Retries if we had no matches, but there were ignored matches */ static int tw_collect(COMMAND command, int looking, struct Strbuf *exp_dir, struct Strbuf *exp_name, Char *target, Char *pat, int flags, DIR *dir_fd) { volatile int ni; jmp_buf_t osetexit; #ifdef TDEBUG xprintf("target = %S\n", target); #endif ni = 0; getexit(osetexit); for (;;) { volatile size_t omark; (*tw_start_entry[looking])(dir_fd, pat); InsideCompletion = 1; if (setexit()) { cleanup_pop_mark(omark); resexit(osetexit); /* interrupted, clean up */ haderr = 0; ni = -1; /* flag error */ break; } omark = cleanup_push_mark(); ni = tw_collect_items(command, looking, exp_dir, exp_name, target, pat, ni >= 0 ? flags : flags & ~TW_IGN_OK); cleanup_pop_mark(omark); resexit(osetexit); if (ni >= 0) break; } InsideCompletion = 0; #if defined(SOLARIS2) && defined(i386) && !defined(__GNUC__) /* Compiler bug? (from PWP) */ if ((looking == TW_LOGNAME) || (looking == TW_USER)) tw_logname_end(); else if (looking == TW_GRPNAME) tw_grpname_end(); else tw_dir_end(); #else /* !(SOLARIS2 && i386 && !__GNUC__) */ (*tw_end_entry[looking])(); #endif /* !(SOLARIS2 && i386 && !__GNUC__) */ return(ni); } /* end tw_collect */ /* tw_list_items(): * List the items that were found * * NOTE instead of looking at numerical vars listmax and listmaxrows * we can look at numerical var listmax, and have a string value * listmaxtype (or similar) than can have values 'items' and 'rows' * (by default interpreted as 'items', for backwards compatibility) */ static void tw_list_items(int looking, int numitems, int list_max) { Char *ptr; int max_items = 0; int max_rows = 0; if (numitems == 0) return; if ((ptr = varval(STRlistmax)) != STRNULL) { while (*ptr) { if (!Isdigit(*ptr)) { max_items = 0; break; } max_items = max_items * 10 + *ptr++ - '0'; } if ((max_items > 0) && (numitems > max_items) && list_max) max_items = numitems; else max_items = 0; } if (max_items == 0 && (ptr = varval(STRlistmaxrows)) != STRNULL) { int rows; while (*ptr) { if (!Isdigit(*ptr)) { max_rows = 0; break; } max_rows = max_rows * 10 + *ptr++ - '0'; } if (max_rows != 0 && looking != TW_JOB) rows = find_rows(tw_item_get(), numitems, TRUE); else rows = numitems; /* underestimate for lines wider than the termH */ if ((max_rows > 0) && (rows > max_rows) && list_max) max_rows = rows; else max_rows = 0; } if (max_items || max_rows) { char tc, *sname; const char *name; int maxs; if (max_items) { name = CGETS(30, 5, "items"); maxs = max_items; } else { name = CGETS(30, 6, "rows"); maxs = max_rows; } sname = strsave(name); cleanup_push(sname, xfree); xprintf(CGETS(30, 7, "There are %d %s, list them anyway? [n/y] "), maxs, sname); cleanup_until(sname); flush(); /* We should be in Rawmode here, so no \n to catch */ (void) xread(SHIN, &tc, 1); xprintf("%c\r\n", tc); /* echo the char, do a newline */ /* * Perhaps we should use the yesexpr from the * actual locale */ if (strchr(CGETS(30, 13, "Yy"), tc) == NULL) return; } if (looking != TW_SIGNAL) qsort(tw_item_get(), numitems, sizeof(Char *), fcompare); if (looking != TW_JOB) print_by_column(STRNULL, tw_item_get(), numitems, TRUE); else { /* * print one item on every line because jobs can have spaces * and it is confusing. */ int i; Char **w = tw_item_get(); for (i = 0; i < numitems; i++) { xprintf("%S", w[i]); if (Tty_raw_mode) xputchar('\r'); xputchar('\n'); } } } /* end tw_list_items */ /* t_search(): * Perform a RECOGNIZE, LIST or SPELL command on string "word". * * Return value: * >= 0: SPELL command: "distance" (see spdist()) * other: No. of items found * < 0: Error (message or beep is output) */ /*ARGSUSED*/ int t_search(struct Strbuf *word, COMMAND command, int looking, int list_max, Char *pat, eChar suf) { int numitems, /* Number of items matched */ flags = 0, /* search flags */ gpat = pat[0] != '\0', /* Glob pattern search */ res; /* Return value */ struct Strbuf exp_dir = Strbuf_INIT;/* dir after ~ expansion */ struct Strbuf dir = Strbuf_INIT; /* /x/y/z/ part in /x/y/z/f */ struct Strbuf exp_name = Strbuf_INIT;/* the recognized (extended) */ Char *name, /* f part in /d/d/d/f name */ *target; /* Target to expand/correct/list */ DIR *dir_fd = NULL; /* * bugfix by Marty Grossman (grossman@CC5.BBN.COM): directory listing can * dump core when interrupted */ tw_item_free(); non_unique_match = FALSE; /* See the recexact code below */ extract_dir_and_name(word->s, &dir, &name); cleanup_push(&dir, Strbuf_cleanup); cleanup_push(&name, xfree_indirect); /* * SPECIAL HARDCODED COMPLETIONS: * foo$variable -> TW_VARIABLE * ~user -> TW_LOGNAME * */ if ((*word->s == '~') && (Strchr(word->s, '/') == NULL)) { looking = TW_LOGNAME; target = name; gpat = 0; /* Override pattern mechanism */ } - else if ((target = Strrchr(name, '$')) != 0 && + else if ((target = Strrchr(name, '$')) != 0 && (target[1] != '{' || Strchr(target, '}') == NULL) && (Strchr(name, '/') == NULL)) { target++; if (target[0] == '{') target++; looking = TW_VARIABLE; gpat = 0; /* Override pattern mechanism */ } else target = name; /* * Try to figure out what we should be looking for */ if (looking & TW_PATH) { gpat = 0; /* pattern holds the pathname to be used */ Strbuf_append(&exp_dir, pat); if (exp_dir.len != 0 && exp_dir.s[exp_dir.len - 1] != '/') Strbuf_append1(&exp_dir, '/'); Strbuf_append(&exp_dir, dir.s); } Strbuf_terminate(&exp_dir); cleanup_push(&exp_dir, Strbuf_cleanup); switch (looking & ~TW_PATH) { case TW_NONE: res = -1; goto err_dir; case TW_ZERO: looking = TW_FILE; break; case TW_COMMAND: if (Strchr(word->s, '/') || (looking & TW_PATH)) { looking = TW_FILE; flags |= TW_EXEC_CHK; flags |= TW_DIR_OK; } #ifdef notdef /* PWP: don't even bother when doing ALL of the commands */ if (looking == TW_COMMAND && word->len == 0) { res = -1; goto err_dir; } #endif break; case TW_VARLIST: case TW_WORDLIST: gpat = 0; /* pattern holds the name of the variable */ break; case TW_EXPLAIN: if (command == LIST && pat != NULL) { xprintf("%S", pat); if (Tty_raw_mode) xputchar('\r'); xputchar('\n'); } res = 2; goto err_dir; default: break; } /* * let fignore work only when we are not using a pattern */ flags |= (gpat == 0) ? TW_IGN_OK : TW_PAT_OK; #ifdef TDEBUG xprintf(CGETS(30, 8, "looking = %d\n"), looking); #endif switch (looking) { Char *user_name; case TW_ALIAS: case TW_SHELLVAR: case TW_ENVVAR: case TW_BINDING: case TW_LIMIT: case TW_SIGNAL: case TW_JOB: case TW_COMPLETION: case TW_GRPNAME: break; case TW_VARIABLE: if ((res = expand_dir(dir.s, &exp_dir, &dir_fd, command)) != 0) goto err_dir; break; case TW_DIRECTORY: flags |= TW_DIR_CHK; #ifdef notyet /* * This is supposed to expand the directory stack. * Problems: * 1. Slow * 2. directories with the same name */ flags |= TW_DIR_OK; #endif #ifdef notyet /* * Supposed to do delayed expansion, but it is inconsistent * from a user-interface point of view, since it does not * immediately obey addsuffix */ if ((res = expand_dir(dir.s, &exp_dir, &dir_fd, command)) != 0) goto err_dir; if (isadirectory(exp_dir.s, name)) { if (exp_dir.len != 0 || name[0] != '\0') { Strbuf_append(&dir, name); if (dir.s[dir.len - 1] != '/') Strbuf_append1(&dir, '/'); Strbuf_terminate(&dir); if ((res = expand_dir(dir.s, &exp_dir, &dir_fd, command)) != 0) goto err_dir; if (word->len != 0 && word->s[word->len - 1] != '/') { Strbuf_append1(word, '/'); Strbuf_terminate(word); } name[0] = '\0'; } } #endif if ((res = expand_dir(dir.s, &exp_dir, &dir_fd, command)) != 0) goto err_dir; break; case TW_TEXT: flags |= TW_TEXT_CHK; /*FALLTHROUGH*/ case TW_FILE: if ((res = expand_dir(dir.s, &exp_dir, &dir_fd, command)) != 0) goto err_dir; break; case TW_PATH | TW_TEXT: case TW_PATH | TW_FILE: case TW_PATH | TW_DIRECTORY: case TW_PATH | TW_COMMAND: if ((dir_fd = opendir(short2str(exp_dir.s))) == NULL) { if (command == RECOGNIZE) xprintf("\n"); xprintf("%S: %s", exp_dir.s, strerror(errno)); if (command != RECOGNIZE) xprintf("\n"); NeedsRedraw = 1; res = -1; goto err_dir; } if (exp_dir.len != 0 && exp_dir.s[exp_dir.len - 1] != '/') { Strbuf_append1(&exp_dir, '/'); Strbuf_terminate(&exp_dir); } looking &= ~TW_PATH; switch (looking) { case TW_TEXT: flags |= TW_TEXT_CHK; break; case TW_FILE: break; case TW_DIRECTORY: flags |= TW_DIR_CHK; break; case TW_COMMAND: xfree(name); target = name = Strsave(word->s); /* so it can match things */ break; default: abort(); /* Cannot happen */ break; } break; case TW_LOGNAME: user_name = word->s + 1; goto do_user; /*FALLTHROUGH*/ case TW_USER: user_name = word->s; do_user: /* * Check if the spelling was already correct * From: Rob McMahon */ if (command == SPELL && xgetpwnam(short2str(user_name)) != NULL) { #ifdef YPBUGS fix_yp_bugs(); #endif /* YPBUGS */ res = 0; goto err_dir; } xfree(name); target = name = Strsave(user_name); break; case TW_COMMAND: case TW_VARLIST: case TW_WORDLIST: target = name = Strsave(word->s); /* so it can match things */ break; default: xprintf(CGETS(30, 9, "\n%s internal error: I don't know what I'm looking for!\n"), progname); NeedsRedraw = 1; res = -1; goto err_dir; } cleanup_push(&exp_name, Strbuf_cleanup); numitems = tw_collect(command, looking, &exp_dir, &exp_name, target, pat, flags, dir_fd); if (numitems == -1) goto end; switch (command) { case RECOGNIZE: case RECOGNIZE_ALL: case RECOGNIZE_SCROLL: - if (numitems <= 0) + if (numitems <= 0) break; Strbuf_terminate(&exp_name); tw_fixword(looking, word, dir.s, exp_name.s); if (!match_unique_match && is_set(STRaddsuffix) && numitems == 1) { switch (suf) { case 0: /* Automatic suffix */ Strbuf_append1(word, tw_suffix(looking, word, exp_dir.s, exp_name.s)); break; case CHAR_ERR: /* No suffix */ break; default: /* completion specified suffix */ Strbuf_append1(word, suf); break; } Strbuf_terminate(word); } break; case LIST: tw_list_items(looking, numitems, list_max); tw_item_free(); break; case SPELL: Strbuf_terminate(&exp_name); tw_fixword(looking, word, dir.s, exp_name.s); break; default: xprintf("Bad tw_command\n"); numitems = 0; } end: res = numitems; err_dir: cleanup_until(&dir); return res; } /* end t_search */ /* extract_dir_and_name(): * parse full path in file into 2 parts: directory and file names * Should leave final slash (/) at end of dir. */ static void extract_dir_and_name(const Char *path, struct Strbuf *dir, Char **name) { Char *p; p = Strrchr(path, '/'); #ifdef WINNT_NATIVE if (p == NULL) p = Strrchr(path, ':'); #endif /* WINNT_NATIVE */ if (p == NULL) *name = Strsave(path); else { p++; *name = Strsave(p); Strbuf_appendn(dir, path, p - path); } Strbuf_terminate(dir); } /* end extract_dir_and_name */ /* dollar(): * expand "/$old1/$old2/old3/" * to "/value_of_old1/value_of_old2/old3/" */ Char * dollar(const Char *old) { struct Strbuf buf = Strbuf_INIT; while (*old) { if (*old != '$') Strbuf_append1(&buf, *old++); else { if (expdollar(&buf, &old, QUOTE) == 0) { xfree(buf.s); return NULL; } } } return Strbuf_finish(&buf); } /* end dollar */ /* tilde(): * expand ~person/foo to home_directory_of_person/foo * or = to */ static int tilde(struct Strbuf *new, Char *old) { Char *o, *p; new->len = 0; switch (old[0]) { case '~': { Char *name, *home; old++; for (o = old; *o && *o != '/'; o++) continue; name = Strnsave(old, o - old); home = gethdir(name); xfree(name); if (home == NULL) goto err; Strbuf_append(new, home); xfree(home); /* If the home directory expands to "/", we do * not want to create "//" by appending a slash from o. */ if (new->s[0] == '/' && new->len == 1 && *o == '/') ++o; Strbuf_append(new, o); break; } case '=': if ((p = globequal(old)) == NULL) goto err; if (p != old) { Strbuf_append(new, p); xfree(p); break; } /*FALLTHROUGH*/ default: Strbuf_append(new, old); break; } Strbuf_terminate(new); return 0; err: Strbuf_terminate(new); return -1; } /* end tilde */ /* expand_dir(): * Open the directory given, expanding ~user and $var * Optionally normalize the path given */ static int expand_dir(const Char *dir, struct Strbuf *edir, DIR **dfd, COMMAND cmd) { Char *nd = NULL; Char *tdir; tdir = dollar(dir); cleanup_push(tdir, xfree); if (tdir == NULL || (tilde(edir, tdir) != 0) || !(nd = dnormalize(edir->len ? edir->s : STRdot, symlinks == SYM_IGNORE || symlinks == SYM_EXPAND)) || ((*dfd = opendir(short2str(nd))) == NULL)) { xfree(nd); if (cmd == SPELL || SearchNoDirErr) { cleanup_until(tdir); return (-2); } /* * From: Amos Shapira * Print a better message when completion fails */ xprintf("\n%S %s\n", edir->len ? edir->s : (tdir ? tdir : dir), (errno == ENOTDIR ? CGETS(30, 10, "not a directory") : (errno == ENOENT ? CGETS(30, 11, "not found") : CGETS(30, 12, "unreadable")))); NeedsRedraw = 1; cleanup_until(tdir); return (-1); } cleanup_until(tdir); if (nd) { if (*dir != '\0') { int slash; /* * Copy and append a / if there was one */ slash = edir->len != 0 && edir->s[edir->len - 1] == '/'; edir->len = 0; Strbuf_append(edir, nd); if (slash != 0 && edir->s[edir->len - 1] != '/') Strbuf_append1(edir, '/'); Strbuf_terminate(edir); } xfree(nd); } return 0; } /* end expand_dir */ /* nostat(): * Returns true if the directory should not be stat'd, * false otherwise. * This way, things won't grind to a halt when you complete in /afs * or very large directories. */ static int nostat(Char *dir) { struct varent *vp; Char **cp; if ((vp = adrof(STRnostat)) == NULL || (cp = vp->vec) == NULL) return FALSE; for (; *cp != NULL; cp++) { if (Strcmp(*cp, STRstar) == 0) return TRUE; if (Gmatch(dir, *cp)) return TRUE; } return FALSE; } /* end nostat */ /* filetype(): * Return a character that signifies a filetype * symbology from 4.3 ls command. */ static Char filetype(Char *dir, Char *file) { if (dir) { Char *path; char *ptr; struct stat statb; if (nostat(dir)) return(' '); path = Strspl(dir, file); ptr = short2str(path); xfree(path); if (lstat(ptr, &statb) != -1) { #ifdef S_ISLNK if (S_ISLNK(statb.st_mode)) { /* Symbolic link */ if (adrof(STRlistlinks)) { if (stat(ptr, &statb) == -1) return ('&'); else if (S_ISDIR(statb.st_mode)) return ('>'); else return ('@'); } else return ('@'); } #endif #ifdef S_ISSOCK if (S_ISSOCK(statb.st_mode)) /* Socket */ return ('='); #endif #ifdef S_ISFIFO if (S_ISFIFO(statb.st_mode)) /* Named Pipe */ return ('|'); #endif #ifdef S_ISHIDDEN if (S_ISHIDDEN(statb.st_mode)) /* Hidden Directory [aix] */ return ('+'); #endif #ifdef S_ISCDF { struct stat hpstatb; char *p2; p2 = strspl(ptr, "+"); /* Must append a '+' and re-stat(). */ if ((stat(p2, &hpstatb) != -1) && S_ISCDF(hpstatb.st_mode)) { xfree(p2); return ('+'); /* Context Dependent Files [hpux] */ } xfree(p2); } #endif #ifdef S_ISNWK if (S_ISNWK(statb.st_mode)) /* Network Special [hpux] */ return (':'); #endif #ifdef S_ISCHR if (S_ISCHR(statb.st_mode)) /* char device */ return ('%'); #endif #ifdef S_ISBLK if (S_ISBLK(statb.st_mode)) /* block device */ return ('#'); #endif #ifdef S_ISDIR if (S_ISDIR(statb.st_mode)) /* normal Directory */ return ('/'); #endif if (statb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) return ('*'); } } return (' '); } /* end filetype */ /* isadirectory(): * Return trus if the file is a directory */ static int isadirectory(const Char *dir, const Char *file) /* return 1 if dir/file is a directory */ /* uses stat rather than lstat to get dest. */ { if (dir) { Char *path; char *cpath; struct stat statb; path = Strspl(dir, file); cpath = short2str(path); xfree(path); if (stat(cpath, &statb) >= 0) { /* resolve through symlink */ #ifdef S_ISSOCK if (S_ISSOCK(statb.st_mode)) /* Socket */ return 0; #endif #ifdef S_ISFIFO if (S_ISFIFO(statb.st_mode)) /* Named Pipe */ return 0; #endif if (S_ISDIR(statb.st_mode)) /* normal Directory */ return 1; } } return 0; } /* end isadirectory */ /* find_rows(): * Return how many rows needed to print sorted down columns */ static int find_rows(Char *items[], int count, int no_file_suffix) { int i, columns, rows; unsigned int maxwidth = 0; for (i = 0; i < count; i++) /* find widest string */ maxwidth = max(maxwidth, (unsigned int) Strlen(items[i])); maxwidth += no_file_suffix ? 1 : 2; /* for the file tag and space */ columns = (TermH + 1) / maxwidth; /* PWP: terminal size change */ if (!columns) columns = 1; rows = (count + (columns - 1)) / columns; return rows; } /* end rows_needed_by_print_by_column */ /* print_by_column(): * Print sorted down columns or across columns when the first * word of $listflags shell variable contains 'x'. * */ void print_by_column(Char *dir, Char *items[], int count, int no_file_suffix) { int i, r, c, columns, rows; size_t w; unsigned int wx, maxwidth = 0; Char *val; int across; lbuffed = 0; /* turn off line buffering */ - - across = ((val = varval(STRlistflags)) != STRNULL) && + + across = ((val = varval(STRlistflags)) != STRNULL) && (Strchr(val, 'x') != NULL); for (i = 0; i < count; i++) { /* find widest string */ maxwidth = max(maxwidth, (unsigned int) NLSStringWidth(items[i])); } maxwidth += no_file_suffix ? 1 : 2; /* for the file tag and space */ columns = TermH / maxwidth; /* PWP: terminal size change */ if (!columns || !isatty(didfds ? 1 : SHOUT)) columns = 1; rows = (count + (columns - 1)) / columns; i = -1; for (r = 0; r < rows; r++) { for (c = 0; c < columns; c++) { i = across ? (i + 1) : (c * rows + r); if (i < count) { wx = 0; w = Strlen(items[i]); #ifdef COLOR_LS_F if (no_file_suffix) { /* Print the command name */ Char f = items[i][w - 1]; items[i][w - 1] = 0; print_with_color(items[i], w - 1, f); items[i][w - 1] = f; } else { /* Print filename followed by '/' or '*' or ' ' */ print_with_color(items[i], w, filetype(dir, items[i])); wx++; } #else /* ifndef COLOR_LS_F */ if (no_file_suffix) { /* Print the command name */ xprintf("%S", items[i]); } else { /* Print filename followed by '/' or '*' or ' ' */ xprintf("%-S%c", items[i], filetype(dir, items[i])); wx++; } #endif /* COLOR_LS_F */ if (c < (columns - 1)) { /* Not last column? */ w = NLSStringWidth(items[i]) + wx; for (; w < maxwidth; w++) xputchar(' '); } } else if (across) break; } if (Tty_raw_mode) xputchar('\r'); xputchar('\n'); } lbuffed = 1; /* turn back on line buffering */ flush(); } /* end print_by_column */ /* StrQcmp(): * Compare strings ignoring the quoting chars */ int StrQcmp(const Char *str1, const Char *str2) { - for (; *str1 && samecase(*str1 & TRIM) == samecase(*str2 & TRIM); + for (; *str1 && samecase(*str1 & TRIM) == samecase(*str2 & TRIM); str1++, str2++) continue; /* * The following case analysis is necessary so that characters which look * negative collate low against normal characters but high against the * end-of-string NUL. */ if (*str1 == '\0' && *str2 == '\0') return (0); else if (*str1 == '\0') return (-1); else if (*str2 == '\0') return (1); else return ((*str1 & TRIM) - (*str2 & TRIM)); } /* end StrQcmp */ /* fcompare(): * Comparison routine for qsort, (Char **, Char **) */ int fcompare(const void *xfile1, const void *xfile2) { const Char *const *file1 = xfile1, *const *file2 = xfile2; return collate(*file1, *file2); } /* end fcompare */ /* catn(): * Concatenate src onto tail of des. * Des is a string whose maximum length is count. * Always null terminate. */ void catn(Char *des, const Char *src, int count) { while (*des && --count > 0) des++; while (--count > 0) if ((*des++ = *src++) == 0) return; *des = '\0'; } /* end catn */ /* copyn(): * like strncpy but always leave room for trailing \0 * and always null terminate. */ void copyn(Char *des, const Char *src, size_t count) { while (--count != 0) if ((*des++ = *src++) == 0) return; *des = '\0'; } /* end copyn */ /* tgetenv(): * like it's normal string counter-part */ Char * tgetenv(Char *str) { Char **var; size_t len; int res; len = Strlen(str); /* Search the STR_environ for the entry matching str. */ for (var = STR_environ; var != NULL && *var != NULL; var++) if (Strlen(*var) >= len && (*var)[len] == '=') { /* Temporarily terminate the string so we can copy the variable name. */ (*var)[len] = '\0'; res = StrQcmp(*var, str); /* Restore the '=' and return a pointer to the value of the environment variable. */ (*var)[len] = '='; if (res == 0) return (&((*var)[len + 1])); } return (NULL); } /* end tgetenv */ struct scroll_tab_list *scroll_tab = 0; static void add_scroll_tab(Char *item) { struct scroll_tab_list *new_scroll; new_scroll = xmalloc(sizeof(struct scroll_tab_list)); new_scroll->element = Strsave(item); new_scroll->next = scroll_tab; scroll_tab = new_scroll; } static void choose_scroll_tab(struct Strbuf *exp_name, int cnt) { struct scroll_tab_list *loop; int tmp = cnt; Char **ptr; ptr = xmalloc(sizeof(Char *) * cnt); cleanup_push(ptr, xfree); for (loop = scroll_tab; loop && (tmp >= 0); loop = loop->next) ptr[--tmp] = loop->element; qsort(ptr, cnt, sizeof(Char *), fcompare); exp_name->len = 0; Strbuf_append(exp_name, ptr[curchoice]); Strbuf_terminate(exp_name); cleanup_until(ptr); } static void free_scroll_tab(void) { struct scroll_tab_list *loop; while (scroll_tab) { loop = scroll_tab; scroll_tab = scroll_tab->next; xfree(loop->element); xfree(loop); } } diff --git a/contrib/tcsh/vms.termcap.c b/contrib/tcsh/vms.termcap.c index a37e60985b52..66f3be6b965d 100644 --- a/contrib/tcsh/vms.termcap.c +++ b/contrib/tcsh/vms.termcap.c @@ -1,353 +1,353 @@ /* * termcap.c 1.1 20/7/87 agc Joypace Ltd * * Copyright Joypace Ltd, London, UK, 1987. All rights reserved. * This file may be freely distributed provided that this notice * remains attached. * * A public domain implementation of the termcap(3) routines. */ #include "sh.h" #if defined(_VMS_POSIX) || defined(_OSD_POSIX) || defined(__ANDROID__) /* efth 1988-Apr-29 - Correct when TERM != name and TERMCAP is defined [tgetent] - Correct the comparison for the terminal name [tgetent] - Correct the value of ^x escapes [tgetstr] - Added %r to reverse row/column [tgoto] Paul Gillingwater July 1992 - Modified to allow terminal aliases in termcap file - Uses TERMCAP environment variable for file only */ #include #include #define CAPABLEN 2 #define ISSPACE(c) ((c) == ' ' || (c) == '\t' || (c) == '\r' || (c) == '\n') #define ISDIGIT(x) ((x) >= '0' && (x) <= '9') char *capab; /* the capability itself */ extern char *getenv(); /* new, improved getenv */ #ifndef fopen extern FILE *fopen(); /* old fopen */ #endif /* * tgetent - get the termcap entry for terminal name, and put it * in bp (which must be an array of 1024 chars). Returns 1 if * termcap entry found, 0 if not found, and -1 if file not found. */ int tgetent(char *bp, char *name) { #ifdef __ANDROID__ /* Use static termcap entry since termcap file usually doesn't exist. */ capab = bp; strcpy(bp, "linux|linux console:" ":am:eo:mi:ms:xn:xo:" ":it#8:" ":AL=\\E[%dL:DC=\\E[%dP:DL=\\E[%dM:IC=\\E[%d@:K2=\\E[G:al=\\E[L:" ":bl=^G:cd=\\E[J:ce=\\E[K:cl=\\E[H\\E[J:cm=\\E[%i%d;%dH:cr=^M:" ":cs=\\E[%i%d;%dr:ct=\\E[3g:dc=\\E[P:dl=\\E[M:do=^J:ec=\\E[%dX:" ":ei=\\E[4l:ho=\\E[H:ic=\\E[@:im=\\E[4h:k1=\\E[[A:k2=\\E[[B:" ":k3=\\E[[C:k4=\\E[[D:k5=\\E[[E:k6=\\E[17~:k7=\\E[18~:k8=\\E[19~:" ":k9=\\E[20~:kD=\\E[3~:kI=\\E[2~:kN=\\E[6~:kP=\\E[5~:kb=\\177:" ":kd=\\E[B:kh=\\E[1~:kl=\\E[D:kr=\\E[C:ku=\\E[A:le=^H:mb=\\E[5m:" ":md=\\E[1m:me=\\E[0m:mh=\\E[2m:mr=\\E[7m:nd=\\E[C:nw=^M^J:" ":rc=\\E8:sc=\\E7:se=\\E[27m:sf=^J:so=\\E[7m:sr=\\EM:st=\\EH:ta=^I:" ":ue=\\E[24m:up=\\E[A:us=\\E[4m:vb=200\\E[?5h\\E[?5l:" ":ve=\\E[?25h\\E[?0c:vi=\\E[?25l\\E[?1c:vs=\\E[?25h\\E[?0c:" ); return(1); #else FILE *fp; char *termfile; char *cp, *ptr, /* temporary pointer */ tmp[1024]; /* buffer for terminal name *//*FIXBUF*/ size_t len = strlen(name); capab = bp; /* Use TERMCAP to override default. */ termfile = getenv("TERMCAP"); if (termfile == NULL ) termfile = "/etc/termcap"; if ((fp = fopen(termfile, "r")) == (FILE *) NULL) { fprintf(stderr, CGETS(31, 1, "Can't open TERMCAP: [%s]\n"), termfile); fprintf(stderr, CGETS(31, 2, "Can't open %s.\n"), termfile); sleep(1); return(-1); } while (fgets(bp, 1024, fp) != NULL) { /* Any line starting with # or NL is skipped as a comment */ if ((*bp == '#') || (*bp == '\n')) continue; /* Look for lines which end with two backslashes, and then append the next line. */ while (*(cp = &bp[strlen(bp) - 2]) == '\\') fgets(cp, 1024, fp); /* Skip over any spaces or tabs */ for (++cp ; ISSPACE(*cp) ; cp++); /* Make sure "name" matches exactly (efth) */ /* Here we might want to look at any aliases as well. We'll use sscanf to look at aliases. These are delimited by '|'. */ sscanf(bp,"%[^|]",tmp); if (strncmp(name, tmp, len) == 0) { fclose(fp); #ifdef DEBUG fprintf(stderr, CGETS(31, 3, "Found %s in %s.\n"), name, termfile); sleep(1); #endif /* DEBUG */ return(1); } ptr = bp; while ((ptr = strchr(ptr,'|')) != NULL) { ptr++; if (strchr(ptr,'|') == NULL) break; sscanf(ptr,"%[^|]",tmp); if (strncmp(name, tmp, len) == 0) { fclose(fp); #ifdef DEBUG fprintf(stderr,CGETS(31, 3, "Found %s in %s.\n"), name, termfile); sleep(1); #endif /* DEBUG */ return(1); } } } /* If we get here, then we haven't found a match. */ fclose(fp); #ifdef DEBUG fprintf(stderr,CGETS(31, 4, "No match found for %s in file %s\n"), name, termfile); sleep(1); #endif /* DEBUG */ return(0); #endif /* ANDROID */ } /* * tgetnum - get the numeric terminal capability corresponding * to id. Returns the value, -1 if invalid. */ int tgetnum(char *id) { char *cp; int ret; if ((cp = capab) == NULL || id == NULL) return(-1); while (*++cp != ':') ; for (++cp ; *cp ; cp++) { while (ISSPACE(*cp)) cp++; if (strncmp(cp, id, CAPABLEN) == 0) { while (*cp && *cp != ':' && *cp != '#') cp++; if (*cp != '#') return(-1); for (ret = 0, cp++ ; *cp && ISDIGIT(*cp) ; cp++) ret = ret * 10 + *cp - '0'; return(ret); } while (*cp && *cp != ':') cp++; } return(-1); } /* * tgetflag - get the boolean flag corresponding to id. Returns -1 * if invalid, 0 if the flag is not in termcap entry, or 1 if it is * present. */ int tgetflag(char *id) { char *cp; if ((cp = capab) == NULL || id == NULL) return(-1); while (*++cp != ':') ; for (++cp ; *cp ; cp++) { while (ISSPACE(*cp)) cp++; if (strncmp(cp, id, CAPABLEN) == 0) return(1); while (*cp && *cp != ':') cp++; } return(0); } /* * tgetstr - get the string capability corresponding to id and place * it in area (advancing area at same time). Expand escape sequences * etc. Returns the string, or NULL if it can't do it. */ char * tgetstr(char *id, char **area) { char *cp; char *ret; int i; if ((cp = capab) == NULL || id == NULL) return(NULL); while (*++cp != ':') ; for (++cp ; *cp ; cp++) { while (ISSPACE(*cp)) cp++; if (strncmp(cp, id, CAPABLEN) == 0) { while (*cp && *cp != ':' && *cp != '=') cp++; if (*cp != '=') return(NULL); - for (ret = *area, cp++; *cp && *cp != ':' ; + for (ret = *area, cp++; *cp && *cp != ':' ; (*area)++, cp++) switch(*cp) { case '^' : **area = *++cp - '@'; /* fix (efth)*/ break; case '\\' : switch(*++cp) { case 'E' : **area = CTL_ESC('\033'); break; case 'n' : **area = '\n'; break; case 'r' : **area = '\r'; break; case 't' : **area = '\t'; break; case 'b' : **area = '\b'; break; case 'f' : **area = '\f'; break; case '0' : case '1' : case '2' : case '3' : for (i=0 ; *cp && ISDIGIT(*cp) ; cp++) i = i * 8 + *cp - '0'; **area = i; cp--; break; case '^' : case '\\' : **area = *cp; break; } break; default : **area = *cp; } *(*area)++ = '\0'; return(ret); } while (*cp && *cp != ':') cp++; } return(NULL); } /* * tgoto - given the cursor motion string cm, make up the string * for the cursor to go to (destcol, destline), and return the string. * Returns "OOPS" if something's gone wrong, or the string otherwise. */ char * tgoto(char *cm, int destcol, int destline) { char *rp; static char ret[24]; int incr = 0; int argno = 0, numval; for (rp = ret ; *cm ; cm++) { switch(*cm) { case '%' : switch(*++cm) { case '+' : numval = (argno == 0 ? destline : destcol); argno = 1 - argno; *rp++ = numval + incr + *++cm; break; case '%' : *rp++ = '%'; break; case 'i' : incr = 1; break; case 'd' : numval = (argno == 0 ? destline : destcol); numval += incr; argno = 1 - argno; *rp++ = '0' + (numval/10); *rp++ = '0' + (numval%10); break; case 'r' : argno = 1; break; } break; default : *rp++ = *cm; } } *rp = '\0'; return(ret); } /* * tputs - put the string cp out onto the terminal, using the function * outc. This should do padding for the terminal, but I can't find a * terminal that needs padding at the moment... */ int tputs(char *cp, int affcnt, int (*outc)()) { unsigned long delay = 0; if (cp == NULL) return(1); /* do any padding interpretation - left null for MINIX just now */ for (delay = 0; *cp && ISDIGIT(*cp) ; cp++) delay = delay * 10 + *cp - '0'; while (*cp) (*outc)(*cp++); #ifdef _OSD_POSIX usleep(delay*100); /* strictly spoken, it should be *1000 */ #endif return(1); } #endif /* _VMS_POSIX || _OSD_POSIX */