1 ! Copyright (C) 2010 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: arrays assocs combinators.short-circuit formatting
5 hashtables io io.streams.string kernel make math namespaces
6 quoting sequences splitting strings strings.parser ;
12 : escape ( ch -- ch' )
29 } ?at [ bad-escape ] unless ;
31 : (unescape-string) ( str -- )
33 cut-slice [ % ] dip rest-slice
34 dup empty? [ "Missing escape code" throw ] when
35 unclip-slice escape , (unescape-string)
38 : unescape-string ( str -- str' )
39 [ (unescape-string) ] "" make ;
41 : escape-string ( str -- str' )
65 "\s\t\n\r\f\v" member-eq? ;
67 : unspace ( str -- str' )
70 : unwrap ( str -- str' )
71 1 swap index-of-last subseq ;
73 : uncomment ( str -- str' )
74 ";#" [ over index [ head ] when* ] each ;
76 : cleanup-string ( str -- str' )
77 unspace unquote unescape-string ;
82 : section? ( line -- index/f )
86 [ CHAR: ] swap last-index ]
89 : line-continues? ( line -- ? )
93 section get [ , ] when* ;
95 : option, ( name value -- )
96 section get [ second swapd set-at ] [ 2array , ] if* ;
98 : [section] ( line -- )
99 unwrap cleanup-string H{ } clone 2array section set ;
101 : name=value ( line -- )
103 [ swap [ first2 ] dip ] [
104 "=" split1 [ cleanup-string "" ] [ "" or ] bi*
106 dup line-continues? [
107 dup length 1 - head cleanup-string
108 dup last space? [ " " append ] unless append 2array
110 cleanup-string append option, f
114 : parse-line ( line -- )
115 uncomment unspace dup section? [
116 section, 1 + cut [ [section] ] [ unspace ] bi*
117 ] when* [ name=value ] unless-empty ;
121 : read-ini ( -- assoc )
122 section off option off
123 [ [ parse-line ] each-line section, ] { } make
126 : write-ini ( assoc -- )
129 [ escape-string ] bi@ "%s=%s\n" printf
131 [ escape-string "[%s]\n" printf ] dip
132 [ [ escape-string ] bi@ "%s=%s\n" printf ]
137 ! FIXME: escaped comments "\;" don't work
139 : string>ini ( str -- assoc )
140 [ read-ini ] with-string-reader ;
142 : ini>string ( assoc -- str )
143 [ write-ini ] with-string-writer ;