############################################################################
#
#	File:     word.icn
#
#	Subject:  Procedure to scan UNIX-style command line words
#
#	Author:   Robert J. Alexander
#
#	Date:     August 14, 1996
#
############################################################################
#
#   This file is in the public domain.
#
############################################################################
#
#  word(s) -- Produces the position past a UNIX-style command line
#  word.
#
#  dequote(s) -- Produces the UNIX-style command line word s with any
#  quoting characters removed.
#
############################################################################
#
#  Links: scanset
#
############################################################################

link scanset

#
#  word(s) -- Produces the position past a UNIX-style command line
#  word.
#
procedure word(s,i1,i2)
   local c,d,p,e,x
   x := scan_setup(s,i1,i2)
   x.ss ? {
      (while tab(upto(' \t"\'')) do {
	 if (c := move(1)) == ("\"" | "'") then {
	    e := c ++ "\\"
	    while tab(upto(e)) do {
	       d := move(1)
	       if d == c then break
	       move(1)
	       }
	    }
	 else break
	 }) | "" ~== tab(0) | fail
      p := &pos
      }
   return x.offset + p
end


#
#  dequote(s) -- Produces the UNIX-style command line word s with any
#  quoting characters removed.
#

procedure word_dequote(s)
   local c,d
   s ? {
      s := ""
      while s ||:= tab(upto('"\'\\')) do {
	 c := move(1)
	 if c == "\\" then s ||:= move(1)
	 else {
	    if \d then (s ||:= d ~== c) | (d := &null)
	    else d := c
	    }
	 }
      return s || tab(0)
      }
end
