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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;

using Dbg = System.Management.Automation.Diagnostics;
#if !UNIX
using ConsoleHandle = Microsoft.Win32.SafeHandles.SafeFileHandle;
#endif

namespace Microsoft.PowerShell
{
    using PowerShell = System.Management.Automation.PowerShell;

    /// <summary>
    /// ConsoleHostUserInterface implements console-mode user interface for powershell.
    /// </summary>
    [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
    internal partial class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInterface
    {
        /// <summary>
        /// This is the char that is echoed to the console when the input is masked. This not localizable.
        /// </summary>
        private const char PrintToken = '*';

        /// <summary>
        /// Command completion implementation object.
        /// </summary>
        private PowerShell _commandCompletionPowerShell;

        /// <summary>
        /// This is a test hook for programmatically reading and writing ConsoleHost I/O.
        /// </summary>
        private static readonly PSHostUserInterface s_h = null;

        /// <summary>
        /// Return true if the console supports a VT100 like virtual terminal.
        /// </summary>
        public override bool SupportsVirtualTerminal { get; }

        /// <summary>
        /// Constructs an instance.
        /// </summary>
        /// <param name="parent"></param>
        /// <exception/>
        internal ConsoleHostUserInterface(ConsoleHost parent)
        {
            Dbg.Assert(parent != null, "parent may not be null");

            _parent = parent;
            _rawui = new ConsoleHostRawUserInterface(this);
            SupportsVirtualTerminal = true;
            _isInteractiveTestToolListening = false;

            // check if TERM env var is set
            // `dumb` means explicitly don't use VT
            // `xterm-mono` and `xtermm` means support VT, but emit plaintext
            switch (Environment.GetEnvironmentVariable("TERM"))
            {
                case "dumb":
                    SupportsVirtualTerminal = false;
                    break;
                case "xterm-mono":
                case "xtermm":
                    PSStyle.Instance.OutputRendering = OutputRendering.PlainText;
                    break;
                default:
                    break;
            }

            // widely supported by CLI tools via https://no-color.org/
            if (Environment.GetEnvironmentVariable("NO_COLOR") != null)
            {
                PSStyle.Instance.OutputRendering = OutputRendering.PlainText;
            }

            if (SupportsVirtualTerminal)
            {
                SupportsVirtualTerminal = TryTurnOnVirtualTerminal();
            }
        }

        internal bool TryTurnOnVirtualTerminal()
        {
#if UNIX
            return true;
#else
            try
            {
                // Turn on virtual terminal if possible.
                // This might throw - not sure how exactly (no console), but if it does, we shouldn't fail to start.
                var outputHandle = ConsoleControl.GetActiveScreenBufferHandle();
                var outputMode = ConsoleControl.GetMode(outputHandle);

                if (outputMode.HasFlag(ConsoleControl.ConsoleModes.VirtualTerminal))
                {
                    return true;
                }

                outputMode |= ConsoleControl.ConsoleModes.VirtualTerminal;
                if (ConsoleControl.NativeMethods.SetConsoleMode(outputHandle.DangerousGetHandle(), (uint)outputMode))
                {
                    // We only know if vt100 is supported if the previous call actually set the new flag, older
                    // systems ignore the setting.
                    outputMode = ConsoleControl.GetMode(outputHandle);
                    return outputMode.HasFlag(ConsoleControl.ConsoleModes.VirtualTerminal);
                }
            }
            catch
            {
                // Do nothing if failed
            }

            return false;
#endif
        }

        /// <summary>
        /// Supplies an implementation of PSHostRawUserInterface that provides low-level console mode UI facilities.
        /// </summary>
        /// <value></value>
        /// <exception/>
        public override PSHostRawUserInterface RawUI
        {
            get
            {
                Dbg.Assert(_rawui != null, "rawui should have been created by ctor");

                // no locking because this is read-only, and allocated in the ctor.

                return _rawui;
            }
        }

        // deadcode; but could be needed in the future.
        ///// <summary>
        ///// gets the PSHost instance that uses this ConsoleHostUserInterface instance
        ///// </summary>
        ///// <value></value>
        ///// <exception/>

        // internal
        // PSHost
        // Parent
        // {
        //    get
        //    {
        //        using (tracer.TraceProperty())
        //        {
        //            // no locking because this is read-only and set in the ctor.

        //            return parent;
        //        }
        //    }
        // }

        /// <summary>
        /// True if command completion is currently running.
        /// </summary>
        internal bool IsCommandCompletionRunning
        {
            get
            {
                return _commandCompletionPowerShell != null &&
                       _commandCompletionPowerShell.InvocationStateInfo.State == PSInvocationState.Running;
            }
        }

        /// <summary>
        /// True if the Read* functions should read from the stdin stream instead of from the win32 console.
        /// </summary>
        internal bool ReadFromStdin { get; set; }

        /// <summary>
        /// True if the host shouldn't write out prompts.
        /// </summary>
        internal bool NoPrompt { get; set; }

        #region Line-oriented interaction

        /// <summary>
        /// See base class.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="HostException">
        /// If Win32's SetConsoleMode fails
        ///    OR
        ///    Win32's ReadConsole fails
        ///    OR
        ///    obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleCursorPosition failed
        /// </exception>
        public override string ReadLine()
        {
            HandleThrowOnReadAndPrompt();

            // call our internal version such that it does not end input on a tab

            return ReadLine(false, string.Empty, out _, true, true);
        }

        /// <summary>
        /// See base class.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="HostException">
        /// If obtaining a handle to the active screen buffer failed
        ///    OR
        ///    Win32's setting input buffer mode to disregard window and mouse input failed
        ///    OR
        ///    Win32's ReadConsole failed
        /// </exception>
        /// <exception cref="PipelineStoppedException">
        /// If Ctrl-C is entered by user
        /// </exception>
        public override SecureString ReadLineAsSecureString()
        {
            HandleThrowOnReadAndPrompt();

            // we lock here so that multiple threads won't interleave the various reads and writes here.

            object result = null;
            lock (_instanceLock)
            {
                result = ReadLineSafe(true, PrintToken);
            }

            SecureString secureResult = result as SecureString;
            System.Management.Automation.Diagnostics.Assert(secureResult != null, "ReadLineSafe did not return a SecureString");

            return secureResult;
        }

        /// <summary>
        /// Implementation based on NT CredUI's GetPasswdStr.
        /// Use Win32.ReadConsole to construct a SecureString. The advantage of ReadConsole over ReadKey is
        /// Alt-ddd where d is {0-9} is allowed.
        /// It also manages the cursor as keys are entered and "backspaced". However, it is possible that
        /// while this method is running, the console buffer contents could change. Then, its cursor mgmt
        /// will likely be messed up.
        ///
        /// Secondary implementation for Unix based on Console.ReadKey(), where
        /// the advantage is portability through abstraction. Does not support
        /// arrow key movement, but supports backspace.
        /// </summary>
        /// <param name="isSecureString">
        /// True to specify reading a SecureString; false reading a string
        /// </param>
        /// <param name="printToken">
        /// string for output echo
        /// </param>
        /// <returns></returns>
        /// <exception cref="HostException">
        /// If obtaining a handle to the active screen buffer failed
        ///    OR
        ///    Win32's setting input buffer mode to disregard window and mouse input failed
        ///    OR
        ///    Win32's ReadConsole failed
        ///    OR
        ///    obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleCursorPosition failed
        /// </exception>
        /// <exception cref="PipelineStoppedException">
        /// If Ctrl-C is entered by user
        /// </exception>
        private object ReadLineSafe(bool isSecureString, char? printToken)
        {
            // Don't lock (instanceLock) in here -- the caller needs to do that...

            PreRead();
            string printTokenString = printToken.HasValue ?
                printToken.ToString() :
                null;
            SecureString secureResult = new SecureString();
            StringBuilder result = new StringBuilder();
#if UNIX
            bool treatControlCAsInput = Console.TreatControlCAsInput;
#else
            ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle();
            ConsoleControl.ConsoleModes originalMode = ConsoleControl.GetMode(handle);
            bool isModeChanged = true; // assume ConsoleMode is changed so that if ReadLineSetMode
            // fails to return the value correctly, the original mode is
            // restored.
#endif

            try
            {
#if UNIX
                Console.TreatControlCAsInput = true;
#else
                // Ensure that we're in the proper line-input mode.

                const ConsoleControl.ConsoleModes DesiredMode =
                    ConsoleControl.ConsoleModes.Extended |
                    ConsoleControl.ConsoleModes.QuickEdit;

                ConsoleControl.ConsoleModes m = originalMode;
                bool shouldUnsetEchoInput = shouldUnsetMode(ConsoleControl.ConsoleModes.EchoInput, ref m);
                bool shouldUnsetLineInput = shouldUnsetMode(ConsoleControl.ConsoleModes.LineInput, ref m);
                bool shouldUnsetMouseInput = shouldUnsetMode(ConsoleControl.ConsoleModes.MouseInput, ref m);
                bool shouldUnsetProcessInput = shouldUnsetMode(ConsoleControl.ConsoleModes.ProcessedInput, ref m);

                if ((m & DesiredMode) != DesiredMode ||
                    shouldUnsetMouseInput ||
                    shouldUnsetEchoInput ||
                    shouldUnsetLineInput ||
                    shouldUnsetProcessInput)
                {
                    m |= DesiredMode;
                    ConsoleControl.SetMode(handle, m);
                }
                else
                {
                    isModeChanged = false;
                }

                _rawui.ClearKeyCache();
#endif

                Coordinates originalCursorPos = _rawui.CursorPosition;

                //
                // read one char at a time so that we don't
                // end up having a immutable string holding the
                // secret in memory.
                //
                const int CharactersToRead = 1;
                Span<char> inputBuffer = stackalloc char[CharactersToRead + 1];

                while (true)
                {
#if UNIX
                    ConsoleKeyInfo keyInfo = Console.ReadKey(true);
#else
                    string key = ConsoleControl.ReadConsole(handle, initialContentLength: 0, inputBuffer, charactersToRead: CharactersToRead, endOnTab: false, out _);
#endif

#if UNIX
                    // Handle Ctrl-C ending input
                    if (keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
#else
                    if (string.IsNullOrEmpty(key) || key[0] == (char)3)
#endif
                    {
                        PipelineStoppedException e = new PipelineStoppedException();
                        throw e;
                    }
#if UNIX
                    if (keyInfo.Key == ConsoleKey.Enter)
#else
                    if (key[0] == (char)13)
#endif
                    {
                        //
                        // we are done if user presses ENTER key
                        //
                        break;
                    }
#if UNIX
                    if (keyInfo.Key == ConsoleKey.Backspace)
#else
                    if (key[0] == (char)8)
#endif
                    {
                        //
                        // for backspace, remove last char appended
                        //
                        if (isSecureString && secureResult.Length > 0)
                        {
                            secureResult.RemoveAt(secureResult.Length - 1);
                            WriteBackSpace(originalCursorPos);
                        }
                        else if (result.Length > 0)
                        {
                            result.Remove(result.Length - 1, 1);
                            WriteBackSpace(originalCursorPos);
                        }
                    }
#if UNIX
                    else if (char.IsControl(keyInfo.KeyChar))
                    {
                        // deny list control characters
                        continue;
                    }
#endif
                    else
                    {
                        //
                        // append the char to our string
                        //
                        if (isSecureString)
                        {
#if UNIX
                            secureResult.AppendChar(keyInfo.KeyChar);
#else
                            secureResult.AppendChar(key[0]);
#endif
                        }
                        else
                        {
#if UNIX
                            result.Append(keyInfo.KeyChar);
#else
                            result.Append(key);
#endif
                        }

                        if (!string.IsNullOrEmpty(printTokenString))
                        {
                            WritePrintToken(printTokenString, ref originalCursorPos);
                        }
                    }
                }
            }
#if UNIX
            catch (InvalidOperationException)
            {
                // ReadKey() failed so we stop
                throw new PipelineStoppedException();
            }
#endif
            finally
            {
#if UNIX
                Console.TreatControlCAsInput = treatControlCAsInput;
#else
                if (isModeChanged)
                {
                    ConsoleControl.SetMode(handle, originalMode);
                }
#endif
            }

            WriteLineToConsole();
            PostRead(result.ToString());
            if (isSecureString)
            {
                return secureResult;
            }
            else
            {
                return result;
            }
        }

        /// <summary>
        /// Handle writing print token with proper cursor adjustment for ReadLineSafe.
        /// </summary>
        /// <param name="printToken">
        /// token output for each char input. It must be a one-char string
        /// </param>
        /// <param name="originalCursorPosition">
        /// it is the cursor position where ReadLineSafe begins
        /// </param>
        /// <exception cref="HostException">
        /// If obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleCursorPosition failed
        /// </exception>
        private void WritePrintToken(
            string printToken,
            ref Coordinates originalCursorPosition)
        {
            Dbg.Assert(!string.IsNullOrEmpty(printToken),
                "Calling WritePrintToken with printToken being null or empty");
            Dbg.Assert(printToken.Length == 1,
                "Calling WritePrintToken with printToken's Length being " + printToken.Length);
            Size consoleBufferSize = _rawui.BufferSize;
            Coordinates currentCursorPosition = _rawui.CursorPosition;

            // if the cursor is currently at the lower right corner, this write will cause the screen buffer to
            // scroll up. So, it is necessary to adjust the original cursor position one row up.
            if (currentCursorPosition.Y >= consoleBufferSize.Height - 1 && // last row
                currentCursorPosition.X >= consoleBufferSize.Width - 1)  // last column
            {
                if (originalCursorPosition.Y > 0)
                {
                    originalCursorPosition.Y--;
                }
            }

            WriteToConsole(printToken, false);
        }

        /// <summary>
        /// Handle backspace with proper cursor adjustment for ReadLineSafe.
        /// </summary>
        /// <param name="originalCursorPosition">
        /// it is the cursor position where ReadLineSafe begins
        /// </param>
        /// <exception cref="HostException">
        /// If obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleCursorPosition failed
        /// </exception>
        private void WriteBackSpace(Coordinates originalCursorPosition)
        {
            Coordinates cursorPosition = _rawui.CursorPosition;
            if (cursorPosition == originalCursorPosition)
            {
                // at originalCursorPosition, don't move
                return;
            }

            if (cursorPosition.X == 0)
            {
                if (cursorPosition.Y <= originalCursorPosition.Y)
                {
                    return;
                }
                // BufferSize.Width is 1 larger than cursor position
                cursorPosition.X = _rawui.BufferSize.Width - 1;
                cursorPosition.Y--;
                BlankAtCursor(cursorPosition);
            }
            else if (cursorPosition.X > 0)
            {
                cursorPosition.X--;
                BlankAtCursor(cursorPosition);
            }
            // do nothing if cursorPosition.X is left of screen
        }

        /// <summary>
        /// Blank out at and move rawui.CursorPosition to <paramref name="cursorPosition"/>
        /// </summary>
        /// <param name="cursorPosition">Position to blank out.</param>
        private void BlankAtCursor(Coordinates cursorPosition)
        {
            _rawui.CursorPosition = cursorPosition;
            WriteToConsole(" ", true);
            _rawui.CursorPosition = cursorPosition;
        }

#if !UNIX
        /// <summary>
        /// If <paramref name="m"/> is set on <paramref name="flagToUnset"/>, unset it and return true;
        /// otherwise return false.
        /// </summary>
        /// <param name="flagToUnset">
        /// a flag in ConsoleControl.ConsoleModes to be unset in <paramref name="m"/>
        /// </param>
        /// <param name="m">
        /// </param>
        /// <returns>
        /// true if <paramref name="m"/> is set on <paramref name="flagToUnset"/>
        /// false otherwise
        /// </returns>
        private static bool shouldUnsetMode(
            ConsoleControl.ConsoleModes flagToUnset,
            ref ConsoleControl.ConsoleModes m)
        {
            if ((m & flagToUnset) > 0)
            {
                m &= ~flagToUnset;
                return true;
            }

            return false;
        }
#endif

        #region WriteToConsole

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal void WriteToConsole(char c, bool transcribeResult)
        {
            ReadOnlySpan<char> value = [c];
            WriteToConsole(value, transcribeResult);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal void WriteToConsole(ReadOnlySpan<char> value, bool transcribeResult)
        {
            WriteToConsole(value, transcribeResult, newLine: false);
        }

        private void WriteToConsole(ReadOnlySpan<char> value, bool transcribeResult, bool newLine)
        {
#if !UNIX
            ConsoleHandle handle = ConsoleControl.GetActiveScreenBufferHandle();

            // Ensure that we're in the proper line-output mode.  We don't lock here as it does not matter if we
            // attempt to set the mode from multiple threads at once.
            ConsoleControl.ConsoleModes m = ConsoleControl.GetMode(handle);

            const ConsoleControl.ConsoleModes DesiredMode =
                ConsoleControl.ConsoleModes.ProcessedOutput
                | ConsoleControl.ConsoleModes.WrapEndOfLine;

            if ((m & DesiredMode) != DesiredMode)
            {
                m |= DesiredMode;
                ConsoleControl.SetMode(handle, m);
            }
#endif

            PreWrite();

            // This is atomic, so we don't lock here...
#if !UNIX
            ConsoleControl.WriteConsole(handle, value, newLine);
#else
            ConsoleOutWriteHelper(value, newLine);
#endif

            if (_isInteractiveTestToolListening && Console.IsOutputRedirected)
            {
                ConsoleOutWriteHelper(value, newLine);
            }

            if (transcribeResult)
            {
                PostWrite(value, newLine);
            }
            else
            {
                PostWrite();
            }
        }

        private void WriteToConsole(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string text, bool newLine = false)
        {
            // Sync access so that we don't conflict on color settings if called from multiple threads.
            lock (_instanceLock)
            {
                ConsoleColor fg = RawUI.ForegroundColor;
                ConsoleColor bg = RawUI.BackgroundColor;

                RawUI.ForegroundColor = foregroundColor;
                RawUI.BackgroundColor = backgroundColor;

                try
                {
                    WriteToConsole(text, transcribeResult: true, newLine);
                }
                finally
                {
                    RawUI.ForegroundColor = fg;
                    RawUI.BackgroundColor = bg;
                }
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static void ConsoleOutWriteHelper(ReadOnlySpan<char> value, bool newLine)
        {
            if (newLine)
            {
                Console.Out.WriteLine(value);
            }
            else
            {
                Console.Out.Write(value);
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal void WriteLineToConsole(ReadOnlySpan<char> value, bool transcribeResult)
        {
            WriteToConsole(value, transcribeResult, newLine: true);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void WriteLineToConsole(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string text)
        {
            WriteToConsole(foregroundColor, backgroundColor, text, newLine: true);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void WriteLineToConsole(string text)
        {
            WriteLineToConsole(text, transcribeResult: true);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void WriteLineToConsole()
        {
            WriteToConsole(Environment.NewLine, transcribeResult: true, newLine: false);
        }

        #endregion WriteToConsole

        /// <summary>
        /// See base class.
        /// </summary>
        /// <param name="value"></param>
        /// <exception cref="HostException">
        /// If Win32's CreateFile fails
        ///    OR
        ///    Win32's GetConsoleMode fails
        ///    OR
        ///    Win32's SetConsoleMode fails
        ///    OR
        ///    Win32's WriteConsole fails
        /// </exception>
        public override void Write(string value)
        {
            lock (_instanceLock)
            {
                WriteImpl(value, newLine: false);
            }
        }

        // The WriteImpl() method should always be called within a lock on _instanceLock
        // to ensure thread safety and prevent issues in multi-threaded scenarios.
        private void WriteImpl(string value, bool newLine)
        {
            if (string.IsNullOrEmpty(value) && !newLine)
            {
                return;
            }

            // If the test hook is set, write to it and continue.
            if (s_h != null)
            {
                if (newLine)
                {
                    s_h.WriteLine(value);
                }
                else
                {
                    s_h.Write(value);
                }
            }

            TextWriter writer = Console.IsOutputRedirected ? Console.Out : _parent.ConsoleTextWriter;
            value = GetOutputString(value, SupportsVirtualTerminal);

            if (_parent.IsRunningAsync)
            {
                Dbg.Assert(writer == _parent.OutputSerializer.textWriter, "writers should be the same");

                _parent.OutputSerializer.Serialize(value);

                if (newLine)
                {
                    _parent.OutputSerializer.Serialize(Environment.NewLine);
                }
            }
            else
            {
                if (newLine)
                {
                    writer.WriteLine(value);
                }
                else
                {
                    writer.Write(value);
                }
            }
        }

        /// <summary>
        /// See base class.
        /// </summary>
        /// <param name="foregroundColor"></param>
        /// <param name="backgroundColor"></param>
        /// <param name="value"></param>
        /// <exception cref="HostException">
        /// If obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleTextAttribute
        ///    OR
        ///    Win32's CreateFile fails
        ///    OR
        ///    Win32's GetConsoleMode fails
        ///    OR
        ///    Win32's SetConsoleMode fails
        ///    OR
        ///    Win32's WriteConsole fails
        /// </exception>
        public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
        {
            Write(foregroundColor, backgroundColor, value, newLine: false);
        }

        /// <summary>
        /// See base class.
        /// </summary>
        /// <param name="foregroundColor"></param>
        /// <param name="backgroundColor"></param>
        /// <param name="value"></param>
        /// <exception cref="HostException">
        /// If obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleTextAttribute
        ///    OR
        ///    Win32's CreateFile fails
        ///    OR
        ///    Win32's GetConsoleMode fails
        ///    OR
        ///    Win32's SetConsoleMode fails
        ///    OR
        ///    Win32's WriteConsole fails
        /// </exception>
        public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
        {
            Write(foregroundColor, backgroundColor, value, newLine: true);
        }

        private void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value, bool newLine)
        {
            // Sync access so that we don't conflict on color settings if called from multiple threads.
            lock (_instanceLock)
            {
                ConsoleColor fg = RawUI.ForegroundColor;
                ConsoleColor bg = RawUI.BackgroundColor;

                RawUI.ForegroundColor = foregroundColor;
                RawUI.BackgroundColor = backgroundColor;

                try
                {
                    this.WriteImpl(value, newLine);
                }
                finally
                {
                    RawUI.ForegroundColor = fg;
                    RawUI.BackgroundColor = bg;
                }
            }
        }

        /// <summary>
        /// See base class.
        /// </summary>
        /// <param name="value"></param>
        /// <exception cref="HostException">
        ///    Win32's CreateFile fails
        ///    OR
        ///    Win32's GetConsoleMode fails
        ///    OR
        ///    Win32's SetConsoleMode fails
        ///    OR
        ///    Win32's WriteConsole fails
        /// </exception>
        public override void WriteLine(string value)
        {
            lock (_instanceLock)
            {
                this.WriteImpl(value, newLine: true);
            }
        }

        /// <summary>
        /// See base class.
        /// </summary>
        /// <exception cref="HostException">
        ///    Win32's CreateFile fails
        ///    OR
        ///    Win32's GetConsoleMode fails
        ///    OR
        ///    Win32's SetConsoleMode fails
        ///    OR
        ///    Win32's WriteConsole fails
        /// </exception>
        public override void WriteLine()
        {
            lock (_instanceLock)
            {
                this.WriteImpl(Environment.NewLine, newLine: false);
            }
        }

        #region Word Wrapping

        /// <summary>
        /// This is a poor-man's word-wrapping routine.  It breaks a single string into segments small enough to fit within a
        /// given number of cells.  A break is determined by the last occurrence of whitespace that allows all prior characters
        /// on a line to be written within a given number of cells.  If there is no whitespace found within that span, then the
        /// largest span that will fit in the bounds is used.
        ///
        /// The problem is complicated by the fact that a single character may consume more than one cell.  Conceptually, this
        /// is the same case as placing an upper bound on the length of a line while also having a strlen function that
        /// arbitrarily considers the length of any single character to be 1 or greater.
        /// </summary>
        /// <param name="text">
        /// Text to be emitted.
        /// Each tab character in the text is replaced with a space in the results.
        /// </param>
        /// <param name="maxWidthInBufferCells">
        /// Max width, in buffer cells, of a single line.  Note that a single character may consume more than one cell.  The
        /// number of cells consumed is determined by calling ConsoleHostRawUserInterface.LengthInBufferCells.
        /// </param>
        /// <returns>
        /// A list of strings representing the text broken into "lines" each of which are guaranteed not to exceed
        /// maxWidthInBufferCells.
        /// </returns>
        internal List<string> WrapText(string text, int maxWidthInBufferCells)
        {
            List<string> result = new List<string>();

            List<Word> words = ChopTextIntoWords(text, maxWidthInBufferCells);
            if (words.Count < 1)
            {
                return result;
            }

            IEnumerator<Word> e = words.GetEnumerator();
            bool valid = false;
            int cellCounter = 0;
            StringBuilder line = new StringBuilder();
            string l = null;

            do
            {
                valid = e.MoveNext();
                if (!valid)
                {
                    if (line.Length > 0)
                    {
                        l = line.ToString();
                        Dbg.Assert(RawUI.LengthInBufferCells(l) <= maxWidthInBufferCells, "line is too long");
                        result.Add(l);
                    }

                    break;
                }

                if ((e.Current.Flags & WordFlags.IsNewline) > 0)
                {
                    l = line.ToString();
                    Dbg.Assert(RawUI.LengthInBufferCells(l) <= maxWidthInBufferCells, "line is too long");
                    result.Add(l);

                    // skip the newline "words"

                    line = new StringBuilder();
                    cellCounter = 0;
                    continue;
                }

                // will the word fit?

                if (cellCounter + e.Current.CellCount <= maxWidthInBufferCells)
                {
                    // yes, add it to the line.

                    line.Append(e.Current.Text);
                    cellCounter += e.Current.CellCount;
                }
                else
                {
                    // no: too long.  Either start a new line, or pick off as much whitespace as we need.

                    if ((e.Current.Flags & WordFlags.IsWhitespace) == 0)
                    {
                        l = line.ToString();
                        Dbg.Assert(RawUI.LengthInBufferCells(l) <= maxWidthInBufferCells, "line is too long");
                        result.Add(l);

                        line = new StringBuilder(e.Current.Text);
                        cellCounter = e.Current.CellCount;
                        continue;
                    }

                    // chop the whitespace into bits.

                    int w = maxWidthInBufferCells - cellCounter;
                    Dbg.Assert(w < e.Current.CellCount, "width remaining should be less than size of word");

                    line.Append(e.Current.Text.AsSpan(0, w));

                    l = line.ToString();
                    Dbg.Assert(RawUI.LengthInBufferCells(l) == maxWidthInBufferCells, "line should exactly fit");
                    result.Add(l);

                    string remaining = e.Current.Text.Substring(w);
                    line = new StringBuilder(remaining);
                    cellCounter = RawUI.LengthInBufferCells(remaining);
                }
            } while (valid);

            return result;
        }

        /// <summary>
        /// Struct used by WrapText.
        /// </summary>
        [Flags]
        internal enum WordFlags
        {
            IsWhitespace = 0x01,
            IsNewline = 0x02
        }

        internal struct Word
        {
            internal int CellCount;
            internal string Text;
            internal WordFlags Flags;
        }

        /// <summary>
        /// Chops text into "words," where a word is defined to be a sequence of whitespace characters, or a sequence of
        /// non-whitespace characters, each sequence being no longer than a given maximum.  Therefore, in the text "this is a
        /// string" there are 7 words: 4 sequences of non-whitespace characters and 3 sequences of whitespace characters.
        ///
        /// Whitespace is considered to be spaces or tabs.  Each tab character is replaced with a single space.
        /// </summary>
        /// <param name="text">
        /// The text to be chopped up.
        /// </param>
        /// <param name="maxWidthInBufferCells">
        /// The maximum number of buffer cells that each word may consume.
        /// </param>
        /// <returns>
        /// A list of words, in the same order they appear in the source text.
        /// </returns>
        /// <remarks>
        /// This can be made faster by, instead of creating little strings for each word, creating indices of the start and end
        /// range of a word.  That would reduce the string allocations.
        /// </remarks>
        internal List<Word> ChopTextIntoWords(string text, int maxWidthInBufferCells)
        {
            List<Word> result = new List<Word>();

            if (string.IsNullOrEmpty(text))
            {
                return result;
            }

            if (maxWidthInBufferCells < 1)
            {
                return result;
            }

            text = text.Replace('\t', ' ');

            result = new List<Word>();

            // a "word" is a span of characters delimited by whitespace.  Contiguous whitespace, too, is a word.

            int startIndex = 0;
            int wordEnd = 0;
            bool inWs = false;

            while (wordEnd < text.Length)
            {
                if (text[wordEnd] == '\n')
                {
                    if (startIndex < wordEnd)
                    {
                        // the span up to this point needs to be saved off

                        AddWord(text, startIndex, wordEnd, maxWidthInBufferCells, inWs, ref result);
                    }

                    // add a nl word

                    Word w = new Word();
                    w.Flags = WordFlags.IsNewline;
                    result.Add(w);

                    // skip the nl

                    ++wordEnd;
                    startIndex = wordEnd;

                    inWs = false;
                    continue;
                }
                else if (text[wordEnd] == ' ')
                {
                    if (!inWs)
                    {
                        // span from startIndex..(wordEnd - 1) is a word

                        AddWord(text, startIndex, wordEnd, maxWidthInBufferCells, inWs, ref result);
                        startIndex = wordEnd;
                    }

                    inWs = true;
                }
                else
                {
                    // not whitespace

                    if (inWs)
                    {
                        AddWord(text, startIndex, wordEnd, maxWidthInBufferCells, inWs, ref result);
                        startIndex = wordEnd;
                    }

                    inWs = false;
                }

                ++wordEnd;
            }

            if (startIndex != wordEnd)
            {
                AddWord(text, startIndex, text.Length, maxWidthInBufferCells, inWs, ref result);
            }

            return result;
        }

        /// <summary>
        /// Helper for ChopTextIntoWords.  Takes a span of characters in a string and adds it to the word list, further
        /// subdividing the span as needed so that each subdivision fits within the limit.
        /// </summary>
        /// <param name="text">
        /// The string of characters in which the span is to be extracted.
        /// </param>
        /// <param name="startIndex">
        /// index into text of the start of the word to be added.
        /// </param>
        /// <param name="endIndex">
        /// index of the char after the last char to be included in the word.
        /// </param>
        /// <param name="maxWidthInBufferCells">
        /// The maximum number of buffer cells that each word may consume.
        /// </param>
        /// <param name="isWhitespace">
        /// true if the span is whitespace, false if not.
        /// </param>
        /// <param name="result">
        /// The list into which the words will be added.
        /// </param>
        internal void AddWord(string text, int startIndex, int endIndex,
            int maxWidthInBufferCells, bool isWhitespace, ref List<Word> result)
        {
            Dbg.Assert(endIndex >= startIndex, "startIndex must be before endIndex");
            Dbg.Assert(endIndex >= 0, "endIndex must be positive");
            Dbg.Assert(startIndex >= 0, "startIndex must be positive");
            Dbg.Assert(startIndex < text.Length, "startIndex must be within the string");
            Dbg.Assert(endIndex <= text.Length, "endIndex must be within the string");

            while (startIndex < endIndex)
            {
                int i = Math.Min(endIndex, startIndex + maxWidthInBufferCells);
                Word w = new Word();
                if (isWhitespace)
                {
                    w.Flags = WordFlags.IsWhitespace;
                }

                while (true)
                {
                    w.Text = text.Substring(startIndex, i - startIndex);
                    w.CellCount = RawUI.LengthInBufferCells(w.Text);
                    if (w.CellCount <= maxWidthInBufferCells)
                    {
                        // the segment from start..i fits

                        break;
                    }
                    else
                    {
                        // The segment does not fit, back off a tad until it does

                        --i;
                    }
                }

                Dbg.Assert(RawUI.LengthInBufferCells(w.Text) <= maxWidthInBufferCells, "word should not exceed max");
                result.Add(w);

                startIndex = i;
            }
        }

        internal string WrapToCurrentWindowWidth(string text)
        {
            StringBuilder sb = new StringBuilder();

            // we leave a 1-cell margin on the end because if the very last character butts up against the
            // edge of the screen buffer, then the console will wrap the line.

            List<string> lines = WrapText(text, RawUI.WindowSize.Width - 1);
            int count = 0;
            foreach (string s in lines)
            {
                sb.Append(s);
                if (++count != lines.Count)
                {
                    sb.Append(Environment.NewLine);
                }
            }

            return sb.ToString();
        }

        #endregion Word Wrapping

        /// <summary>
        /// See base class.
        /// </summary>
        /// <param name="message"></param>
        /// <exception cref="HostException">
        /// If obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleTextAttribute
        ///    OR
        ///    Win32's CreateFile fails
        ///    OR
        ///    Win32's GetConsoleMode fails
        ///    OR
        ///    Win32's SetConsoleMode fails
        ///    OR
        ///    Win32's WriteConsole fails
        /// </exception>
        public override void WriteDebugLine(string message)
        {
            // We should write debug to error stream only if debug is redirected.)
            if (_parent.ErrorFormat == Serialization.DataFormat.XML)
            {
                _parent.ErrorSerializer.Serialize(message, "debug");
            }
            else
            {
                if (SupportsVirtualTerminal)
                {
                    WriteLine(GetFormatStyleString(FormatStyle.Debug) + StringUtil.Format(ConsoleHostUserInterfaceStrings.DebugFormatString, message) + PSStyle.Instance.Reset);
                }
                else
                {
                    WriteLine(
                        DebugForegroundColor,
                        DebugBackgroundColor,
                        StringUtil.Format(ConsoleHostUserInterfaceStrings.DebugFormatString, message));
                }
            }
        }

        /// <summary>
        /// See base class.
        /// </summary>
        /// <param name="record"></param>
        public override void WriteInformation(InformationRecord record)
        {
            // We should write information to error stream only if redirected.)
            if (_parent.ErrorFormat == Serialization.DataFormat.XML)
            {
                _parent.ErrorSerializer.Serialize(record, "information");
            }
            else
            {
                // Do nothing. The information stream is not visible by default
            }
        }

        /// <summary>
        /// See base class.
        /// </summary>
        /// <param name="message"></param>
        /// <exception cref="HostException">
        /// If obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleTextAttribute
        ///    OR
        ///    Win32's CreateFile fails
        ///    OR
        ///    Win32's GetConsoleMode fails
        ///    OR
        ///    Win32's SetConsoleMode fails
        ///    OR
        ///    Win32's WriteConsole fails
        /// </exception>
        public override void WriteVerboseLine(string message)
        {
            // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here...)
            if (_parent.ErrorFormat == Serialization.DataFormat.XML)
            {
                _parent.ErrorSerializer.Serialize(message, "verbose");
            }
            else
            {
                if (SupportsVirtualTerminal)
                {
                    WriteLine(GetFormatStyleString(FormatStyle.Verbose) + StringUtil.Format(ConsoleHostUserInterfaceStrings.VerboseFormatString, message) + PSStyle.Instance.Reset);
                }
                else
                {
                    WriteLine(
                        VerboseForegroundColor,
                        VerboseBackgroundColor,
                        StringUtil.Format(ConsoleHostUserInterfaceStrings.VerboseFormatString, message));
                }
            }
        }

        /// <summary>
        /// See base class.
        /// </summary>
        /// <param name="message"></param>
        /// <exception cref="HostException">
        /// If obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleTextAttribute
        ///    OR
        ///    Win32's CreateFile fails
        ///    OR
        ///    Win32's GetConsoleMode fails
        ///    OR
        ///    Win32's SetConsoleMode fails
        ///    OR
        ///    Win32's WriteConsole fails
        /// </exception>
        public override void WriteWarningLine(string message)
        {
            // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here...)
            if (_parent.ErrorFormat == Serialization.DataFormat.XML)
            {
                _parent.ErrorSerializer.Serialize(message, "warning");
            }
            else
            {
                if (SupportsVirtualTerminal)
                {
                    WriteLine(GetFormatStyleString(FormatStyle.Warning) + StringUtil.Format(ConsoleHostUserInterfaceStrings.WarningFormatString, message) + PSStyle.Instance.Reset);
                }
                else
                {
                    WriteLine(
                        WarningForegroundColor,
                        WarningBackgroundColor,
                        StringUtil.Format(ConsoleHostUserInterfaceStrings.WarningFormatString, message));
                }
            }
        }

        /// <summary>
        /// Invoked by CommandBase.WriteProgress to display a progress record.
        /// </summary>
        public override void WriteProgress(long sourceId, ProgressRecord record)
        {
            Dbg.Assert(record != null, "WriteProgress called with null ProgressRecord");

            if (_parent.ErrorFormat == Serialization.DataFormat.XML)
            {
                PSObject obj = new PSObject();
                obj.Properties.Add(new PSNoteProperty("SourceId", sourceId));
                obj.Properties.Add(new PSNoteProperty("Record", record));
                _parent.ErrorSerializer.Serialize(obj, "progress");
            }
            else if (Console.IsOutputRedirected)
            {
                // Do not write progress bar when the stdout is redirected.
                return;
            }
            else
            {
                // We allow only one thread at a time to update the progress state.)
                lock (_instanceLock)
                {
                    HandleIncomingProgressRecord(sourceId, record);
                }
            }
        }

        public override void WriteErrorLine(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return;
            }

            TextWriter writer = (!Console.IsErrorRedirected || _parent.IsInteractive)
                ? _parent.ConsoleTextWriter
                : Console.Error;

            if (_parent.ErrorFormat == Serialization.DataFormat.XML)
            {
                Dbg.Assert(writer == _parent.ErrorSerializer.textWriter, "writers should be the same");

                _parent.ErrorSerializer.Serialize(value + Environment.NewLine);
            }
            else
            {
                if (writer == _parent.ConsoleTextWriter)
                {
                    if (SupportsVirtualTerminal)
                    {
                        WriteLine(value);
                    }
                    else
                    {
                        WriteLine(ErrorForegroundColor, ErrorBackgroundColor, value);
                    }
                }
                else
                {
                    value = GetOutputString(value, SupportsVirtualTerminal);
                    Console.Error.WriteLine(value);
                }
            }
        }

        public ConsoleColor FormatAccentColor { get; set; } = ConsoleColor.Green;

        public ConsoleColor ErrorAccentColor { get; set; } = ConsoleColor.Cyan;

        public ConsoleColor ErrorForegroundColor { get; set; } = ConsoleColor.Red;

        public ConsoleColor ErrorBackgroundColor { get; set; } = Console.BackgroundColor;

        public ConsoleColor WarningForegroundColor { get; set; } = ConsoleColor.Yellow;

        public ConsoleColor WarningBackgroundColor { get; set; } = Console.BackgroundColor;

        public ConsoleColor DebugForegroundColor { get; set; } = ConsoleColor.Yellow;

        public ConsoleColor DebugBackgroundColor { get; set; } = Console.BackgroundColor;

        public ConsoleColor VerboseForegroundColor { get; set; } = ConsoleColor.Yellow;

        public ConsoleColor VerboseBackgroundColor { get; set; } = Console.BackgroundColor;

        public ConsoleColor ProgressForegroundColor { get; set; } = ConsoleColor.Black;

        public ConsoleColor ProgressBackgroundColor { get; set; } = ConsoleColor.Yellow;

        #endregion Line-oriented interaction

        #region implementation

        // We use System.Environment.NewLine because we are platform-agnostic

        internal static readonly string Crlf = System.Environment.NewLine;

        private const string Tab = "\x0009";

        internal enum ReadLineResult
        {
            endedOnEnter = 0,
            endedOnTab = 1,
            endedOnShiftTab = 2,
            endedOnBreak = 3
        }

        private const int MaxInputLineLength = 1024;

        /// <summary>
        /// Reads a line of input from the console.  Returns when the user hits enter, a break key, a break event occurs.  In
        /// the case that stdin has been redirected, reads from the stdin stream instead of the console.
        /// </summary>
        /// <param name="endOnTab">
        /// true to end input when the user hits the tab or shift-tab keys, false to only end on the enter key (or a break
        /// event). Ignored if not reading from the console device.
        /// </param>
        /// <param name="initialContent">
        /// The initial contents of the input buffer.  Nice if you want to have a default result. Ignored if not reading from the
        /// console device.
        /// </param>
        /// <param name="result">
        /// Receives an enum value indicating how input was ended.
        /// </param>
        /// <param name="calledFromPipeline">
        /// TBD
        /// </param>
        /// <param name="transcribeResult">
        /// true to include the results in any transcription that might be happening.
        /// </param>
        /// <returns>
        /// The string read from either the console or the stdin stream.  null if:
        /// - stdin was read and EOF was reached on the stream, or
        /// - the console was read, and input was terminated with Ctrl-C, Ctrl-Break, or Close.
        /// </returns>
        /// <exception cref="HostException">
        /// If Win32's SetConsoleMode fails
        ///    OR
        ///    Win32's ReadConsole fails
        ///    OR
        ///    obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleCursorPosition failed
        /// </exception>
        internal string ReadLine(bool endOnTab, string initialContent, out ReadLineResult result, bool calledFromPipeline, bool transcribeResult)
        {
            result = ReadLineResult.endedOnEnter;

            // If the test hook is set, read from it.
            if (s_h != null)
            {
                return s_h.ReadLine();
            }

            string restOfLine = null;

            string s = ReadFromStdin
                ? ReadLineFromFile(initialContent)
                : ReadLineFromConsole(endOnTab, initialContent, calledFromPipeline, ref restOfLine, ref result);

            if (transcribeResult)
            {
                PostRead(s);
            }
            else
            {
                PostRead();
            }

            if (restOfLine != null)
                s += restOfLine;

            return s;
        }

        private string ReadLineFromFile(string initialContent)
        {
            var sb = new StringBuilder();
            if (!string.IsNullOrEmpty(initialContent))
            {
                sb.Append(initialContent);
                sb.Append('\n');
            }

            var consoleIn = _parent.ConsoleIn.Value;
            while (true)
            {
                var inC = consoleIn.Read();
                if (inC == -1)
                {
                    // EOF - we return null which tells our caller to exit
                    // but only if we don't have any input, we could have
                    // input and then stdin was closed, but never saw a newline.
                    return sb.Length == 0 ? null : sb.ToString();
                }

                var c = unchecked((char)inC);
                if (!NoPrompt)
                {
                    Console.Out.Write(c);
                }

                if (c == '\r')
                {
                    // Treat as newline, but consume \n if there is one.
                    if (consoleIn.Peek() == '\n')
                    {
                        if (!NoPrompt)
                        {
                            Console.Out.Write('\n');
                        }

                        consoleIn.Read();
                    }

                    break;
                }

                if (c == '\n')
                {
                    break;
                }

                // If NoPrompt is true, we are in a sort of server mode where we shouldn't
                // do anything like edit the command line - every character is part of the input.
                if (c == '\b' && !NoPrompt)
                {
                    sb.Remove(sb.Length - 1, 1);
                }
                else
                {
                    sb.Append(c);
                }
            }

            return sb.ToString();
        }

        private string ReadLineFromConsole(bool endOnTab, string initialContent, bool calledFromPipeline, ref string restOfLine, ref ReadLineResult result)
        {
            PreRead();
            // Ensure that we're in the proper line-input mode.

#if !UNIX
            ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle();
            ConsoleControl.ConsoleModes m = ConsoleControl.GetMode(handle);

            const ConsoleControl.ConsoleModes DesiredMode =
                ConsoleControl.ConsoleModes.LineInput
                | ConsoleControl.ConsoleModes.EchoInput
                | ConsoleControl.ConsoleModes.ProcessedInput;

            if ((m & DesiredMode) != DesiredMode || (m & ConsoleControl.ConsoleModes.MouseInput) > 0)
            {
                m &= ~ConsoleControl.ConsoleModes.MouseInput;
                m |= DesiredMode;
                ConsoleControl.SetMode(handle, m);
            }
#endif

            // If more characters are typed than you asked, then the next call to ReadConsole will return the
            // additional characters beyond those you requested.
            //
            // If input is terminated with a tab key, then the buffer returned will have a tab (ascii 0x9) at the
            // position where the tab key was hit.  If the user has arrowed backward over existing input in the line
            // buffer, the tab will overwrite whatever character was in that position. That character will be lost in
            // the input buffer, but since we echo each character the user types, it's still in the active screen buffer
            // and we can read the console output to get that character.
            //
            // If input is terminated with an enter key, then the buffer returned will have ascii 0x0D and 0x0A
            // (Carriage Return and Line Feed) as the last two characters of the buffer.
            //
            // If input is terminated with a break key (Ctrl-C, Ctrl-Break, Close, etc.), then the buffer will be
            // the empty string.

#if UNIX
            // For Unix systems, we implement a basic readline loop around Console.ReadKey(), that
            // supports backspace, arrow keys, Ctrl-C, and Ctrl-D. This readline is only used for
            // interactive prompts (like Read-Host), otherwise it is assumed that PSReadLine is
            // available. Therefore this explicitly does not support history or tab completion.

            bool treatControlCAsInput = Console.TreatControlCAsInput;

            try
            {

                ConsoleKeyInfo keyInfo;
                string s = string.Empty;
                int index = 0;
                int cursorLeft = Console.CursorLeft;
                int cursorCurrent = cursorLeft;
                bool insertMode = true;
                Console.TreatControlCAsInput = true;
#else
            _rawui.ClearKeyCache();
            uint keyState = 0;
            string s = string.Empty;
            Span<char> inputBuffer = stackalloc char[MaxInputLineLength + 1];
            if (initialContent.Length > 0)
            {
                initialContent.AsSpan().CopyTo(inputBuffer);
            }

#endif
            while (true)
            {
#if UNIX
                    keyInfo = Console.ReadKey(true);
#else
                s += ConsoleControl.ReadConsole(handle, initialContent.Length, inputBuffer, MaxInputLineLength, endOnTab, out keyState);
                Dbg.Assert(s != null, "s should never be null");
#endif

#if UNIX
                    // Handle Ctrl-C ending input
                    if (keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
#else
                if (s.Length == 0)
#endif
                {
                    result = ReadLineResult.endedOnBreak;
                    s = null;

                    if (calledFromPipeline)
                    {
                        // make sure that the pipeline that called us is stopped

                        throw new PipelineStoppedException();
                    }

                    break;
                }

#if UNIX
                    if (keyInfo.Key == ConsoleKey.Enter)
#else
                if (s.EndsWith(Environment.NewLine, StringComparison.Ordinal))
#endif
                {
                    result = ReadLineResult.endedOnEnter;
#if UNIX
                        // We're intercepting characters, so we need to echo the newline
                        Console.Out.WriteLine();
#else
                    s = s.Remove(s.Length - Environment.NewLine.Length);
#endif
                    break;
                }

#if UNIX
                    if (keyInfo.Key == ConsoleKey.Tab)
                    {
                        // This is unsupported
                        continue;
                    }
#else
                int i = s.IndexOf(Tab, StringComparison.Ordinal);

                if (endOnTab && i != -1)
                {
                    // then the tab we found is the completion character.  bit 0x10 is set if the shift key was down
                    // when the key was hit.

                    if ((keyState & 0x10) == 0)
                    {
                        result = ReadLineResult.endedOnTab;
                    }
                    else if ((keyState & 0x10) > 0)
                    {
                        result = ReadLineResult.endedOnShiftTab;
                    }
                    else
                    {
                        // do nothing: leave the result state as it was. This is the circumstance when we've have to
                        // do more than one iteration and the input ended on a tab or shift-tab, or the user hit
                        // enter, or the user hit ctrl-c
                    }

                    // also clean up the screen -- if the cursor was positioned somewhere before the last character
                    // in the input buffer, then the characters from the tab to the end of the buffer need to be
                    // erased.
                    int leftover = RawUI.LengthInBufferCells(s.Substring(i + 1));

                    if (leftover > 0)
                    {
                        Coordinates c = RawUI.CursorPosition;

                        // before cleaning up the screen, read the active screen buffer to retrieve the character that
                        // is overridden by the tab
                        char charUnderCursor = GetCharacterUnderCursor(c);

                        Write(StringUtil.Padding(leftover));
                        RawUI.CursorPosition = c;

                        restOfLine = s[i] + (charUnderCursor + s.Substring(i + 1));
                    }
                    else
                    {
                        restOfLine += s[i];
                    }

                    s = s.Remove(i);

                    break;
                }
#endif
#if UNIX
                    if (keyInfo.Key == ConsoleKey.Backspace)
                    {
                        if (index > 0)
                        {
                            int length = s.Length;
                            s = s.Remove(index - 1, 1);
                            index--;
                            cursorCurrent = Console.CursorLeft;
                            Console.CursorLeft = cursorLeft;
                            Console.Out.Write(s.PadRight(length));
                            Console.CursorLeft = cursorCurrent - 1;
                        }

                        continue;
                    }

                    if (keyInfo.Key == ConsoleKey.Delete
                        || (keyInfo.Key == ConsoleKey.D && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control)))
                    {
                        if (index < s.Length)
                        {
                            int length = s.Length;
                            s = s.Remove(index, 1);
                            cursorCurrent = Console.CursorLeft;
                            Console.CursorLeft = cursorLeft;
                            Console.Out.Write(s.PadRight(length));
                            Console.CursorLeft = cursorCurrent;
                        }

                        continue;
                    }

                    if (keyInfo.Key == ConsoleKey.LeftArrow
                        || (keyInfo.Key == ConsoleKey.B && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control)))
                    {
                        if (Console.CursorLeft > cursorLeft)
                        {
                            Console.CursorLeft--;
                            index--;
                        }

                        continue;
                    }

                    if (keyInfo.Key == ConsoleKey.RightArrow
                        || (keyInfo.Key == ConsoleKey.F && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control)))
                    {
                        if (Console.CursorLeft < cursorLeft + s.Length)
                        {
                            Console.CursorLeft++;
                            index++;
                        }

                        continue;
                    }

                    if (keyInfo.Key == ConsoleKey.UpArrow
                        || keyInfo.Key == ConsoleKey.DownArrow
                        || keyInfo.Key == ConsoleKey.PageUp
                        || keyInfo.Key == ConsoleKey.PageDown)
                    {
                        // Arrow/Page Up/down is unimplemented, so fail gracefully
                        continue;
                    }

                    if (keyInfo.Key == ConsoleKey.Home
                        || (keyInfo.Key == ConsoleKey.A && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control)))
                    {
                        Console.CursorLeft = cursorLeft;
                        index = 0;
                        continue;
                    }

                    if (keyInfo.Key == ConsoleKey.End
                        || (keyInfo.Key == ConsoleKey.E && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control)))
                    {
                        Console.CursorLeft = cursorLeft + s.Length;
                        index = s.Length;
                        continue;
                    }

                    if (keyInfo.Key == ConsoleKey.Escape)
                    {
                        Console.CursorLeft = cursorLeft;
                        index = s.Length;
                        s = string.Empty;
                        continue;
                    }

                    if (keyInfo.Key == ConsoleKey.Insert)
                    {
                        // Toggle insert/overwrite mode
                        insertMode = !insertMode;
                        continue;
                    }

                    if (char.IsControl(keyInfo.KeyChar))
                    {
                        // deny list control characters
                        continue;
                    }

                    // Handle case where terminal gets reset and the index is outside of the buffer
                    if (index > s.Length)
                    {
                        index = s.Length;
                    }

                    // Modify string
                    if (!insertMode && index < s.Length) // then overwrite mode
                    {
                        s = s.Remove(index, 1);
                    }

                    s = s.Insert(index, keyInfo.KeyChar.ToString());
                    index++;

                    // Redisplay string
                    cursorCurrent = Console.CursorLeft;
                    Console.CursorLeft = cursorLeft;
                    Console.Out.Write(s);
                    Console.CursorLeft = cursorCurrent + 1;
#endif
            }

            Dbg.Assert(
                       (s == null && result == ReadLineResult.endedOnBreak)
                       || (s != null && result != ReadLineResult.endedOnBreak),
                       "s should only be null if input ended with a break");

            return s;
#if UNIX
            }
            finally
            {
                Console.TreatControlCAsInput = treatControlCAsInput;
            }
#endif
        }

#if !UNIX
        /// <summary>
        /// Get the character at the cursor when the user types 'tab' in the middle of line.
        /// </summary>
        /// <param name="cursorPosition">The cursor position where 'tab' is hit.</param>
        /// <returns></returns>
        private char GetCharacterUnderCursor(Coordinates cursorPosition)
        {
            Rectangle region = new Rectangle(0, cursorPosition.Y, RawUI.BufferSize.Width - 1, cursorPosition.Y);
            BufferCell[,] content = RawUI.GetBufferContents(region);

            for (int index = 0, column = 0; column <= cursorPosition.X; index++)
            {
                BufferCell cell = content[0, index];
                if (cell.BufferCellType == BufferCellType.Complete || cell.BufferCellType == BufferCellType.Leading)
                {
                    if (column == cursorPosition.X)
                    {
                        return cell.Character;
                    }

                    column += ConsoleControl.LengthInBufferCells(cell.Character);
                }
            }

            Dbg.Assert(false, "the character at the cursor should be retrieved, never gets to here");
            return '\0';
        }
#endif

        /// <summary>
        /// Strip nulls from a string.
        /// </summary>
        /// <param name="input">The string to process.</param>
        /// <returns>The string with any '\0' characters removed.</returns>
        private static string RemoveNulls(string input)
        {
            if (!input.Contains('\0'))
            {
                return input;
            }

            StringBuilder sb = new StringBuilder(input.Length);
            foreach (char c in input)
            {
                if (c != '\0')
                {
                    sb.Append(c);
                }
            }

            return sb.ToString();
        }

        /// <summary>
        /// Reads a line, and completes the input for the user if they hit tab.
        /// </summary>
        /// <param name="exec">
        /// The Executor instance on which to run any pipelines that are needed to find matches
        /// </param>
        /// <returns>
        /// null on a break event
        /// the completed line otherwise
        /// </returns>
        internal string ReadLineWithTabCompletion(Executor exec)
        {
            string input = null;
            string lastInput = string.Empty;

            ReadLineResult rlResult = ReadLineResult.endedOnEnter;

#if !UNIX
            ConsoleHandle handle = ConsoleControl.GetActiveScreenBufferHandle();

            string lastCompletion = string.Empty;
            Size screenBufferSize = RawUI.BufferSize;

            // Save the cursor position at the end of the prompt string so that we can restore it later to write the
            // completed input.

            Coordinates endOfPromptCursorPos = RawUI.CursorPosition;

            CommandCompletion commandCompletion = null;
            string completionInput = null;
#endif

            while (true)
            {
                if (TryInvokeUserDefinedReadLine(out input))
                {
                    break;
                }

                input = ReadLine(true, lastInput, out rlResult, false, false);

                if (input == null)
                {
                    break;
                }

                if (rlResult == ReadLineResult.endedOnEnter)
                {
                    break;
                }

#if UNIX // Portable code only ends on enter (or no input), so tab is not processed
                throw new PlatformNotSupportedException("This readline state is unsupported in portable code!");
#else

                Coordinates endOfInputCursorPos = RawUI.CursorPosition;
                string completedInput = null;

                if (rlResult == ReadLineResult.endedOnTab || rlResult == ReadLineResult.endedOnShiftTab)
                {
                    int tabIndex = input.IndexOf(Tab, StringComparison.Ordinal);
                    Dbg.Assert(tabIndex != -1, "tab should appear in the input");

                    string restOfLine = string.Empty;
                    int leftover = input.Length - tabIndex - 1;
                    if (leftover > 0)
                    {
                        // We are reading from the console (not redirected, b/c we don't end on tab when redirected)
                        // If the cursor is at the end of a line, there is actually a space character at the cursor's position and when we type tab
                        // at the end of a line, that space character is replaced by the tab. But when we type tab at the middle of a line, the space
                        // character at the end is preserved, we should remove that space character because it's not provided by the user.
                        input = input.Remove(input.Length - 1);
                        restOfLine = input.Substring(tabIndex + 1);
                    }

                    input = input.Remove(tabIndex);

                    if (input != lastCompletion || commandCompletion == null)
                    {
                        completionInput = input;
                        commandCompletion = GetNewCompletionResults(input);
                    }

                    var completionResult = commandCompletion.GetNextResult(rlResult == ReadLineResult.endedOnTab);
                    if (completionResult != null)
                    {
                        completedInput = string.Concat(completionInput.AsSpan(0, commandCompletion.ReplacementIndex), completionResult.CompletionText);
                    }
                    else
                    {
                        completedInput = completionInput;
                    }

                    if (restOfLine != string.Empty)
                    {
                        completedInput += restOfLine;
                    }

                    if (completedInput.Length > (MaxInputLineLength - 2))
                    {
                        completedInput = completedInput.Substring(0, MaxInputLineLength - 2);
                    }

                    // Remove any nulls from the string...
                    completedInput = RemoveNulls(completedInput);

                    // adjust the saved cursor position if the buffer scrolled as the user was typing (i.e. the user
                    // typed past the end of the buffer).

                    int linesOfInput = (endOfPromptCursorPos.X + input.Length) / screenBufferSize.Width;
                    endOfPromptCursorPos.Y = endOfInputCursorPos.Y - linesOfInput;

                    // replace the displayed input with the new input
                    try
                    {
                        RawUI.CursorPosition = endOfPromptCursorPos;
                    }
                    catch (PSArgumentOutOfRangeException)
                    {
                        // If we go a range exception, it's because
                        // there's no room in the buffer for the completed
                        // line so we'll just pretend that there was no match...
                        break;
                    }

                    // When the string is written to the console, a space character is actually appended to the string
                    // and the cursor will flash at the position of that space character.
                    WriteToConsole(completedInput, false);

                    Coordinates endOfCompletionCursorPos = RawUI.CursorPosition;

                    // adjust the starting cursor position if the screen buffer has scrolled as a result of writing the
                    // completed input (i.e. writing the completed input ran past the end of the buffer).

                    int linesOfCompletedInput = (endOfPromptCursorPos.X + completedInput.Length) / screenBufferSize.Width;
                    endOfPromptCursorPos.Y = endOfCompletionCursorPos.Y - linesOfCompletedInput;

                    // blank out any "leftover" old input.  That's everything between the cursor position at the time
                    // the user hit tab up to the current cursor position after writing the completed text.

                    int deltaInput =
                        (endOfInputCursorPos.Y * screenBufferSize.Width + endOfInputCursorPos.X)
                        - (endOfCompletionCursorPos.Y * screenBufferSize.Width + endOfCompletionCursorPos.X);

                    if (deltaInput > 0)
                    {
                        ConsoleControl.FillConsoleOutputCharacter(handle, ' ', deltaInput, endOfCompletionCursorPos);
                    }

                    if (restOfLine != string.Empty)
                    {
                        lastCompletion = completedInput.Remove(completedInput.Length - restOfLine.Length);
                        SendLeftArrows(restOfLine.Length);
                    }
                    else
                    {
                        lastCompletion = completedInput;
                    }

                    lastInput = completedInput;
                }
#endif
            }

            // Since we did not transcribe any call to ReadLine, transcribe the results here.

            if (_parent.IsTranscribing)
            {
                // Reads always terminate with the enter key, so add that.

                _parent.WriteLineToTranscript(input);
            }

            return input;
        }

#if !UNIX
        private static void SendLeftArrows(int length)
        {
            var inputs = new ConsoleControl.INPUT[length * 2];
            for (int i = 0; i < length; i++)
            {
                var down = new ConsoleControl.INPUT();
                down.Type = (uint)ConsoleControl.InputType.Keyboard;
                down.Data.Keyboard = new ConsoleControl.KeyboardInput();
                down.Data.Keyboard.Vk = (ushort)ConsoleControl.VirtualKeyCode.Left;
                down.Data.Keyboard.Scan = 0;
                down.Data.Keyboard.Flags = 0;
                down.Data.Keyboard.Time = 0;
                down.Data.Keyboard.ExtraInfo = IntPtr.Zero;

                var up = new ConsoleControl.INPUT();
                up.Type = (uint)ConsoleControl.InputType.Keyboard;
                up.Data.Keyboard = new ConsoleControl.KeyboardInput();
                up.Data.Keyboard.Vk = (ushort)ConsoleControl.VirtualKeyCode.Left;
                up.Data.Keyboard.Scan = 0;
                up.Data.Keyboard.Flags = (uint)ConsoleControl.KeyboardFlag.KeyUp;
                up.Data.Keyboard.Time = 0;
                up.Data.Keyboard.ExtraInfo = IntPtr.Zero;

                inputs[2 * i] = down;
                inputs[2 * i + 1] = up;
            }

            ConsoleControl.MimicKeyPress(inputs);
        }
#endif

        private CommandCompletion GetNewCompletionResults(string input)
        {
            try
            {
                var runspace = _parent.Runspace;
                var debugger = runspace.Debugger;

                if ((debugger != null) && debugger.InBreakpoint)
                {
                    // If in debug stop mode do command completion though debugger process command.
                    try
                    {
                        return CommandCompletion.CompleteInputInDebugger(input, input.Length, null, debugger);
                    }
                    catch (PSInvalidOperationException)
                    { }
                }

                if (runspace is LocalRunspace &&
                    runspace.ExecutionContext.EngineHostInterface.NestedPromptCount > 0)
                {
                    _commandCompletionPowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace);
                }
                else
                {
                    _commandCompletionPowerShell = PowerShell.Create();
                    _commandCompletionPowerShell.SetIsNested(_parent.IsNested);
                    _commandCompletionPowerShell.Runspace = runspace;
                }

                return CommandCompletion.CompleteInput(input, input.Length, null, _commandCompletionPowerShell);
            }
            finally
            {
                _commandCompletionPowerShell = null;
            }
        }

        private const string CustomReadlineCommand = "PSConsoleHostReadLine";

        private bool TryInvokeUserDefinedReadLine(out string input)
        {
            // We're using GetCommands instead of GetCommand so we don't auto-load a module should the command exist, but isn't loaded.
            // The idea is that if someone hasn't defined the command (say because they started -noprofile), we shouldn't auto-load
            // this function.

            var runspace = _parent.LocalRunspace;
            if (runspace != null &&
                runspace.Engine.Context.EngineIntrinsics.InvokeCommand.GetCommands(CustomReadlineCommand,
                    CommandTypes.Function | CommandTypes.Cmdlet, nameIsPattern: false).Any())
            {
                try
                {
                    PowerShell ps;
                    if ((runspace.ExecutionContext.EngineHostInterface.NestedPromptCount > 0) &&
                        (Runspace.DefaultRunspace != null))
                    {
                        ps = PowerShell.Create(RunspaceMode.CurrentRunspace);
                    }
                    else
                    {
                        ps = PowerShell.Create();
                        ps.Runspace = runspace;
                    }

                    var result = ps.AddCommand(CustomReadlineCommand).Invoke();
                    if (result.Count == 1)
                    {
                        input = PSObject.Base(result[0]) as string;
                        return true;
                    }
                }
                catch (Exception)
                {
                }
            }

            input = null;
            return false;
        }

        #endregion implementation

        // used to serialize access to instance data

        private readonly object _instanceLock = new object();

        // If this is true, class throws on read or prompt method which require
        // access to console.
        internal bool ThrowOnReadAndPrompt
        {
            set
            {
                _throwOnReadAndPrompt = value;
            }
        }

        private bool _throwOnReadAndPrompt;

        internal void HandleThrowOnReadAndPrompt()
        {
            if (_throwOnReadAndPrompt)
            {
                throw PSTraceSource.NewInvalidOperationException(ConsoleHostUserInterfaceStrings.ReadFailsOnNonInteractiveFlag);
            }
        }

        // this is a test hook for the ConsoleInteractiveTestTool, which sets this field to true.

        private readonly bool _isInteractiveTestToolListening;

        // This instance data is "read-only" and need not have access serialized.

        private readonly ConsoleHostRawUserInterface _rawui;
        private readonly ConsoleHost _parent;

        [TraceSource("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console")]
        private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console");
    }
}   // namespace