@@ -42,6 +42,7 @@ pub struct YamlEmitter<'a> {
4242 best_indent : usize ,
4343 compact : bool ,
4444 escape_all_strings : bool ,
45+ multiline_strings : bool ,
4546
4647 level : isize ,
4748}
@@ -119,6 +120,7 @@ impl<'a> YamlEmitter<'a> {
119120 compact : true ,
120121 level : -1 ,
121122 escape_all_strings : false ,
123+ multiline_strings : false ,
122124 }
123125 }
124126
@@ -152,6 +154,42 @@ impl<'a> YamlEmitter<'a> {
152154 self . escape_all_strings
153155 }
154156
157+ /// Render strings containing multiple lines in [literal style].
158+ ///
159+ /// # Examples
160+ ///
161+ /// ```rust
162+ /// use yaml_rust::{Yaml, YamlEmitter, YamlLoader};
163+ ///
164+ /// let input = r#"{foo: "bar!\nbar!", baz: 42}"#;
165+ /// let parsed = YamlLoader::load_from_str(input).unwrap();
166+ /// eprintln!("{:?}", parsed);
167+ ///
168+ /// let mut output = String::new();
169+ /// # {
170+ /// let mut emitter = YamlEmitter::new(&mut output);
171+ /// emitter.multiline_strings(true);
172+ /// emitter.dump(&parsed[0]).unwrap();
173+ /// # }
174+ ///
175+ /// assert_eq!(output.as_str(), "\
176+ /// ---
177+ /// foo: |
178+ /// bar!
179+ /// bar!
180+ /// baz: 42");
181+ /// ```
182+ ///
183+ /// [literal style]: https://yaml.org/spec/1.2/spec.html#id2795688
184+ pub fn multiline_strings ( & mut self , multiline_strings : bool ) {
185+ self . multiline_strings = multiline_strings
186+ }
187+
188+ /// Determine if this emitter will wrap all strings in double-quotes.
189+ pub fn is_multiline_strings ( & self ) -> bool {
190+ self . multiline_strings
191+ }
192+
155193 pub fn dump ( & mut self , doc : & Yaml ) -> EmitResult {
156194 // write DocumentStart
157195 writeln ! ( self . writer, "---" ) ?;
@@ -176,7 +214,16 @@ impl<'a> YamlEmitter<'a> {
176214 Yaml :: Array ( ref v) => self . emit_array ( v) ,
177215 Yaml :: Hash ( ref h) => self . emit_hash ( h) ,
178216 Yaml :: String ( ref v) => {
179- if need_quotes ( v) | self . escape_all_strings {
217+ if self . multiline_strings && v. contains ( '\n' ) {
218+ write ! ( self . writer, "|" ) ?;
219+ self . level += 1 ;
220+ for line in v. lines ( ) {
221+ writeln ! ( self . writer) ?;
222+ self . write_indent ( ) ?;
223+ write ! ( self . writer, "{}" , line) ?;
224+ }
225+ self . level -= 1 ;
226+ } else if self . escape_all_strings || need_quotes ( v) {
180227 escape_str ( self . writer , v) ?;
181228 } else {
182229 write ! ( self . writer, "{}" , v) ?;
0 commit comments