summaryrefslogtreecommitdiff
path: root/lib/yaml/emitter.rb
blob: 4b8541c2c3f5db8466e657d79176b8e2f174d969 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#
# Output classes and methods
#

require 'yaml/constants'
require 'yaml/encoding'
require 'yaml/error'

module YAML

	#
	# Emit a set of values
	#
    
	class Emitter
		attr_accessor :options
		def initialize( opts )
			opts = {} if opts.class != Hash
			@options = YAML::DEFAULTS.dup.update( opts )
            @headless = 0
            @seq_map = false
            @anchors = {}
            @anchor_extras = {}
            @active_anchors = []
            @level = -1
            self.clear
		end

		def clear
			@buffer = []
		end

		#
		# Version string
		#
		def version_s
			" %YAML:#{@options[:Version]}" if @options[:UseVersion]
		end

		#
		# Header
		#
		def header
            if @headless.nonzero?
                ""
            else
                "---#{version_s} "
            end
		end

        #
        # Emit binary data
        #
        def binary_base64( value )
            self << "!binary "
            self.node_text( [value].pack("m"), '|' )
        end

		#
		# Emit plain, normal flowing text
		#
		def node_text( value, block = '>' )
			valx = value.dup
			if @options[:UseBlock]
				block = '|'
			elsif not @options[:UseFold] and valx =~ /\n[ \t]/ and not valx =~ /#{YAML::ESCAPE_CHAR}/
				block = '|'
			end 
			str = block.dup
			if valx =~ /\n\Z\n/
				str << "+"
			elsif valx =~ /\Z\n/
			else
				str << "-"
			end
			if valx =~ /#{YAML::ESCAPE_CHAR}/
				valx = YAML::escape( valx )
			end
			if valx =~ /\A[ \t#]/
				str << @options[:Indent].to_s
			end
			if block == '>'
				valx = fold( valx ) 
			end
			self << str + indent_text( valx ) + "\n"
		end

		#
		# Emit a simple, unqouted string
		#
		def simple( value )
            self << value.to_s
		end

		#
		# Emit double-quoted string
		#
		def double( value )
			"\"#{YAML.escape( value )}\"" 
		end

		#
		# Emit single-quoted string
		#
		def single( value )
			"'#{value}'"
		end

		#
		# Write a text block with the current indent
		#
		def indent_text( text )
			return "" if text.to_s.empty?
            spacing = " " * ( @level * @options[:Indent] )
			return "\n" + text.gsub( /^([^\n])/, "#{spacing}\\1" )
		end

		#
		# Write a current indent
		#
		def indent
            #p [ self.id, @level, :INDENT ]
			return " " * ( @level * @options[:Indent] )
		end

		#
		# Add indent to the buffer
		#
		def indent!
			self << indent
		end

		#
		# Folding paragraphs within a column
		#
		def fold( value )
			value.gsub!( /\A\n+/, '' )
			folded = $&.to_s
			width = (0..@options[:BestWidth])
			while not value.empty?
				last = value.index( /(\n+)/ )
				chop_s = false
				if width.include?( last )
					last += $1.length - 1
				elsif width.include?( value.length )
					last = value.length
				else
					last = value.rindex( /[ \t]/, @options[:BestWidth] )
					chop_s = true
				end
				folded += value.slice!( 0, width.include?( last ) ? last + 1 : @options[:BestWidth] )
				folded.chop! if chop_s
				folded += "\n" unless value.empty?
			end
			folded
		end

        #
        # Quick mapping
        #
        def map( type, &e )
            val = Mapping.new
            e.call( val )
			self << "#{type} " if type.length.nonzero?

			#
			# Empty hashes
			#
			if val.length.zero?
				self << "{}"
			else
                if @buffer.length == 1 and @options[:UseHeader] == false and type.length.zero? 
			        @headless = 1 
                end

                defkey = @options.delete( :DefaultKey )
                if defkey
                    seq_map_shortcut
                    self << "= : "
                    defkey.to_yaml( :Emitter => self )
                end

				#
				# Emit the key and value
				#
                val.each { |v|
                    seq_map_shortcut
                    if v[0].is_complex_yaml?
                        self << "? "
                    end
                    v[0].to_yaml( :Emitter => self )
                    if v[0].is_complex_yaml?
                        self << "\n"
                        indent!
                    end
                    self << ": " 
                    v[1].to_yaml( :Emitter => self )
                }
			end
        end

        def seq_map_shortcut
            if @seq_map
                @anchor_extras[@buffer.length - 1] = "\n" + indent
                @seq_map = false
            else
                self << "\n"
                indent! 
            end
        end

        #
        # Quick sequence
        #
        def seq( type, &e )
            val = Sequence.new
            e.call( val )
			self << "#{type} " if type.length.nonzero?

			#
			# Empty arrays
			#
			if val.length.zero?
				self << "[]"
			else
                if @buffer.length == 1 and @options[:UseHeader] == false and type.length.zero? 
			        @headless = 1 
                end
				#
				# Emit the key and value
				#
                val.each { |v|
                    self << "\n"
                    indent!
                    self << "- "
                    @seq_map = true if v.class == Hash
                    v.to_yaml( :Emitter => self )
                }
			end
        end

		#
		# Concatenate to the buffer
		#
		def <<( str )
            #p [ self.id, @level, str ]
			@buffer.last << str
		end

        #
        # Monitor objects and allow references
        #
        def start_object( oid )
		    @level += 1
            @buffer.push( "" )
            #p [ self.id, @level, :OPEN ]
            idx = nil
            if oid
                if @anchors.has_key?( oid )
                    idx = @active_anchors.index( oid )
                    unless idx
                        idx = @active_anchors.length
                        af_str = "&#{@options[:AnchorFormat]} " % [ idx + 1 ]
                        af_str += @anchor_extras[ @anchors[ oid ] ].to_s
                        @buffer[ @anchors[ oid ] ][0,0] = af_str
					    @headless = 0 if @anchors[ oid ].zero?
                    end
                    idx += 1
                    @active_anchors.push( oid )
                else
                    @anchors[ oid ] = @buffer.length - 1
                end
            end
            return idx
        end

		#
		# Output method
		#
		def end_object
		    @level -= 1
            @buffer.push( "" )
            #p [ self.id, @level, :END ]
			if @level < 0
				YAML.internal_to_utf( header + @buffer.to_s[@headless..-1], @options[:Encoding] )
			end
		end
	end

    #
    # Emitter helper classes
    #
    class Mapping < Array
        def add( k, v )
            push [k, v]
        end
    end

    class Sequence < Array
        def add( v )
            push v
        end
    end

	#
	# Allocate an Emitter if needed
	#
	def YAML.quick_emit( oid, opts = {}, &e )
		old_opt = nil
		if opts[:Emitter].is_a? YAML::Emitter
			out = opts.delete( :Emitter )
			old_opt = out.options.dup
			out.options.update( opts )
		else
			out = YAML::Emitter.new( opts )
		end
        aidx = out.start_object( oid )
        if aidx
            out.simple( "*#{out.options[:AnchorFormat]} " % [ aidx ] )
        else
            e.call( out )
        end
		if old_opt.is_a? Hash
			out.options = old_opt
		end 
		out.end_object
	end
	
end