@@ -760,7 +760,15 @@ function detectType(state, object, explicit) {
760760 ( ! type . instanceOf || ( ( typeof object === 'object' ) && ( object instanceof type . instanceOf ) ) ) &&
761761 ( ! type . predicate || type . predicate ( object ) ) ) {
762762
763- state . tag = explicit ? type . tag : '?' ;
763+ if ( explicit ) {
764+ if ( type . multi && type . representName ) {
765+ state . tag = type . representName ( object ) ;
766+ } else {
767+ state . tag = type . tag ;
768+ }
769+ } else {
770+ state . tag = '?' ;
771+ }
764772
765773 if ( type . represent ) {
766774 style = state . styleMap [ type . tag ] || type . defaultStyle ;
@@ -796,6 +804,7 @@ function writeNode(state, level, object, block, compact, iskey, isblockseq) {
796804
797805 var type = _toString . call ( state . dump ) ;
798806 var inblock = block ;
807+ var tagStr ;
799808
800809 if ( block ) {
801810 block = ( state . flowLevel < 0 || state . flowLevel > level ) ;
@@ -860,7 +869,30 @@ function writeNode(state, level, object, block, compact, iskey, isblockseq) {
860869 }
861870
862871 if ( state . tag !== null && state . tag !== '?' ) {
863- state . dump = '!<' + state . tag + '> ' + state . dump ;
872+ // Need to encode all characters except those allowed by the spec:
873+ //
874+ // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */
875+ // [36] ns-hex-digit ::= ns-dec-digit
876+ // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */
877+ // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */
878+ // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-”
879+ // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#”
880+ // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”
881+ // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]”
882+ //
883+ // Also need to encode '!' because it has special meaning (end of tag prefix).
884+ //
885+ tagStr = encodeURI (
886+ state . tag [ 0 ] === '!' ? state . tag . slice ( 1 ) : state . tag
887+ ) . replace ( / ! / g, '%21' ) ;
888+
889+ if ( state . tag [ 0 ] === '!' ) {
890+ tagStr = '!' + tagStr ;
891+ } else {
892+ tagStr = '!<' + tagStr + '>' ;
893+ }
894+
895+ state . dump = tagStr + ' ' + state . dump ;
864896 }
865897 }
866898
0 commit comments