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 : skip-to-field-end ( -- endchar )
19 "\n" delimiter> suffix read-until nip ; inline
21 : not-quoted-field ( -- endchar )
22 "\"\n" delimiter> suffix read-until
24 { CHAR: " [ 2drop quoted-field ] }
25 { delimiter> [ swap [ blank? ] trim % ] }
26 { CHAR: \n [ swap [ blank? ] trim % ] }
27 { f [ swap [ blank? ] trim % ] }
30 : maybe-escaped-quote ( -- endchar )
32 { CHAR: " [ , quoted-field ] }
35 [ 2drop skip-to-field-end ]
38 : quoted-field ( -- endchar )
40 drop % maybe-escaped-quote ;
42 : field ( -- sep string )
43 [ not-quoted-field ] "" make ;
47 dup delimiter> = [ drop (row) ] when ;
49 : row ( -- eof? array[string] )
54 dup [ empty? ] all? [ drop ] [ , ] if
59 : csv-row ( stream -- row )
60 [ row nip ] with-input-stream ;
62 : csv ( stream -- rows )
63 [ [ (csv) ] { } make ] with-input-stream
64 dup last { "" } = [ but-last ] when ;
66 : string>csv ( string -- csv )
69 : file>csv ( path encoding -- csv )
72 : with-delimiter ( ch quot -- )
73 [ delimiter ] dip with-variable ; inline
77 : needs-escaping? ( cell -- ? )
78 [ { [ "\n\"" member? ] [ delimiter> = ] } 1|| ] any? ; inline
80 : escape-quotes ( cell -- cell' )
84 [ dup CHAR: " = [ , ] [ drop ] if ] bi
88 : enclose-in-quotes ( cell -- cell' )
89 "\"" dup surround ; inline
91 : escape-if-required ( cell -- cell' )
93 [ escape-quotes enclose-in-quotes ] when ; inline
97 : write-row ( row -- )
99 [ escape-if-required write ] interleave nl ; inline
103 : (write-csv) ( rows -- )
108 : write-csv ( rows stream -- )
109 [ (write-csv) ] with-output-stream ;
111 : csv>string ( csv -- string )
112 [ (write-csv) ] with-string-writer ;
114 : csv>file ( rows path encoding -- ) <file-writer> write-csv ;