1 ! Copyright (C) 2007, 2008 Phil Dawes
2 ! See http://factorcode.org/license.txt for BSD license.
5 ! Phil Dawes phil@phildawes.net
7 USING: kernel sequences io namespaces combinators unicode.categories ;
12 CHAR: , delimiter set-global
14 : delimiter> delimiter get ; inline
16 DEFER: quoted-field ( -- endchar )
18 ! trims whitespace from either end of string
19 : trim-whitespace ( str -- str )
20 [ blank? ] trim ; inline
22 : skip-to-field-end ( -- endchar )
23 "\n" delimiter> suffix read-until nip ; inline
25 : not-quoted-field ( -- endchar )
26 "\"\n" delimiter> suffix read-until ! "
28 { { CHAR: " [ drop drop quoted-field ] } ! "
29 { delimiter> [ swap trim-whitespace % ] }
30 { CHAR: \n [ swap trim-whitespace % ] }
31 { f [ swap trim-whitespace % ] } ! eof
34 : maybe-escaped-quote ( -- endchar )
36 { { CHAR: " [ , quoted-field ] } ! " is an escaped quote
37 { delimiter> [ ] } ! end of quoted field
39 [ 2drop skip-to-field-end ] ! end of quoted field + padding
42 : quoted-field ( -- endchar )
44 drop % maybe-escaped-quote ;
46 : field ( -- sep string )
47 [ not-quoted-field ] "" make ; ! trim-whitespace
51 dup delimiter get = [ drop (row) ] when ;
53 : row ( -- eof? array[string] )
56 : append-if-row-not-empty ( row -- )
57 dup { "" } = [ drop ] [ , ] if ;
60 row append-if-row-not-empty
63 : csv-row ( stream -- row )
64 [ row nip ] with-input-stream ;
66 : csv ( stream -- rows )
67 [ [ (csv) ] { } make ] with-input-stream ;
69 : with-delimiter ( char quot -- )
70 delimiter swap with-variable ; inline
72 : needs-escaping? ( cell -- ? )
73 [ [ "\n\"" member? ] [ delimiter get = ] bi or ] contains? ; inline ! "
75 : escape-quotes ( cell -- cell' )
76 [ [ dup , CHAR: " = [ CHAR: " , ] when ] each ] "" make ; inline
78 : enclose-in-quotes ( cell -- cell' )
79 CHAR: " [ prefix ] [ suffix ] bi ; inline ! "
81 : escape-if-required ( cell -- cell' )
82 dup needs-escaping? [ escape-quotes enclose-in-quotes ] when ; inline
84 : write-row ( row -- )
85 [ delimiter get write1 ] [ escape-if-required write ] interleave nl ; inline
87 : write-csv ( rows stream -- )
88 [ [ write-row ] each ] with-output-stream ;