1 ! Copyright (C) 2007, 2008 Phil Dawes
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel sequences io namespaces make combinators
4 unicode.categories io.files combinators.short-circuit
10 CHAR: , delimiter set-global
14 : delimiter> ( -- delimiter ) delimiter get ; inline
16 DEFER: quoted-field ( -- endchar )
18 : trim-whitespace ( str -- str )
19 [ blank? ] trim ; inline
21 : skip-to-field-end ( -- endchar )
22 "\n" delimiter> suffix read-until nip ; inline
24 : not-quoted-field ( -- endchar )
25 "\"\n" delimiter> suffix read-until
27 { CHAR: " [ 2drop quoted-field ] }
28 { delimiter> [ swap trim-whitespace % ] }
29 { CHAR: \n [ swap trim-whitespace % ] }
30 { f [ swap trim-whitespace % ] }
33 : maybe-escaped-quote ( -- endchar )
35 { CHAR: " [ , quoted-field ] }
38 [ 2drop skip-to-field-end ]
41 : quoted-field ( -- endchar )
43 drop % maybe-escaped-quote ;
45 : field ( -- sep string )
46 [ not-quoted-field ] "" make ;
50 dup delimiter> = [ drop (row) ] when ;
52 : row ( -- eof? array[string] )
57 dup [ empty? ] all? [ drop ] [ , ] if
62 : csv-row ( stream -- row )
63 [ row nip ] with-input-stream ;
65 : csv ( stream -- rows )
66 [ [ (csv) ] { } make ] with-input-stream
67 dup last { "" } = [ but-last ] when ;
69 : string>csv ( string -- csv )
72 : file>csv ( path encoding -- csv )
75 : with-delimiter ( ch quot -- )
76 [ delimiter ] dip with-variable ; inline
80 : needs-escaping? ( cell -- ? )
81 [ { [ "\n\"" member? ] [ delimiter get = ] } 1|| ] any? ; inline
83 : escape-quotes ( cell -- cell' )
87 [ dup CHAR: " = [ , ] [ drop ] if ] bi
91 : enclose-in-quotes ( cell -- cell' )
92 "\"" dup surround ; inline
94 : escape-if-required ( cell -- cell' )
96 [ escape-quotes enclose-in-quotes ] when ; inline
100 : write-row ( row -- )
101 [ delimiter get write1 ]
102 [ escape-if-required write ] interleave nl ; inline
106 : (write-csv) ( rows -- )
111 : write-csv ( rows stream -- )
112 [ (write-csv) ] with-output-stream ;
114 : csv>string ( csv -- string )
115 [ (write-csv) ] with-string-writer ;
117 : csv>file ( rows path encoding -- ) <file-writer> write-csv ;