# All files engine.js

87.89% Statements 755/859
78.98% Branches 372/471
97.59% Functions 81/83
88.96% Lines 693/779

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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

    461x
    5x
    1x

    1x
    105x
    105x
    105x
    105x
    105x
    105x
    105x
    105x
    105x
    105x
    105x
    105x
    105x
    105x
    105x

    1x
    1x
    1x
    1x
    1x

    1x
    2379x

    1x
    1157x

    1x
    1522x

    1x
    109x

    1x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x
    122x

    1x
    8x
    8x

    1x
    2x
    2x

    1x
    3x
    3x

    1x
    1157x
    1157x
    1157x
    1157x
    1157x

    1x
    1x

    1x
    1x

    1x
    3x
    1x
    1x
    1x

    2x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x

    1x
    14x

    1x
    16x

    1x
    7283x
    3459x

    3824x
    3824x
    7620x
    6423x
    5581x
    5216x

    1x
    7283x
    3459x
    3459x

    3459x
    3459x
    3459x
    3459x
    76x
    76x
    19x

    57x

    76x
    76x

    3459x
    3459x
    3459x
    1822x
    669x
    596x
    596x

    73x
    73x

    73x

    1153x

    1070x

    3459x
    6100x
    824x
    824x
    82x

    742x

    824x
    10x
    814x
    14x
    824x

    5276x
    24x

    5252x
    5x
    5x

    5x
    5x

    6100x

    3459x
    47x

    3459x
    3459x

    3824x
    7620x

    1x
    11254x
    3459x
    3459x
    3459x
    3459x

    7795x
    13626x

    1x
    15x
    30x
    15x
    30x
    15x

    1x
    74x
    74x
    192x

    74x

    59x
    59x

    59x

    15x

    1x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x
    6x

    1x
    102x

    1x

    1x
    102x
    102x

    102x

    102x
    102x
    102x
    102x

    102x
    25x
    25x
    1x
    1x
    1x
    1x
    1x

    24x

    24x
    5x
    5x
    5x

    19x
    19x
    19x
    19x
    19x
    19x
    19x

    102x
    77x

    77x
    77x
    77x

    102x
    102x

    102x

    102x

    102x
    5x

    97x

    97x
    78x
    78x

    97x
    97x
    97x

    102x
    102x
    102x
    28x

    74x
    74x

    102x
    102x
    102x

    1x
    16x
    4x

    12x
    12x
    12x

    12x
    8x

    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x

    4x
    4x

    1x
    279x
    279x
    279x
    279x

    1x
    461x
    461x
    5x
    5x

    461x
    461x
    461x
    461x
    461x
    461x
    4x
    4x

    1x
    3x

    1x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x

    2x
    2x
    2x

    2x

    1x
    4x

    4x
    4x
    4x
    4x
    4x
    4x
    4x
    4x

    4x

    1x
    2x
    2x
    2x
    2x
    2x
    2x
    4x
    4x
    4x

    2x
    2x
    2x

    1x
    9x
    9x
    15x

    9x
    6x
    6x

    3x
    3x
    3x
    3x

    3x
    3x
    3x
    3x
    3x

    1x
    4x
    4x
    4x
    4x
    4x
    4x

    1x
    214x
    214x
    214x

    1x
    13x
    13x
    9x
    9x
    9x
    17x
    17x

    9x
    8x
    6x

    2x

    1x
    1x

    1x

    9x
    9x
    9x

    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    10x
    5x
    5x

    10x
    1x
    1x
    1x
    1x
    1x

    9x
    9x

    10x

    1x
    19x
    19x
    8x
    11x
    11x

    1x
    7x
    4x
    4x

    7x

    7x
    7x

    7x

    1x
    2x
    5x
    1x
    1x
    5x
    3x
    1x

    1x
    2x
    2x
    2x

    2x
    2x
    2x
    2x

    2x
    2x
    2x
    2x
    2x

    2x
    2x

    1x
    19x
    19x
    19x
    19x
    19x
    19x
    29x

    19x

    19x
    9x
    9x
    9x
    9x
    9x

    9x
    9x
    9x
    9x

    9x
    9x
    9x
    6x
    9x

    9x
    9x
    9x
    9x
    9x

    10x
    4x

    6x
    6x
    6x
    6x
    10x
    10x
    10x

    10x
    10x
    10x
    10x

    10x
    10x

    1x
    1x
    1x
    3x

    1x

    1x

    1x
    1x
    1x

    1x
    1x

    1x

    1x
    1x
    1x
    2x

    1x
    2x
    2x
    2x

    1x

    1x
    1x
    1x
    4x

    1x

    1x
    1x
    1x

    1x
    1x
    1x

    1x
    1x
    1x
    3x

    1x
    1x
    1x
    1x

    1x
    50x
    50x
    38x
    38x
    37x
    37x

    1x

    12x

    1x
    2x
    2x

    1x
    17x
    17x
    9x
    9x
    8x
    8x

    1x

    8x

    1x
    2x
    2x
    2x
    3x
    3x

    2x
    2x
    2x
    2x
    2x

    2x
    2x
    2x

    1x

    6x
    3x
    3x

    3x

    1x
    1x

    2x

    2x

    1x
    1x

    1x

    1x
    1x

    1x
    1x

    6x

    1x

    3x
    2x

    1x

    1x
    1x

    3x

    1x
    8x
    2x
    2x
    2x

    6x
    6x

    1x
    3x

    3x
    3x

    1x
    1x
    1x

    1x
    1x
    1x

    1x
    4x
    4x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    5x
    5x

    1x
    1x

    1x
    3x
    3x
    1x
    1x
    1x
    1x
    4x
    4x

    1x
    1x

    2x

    1x
    3x
    3x

    1x
    1x
    1x

    1x
    828x
    828x
    828x
    828x
    828x
    828x
    828x
    828x
    828x
    828x
    828x

    1x
    6x
    6x
    6x
    6x

    1x
    6x
    6x

    1x
    7x
    7x
    5x
    5x
    5x
    5x
    5x

    1x
    2x
    2x
    1x
    1x
    1x
    1x
    1x

    1x
    3x
    2x
    1x
    1x

    1x

    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x

    1x

    1x
    1x
    1x

    1x
    1x

    1x
    102x
    102x

    102x

    1x
    459x
    459x
    432x
    432x
    432x
    8x
    8x
    8x
    8x
    8x

    424x
    424x
    768x
    54x
    54x

    714x

    432x

    55x
    55x
    55x
    55x
    55x
    55x

    55x

     import Doc from './doc.js';
    import Keyboard from './keyboard.js';
    import Settings from './settings.js';
    import Symbols from './symbols.js';
    import Utils from './utils.js';

    String.prototype.splice = function(idx, s){ return (this.slice(0,idx) + s + this.slice(idx)); };
    String.prototype.splicen = function(idx, s, n){ return (this.slice(0,idx) + s + this.slice(idx+n));};
    String.prototype.search_at = function(idx, s){ return (this.substring(idx-s.length,idx) == s); };

    /**
     * @class
     * @classdesc The engine for scripting the editor.  To access the
     * engine for scripting a particular Guppy instance, say called
     * `"guppy1"`, do `Guppy("guppy1").engine`.
     *
     * At that point, you can, for example, move that editor's cursor
     * one spot to the left with `Guppy("guppy1").engine.left()`.
    */
    var Engine = function(parent){
        this.parent = parent;
        this.symbols = {};
        this.events = {};
        this.settings = {};
        this.doc = new Doc();
        this.current = this.doc.root().firstChild;
        this.caret = 0;
        this.space_caret = 0;
        this.sel_start = null;
        this.sel_end = null;
        this.undo_data = [];
        this.undo_now = -1;
        this.sel_status = Engine.SEL_NONE;
        this.checkpoint();
        this.symbols = JSON.parse(JSON.stringify(Symbols.symbols));
    }

    Engine.kb_info = new Keyboard();
    Engine.SEL_NONE = 0;
    Engine.SEL_CURSOR_AT_START = 1;
    Engine.SEL_CURSOR_AT_END = 2;
    Engine.clipboard = null;

    Engine.prototype.setting = function(name){
        return name in this.settings ? this.settings[name] : Settings.config.settings[name];
    }

    Engine.prototype.event = function(name){
        return name in this.events ? this.events[name] : Settings.config.events[name];
    }

    /**
        Get the content of the editor
        @memberof Engine
        @param {string} t - The type of content to render ("latex", "text", or "xml").
    */
    Engine.prototype.get_content = function(t,r){
        return this.doc.get_content(t,r);
    }

    /**
        Set the XML content of the editor
        @memberof Engine
        @param {string} xml_data - An XML string of the content to place in the editor
    */
    Engine.prototype.set_content = function(xml_data){
        this.set_doc(new Doc(xml_data));
    }

    /**
        Set the document of the editor
        @memberof Engine
        @param {Doc} doc - The Doc that will be the editor's source
    */
    Engine.prototype.set_doc = function(doc){
        this.doc = doc;
        this.current = this.doc.root().firstChild;
        this.caret = 0;
        this.sel_start = null;
        this.sel_end = null;
        this.undo_data = [];
        this.undo_now = -1;
        this.sel_status = Engine.SEL_NONE;
        this.checkpoint();
    }

    Engine.prototype.import_text = function(text){
        this.doc.import_text(text, this.symbols);
        this.set_doc(this.doc);
    }

    Engine.prototype.import_latex = function(text){
        this.doc.import_latex(text, this.symbols);
        this.set_doc(this.doc);
    }

    Engine.prototype.import_ast = function(ast){
        this.doc.import_ast(ast, this.symbols);
        this.set_doc(this.doc);
    }

    Engine.prototype.fire_event = function(event, args){
        args = args || {};
        args.target = this.parent || this;
        args.type = event;
        var ev = this.event(event);
        Eif(ev) ev(args);
    }

    /**
        Remove a symbol from this instance of the editor.
        @memberof Engine
        @param {string} name - The name of the symbol to remove.
    */
    Engine.prototype.remove_symbol = function(name){
        Eif(this.symbols[name]) delete this.symbols[name];
    }

    /**
        Add a symbol to this instance of the editor.
        @memberof Engine
        @param {string} name - param
        @param {Object} symbol - If `template` is present, this is the
        template arguments.  Otherwise, it is a complete specification
        of the symbol, the format for which can be found in the
        documentation for Guppy.add_global_symbol.
        @param {string} [template] - The name of the template to use.
    */
    Engine.prototype.add_symbol = function(name, symbol){
        this.symbols[name] = symbol;
    }

    Engine.prototype.select_to = function(loc, sel_cursor, sel_caret, mouse){
        if(loc.current == sel_cursor && loc.caret == sel_caret){
            this.current = loc.current;
            this.caret = loc.caret;
            this.sel_status = Engine.SEL_NONE;
        }
        else if(loc.pos == "left"){
            this.sel_end = {"node":sel_cursor,"caret":sel_caret};
            this.current = loc.current;
            this.caret = loc.caret;
            this.set_sel_boundary(Engine.SEL_CURSOR_AT_START, mouse);
        }
        else Eif(loc.pos == "right"){
            this.sel_start = {"node":sel_cursor,"caret":sel_caret};
            this.current = loc.current;
            this.caret = loc.caret;
            this.set_sel_boundary(Engine.SEL_CURSOR_AT_END, mouse);
        }
    }

    Engine.prototype.set_sel_start = function(){
        this.sel_start = {"node":this.current, "caret":this.caret};
    }

    Engine.prototype.set_sel_end = function(){
        this.sel_end = {"node":this.current, "caret":this.caret};
    }

    Engine.prototype.add_paths = function(n,path){
        if(n.nodeName == "e"){
            n.setAttribute("path",path);
        }
        else{
            var es = 1, fs = 1, cs = 1, ls = 1;
            for(var c = n.firstChild; c != null; c = c.nextSibling){
                if(c.nodeName == "c"){ this.add_paths(c, path+"_c"+cs); cs++; }
                else if(c.nodeName == "f"){ this.add_paths(c, path+"_f"+fs); fs++; }
                else if(c.nodeName == "l"){ this.add_paths(c, path+"_l"+ls); ls++; }
                else if(c.nodeName == "e"){ this.add_paths(c, path+"_e"+es); es++; }
            }
        }
    }

    Engine.prototype.add_classes_cursors = function(n){
        if(n.nodeName == "e"){
            var text = n.firstChild.nodeValue;
            var ans = "";
            var sel_cursor;
    	var text_node = Utils.is_text(n);
            if(this.sel_status == Engine.SEL_CURSOR_AT_START) sel_cursor = this.sel_end;
            if(this.sel_status == Engine.SEL_CURSOR_AT_END) sel_cursor = this.sel_start;
            if(this.sel_status != Engine.SEL_NONE){
                var sel_caret_text = Utils.is_small(sel_cursor.node) ? Utils.SMALL_SEL_CARET : Utils.SEL_CARET;
                if(text.length == 0 && n.parentNode.childElementCount > 1){
                    sel_caret_text = "\\blue{\\xmlClass{guppy_elt guppy_blank guppy_loc_"+n.getAttribute("path")+"_0}{"+sel_caret_text+"}}";
                }
                else{
                    sel_caret_text = "\\blue{"+sel_caret_text+"}";
                }
                if(this.sel_status == Engine.SEL_CURSOR_AT_END) sel_caret_text = sel_caret_text + "\\"+Utils.SEL_COLOR+"{";
                if(this.sel_status == Engine.SEL_CURSOR_AT_START) sel_caret_text = "}" + sel_caret_text;
            }
            var caret_text = "";
            var temp_caret_text = "";
            if(text.length == 0){
                if(n.parentNode.childElementCount == 1){
                    if(this.current == n){
                        var blank_caret = this.setting("blank_caret") || (Utils.is_small(this.current) ? Utils.SMALL_CARET : Utils.CARET);
                        ans = "\\red{\\xmlClass{main_cursor guppy_elt guppy_blank guppy_loc_"+n.getAttribute("path")+"_0"+"}{"+blank_caret+"}}";
                    }
                    else{
                        var blank_placeholder = this.setting("blank_placeholder") || "[?]";
                        Iif(this.temp_cursor.node == n)
                            ans = "\\gray{\\xmlClass{guppy_elt guppy_blank guppy_loc_"+n.getAttribute("path")+"_0"+"}{"+blank_placeholder+"}}";
                        else
                            ans = "\\blue{\\xmlClass{guppy_elt guppy_blank guppy_loc_"+n.getAttribute("path")+"_0"+"}{"+blank_placeholder+"}}";
                    }
                }
                else if(this.temp_cursor.node != n && this.current != n && (!(sel_cursor) || sel_cursor.node != n)){
                    // These are the empty e elements at either end of
                    // a c or m node, such as the space before and
                    // after both the sin and x^2 in sin(x^2)
                    //
                    // Here, we add in a small element so that we can
                    // use the mouse to select these areas
                    ans = "\\phantom{\\xmlClass{guppy_elt guppy_blank guppy_loc_"+n.getAttribute("path")+"_0"+"}{\\hspace{0pt}}}";
                }
            }
            for(var i = 0; i < text.length+1; i++){
                if(n == this.current && i == this.caret && (text.length > 0 || n.parentNode.childElementCount > 1)){
                    caret_text = Utils.is_small(this.current) ? Utils.SMALL_CARET : Utils.CARET;
                    if(text.length == 0)
                        caret_text = "\\red{\\xmlClass{main_cursor guppy_elt guppy_blank guppy_loc_"+n.getAttribute("path")+"_0}{"+caret_text+"}}";
                    else{
                        caret_text = "\\red{\\xmlClass{main_cursor}{"+caret_text+"}}"
                    }
                    if(this.sel_status == Engine.SEL_CURSOR_AT_START)
                        caret_text = caret_text + "\\"+Utils.SEL_COLOR+"{";
                    else if(this.sel_status == Engine.SEL_CURSOR_AT_END)
                        caret_text = "}" + caret_text;
                    ans += caret_text;
                }
                else if(this.sel_status != Engine.SEL_NONE && sel_cursor.node == n && i == sel_cursor.caret){
                    ans += sel_caret_text;
                }
                else if(this.temp_cursor.node == n && i == this.temp_cursor.caret && (text.length > 0 || n.parentNode.childElementCount > 1)){
                    temp_caret_text = Utils.is_small(this.current) ? Utils.TEMP_SMALL_CARET : Utils.TEMP_CARET;
                    Iif(text.length == 0){
                        temp_caret_text = "\\gray{\\xmlClass{guppy_elt guppy_blank guppy_loc_"+n.getAttribute("path")+"_0}{"+temp_caret_text+"}}";
                        }
                    else
                        temp_caret_text = "\\gray{"+temp_caret_text+"}";
                    ans += temp_caret_text;
                }
                if(i < text.length) ans += "\\xmlClass{guppy_elt guppy_loc_"+n.getAttribute("path")+"_"+i+"}{"+text[i]+"}";
            }
            if(text_node && n == this.current){
                ans = "\\xmlClass{guppy_text_current}{{"+ans+"}}";
            }
            n.setAttribute("render", ans);
            n.removeAttribute("path");
        }
        else{
            for(var c = n.firstChild; c != null; c = c.nextSibling){
                if(c.nodeName == "c" || c.nodeName == "l" || c.nodeName == "f" || c.nodeName == "e"){ this.add_classes_cursors(c); }
            }
        }
    }

    Engine.prototype.remove_cursors_classes = function(n){
        if(n.nodeName == "e"){
            n.removeAttribute("path");
            n.removeAttribute("render");
            n.removeAttribute("current");
            n.removeAttribute("temp");
        }
        else{
            for(var c = n.firstChild; c != null; c = c.nextSibling){
                if(c.nodeType == 1){ this.remove_cursors_classes(c); }
            }
        }
    }

    Engine.prototype.down_from_f = function(){
        var nn = this.current.firstChild;
        while(nn != null && nn.nodeName != 'c' && nn.nodeName != 'l') nn = nn.nextSibling;
        Eif(nn != null){
            while(nn.nodeName == 'l') nn = nn.firstChild;
            this.current = nn.firstChild;
        }
    }

    Engine.prototype.down_from_f_to_blank = function(){
        var nn = this.current.firstChild;
        while(nn != null && !(nn.nodeName == 'c' && nn.children.length == 1 && nn.firstChild.firstChild.nodeValue == "")){
            nn = nn.nextSibling;
        }
        if(nn != null){
            //Sanity check:

            while(nn.nodeName == 'l') nn = nn.firstChild;
            Iif(nn.nodeName != 'c' || nn.firstChild.nodeName != 'e'){
                this.problem('dfftb');
                return;
            }
            this.current = nn.firstChild;
        }
        else this.down_from_f();
    }

    Engine.prototype.delete_from_f = function(to_insert){
        var n = this.current;
        var p = n.parentNode;
        var prev = n.previousSibling;
        var next = n.nextSibling;
        var middle = to_insert || "";
        var new_node = this.make_e(prev.firstChild.textContent + middle + next.firstChild.textContent);
        this.current = new_node;
        this.caret = prev.firstChild.textContent.length;
        p.insertBefore(new_node, prev);
        p.removeChild(prev);
        p.removeChild(n);
        p.removeChild(next);
    }

    Engine.prototype.symbol_to_node = function(sym, content){
        return Symbols.symbol_to_node(sym, content, this.doc.base);
    }

    Engine.prototype.template_to_node = function(tmpl_name, content, name, tmpl_args){
        return Symbols.symbol_to_node(Symbols.make_template_symbol(tmpl_name, name, tmpl_args), content, this.doc.base);
    }

    /**
        Insert a symbol into the document at the current cursor position.
        @memberof Engine
        @param {string} sym_name - The name of the symbol to insert.
        Should match one of the keys in the symbols JSON object
    */
    Engine.prototype.insert_symbol = function(sym_name,sym_args){
        var s = sym_args ? Symbols.make_template_symbol(sym_name, sym_args.name, sym_args) : this.symbols[sym_name];
        Iif(s.attrs && this.is_blacklisted(s.attrs.type)){
            return false;
        }
        var content = {};
        var left_piece,right_piece;
        var cur = "input" in s ? s.input : 0;
        var to_remove = [];
        var to_replace = null;
        var replace_f = false;
        var sel;

        if(cur > 0){
            cur--;
            if(this.sel_status != Engine.SEL_NONE){
                sel = this.sel_get();
                to_remove = sel.involved;
                left_piece = this.make_e(sel.remnant.firstChild.nodeValue.slice(0,this.sel_start.caret));
                right_piece = this.make_e(sel.remnant.firstChild.nodeValue.slice(this.sel_start.caret));
                content[cur] = sel.node_list;
            }
            else Eif("input" in s){
                // If we're at the beginning, then the token is the previous f node
                if(this.caret == 0 && this.current.previousSibling != null){
                    content[cur] = [this.make_e(""), this.current.previousSibling, this.make_e("")];
                    to_replace = this.current.previousSibling;
                    replace_f = true;
                }
                else{
                    // look for [0-9.]+|[a-zA-Z] immediately preceeding the caret and use that as token
                    var prev = this.current.firstChild.nodeValue.substring(0,this.caret);
                    var token = prev.charCodeAt(prev.length-1) > 128 ? prev[prev.length-1] : prev.match(/[0-9.]+$|[a-zA-Z]$/);
                    Eif(token != null && token.length > 0){
                        token = token[0];
                        left_piece = this.make_e(this.current.firstChild.nodeValue.slice(0,this.caret-token.length));
                        right_piece = this.make_e(this.current.firstChild.nodeValue.slice(this.caret));
                        content[cur] = [this.make_e(token)];
                    }
                }
            }
        }
        if(!replace_f && (left_piece == null || right_piece == null)){
            Iif(this.sel_status != Engine.SEL_NONE){
                sel = this.sel_get();
                to_remove = sel.involved;
                left_piece = this.make_e(sel.remnant.firstChild.nodeValue.slice(0,this.sel_start.caret));
                right_piece = this.make_e(sel.remnant.firstChild.nodeValue.slice(this.sel_start.caret));
                content = "input" in s && s.input < 0 ? [] : [sel.node_list];
            }
            else{
                left_piece = this.make_e(this.current.firstChild.nodeValue.slice(0,this.caret));
                right_piece = this.make_e(this.current.firstChild.nodeValue.slice(this.caret));
                to_remove = [this.current];
            }
        }

        // By now:
        //
        // content contains whatever we want to pre-populate the 'current' field with (if any)
        //
        // right_piece contains whatever content was in an involved node
        // to the right of the cursor but is not part of the insertion.
        // Analogously for left_piece
        //
        // Thus all we should have to do now is symbol_to_node(sym_type,
        // content) and then add the left_piece, resulting node, and
        // right_piece in that order.
        var sym = this.symbol_to_node(s,content);
        var current_parent = this.current.parentNode;

        var f = sym.f;

        var next = this.current.nextSibling;

        if(replace_f){
            current_parent.replaceChild(f,to_replace);
        }
        else{
            if(to_remove.length == 0) this.current.parentNode.removeChild(this.current);

            for(var i = 0; i < to_remove.length; i++){
                Iif(next == to_remove[i]) next = next.nextSibling;
                current_parent.removeChild(to_remove[i]);
            }
            current_parent.insertBefore(left_piece, next);
            current_parent.insertBefore(f, next);
            current_parent.insertBefore(right_piece, next);
        }

        this.caret = 0;
        this.current = f;
        if(sym.args.length == 0 || ("input" in s && s.input >= sym.args.length)){
            this.current = this.current.nextSibling;
        }
        else{
            this.down_from_f_to_blank();
            this.caret = this.current.firstChild.textContent.length;
        }

        this.sel_clear();
        this.checkpoint();
        return true;
    }

    Engine.prototype.sel_get = function(){
        if(this.sel_status == Engine.SEL_NONE){
            return null;
        }
        var involved = [];
        var node_list = [];
        var remnant = null;

        if(this.sel_start.node == this.sel_end.node){
            return {"node_list":[this.make_e(this.sel_start.node.firstChild.nodeValue.substring(this.sel_start.caret, this.sel_end.caret))],
                    "remnant":this.make_e(this.sel_start.node.firstChild.nodeValue.substring(0, this.sel_start.caret) + this.sel_end.node.firstChild.nodeValue.substring(this.sel_end.caret)),
                    "involved":[this.sel_start.node]};
        }

        node_list.push(this.make_e(this.sel_start.node.firstChild.nodeValue.substring(this.sel_start.caret)));
        involved.push(this.sel_start.node);
        involved.push(this.sel_end.node);
        remnant = this.make_e(this.sel_start.node.firstChild.nodeValue.substring(0, this.sel_start.caret) + this.sel_end.node.firstChild.nodeValue.substring(this.sel_end.caret));
        var n = this.sel_start.node.nextSibling;
        while(n != null && n != this.sel_end.node){
            involved.push(n);
            node_list.push(n);
            n = n.nextSibling;
        }
        node_list.push(this.make_e(this.sel_end.node.firstChild.nodeValue.substring(0, this.sel_end.caret)));
        return {"node_list":node_list,
                "remnant":remnant,
                "involved":involved,
                "cursor":0};
    }

    Engine.prototype.make_e = function(text){
        var base = this.doc.base;
        var new_node = base.createElement("e");
        new_node.appendChild(base.createTextNode(text));
        return new_node;
    }

    /**
        Insert a string into the document at the current cursor position.
        @memberof Engine
        @param {string} s - The string to insert.
    */
    Engine.prototype.insert_string = function(s){
        var self = this;
        if(this.sel_status != Engine.SEL_NONE){
            this.sel_delete();
            this.sel_clear();
        }
        this.current.firstChild.nodeValue = this.current.firstChild.nodeValue.splice(this.caret,s)
        this.caret += s.length;
        this.checkpoint();
        if(this.setting("autoreplace") == "auto") this.check_for_symbol(false);
        if(this.setting("autoreplace") == "whole") this.check_for_symbol(true);
        if(this.setting("autoreplace") == "delay" && setTimeout){
            if(this.delayed_check) clearTimeout(this.delayed_check);
            this.delayed_check = setTimeout(function(){ self.check_for_symbol(false); }, 200);
        }
    }

    /**
        Insert a copy of the given document into the editor at the current cursor position.
        @memberof Engine
        @param {Doc} doc - The document to insert.
    */
    Engine.prototype.insert_doc = function(doc){
        this.insert_nodes(doc.root().childNodes, true);
    }

    /**
        Copy the current selection, leaving the document unchanged but
        placing the contents of the current selection on the clipboard.
        @memberof Engine
    */
    Engine.prototype.sel_copy = function(){
        var sel = this.sel_get();
        Iif(!sel) return;
        Engine.clipboard = [];
        var cliptype = this.setting("cliptype");
        Eif(cliptype != "none") var clip_doc = new Doc("<m></m>");
        for(var i = 0; i < sel.node_list.length; i++){
            var node = sel.node_list[i].cloneNode(true);
            Engine.clipboard.push(node);
            Eif(cliptype != "none") clip_doc.root().appendChild(node.cloneNode(true));//clip_text += this.doc.manual_render(cliptype, node);
        }
        Eif(cliptype != "none"){
            try{
                this.system_copy(clip_doc.get_content(cliptype));
            }
            catch(e){
                this.system_copy("Syntax error");
            }
        }
        this.sel_clear();
    }

    Engine.prototype.system_copy = function(text) {
        Iif (window.clipboardData && window.clipboardData.setData)
            return window.clipboardData.setData("Text", text);
        else Eif (document.queryCommandSupported && document.queryCommandSupported("copy")) {
            var textarea = document.createElement("textarea");
            textarea.textContent = text;
            textarea.style.position = "fixed";
            textarea.style.background = "transparent";
            document.body.appendChild(textarea);
            textarea.select();
            try { return document.execCommand("copy"); }
            catch (ex) { return false; }
            finally { document.body.removeChild(textarea); }
        }
    }

    /**
        Cut the current selection, removing it from the document and placing it in the clipboard.
        @memberof Engine
    */
    Engine.prototype.sel_cut = function(){
        var node_list = this.sel_delete();
        Iif(!node_list) return;
        Engine.clipboard = [];
        var cliptype = this.setting("cliptype");
        var clip_text = "";
        for(var i = 0; i < node_list.length; i++){
            var node = node_list[i].cloneNode(true);
            Engine.clipboard.push(node);
            Eif(cliptype != "none") clip_text += this.doc.manual_render(cliptype, node);
        }
        Eif(cliptype != "none") this.system_copy(clip_text);
        this.sel_clear();
        this.checkpoint();
    }

    Engine.prototype.insert_nodes = function(node_list, move_cursor){
        var real_clipboard = [];
        for(var i = 0; i < node_list.length; i++){
            real_clipboard.push(node_list[i].cloneNode(true));
        }

        if(real_clipboard.length == 1){
            this.current.firstChild.nodeValue = this.current.firstChild.nodeValue.substring(0,this.caret) + real_clipboard[0].firstChild.nodeValue + this.current.firstChild.nodeValue.substring(this.caret);
            if(move_cursor) this.caret += real_clipboard[0].firstChild.nodeValue.length;
        }
        else{
            var nn = this.make_e(real_clipboard[real_clipboard.length-1].firstChild.nodeValue + this.current.firstChild.nodeValue.substring(this.caret));
            this.current.firstChild.nodeValue = this.current.firstChild.nodeValue.substring(0,this.caret) + real_clipboard[0].firstChild.nodeValue;
            Eif(this.current.nextSibling == null)
                this.current.parentNode.appendChild(nn)
            else
                this.current.parentNode.insertBefore(nn, this.current.nextSibling)
            for(var j = 1; j < real_clipboard.length - 1; j++)
                this.current.parentNode.insertBefore(real_clipboard[j], nn);
            Eif(move_cursor){
                this.current = nn;
                this.caret = real_clipboard[real_clipboard.length-1].firstChild.nodeValue.length
            }
        }
    }

    /**
        Paste the current contents of the clipboard.
        @memberof Engine
    */
    Engine.prototype.sel_paste = function(){
        this.sel_delete();
        this.sel_clear();
        Iif(!(Engine.clipboard) || Engine.clipboard.length == 0) return;
        this.insert_nodes(Engine.clipboard, true);
        this.checkpoint();
        return;
    }

    /**
        Clear the current selection, leaving the document unchanged and
        nothing selected.
        @memberof Engine
    */
    Engine.prototype.sel_clear = function(){
        this.sel_start = null;
        this.sel_end = null;
        this.sel_status = Engine.SEL_NONE;
    }

    /**
        Delete the current selection.
        @memberof Engine
    */
    Engine.prototype.sel_delete = function(){
        var sel = this.sel_get();
        if(!sel) return null;
        var sel_parent = sel.involved[0].parentNode;
        var sel_prev = sel.involved[0].previousSibling;
        for(var i = 0; i < sel.involved.length; i++){
            var n = sel.involved[i];
            sel_parent.removeChild(n);
        }
        if(sel_prev == null){
            if(sel_parent.firstChild == null)
                sel_parent.appendChild(sel.remnant);
            else
                sel_parent.insertBefore(sel.remnant, sel_parent.firstChild);
        }
        else Eif(sel_prev.nodeName == 'f'){
            Iif(sel_prev.nextSibling == null)
                sel_parent.appendChild(sel.remnant);
            else
                sel_parent.insertBefore(sel.remnant, sel_prev.nextSibling);
        }
        this.current = sel.remnant
        this.caret = this.sel_start.caret;
        return sel.node_list;
    }

    /**
        Select the entire contents of the editor.
        @memberof Engine
    */
    Engine.prototype.sel_all = function(){
        this.home();
        this.set_sel_start();
        this.end();
        this.set_sel_end();
        Eif(this.sel_start.node != this.sel_end.node || this.sel_start.caret != this.sel_end.caret)
            this.sel_status = Engine.SEL_CURSOR_AT_END;
    }

    /**
        function
        @memberof Engine
        @param {string} name - param
    */
    Engine.prototype.sel_right = function(){
        if(this.sel_status == Engine.SEL_NONE){
            this.set_sel_start();
            this.sel_status = Engine.SEL_CURSOR_AT_END;
        }
        if(this.caret >= Utils.get_length(this.current)){
            var nn = this.current.nextSibling;
            Eif(nn != null){
                this.current = nn.nextSibling;
                this.caret = 0;
                this.set_sel_boundary(Engine.SEL_CURSOR_AT_END);
            }
            else{
                this.set_sel_boundary(Engine.SEL_CURSOR_AT_END);
            }
        }
        else{
            this.caret += 1;
            this.set_sel_boundary(Engine.SEL_CURSOR_AT_END);
        }
        Iif(this.sel_start.node == this.sel_end.node && this.sel_start.caret == this.sel_end.caret){
            this.sel_status = Engine.SEL_NONE;
        }
    }

    Engine.prototype.set_sel_boundary = function(sstatus, mouse){
        if(this.sel_status == Engine.SEL_NONE || mouse) this.sel_status = sstatus;
        if(this.sel_status == Engine.SEL_CURSOR_AT_START)
            this.set_sel_start();
        else Eif(this.sel_status == Engine.SEL_CURSOR_AT_END)
            this.set_sel_end();
    }

    /**
        Move the cursor to the left, adjusting the selection along with
        the cursor.
        @memberof Engine
    */
    Engine.prototype.sel_left = function(){
        if(this.sel_status == Engine.SEL_NONE){
            this.set_sel_end();
            this.sel_status = Engine.SEL_CURSOR_AT_START;
        }
        Iif(this.caret <= 0){
            var nn = this.current.previousSibling;
            if(nn != null){
                this.current = nn.previousSibling;
                this.caret = this.current.firstChild.nodeValue.length;
                this.set_sel_boundary(Engine.SEL_CURSOR_AT_START);
            }
            else{
                this.set_sel_boundary(Engine.SEL_CURSOR_AT_START);
            }
        }
        else{
            this.caret -= 1;
            this.set_sel_boundary(Engine.SEL_CURSOR_AT_START);
        }
        Iif(this.sel_start.node == this.sel_end.node && this.sel_start.caret == this.sel_end.caret){
            this.sel_status = Engine.SEL_NONE;
        }
    }

    Engine.prototype.list_extend_copy_right = function(){this.list_extend("right", true);}
    Engine.prototype.list_extend_copy_left = function(){this.list_extend("left", true);}
    Engine.prototype.list_extend_right = function(){this.list_extend("right", false);}
    Engine.prototype.list_extend_left = function(){this.list_extend("left", false);}
    Engine.prototype.list_extend_up = function(){this.list_extend("up", false);}
    Engine.prototype.list_extend_down = function(){this.list_extend("down", false);}
    Engine.prototype.list_extend_copy_up = function(){this.list_extend("up", true);}
    Engine.prototype.list_extend_copy_down = function(){this.list_extend("down", true);}

    /**
        Move the cursor by one row up or down in a matrix.
        @memberof Engine
        @param {boolean} down - If `true`, move down in the matrix;
        otherwise, up.
    */
    Engine.prototype.list_vertical_move = function(down){
        var n = this.current;
        while(n.parentNode && n.parentNode.parentNode && !(n.nodeName == 'c' && n.parentNode.nodeName == 'l' && n.parentNode.parentNode.nodeName == 'l')){
            n = n.parentNode;
        }
        Iif(!n.parentNode) return;
        var pos = 1;
        var cc = n;
        while(cc.previousSibling != null){
            pos++;
            cc = cc.previousSibling;
        }
        var new_l = down ? n.parentNode.nextSibling : n.parentNode.previousSibling
        Iif(!new_l) return;
        var idx = 1;
        var nn = new_l.firstChild;
        while(idx < pos){
            idx++;
            nn = nn.nextSibling;
        }
        this.current = nn.firstChild;
        this.caret = down ? 0 : this.current.firstChild.textContent.length;
    }

    /**
        Add an element to a list (or row/column to a matrix) in the
        specified direction.  Can optionally copy the current
        element/row/column to the new one.
        @memberof Engine
        @param {string} direction - One of `"up"`, `"down"`, `"left"`, or
        `"right"`.
        @param {boolean} copy - Whether or not to copy the current
        element/row/column into the new one.
    */
    Engine.prototype.list_extend = function(direction, copy){
        var base = this.doc.base;
        var vertical = direction == "up" || direction == "down";
        var before = direction == "up" || direction == "left";
        var this_name = vertical ? "l" : "c";
        var n = this.current;
        while(n.parentNode && !(n.nodeName == this_name && n.parentNode.nodeName == 'l')){
            n = n.parentNode;
        }
        Iif(!n.parentNode) return;
        var to_insert;

        // check if 2D and horizontal and extend all the other rows if so
        if(!vertical && n.parentNode.parentNode.nodeName == "l"){
            to_insert = base.createElement("c");
            to_insert.appendChild(this.make_e(""));
            var pos = 1;
            var cc = n;
            while(cc.previousSibling != null){
                pos++;
                cc = cc.previousSibling;
            }
            var to_modify = [];
            var iterator = this.doc.xpath_list("./l/c[position()="+pos+"]", n.parentNode.parentNode);
            var nn = null;
            try{ for(nn = iterator.iterateNext(); nn != null; nn = iterator.iterateNext()){ to_modify.push(nn); }}
            catch(e) { this.fire_event("error",{"message":'XML modified during iteration? ' + e}); }
            for(var j = 0; j < to_modify.length; j++){
                nn = to_modify[j];
                if(copy) nn.parentNode.insertBefore(nn.cloneNode(true), before ? nn : nn.nextSibling);
                else nn.parentNode.insertBefore(to_insert.cloneNode(true), before ? nn : nn.nextSibling);
                nn.parentNode.setAttribute("s",parseInt(nn.parentNode.getAttribute("s"))+1);
            }
            this.sel_clear();
            this.current = before ? n.previousSibling.lastChild : n.nextSibling.firstChild;
            this.caret = this.current.firstChild.textContent.length;
            this.checkpoint();
            return;
        }

        if(copy){
            to_insert = n.cloneNode(true);
        }
        else{
            Eif(vertical){
                to_insert = base.createElement("l");
                to_insert.setAttribute("s",n.getAttribute("s"))
                for(var i = 0; i < parseInt(n.getAttribute("s")); i++){
                    var c = base.createElement("c");
                    c.appendChild(this.make_e(""));
                    to_insert.appendChild(c);
                }
            }
            else{
                to_insert = base.createElement("c");
                to_insert.appendChild(this.make_e(""));
            }
        }
        n.parentNode.setAttribute("s",parseInt(n.parentNode.getAttribute("s"))+1);
        n.parentNode.insertBefore(to_insert, before ? n : n.nextSibling);
        this.sel_clear();
        Eif(vertical) this.current = to_insert.firstChild.firstChild;
        else this.current = to_insert.firstChild;
        this.caret = 0;
        this.checkpoint();
    }

    /**
        Remove the current column from a matrix
        @memberof Engine
    */
    Engine.prototype.list_remove_col = function(){
        var n = this.current;
        while(n.parentNode && n.parentNode.parentNode && !(n.nodeName == 'c' && n.parentNode.nodeName == 'l' && n.parentNode.parentNode.nodeName == 'l')){
            n = n.parentNode;
        }
        Iif(!n.parentNode) return;

        // Don't remove if there is only a single column:
        Iif(n.previousSibling != null){
            this.current = n.previousSibling.lastChild;
            this.caret = n.previousSibling.lastChild.firstChild.textContent.length;
        }
        else Eif(n.nextSibling != null){
            this.current = n.nextSibling.firstChild;
            this.caret = 0;
        }
        else return;

        var pos = 1;
        var cc = n;

        // Find position of column
        while(cc.previousSibling != null){
            pos++;
            cc = cc.previousSibling;
        }
        var to_modify = [];
        var iterator = this.doc.xpath_list("./l/c[position()="+pos+"]", n.parentNode.parentNode)
        var nn = null;
        try{ for(nn = iterator.iterateNext(); nn != null; nn = iterator.iterateNext()){ to_modify.push(nn); }}
        catch(e) { this.fire_event("error",{"message":'XML modified during iteration? ' + e}); }
        for(var j = 0; j < to_modify.length; j++){
            nn = to_modify[j];
            nn.parentNode.setAttribute("s",parseInt(nn.parentNode.getAttribute("s"))-1);
            nn.parentNode.removeChild(nn);
        }
        this.checkpoint();
    }

    /**
        Remove the current row from a matrix
        @memberof Engine
    */
    Engine.prototype.list_remove_row = function(){
        var n = this.current;
        while(n.parentNode && !(n.nodeName == 'l' && n.parentNode.nodeName == 'l')){
            n = n.parentNode;
        }
        Iif(!n.parentNode) return;
        // Don't remove if there is only a single row:
        Eif(n.previousSibling != null){
            this.current = n.previousSibling.firstChild.lastChild;
            this.caret = n.previousSibling.lastChild.firstChild.textContent.length;
        }
        else if(n.nextSibling != null){
            this.current = n.nextSibling.firstChild.firstChild;
            this.caret = 0;
        }
        else return;

        n.parentNode.setAttribute("s",parseInt(n.parentNode.getAttribute("s"))-1);
        n.parentNode.removeChild(n);
        this.checkpoint();
    }

    /**
        Remove the current element from a list (or column from a matrix)
        @memberof Engine
    */
    Engine.prototype.list_remove = function(){
        var n = this.current;
        while(n.parentNode && !(n.nodeName == 'c' && n.parentNode.nodeName == 'l')){
            n = n.parentNode;
        }
        Iif(!n.parentNode) return;
        Eif(n.parentNode.parentNode && n.parentNode.parentNode.nodeName == "l"){
            this.list_remove_col();
            return;
        }
        if(n.previousSibling != null){
            this.current = n.previousSibling.lastChild;
            this.caret = n.previousSibling.lastChild.firstChild.textContent.length;
        }
        else if(n.nextSibling != null){
            this.current = n.nextSibling.firstChild;
            this.caret = 0;
        }
        else return;
        n.parentNode.setAttribute("s",parseInt(n.parentNode.getAttribute("s"))-1);
        n.parentNode.removeChild(n);
        this.checkpoint();
    }

    /**
        Simulate the right arrow key press
        @memberof Engine
    */
    Engine.prototype.right = function(){
        this.sel_clear();
        if(this.caret >= Utils.get_length(this.current)){
            var nn = this.doc.xpath_node("following::e[1]", this.current);
            if(nn != null){
                this.current = nn;
                this.caret = 0;
            }
            else{
                this.fire_event("right_end");
            }
        }
        else{
            this.caret += 1;
        }
    }

    /**
        Simulate the spacebar key press
        @memberof Engine
    */
    Engine.prototype.spacebar = function(){
        Iif(Utils.is_text(this.current)) this.insert_string(" ");
        else this.space_caret = this.caret;
    }

    /**
        Simulate the left arrow key press
        @memberof Engine
    */
    Engine.prototype.left = function(){
        this.sel_clear();
        if(this.caret <= 0){
            var pn = this.doc.xpath_node("preceding::e[1]", this.current);
            if(pn != null){
                this.current = pn;
                this.caret = this.current.firstChild.nodeValue.length;
            }
            else{
                this.fire_event("left_end");
            }
        }
        else{
            this.caret -= 1;
        }
    }

    Engine.prototype.delete_from_c = function(){
        var pos = 0;
        var c = this.current.parentNode;
        while(c && c.nodeName == "c"){
            pos++;
            c = c.previousSibling;
        }
        var idx = this.current.parentNode.getAttribute("delete");
        var survivor_node = this.doc.xpath_node("./c[position()="+idx+"]", this.current.parentNode.parentNode);
        var survivor_nodes = [];
        for(var n = survivor_node.firstChild; n != null; n = n.nextSibling){
            survivor_nodes.push(n);
        }
        this.current = this.current.parentNode.parentNode;
        this.delete_from_f();
        this.insert_nodes(survivor_nodes, pos > idx);
    }

    Engine.prototype.delete_from_e = function(){
        // return false if we deleted something, and true otherwise.
        if(this.caret > 0){
            this.current.firstChild.nodeValue = this.current.firstChild.nodeValue.splicen(this.caret-1,"",1);
            this.caret--;
        }
        else{
            // The order of these is important
            if(this.current.previousSibling != null && Utils.is_char(this.current.previousSibling)){
                // The previous node is an f node but is really just a character.  Delete it.
                this.current = this.current.previousSibling;
                this.delete_from_f();
            }
            else Iif(this.current.previousSibling != null && this.current.previousSibling.nodeName == 'f'){
                // We're in an e node just after an f node.  Move back into the f node (delete it?)
                this.left();
                return false;
            }
            else if(this.current.parentNode.previousSibling != null && this.current.parentNode.previousSibling.nodeName == 'c'){
                // We're in a c child of an f node, but not the first one.  Go to the previous c
                Eif(this.current.parentNode.hasAttribute("delete")){
                    this.delete_from_c();
                }
                else{
                    this.left();
                    return false;
                }
            }
            else Eif(this.current.previousSibling == null && this.current.parentNode.nodeName == 'c' && (this.current.parentNode.previousSibling == null || this.current.parentNode.previousSibling.nodeName != 'c')){
                // We're in the first c child of an f node and at the beginning--delete the f node
                var par = this.current.parentNode;
                while(par.parentNode.nodeName == 'l' || par.parentNode.nodeName == 'c'){
                    par = par.parentNode;
                }
                Eif(par.hasAttribute("delete")){
                    this.delete_from_c();
                }
                else{
                    this.current = par.parentNode;
                    this.delete_from_f();
                }
            }
            else{
                // We're at the beginning (hopefully!)
                return false;
            }
        }
        return true;
    }

    Engine.prototype.delete_forward_from_e = function(){
        // return false if we deleted something, and true otherwise.
        if(this.caret < this.current.firstChild.nodeValue.length){
            this.current.firstChild.nodeValue = this.current.firstChild.nodeValue.splicen(this.caret,"",1);
        }
        else{
            //We're at the end
            Eif(this.current.nextSibling != null){
                // The next node is an f node.  Delete it.
                this.current = this.current.nextSibling;
                this.delete_from_f();
            }
            else if(this.current.parentNode.nodeName == 'c'){
                // We're in a c child of an f node.  Do nothing
                return false;
            }
        }
        return true;
    }

    /**
        Simulate the "backspace" key press
        @memberof Engine
    */
    Engine.prototype.backspace = function(){
        if(this.sel_status != Engine.SEL_NONE){
            this.sel_delete();
            this.sel_status = Engine.SEL_NONE;
            this.checkpoint();
        }
        else Eif(this.delete_from_e()){
            this.checkpoint();
        }
    }

    /**
        Simulate the "delete" key press
        @memberof Engine
    */
    Engine.prototype.delete_key = function(){
        Iif(this.sel_status != Engine.SEL_NONE){
            this.sel_delete();
            this.sel_status = Engine.SEL_NONE;
            this.checkpoint();
        }
        else Eif(this.delete_forward_from_e()){
            this.checkpoint();
        }
    }

    Engine.prototype.backslash = function(){
        Iif(Utils.is_text(this.current)) return;
        this.insert_symbol("sym_name");
    }

    /**
        Simulate a tab key press
        @memberof Engine
    */
    Engine.prototype.tab = function(){
        Eif(!Utils.is_symbol(this.current)){
            Eif(this.check_for_symbol()) return;
        }
        if(Utils.is_utf8entry(this.current)){
            var codepoint = this.current.firstChild.textContent;
            this.complete_utf8(codepoint);
            return;
        }
        var sym_name = this.current.firstChild.textContent;
        var candidates = [];
        for(var n in this.symbols){
            if(n.startsWith(sym_name)) candidates.push(n);
        }
        if(candidates.length == 1){
            this.current.firstChild.textContent = candidates[0];
            this.caret = candidates[0].length;
            this.check_for_symbol();
        }
        else {
            this.fire_event("completion",{"candidates":candidates});
        }
    }

    Engine.prototype.right_paren = function(){
        Iif(this.current.nodeName == 'e' && this.caret < this.current.firstChild.nodeValue.length - 1) return;
        else this.right();
    }

    /**
        Simulate an up arrow key press
        @memberof Engine
    */
    Engine.prototype.up = function(){
        this.sel_clear();
        Eif(this.current.parentNode.hasAttribute("up")){
            var t = parseInt(this.current.parentNode.getAttribute("up"));
            var f = this.current.parentNode.parentNode;
            var n = f.firstChild;
            while(n != null && t > 0){
                if(n.nodeName == 'c') t--;
                if(t > 0) n = n.nextSibling;
            }
            this.current = n.lastChild;
            this.caret = this.current.firstChild.nodeValue.length;
        }
        else this.list_vertical_move(false);
    }

    /**
        Simulate a down arrow key press
        @memberof Engine
    */
    Engine.prototype.down = function(){
        this.sel_clear();
        if(this.current.parentNode.hasAttribute("down")){
            var t = parseInt(this.current.parentNode.getAttribute("down"));
            var f = this.current.parentNode.parentNode;
            var n = f.firstChild;
            while(n != null && t > 0){
                if(n.nodeName == 'c') t--;
                if(t > 0) n = n.nextSibling;
            }
            this.current = n.lastChild;
            this.caret = this.current.firstChild.nodeValue.length;
        }
        else this.list_vertical_move(true);
    }

    /**
        Move the cursor to the beginning of the document
        @memberof Engine
    */
    Engine.prototype.home = function(){
        this.current = this.doc.root().firstChild;
        this.caret = 0;
    }

    /**
        Move the cursor to the end of the document
        @memberof Engine
    */
    Engine.prototype.end = function(){
        this.current = this.doc.root().lastChild;
        this.caret = this.current.firstChild.nodeValue.length;
    }

    Engine.prototype.checkpoint = function(){
        var base = this.doc.base;
        this.current.setAttribute("current","yes");
        this.current.setAttribute("caret",this.caret.toString());
        this.undo_now++;
        this.undo_data[this.undo_now] = base.cloneNode(true);
        this.undo_data.splice(this.undo_now+1, this.undo_data.length);
        var old_data = this.undo_data[this.undo_now-1] ? (new XMLSerializer()).serializeToString(this.undo_data[this.undo_now-1]) : "[none]";
        var new_data = (new XMLSerializer()).serializeToString(this.undo_data[this.undo_now]);
        this.fire_event("change",{"old":old_data,"new":new_data});
        this.current.removeAttribute("current");
        this.current.removeAttribute("caret");
    }

    Engine.prototype.restore = function(t){
        this.doc.base = this.undo_data[t].cloneNode(true);
        this.find_current();
        this.current.removeAttribute("current");
        this.current.removeAttribute("caret");
    }

    Engine.prototype.find_current = function(){
        this.current = this.doc.xpath_node("//*[@current='yes']");
        this.caret = parseInt(this.current.getAttribute("caret"));
    }

    /**
        Undo the last action
        @memberof Engine
    */
    Engine.prototype.undo = function(){
        this.sel_clear();
        if(this.undo_now <= 0) return;
        this.undo_now--;
        this.restore(this.undo_now);
        var old_data = this.undo_data[this.undo_now+1] ? (new XMLSerializer()).serializeToString(this.undo_data[this.undo_now+1]) : "[none]";
        var new_data = (new XMLSerializer()).serializeToString(this.undo_data[this.undo_now]);
        this.fire_event("change",{"old":old_data,"new":new_data});
    }

    /**
        Redo the last undone action
        @memberof Engine
    */
    Engine.prototype.redo = function(){
        this.sel_clear();
        if(this.undo_now >= this.undo_data.length-1) return;
        this.undo_now++;
        this.restore(this.undo_now);
        var old_data = this.undo_data[this.undo_now-1] ? (new XMLSerializer()).serializeToString(this.undo_data[this.undo_now-1]) : "[none]";
        var new_data = (new XMLSerializer()).serializeToString(this.undo_data[this.undo_now]);
        this.fire_event("change",{"old":old_data,"new":new_data});
    }

    /**
        Execute the "done" callback
        @memberof Engine
    */
    Engine.prototype.done = function(){
        if(Utils.is_symbol(this.current)) this.complete_symbol();
        else if(Utils.is_utf8entry(this.current)){
            var codepoint = this.current.firstChild.textContent;
            this.complete_utf8(codepoint);
        }
        else this.fire_event("done");
    }

    Engine.prototype.complete_symbol = function(){
        var sym_name = this.current.firstChild.textContent;
        Iif(!(this.symbols[sym_name])) return;
        this.current = this.current.parentNode.parentNode;
        this.delete_from_f();
        this.insert_symbol(sym_name);
    }

    Engine.prototype.complete_utf8 = function(codepoint){
        codepoint = parseInt('0x'+codepoint);
        this.current = this.current.parentNode.parentNode;
        this.delete_from_f();
        this.insert_utf8(codepoint);
    }

    Engine.prototype.insert_utf8 = function(codepoint){
        //this.insert_string(c);
        // if((codepoint < 0xffff && Object.values(Engine.kb_info.k_chars).indexOf(c) >= 0) || Utils.is_text(this.current)){
        //     this.insert_string(c);
        // }
        // else{
        //     this.insert_symbol("utf8codepoint",{"name":"UTF8","codepoint":codepoint.toString(16)});
        // }
        Eif(codepoint <= 0xffff){
    	var c = String.fromCharCode(codepoint);
            this.insert_string(c);
        }
        else{
            this.insert_symbol("utf8codepoint",{"name":"UTF8","codepoint":codepoint.toString(16)});
        }
    }

    Engine.prototype.problem = function(message){
        this.fire_event("error",{"message":message});
    }

    Engine.prototype.is_blacklisted = function(symb_type){
        var blacklist = this.setting("blacklist");
        for(var i = 0; i < blacklist.length; i++)
            if(symb_type == blacklist[i]) return true;
        return false;
    }

    Engine.prototype.check_for_symbol = function(whole_node){
        var instance = this;
        if(Utils.is_text(this.current)) return false;
        var sym = "";
        var n = null;
        if(whole_node){
            n = instance.current.firstChild.nodeValue.substring(instance.space_caret, instance.caret);
            var m = /[a-zA-Z_]+$/.exec(n);
            Eif(m){
                var s = m[0];
                if(this.symbols[s]) sym = s;
            }
        }
        else{
            n = instance.current.firstChild.nodeValue.substring(instance.space_caret, instance.caret);
            while(n.length > 0){
                if(n in this.symbols){
                    sym = n;
                    break;
                }
                n = n.substring(1);
            }
        }

        if(sym == "") return false;

        var temp = instance.current.firstChild.nodeValue;
        var temp_caret = instance.caret;
        instance.current.firstChild.nodeValue = instance.current.firstChild.nodeValue.slice(0,instance.caret-sym.length)+instance.current.firstChild.nodeValue.slice(instance.caret);
        instance.caret -= sym.length;
        var success = instance.insert_symbol(sym);
        Iif(!success){
            instance.current.firstChild.nodeValue = temp;
            instance.caret = temp_caret;
        }
        return success;
    }

    export default Engine;