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 vars ;
14 ! trims whitespace from either end of string
15 : trim-whitespace ( str -- str )
16 [ blank? ] trim ; inline
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: " [ drop drop quoted-field ] } ! "
25 { delimiter> [ swap trim-whitespace % ] }
26 { CHAR: \n [ swap trim-whitespace % ] }
27 { f [ swap trim-whitespace % ] } ! eof
30 : maybe-escaped-quote ( -- endchar )
32 { { CHAR: " [ , quoted-field ] } ! " is an escaped quote
33 { delimiter> [ ] } ! end of quoted field
35 [ 2drop skip-to-field-end ] ! end of quoted field + padding
38 : quoted-field ( -- endchar )
40 drop % maybe-escaped-quote ;
42 : field ( -- sep string )
43 [ not-quoted-field ] "" make ; ! trim-whitespace
47 dup delimiter> = [ drop (row) ] when ;
49 : row ( -- eof? array[string] )
52 : append-if-row-not-empty ( row -- )
53 dup { "" } = [ drop ] [ , ] if ;
56 row append-if-row-not-empty
60 delimiter> [ CHAR: , >delimiter ] unless ; inline
62 : csv-row ( stream -- row )
64 [ row nip ] with-input-stream ;
66 : csv ( stream -- rows )
68 [ [ (csv) ] { } make ] with-input-stream ;
70 : with-delimiter ( char quot -- )
71 delimiter swap with-variable ; inline
75 : needs-escaping? ( cell -- ? )
76 [ "\n\"" delimiter> suffix member? ] contains? ; inline ! "
78 : escape-quotes ( cell -- cell' )
79 [ [ dup , CHAR: " = [ CHAR: " , ] when ] each ] "" make ; inline
81 : enclose-in-quotes ( cell -- cell' )
82 CHAR: " [ prefix ] [ suffix ] bi ; inline ! "
84 : escape-if-required ( cell -- cell' )
85 dup needs-escaping? [ escape-quotes enclose-in-quotes ] when ; inline
87 : write-row ( row -- )
88 [ delimiter> write1 ] [ escape-if-required write ] interleave nl ; inline
90 : write-csv ( rows outstream -- )
92 [ [ write-row ] each ] with-output-stream ;