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 make
8 combinators unicode.categories ;
13 CHAR: , delimiter set-global
15 : delimiter> ( -- delimiter ) delimiter get ; inline
17 DEFER: quoted-field ( -- endchar )
19 ! trims whitespace from either end of string
20 : trim-whitespace ( str -- str )
21 [ blank? ] trim ; inline
23 : skip-to-field-end ( -- endchar )
24 "\n" delimiter> suffix read-until nip ; inline
26 : not-quoted-field ( -- endchar )
27 "\"\n" delimiter> suffix read-until ! "
29 { { CHAR: " [ drop drop quoted-field ] } ! "
30 { delimiter> [ swap trim-whitespace % ] }
31 { CHAR: \n [ swap trim-whitespace % ] }
32 { f [ swap trim-whitespace % ] } ! eof
35 : maybe-escaped-quote ( -- endchar )
37 { { CHAR: " [ , quoted-field ] } ! " is an escaped quote
38 { delimiter> [ ] } ! end of quoted field
40 [ 2drop skip-to-field-end ] ! end of quoted field + padding
43 : quoted-field ( -- endchar )
45 drop % maybe-escaped-quote ;
47 : field ( -- sep string )
48 [ not-quoted-field ] "" make ; ! trim-whitespace
52 dup delimiter get = [ drop (row) ] when ;
54 : row ( -- eof? array[string] )
57 : append-if-row-not-empty ( row -- )
58 dup { "" } = [ drop ] [ , ] if ;
61 row append-if-row-not-empty
64 : csv-row ( stream -- row )
65 [ row nip ] with-input-stream ;
67 : csv ( stream -- rows )
68 [ [ (csv) ] { } make ] with-input-stream ;
70 : with-delimiter ( char quot -- )
71 delimiter swap with-variable ; inline
73 : needs-escaping? ( cell -- ? )
74 [ [ "\n\"" member? ] [ delimiter get = ] bi or ] contains? ; inline ! "
76 : escape-quotes ( cell -- cell' )
77 [ [ dup , CHAR: " = [ CHAR: " , ] when ] each ] "" make ; inline
79 : enclose-in-quotes ( cell -- cell' )
80 CHAR: " [ prefix ] [ suffix ] bi ; inline ! "
82 : escape-if-required ( cell -- cell' )
83 dup needs-escaping? [ escape-quotes enclose-in-quotes ] when ; inline
85 : write-row ( row -- )
86 [ delimiter get write1 ] [ escape-if-required write ] interleave nl ; inline
88 : write-csv ( rows stream -- )
89 [ [ write-row ] each ] with-output-stream ;