summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.cc
blob: 9a51fcdf019150135e2691f4d25b98331b9639d6 (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
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
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
/*
 * Copyright (C) 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "third_party/blink/renderer/core/editing/commands/composite_edit_command.h"

#include <algorithm>
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/document_fragment.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/scoped_event_queue.h"
#include "third_party/blink/renderer/core/dom/node_traversal.h"
#include "third_party/blink/renderer/core/dom/range.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/editing/commands/append_node_command.h"
#include "third_party/blink/renderer/core/editing/commands/apply_style_command.h"
#include "third_party/blink/renderer/core/editing/commands/delete_from_text_node_command.h"
#include "third_party/blink/renderer/core/editing/commands/delete_selection_command.h"
#include "third_party/blink/renderer/core/editing/commands/editing_commands_utilities.h"
#include "third_party/blink/renderer/core/editing/commands/insert_into_text_node_command.h"
#include "third_party/blink/renderer/core/editing/commands/insert_line_break_command.h"
#include "third_party/blink/renderer/core/editing/commands/insert_node_before_command.h"
#include "third_party/blink/renderer/core/editing/commands/insert_paragraph_separator_command.h"
#include "third_party/blink/renderer/core/editing/commands/merge_identical_elements_command.h"
#include "third_party/blink/renderer/core/editing/commands/remove_css_property_command.h"
#include "third_party/blink/renderer/core/editing/commands/remove_node_command.h"
#include "third_party/blink/renderer/core/editing/commands/remove_node_preserving_children_command.h"
#include "third_party/blink/renderer/core/editing/commands/replace_node_with_span_command.h"
#include "third_party/blink/renderer/core/editing/commands/replace_selection_command.h"
#include "third_party/blink/renderer/core/editing/commands/set_character_data_command.h"
#include "third_party/blink/renderer/core/editing/commands/set_node_attribute_command.h"
#include "third_party/blink/renderer/core/editing/commands/split_element_command.h"
#include "third_party/blink/renderer/core/editing/commands/split_text_node_command.h"
#include "third_party/blink/renderer/core/editing/commands/split_text_node_containing_element_command.h"
#include "third_party/blink/renderer/core/editing/commands/undo_stack.h"
#include "third_party/blink/renderer/core/editing/commands/wrap_contents_in_dummy_span_command.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/editor.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/iterators/text_iterator.h"
#include "third_party/blink/renderer/core/editing/markers/document_marker_controller.h"
#include "third_party/blink/renderer/core/editing/plain_text_range.h"
#include "third_party/blink/renderer/core/editing/relocatable_position.h"
#include "third_party/blink/renderer/core/editing/selection_template.h"
#include "third_party/blink/renderer/core/editing/serializers/serialization.h"
#include "third_party/blink/renderer/core/editing/visible_position.h"
#include "third_party/blink/renderer/core/editing/visible_selection.h"
#include "third_party/blink/renderer/core/editing/visible_units.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/html/html_br_element.h"
#include "third_party/blink/renderer/core/html/html_div_element.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html/html_li_element.h"
#include "third_party/blink/renderer/core/html/html_quote_element.h"
#include "third_party/blink/renderer/core/html/html_span_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_block.h"
#include "third_party/blink/renderer/core/layout/layout_list_item.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/core/layout/line/inline_text_box.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"

namespace blink {

using namespace html_names;

CompositeEditCommand::CompositeEditCommand(Document& document)
    : EditCommand(document) {
  const VisibleSelection& visible_selection =
      document.GetFrame()
          ->Selection()
          .ComputeVisibleSelectionInDOMTreeDeprecated();
  SetStartingSelection(
      SelectionForUndoStep::From(visible_selection.AsSelection()));
  SetEndingSelection(starting_selection_);
}

CompositeEditCommand::~CompositeEditCommand() {
  DCHECK(IsTopLevelCommand() || !undo_step_);
}

VisibleSelection CompositeEditCommand::EndingVisibleSelection() const {
  // TODO(editing-dev): The use of
  // |Document::UpdateStyleAndLayout()|
  // needs to be audited.  See http://crbug.com/590369 for more details.
  GetDocument().UpdateStyleAndLayout();
  return CreateVisibleSelection(ending_selection_);
}

bool CompositeEditCommand::Apply() {
  DCHECK(!IsCommandGroupWrapper());
  if (!IsRichlyEditablePosition(EndingVisibleSelection().Base())) {
    switch (GetInputType()) {
      case InputEvent::InputType::kInsertText:
      case InputEvent::InputType::kInsertLineBreak:
      case InputEvent::InputType::kInsertParagraph:
      case InputEvent::InputType::kInsertFromPaste:
      case InputEvent::InputType::kInsertFromDrop:
      case InputEvent::InputType::kInsertFromYank:
      case InputEvent::InputType::kInsertTranspose:
      case InputEvent::InputType::kInsertReplacementText:
      case InputEvent::InputType::kInsertCompositionText:
      case InputEvent::InputType::kDeleteWordBackward:
      case InputEvent::InputType::kDeleteWordForward:
      case InputEvent::InputType::kDeleteSoftLineBackward:
      case InputEvent::InputType::kDeleteSoftLineForward:
      case InputEvent::InputType::kDeleteHardLineBackward:
      case InputEvent::InputType::kDeleteHardLineForward:
      case InputEvent::InputType::kDeleteContentBackward:
      case InputEvent::InputType::kDeleteContentForward:
      case InputEvent::InputType::kDeleteByCut:
      case InputEvent::InputType::kDeleteByDrag:
      case InputEvent::InputType::kNone:
        break;
      default:
        return false;
    }
  }
  EnsureUndoStep();

  // Changes to the document may have been made since the last editing operation
  // that require a layout, as in <rdar://problem/5658603>. Low level
  // operations, like RemoveNodeCommand, don't require a layout because the high
  // level operations that use them perform one if one is necessary (like for
  // the creation of VisiblePositions).
  GetDocument().UpdateStyleAndLayout();

  LocalFrame* frame = GetDocument().GetFrame();
  DCHECK(frame);
  // directional is stored at the top level command, so that before and after
  // executing command same directional will be there.
  SetSelectionIsDirectional(frame->Selection().IsDirectional());
  GetUndoStep()->SetSelectionIsDirectional(SelectionIsDirectional());

  EditingState editing_state;
  EventQueueScope event_queue_scope;
  DoApply(&editing_state);

  // Only need to call appliedEditing for top-level commands, and TypingCommands
  // do it on their own (see TypingCommand::typingAddedToOpenCommand).
  if (!IsTypingCommand())
    AppliedEditing();
  return !editing_state.IsAborted();
}

UndoStep* CompositeEditCommand::EnsureUndoStep() {
  CompositeEditCommand* command = this;
  while (command && command->Parent())
    command = command->Parent();
  if (!command->undo_step_) {
    command->undo_step_ = MakeGarbageCollected<UndoStep>(
        &GetDocument(), StartingSelection(), EndingSelection(), GetInputType());
  }
  return command->undo_step_.Get();
}

bool CompositeEditCommand::PreservesTypingStyle() const {
  return false;
}

bool CompositeEditCommand::IsTypingCommand() const {
  return false;
}

bool CompositeEditCommand::IsCommandGroupWrapper() const {
  return false;
}

bool CompositeEditCommand::IsDragAndDropCommand() const {
  return false;
}

bool CompositeEditCommand::IsReplaceSelectionCommand() const {
  return false;
}

//
// sugary-sweet convenience functions to help create and apply edit commands in
// composite commands
//
void CompositeEditCommand::ApplyCommandToComposite(
    EditCommand* command,
    EditingState* editing_state) {
  command->SetParent(this);
  command->SetSelectionIsDirectional(SelectionIsDirectional());
  command->DoApply(editing_state);
  if (editing_state->IsAborted()) {
    command->SetParent(nullptr);
    return;
  }
  if (auto* simple_edit_command = DynamicTo<SimpleEditCommand>(command)) {
    command->SetParent(nullptr);
    EnsureUndoStep()->Append(simple_edit_command);
  }
  commands_.push_back(command);
}

void CompositeEditCommand::AppendCommandToUndoStep(
    CompositeEditCommand* command) {
  EnsureUndoStep()->Append(command->EnsureUndoStep());
  command->undo_step_ = nullptr;
  command->SetParent(this);
  commands_.push_back(command);
}

void CompositeEditCommand::ApplyStyle(const EditingStyle* style,
                                      EditingState* editing_state) {
  ApplyCommandToComposite(
      MakeGarbageCollected<ApplyStyleCommand>(GetDocument(), style,
                                              InputEvent::InputType::kNone),
      editing_state);
}

void CompositeEditCommand::ApplyStyle(const EditingStyle* style,
                                      const Position& start,
                                      const Position& end,
                                      EditingState* editing_state) {
  ApplyCommandToComposite(
      MakeGarbageCollected<ApplyStyleCommand>(GetDocument(), style, start, end),
      editing_state);
}

void CompositeEditCommand::ApplyStyledElement(Element* element,
                                              EditingState* editing_state) {
  ApplyCommandToComposite(
      MakeGarbageCollected<ApplyStyleCommand>(element, false), editing_state);
}

void CompositeEditCommand::RemoveStyledElement(Element* element,
                                               EditingState* editing_state) {
  ApplyCommandToComposite(
      MakeGarbageCollected<ApplyStyleCommand>(element, true), editing_state);
}

void CompositeEditCommand::InsertParagraphSeparator(
    EditingState* editing_state,
    bool use_default_paragraph_element,
    bool paste_blockqutoe_into_unquoted_area) {
  ApplyCommandToComposite(MakeGarbageCollected<InsertParagraphSeparatorCommand>(
                              GetDocument(), use_default_paragraph_element,
                              paste_blockqutoe_into_unquoted_area),
                          editing_state);
}

bool CompositeEditCommand::IsRemovableBlock(const Node* node) {
  DCHECK(node);
  if (!IsHTMLDivElement(*node))
    return false;

  const HTMLDivElement& element = ToHTMLDivElement(*node);
  ContainerNode* parent_node = element.parentNode();
  if (parent_node && parent_node->firstChild() != parent_node->lastChild())
    return false;

  if (!element.hasAttributes())
    return true;

  return false;
}

void CompositeEditCommand::InsertNodeBefore(
    Node* insert_child,
    Node* ref_child,
    EditingState* editing_state,
    ShouldAssumeContentIsAlwaysEditable
        should_assume_content_is_always_editable) {
  ABORT_EDITING_COMMAND_IF(GetDocument().body() == ref_child);
  ABORT_EDITING_COMMAND_IF(!ref_child->parentNode());
  // TODO(editing-dev): Use of UpdateStyleAndLayout
  // needs to be audited.  See http://crbug.com/590369 for more details.
  GetDocument().UpdateStyleAndLayout();
  ABORT_EDITING_COMMAND_IF(!HasEditableStyle(*ref_child->parentNode()) &&
                           ref_child->parentNode()->InActiveDocument());
  ApplyCommandToComposite(
      MakeGarbageCollected<InsertNodeBeforeCommand>(
          insert_child, ref_child, should_assume_content_is_always_editable),
      editing_state);
}

void CompositeEditCommand::InsertNodeAfter(Node* insert_child,
                                           Node* ref_child,
                                           EditingState* editing_state) {
  ABORT_EDITING_COMMAND_IF(!ref_child->parentNode());
  DCHECK(insert_child);
  DCHECK(ref_child);
  DCHECK_NE(GetDocument().body(), ref_child);
  ContainerNode* parent = ref_child->parentNode();
  DCHECK(parent);
  DCHECK(!parent->IsShadowRoot()) << parent;
  if (parent->lastChild() == ref_child) {
    AppendNode(insert_child, parent, editing_state);
  } else {
    DCHECK(ref_child->nextSibling()) << ref_child;
    InsertNodeBefore(insert_child, ref_child->nextSibling(), editing_state);
  }
}

void CompositeEditCommand::InsertNodeAt(Node* insert_child,
                                        const Position& editing_position,
                                        EditingState* editing_state) {
  GetDocument().UpdateStyleAndLayout();
  ABORT_EDITING_COMMAND_IF(!IsEditablePosition(editing_position));
  // For editing positions like [table, 0], insert before the table,
  // likewise for replaced elements, brs, etc.
  Position p = editing_position.ParentAnchoredEquivalent();
  Node* ref_child = p.AnchorNode();
  int offset = p.OffsetInContainerNode();

  auto* ref_child_text_node = DynamicTo<Text>(ref_child);
  if (CanHaveChildrenForEditing(ref_child)) {
    Node* child = ref_child->firstChild();
    for (int i = 0; child && i < offset; i++)
      child = child->nextSibling();
    if (child)
      InsertNodeBefore(insert_child, child, editing_state);
    else
      AppendNode(insert_child, To<ContainerNode>(ref_child), editing_state);
  } else if (CaretMinOffset(ref_child) >= offset) {
    InsertNodeBefore(insert_child, ref_child, editing_state);
  } else if (ref_child_text_node && CaretMaxOffset(ref_child) > offset) {
    SplitTextNode(ref_child_text_node, offset);

    // Mutation events (bug 22634) from the text node insertion may have
    // removed the refChild
    if (!ref_child->isConnected())
      return;
    InsertNodeBefore(insert_child, ref_child, editing_state);
  } else {
    InsertNodeAfter(insert_child, ref_child, editing_state);
  }
}

void CompositeEditCommand::AppendNode(Node* node,
                                      ContainerNode* parent,
                                      EditingState* editing_state) {
  // When cloneParagraphUnderNewElement() clones the fallback content
  // of an OBJECT element, the ASSERT below may fire since the return
  // value of canHaveChildrenForEditing is not reliable until the layout
  // object of the OBJECT is created. Hence we ignore this check for OBJECTs.
  // TODO(yosin): We should move following |ABORT_EDITING_COMMAND_IF|s to
  // |AppendNodeCommand|.
  // TODO(yosin): We should get rid of |canHaveChildrenForEditing()|, since
  // |cloneParagraphUnderNewElement()| attempt to clone non-well-formed HTML,
  // produced by JavaScript.
  auto* parent_element = DynamicTo<Element>(parent);
  ABORT_EDITING_COMMAND_IF(
      !CanHaveChildrenForEditing(parent) &&
      !(parent_element && parent_element->TagQName() == kObjectTag));
  ABORT_EDITING_COMMAND_IF(!HasEditableStyle(*parent) &&
                           parent->InActiveDocument());
  ApplyCommandToComposite(MakeGarbageCollected<AppendNodeCommand>(parent, node),
                          editing_state);
}

void CompositeEditCommand::RemoveAllChildrenIfPossible(
    ContainerNode* container,
    EditingState* editing_state,
    ShouldAssumeContentIsAlwaysEditable
        should_assume_content_is_always_editable) {
  Node* child = container->firstChild();
  while (child) {
    Node* const next = child->nextSibling();
    RemoveNode(child, editing_state, should_assume_content_is_always_editable);
    if (editing_state->IsAborted())
      return;
    if (next && next->parentNode() != container) {
      // |RemoveNode()| moves |next| outside |node|.
      return;
    }
    child = next;
  }
}

void CompositeEditCommand::RemoveChildrenInRange(Node* node,
                                                 unsigned from,
                                                 unsigned to,
                                                 EditingState* editing_state) {
  HeapVector<Member<Node>> children;
  Node* child = NodeTraversal::ChildAt(*node, from);
  for (unsigned i = from; child && i < to; i++, child = child->nextSibling())
    children.push_back(child);

  size_t size = children.size();
  for (wtf_size_t i = 0; i < size; ++i) {
    RemoveNode(children[i].Release(), editing_state);
    if (editing_state->IsAborted())
      return;
  }
}

void CompositeEditCommand::RemoveNode(
    Node* node,
    EditingState* editing_state,
    ShouldAssumeContentIsAlwaysEditable
        should_assume_content_is_always_editable) {
  if (!node || !node->NonShadowBoundaryParentNode())
    return;
  ABORT_EDITING_COMMAND_IF(!node->GetDocument().GetFrame());
  ApplyCommandToComposite(MakeGarbageCollected<RemoveNodeCommand>(
                              node, should_assume_content_is_always_editable),
                          editing_state);
}

void CompositeEditCommand::RemoveNodePreservingChildren(
    Node* node,
    EditingState* editing_state,
    ShouldAssumeContentIsAlwaysEditable
        should_assume_content_is_always_editable) {
  ABORT_EDITING_COMMAND_IF(!node->GetDocument().GetFrame());
  ApplyCommandToComposite(
      MakeGarbageCollected<RemoveNodePreservingChildrenCommand>(
          node, should_assume_content_is_always_editable),
      editing_state);
}

void CompositeEditCommand::RemoveNodeAndPruneAncestors(
    Node* node,
    EditingState* editing_state,
    Node* exclude_node) {
  DCHECK_NE(node, exclude_node);
  ContainerNode* parent = node->parentNode();
  RemoveNode(node, editing_state);
  if (editing_state->IsAborted())
    return;
  Prune(parent, editing_state, exclude_node);
}

void CompositeEditCommand::MoveRemainingSiblingsToNewParent(
    Node* node,
    Node* past_last_node_to_move,
    Element* new_parent,
    EditingState* editing_state) {
  NodeVector nodes_to_remove;

  for (; node && node != past_last_node_to_move; node = node->nextSibling())
    nodes_to_remove.push_back(node);

  for (unsigned i = 0; i < nodes_to_remove.size(); i++) {
    RemoveNode(nodes_to_remove[i], editing_state);
    if (editing_state->IsAborted())
      return;
    AppendNode(nodes_to_remove[i], new_parent, editing_state);
    if (editing_state->IsAborted())
      return;
  }
}

void CompositeEditCommand::UpdatePositionForNodeRemovalPreservingChildren(
    Position& position,
    Node& node) {
  int offset =
      position.IsOffsetInAnchor() ? position.OffsetInContainerNode() : 0;
  position = ComputePositionForNodeRemoval(position, node);
  if (offset == 0)
    return;
  position = Position::CreateWithoutValidationDeprecated(
      *position.ComputeContainerNode(), offset);
}

HTMLSpanElement*
CompositeEditCommand::ReplaceElementWithSpanPreservingChildrenAndAttributes(
    HTMLElement* node) {
  // It would also be possible to implement all of ReplaceNodeWithSpanCommand
  // as a series of existing smaller edit commands.  Someone who wanted to
  // reduce the number of edit commands could do so here.
  auto* command = MakeGarbageCollected<ReplaceNodeWithSpanCommand>(node);
  // ReplaceNodeWithSpanCommand is never aborted.
  ApplyCommandToComposite(command, ASSERT_NO_EDITING_ABORT);
  // Returning a raw pointer here is OK because the command is retained by
  // applyCommandToComposite (thus retaining the span), and the span is also
  // in the DOM tree, and thus alive whie it has a parent.
  DCHECK(command->SpanElement()->isConnected()) << command->SpanElement();
  return command->SpanElement();
}

void CompositeEditCommand::Prune(Node* node,
                                 EditingState* editing_state,
                                 Node* exclude_node) {
  if (Node* highest_node_to_remove =
          HighestNodeToRemoveInPruning(node, exclude_node))
    RemoveNode(highest_node_to_remove, editing_state);
}

void CompositeEditCommand::SplitTextNode(Text* node, unsigned offset) {
  // SplitTextNodeCommand is never aborted.
  ApplyCommandToComposite(
      MakeGarbageCollected<SplitTextNodeCommand>(node, offset),
      ASSERT_NO_EDITING_ABORT);
}

void CompositeEditCommand::SplitElement(Element* element, Node* at_child) {
  // SplitElementCommand is never aborted.
  ApplyCommandToComposite(
      MakeGarbageCollected<SplitElementCommand>(element, at_child),
      ASSERT_NO_EDITING_ABORT);
}

void CompositeEditCommand::MergeIdenticalElements(Element* first,
                                                  Element* second,
                                                  EditingState* editing_state) {
  DCHECK(!first->IsDescendantOf(second)) << first << " " << second;
  DCHECK_NE(second, first);
  if (first->nextSibling() != second) {
    RemoveNode(second, editing_state);
    if (editing_state->IsAborted())
      return;
    InsertNodeAfter(second, first, editing_state);
    if (editing_state->IsAborted())
      return;
  }
  ApplyCommandToComposite(
      MakeGarbageCollected<MergeIdenticalElementsCommand>(first, second),
      editing_state);
}

void CompositeEditCommand::WrapContentsInDummySpan(Element* element) {
  // WrapContentsInDummySpanCommand is never aborted.
  ApplyCommandToComposite(
      MakeGarbageCollected<WrapContentsInDummySpanCommand>(element),
      ASSERT_NO_EDITING_ABORT);
}

void CompositeEditCommand::SplitTextNodeContainingElement(Text* text,
                                                          unsigned offset) {
  // SplitTextNodeContainingElementCommand is never aborted.
  ApplyCommandToComposite(
      MakeGarbageCollected<SplitTextNodeContainingElementCommand>(text, offset),
      ASSERT_NO_EDITING_ABORT);
}

void CompositeEditCommand::InsertTextIntoNode(Text* node,
                                              unsigned offset,
                                              const String& text) {
  // InsertIntoTextNodeCommand is never aborted.
  if (!text.IsEmpty())
    ApplyCommandToComposite(
        MakeGarbageCollected<InsertIntoTextNodeCommand>(node, offset, text),
        ASSERT_NO_EDITING_ABORT);
}

void CompositeEditCommand::DeleteTextFromNode(Text* node,
                                              unsigned offset,
                                              unsigned count) {
  // DeleteFromTextNodeCommand is never aborted.
  ApplyCommandToComposite(
      MakeGarbageCollected<DeleteFromTextNodeCommand>(node, offset, count),
      ASSERT_NO_EDITING_ABORT);
}

void CompositeEditCommand::ReplaceTextInNode(Text* node,
                                             unsigned offset,
                                             unsigned count,
                                             const String& replacement_text) {
  // SetCharacterDataCommand is never aborted.
  ApplyCommandToComposite(MakeGarbageCollected<SetCharacterDataCommand>(
                              node, offset, count, replacement_text),
                          ASSERT_NO_EDITING_ABORT);
}

Position CompositeEditCommand::ReplaceSelectedTextInNode(const String& text) {
  const Position& start = EndingSelection().Start();
  const Position& end = EndingSelection().End();
  auto* text_node = DynamicTo<Text>(start.ComputeContainerNode());
  if (!text_node || text_node != end.ComputeContainerNode() ||
      IsTabHTMLSpanElementTextNode(text_node))
    return Position();

  ReplaceTextInNode(text_node, start.OffsetInContainerNode(),
                    end.OffsetInContainerNode() - start.OffsetInContainerNode(),
                    text);

  return Position(text_node, start.OffsetInContainerNode() + text.length());
}

Position CompositeEditCommand::PositionOutsideTabSpan(const Position& pos) {
  if (!IsTabHTMLSpanElementTextNode(pos.AnchorNode()))
    return pos;

  switch (pos.AnchorType()) {
    case PositionAnchorType::kBeforeChildren:
    case PositionAnchorType::kAfterChildren:
      NOTREACHED();
      return pos;
    case PositionAnchorType::kOffsetInAnchor:
      break;
    case PositionAnchorType::kBeforeAnchor:
      return Position::InParentBeforeNode(*pos.AnchorNode());
    case PositionAnchorType::kAfterAnchor:
      return Position::InParentAfterNode(*pos.AnchorNode());
  }

  HTMLSpanElement* tab_span = TabSpanElement(pos.ComputeContainerNode());
  DCHECK(tab_span);

  // TODO(editing-dev): Hoist this UpdateStyleAndLayout
  // to the callers. See crbug.com/590369 for details.
  GetDocument().UpdateStyleAndLayout();

  if (pos.OffsetInContainerNode() <= CaretMinOffset(pos.ComputeContainerNode()))
    return Position::InParentBeforeNode(*tab_span);

  if (pos.OffsetInContainerNode() >= CaretMaxOffset(pos.ComputeContainerNode()))
    return Position::InParentAfterNode(*tab_span);

  SplitTextNodeContainingElement(To<Text>(pos.ComputeContainerNode()),
                                 pos.OffsetInContainerNode());
  return Position::InParentBeforeNode(*tab_span);
}

void CompositeEditCommand::InsertNodeAtTabSpanPosition(
    Node* node,
    const Position& pos,
    EditingState* editing_state) {
  // insert node before, after, or at split of tab span
  InsertNodeAt(node, PositionOutsideTabSpan(pos), editing_state);
}

bool CompositeEditCommand::DeleteSelection(
    EditingState* editing_state,
    const DeleteSelectionOptions& options) {
  if (!EndingSelection().IsRange())
    return true;

  ApplyCommandToComposite(
      DeleteSelectionCommand::Create(GetDocument(), options), editing_state);
  if (editing_state->IsAborted())
    return false;

  if (!EndingSelection().IsValidFor(GetDocument())) {
    editing_state->Abort();
    return false;
  }
  return true;
}

void CompositeEditCommand::RemoveCSSProperty(Element* element,
                                             CSSPropertyID property) {
  // RemoveCSSPropertyCommand is never aborted.
  ApplyCommandToComposite(MakeGarbageCollected<RemoveCSSPropertyCommand>(
                              GetDocument(), element, property),
                          ASSERT_NO_EDITING_ABORT);
}

void CompositeEditCommand::RemoveElementAttribute(
    Element* element,
    const QualifiedName& attribute) {
  SetNodeAttribute(element, attribute, AtomicString());
}

void CompositeEditCommand::SetNodeAttribute(Element* element,
                                            const QualifiedName& attribute,
                                            const AtomicString& value) {
  // SetNodeAttributeCommand is never aborted.
  ApplyCommandToComposite(
      MakeGarbageCollected<SetNodeAttributeCommand>(element, attribute, value),
      ASSERT_NO_EDITING_ABORT);
}

bool CompositeEditCommand::CanRebalance(const Position& position) const {
  // TODO(editing-dev): Use of UpdateStyleAndLayout()
  // needs to be audited.  See http://crbug.com/590369 for more details.
  GetDocument().UpdateStyleAndLayout();

  auto* text_node = DynamicTo<Text>(position.ComputeContainerNode());
  if (!position.IsOffsetInAnchor() || !text_node ||
      !HasRichlyEditableStyle(*text_node))
    return false;

  if (text_node->length() == 0)
    return false;

  LayoutText* layout_text = text_node->GetLayoutObject();
  if (layout_text && !layout_text->Style()->CollapseWhiteSpace())
    return false;

  return true;
}

// FIXME: Doesn't go into text nodes that contribute adjacent text (siblings,
// cousins, etc).
void CompositeEditCommand::RebalanceWhitespaceAt(const Position& position) {
  Node* node = position.ComputeContainerNode();
  if (!CanRebalance(position))
    return;

  // If the rebalance is for the single offset, and neither text[offset] nor
  // text[offset - 1] are some form of whitespace, do nothing.
  int offset = position.ComputeOffsetInContainerNode();
  String text = To<Text>(node)->data();
  if (!IsWhitespace(text[offset])) {
    offset--;
    if (offset < 0 || !IsWhitespace(text[offset]))
      return;
  }

  RebalanceWhitespaceOnTextSubstring(To<Text>(node),
                                     position.OffsetInContainerNode(),
                                     position.OffsetInContainerNode());
}

void CompositeEditCommand::RebalanceWhitespaceOnTextSubstring(Text* text_node,
                                                              int start_offset,
                                                              int end_offset) {
  String text = text_node->data();
  DCHECK(!text.IsEmpty());

  // Set upstream and downstream to define the extent of the whitespace
  // surrounding text[offset].
  int upstream = start_offset;
  while (upstream > 0 && IsWhitespace(text[upstream - 1]))
    upstream--;

  int downstream = end_offset;
  while ((unsigned)downstream < text.length() && IsWhitespace(text[downstream]))
    downstream++;

  int length = downstream - upstream;
  if (!length)
    return;

  GetDocument().UpdateStyleAndLayout();
  VisiblePosition visible_upstream_pos =
      CreateVisiblePosition(Position(text_node, upstream));
  VisiblePosition visible_downstream_pos =
      CreateVisiblePosition(Position(text_node, downstream));

  String string = text.Substring(upstream, length);
  // FIXME: Because of the problem mentioned at the top of this function, we
  // must also use nbsps at the start/end of the string because this function
  // doesn't get all surrounding whitespace, just the whitespace in the
  // current text node. However, if the next sibling node is a text node
  // (not empty, see http://crbug.com/632300), we should use a plain space.
  // See http://crbug.com/310149
  auto* next_text_node = DynamicTo<Text>(text_node->nextSibling());
  const bool next_sibling_is_text_node =
      next_text_node && next_text_node->data().length() &&
      !IsWhitespace(next_text_node->data()[0]);
  const bool should_emit_nbs_pbefore_end =
      (IsEndOfParagraph(visible_downstream_pos) ||
       (unsigned)downstream == text.length()) &&
      !next_sibling_is_text_node;
  String rebalanced_string = StringWithRebalancedWhitespace(
      string, IsStartOfParagraph(visible_upstream_pos) || !upstream,
      should_emit_nbs_pbefore_end);

  if (string != rebalanced_string)
    ReplaceTextInNode(text_node, upstream, length, rebalanced_string);
}

void CompositeEditCommand::PrepareWhitespaceAtPositionForSplit(
    Position& position) {
  if (!IsRichlyEditablePosition(position))
    return;

  auto* text_node = DynamicTo<Text>(position.AnchorNode());
  if (!text_node)
    return;

  if (text_node->length() == 0)
    return;
  LayoutText* layout_text = text_node->GetLayoutObject();
  if (layout_text && !layout_text->Style()->CollapseWhiteSpace())
    return;

  // Delete collapsed whitespace so that inserting nbsps doesn't uncollapse it.
  Position upstream_pos = MostBackwardCaretPosition(position);
  DeleteInsignificantText(upstream_pos, MostForwardCaretPosition(position));

  GetDocument().UpdateStyleAndLayout();
  position = MostForwardCaretPosition(upstream_pos);
  VisiblePosition visible_pos = CreateVisiblePosition(position);
  VisiblePosition previous_visible_pos = PreviousPositionOf(visible_pos);
  ReplaceCollapsibleWhitespaceWithNonBreakingSpaceIfNeeded(
      previous_visible_pos);

  GetDocument().UpdateStyleAndLayout();
  ReplaceCollapsibleWhitespaceWithNonBreakingSpaceIfNeeded(
      CreateVisiblePosition(position));
}

void CompositeEditCommand::
    ReplaceCollapsibleWhitespaceWithNonBreakingSpaceIfNeeded(
        const VisiblePosition& visible_position) {
  if (!IsCollapsibleWhitespace(CharacterAfter(visible_position)))
    return;
  Position pos = MostForwardCaretPosition(visible_position.DeepEquivalent());
  auto* container_text_node = DynamicTo<Text>(pos.ComputeContainerNode());
  if (!container_text_node)
    return;
  ReplaceTextInNode(container_text_node, pos.OffsetInContainerNode(), 1,
                    NonBreakingSpaceString());
}

void CompositeEditCommand::RebalanceWhitespace() {
  VisibleSelection selection = EndingVisibleSelection();
  if (selection.IsNone())
    return;

  RebalanceWhitespaceAt(selection.Start());
  if (selection.IsRange())
    RebalanceWhitespaceAt(selection.End());
}

void CompositeEditCommand::DeleteInsignificantText(Text* text_node,
                                                   unsigned start,
                                                   unsigned end) {
  if (!text_node || start >= end)
    return;

  GetDocument().UpdateStyleAndLayout();

  LayoutText* text_layout_object = text_node->GetLayoutObject();
  if (!text_layout_object)
    return;

  Vector<InlineTextBox*> sorted_text_boxes;
  wtf_size_t sorted_text_boxes_position = 0;

  for (InlineTextBox* text_box : text_layout_object->TextBoxes())
    sorted_text_boxes.push_back(text_box);

  // If there is mixed directionality text, the boxes can be out of order,
  // (like Arabic with embedded LTR), so sort them first.
  if (text_layout_object->ContainsReversedText())
    std::sort(sorted_text_boxes.begin(), sorted_text_boxes.end(),
              InlineTextBox::CompareByStart);
  InlineTextBox* box = sorted_text_boxes.IsEmpty()
                           ? 0
                           : sorted_text_boxes[sorted_text_boxes_position];

  if (!box) {
    // whole text node is empty
    // Removing a Text node won't dispatch synchronous events.
    RemoveNode(text_node, ASSERT_NO_EDITING_ABORT);
    return;
  }

  unsigned length = text_node->length();
  if (start >= length || end > length)
    return;

  unsigned removed = 0;
  InlineTextBox* prev_box = nullptr;
  String str;

  // This loop structure works to process all gaps preceding a box,
  // and also will look at the gap after the last box.
  while (prev_box || box) {
    unsigned gap_start = prev_box ? prev_box->Start() + prev_box->Len() : 0;
    if (end < gap_start) {
      // No more chance for any intersections
      break;
    }

    unsigned gap_end = box ? box->Start() : length;
    bool indices_intersect = start <= gap_end && end >= gap_start;
    int gap_len = gap_end - gap_start;
    if (indices_intersect && gap_len > 0) {
      gap_start = std::max(gap_start, start);
      if (str.IsNull())
        str = text_node->data().Substring(start, end - start);
      // remove text in the gap
      str.Remove(gap_start - start - removed, gap_len);
      removed += gap_len;
    }

    prev_box = box;
    if (box) {
      if (++sorted_text_boxes_position < sorted_text_boxes.size())
        box = sorted_text_boxes[sorted_text_boxes_position];
      else
        box = nullptr;
    }
  }

  if (!str.IsNull()) {
    // Replace the text between start and end with our pruned version.
    if (!str.IsEmpty()) {
      ReplaceTextInNode(text_node, start, end - start, str);
    } else {
      // Assert that we are not going to delete all of the text in the node.
      // If we were, that should have been done above with the call to
      // removeNode and return.
      DCHECK(start > 0 || end - start < text_node->length());
      DeleteTextFromNode(text_node, start, end - start);
    }
  }
}

void CompositeEditCommand::DeleteInsignificantText(const Position& start,
                                                   const Position& end) {
  if (start.IsNull() || end.IsNull())
    return;

  if (ComparePositions(start, end) >= 0)
    return;

  HeapVector<Member<Text>> nodes;
  for (Node& node : NodeTraversal::StartsAt(*start.AnchorNode())) {
    if (auto* text_node = DynamicTo<Text>(&node))
      nodes.push_back(text_node);
    if (&node == end.AnchorNode())
      break;
  }

  for (const auto& node : nodes) {
    Text* text_node = node;
    int start_offset = text_node == start.AnchorNode()
                           ? start.ComputeOffsetInContainerNode()
                           : 0;
    int end_offset = text_node == end.AnchorNode()
                         ? end.ComputeOffsetInContainerNode()
                         : static_cast<int>(text_node->length());
    DeleteInsignificantText(text_node, start_offset, end_offset);
  }
}

void CompositeEditCommand::DeleteInsignificantTextDownstream(
    const Position& pos) {
  DCHECK(!GetDocument().NeedsLayoutTreeUpdate());
  Position end = MostForwardCaretPosition(
      NextPositionOf(CreateVisiblePosition(pos)).DeepEquivalent());
  DeleteInsignificantText(pos, end);
}

HTMLBRElement* CompositeEditCommand::AppendBlockPlaceholder(
    Element* container,
    EditingState* editing_state) {
  if (!container)
    return nullptr;

  GetDocument().UpdateStyleAndLayout();

  // Should assert isLayoutBlockFlow || isInlineFlow when deletion improves. See
  // 4244964.
  DCHECK(container->GetLayoutObject()) << container;

  auto* placeholder = MakeGarbageCollected<HTMLBRElement>(GetDocument());
  AppendNode(placeholder, container, editing_state);
  if (editing_state->IsAborted())
    return nullptr;
  return placeholder;
}

HTMLBRElement* CompositeEditCommand::InsertBlockPlaceholder(
    const Position& pos,
    EditingState* editing_state) {
  if (pos.IsNull())
    return nullptr;

  // Should assert isLayoutBlockFlow || isInlineFlow when deletion improves. See
  // 4244964.
  DCHECK(pos.AnchorNode()->GetLayoutObject()) << pos;

  auto* placeholder = MakeGarbageCollected<HTMLBRElement>(GetDocument());
  InsertNodeAt(placeholder, pos, editing_state);
  if (editing_state->IsAborted())
    return nullptr;
  return placeholder;
}

HTMLBRElement* CompositeEditCommand::AddBlockPlaceholderIfNeeded(
    Element* container,
    EditingState* editing_state) {
  if (!container)
    return nullptr;

  GetDocument().UpdateStyleAndLayout();

  auto* block = DynamicTo<LayoutBlockFlow>(container->GetLayoutObject());
  if (!block)
    return nullptr;

  // append the placeholder to make sure it follows
  // any unrendered blocks
  if (block->Size().Height() == 0 ||
      (block->IsListItem() && ToLayoutListItem(block)->IsEmpty()))
    return AppendBlockPlaceholder(container, editing_state);

  return nullptr;
}

// Assumes that the position is at a placeholder and does the removal without
// much checking.
void CompositeEditCommand::RemovePlaceholderAt(const Position& p) {
  DCHECK(LineBreakExistsAtPosition(p)) << p;

  // We are certain that the position is at a line break, but it may be a br or
  // a preserved newline.
  if (IsHTMLBRElement(*p.AnchorNode())) {
    // Removing a BR element won't dispatch synchronous events.
    RemoveNode(p.AnchorNode(), ASSERT_NO_EDITING_ABORT);
    return;
  }

  DeleteTextFromNode(To<Text>(p.AnchorNode()), p.OffsetInContainerNode(), 1);
}

HTMLElement* CompositeEditCommand::InsertNewDefaultParagraphElementAt(
    const Position& position,
    EditingState* editing_state) {
  HTMLElement* paragraph_element = CreateDefaultParagraphElement(GetDocument());
  paragraph_element->AppendChild(
      MakeGarbageCollected<HTMLBRElement>(GetDocument()));
  InsertNodeAt(paragraph_element, position, editing_state);
  if (editing_state->IsAborted())
    return nullptr;
  return paragraph_element;
}

// If the paragraph is not entirely within it's own block, create one and move
// the paragraph into it, and return that block.  Otherwise return 0.
HTMLElement* CompositeEditCommand::MoveParagraphContentsToNewBlockIfNecessary(
    const Position& pos,
    EditingState* editing_state) {
  DCHECK(!GetDocument().NeedsLayoutTreeUpdate());
  DCHECK(IsEditablePosition(pos)) << pos;

  // It's strange that this function is responsible for verifying that pos has
  // not been invalidated by an earlier call to this function.  The caller,
  // applyBlockStyle, should do this.
  VisiblePosition visible_pos = CreateVisiblePosition(pos);
  VisiblePosition visible_paragraph_start = StartOfParagraph(visible_pos);
  VisiblePosition visible_paragraph_end = EndOfParagraph(visible_pos);
  VisiblePosition next = NextPositionOf(visible_paragraph_end);
  VisiblePosition visible_end = next.IsNotNull() ? next : visible_paragraph_end;

  Position upstream_start =
      MostBackwardCaretPosition(visible_paragraph_start.DeepEquivalent());
  Position upstream_end =
      MostBackwardCaretPosition(visible_end.DeepEquivalent());

  // If there are no VisiblePositions in the same block as pos then
  // upstreamStart will be outside the paragraph
  if (ComparePositions(pos, upstream_start) < 0)
    return nullptr;

  // Perform some checks to see if we need to perform work in this function.
  if (IsEnclosingBlock(upstream_start.AnchorNode())) {
    // If the block is the root editable element, always move content to a new
    // block, since it is illegal to modify attributes on the root editable
    // element for editing.
    if (upstream_start.AnchorNode() == RootEditableElementOf(upstream_start)) {
      // If the block is the root editable element and it contains no visible
      // content, create a new block but don't try and move content into it,
      // since there's nothing for moveParagraphs to move.
      if (!HasRenderedNonAnonymousDescendantsWithHeight(
              upstream_start.AnchorNode()->GetLayoutObject()))
        return InsertNewDefaultParagraphElementAt(upstream_start,
                                                  editing_state);
    } else if (IsEnclosingBlock(upstream_end.AnchorNode())) {
      if (!upstream_end.AnchorNode()->IsDescendantOf(
              upstream_start.AnchorNode())) {
        // If the paragraph end is a descendant of paragraph start, then we need
        // to run the rest of this function. If not, we can bail here.
        return nullptr;
      }
    } else if (EnclosingBlock(upstream_end.AnchorNode()) !=
               upstream_start.AnchorNode()) {
      // It should be an ancestor of the paragraph start.
      // We can bail as we have a full block to work with.
      return nullptr;
    } else if (IsEndOfEditableOrNonEditableContent(visible_end)) {
      // At the end of the editable region. We can bail here as well.
      return nullptr;
    }
  }

  if (visible_paragraph_end.IsNull())
    return nullptr;

  HTMLElement* const new_block =
      InsertNewDefaultParagraphElementAt(upstream_start, editing_state);
  if (editing_state->IsAborted())
    return nullptr;
  DCHECK(new_block);

  bool end_was_br =
      IsHTMLBRElement(*visible_paragraph_end.DeepEquivalent().AnchorNode());

  // Inserting default paragraph element can change visible position. We
  // should update visible positions before use them.
  GetDocument().UpdateStyleAndLayout();
  const VisiblePosition& destination =
      VisiblePosition::FirstPositionInNode(*new_block);
  if (destination.IsNull()) {
    // Reached by CompositeEditingCommandTest
    //    .MoveParagraphContentsToNewBlockWithNonEditableStyle.
    editing_state->Abort();
    return nullptr;
  }

  visible_pos = CreateVisiblePosition(pos);
  visible_paragraph_start = StartOfParagraph(visible_pos);
  visible_paragraph_end = EndOfParagraph(visible_pos);
  MoveParagraphs(visible_paragraph_start, visible_paragraph_end, destination,
                 editing_state);
  if (editing_state->IsAborted())
    return nullptr;

  if (new_block->lastChild() && IsHTMLBRElement(*new_block->lastChild()) &&
      !end_was_br) {
    RemoveNode(new_block->lastChild(), editing_state);
    if (editing_state->IsAborted())
      return nullptr;
  }

  return new_block;
}

void CompositeEditCommand::PushAnchorElementDown(Element* anchor_node,
                                                 EditingState* editing_state) {
  if (!anchor_node)
    return;

  DCHECK(anchor_node->IsLink()) << anchor_node;

  const VisibleSelection& visible_selection = CreateVisibleSelection(
      SelectionInDOMTree::Builder().SelectAllChildren(*anchor_node).Build());
  SetEndingSelection(
      SelectionForUndoStep::From(visible_selection.AsSelection()));
  ApplyStyledElement(anchor_node, editing_state);
  if (editing_state->IsAborted())
    return;
  // Clones of anchorNode have been pushed down, now remove it.
  if (anchor_node->isConnected())
    RemoveNodePreservingChildren(anchor_node, editing_state);
}

// Clone the paragraph between start and end under blockElement,
// preserving the hierarchy up to outerNode.

void CompositeEditCommand::CloneParagraphUnderNewElement(
    const Position& start,
    const Position& end,
    Node* passed_outer_node,
    Element* block_element,
    EditingState* editing_state) {
  DCHECK_LE(start, end);
  DCHECK(passed_outer_node);
  DCHECK(block_element);

  // First we clone the outerNode
  Node* last_node = nullptr;
  Node* outer_node = passed_outer_node;

  if (IsRootEditableElement(*outer_node)) {
    last_node = block_element;
  } else {
    last_node = outer_node->cloneNode(IsDisplayInsideTable(outer_node));
    AppendNode(last_node, block_element, editing_state);
    if (editing_state->IsAborted())
      return;
  }

  if (start.AnchorNode() != outer_node && last_node->IsElementNode() &&
      start.AnchorNode()->IsDescendantOf(outer_node)) {
    HeapVector<Member<Node>> ancestors;

    // Insert each node from innerNode to outerNode (excluded) in a list.
    for (Node& runner :
         NodeTraversal::InclusiveAncestorsOf(*start.AnchorNode())) {
      if (runner == outer_node)
        break;
      ancestors.push_back(runner);
    }

    // Clone every node between start.anchorNode() and outerBlock.

    for (wtf_size_t i = ancestors.size(); i != 0; --i) {
      Node* item = ancestors[i - 1].Get();
      Node* child = item->cloneNode(IsDisplayInsideTable(item));
      AppendNode(child, To<Element>(last_node), editing_state);
      if (editing_state->IsAborted())
        return;
      last_node = child;
    }
  }

  // Scripts specified in javascript protocol may remove |outerNode|
  // during insertion, e.g. <iframe src="javascript:...">
  if (!outer_node->isConnected())
    return;

  // Handle the case of paragraphs with more than one node,
  // cloning all the siblings until end.anchorNode() is reached.

  if (start.AnchorNode() != end.AnchorNode() &&
      !start.AnchorNode()->IsDescendantOf(end.AnchorNode())) {
    // If end is not a descendant of outerNode we need to
    // find the first common ancestor to increase the scope
    // of our nextSibling traversal.
    while (outer_node && !end.AnchorNode()->IsDescendantOf(outer_node)) {
      outer_node = outer_node->parentNode();
    }

    if (!outer_node)
      return;

    Node* start_node = start.AnchorNode();
    for (Node* node =
             NodeTraversal::NextSkippingChildren(*start_node, outer_node);
         node; node = NodeTraversal::NextSkippingChildren(*node, outer_node)) {
      // Move lastNode up in the tree as much as node was moved up in the tree
      // by NodeTraversal::nextSkippingChildren, so that the relative depth
      // between node and the original start node is maintained in the clone.
      while (start_node && last_node &&
             start_node->parentNode() != node->parentNode()) {
        start_node = start_node->parentNode();
        last_node = last_node->parentNode();
      }

      if (!last_node || !last_node->parentNode())
        return;

      Node* cloned_node = node->cloneNode(true);
      InsertNodeAfter(cloned_node, last_node, editing_state);
      if (editing_state->IsAborted())
        return;
      last_node = cloned_node;
      if (node == end.AnchorNode() || end.AnchorNode()->IsDescendantOf(node))
        break;
    }
  }
}

// There are bugs in deletion when it removes a fully selected table/list.
// It expands and removes the entire table/list, but will let content
// before and after the table/list collapse onto one line.
// Deleting a paragraph will leave a placeholder. Remove it (and prune
// empty or unrendered parents).

void CompositeEditCommand::CleanupAfterDeletion(EditingState* editing_state) {
  CleanupAfterDeletion(editing_state, VisiblePosition());
}

void CompositeEditCommand::CleanupAfterDeletion(EditingState* editing_state,
                                                VisiblePosition destination) {
  GetDocument().UpdateStyleAndLayout();

  VisiblePosition caret_after_delete = EndingVisibleSelection().VisibleStart();
  Node* destination_node = destination.DeepEquivalent().AnchorNode();
  if (caret_after_delete.DeepEquivalent() != destination.DeepEquivalent() &&
      IsStartOfParagraph(caret_after_delete) &&
      IsEndOfParagraph(caret_after_delete)) {
    // Note: We want the rightmost candidate.
    Position position =
        MostForwardCaretPosition(caret_after_delete.DeepEquivalent());
    Node* node = position.AnchorNode();

    // InsertListCommandTest.CleanupNodeSameAsDestinationNode reaches here.
    ABORT_EDITING_COMMAND_IF(destination_node == node);
    // Bail if we'd remove an ancestor of our destination.
    if (destination_node && destination_node->IsDescendantOf(node))
      return;

    // Normally deletion will leave a br as a placeholder.
    if (IsHTMLBRElement(*node)) {
      RemoveNodeAndPruneAncestors(node, editing_state, destination_node);

      // If the selection to move was empty and in an empty block that
      // doesn't require a placeholder to prop itself open (like a bordered
      // div or an li), remove it during the move (the list removal code
      // expects this behavior).
    } else if (IsEnclosingBlock(node)) {
      // If caret position after deletion and destination position coincides,
      // node should not be removed.
      if (!RendersInDifferentPosition(position, destination.DeepEquivalent())) {
        Prune(node, editing_state, destination_node);
        return;
      }
      RemoveNodeAndPruneAncestors(node, editing_state, destination_node);
    } else if (LineBreakExistsAtPosition(position)) {
      // There is a preserved '\n' at caretAfterDelete.
      // We can safely assume this is a text node.
      auto* text_node = To<Text>(node);
      if (text_node->length() == 1)
        RemoveNodeAndPruneAncestors(node, editing_state, destination_node);
      else
        DeleteTextFromNode(text_node, position.ComputeOffsetInContainerNode(),
                           1);
    }
  }
}

// This is a version of moveParagraph that preserves style by keeping the
// original markup. It is currently used only by IndentOutdentCommand but it is
// meant to be used in the future by several other commands such as InsertList
// and the align commands.
// The blockElement parameter is the element to move the paragraph to, outerNode
// is the top element of the paragraph hierarchy.

void CompositeEditCommand::MoveParagraphWithClones(
    const VisiblePosition& start_of_paragraph_to_move,
    const VisiblePosition& end_of_paragraph_to_move,
    HTMLElement* block_element,
    Node* outer_node,
    EditingState* editing_state) {
  // InsertListCommandTest.InsertListWithCollapsedVisibility reaches here.
  ABORT_EDITING_COMMAND_IF(start_of_paragraph_to_move.IsNull());
  ABORT_EDITING_COMMAND_IF(end_of_paragraph_to_move.IsNull());
  DCHECK(outer_node);
  DCHECK(block_element);

  RelocatablePosition relocatable_before_paragraph(
      PreviousPositionOf(start_of_paragraph_to_move).DeepEquivalent());
  RelocatablePosition relocatable_after_paragraph(
      NextPositionOf(end_of_paragraph_to_move).DeepEquivalent());

  // We upstream() the end and downstream() the start so that we don't include
  // collapsed whitespace in the move. When we paste a fragment, spaces after
  // the end and before the start are treated as though they were rendered.
  Position start =
      MostForwardCaretPosition(start_of_paragraph_to_move.DeepEquivalent());
  Position end = start_of_paragraph_to_move.DeepEquivalent() ==
                         end_of_paragraph_to_move.DeepEquivalent()
                     ? start
                     : MostBackwardCaretPosition(
                           end_of_paragraph_to_move.DeepEquivalent());
  if (ComparePositions(start, end) > 0)
    end = start;

  CloneParagraphUnderNewElement(start, end, outer_node, block_element,
                                editing_state);

  SetEndingSelection(SelectionForUndoStep::From(
      SelectionInDOMTree::Builder().Collapse(start).Extend(end).Build()));
  if (!DeleteSelection(
          editing_state,
          DeleteSelectionOptions::Builder().SetSanitizeMarkup(true).Build()))
    return;

  // There are bugs in deletion when it removes a fully selected table/list.
  // It expands and removes the entire table/list, but will let content
  // before and after the table/list collapse onto one line.

  CleanupAfterDeletion(editing_state);
  if (editing_state->IsAborted())
    return;

  GetDocument().UpdateStyleAndLayout();

  // Add a br if pruning an empty block level element caused a collapse.  For
  // example:
  // foo^
  // <div>bar</div>
  // baz
  // Imagine moving 'bar' to ^.  'bar' will be deleted and its div pruned.  That
  // would cause 'baz' to collapse onto the line with 'foobar' unless we insert
  // a br. Must recononicalize these two VisiblePositions after the pruning
  // above.
  const VisiblePosition& before_paragraph =
      CreateVisiblePosition(relocatable_before_paragraph.GetPosition());
  const VisiblePosition& after_paragraph =
      CreateVisiblePosition(relocatable_after_paragraph.GetPosition());

  if (before_paragraph.IsNotNull() &&
      !IsDisplayInsideTable(before_paragraph.DeepEquivalent().AnchorNode()) &&
      ((!IsEndOfParagraph(before_paragraph) &&
        !IsStartOfParagraph(before_paragraph)) ||
       before_paragraph.DeepEquivalent() == after_paragraph.DeepEquivalent())) {
    // FIXME: Trim text between beforeParagraph and afterParagraph if they
    // aren't equal.
    InsertNodeAt(MakeGarbageCollected<HTMLBRElement>(GetDocument()),
                 before_paragraph.DeepEquivalent(), editing_state);
  }
}

void CompositeEditCommand::MoveParagraph(
    const VisiblePosition& start_of_paragraph_to_move,
    const VisiblePosition& end_of_paragraph_to_move,
    const VisiblePosition& destination,
    EditingState* editing_state,
    ShouldPreserveSelection should_preserve_selection,
    ShouldPreserveStyle should_preserve_style,
    Node* constraining_ancestor) {
  DCHECK(!GetDocument().NeedsLayoutTreeUpdate());
  DCHECK(IsStartOfParagraph(start_of_paragraph_to_move))
      << start_of_paragraph_to_move;
  DCHECK(IsEndOfParagraph(end_of_paragraph_to_move))
      << end_of_paragraph_to_move;
  MoveParagraphs(start_of_paragraph_to_move, end_of_paragraph_to_move,
                 destination, editing_state, should_preserve_selection,
                 should_preserve_style, constraining_ancestor);
}

void CompositeEditCommand::MoveParagraphs(
    const VisiblePosition& start_of_paragraph_to_move,
    const VisiblePosition& end_of_paragraph_to_move,
    const VisiblePosition& destination,
    EditingState* editing_state,
    ShouldPreserveSelection should_preserve_selection,
    ShouldPreserveStyle should_preserve_style,
    Node* constraining_ancestor) {
  DCHECK(!GetDocument().NeedsLayoutTreeUpdate());
  DCHECK(start_of_paragraph_to_move.IsNotNull());
  DCHECK(end_of_paragraph_to_move.IsNotNull());
  DCHECK(destination.IsNotNull());

  if (start_of_paragraph_to_move.DeepEquivalent() ==
          destination.DeepEquivalent() ||
      start_of_paragraph_to_move.IsNull())
    return;

  // Can't move the range to a destination inside itself.
  if (destination.DeepEquivalent() >=
          start_of_paragraph_to_move.DeepEquivalent() &&
      destination.DeepEquivalent() <=
          end_of_paragraph_to_move.DeepEquivalent()) {
    // Reached by unit test TypingCommandTest.insertLineBreakWithIllFormedHTML
    // and ApplyStyleCommandTest.JustifyRightDetachesDestination
    editing_state->Abort();
    return;
  }

  int start_index = -1;
  int end_index = -1;
  int destination_index = -1;
  if (should_preserve_selection == kPreserveSelection &&
      !EndingSelection().IsNone()) {
    VisiblePosition visible_start = EndingVisibleSelection().VisibleStart();
    VisiblePosition visible_end = EndingVisibleSelection().VisibleEnd();

    bool start_after_paragraph =
        ComparePositions(visible_start, end_of_paragraph_to_move) > 0;
    bool end_before_paragraph =
        ComparePositions(visible_end, start_of_paragraph_to_move) < 0;

    if (!start_after_paragraph && !end_before_paragraph) {
      bool start_in_paragraph =
          ComparePositions(visible_start, start_of_paragraph_to_move) >= 0;
      bool end_in_paragraph =
          ComparePositions(visible_end, end_of_paragraph_to_move) <= 0;

      const TextIteratorBehavior behavior =
          TextIteratorBehavior::AllVisiblePositionsRangeLengthBehavior();

      start_index = 0;
      if (start_in_paragraph) {
        start_index = TextIterator::RangeLength(
            start_of_paragraph_to_move.ToParentAnchoredPosition(),
            visible_start.ToParentAnchoredPosition(), behavior);
      }

      end_index = 0;
      if (end_in_paragraph) {
        end_index = TextIterator::RangeLength(
            start_of_paragraph_to_move.ToParentAnchoredPosition(),
            visible_end.ToParentAnchoredPosition(), behavior);
      }
    }
  }

  RelocatablePosition before_paragraph_position(
      PreviousPositionOf(start_of_paragraph_to_move,
                         kCannotCrossEditingBoundary)
          .DeepEquivalent());
  RelocatablePosition after_paragraph_position(
      NextPositionOf(end_of_paragraph_to_move, kCannotCrossEditingBoundary)
          .DeepEquivalent());

  // We upstream() the end and downstream() the start so that we don't include
  // collapsed whitespace in the move. When we paste a fragment, spaces after
  // the end and before the start are treated as though they were rendered.
  Position start =
      MostForwardCaretPosition(start_of_paragraph_to_move.DeepEquivalent());
  Position end =
      MostBackwardCaretPosition(end_of_paragraph_to_move.DeepEquivalent());

  // FIXME: This is an inefficient way to preserve style on nodes in the
  // paragraph to move. It shouldn't matter though, since moved paragraphs will
  // usually be quite small.
  DocumentFragment* fragment =
      start_of_paragraph_to_move.DeepEquivalent() !=
              end_of_paragraph_to_move.DeepEquivalent()
          ? CreateFragmentFromMarkup(
                GetDocument(),
                CreateMarkup(start.ParentAnchoredEquivalent(),
                             end.ParentAnchoredEquivalent(),
                             kDoNotAnnotateForInterchange,
                             ConvertBlocksToInlines::kConvert,
                             kDoNotResolveURLs, constraining_ancestor),
                "", kDisallowScriptingAndPluginContent)
          : nullptr;

  // A non-empty paragraph's style is moved when we copy and move it.  We don't
  // move anything if we're given an empty paragraph, but an empty paragraph can
  // have style too, <div><b><br></b></div> for example.  Save it so that we can
  // preserve it later.
  EditingStyle* style_in_empty_paragraph = nullptr;
  if (start_of_paragraph_to_move.DeepEquivalent() ==
          end_of_paragraph_to_move.DeepEquivalent() &&
      should_preserve_style == kPreserveStyle) {
    style_in_empty_paragraph = MakeGarbageCollected<EditingStyle>(
        start_of_paragraph_to_move.DeepEquivalent());
    style_in_empty_paragraph->MergeTypingStyle(&GetDocument());
    // The moved paragraph should assume the block style of the destination.
    style_in_empty_paragraph->RemoveBlockProperties();
  }

  // FIXME (5098931): We should add a new insert action
  // "WebViewInsertActionMoved" and call shouldInsertFragment here.

  DCHECK(!GetDocument().NeedsLayoutTreeUpdate());

  const VisibleSelection& selection_to_delete = CreateVisibleSelection(
      SelectionInDOMTree::Builder().Collapse(start).Extend(end).Build());
  SetEndingSelection(
      SelectionForUndoStep::From(selection_to_delete.AsSelection()));
  if (!DeleteSelection(
          editing_state,
          DeleteSelectionOptions::Builder().SetSanitizeMarkup(true).Build()))
    return;

  DCHECK(destination.DeepEquivalent().IsConnected()) << destination;
  CleanupAfterDeletion(editing_state, destination);
  if (editing_state->IsAborted())
    return;
  DCHECK(destination.DeepEquivalent().IsConnected()) << destination;

  GetDocument().UpdateStyleAndLayout();

  // Add a br if pruning an empty block level element caused a collapse. For
  // example:
  // foo^
  // <div>bar</div>
  // baz
  // Imagine moving 'bar' to ^. 'bar' will be deleted and its div pruned. That
  // would cause 'baz' to collapse onto the line with 'foobar' unless we insert
  // a br. Must recononicalize these two VisiblePositions after the pruning
  // above.
  VisiblePosition before_paragraph =
      CreateVisiblePosition(before_paragraph_position.GetPosition());
  VisiblePosition after_paragraph =
      CreateVisiblePosition(after_paragraph_position.GetPosition());
  if (before_paragraph.IsNotNull() &&
      ((!IsStartOfParagraph(before_paragraph) &&
        !IsEndOfParagraph(before_paragraph)) ||
       before_paragraph.DeepEquivalent() == after_paragraph.DeepEquivalent())) {
    // FIXME: Trim text between beforeParagraph and afterParagraph if they
    // aren't equal.
    InsertNodeAt(MakeGarbageCollected<HTMLBRElement>(GetDocument()),
                 before_paragraph.DeepEquivalent(), editing_state);
    if (editing_state->IsAborted())
      return;
  }

  // TextIterator::rangeLength requires clean layout.
  GetDocument().UpdateStyleAndLayout();

  destination_index = TextIterator::RangeLength(
      Position::FirstPositionInNode(*GetDocument().documentElement()),
      destination.ToParentAnchoredPosition(),
      TextIteratorBehavior::AllVisiblePositionsRangeLengthBehavior());

  const VisibleSelection& destination_selection =
      CreateVisibleSelection(SelectionInDOMTree::Builder()
                                 .Collapse(destination.ToPositionWithAffinity())
                                 .Build());
  if (EndingSelection().IsNone()) {
    // We abort executing command since |destination| becomes invisible.
    editing_state->Abort();
    return;
  }
  SetEndingSelection(
      SelectionForUndoStep::From(destination_selection.AsSelection()));
  ReplaceSelectionCommand::CommandOptions options =
      ReplaceSelectionCommand::kSelectReplacement |
      ReplaceSelectionCommand::kMovingParagraph;
  if (should_preserve_style == kDoNotPreserveStyle)
    options |= ReplaceSelectionCommand::kMatchStyle;
  ApplyCommandToComposite(MakeGarbageCollected<ReplaceSelectionCommand>(
                              GetDocument(), fragment, options),
                          editing_state);
  if (editing_state->IsAborted())
    return;
  ABORT_EDITING_COMMAND_IF(!EndingSelection().IsValidFor(GetDocument()));

  GetDocument().UpdateStyleAndLayout();

  // If the selection is in an empty paragraph, restore styles from the old
  // empty paragraph to the new empty paragraph.
  bool selection_is_empty_paragraph =
      EndingSelection().IsCaret() &&
      IsStartOfParagraph(EndingVisibleSelection().VisibleStart()) &&
      IsEndOfParagraph(EndingVisibleSelection().VisibleStart());
  if (style_in_empty_paragraph && selection_is_empty_paragraph) {
    ApplyStyle(style_in_empty_paragraph, editing_state);
    if (editing_state->IsAborted())
      return;
  }

  if (should_preserve_selection == kDoNotPreserveSelection || start_index == -1)
    return;
  Element* document_element = GetDocument().documentElement();
  if (!document_element)
    return;

  // We need clean layout in order to compute plain-text ranges below.
  GetDocument().UpdateStyleAndLayout();

  // Fragment creation (using createMarkup) incorrectly uses regular spaces
  // instead of nbsps for some spaces that were rendered (11475), which causes
  // spaces to be collapsed during the move operation. This results in a call
  // to rangeFromLocationAndLength with a location past the end of the
  // document (which will return null).
  EphemeralRange start_range = PlainTextRange(destination_index + start_index)
                                   .CreateRangeForSelection(*document_element);
  if (start_range.IsNull())
    return;
  EphemeralRange end_range = PlainTextRange(destination_index + end_index)
                                 .CreateRangeForSelection(*document_element);
  if (end_range.IsNull())
    return;
  const VisibleSelection& visible_selection =
      CreateVisibleSelection(SelectionInDOMTree::Builder()
                                 .Collapse(start_range.StartPosition())
                                 .Extend(end_range.StartPosition())
                                 .Build());
  SetEndingSelection(
      SelectionForUndoStep::From(visible_selection.AsSelection()));
}

// FIXME: Send an appropriate shouldDeleteRange call.
bool CompositeEditCommand::BreakOutOfEmptyListItem(
    EditingState* editing_state) {
  DCHECK(!GetDocument().NeedsLayoutTreeUpdate());
  Node* empty_list_item =
      EnclosingEmptyListItem(EndingVisibleSelection().VisibleStart());
  if (!empty_list_item)
    return false;

  EditingStyle* style =
      MakeGarbageCollected<EditingStyle>(EndingSelection().Start());
  style->MergeTypingStyle(&GetDocument());

  ContainerNode* list_node = empty_list_item->parentNode();
  // FIXME: Can't we do something better when the immediate parent wasn't a list
  // node?
  if (!list_node ||
      (!IsHTMLUListElement(*list_node) && !IsHTMLOListElement(*list_node)) ||
      !HasEditableStyle(*list_node) ||
      list_node == RootEditableElement(*empty_list_item))
    return false;

  HTMLElement* new_block = nullptr;
  if (ContainerNode* block_enclosing_list = list_node->parentNode()) {
    if (IsHTMLLIElement(
            *block_enclosing_list)) {  // listNode is inside another list item
      if (CreateVisiblePosition(PositionAfterNode(*block_enclosing_list))
              .DeepEquivalent() ==
          CreateVisiblePosition(PositionAfterNode(*list_node))
              .DeepEquivalent()) {
        // If listNode appears at the end of the outer list item, then move
        // listNode outside of this list item, e.g.
        //   <ul><li>hello <ul><li><br></li></ul> </li></ul>
        // should become
        //   <ul><li>hello</li> <ul><li><br></li></ul> </ul>
        // after this section.
        //
        // If listNode does NOT appear at the end, then we should consider it as
        // a regular paragraph, e.g.
        //   <ul><li> <ul><li><br></li></ul> hello</li></ul>
        // should become
        //   <ul><li> <div><br></div> hello</li></ul>
        // at the end
        SplitElement(To<Element>(block_enclosing_list), list_node);
        RemoveNodePreservingChildren(list_node->parentNode(), editing_state);
        if (editing_state->IsAborted())
          return false;
        new_block = MakeGarbageCollected<HTMLLIElement>(GetDocument());
      }
      // If listNode does NOT appear at the end of the outer list item, then
      // behave as if in a regular paragraph.
    } else if (IsHTMLOListElement(*block_enclosing_list) ||
               IsHTMLUListElement(*block_enclosing_list)) {
      new_block = MakeGarbageCollected<HTMLLIElement>(GetDocument());
    }
  }
  if (!new_block)
    new_block = CreateDefaultParagraphElement(GetDocument());

  Node* previous_list_node =
      empty_list_item->IsElementNode()
          ? ElementTraversal::PreviousSibling(*empty_list_item)
          : empty_list_item->previousSibling();
  Node* next_list_node = empty_list_item->IsElementNode()
                             ? ElementTraversal::NextSibling(*empty_list_item)
                             : empty_list_item->nextSibling();
  if (IsListItem(next_list_node) || IsHTMLListElement(next_list_node)) {
    // If emptyListItem follows another list item or nested list, split the list
    // node.
    if (IsListItem(previous_list_node) || IsHTMLListElement(previous_list_node))
      SplitElement(To<Element>(list_node), empty_list_item);

    // If emptyListItem is followed by other list item or nested list, then
    // insert newBlock before the list node. Because we have splitted the
    // element, emptyListItem is the first element in the list node.
    // i.e. insert newBlock before ul or ol whose first element is emptyListItem
    InsertNodeBefore(new_block, list_node, editing_state);
    if (editing_state->IsAborted())
      return false;
    RemoveNode(empty_list_item, editing_state);
    if (editing_state->IsAborted())
      return false;
  } else {
    // When emptyListItem does not follow any list item or nested list, insert
    // newBlock after the enclosing list node. Remove the enclosing node if
    // emptyListItem is the only child; otherwise just remove emptyListItem.
    InsertNodeAfter(new_block, list_node, editing_state);
    if (editing_state->IsAborted())
      return false;
    RemoveNode(
        IsListItem(previous_list_node) || IsHTMLListElement(previous_list_node)
            ? empty_list_item
            : list_node,
        editing_state);
    if (editing_state->IsAborted())
      return false;
  }

  AppendBlockPlaceholder(new_block, editing_state);
  if (editing_state->IsAborted())
    return false;

  SetEndingSelection(SelectionForUndoStep::From(
      SelectionInDOMTree::Builder()
          .Collapse(Position::FirstPositionInNode(*new_block))
          .Build()));

  style->PrepareToApplyAt(EndingSelection().Start());
  if (!style->IsEmpty()) {
    ApplyStyle(style, editing_state);
    if (editing_state->IsAborted())
      return false;
  }

  return true;
}

// If the caret is in an empty quoted paragraph, and either there is nothing
// before that paragraph, or what is before is unquoted, and the user presses
// delete, unquote that paragraph.
bool CompositeEditCommand::BreakOutOfEmptyMailBlockquotedParagraph(
    EditingState* editing_state) {
  if (!EndingSelection().IsCaret())
    return false;

  GetDocument().UpdateStyleAndLayout();

  VisiblePosition caret = EndingVisibleSelection().VisibleStart();
  HTMLQuoteElement* highest_blockquote =
      ToHTMLQuoteElement(HighestEnclosingNodeOfType(
          caret.DeepEquivalent(), &IsMailHTMLBlockquoteElement));
  if (!highest_blockquote)
    return false;

  if (!IsStartOfParagraph(caret) || !IsEndOfParagraph(caret))
    return false;

  VisiblePosition previous =
      PreviousPositionOf(caret, kCannotCrossEditingBoundary);
  // Only move forward if there's nothing before the caret, or if there's
  // unquoted content before it.
  if (EnclosingNodeOfType(previous.DeepEquivalent(),
                          &IsMailHTMLBlockquoteElement))
    return false;

  auto* br = MakeGarbageCollected<HTMLBRElement>(GetDocument());
  // We want to replace this quoted paragraph with an unquoted one, so insert a
  // br to hold the caret before the highest blockquote.
  InsertNodeBefore(br, highest_blockquote, editing_state);
  if (editing_state->IsAborted())
    return false;

  GetDocument().UpdateStyleAndLayout();

  VisiblePosition at_br = VisiblePosition::BeforeNode(*br);
  // If the br we inserted collapsed, for example:
  //   foo<br><blockquote>...</blockquote>
  // insert a second one.
  if (!IsStartOfParagraph(at_br)) {
    InsertNodeBefore(MakeGarbageCollected<HTMLBRElement>(GetDocument()), br,
                     editing_state);
    if (editing_state->IsAborted())
      return false;
    GetDocument().UpdateStyleAndLayout();
  }
  SetEndingSelection(SelectionForUndoStep::From(
      SelectionInDOMTree::Builder()
          .Collapse(at_br.ToPositionWithAffinity())
          .Build()));

  // If this is an empty paragraph there must be a line break here.
  if (!LineBreakExistsAtVisiblePosition(caret))
    return false;

  Position caret_pos(MostForwardCaretPosition(caret.DeepEquivalent()));
  // A line break is either a br or a preserved newline.
  DCHECK(
      IsHTMLBRElement(caret_pos.AnchorNode()) ||
      (caret_pos.AnchorNode()->IsTextNode() &&
       caret_pos.AnchorNode()->GetLayoutObject()->Style()->PreserveNewline()))
      << caret_pos;

  if (IsHTMLBRElement(*caret_pos.AnchorNode())) {
    RemoveNodeAndPruneAncestors(caret_pos.AnchorNode(), editing_state);
    if (editing_state->IsAborted())
      return false;
  } else if (auto* text_node = DynamicTo<Text>(caret_pos.AnchorNode())) {
    DCHECK_EQ(caret_pos.ComputeOffsetInContainerNode(), 0);
    ContainerNode* parent_node = text_node->parentNode();
    // The preserved newline must be the first thing in the node, since
    // otherwise the previous paragraph would be quoted, and we verified that it
    // wasn't above.
    DeleteTextFromNode(text_node, 0, 1);
    Prune(parent_node, editing_state);
    if (editing_state->IsAborted())
      return false;
  }

  return true;
}

// Operations use this function to avoid inserting content into an anchor when
// at the start or the end of that anchor, as in NSTextView.
// FIXME: This is only an approximation of NSTextViews insertion behavior, which
// varies depending on how the caret was made.
Position CompositeEditCommand::PositionAvoidingSpecialElementBoundary(
    const Position& original,
    EditingState* editing_state) {
  if (original.IsNull())
    return original;

  GetDocument().UpdateStyleAndLayout();
  VisiblePosition visible_pos = CreateVisiblePosition(original);
  Element* enclosing_anchor = EnclosingAnchorElement(original);
  Position result = original;

  if (!enclosing_anchor)
    return result;

  // Don't avoid block level anchors, because that would insert content into the
  // wrong paragraph.
  if (enclosing_anchor && !IsEnclosingBlock(enclosing_anchor)) {
    VisiblePosition first_in_anchor =
        VisiblePosition::FirstPositionInNode(*enclosing_anchor);
    VisiblePosition last_in_anchor =
        VisiblePosition::LastPositionInNode(*enclosing_anchor);
    // If visually just after the anchor, insert *inside* the anchor unless it's
    // the last VisiblePosition in the document, to match NSTextView.
    if (visible_pos.DeepEquivalent() == last_in_anchor.DeepEquivalent()) {
      // Make sure anchors are pushed down before avoiding them so that we don't
      // also avoid structural elements like lists and blocks (5142012).
      if (original.AnchorNode() != enclosing_anchor &&
          original.AnchorNode()->parentNode() != enclosing_anchor) {
        PushAnchorElementDown(enclosing_anchor, editing_state);
        if (editing_state->IsAborted())
          return original;
        enclosing_anchor = EnclosingAnchorElement(original);
        if (!enclosing_anchor)
          return original;
      }

      GetDocument().UpdateStyleAndLayout();

      // Don't insert outside an anchor if doing so would skip over a line
      // break.  It would probably be safe to move the line break so that we
      // could still avoid the anchor here.
      Position downstream(
          MostForwardCaretPosition(visible_pos.DeepEquivalent()));
      if (LineBreakExistsAtVisiblePosition(visible_pos) &&
          downstream.AnchorNode()->IsDescendantOf(enclosing_anchor))
        return original;

      result = Position::InParentAfterNode(*enclosing_anchor);
    }

    // If visually just before an anchor, insert *outside* the anchor unless
    // it's the first VisiblePosition in a paragraph, to match NSTextView.
    if (visible_pos.DeepEquivalent() == first_in_anchor.DeepEquivalent()) {
      // Make sure anchors are pushed down before avoiding them so that we don't
      // also avoid structural elements like lists and blocks (5142012).
      if (original.AnchorNode() != enclosing_anchor &&
          original.AnchorNode()->parentNode() != enclosing_anchor) {
        PushAnchorElementDown(enclosing_anchor, editing_state);
        if (editing_state->IsAborted())
          return original;
        enclosing_anchor = EnclosingAnchorElement(original);
      }
      if (!enclosing_anchor)
        return original;

      result = Position::InParentBeforeNode(*enclosing_anchor);
    }
  }

  if (result.IsNull() || !RootEditableElementOf(result))
    result = original;

  return result;
}

// Splits the tree parent by parent until we reach the specified ancestor. We
// use VisiblePositions to determine if the split is necessary. Returns the last
// split node.
Node* CompositeEditCommand::SplitTreeToNode(Node* start,
                                            Node* end,
                                            bool should_split_ancestor) {
  DCHECK(start);
  DCHECK(end);
  DCHECK_NE(start, end);

  if (should_split_ancestor && end->parentNode())
    end = end->parentNode();
  if (!start->IsDescendantOf(end))
    return end;

  Node* end_node = end;
  Node* node = nullptr;
  for (node = start; node->parentNode() != end_node;
       node = node->parentNode()) {
    Element* parent_element = node->parentElement();
    if (!parent_element)
      break;

    GetDocument().UpdateStyleAndLayout();

    // Do not split a node when doing so introduces an empty node.
    VisiblePosition position_in_parent =
        VisiblePosition::FirstPositionInNode(*parent_element);
    VisiblePosition position_in_node =
        CreateVisiblePosition(FirstPositionInOrBeforeNode(*node));
    if (position_in_parent.DeepEquivalent() !=
        position_in_node.DeepEquivalent())
      SplitElement(parent_element, node);
  }

  return node;
}

void CompositeEditCommand::SetStartingSelection(
    const SelectionForUndoStep& selection) {
  for (CompositeEditCommand* command = this;; command = command->Parent()) {
    if (UndoStep* undo_step = command->GetUndoStep()) {
      DCHECK(command->IsTopLevelCommand());
      undo_step->SetStartingSelection(selection);
    }
    command->starting_selection_ = selection;
    if (!command->Parent() || command->Parent()->IsFirstCommand(command))
      break;
  }
}

void CompositeEditCommand::SetEndingSelection(
    const SelectionForUndoStep& selection) {
  for (CompositeEditCommand* command = this; command;
       command = command->Parent()) {
    if (UndoStep* undo_step = command->GetUndoStep()) {
      DCHECK(command->IsTopLevelCommand());
      undo_step->SetEndingSelection(selection);
    }
    command->ending_selection_ = selection;
  }
}

void CompositeEditCommand::SetParent(CompositeEditCommand* parent) {
  EditCommand::SetParent(parent);
  if (!parent)
    return;
  starting_selection_ = parent->ending_selection_;
  ending_selection_ = parent->ending_selection_;
}

// Determines whether a node is inside a range or visibly starts and ends at the
// boundaries of the range. Call this function to determine whether a node is
// visibly fit inside selectedRange
bool CompositeEditCommand::IsNodeVisiblyContainedWithin(
    Node& node,
    const EphemeralRange& selected_range) {
  DCHECK(!NeedsLayoutTreeUpdate(node));
  DocumentLifecycle::DisallowTransitionScope disallow_transition(
      node.GetDocument().Lifecycle());

  if (IsNodeFullyContained(selected_range, node))
    return true;

  bool start_is_visually_same =
      CreateVisiblePosition(PositionBeforeNode(node)).DeepEquivalent() ==
      CreateVisiblePosition(selected_range.StartPosition()).DeepEquivalent();
  if (start_is_visually_same &&
      ComparePositions(Position::InParentAfterNode(node),
                       selected_range.EndPosition()) < 0)
    return true;

  bool end_is_visually_same =
      CreateVisiblePosition(PositionAfterNode(node)).DeepEquivalent() ==
      CreateVisiblePosition(selected_range.EndPosition()).DeepEquivalent();
  if (end_is_visually_same &&
      ComparePositions(selected_range.StartPosition(),
                       Position::InParentBeforeNode(node)) < 0)
    return true;

  return start_is_visually_same && end_is_visually_same;
}

void CompositeEditCommand::Trace(Visitor* visitor) {
  visitor->Trace(commands_);
  visitor->Trace(starting_selection_);
  visitor->Trace(ending_selection_);
  visitor->Trace(undo_step_);
  EditCommand::Trace(visitor);
}

void CompositeEditCommand::AppliedEditing() {
  DCHECK(!IsCommandGroupWrapper());
  EventQueueScope scope;

  const UndoStep& undo_step = *GetUndoStep();
  DispatchEditableContentChangedEvents(undo_step.StartingRootEditableElement(),
                                       undo_step.EndingRootEditableElement());
  LocalFrame* const frame = GetDocument().GetFrame();
  Editor& editor = frame->GetEditor();
  // TODO(editing-dev): Filter empty InputType after spec is finalized.
  DispatchInputEventEditableContentChanged(
      undo_step.StartingRootEditableElement(),
      undo_step.EndingRootEditableElement(), GetInputType(),
      TextDataForInputEvent(), IsComposingFromCommand(this));

  const SelectionInDOMTree& new_selection =
      CorrectedSelectionAfterCommand(EndingSelection(), &GetDocument());

  // Don't clear the typing style with this selection change. We do those things
  // elsewhere if necessary.
  ChangeSelectionAfterCommand(frame, new_selection,
                              SetSelectionOptions::Builder()
                                  .SetIsDirectional(SelectionIsDirectional())
                                  .Build());

  if (!PreservesTypingStyle())
    editor.ClearTypingStyle();

  CompositeEditCommand* const last_edit_command = editor.LastEditCommand();
  // Command will be equal to last edit command only in the case of typing
  if (last_edit_command == this) {
    DCHECK(IsTypingCommand());
  } else if (last_edit_command && last_edit_command->IsDragAndDropCommand() &&
             (GetInputType() == InputEvent::InputType::kDeleteByDrag ||
              GetInputType() == InputEvent::InputType::kInsertFromDrop)) {
    // Only register undo entry when combined with other commands.
    if (!last_edit_command->GetUndoStep()) {
      editor.GetUndoStack().RegisterUndoStep(
          last_edit_command->EnsureUndoStep());
    }
    last_edit_command->EnsureUndoStep()->SetEndingSelection(
        EnsureUndoStep()->EndingSelection());
    last_edit_command->GetUndoStep()->SetSelectionIsDirectional(
        GetUndoStep()->SelectionIsDirectional());
    last_edit_command->AppendCommandToUndoStep(this);
  } else {
    // Only register a new undo command if the command passed in is
    // different from the last command
    editor.SetLastEditCommand(this);
    editor.GetUndoStack().RegisterUndoStep(EnsureUndoStep());
  }

  editor.RespondToChangedContents(new_selection.Base());
}

}  // namespace blink