all files / src/dm/ ve.dm.Converter.js

95.38% Statements 661/693
90.25% Branches 500/554
87.76% Functions 43/49
95.38% Lines 661/693
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 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786                                                                                                        2509×     2509× 2200×     309×   819×   309×                               5935×         5935× 1738× 1738× 1943×     1943×       1414×   529× 529×     1738×     529× 594×   594×         5935× 1966×   1966× 2255×     2255×             1414×   841×   841×                               1676×   1676×     1676×     1667× 1693× 73×   1620× 1620× 11×   1609× 397×         314× 94×   220×   314×     397× 382×             1609× 49×                                                 561×       32× 32× 30× 30× 30×         561× 12861× 12861×   819×   12861×   5871×   6990×   3511×   32× 32× 32× 30× 30×             30×   30×             3479×               3479× 3479× 2536× 30× 30×     30× 30× 30× 30×   30× 30×                                           176×                                               2817×                               17×               56×               2744×               317×               263×                                     74× 74×                 93×   93×     93× 93×                 85× 85×                 11× 11×                             1769×       1769×     1769×     1769× 1769×     1769×   1769× 542×                             1769× 84× 86×     95× 95×           1769× 1165× 1165×     1769×                   3005×     3005×     3005× 2993×   3005× 3005× 327×   327×     2678×   3005×       3005×   1800× 1800×     3005×                                                         561×     561× 561×     561× 561× 561× 561× 561× 561×       561× 561×   561× 561× 561× 561×     561× 561× 561× 561× 561× 561×   561×                           12× 12× 12× 12× 12×                       3375×                                             229×   228× 13×           228× 120×   228×       3485× 20× 20×       3798×       3798× 20× 10×         10×   20×   3798×     15×   3783×   3798×       741×       741× 741× 741× 741× 741×   741×   11×   11× 11×   741× 741× 741× 741× 741× 741×   2993×     2993× 2975×   18× 18× 23× 12×   11×     18×   918× 918× 906× 906× 574× 574× 548×     332×     38×     3375×     3375×     3375× 3375× 3375× 3375× 3375× 3375×     3375× 2485×     37×   3375× 4818× 4818×     2993×           2993× 2993× 2993× 2993× 327×     2666×     2993×   2993×           2993×   2993×           2993× 327×   327× 45× 45×     327× 327×   327× 327×                 327× 327×   327×     2666× 41×   28×         41× 41×     41×       41× 10× 10×     31× 31× 31× 31×     41× 41×     2625×     2625× 14× 14× 2611× 36× 33×                 2625× 29× 29×   29×       2625× 13×       2625×               2473× 2473×           152× 140×     152× 152×   2625× 2625×     2625×   2952×   1825× 1825×       1825×   739×   42×       12× 12× 12×         30× 12×               18×   30× 30× 30×     42×           697× 697×   682×       682× 11×                 11×     15×     15×         697×                     697× 697× 697×     697× 697×             1086×         660× 660× 64× 64×     1086×             631× 631× 64× 64×         1086×     1086×       3375× 708×   708×         3375×         57× 57× 57× 57×       3375×       2485× 15× 15×   2485×     3375× 31× 31× 31× 31×     3375× 3375×                 561×         561× 561× 561×   561×   561× 561× 7786× 2115× 5671× 2316× 2316× 201×       561× 561×   561×                   405×     405×     405×   405×   405×                                                 453×     453×   453× 453× 453×   453× 453×   453×     453× 453× 453× 453× 453×                     469×                               348× 31× 31×   348× 348×     348×                   348× 114× 114×     348× 348×       348× 312× 312×           38× 38× 38× 22×     16×   16×   312× 312×           32× 32× 32× 20×     12×   12×       348× 346×         348× 36×   348× 343× 449×   343×       348× 28×       16× 16× 158× 80×     16×     16×     1423× 1423×       16×   1407×   1423×     2697×         2697×     469× 3924×   676× 676×           676×     1921× 1914× 1914×   1921×     676×   676× 676×   3248×               192× 192× 192× 192×                 846×     846×       846×   783×       63× 28× 28×     63× 63× 63× 63×   63×     63×     846×     192×     192× 158× 158×     192×       192× 324×   3056× 3056×   3056×   1360× 1360× 1360×     1360× 1360×               196× 196× 48×         37×     11× 11× 11×           196×         196× 196×       137×   59×   196× 82×   53×     29× 29× 29×           196× 1164×     1073×               1360× 1360× 1360×           21×                           17×   21×         277× 277×     277× 61× 61×         61×     18×     277×     1360× 296×   277× 428×                 19×   296×     1360× 1360×     1360× 1360×       1696×   336×   1360×   1360× 1360× 1360×       1360×     1360×         1360× 1377×     1360× 1360×                     1360×   196× 196× 196×   61× 135×   59×     76×       53×   53×       196×   99× 99× 99×         1164×                         1360× 16× 1344×             469×       34×   28×   12×   34×     469×          
/*!
 * VisualEditor DataModel Converter class.
 *
 * @copyright 2011-2019 VisualEditor Team and others; see http://ve.mit-license.org
 */
 
/**
 * DataModel converter.
 *
 * Converts between HTML DOM and VisualEditor linear data.
 *
 * @class
 * @constructor
 * @param {ve.dm.ModelRegistry} modelRegistry
 * @param {ve.dm.NodeFactory} nodeFactory
 * @param {ve.dm.AnnotationFactory} annotationFactory
 */
ve.dm.Converter = function VeDmConverter( modelRegistry, nodeFactory, annotationFactory ) {
	// Properties
	this.modelRegistry = modelRegistry;
	this.nodeFactory = nodeFactory;
	this.annotationFactory = annotationFactory;
	this.doc = null;
	this.documentData = null;
	this.store = null;
	this.internalList = null;
	this.mode = null;
	this.fromClipboard = null;
	this.contextStack = null;
};
 
/* Inheritance */
 
OO.initClass( ve.dm.Converter );
 
/* Static Properties */
 
/**
 * List of HTML attribute names that {#renderHtmlAttributeList} should use computed values for.
 *
 * @type {string[]}
 */
ve.dm.Converter.static.computedAttributes = [ 'href', 'src' ];
 
/**
 * Pattern matching 'white space characters' as defined by the HTML spec only.
 *
 * All other whitespace should be treated as text, e.g. non-breaking spaces.
 *
 * See https://www.w3.org/TR/html4/struct/text.html#h-9.1
 *
 * @type {RegExp}
 */
ve.dm.Converter.static.whitespaceList = ' \\t\\f\\u200b\\r\\n';
 
ve.dm.Converter.static.PARSER_MODE = 0;
ve.dm.Converter.static.CLIPBOARD_MODE = 1;
ve.dm.Converter.static.PREVIEW_MODE = 2;
 
/* Static Methods */
 
/**
 * Get linear model data from a string optionally applying annotations
 *
 * @static
 * @param {string} text Plain text to convert
 * @param {ve.dm.AnnotationSet} [annotations] Annotations to apply
 * @return {Array} Linear model data, one element per character
 */
ve.dm.Converter.static.getDataContentFromText = function ( text, annotations ) {
	var i, len,
		characters = text.split( '' );
 
	if ( !annotations || annotations.isEmpty() ) {
		return characters;
	}
	// Apply annotations to characters
	for ( i = 0, len = characters.length; i < len; i++ ) {
		// Just store the annotations' hashes from the hash-value store
		characters[ i ] = [ characters[ i ], annotations.getHashes().slice() ];
	}
	return characters;
};
 
/**
 * Utility function for annotation rendering. Transforms one set of annotations into another
 * by opening and closing annotations. Each time an annotation is opened or closed, the associated
 * callback is called with the annotation passed as a parameter.
 *
 * Note that currentSet will be modified, and will be equal to targetSet once this function returns.
 *
 * @static
 * @param {ve.dm.AnnotationSet} currentSet The set of annotations currently opened. Will be modified.
 * @param {ve.dm.AnnotationSet} targetSet The set of annotations we want to have.
 * @param {Function} open Callback called when an annotation is opened. Passed a ve.dm.Annotation.
 * @param {Function} close Callback called when an annotation is closed. Passed a ve.dm.Annotation.
 */
ve.dm.Converter.static.openAndCloseAnnotations = function ( currentSet, targetSet, open, close ) {
	var i, len, hash, startClosingAt, currentSetOpen, targetSetOpen;
 
	// Close annotations as needed
	// Go through annotationStack from bottom to top (low to high),
	// and find the first annotation that's not in annotations.
	if ( currentSet.getLength() ) {
		targetSetOpen = targetSet.clone();
		for ( i = 0, len = currentSet.getLength(); i < len; i++ ) {
			hash = currentSet.getHash( i );
			// containsComparableForSerialization is expensive,
			// so do a simple contains check first
			if (
				targetSetOpen.containsHash( hash ) ||
				targetSetOpen.containsComparableForSerialization( currentSet.get( i ) )
			) {
				targetSetOpen.removeHash( hash );
			} else {
				startClosingAt = i;
				break;
			}
		}
		if ( startClosingAt !== undefined ) {
			// Close all annotations from top to bottom (high to low)
			// until we reach startClosingAt
			for ( i = currentSet.getLength() - 1; i >= startClosingAt; i-- ) {
				close( currentSet.get( i ) );
				// Remove from currentClone
				currentSet.removeAt( i );
			}
		}
	}
 
	if ( targetSet.getLength() ) {
		currentSetOpen = currentSet.clone();
		// Open annotations as needed
		for ( i = 0, len = targetSet.getLength(); i < len; i++ ) {
			hash = targetSet.getHash( i );
			// containsComparableForSerialization is expensive,
			// so do a simple contains check first
			if (
				currentSetOpen.containsHash( hash ) ||
				currentSetOpen.containsComparableForSerialization( targetSet.get( i ) )
			) {
				// If an annotation is already open remove it from the currentSetOpen list
				// as it may exist multiple times in the targetSet, and so may need to be
				// opened again
				currentSetOpen.removeHash( hash );
			} else {
				open( targetSet.get( i ) );
				// Add to currentClone
				currentSet.pushHash( hash );
			}
		}
	}
};
 
/**
 * Copy attributes from one set of DOM elements to another.
 *
 * @static
 * @param {HTMLElement[]} originalDomElements Array of DOM elements to render from
 * @param {HTMLElement[]} targetDomElements Array of DOM elements to render onto
 * @param {boolean|Function} [filter=true] Attribute filter
 * @param {boolean} [computed=false] If true, use the computed values of attributes where available
 * @param {boolean} [deep=false] Recurse into child nodes
 */
ve.dm.Converter.static.renderHtmlAttributeList = function ( originalDomElements, targetDomElements, filter, computed, deep ) {
	var i, ilen, j, jlen, attrs, value;
 
	Iif ( filter === undefined ) {
		filter = true;
	}
	if ( filter === false ) {
		return;
	}
 
	for ( i = 0, ilen = originalDomElements.length; i < ilen; i++ ) {
		if ( !targetDomElements[ i ] ) {
			continue;
		}
		attrs = originalDomElements[ i ].attributes;
		if ( !attrs ) {
			continue;
		}
		for ( j = 0, jlen = attrs.length; j < jlen; j++ ) {
			if (
				targetDomElements[ i ].nodeType === Node.ELEMENT_NODE &&
				!targetDomElements[ i ].hasAttribute( attrs[ j ].name ) &&
				( filter === true || filter( attrs[ j ].name ) )
			) {
				if ( computed && this.computedAttributes.indexOf( attrs[ j ].name ) !== -1 ) {
					value = originalDomElements[ i ][ attrs[ j ].name ];
				} else {
					value = attrs[ j ].value;
				}
				targetDomElements[ i ].setAttribute( attrs[ j ].name, value );
			}
 
			if ( filter === true || filter( attrs[ j ].name ) ) {
				value = computed && this.computedAttributes.indexOf( attrs[ j ].name ) !== -1 ?
					originalDomElements[ i ][ attrs[ j ].name ] :
					attrs[ j ].value;
			}
		}
 
		// Descend into element children only (skipping text nodes, comment nodes and nodes we just created)
		if ( deep && !targetDomElements[ i ].veFromDataElement && originalDomElements[ i ].children.length > 0 ) {
			this.renderHtmlAttributeList(
				originalDomElements[ i ].children,
				targetDomElements[ i ].children,
				filter,
				computed,
				true
			);
		}
	}
};
 
/**
 * Modify linear model data in-place to move inline meta items out of content context
 *
 * All branch node start items must have item.internal.metaItems = []
 * All inline meta items must have item.internal.isInlineMeta set to true
 *
 * After the method completes, each inline meta item will be moved downward to the nearest legal
 * block position (i.e. just after the close meta parent item), and has these properties:
 * item.internal.loadMetaParentHash - corresponding meta parent's item.originalDomElementsHash
 * item.internal.loadMetaParentOffset - offset at load time within the meta parent (0 for start).
 * Each meta item is appended to the corresponding meta parent's item.internal.metaItems .
 *
 * @param {Array} data Linear model data to modify in place
 */
ve.dm.Converter.static.moveInlineMetaItems = function ( data ) {
	var i, item, metaParent, j, pending,
		ancestors = [],
		pendingMetaItems = [];
 
	function closestMetaParent() {
		var i, ancestor;
		for ( i = ancestors.length - 1; i >= 0; i-- ) {
			ancestor = ancestors[ i ];
			Eif ( ancestor.isMetaParent ) {
				return ancestor;
			}
		}
		return undefined;
	}
 
	for ( i = 0; i < data.length; i++ ) {
		item = data[ i ];
		if ( Array.isArray( item ) ) {
			// Ignore annotations
			item = item[ 0 ];
		}
		if ( !item.type ) {
			// Item is not a node
			continue;
		}
		if ( item.type[ 0 ] !== '/' ) {
			// Item is a node start
			if ( ve.getProp( item, 'internal', 'isInlineMeta' ) ) {
				// This is an inline meta item: move it
				delete item.internal.isInlineMeta;
				metaParent = closestMetaParent();
				if ( metaParent ) {
					metaParent.item.internal.metaItems.push( item );
					pendingMetaItems.push( {
						item: item,
						closeItem: data[ i + 1 ],
						metaParent: metaParent,
						offset: i - metaParent.offset - 1
					} );
					// Remove this item and the immediately following close item
					data.splice( i, 2 );
					// Prepare to rescan this index
					i--;
				} else {
					// Inline meta outside meta parent. This can happen if, say,
					// the document starts with a comment then a meta item.
					// Skip this item and the immediately following close item
					i++;
				}
			} else {
				ancestors.push( {
					item: item,
					offset: i,
					isMetaParent: !!ve.getProp( item, 'internal', 'metaItems' )
				} );
			}
		} else {
			// Item is a node end
			metaParent = ancestors.pop();
			if ( metaParent.isMetaParent ) {
				for ( j = 0; j < pendingMetaItems.length; j++ ) {
					pending = pendingMetaItems[ j ];
					Iif ( pending.metaParent.item !== metaParent.item ) {
						continue;
					}
					pending.item.internal.loadMetaParentHash = metaParent.item.originalDomElementsHash;
					pending.item.internal.loadMetaParentOffset = pending.offset;
					pendingMetaItems.splice( j, 1 );
					j--;
					// This will drop annotations on meta items; fine
					data.splice( i + 1, 0, pending.item, pending.closeItem );
					i += 2;
				}
			}
		}
	}
};
 
/* Methods */
 
/**
 * Check whether this converter instance is currently inside a getModelFromDom() conversion.
 *
 * @return {boolean} Whether we're converting
 */
ve.dm.Converter.prototype.isConverting = function () {
	return this.contextStack !== null;
};
 
/**
 * Get the HashValueStore used for the current conversion.
 *
 * @return {ve.dm.HashValueStore|null} Current store, or null if not converting
 */
ve.dm.Converter.prototype.getStore = function () {
	return this.store;
};
 
/**
 * Get the HTML document currently being converted
 *
 * @return {HTMLDocument|null} HTML document being converted, or null if not converting
 */
ve.dm.Converter.prototype.getHtmlDocument = function () {
	return this.doc;
};
 
/**
 * Get the HTML document we are converting data for
 *
 * @return {HTMLDocument|null} HTML document being converted for, or null if not converting
 */
ve.dm.Converter.prototype.getTargetHtmlDocument = function () {
	return this.targetDoc;
};
 
/**
 * Get the converter mode, one of PARSER_MODE, CLIPBOARD_MODE or PREVIEW_MODE
 *
 * @return {number} Converter mode
 */
ve.dm.Converter.prototype.getMode = function () {
	return this.mode;
};
 
/**
 * Checks if the current mode needs a full view rendering in the HTML
 *
 * @return {boolean} Mode needs a rendering
 */
ve.dm.Converter.prototype.doesModeNeedRendering = function () {
	return this.getMode() !== this.constructor.static.PARSER_MODE;
};
 
/**
 * Is the current conversion for the parser
 *
 * @return {boolean} The conversion is for the paser
 */
ve.dm.Converter.prototype.isForParser = function () {
	return this.getMode() === this.constructor.static.PARSER_MODE;
};
 
/**
 * Is the current conversion for the clipboard
 *
 * @return {boolean} The conversion is for the clipboard
 */
ve.dm.Converter.prototype.isForClipboard = function () {
	return this.getMode() === this.constructor.static.CLIPBOARD_MODE;
};
 
/**
 * Is the current conversion for the preview
 *
 * @return {boolean} The conversion is for the preview
 */
ve.dm.Converter.prototype.isForPreview = function () {
	return this.getMode() === this.constructor.static.PREVIEW_MODE;
};
 
/**
 * Is the current conversion from the clipboard
 *
 * @return {boolean|null} The conversion is from the clipboard, or null if not converting
 */
ve.dm.Converter.prototype.isFromClipboard = function () {
	return this.fromClipboard;
};
 
/**
 * Get the current conversion context. This is the recursion state of getDataFromDomSubtree().
 *
 * @return {Object|null} Context object, or null if not converting
 */
ve.dm.Converter.prototype.getCurrentContext = function () {
	return this.contextStack === null ? null : this.contextStack[ this.contextStack.length - 1 ];
};
 
/**
 * Get the annotations currently being applied by the converter. Note that this is specific to
 * the current recursion level.
 *
 * @return {ve.dm.AnnotationSet|null} Annotation set, or null if not converting
 */
ve.dm.Converter.prototype.getActiveAnnotations = function () {
	var context = this.getCurrentContext();
	return context ? context.annotations : null;
};
 
/**
 * Whether the converter is currently expecting content. Note that this is specific to the current
 * recursion level.
 *
 * @return {boolean|null} Boolean indicating whether content is expected, or null if not converting
 */
ve.dm.Converter.prototype.isExpectingContent = function () {
	var context = this.getCurrentContext();
	return context ? context.expectingContent : null;
};
 
/**
 * Whether the converter can currently accept a child node with the given type.
 *
 * @param {string} nodeType
 * @return {boolean|null} Whether the node type is valid, or null if not converting
 */
ve.dm.Converter.prototype.isValidChildNodeType = function ( nodeType ) {
	var childTypes,
		context = this.getCurrentContext();
	Iif ( !context ) {
		return null;
	}
	childTypes = this.nodeFactory.getChildNodeTypes( context.branchType );
	return ( childTypes === null || childTypes.indexOf( nodeType ) !== -1 );
};
 
/**
 * Whether the conversion is currently inside a wrapper paragraph generated by the converter.
 * Note that this is specific to the current recursion level.
 *
 * @return {boolean|null} Boolean indicating whether we're wrapping, or null if not converting
 */
ve.dm.Converter.prototype.isInWrapper = function () {
	var context = this.getCurrentContext();
	return context ? context.inWrapper : null;
};
 
/**
 * Whether the active wrapper can be closed. Note that this is specific to the current recursion
 * level. If there is no active wrapper, this returns false.
 *
 * @return {boolean|null} Boolean indicating whether the wrapper can be closed, or null if not converting
 */
ve.dm.Converter.prototype.canCloseWrapper = function () {
	var context = this.getCurrentContext();
	return context ? context.canCloseWrapper : null;
};
 
/**
 * Get the DOM element for a given linear model element.
 *
 * This invokes the toDomElements function registered for the element type.
 *
 * @param {Object|Array} dataElements Linear model element or data slice
 * @param {HTMLDocument} doc Document to create DOM elements in
 * @param {Node[]} [childDomElements] Array of child DOM elements to pass in (annotations only)
 * @return {Node[]|boolean} DOM elements, or false if the element cannot be converted.
 *  If the first DOMelement has a 'handledOwnChildren' property set, the converter treats it as if it
 *  were a handlesOwnChildren node.
 */
ve.dm.Converter.prototype.getDomElementsFromDataElement = function ( dataElements, doc, childDomElements ) {
	var domElements, originalDomElements, key,
		dataElement = Array.isArray( dataElements ) ? dataElements[ 0 ] : dataElements,
		nodeClass = this.modelRegistry.lookup( dataElement.type );
 
	Iif ( !nodeClass ) {
		throw new Error( 'Attempting to convert unknown data element type ' + dataElement.type );
	}
	Iif ( nodeClass.static.isInternal ) {
		return false;
	}
	domElements = nodeClass.static.toDomElements( dataElements, doc, this, childDomElements );
	Iif ( !Array.isArray( domElements ) && !( nodeClass.prototype instanceof ve.dm.Annotation ) ) {
		throw new Error( 'toDomElements() failed to return an array when converting element of type ' + dataElement.type );
	}
	originalDomElements = this.store.value( dataElement.originalDomElementsHash );
	// Optimization: don't call renderHtmlAttributeList if returned domElements are equal to the originals
	if ( originalDomElements && !ve.isEqualDomElements( domElements, originalDomElements ) ) {
		this.constructor.static.renderHtmlAttributeList(
			originalDomElements,
			domElements,
			nodeClass.static.preserveHtmlAttributes,
			// computed
			false,
			// deep
			(
				!this.nodeFactory.lookup( dataElement.type ) ||
				!this.nodeFactory.canNodeHaveChildren( dataElement.type ) ||
				this.nodeFactory.doesNodeHandleOwnChildren( dataElement.type )
			)
		);
	}
	// TODO: This is only for the diff. Eventually should make a DiffConverter subclass
	if ( dataElement.internal && dataElement.internal.diff ) {
		Array.prototype.forEach.call( domElements, function ( domElement ) {
			for ( key in dataElement.internal.diff ) {
				// toDomElements is a misnomer, it can actually return other nodes,
				// such as comment nodes or text nodes.
				Eif ( domElement.setAttribute ) {
					domElement.setAttribute( key, dataElement.internal.diff[ key ] );
				}
			}
		} );
	}
	// Mark branch nodes as generated from dataElement, so we don't try and descend into them in a deep renderHtmlAttributeList call
	if ( this.nodeFactory.lookup( dataElement.type ) && this.nodeFactory.canNodeHaveChildren( dataElement.type ) ) {
		domElements.forEach( function ( domElement ) {
			domElement.veFromDataElement = true;
		} );
	}
	return domElements;
};
 
/**
 * Create a data element from a DOM element.
 *
 * @param {ve.dm.Model} modelClass Model class to use for conversion
 * @param {Node[]} domElements DOM elements to convert
 * @return {Object|Array|null} Data element or array of linear model data, or null to alienate
 */
ve.dm.Converter.prototype.createDataElements = function ( modelClass, domElements ) {
	var serializer,
		dataElements = modelClass.static.toDataElement( domElements, this );
 
	Iif ( !dataElements ) {
		return null;
	}
	if ( !Array.isArray( dataElements ) ) {
		dataElements = [ dataElements ];
	}
	Eif ( dataElements.length ) {
		if ( modelClass.prototype instanceof ve.dm.Annotation ) {
			serializer = function ( node ) {
				// Do not include childNodes; see T160839
				return node.cloneNode( false ).outerHTML;
			};
		} else {
			serializer = ve.getNodeHtml;
		}
		dataElements[ 0 ].originalDomElementsHash = this.store.hash(
			domElements,
			domElements.map( serializer ).join( '' )
		);
		if ( modelClass.prototype instanceof ve.dm.BranchNode && modelClass.static.childNodeTypes === null ) {
			// Set this item up as a meta parent
			ve.setProp( dataElements[ 0 ], 'internal', 'metaItems', [] );
			ve.setProp( dataElements[ 0 ], 'internal', 'changesSinceLoad', 0 );
		}
	}
	return dataElements;
};
 
/**
 * Build an HTML DOM node for a linear model annotation.
 *
 * @param {Object} dataAnnotation Annotation object
 * @param {HTMLDocument} doc HTML document to create element with
 * @return {HTMLElement} HTML DOM node
 */
ve.dm.Converter.prototype.getDomElementFromDataAnnotation = function ( dataAnnotation, doc ) {
	var htmlData = dataAnnotation.toHtml(),
		domElement = doc.createElement( htmlData.tag );
 
	ve.setDomAttributes( domElement, htmlData.attributes );
	return domElement;
};
 
/**
 * Convert an HTML document to a document model.
 *
 * @param {HTMLDocument} doc HTML document to convert
 * @param {Object} [options] Conversion options
 * @param {HTMLDocument} [options.targetDoc=doc] Target HTML document we are converting for, if different from doc
 * @param {boolean} [options.fromClipboard=false] Conversion is from clipboard
 * @param {string} [options.lang] Document language code
 * @param {string} [options.dir] Document directionality (ltr/rtl)
 * @param {ve.dm.HashValueStore} [store] Hash value store
 * @return {ve.dm.Document} Document model
 */
ve.dm.Converter.prototype.getModelFromDom = function ( doc, options, store ) {
	var data, linearData, refData, innerWhitespace,
		internalList = new ve.dm.InternalList();
 
	store = store || new ve.dm.HashValueStore();
	options = options || {};
 
	// Set up the converter state
	this.doc = doc;
	this.targetDoc = options.targetDoc || doc;
	this.fromClipboard = options.fromClipboard;
	this.store = store;
	this.internalList = internalList;
	this.contextStack = [];
	// Possibly do things with doc and the head in the future
 
	// Generate data
	data = this.getDataFromDomSubtree( doc.body );
	this.constructor.static.moveInlineMetaItems( data );
 
	linearData = new ve.dm.ElementLinearData( store, data );
	refData = this.internalList.convertToData( this, doc );
	linearData.batchSplice( linearData.getLength(), 0, refData );
	innerWhitespace = this.getInnerWhitespace( linearData );
 
	// Clear the state
	this.doc = null;
	this.targetDoc = null;
	this.fromClipboard = null;
	this.store = null;
	this.internalList = null;
	this.contextStack = null;
 
	return new ve.dm.Document( linearData, doc, undefined, internalList, innerWhitespace, options.lang, options.dir );
};
 
/**
 * Wrapper for getDataFromDom which resets contextStack before the call
 * and then set it back after the call.
 *
 * TODO: This is kind of a hack, better implementation would be more appropriate in near future.
 *
 * @param {HTMLElement} domElement HTML element to convert
 * @param {Object} [wrapperElement] Data element to wrap the returned data in
 * @param {ve.dm.AnnotationSet} [annotationSet] Override the set of annotations to use
 * @return {Array} Linear model data
 */
ve.dm.Converter.prototype.getDataFromDomClean = function ( domElement, wrapperElement, annotationSet ) {
	var result, contextStack = this.contextStack;
	this.contextStack = [];
	result = this.getDataFromDomSubtree( domElement, wrapperElement, annotationSet );
	this.contextStack = contextStack;
	return result;
};
 
/**
 * Get linear model data from a DOM node. Called recursively. For internal use
 * and ve.dm.Model.static.toDataElement() implementations.
 *
 * @param {HTMLElement} domElement HTML element to convert
 * @param {Object} [wrapperElement] Data element to wrap the returned data in
 * @param {ve.dm.AnnotationSet} [annotationSet] Override the set of annotations to use
 * @return {Array} Linear model data
 */
ve.dm.Converter.prototype.getDataFromDomSubtree = function ( domElement, wrapperElement, annotationSet ) {
	var i, childNode, childNodes, childDataElements, text, matches,
		wrappingParagraph, prevElement, childAnnotations, modelName, modelClass,
		annotation, childIsContent, aboutGroup, emptyParagraph,
		converter = this,
		whitespaceList = this.constructor.static.whitespaceList,
		modelRegistry = this.modelRegistry,
		data = [],
		nextWhitespace = '',
		wrappedWhitespace = '',
		wrappedWhitespaceIndex,
		wrappedMetaItems = [],
		context = {},
		prevContext = this.contextStack.length ?
			this.contextStack[ this.contextStack.length - 1 ] : null;
 
	/**
	 * Add whitespace to an element at a specific offset.
	 *
	 * @private
	 * @param {Array} element Data element
	 * @param {number} index Whitespace index, 0-3
	 * @param {string} whitespace Whitespace content
	 */
	function addWhitespace( element, index, whitespace ) {
		if ( !whitespace ) {
			return;
		}
		if ( !element.internal ) {
			element.internal = {};
		}
		// whitespace = [ outerPre, innerPre, innerPost, outerPost ]
		//         <tag>        text         </tag>         <nextTag>
		// ^^^^^^^^     ^^^^^^^^    ^^^^^^^^^      ^^^^^^^^^
		// outerPre     innerPre    innerPost      outerPost
		if ( !element.internal.whitespace ) {
			element.internal.whitespace = [];
		}
		element.internal.whitespace[ index ] = whitespace;
	}
	function processNextWhitespace( element ) {
		// This function uses and changes nextWhitespace in the outer function's scope,
		// which means it's not really a function but more of a shortcut.
		if ( nextWhitespace !== '' ) {
			addWhitespace( element, 0, nextWhitespace );
			nextWhitespace = '';
		}
	}
	// FIXME rewrite this horrible meta item / whitespace queueing/wrapping business
	function outputWrappedMetaItems( whitespaceTreatment ) {
		var i, len,
			toInsert = [],
			prev = wrappingParagraph;
 
		for ( i = 0, len = wrappedMetaItems.length; i < len; i++ ) {
			if ( wrappedMetaItems[ i ].type && wrappedMetaItems[ i ].type.charAt( 0 ) !== '/' ) {
				if ( wrappedMetaItems[ i ].internal && wrappedMetaItems[ i ].internal.whitespace ) {
					if ( whitespaceTreatment === 'restore' ) {
						ve.batchPush( toInsert, converter.constructor.static.getDataContentFromText(
							wrappedMetaItems[ i ].internal.whitespace[ 0 ], context.annotations
						) );
						delete wrappedMetaItems[ i ].internal;
					} else Eif ( whitespaceTreatment === 'fixup' ) {
						addWhitespace( prev, 3, wrappedMetaItems[ i ].internal.whitespace[ 0 ] );
					}
				}
				prev = wrappedMetaItems[ i ];
			}
			toInsert.push( wrappedMetaItems[ i ] );
		}
		if ( wrappedWhitespace !== '' && whitespaceTreatment === 'restore' ) {
			// If we have wrapped whitespace, insert the wrapped meta items before it
			// This is horrible and this whole system desperately needs to be rewritten
			ve.batchSplice( data, wrappedWhitespaceIndex, 0, toInsert );
		} else {
			ve.batchPush( data, toInsert );
		}
		wrappedMetaItems = [];
	}
	function startWrapping() {
		// Mark this paragraph as having been generated by
		// us, so we can strip it on the way out
		wrappingParagraph = {
			type: 'paragraph',
			internal: { generated: 'wrapper', metaItems: [] }
		};
		data.push( wrappingParagraph );
		context.inWrapper = true;
		context.canCloseWrapper = true;
		context.expectingContent = true;
		processNextWhitespace( wrappingParagraph );
	}
	function stopWrapping() {
		if ( wrappedWhitespace !== '' ) {
			// Remove wrappedWhitespace from data
			data.splice( wrappedWhitespaceIndex, wrappedWhitespace.length );
			// Add whitespace to the last sibling: either the last meta item or the wrapper paragraph
			addWhitespace( wrappedMetaItems.length > 0 ? wrappedMetaItems[ wrappedMetaItems.length - 2 ] : wrappingParagraph, 3, wrappedWhitespace );
			nextWhitespace = wrappedWhitespace;
		}
		data.push( { type: '/paragraph' } );
		outputWrappedMetaItems( 'fixup' );
		wrappingParagraph = undefined;
		context.inWrapper = false;
		context.canCloseWrapper = false;
		context.expectingContent = context.originallyExpectingContent;
	}
	function getAboutGroup( node ) {
		var about,
			aboutGroup = [ node ];
 
		if ( node.nodeType !== Node.ELEMENT_NODE || node.getAttribute( 'about' ) === null ) {
			return aboutGroup;
		}
		about = node.getAttribute( 'about' );
		while ( ( node = node.nextSibling ) !== null ) {
			if ( node.nodeType === Node.ELEMENT_NODE && node.getAttribute( 'about' ) === about ) {
				aboutGroup.push( node );
			} else {
				break;
			}
		}
		return aboutGroup;
	}
	function isAllInstanceOf( data, targetClass ) {
		var i, type, itemClass;
		for ( i = data.length - 1; i >= 0; i-- ) {
			type = ve.dm.LinearData.static.getType( data[ i ] );
			if ( type ) {
				itemClass = modelRegistry.lookup( type ) || ve.dm.AlienNode;
				if ( !( itemClass === targetClass || itemClass.prototype instanceof targetClass ) ) {
					return false;
				}
			} else {
				return false;
			}
		}
		return true;
	}
 
	context.annotations = annotationSet || (
		prevContext ? prevContext.annotations.clone() : new ve.dm.AnnotationSet( this.store )
	);
	context.branchType = wrapperElement ? wrapperElement.type : (
		prevContext ? prevContext.branchType : 'document'
	);
	context.branchHasContent = this.nodeFactory.canNodeContainContent( context.branchType );
	context.originallyExpectingContent = context.branchHasContent || !context.annotations.isEmpty();
	context.expectingContent = context.originallyExpectingContent;
	context.inWrapper = prevContext ? prevContext.inWrapper : false;
	context.canCloseWrapper = false;
	this.contextStack.push( context );
 
	// Open element
	if ( wrapperElement ) {
		data.push( wrapperElement );
	}
	// Add contents
	function setInlineMeta( element ) {
		ve.setProp( element, 'internal', 'isInlineMeta', true );
	}
	for ( i = 0; i < domElement.childNodes.length; i++ ) {
		childNode = domElement.childNodes[ i ];
		switch ( childNode.nodeType ) {
			case Node.ELEMENT_NODE:
			case Node.COMMENT_NODE:
				Iif (
					childNode.getAttribute &&
					childNode.getAttribute( 'data-ve-ignore' )
				) {
					continue;
				}
				aboutGroup = getAboutGroup( childNode );
				modelName = this.modelRegistry.matchElement( childNode, aboutGroup.length > 1 );
				modelClass = this.modelRegistry.lookup( modelName ) || ve.dm.AlienNode;
				if ( modelClass.prototype instanceof ve.dm.Annotation ) {
					childNodes = [ childNode ];
				} else {
					// Node or meta item
					childNodes = modelClass.static.enableAboutGrouping ?
						aboutGroup : [ childNode ];
				}
				childDataElements = this.createDataElements( modelClass, childNodes );
 
				Iif ( !childDataElements ) {
					// Alienate
					modelClass = ve.dm.AlienNode;
					childNodes = modelClass.static.enableAboutGrouping ?
						aboutGroup : [ childNode ];
					childDataElements = this.createDataElements( modelClass, childNodes );
				} else Eif ( childDataElements.length ) {
					// Update modelClass to reflect the type we got back
					modelClass = this.modelRegistry.lookup( childDataElements[ 0 ].type );
				} else {
					continue;
				}
 
				// Now take the appropriate action based on that
				if ( modelClass.prototype instanceof ve.dm.Annotation ) {
					annotation = this.annotationFactory.createFromElement( childDataElements[ 0 ], this.store );
					// Start wrapping if needed
					if ( !context.inWrapper && !context.expectingContent ) {
						startWrapping();
						prevElement = wrappingParagraph;
					}
					// Append child element data
					childAnnotations = context.annotations.clone();
					childAnnotations.push( annotation );
 
					childDataElements = this.getDataFromDomSubtree( childNode, undefined, childAnnotations );
					if ( !childDataElements.length || isAllInstanceOf( childDataElements, ve.dm.AlienMetaItem ) ) {
						// Empty annotation, create a meta item
						if ( !childDataElements.length || isAllInstanceOf( childDataElements, ve.dm.RemovableAlienMetaItem ) ) {
							childDataElements = this.createDataElements( ve.dm.RemovableAlienMetaItem, childNodes );
						} else {
							childDataElements = this.createDataElements( ve.dm.AlienMetaItem, childNodes );
						}
						childDataElements.push( { type: '/' + childDataElements[ 0 ].type } );
						// Annotate meta item
						if ( !context.annotations.isEmpty() ) {
							childDataElements[ 0 ].annotations = context.annotations.getHashes().slice();
						}
						// Mark meta items to be moved outside of content context, as we can't handle them here
						// (context.expectingContent is always true at this point)
						setInlineMeta( childDataElements[ 0 ] );
					}
					outputWrappedMetaItems( 'restore' );
					ve.batchPush( data, childDataElements );
					// Clear wrapped whitespace
					wrappedWhitespace = '';
				} else {
					// Node or meta item
					if ( modelClass.prototype instanceof ve.dm.MetaItem ) {
						if ( context.expectingContent ) {
							// Mark meta items to be moved outside of content context, as we can't handle them here
							childDataElements.forEach( setInlineMeta );
						}
 
						// No additional processing needed
						// Write to data and continue
						Eif ( childDataElements.length === 1 ) {
							childDataElements.push( { type: '/' + childDataElements[ 0 ].type } );
						}
						// Annotate meta item
						if ( !context.annotations.isEmpty() ) {
							childDataElements[ 0 ].annotations = context.annotations.getHashes().slice();
						}
						// Queue wrapped meta items only if it's actually possible for us to move them out
						// of the wrapper
						if ( context.inWrapper && context.canCloseWrapper ) {
							ve.batchPush( wrappedMetaItems, childDataElements );
							if ( wrappedWhitespace !== '' ) {
								data.splice( wrappedWhitespaceIndex, wrappedWhitespace.length );
								addWhitespace( childDataElements[ 0 ], 0, wrappedWhitespace );
								nextWhitespace = wrappedWhitespace;
								wrappedWhitespace = '';
							}
						} else {
							outputWrappedMetaItems( 'restore' );
							ve.batchPush( data, childDataElements );
							processNextWhitespace( childDataElements[ 0 ] );
							prevElement = childDataElements[ 0 ];
						}
						// In case we consumed multiple childNodes, adjust i accordingly
						i += childNodes.length - 1;
						break;
					}
 
					childIsContent = this.nodeFactory.canNodeSerializeAsContent( childDataElements[ 0 ].type );
 
					// If childIsContent isn't what we expect, adjust
					if ( !context.expectingContent && childIsContent ) {
						startWrapping();
						prevElement = wrappingParagraph;
					} else if ( context.expectingContent && !childIsContent ) {
						if ( context.inWrapper && context.canCloseWrapper ) {
							stopWrapping();
						} else {
							// Alienate
							modelClass = ve.dm.AlienNode;
							childNodes = modelClass.static.enableAboutGrouping ?
								aboutGroup : [ childNode ];
							childDataElements = this.createDataElements( modelClass, childNodes );
							childIsContent = this.nodeFactory.canNodeSerializeAsContent( childDataElements[ 0 ].type );
						}
					}
 
					// If we're inserting content into a wrapper, any wrapped whitespace and meta
					// items up until this point are here to stay
					if ( context.inWrapper && childIsContent ) {
						outputWrappedMetaItems( 'restore' );
						wrappedWhitespace = '';
						// Don't record the wrapped whitespace as the child node's outer whitespace
						nextWhitespace = '';
					}
 
					// Annotate child
					if ( childIsContent && !context.annotations.isEmpty() ) {
						childDataElements[ 0 ].annotations = context.annotations.getHashes().slice();
					}
 
					// Output child and process children if needed
					if (
						childDataElements.length === 1 &&
						childNodes.length === 1 &&
						this.nodeFactory.canNodeHaveChildren( childDataElements[ 0 ].type ) &&
						!this.nodeFactory.doesNodeHandleOwnChildren( childDataElements[ 0 ].type )
					) {
						// Recursion
						// Opening and closing elements are added by the recursion too
						outputWrappedMetaItems( 'restore' );
						ve.batchPush( data,
							this.getDataFromDomSubtree( childNode, childDataElements[ 0 ],
								new ve.dm.AnnotationSet( this.store )
							)
						);
					} else {
						if ( childDataElements.length === 1 ) {
							childDataElements.push( { type: '/' + childDataElements[ 0 ].type } );
						}
						// Write childDataElements directly
						outputWrappedMetaItems( 'restore' );
						ve.batchPush( data, childDataElements );
					}
					processNextWhitespace( childDataElements[ 0 ] );
					prevElement = childDataElements[ 0 ];
 
					// In case we consumed multiple childNodes, adjust i accordingly
					i += childNodes.length - 1;
				}
				break;
			case Node.TEXT_NODE:
				text = childNode.data;
				Iif ( text === '' ) {
					// Empty text node?!?
					break;
				}
				if ( !context.originallyExpectingContent ) {
					// Strip and store outer whitespace
					if ( text.match( new RegExp( '^[' + whitespaceList + ']+$' ) ) ) {
						// This text node is whitespace only
						if ( context.inWrapper ) {
							// We're already wrapping, so output this whitespace
							// and store it in wrappedWhitespace (see
							// comment about wrappedWhitespace below)
							wrappedWhitespace = text;
							wrappedWhitespaceIndex = data.length;
							ve.batchPush( data,
								this.constructor.static.getDataContentFromText( wrappedWhitespace, context.annotations )
							);
						} else {
							// We're not in wrapping mode, store this whitespace
							if ( !prevElement ) {
								if ( wrapperElement ) {
									// First child, store as inner
									// whitespace in the parent
									addWhitespace( wrapperElement, 1, text );
								}
								// Else, WTF?!? This is not supposed to
								// happen, but it's not worth
								// throwing an exception over.
							} else {
								addWhitespace( prevElement, 3, text );
							}
							nextWhitespace = text;
							wrappedWhitespace = '';
							outputWrappedMetaItems( 'restore' );
						}
						// We're done, no actual text left to process
						break;
					} else {
						// This text node contains actual text
						// Separate the real text from the whitespace
						// HACK: '.' doesn't match newlines in JS, so use
						// [\s\S] to match any character
						matches = text.match( new RegExp( '^([' + whitespaceList + ']*)([\\s\\S]*?)([' + whitespaceList + ']*)$' ) );
						if ( !context.inWrapper ) {
							// Wrap the text in a paragraph and output it
							startWrapping();
 
							// Only store leading whitespace if we just
							// started wrapping
							if ( matches[ 1 ] !== '' ) {
								if ( !prevElement ) {
									if ( wrapperElement ) {
										// First child, store as inner
										// whitespace in the parent
										addWhitespace( wrapperElement, 1, matches[ 1 ] );
									}
									// Else, WTF?!? This is not supposed to
									// happen, but it's not worth
									// throwing an exception over.
								} else {
									addWhitespace( prevElement, 3, matches[ 1 ] );
								}
								addWhitespace( wrappingParagraph, 0, matches[ 1 ] );
							}
						} else {
							outputWrappedMetaItems( 'restore' );
							// We were already wrapping in a paragraph,
							// so the leading whitespace must be output
							ve.batchPush( data,
								this.constructor.static.getDataContentFromText( matches[ 1 ], context.annotations )
							);
						}
						// Output the text sans whitespace
						ve.batchPush( data,
							this.constructor.static.getDataContentFromText( matches[ 2 ], context.annotations )
						);
 
						// Don't store this in wrappingParagraph.internal.whitespace[3]
						// and nextWhitespace just yet. Instead, store it
						// in wrappedWhitespace. There might be more text
						// nodes after this one, so we output wrappedWhitespace
						// for now and undo that if it turns out this was
						// the last text node. We can't output it later
						// because we have to apply the correct annotations.
						wrappedWhitespace = matches[ 3 ];
						wrappedWhitespaceIndex = data.length;
						ve.batchPush( data,
							this.constructor.static.getDataContentFromText( wrappedWhitespace, context.annotations )
						);
						prevElement = wrappingParagraph;
						break;
					}
				}
 
				// Strip leading and trailing inner whitespace
				// (but only in non-annotation nodes)
				// and store it so it can be restored later.
				if (
					context.annotations.isEmpty() && i === 0 && wrapperElement &&
					!this.nodeFactory.doesNodeHaveSignificantWhitespace( wrapperElement.type )
				) {
					// Strip leading whitespace from the first child
					matches = text.match( new RegExp( '^[' + whitespaceList + ']+' ) );
					if ( matches && matches[ 0 ] !== '' ) {
						addWhitespace( wrapperElement, 1, matches[ 0 ] );
						text = text.slice( matches[ 0 ].length );
					}
				}
				if (
					context.annotations.isEmpty() &&
					i === domElement.childNodes.length - 1 &&
					wrapperElement &&
					!this.nodeFactory.doesNodeHaveSignificantWhitespace( wrapperElement.type )
				) {
					// Strip trailing whitespace from the last child
					matches = text.match( new RegExp( '[' + whitespaceList + ']+$' ) );
					if ( matches && matches[ 0 ] !== '' ) {
						addWhitespace( wrapperElement, 2, matches[ 0 ] );
						text = text.slice( 0, text.length - matches[ 0 ].length );
					}
				}
 
				// Annotate the text and output it
				ve.batchPush( data,
					this.constructor.static.getDataContentFromText( text, context.annotations )
				);
				break;
		}
	}
	// End auto-wrapping of bare content
	if ( context.inWrapper && context.canCloseWrapper ) {
		stopWrapping();
		// HACK: don't set context.inWrapper = false here because it's checked below
		context.inWrapper = true;
	}
 
	// If we're closing a node that doesn't have any children, but could contain a paragraph,
	// add a paragraph. This prevents things like empty list items
	if ( context.branchType !== 'paragraph' && wrapperElement && data[ data.length - 1 ] === wrapperElement &&
		!context.inWrapper && !this.nodeFactory.canNodeContainContent( context.branchType ) &&
		!this.nodeFactory.isNodeContent( context.branchType ) &&
		this.isValidChildNodeType( 'paragraph' )
	) {
		emptyParagraph = { type: 'paragraph', internal: { generated: 'empty' } };
		processNextWhitespace( emptyParagraph );
		data.push( emptyParagraph );
		data.push( { type: '/paragraph' } );
	}
 
	// Close element
	if ( wrapperElement ) {
		// Add the whitespace after the last child to the parent as innerPost
		// But don't do this if the parent is empty, because in that case we've already put that
		// whitespace in innerPre
		if ( nextWhitespace !== '' && data[ data.length - 1 ] !== wrapperElement ) {
			addWhitespace( wrapperElement, 2, nextWhitespace );
			nextWhitespace = '';
		}
		data.push( { type: '/' + wrapperElement.type } );
	}
	// Don't return an empty document
	if ( context.branchType === 'document' && isAllInstanceOf( data, ve.dm.MetaItem ) && !annotationSet ) {
		emptyParagraph = { type: 'paragraph', internal: { generated: 'empty' } };
		processNextWhitespace( emptyParagraph );
		data.push( emptyParagraph );
		data.push( { type: '/paragraph' } );
	}
 
	this.contextStack.pop();
	return data;
};
 
/**
 * Get inner whitespace from linear data
 *
 * @param {ve.dm.ElementLinearData} data Linear model data
 * @return {Array} innerWhitespace Inner whitespace
 */
ve.dm.Converter.prototype.getInnerWhitespace = function ( data ) {
	var whitespace,
		innerWhitespace = new Array( 2 ),
		stack = 0,
		last = data.getLength() - 1;
 
	Eif ( data.isOpenElementData( 0 ) ) {
		whitespace = ve.getProp( data.getData( 0 ), 'internal', 'whitespace' );
		innerWhitespace[ 0 ] = whitespace ? whitespace[ 0 ] : undefined;
	}
	Eif ( data.isCloseElementData( last ) ) {
		// Find matching opening tag of the last close tag
		stack++;
		while ( --last ) {
			if ( data.isCloseElementData( last ) ) {
				stack++;
			} else if ( data.isOpenElementData( last ) ) {
				stack--;
				if ( stack === 0 && data.getType( last ) !== 'internalList' ) {
					break;
				}
			}
		}
		whitespace = ve.getProp( data.getData( last ), 'internal', 'whitespace' );
		innerWhitespace[ 1 ] = whitespace ? whitespace[ 3 ] : undefined;
	}
	return innerWhitespace;
};
 
/**
 * Convert document model to an HTML DOM
 *
 * @param {ve.dm.Document} model Document model
 * @param {number} [mode=PARSER_MODE] Conversion mode, defaults to PARSER_MODE
 * @return {HTMLDocument} Document containing the resulting HTML
 */
ve.dm.Converter.prototype.getDomFromModel = function ( model, mode ) {
	var doc = ve.createDocumentFromHtml( '' );
 
	// Backwards compatibility with 'forClipboard' argument
	Iif ( typeof mode === 'boolean' ) {
		mode = mode ? this.constructor.static.CLIPBOARD_MODE : this.constructor.static.PARSER_MODE;
	}
	mode = mode || this.constructor.static.PARSER_MODE;
 
	this.getDomSubtreeFromModel( model, doc.body, mode );
 
	return doc;
};
 
/**
 * Convert model node to an HTML DOM
 *
 * @param {ve.dm.Node} node Model node
 * @param {number} [mode=PARSER_MODE] Conversion mode, defaults to PARSER_MODE
 * @return {HTMLDocument} Document containing the resulting HTML
 */
ve.dm.Converter.prototype.getDomFromNode = function ( node, mode ) {
	// Backwards compatibility with 'forClipboard' argument
	Iif ( typeof mode === 'boolean' ) {
		mode = mode ? this.constructor.static.CLIPBOARD_MODE : this.constructor.static.PARSER_MODE;
	}
	mode = mode || this.constructor.static.PARSER_MODE;
	return this.getDomFromModel(
		node.getDocument().shallowCloneFromRange( node.isInternal() ? node.getRange() : node.getOuterRange() ),
		mode
	);
};
 
/**
 * Convert document model to an HTML DOM subtree and add it to a container element.
 *
 * @param {ve.dm.Document} model Document model
 * @param {HTMLElement} container DOM element to add the generated elements to. Should be empty.
 * @param {number} [mode=PARSER_MODE] Conversion mode, defaults to PARSER_MODE
 */
ve.dm.Converter.prototype.getDomSubtreeFromModel = function ( model, container, mode ) {
	Iif ( typeof mode === 'boolean' ) {
		mode = mode ? this.constructor.static.CLIPBOARD_MODE : this.constructor.static.PARSER_MODE;
	}
	mode = mode || this.constructor.static.PARSER_MODE;
	// Set up the converter state
	this.documentData = model.getFullData( undefined, 'roundTrip' );
	this.store = model.getStore();
	this.internalList = model.getInternalList();
	// Internal list of the doc this was cloned from, or itself if not cloned
	this.originalDocInternalList = model.getOriginalDocument() ? model.getOriginalDocument().getInternalList() : this.internalList;
	this.mode = mode;
 
	this.getDomSubtreeFromData( this.documentData, container, model.getInnerWhitespace() );
 
	// Clear the state
	this.documentData = null;
	this.store = null;
	this.internalList = null;
	this.originalDocInternalList = null;
	this.mode = null;
};
 
/**
 * Convert linear model data to an HTML DOM subtree and add it to a container element.
 *
 * @param {Array} data Linear model data
 * @param {HTMLElement} container DOM element to add the generated elements to. Should be empty.
 * @param {Array} [innerWhitespace] Inner whitespace if the container is the body
 * @throws Unbalanced data: looking for closing /type
 */
ve.dm.Converter.prototype.getDomSubtreeFromData = function ( data, container, innerWhitespace ) {
	var text, i, j, isStart, annotations, dataElement, dataElementOrSlice, oldLastOuterPost,
		childDomElements, pre, ours, theirs, parentDomElement, lastChild, isContentNode, sibling,
		previousSiblings, doUnwrap, textNode, type, annotatedDomElementStack, annotatedDomElements,
		whitespaceList = this.constructor.static.whitespaceList,
		whitespaceHtmlChars = ve.visibleWhitespaceCharacters,
		dataLen = data.length,
		converter = this,
		doc = container.ownerDocument,
		domElement = container,
		annotationStack = new ve.dm.AnnotationSet( this.store );
 
	// TODO this whole function should be rewritten with a domElementStack and ascend() and
	// descend() functions, to build the whole DOM bottom-up rather than top-down. That would make
	// unwrapping easier and will hopefully result in fewer DOM operations.
 
	function openAnnotation() {
		// Add text if needed
		if ( text.length > 0 ) {
			annotatedDomElements.push( doc.createTextNode( text ) );
			text = '';
		}
		annotatedDomElements = [];
		annotatedDomElementStack.push( annotatedDomElements );
	}
 
	function closeAnnotation( annotation ) {
		var i, len, annotationElement, annotatedChildDomElements,
			matches, first, last,
			leading = '',
			trailing = '',
			originalDomElements = annotation.getOriginalDomElements( converter.store ),
			origElementText = originalDomElements[ 0 ] &&
				originalDomElements[ 0 ].textContent ||
				'';
 
		// Add text if needed
		if ( text.length > 0 ) {
			annotatedDomElements.push( doc.createTextNode( text ) );
			text = '';
		}
 
		annotatedChildDomElements = annotatedDomElementStack.pop();
		annotatedDomElements = annotatedDomElementStack[ annotatedDomElementStack.length - 1 ];
 
		// HACK: Move any leading and trailing whitespace out of the annotation, but only if the
		// annotation didn't originally have leading/trailing whitespace
		if ( annotation.constructor.static.trimWhitespace ) {
			first = annotatedChildDomElements[ 0 ];
			while (
				first &&
				first.nodeType === Node.TEXT_NODE &&
				( matches = first.data.match( new RegExp( '^[' + whitespaceList + ']+' ) ) ) &&
				!origElementText.match( new RegExp( '^[' + whitespaceList + ']' ) )
			) {
				leading += matches[ 0 ];
				first.deleteData( 0, matches[ 0 ].length );
				if ( first.data.length !== 0 ) {
					break;
				}
				// Remove empty text node
				annotatedChildDomElements.shift();
				// Process next text node to see if it also has whitespace
				first = annotatedChildDomElements[ 0 ];
			}
			last = annotatedChildDomElements[ annotatedChildDomElements.length - 1 ];
			while (
				last &&
				last.nodeType === Node.TEXT_NODE &&
				( matches = last.data.match( new RegExp( '[' + whitespaceList + ']+$' ) ) ) &&
				!origElementText.match( new RegExp( '[' + whitespaceList + ']$' ) )
			) {
				trailing = matches[ 0 ] + trailing;
				last.deleteData( last.data.length - matches[ 0 ].length, matches[ 0 ].length );
				if ( last.data.length !== 0 ) {
					break;
				}
				// Remove empty text node
				annotatedChildDomElements.pop();
				// Process next text node to see if it also has whitespace
				last = annotatedChildDomElements[ annotatedChildDomElements.length - 1 ];
			}
		}
 
		if ( annotatedChildDomElements.length ) {
			annotationElement = converter.getDomElementsFromDataElement(
				annotation.getElement(), doc, annotatedChildDomElements
			)[ 0 ];
		}
 
		if ( leading ) {
			annotatedDomElements.push( doc.createTextNode( leading ) );
		}
		if ( annotationElement ) {
			for ( i = 0, len = annotatedChildDomElements.length; i < len; i++ ) {
				annotationElement.appendChild( annotatedChildDomElements[ i ] );
			}
			annotatedDomElements.push( annotationElement );
		} else {
			for ( i = 0, len = annotatedChildDomElements.length; i < len; i++ ) {
				annotatedDomElements.push( annotatedChildDomElements[ i ] );
			}
		}
		if ( trailing ) {
			annotatedDomElements.push( doc.createTextNode( trailing ) );
		}
	}
 
	function findEndOfNode( i ) {
		var j, depth;
		for ( j = i + 1, depth = 1; j < dataLen && depth > 0; j++ ) {
			if ( data[ j ].type ) {
				depth += data[ j ].type.charAt( 0 ) === '/' ? -1 : 1;
			}
		}
		Iif ( depth !== 0 ) {
			throw new Error( 'Unbalanced data: ' + depth + ' element(s) left open.' );
		}
		return j;
	}
 
	function getDataElementOrSlice() {
		var dataSlice;
		if (
			ve.dm.nodeFactory.lookup( data[ i ].type ) &&
			ve.dm.nodeFactory.doesNodeHandleOwnChildren( data[ i ].type )
		) {
			dataSlice = data.slice( i, findEndOfNode( i ) );
		} else {
			dataSlice = data[ i ];
		}
		return dataSlice;
	}
 
	function getChar( char ) {
		if (
			converter.isForPreview() &&
			Object.prototype.hasOwnProperty.call( whitespaceHtmlChars, char )
		) {
			char = whitespaceHtmlChars[ char ];
		}
		return char;
	}
 
	for ( i = 0; i < dataLen; i++ ) {
		if ( typeof data[ i ] === 'string' ) {
			// Text
			text = '';
			isStart = i > 0 &&
				ve.dm.LinearData.static.isOpenElementData( data[ i - 1 ] ) &&
				!ve.dm.nodeFactory.doesNodeHaveSignificantWhitespace(
					ve.dm.LinearData.static.getType( data[ i - 1 ] )
				);
			// Continue forward as far as the plain text goes
			while ( typeof data[ i ] === 'string' ) {
				// HACK: Skip over leading whitespace (T53462/T142132) in non-whitespace-preserving tags
				// This should possibly be handled by Parsoid or in the UI.
				if ( !( isStart && data[ i ].match( new RegExp( '[' + whitespaceList + ']' ) ) && this.isForParser() ) ) {
					text += getChar( data[ i ] );
					isStart = false;
				}
				i++;
			}
			// i points to the first non-text thing, go back one so we don't skip this later
			i--;
			// Add text
			Eif ( text.length > 0 ) {
				domElement.appendChild( doc.createTextNode( text ) );
			}
		} else if (
			Array.isArray( data[ i ] ) ||
			(
				data[ i ].annotations !== undefined &&
				this.nodeFactory.canNodeSerializeAsContent( data[ i ].type )
			)
		) {
			// Annotated text, nodes or meta
			text = '';
			annotatedDomElements = [];
			annotatedDomElementStack = [ annotatedDomElements ];
			while (
				data[ i ] !== undefined && (
					Array.isArray( data[ i ] ) ||
					(
						data[ i ].annotations !== undefined &&
						this.nodeFactory.canNodeSerializeAsContent( data[ i ].type )
					)
				)
			) {
				annotations = new ve.dm.AnnotationSet(
					this.store, data[ i ].annotations || data[ i ][ 1 ]
				);
				this.constructor.static.openAndCloseAnnotations( annotationStack, annotations,
					openAnnotation, closeAnnotation
				);
 
				if ( data[ i ].annotations === undefined ) {
					// Annotated text
					text += getChar( data[ i ][ 0 ] );
				} else {
					// Annotated node
					// Add text if needed
					if ( text.length > 0 ) {
						annotatedDomElements.push( doc.createTextNode( text ) );
						text = '';
					}
					// Insert the elements
					dataElementOrSlice = getDataElementOrSlice();
					childDomElements = this.getDomElementsFromDataElement( dataElementOrSlice, doc );
					for ( j = 0; j < childDomElements.length; j++ ) {
						annotatedDomElements.push( childDomElements[ j ] );
					}
					Iif ( Array.isArray( dataElementOrSlice ) ) {
						i += dataElementOrSlice.length - 1;
					} else {
						i++; // Skip the closing
					}
				}
				i++;
			}
			// We're now at the first non-annotated thing, go back one so we don't skip this later
			i--;
 
			// Add any gathered text
			if ( text.length > 0 ) {
				annotatedDomElements.push( doc.createTextNode( text ) );
				text = '';
			}
			// Close any remaining annotations
			this.constructor.static.openAndCloseAnnotations( annotationStack, new ve.dm.AnnotationSet( this.store ),
				openAnnotation, closeAnnotation
			);
			// Put the annotated nodes in the DOM
			for ( j = 0; j < annotatedDomElements.length; j++ ) {
				domElement.appendChild( annotatedDomElements[ j ] );
			}
		} else Eif ( data[ i ].type !== undefined ) {
			dataElement = data[ i ];
			// Element
			if ( dataElement.type.charAt( 0 ) === '/' ) {
				// Close element
				parentDomElement = domElement.parentNode;
				type = data[ i ].type.slice( 1 );
				isContentNode = this.nodeFactory.isNodeContent( type );
				// Process whitespace
				// whitespace = [ outerPre, innerPre, innerPost, outerPost ]
				oldLastOuterPost = parentDomElement.lastOuterPost;
				if (
					!isContentNode &&
					domElement.veInternal &&
					domElement.veInternal.whitespace
				) {
					// Process inner whitespace. innerPre is for sure legitimate
					// whitespace that should be inserted; if it was a duplicate
					// of our child's outerPre, we would have cleared it.
					pre = domElement.veInternal.whitespace[ 1 ];
					if ( pre ) {
						if (
							domElement.firstChild &&
							domElement.firstChild.nodeType === Node.TEXT_NODE
						) {
							// First child is a TextNode, prepend to it
							domElement.firstChild.insertData( 0, pre );
						} else {
							// Prepend a TextNode
							textNode = doc.createTextNode( pre );
							textNode.veIsWhitespace = true;
							domElement.insertBefore(
								textNode,
								domElement.firstChild
							);
						}
					}
					lastChild = domElement.veInternal.childDomElements ?
						domElement.veInternal
							.childDomElements[ domElement.veInternal.childDomElements.length - 1 ]
							.lastChild :
						domElement.lastChild;
					ours = domElement.veInternal.whitespace[ 2 ];
					if ( domElement.lastOuterPost === undefined ) {
						// This node didn't have any structural children
						// (i.e. it's a content-containing node), so there's
						// nothing to check innerPost against
						theirs = ours;
					} else {
						theirs = domElement.lastOuterPost;
					}
					if ( ours && ours === theirs ) {
						if ( lastChild && lastChild.nodeType === Node.TEXT_NODE ) {
							// Last child is a TextNode, append to it
							domElement.lastChild.appendData( ours );
						} else {
							// Append a TextNode
							textNode = doc.createTextNode( ours );
							textNode.veIsWhitespace = true;
							domElement.appendChild(
								textNode
							);
						}
					}
					// Tell the parent about our outerPost
					parentDomElement.lastOuterPost = domElement.veInternal.whitespace[ 3 ] || '';
				} else if ( !isContentNode ) {
					// Use empty string, because undefined means there were no
					// structural children
					parentDomElement.lastOuterPost = '';
				}
				// else don't touch lastOuterPost
 
				// Logic to unwrap empty & wrapper nodes.
				// It would be nicer if we could avoid generating in the first
				// place, but then remembering where we have to skip ascending
				// to the parent would be tricky.
				doUnwrap = false;
				Eif ( domElement.veInternal ) {
					switch ( domElement.veInternal.generated ) {
						case 'slug':
							// 'slug' elements - remove if they are still empty
							Eif ( domElement.childNodes.length === 0 ) {
								doUnwrap = true;
							}
							break;
						case 'empty':
							// 'empty' elements - first ensure they are actually empty
							if (
								domElement.childNodes.length === 0 &&
								(
									// then check that we are the last child
									// before unwrapping (and therefore destroying)
									data[ i + 1 ] === undefined ||
									data[ i + 1 ].type.charAt( 0 ) === '/' ||
									// Document ends when we encounter the internal list
									(
										data[ i + 1 ].type &&
										this.nodeFactory.isNodeInternal( data[ i + 1 ].type )
									)
								)
							) {
								doUnwrap = true;
							}
							break;
						case 'wrapper':
							// 'wrapper' elements - ensure there is a block level
							// element between this element and the previous sibling
							// wrapper or parent node
							doUnwrap = true;
							previousSiblings = domElement.parentElement.childNodes;
							// Note: previousSiblings includes the current element
							// so we only go up to length - 2
							for ( j = previousSiblings.length - 2; j >= 0; j-- ) {
								sibling = previousSiblings[ j ];
								Iif ( sibling.nodeType === Node.TEXT_NODE && !sibling.veIsWhitespace ) {
									// we've found an unwrapped paragraph so don't unwrap
									doUnwrap = false;
									break;
								}
								if ( ve.isBlockElement( sibling ) ) {
									// there is a block element before the next unwrapped node
									// so it's safe to unwrap
									break;
								}
							}
							break;
					}
				}
				if ( doUnwrap ) {
					if ( domElement.childNodes.length ) {
						// If domElement has children, append them to parentDomElement
						while ( domElement.firstChild ) {
							parentDomElement.insertBefore(
								domElement.firstChild,
								domElement
							);
						}
					} else {
						// If domElement has no children, it's as if it was never there at all,
						// so set lastOuterPost back to what it was, except that we need to
						// change undefined to '' , since undefined means there were no children.
						parentDomElement.lastOuterPost = oldLastOuterPost || '';
					}
					parentDomElement.removeChild( domElement );
				}
 
				delete domElement.veInternal;
				delete domElement.lastOuterPost;
				// Ascend to parent node, except if this is an internal node
				// TODO: It's not covered with unit tests.
				Eif ( !ve.dm.nodeFactory.lookup( type ) || !ve.dm.nodeFactory.isNodeInternal( type ) ) {
					domElement = parentDomElement;
				}
			} else {
				// Create node from data
				if ( this.nodeFactory.isNodeInternal( data[ i ].type ) ) {
					// Reached the internal list, finish
					break;
				}
				isContentNode = this.nodeFactory.isNodeContent( data[ i ].type );
 
				dataElementOrSlice = getDataElementOrSlice();
				childDomElements = this.getDomElementsFromDataElement( dataElementOrSlice, doc );
				Iif ( childDomElements && !childDomElements.length ) {
					// Support toDomElements returning an empty array
					i = findEndOfNode( i ) - 1;
					continue;
				} else Eif ( childDomElements ) {
					// Add clone of internal data; we use a clone rather than a reference because
					// we modify .veInternal.whitespace[1] in some cases
					childDomElements[ 0 ].veInternal = ve.extendObject(
						{ childDomElements: childDomElements },
						dataElement.internal ? ve.copy( dataElement.internal ) : {}
					);
					// Add elements
					for ( j = 0; j < childDomElements.length; j++ ) {
						domElement.appendChild( childDomElements[ j ] );
					}
					// Descend into the first child node
					parentDomElement = domElement;
					domElement = childDomElements[ 0 ];
 
					// Process outer whitespace
					// Every piece of outer whitespace is duplicated somewhere:
					// each node's outerPost is duplicated as the next node's
					// outerPre, the first node's outerPre is the parent's
					// innerPre, and the last node's outerPost is the parent's
					// innerPost. For each piece of whitespace, we verify that
					// the duplicate matches. If it doesn't, we take that to
					// mean the user has messed with it and don't output any
					// whitespace.
					if ( domElement.veInternal && domElement.veInternal.whitespace ) {
						// Process this node's outerPre
						ours = domElement.veInternal.whitespace[ 0 ];
						theirs = undefined;
						if ( domElement.previousSibling ) {
							// Get previous sibling's outerPost
							theirs = parentDomElement.lastOuterPost;
						} else if ( parentDomElement === container ) {
							// outerPre of the very first node in the document, check against body innerWhitespace
							theirs = innerWhitespace ? innerWhitespace[ 0 ] : ours;
						} else {
							// First child, get parent's innerPre
							if (
								parentDomElement.veInternal &&
								parentDomElement.veInternal.whitespace
							) {
								theirs = parentDomElement.veInternal.whitespace[ 1 ];
								// Clear parent's innerPre so it's not used again
								parentDomElement.veInternal.whitespace[ 1 ] = undefined;
							}
							// else theirs=undefined
						}
						if ( ours && ours === theirs ) {
							// Matches the duplicate, insert a TextNode
							textNode = doc.createTextNode( ours );
							textNode.veIsWhitespace = true;
							parentDomElement.insertBefore(
								textNode,
								domElement
							);
						}
					} else if (
						!isContentNode &&
						!domElement.previousSibling &&
						parentDomElement.veInternal &&
						parentDomElement.veInternal.whitespace
					) {
						// The parent's innerPre should not be used, because it doesn't match
						// outerPre (since we didn't have any whitespace set at all).
						// Except if this is a content node, because content nodes
						// don't have whitespace annotated on them *sigh*
						parentDomElement.veInternal.whitespace[ 1 ] = undefined;
					}
				}
 
				if ( Array.isArray( dataElementOrSlice ) ) {
					i += dataElementOrSlice.length - 2;
				} else Iif ( childDomElements && childDomElements.length && childDomElements[ 0 ].handledOwnChildren ) {
					i = findEndOfNode( i ) - 2;
				}
			}
		}
	}
	// Check outerPost whitespace of the very last node against body innerWhitespace
	if (
		container.lastOuterPost !== undefined &&
		( !innerWhitespace || container.lastOuterPost === innerWhitespace[ 1 ] )
	) {
		if ( container.lastChild && container.lastChild.nodeType === Node.TEXT_NODE ) {
			// Last child is a TextNode, append to it
			container.lastChild.appendData( container.lastOuterPost );
		} else if ( container.lastOuterPost.length > 0 ) {
			// Append a TextNode
			container.appendChild( doc.createTextNode( container.lastOuterPost ) );
		}
		delete container.lastOuterPost;
	}
	// Get rid of excess text nodes
	ve.normalizeNode( container );
};
 
/* Initialization */
 
ve.dm.converter = new ve.dm.Converter( ve.dm.modelRegistry, ve.dm.nodeFactory, ve.dm.annotationFactory );