home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / osr5 / sco / scripts / toroff < prev    next >
Encoding:
AWK Script  |  1997-08-26  |  28.0 KB  |  761 lines

  1. #!/usr/local/bin/gawk -f
  2. # @(#) toroff.gawk 1.1 96/06/18
  3. # 1989  john h. dubois iii (john@armory.com)
  4. # 92/05/21 converted to a #!awk script
  5. # 94/10/07 Added all options.
  6. # 96/06/18 Deal with files that do not start or end neatly.
  7.  
  8. BEGIN { 
  9.     Name = "toroff"
  10.     Usage = "Usage: " Name " [-h] [-l<margin>] [filename ...]"
  11.     ARGC = Opts(Name,Usage,"hl:",0)
  12.     if ("h" in Options) {
  13.     print \
  14. Name ": convert formatted text to roff source.\n"\
  15. Usage "\n"\
  16. Name " converts text with normal paragraphs (left justified, with the first\n"\
  17. "line indented at least three spaces and all others less than three spaces)\n"\
  18. "to troff/nroff -ms source, preserving the paragraphs by preceding each\n"\
  19. "with '.PP'.\n"\
  20. "Sentences are put on individual lines, split over multiple lines if they\n"\
  21. "will not fit on one line.  The maximum length a line is allowed to reach\n"\
  22. "is 79 characters.  Sentences are delimited by words ending in '.', '?',\n"\
  23. "and '!', or the same followed by a close parentheses.  Note that this is\n"\
  24. "not a perfect algorithm.\n"\
  25. "Options:\n"\
  26. "-h: Print this help.\n"\
  27. "-l<margin>: Output -ms code to indent the output by <margin> ens."
  28.     exit 0
  29.     }
  30.     if ("l" in Options)
  31.     print ".nr PO " Options["l"] "n"
  32.     LineLen = 0
  33. }
  34.  
  35. # Do for the first line of a paragraph
  36. NR == 1 || $0 ~ /^   / { 
  37.     if (LineLen == 0) 
  38.     print ".PP"
  39.     else { 
  40.     print "\n.PP"
  41.     LineLen = 0 
  42.     }
  43. }
  44.  
  45. # Do for all lines
  46.     for (f = 1; f <= NF; f++) { 
  47.     WordLen = length($f)
  48.     if (LineLen == 0) {
  49.         LineLen = WordLen
  50.         printf "%s",$f
  51.     }
  52.     else {
  53.         LineLen += 1 + WordLen
  54.         if (LineLen <= 79)
  55.         printf " %s",$f
  56.         else {
  57.         LineLen = WordLen
  58.         printf "\n%s",$f
  59.         }
  60.     }
  61.     lchar = substr($f,WordLen,1)
  62.     if (lchar == ")")
  63.         lchar = substr($f,WordLen - 1,1)
  64.     if (lchar == "." || lchar == "?" || lchar == "!") {
  65.         print ""
  66.         LineLen = 0
  67.     }
  68.     }
  69. }
  70.  
  71. END {
  72.     if (LineLen > 0)
  73.     print ""
  74. }
  75.  
  76. ### Start of ProcArgs library
  77. # @(#) ProcArgs 1.11 96/12/08
  78. # 92/02/29 john h. dubois iii (john@armory.com)
  79. # 93/07/18 Added "#" arg type
  80. # 93/09/26 Do not count -h against MinArgs
  81. # 94/01/01 Stop scanning at first non-option arg.  Added ">" option type.
  82. #          Removed meaning of "+" or "-" by itself.
  83. # 94/03/08 Added & option and *()< option types.
  84. # 94/04/02 Added NoRCopt to Opts()
  85. # 94/06/11 Mark numeric variables as such.
  86. # 94/07/08 Opts(): Do not require any args if h option is given.
  87. # 95/01/22 Record options given more than once.  Record option num in argv.
  88. # 95/06/08 Added ExclusiveOptions().
  89. # 96/01/20 Let rcfiles be a colon-separated list of filenames.
  90. #          Expand $VARNAME at the start of its filenames.
  91. #          Let varname=0 and -option- turn off an option.
  92. # 96/05/05 Changed meaning of 7th arg to Opts; now can specify exactly how many
  93. #          of the vars should be searched for in the environment.
  94. #          Check for duplicate rcfiles.
  95. # 96/05/13 Return more specific error values.  Note: ProcArgs() and InitOpts()
  96. #          now return various negatives values on error, not just -1, and
  97. #          Opts() may set Err to various positive values, not just 1.
  98. #          Added AllowUnrecOpt.
  99. # 96/05/23 Check type given for & option
  100. # 96/06/15 Re-port to awk
  101. # 96/10/01 Moved file-reading code into ReadConfFile(), so that it can be
  102. #          used by other functions.
  103. # 96/10/15 Added OptChars
  104. # 96/11/01 Added exOpts arg to Opts()
  105. # 96/11/16 Added ; type
  106. # 96/12/08 Added Opt2Set() & Opt2Sets()
  107. # 96/12/27 Added CmdLineOpt()
  108.  
  109. # optlist is a string which contains all of the possible command line options.
  110. # A character followed by certain characters indicates that the option takes
  111. # an argument, with type as follows:
  112. # :    String argument
  113. # ;    Non-empty string argument
  114. # *    Floating point argument
  115. # (    Non-negative floating point argument
  116. # )    Positive floating point argument
  117. # #    Integer argument
  118. # <    Non-negative integer argument
  119. # >    Positive integer argument
  120. # The only difference the type of argument makes is in the runtime argument
  121. # error checking that is done.
  122.  
  123. # The & option is a special case used to get numeric options without the
  124. # user having to give an option character.  It is shorthand for [-+.0-9].
  125. # If & is included in optlist and an option string that begins with one of
  126. # these characters is seen, the value given to "&" will include the first
  127. # char of the option.  & must be followed by a type character other than ":"
  128. # or ";".
  129. # Note that if e.g. &> is given, an option of -.5 will produce an error.
  130.  
  131. # Strings in argv[] which begin with "-" or "+" are taken to be
  132. # strings of options, except that a string which consists solely of "-"
  133. # or "+" is taken to be a non-option string; like other non-option strings,
  134. # it stops the scanning of argv and is left in argv[].
  135. # An argument of "--" or "++" also stops the scanning of argv[] but is removed.
  136. # If an option takes an argument, the argument may either immediately
  137. # follow it or be given separately.
  138. # "-" and "+" options are treated the same.  "+" is allowed because most awks
  139. # take any -options to be arguments to themselves.  gawk 2.15 was enhanced to
  140. # stop scanning when it encounters an unrecognized option, though until 2.15.5
  141. # this feature had a flaw that caused problems in some cases.  See the OptChars
  142. # parameter to explicitly set the option-specifier characters.
  143.  
  144. # If an option that does not take an argument is given,
  145. # an index with its name is created in Options and its value is set to the
  146. # number of times it occurs in argv[].
  147.  
  148. # If an option that does take an argument is given, an index with its name is
  149. # created in Options and its value is set to the value of the argument given
  150. # for it, and Options[option-name,"count"] is (initially) set to the 1.
  151. # If an option that takes an argument is given more than once,
  152. # Options[option-name,"count"] is incremented, and the value is assigned to
  153. # the index (option-name,instance) where instance is 2 for the second occurance
  154. # of the option, etc.
  155. # In other words, the first time an option with a value is encountered, the
  156. # value is assigned to an index consisting only of its name; for any further
  157. # occurances of the option, the value index has an extra (count) dimension.
  158.  
  159. # The sequence number for each option found in argv[] is stored in
  160. # Options[option-name,"num",instance], where instance is 1 for the first
  161. # occurance of the option, etc.  The sequence number starts at 1 and is
  162. # incremented for each option, both those that have a value and those that
  163. # do not.  Options set from a config file have a value of 0 assigned to this.
  164.  
  165. # Options and their arguments are deleted from argv.
  166. # Note that this means that there may be gaps left in the indices of argv[].
  167. # If compress is nonzero, argv[] is packed by moving its elements so that
  168. # they have contiguous integer indices starting with 0.
  169. # Option processing will stop with the first unrecognized option, just as
  170. # though -- was given except that unlike -- the unrecognized option will not be
  171. # removed from ARGV[].  Normally, an error value is returned in this case.
  172. # If AllowUnrecOpt is true, it is not an error for an unrecognized option to
  173. # be found, so the number of remaining arguments is returned instead.
  174. # If OptChars is not a null string, it is the set of characters that indicate
  175. # that an argument is an option string if the string begins with one of the
  176. # characters.  A string consisting solely of two of the same option-indicator
  177. # characters stops the scanning of argv[].  The default is "-+".
  178. # argv[0] is not examined.
  179. # The number of arguments left in argc is returned.
  180. # If an error occurs, the global string OptErr is set to an error message
  181. # and a negative value is returned.
  182. # Current error values:
  183. # -1: option that required an argument did not get it.
  184. # -2: argument of incorrect type supplied for an option.
  185. # -3: unrecognized (invalid) option.
  186. function ProcArgs(argc,argv,OptList,Options,compress,AllowUnrecOpt,OptChars,
  187. ArgNum,ArgsLeft,Arg,ArgLen,ArgInd,Option,Pos,NumOpt,Value,HadValue,specGiven,
  188. NeedNextOpt,GotValue,OptionNum,Escape,dest,src,count,c,OptTerm,OptCharSet)
  189. {
  190. # ArgNum is the index of the argument being processed.
  191. # ArgsLeft is the number of arguments left in argv.
  192. # Arg is the argument being processed.
  193. # ArgLen is the length of the argument being processed.
  194. # ArgInd is the position of the character in Arg being processed.
  195. # Option is the character in Arg being processed.
  196. # Pos is the position in OptList of the option being processed.
  197. # NumOpt is true if a numeric option may be given.
  198.     ArgsLeft = argc
  199.     NumOpt = index(OptList,"&")
  200.     OptionNum = 0
  201.     if (OptChars == "")
  202.     OptChars = "-+"
  203.     while (OptChars != "") {
  204.     c = substr(OptChars,1,1)
  205.     OptChars = substr(OptChars,2)
  206.     OptCharSet[c]
  207.     OptTerm[c c]
  208.     }
  209.     for (ArgNum = 1; ArgNum < argc; ArgNum++) {
  210.     Arg = argv[ArgNum]
  211.     if (length(Arg) < 2 || !((specGiven = substr(Arg,1,1)) in OptCharSet))
  212.         break    # Not an option; quit
  213.     if (Arg in OptTerm) {
  214.         delete argv[ArgNum]
  215.         ArgsLeft--
  216.         break
  217.     }
  218.     ArgLen = length(Arg)
  219.     for (ArgInd = 2; ArgInd <= ArgLen; ArgInd++) {
  220.         Option = substr(Arg,ArgInd,1)
  221.         if (NumOpt && Option ~ /[-+.0-9]/) {
  222.         # If this option is a numeric option, make its flag be & and
  223.         # its option string flag position be the position of & in
  224.         # the option string.
  225.         Option = "&"
  226.         Pos = NumOpt
  227.         # Prefix Arg with a char so that ArgInd will point to the
  228.         # first char of the numeric option.
  229.         Arg = "&" Arg
  230.         ArgLen++
  231.         }
  232.         # Find position of flag in option string, to get its type (if any).
  233.         # Disallow & as literal flag.
  234.         else if (!(Pos = index(OptList,Option)) || Option == "&") {
  235.         if (AllowUnrecOpt) {
  236.             Escape = 1
  237.             break
  238.         }
  239.         else {
  240.             OptErr = "Invalid option: " specGiven Option
  241.             return -3
  242.         }
  243.         }
  244.  
  245.         # Find what the value of the option will be if it takes one.
  246.         # NeedNextOpt is true if the option specifier is the last char of
  247.         # this arg, which means that if the option requires a value it is
  248.         # the next arg.
  249.         if (NeedNextOpt = (ArgInd >= ArgLen)) { # Value is the next arg
  250.         if (GotValue = ArgNum + 1 < argc)
  251.             Value = argv[ArgNum+1]
  252.         }
  253.         else {    # Value is included with option
  254.         Value = substr(Arg,ArgInd + 1)
  255.         GotValue = 1
  256.         }
  257.  
  258.         if (HadValue = AssignVal(Option,Value,Options,
  259.         substr(OptList,Pos + 1,1),GotValue,"",++OptionNum,!NeedNextOpt,
  260.         specGiven)) {
  261.         if (HadValue < 0)    # error occured
  262.             return HadValue
  263.         if (HadValue == 2)
  264.             ArgInd++    # Account for the single-char value we used.
  265.         else {
  266.             if (NeedNextOpt) {    # option took next arg as value
  267.             delete argv[++ArgNum]
  268.             ArgsLeft--
  269.             }
  270.             break    # This option has been used up
  271.         }
  272.         }
  273.     }
  274.     if (Escape)
  275.         break
  276.     # Do not delete arg until after processing of it, so that if it is not
  277.     # recognized it can be left in ARGV[].
  278.     delete argv[ArgNum]
  279.     ArgsLeft--
  280.     }
  281.     if (compress != 0) {
  282.     dest = 1
  283.     src = argc - ArgsLeft + 1
  284.     for (count = ArgsLeft - 1; count; count--) {
  285.         ARGV[dest] = ARGV[src]
  286.         dest++
  287.         src++
  288.     }
  289.     }
  290.     return ArgsLeft
  291. }
  292.  
  293. # Assignment to values in Options[] occurs only in this function.
  294. # Option: Option specifier character.
  295. # Value: Value to be assigned to option, if it takes a value.
  296. # Options[]: Options array to return values in.
  297. # ArgType: Argument type specifier character.
  298. # GotValue: Whether any value is available to be assigned to this option.
  299. # Name: Name of option being processed.
  300. # OptionNum: Number of this option (starting with 1) if set in argv[],
  301. #     or 0 if it was given in a config file or in the environment.
  302. # SingleOpt: true if the value (if any) that is available for this option was
  303. #     given as part of the same command line arg as the option.  Used only for
  304. #     options from the command line.
  305. # specGiven is the option specifier character use, if any (e.g. - or +),
  306. # for use in error messages.
  307. # Global variables: OptErr
  308. # Return value: negative value on error, 0 if option did not require an
  309. # argument, 1 if it did & used the whole arg, 2 if it required just one char of
  310. # the arg.
  311. # Current error values:
  312. # -1: Option that required an argument did not get it.
  313. # -2: Value of incorrect type supplied for option.
  314. # -3: Bad type given for option &
  315. function AssignVal(Option,Value,Options,ArgType,GotValue,Name,OptionNum,
  316. SingleOpt,specGiven,  UsedValue,Err,NumTypes) {
  317.     # If option takes a value...    [
  318.     NumTypes = "*()#<>]"
  319.     if (Option == "&" && ArgType !~ "[" NumTypes) {    # ]
  320.     OptErr = "Bad type given for & option"
  321.     return -3
  322.     }
  323.  
  324.     if (UsedValue = (ArgType ~ "[:;" NumTypes)) {    # ]
  325.     if (!GotValue) {
  326.         if (Name != "")
  327.         OptErr = "Variable requires a value -- " Name
  328.         else
  329.         OptErr = "option requires an argument -- " Option
  330.         return -1
  331.     }
  332.     if ((Err = CheckType(ArgType,Value,Option,Name,specGiven)) != "") {
  333.         OptErr = Err
  334.         return -2
  335.     }
  336.     # Mark this as a numeric variable; will be propogated to Options[] val.
  337.     if (ArgType != ":" && ArgType != ";")
  338.         Value += 0
  339.     if ((Instance = ++Options[Option,"count"]) > 1)
  340.         Options[Option,Instance] = Value
  341.     else
  342.         Options[Option] = Value
  343.     }
  344.     # If this is an environ or rcfile assignment & it was given a value...
  345.     else if (!OptionNum && Value != "") {
  346.     UsedValue = 1
  347.     # If the value is "0" or "-" and this is the first instance of it,
  348.     # do not set Options[Option]; this allows an assignment in an rcfile to
  349.     # turn off an option (for the simple "Option in Options" test) in such
  350.     # a way that it cannot be turned on in a later file.
  351.     if (!(Option in Options) && (Value == "0" || Value == "-"))
  352.         Instance = 1
  353.     else
  354.         Instance = ++Options[Option]
  355.     # Save the value even though this is a flag
  356.     Options[Option,Instance] = Value
  357.     }
  358.     # If this is a command line flag and has a - following it in the same arg,
  359.     # it is being turned off.
  360.     else if (OptionNum && SingleOpt && substr(Value,1,1) == "-") {
  361.     UsedValue = 2
  362.     if (Option in Options)
  363.         Instance = ++Options[Option]
  364.     else
  365.         Instance = 1
  366.     Options[Option,Instance]
  367.     }
  368.     # If this is a flag assignment without a value, increment the count for the
  369.     # flag unless it was turned off.  The indicator for a flag being turned off
  370.     # is that the flag index has not been set in Options[] but it has an
  371.     # instance count.
  372.     else if (Option in Options || !((Option,1) in Options))
  373.     # Increment number of times this flag seen; will inc null value to 1
  374.     Instance = ++Options[Option]
  375.     Options[Option,"num",Instance] = OptionNum
  376.     return UsedValue
  377. }
  378.  
  379. # Option is the option letter
  380. # Value is the value being assigned
  381. # Name is the var name of the option, if any
  382. # ArgType is one of:
  383. # :    String argument
  384. # ;    Non-null string argument
  385. # *    Floating point argument
  386. # (    Non-negative floating point argument
  387. # )    Positive floating point argument
  388. # #    Integer argument
  389. # <    Non-negative integer argument
  390. # >    Positive integer argument
  391. # specGiven is the option specifier character use, if any (e.g. - or +),
  392. # for use in error messages.
  393. # Returns null on success, err string on error
  394. function CheckType(ArgType,Value,Option,Name,specGiven,  Err,ErrStr) {
  395.     if (ArgType == ":")
  396.     return ""
  397.     if (ArgType == ";") {
  398.     if (Value == "")
  399.         Err = "must be a non-empty string"
  400.     }
  401.     # A number begins with optional + or -, and is followed by a string of
  402.     # digits or a decimal with digits before it, after it, or both
  403.     else if (Value !~ /^[-+]?([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.)$/)
  404.     Err = "must be a number"
  405.     else if (ArgType ~ "[#<>]" && Value ~ /\./)
  406.     Err = "may not include a fraction"
  407.     else if (ArgType ~ "[()<>]" && Value < 0)
  408.     Err = "may not be negative"
  409.     # (
  410.     else if (ArgType ~ "[)>]" && Value == 0)
  411.     Err = "must be a positive number"
  412.     if (Err != "") {
  413.     ErrStr = "Bad value \"" Value "\".  Value assigned to "
  414.     if (Name != "")
  415.         return ErrStr "variable " substr(Name,1,1) " " Err
  416.     else {
  417.         if (Option == "&")
  418.         Option = Value
  419.         return ErrStr "option " specGiven substr(Option,1,1) " " Err
  420.     }
  421.     }
  422.     else
  423.     return ""
  424. }
  425.  
  426. # Note: only the above functions are needed by ProcArgs.
  427. # The rest of these functions call ProcArgs() and also do other
  428. # option-processing stuff.
  429.  
  430. # Opts: Process command line arguments.
  431. # Opts processes command line arguments using ProcArgs()
  432. # and checks for errors.  If an error occurs, a message is printed
  433. # and the program is exited.
  434. #
  435. # Input variables:
  436. # Name is the name of the program, for error messages.
  437. # Usage is a usage message, for error messages.
  438. # OptList the option description string, as used by ProcArgs().
  439. # MinArgs is the minimum number of non-option arguments that this
  440. # program should have, non including ARGV[0] and +h.
  441. # If the program does not require any non-option arguments,
  442. # MinArgs should be omitted or given as 0.
  443. # rcFiles, if given, is a colon-seprated list of filenames to read for
  444. # variable initialization.  If a filename begins with ~/, the ~ is replaced
  445. # by the value of the environment variable HOME.  If a filename begins with
  446. # $, the part from the character after the $ up until (but not including)
  447. # the first character not in [a-zA-Z0-9_] will be searched for in the
  448. # environment; if found its value will be substituted, if not the filename will
  449. # be discarded.
  450. # rcfiles are read in the order given.
  451. # Values given in them will not override values given on the command line,
  452. # and values given in later files will not override those set in earlier
  453. # files, because AssignVal() will store each with a different instance index.
  454. # The first instance of each variable, either on the command line or in an
  455. # rcfile, will be stored with no instance index, and this is the value
  456. # normally used by programs that call this function.
  457. # VarNames is a comma-separated list of variable names to map to options,
  458. # in the same order as the options are given in OptList.
  459. # If EnvSearch is given and nonzero, the first EnvSearch variables will also be
  460. # searched for in the environment.  If set to -1, all values will be searched
  461. # for in the environment.  Values given in the environment will override
  462. # those given in the rcfiles but not those given on the command line.
  463. # NoRCopt, if given, is an additional letter option that if given on the
  464. # command line prevents the rcfiles from being read.
  465. # See ProcArgs() for a description of AllowUnRecOpt and optChars, and
  466. # ExclusiveOptions() for a description of exOpts.
  467. # Special options:
  468. # If x is made an option and is given, some debugging info is output.
  469. # h is assumed to be the help option.
  470.  
  471. # Global variables:
  472. # The command line arguments are taken from ARGV[].
  473. # The arguments that are option specifiers and values are removed from
  474. # ARGV[], leaving only ARGV[0] and the non-option arguments.
  475. # The number of elements in ARGV[] should be in ARGC.
  476. # After processing, ARGC is set to the number of elements left in ARGV[].
  477. # The option values are put in Options[].
  478. # On error, Err is set to a positive integer value so it can be checked for in
  479. # an END block.
  480. # Return value: The number of elements left in ARGV is returned.
  481. # Must keep OptErr global since it may be set by InitOpts().
  482. function Opts(Name,Usage,OptList,MinArgs,rcFiles,VarNames,EnvSearch,NoRCopt,
  483. AllowUnrecOpt,optChars,exOpts,  ArgsLeft,e) {
  484.     if (MinArgs == "")
  485.     MinArgs = 0
  486.     ArgsLeft = ProcArgs(ARGC,ARGV,OptList NoRCopt,Options,1,AllowUnrecOpt,
  487.     optChars)
  488.     if (ArgsLeft < (MinArgs+1) && !("h" in Options)) {
  489.     if (ArgsLeft >= 0) {
  490.         OptErr = "Not enough arguments"
  491.         Err = 4
  492.     }
  493.     else
  494.         Err = -ArgsLeft
  495.     printf "%s: %s.\nUse -h for help.\n%s\n",
  496.     Name,OptErr,Usage > "/dev/stderr"
  497.     exit 1
  498.     }
  499.     if (rcFiles != "" && (NoRCopt == "" || !(NoRCopt in Options)) &&
  500.     (e = InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch)) < 0)
  501.     {
  502.     print Name ": " OptErr ".\nUse -h for help." > "/dev/stderr"
  503.     Err = -e
  504.     exit 1
  505.     }
  506.     if ((exOpts != "") && ((OptErr = ExclusiveOptions(exOpts,Options)) != ""))
  507.     {
  508.     printf "%s: Error: %s\n",Name,OptErr > "/dev/stderr"
  509.     Err = 1
  510.     exit 1
  511.     }
  512.     return ArgsLeft
  513. }
  514.  
  515. # ReadConfFile(): Read a file containing var/value assignments, in the form
  516. # <variable-name><assignment-char><value>.
  517. # Whitespace (spaces and tabs) around a variable (leading whitespace on the
  518. # line and whitespace between the variable name and the assignment character) 
  519. # is stripped.  Lines that do not contain an assignment operator or which
  520. # contain a null variable name are ignored, other than possibly being noted in
  521. # the return value.  If more than one assignment is made to a variable, the
  522. # first assignment is used.
  523. # Input variables:
  524. # File is the file to read.
  525. # Comment is the line-comment character.  If it is found as the first non-
  526. #     whitespace character on a line, the line is ignored.
  527. # Assign is the assignment string.  The first instance of Assign on a line
  528. #     separates the variable name from its value.
  529. # If StripWhite is true, whitespace around the value (whitespace between the
  530. #     assignment char and trailing whitespace on the line) is stripped.
  531. # VarPat is a pattern that variable names must match.  
  532. #     Example: "^[a-zA-Z][a-zA-Z0-9]+$"
  533. # If FlagsOK is true, variables are allowed to be "set" by being put alone on
  534. #     a line; no assignment operator is needed.  These variables are set in
  535. #     the output array with a null value.  Lines containing nothing but
  536. #     whitespace are still ignored.
  537. # Output variables:
  538. # Values[] contains the assignments, with the indexes being the variable names
  539. #     and the values being the assigned values.
  540. # Lines[] contains the line number that each variable occured on.  A flag set
  541. #     is record by giving it an index in Lines[] but not in Values[].
  542. # Return value:
  543. # If any errors occur, a string consisting of descriptions of the errors
  544. # separated by newlines is returned.  In no case will the string start with a
  545. # numeric value.  If no errors occur,  the number of lines read is returned.
  546. function ReadConfigFile(Values,Lines,File,Comment,Assign,StripWhite,VarPat,
  547. FlagsOK,
  548. Line,Status,Errs,AssignLen,LineNum,Var,Val) {
  549.     if (Comment != "")
  550.     Comment = "^" Comment
  551.     AssignLen = length(Assign)
  552.     if (VarPat == "")
  553.     VarPat = "."    # null varname not allowed
  554.     while ((Status = (getline Line < File)) == 1) {
  555.     LineNum++
  556.     sub("^[ \t]+","",Line)
  557.     if (Line == "")        # blank line
  558.         continue
  559.     if (Comment != "" && Line ~ Comment)
  560.         continue
  561.     if (Pos = index(Line,Assign)) {
  562.         Var = substr(Line,1,Pos-1)
  563.         Val = substr(Line,Pos+AssignLen)
  564.         if (StripWhite) {
  565.         sub("^[ \t]+","",Val)
  566.         sub("[ \t]+$","",Val)
  567.         }
  568.     }
  569.     else {
  570.         Var = Line    # If no value, var is entire line
  571.         Val = ""
  572.     }
  573.     if (!FlagsOK && Val == "") {
  574.         Errs = Errs \
  575.         sprintf("\nBad assignment on line %d of file %s: %s",
  576.         LineNum,File,Line)
  577.         continue
  578.     }
  579.     sub("[ \t]+$","",Var)
  580.     if (Var !~ VarPat) {
  581.         Errs = Errs sprintf("\nBad variable name on line %d of file %s: %s",
  582.         LineNum,File,Var)
  583.         continue
  584.     }
  585.     if (!(Var in Lines)) {
  586.         Lines[Var] = LineNum
  587.         if (Pos)
  588.         Values[Var] = Val
  589.     }
  590.     }
  591.     if (Status)
  592.     Errs = Errs "\nCould not read file " File
  593.     close(File)
  594.     return Errs == "" ? LineNum : substr(Errs,2)    # Skip first newline
  595. }
  596.  
  597. # Variables:
  598. # Data is stored in Options[].
  599. # rcFiles, OptList, VarNames, and EnvSearch are as as described for Opts().
  600. # Global vars:
  601. # Sets OptErr.  Uses ENVIRON[].
  602. # If anything is read from any of the rcfiles, sets READ_RCFILE to 1.
  603. function InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch,
  604. Line,Var,Pos,Vars,Map,CharOpt,NumVars,TypesInd,Types,Type,Ret,i,rcFile,
  605. fNames,numrcFiles,filesRead,Err,Values,retStr) {
  606.     split("",filesRead,"")    # make awk know this is an array
  607.     NumVars = split(VarNames,Vars,",")
  608.     TypesInd = Ret = 0
  609.     if (EnvSearch == -1)
  610.     EnvSearch = NumVars
  611.     for (i = 1; i <= NumVars; i++) {
  612.     Var = Vars[i]
  613.     CharOpt = substr(OptList,++TypesInd,1)
  614.     if (CharOpt ~ "^[:;*()#<>&]$")
  615.         CharOpt = substr(OptList,++TypesInd,1)
  616.     Map[Var] = CharOpt
  617.     Types[Var] = Type = substr(OptList,TypesInd+1,1)
  618.     # Do not overwrite entries from environment
  619.     if (i <= EnvSearch && Var in ENVIRON &&
  620.     (Err = AssignVal(CharOpt,ENVIRON[Var],Options,Type,1,Var,0)) < 0)
  621.         return Err
  622.     }
  623.  
  624.     numrcFiles = split(rcFiles,fNames,":")
  625.     for (i = 1; i <= numrcFiles; i++) {
  626.     rcFile = fNames[i]
  627.     if (rcFile ~ "^~/")
  628.         rcFile = ENVIRON["HOME"] substr(rcFile,2)
  629.     else if (rcFile ~ /^\$/) {
  630.         rcFile = substr(rcFile,2)
  631.         match(rcFile,"^[a-zA-Z0-9_]*")
  632.         envvar = substr(rcFile,1,RLENGTH)
  633.         if (envvar in ENVIRON)
  634.         rcFile = ENVIRON[envvar] substr(rcFile,RLENGTH+1)
  635.         else
  636.         continue
  637.     }
  638.     if (rcFile in filesRead)
  639.         continue
  640.     # rcfiles are liable to be given more than once, e.g. UHOME and HOME
  641.     # may be the same
  642.     filesRead[rcFile]
  643.     if ("x" in Options)
  644.         printf "Reading configuration file %s\n",rcFile > "/dev/stderr"
  645.     retStr = ReadConfigFile(Values,Lines,rcFile,"#","=",0,"",1)
  646.     if (retStr > 0)
  647.         READ_RCFILE = 1
  648.     else if (ret != "") {
  649.         OptErr = retStr
  650.         Ret = -1
  651.     }
  652.     for (Var in Lines)
  653.         if (Var in Map) {
  654.         if ((Err = AssignVal(Map[Var],
  655.         Var in Values ? Values[Var] : "",Options,Types[Var],
  656.         Var in Values,Var,0)) < 0)
  657.             return Err
  658.         }
  659.         else {
  660.         OptErr = sprintf(\
  661.         "Unknown var \"%s\" assigned to on line %d\nof file %s",Var,
  662.         Lines[Var],rcFile)
  663.         Ret = -1
  664.         }
  665.     }
  666.  
  667.     if ("x" in Options)
  668.     for (Var in Map)
  669.         if (Map[Var] in Options)
  670.         printf "(%s) %s=%s\n",Map[Var],Var,Options[Map[Var]] > \
  671.         "/dev/stderr"
  672.         else
  673.         printf "(%s) %s not set\n",Map[Var],Var > "/dev/stderr"
  674.     return Ret
  675. }
  676.  
  677. # OptSets is a semicolon-separated list of sets of option sets.
  678. # Within a list of option sets, the option sets are separated by commas.  For
  679. # each set of sets, if any option in one of the sets is in Options[] AND any
  680. # option in one of the other sets is in Options[], an error string is returned.
  681. # If no conflicts are found, nothing is returned.
  682. # Example: if OptSets = "ab,def,g;i,j", an error will be returned due to
  683. # the exclusions presented by the first set of sets (ab,def,g) if:
  684. # (a or b is in Options[]) AND (d, e, or f is in Options[]) OR
  685. # (a or b is in Options[]) AND (g is in Options) OR
  686. # (d, e, or f is in Options[]) AND (g is in Options)
  687. # An error will be returned due to the exclusions presented by the second set
  688. # of sets (i,j) if: (i is in Options[]) AND (j is in Options[]).
  689. # todo: make options given on command line unset options given in config file
  690. # todo: that they conflict with.
  691. function ExclusiveOptions(OptSets,Options,
  692. Sets,SetSet,NumSets,Pos1,Pos2,Len,s1,s2,c1,c2,ErrStr,L1,L2,SetSets,NumSetSets,
  693. SetNum,OSetNum) {
  694.     NumSetSets = split(OptSets,SetSets,";")
  695.     # For each set of sets...
  696.     for (SetSet = 1; SetSet <= NumSetSets; SetSet++) {
  697.     # NumSets is the number of sets in this set of sets.
  698.     NumSets = split(SetSets[SetSet],Sets,",")
  699.     # For each set in a set of sets except the last...
  700.     for (SetNum = 1; SetNum < NumSets; SetNum++) {
  701.         s1 = Sets[SetNum]
  702.         L1 = length(s1)
  703.         for (Pos1 = 1; Pos1 <= L1; Pos1++)
  704.         # If any of the options in this set was given, check whether
  705.         # any of the options in the other sets was given.  Only check
  706.         # later sets since earlier sets will have already been checked
  707.         # against this set.
  708.         if ((c1 = substr(s1,Pos1,1)) in Options)
  709.             for (OSetNum = SetNum+1; OSetNum <= NumSets; OSetNum++) {
  710.             s2 = Sets[OSetNum]
  711.             L2 = length(s2)
  712.             for (Pos2 = 1; Pos2 <= L2; Pos2++)
  713.                 if ((c2 = substr(s2,Pos2,1)) in Options)
  714.                 ErrStr = ErrStr "\n"\
  715.                 sprintf("Cannot give both %s and %s options.",
  716.                 c1,c2)
  717.             }
  718.     }
  719.     }
  720.     if (ErrStr != "")
  721.     return substr(ErrStr,2)
  722.     return ""
  723. }
  724.  
  725. # The value of each instance of option Opt that occurs in Options[] is made an
  726. # index of Set[].
  727. # The return value is the number of instances of Opt in Options.
  728. function Opt2Set(Options,Opt,Set,  count) {
  729.     if (!(Opt in Options))
  730.     return 0
  731.     Set[Options[Opt]]
  732.     count = Options[Opt,"count"]
  733.     for (; count > 1; count--)
  734.     Set[Options[Opt,count]]
  735.     return count
  736. }
  737.  
  738. # The value of each instance of option Opt that occurs in Options[] that
  739. # begins with "!" is made an index of nSet[] (with the ! stripped from it).
  740. # Other values are made indexes of Set[].
  741. # The return value is the number of instances of Opt in Options.
  742. function Opt2Sets(Options,Opt,Set,nSet,  count,aSet,ret) {
  743.     ret = Opt2Set(Options,Opt,aSet)
  744.     for (value in aSet)
  745.     if (substr(value,1,1) == "!")
  746.         nSet[substr(value,2)]
  747.     else
  748.         Set[value]
  749.     return ret
  750. }
  751.  
  752. # Returns true if option Opt was given on the command line.
  753. function CmdLineOpt(Options,Opt,  i) {
  754.     for (i = 1; (Opt,"num",i) in Options; i++)
  755.     if (Options[Opt,"num",i] != 0)
  756.         return 1
  757.     return 0
  758. }
  759. ### End of ProcArgs library
  760.