File: GumboInterface.cpp

package info (click to toggle)
pageedit 2.4.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 10,956 kB
  • sloc: ansic: 31,806; cpp: 15,036; python: 1,141; javascript: 87; sh: 13; makefile: 7
file content (1610 lines) | stat: -rw-r--r-- 55,097 bytes parent folder | download
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
/************************************************************************
**
**  Copyright (C) 2015-2020  Kevin B. Hendricks, Stratford Ontario
**
**  This file is part of PageEdit.
**
**  PageEdit is free software: you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation, either version 3 of the License, or
**  (at your option) any later version.
**
**  PageEdit is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**  GNU General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with PageEdit.  If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/

#include <QString>
#include <QStringList>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QDir>
#include <QUrl>
#include <QFileInfo>
// #include <QDebug>

#include "Utility.h"
#include "GumboInterface.h"
#include "string_buffer.h"
#include "error.h"

static std::unordered_set<std::string> nonbreaking_inline  = { 
    "a","abbr","acronym","b","bdo","big","br","button","cite","code","del",
    "dfn","em","font","i","image","img","input","ins","kbd","label","map",
    "mark", "nobr","object","q","ruby","rt","s","samp","select","small",
    "span","strike","strong","sub","sup","textarea","tt","u","var",
    "wbr", "mbp:nu"
};


static std::unordered_set<std::string> preserve_whitespace = {
    "code", "pre","textarea","script","style"
};


static std::unordered_set<std::string> special_handling    = { 
    "html","body"
};


static std::unordered_set<std::string> no_entity_sub       = {
    "script","style"
};


static std::unordered_set<std::string> void_tags          = {
    "area","base","basefont","bgsound","br","col","command","embed",
    "event-source","frame","hr","img","input","keygen","link",
    "meta","param","source","spacer","track","wbr", 
    "mbp:pagebreak", "mglyph", "mspace", "mprescripts", "none",
    "maligngroup", "malignmark", "msline"
};


static std::unordered_set<std::string> structural_tags     = {
    "article","aside","blockquote","body","canvas","colgroup","div","dl",
    "figure","footer","head","header","hr","html","ol","section",
    "table","tbody","tfoot","thead","td","th","tr","ul"
};


static std::unordered_set<std::string> other_text_holders = {
    "address","caption","dd","div","dt","h1","h2","h3","h4","h5","h6",
    "legend","li","option","p","td","th","title"
};


static std::unordered_set<std::string> manifest_properties = {
    "math","nav","script","svg","epub:switch"
};


static std::unordered_set<std::string> href_src_tags       = {
    "a","area","audio","base","embed","font-face-uri","frame","iframe",
    "image","img","input","link","object","script","source","track","video"
};


static const QChar POUND_SIGN    = QChar::fromLatin1('#');
static const QChar FORWARD_SLASH = QChar::fromLatin1('/');
static const std::string aSRC = std::string("src");
static const std::string aHREF = std::string("href");
static const std::string aPOSTER = std::string("poster");
static const std::string aDATA = std::string("data");
QHash<QString,QString> EmptyHash = QHash<QString,QString>();

// These need to match the GumboAttributeNamespaceEnum sequence
static const char * attribute_nsprefixes[4] = { "", "xlink:", "xml:", "xmlns:" };
 
// Note: m_output contains the gumbo output tree which 
// has data structures with pointers into the original source
// buffer passed in!!!!!!

// This source buffer is provided by the m_utf8src std::string
// which should always exist unchanged alongside the output tree

// Do NOT change or delete m_utf8src once set until after you 
// have properly destroyed the gumbo output tree

GumboInterface::GumboInterface(const QString &source, const QString &version)
        : m_source(source),
          m_output(NULL),
          m_utf8src(""),
          m_sourceupdates(EmptyHash),
          m_newcsslinks(""),
          m_currentbkpath(""),
          m_currentdir(""),
          m_newbody(""),
          m_version(version),
          m_newbookpath("")
{
}


GumboInterface::GumboInterface(const QString &source, const QString &version, const QHash<QString,QString> & source_updates)
        : m_source(source),
          m_output(NULL),
          m_utf8src(""),
          m_sourceupdates(source_updates),
          m_newcsslinks(""),
          m_currentbkpath(""),
          m_currentdir(""),
          m_newbody(""),
          m_version(version),
          m_newbookpath("")
{
}


GumboInterface::~GumboInterface()
{
    if (m_output != NULL) {
        gumbo_destroy_output(m_output);
        m_output = NULL;
        m_utf8src = "";
    }
}


void GumboInterface::parse()
{
    if (!m_source.isEmpty() && (m_output == NULL)) {

        m_utf8src = m_source.toStdString();
        // remove any xml header line and any trailing whitespace
        if (m_utf8src.compare(0,5,"<?xml") == 0) {
            size_t end = m_utf8src.find_first_of('>', 5);
            end = m_utf8src.find_first_not_of("\n\r\t\v\f ",end+1);
            m_utf8src.erase(0,end);
        }

        // In case we ever have to revert to earlier versions, please note the following
        // additional initialization is needed because Microsoft Visual Studio 2013 (and earlier?)
        // do not properly initialize myoptions from the static const kGumboDefaultOptions defined
        // in the gumbo library.  Instead whatever was in memory at the time is used causing random 
        // issues later on so if reverting remember to keep these specific changes as the bug 
        // they work around took a long long time to track down
        GumboOptions myoptions = kGumboDefaultOptions;
        myoptions.tab_stop = 4;
        myoptions.use_xhtml_rules = true;
        myoptions.stop_on_first_error = false;
        myoptions.max_tree_depth = 400;
        myoptions.max_errors = 50;

        // GumboInterface::m_mutex.lock();
        m_output = gumbo_parse_with_options(&myoptions, m_utf8src.data(), m_utf8src.length());
        // GumboInterface::m_mutex.unlock();
    }
}


void GumboInterface::parse_fragment()
{
    if (!m_source.isEmpty() && (m_output == NULL)) {

        // In case we ever have to revert to earlier versions, please note the following
        // additional initialization is needed because Microsoft Visual Studio 2013 (and earlier?)
        // do not properly initialize myoptions from the static const kGumboDefaultOptions defined
        // in the gumbo library.  Instead whatever was in memory at the time is used causing random
        // issues later on so if reverting remember to keep these specific changes as the bug
        // they work around took a long long time to track down
        GumboOptions myoptions = kGumboDefaultOptions;
        myoptions.tab_stop = 4;
        myoptions.use_xhtml_rules = true;
        myoptions.stop_on_first_error = false;
        myoptions.max_tree_depth = 400;
        myoptions.max_errors = 50;

        m_utf8src = m_source.toStdString();
        m_output = gumbo_parse_fragment(&myoptions, m_utf8src.data(), m_utf8src.length(),
                                        GUMBO_TAG_BODY, GUMBO_NAMESPACE_HTML);

        m_output = gumbo_parse_with_options(&myoptions, m_utf8src.data(), m_utf8src.length());
    }
}


QString GumboInterface::repair()
{
    QString result = "";
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
        std::string utf8out = serialize(m_output->document);
        rtrim(utf8out);
        result =  "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
    }
    return result;
}


QString GumboInterface::get_fragment_xhtml()
{
    QString result = "";
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse_fragment();
        }
        std::string utf8out = serialize(m_output->document);
        rtrim(utf8out);
        result = QString::fromStdString(utf8out);
    }
    return result;
}


QString GumboInterface::getxhtml()
{
    QString result = "";
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
        std::string utf8out = serialize(m_output->document);
        rtrim(utf8out);
        result =  "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
    }
    return result;
}


QString GumboInterface::prettyprint(QString indent_chars)
{
    QString result = "";
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
        std::string ind = indent_chars.toStdString();
        std::string utf8out = prettyprint(m_output->document, 0, ind);
        rtrim(utf8out);
        result =  "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
    }
    return result;
}


QStringList GumboInterface::get_all_properties()
{
    QStringList properties;
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
        properties = get_properties(m_output->root);
    }
    return properties;
}


QString GumboInterface::perform_source_updates(const QString& my_current_book_relpath,
                                               const QString& newbookpath)
{
    m_currentbkpath = my_current_book_relpath;
    m_currentdir = QFileInfo(m_currentbkpath).dir().path();
    m_newbookpath = newbookpath;
    QString result = "";
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
        enum UpdateTypes doupdates = SourceUpdates;
        std::string utf8out = serialize(m_output->document, doupdates);
        rtrim(utf8out);
        result =  "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
    }
    return result;
}


QString GumboInterface::perform_style_updates(const QString& my_current_book_relpath,
                                              const QString& newbookpath)
{
    m_currentbkpath = my_current_book_relpath;
    m_currentdir = QFileInfo(m_currentbkpath).dir().path();
    m_newbookpath = newbookpath;
    
    QString result = "";
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
        enum UpdateTypes doupdates = StyleUpdates;
        std::string utf8out = serialize(m_output->document, doupdates);
        rtrim(utf8out);
        result =  "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
    }
    return result;
}


QString GumboInterface::perform_link_updates(const QString& newcsslinks)
{
    m_newcsslinks = newcsslinks.toStdString();
    QString result = "";
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
        enum UpdateTypes doupdates = LinkUpdates;
        std::string utf8out = serialize(m_output->document, doupdates);
        rtrim(utf8out);
        result =  "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
    }
    return result;
}


GumboNode * GumboInterface::get_document_node()
{
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
    }
    return m_output->document;
}


GumboNode * GumboInterface::get_root_node() {
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
    }
    return m_output->root;
}


GumboNode * GumboInterface::get_body_node()
{
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
    }
    QList<GumboTag> tags = QList<GumboTag>() << GUMBO_TAG_BODY;
    QList<GumboNode*> nodes = get_all_nodes_with_tags(tags);
    if (nodes.count() == 0) {
        return NULL;
    }
    return nodes.at(0);
}


QString GumboInterface::get_body_contents() 
{
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
    }
    QList<GumboTag> tags = QList<GumboTag>() << GUMBO_TAG_BODY;
    QList<GumboNode*> nodes = get_all_nodes_with_tags(tags);
    if (nodes.count() != 1) {
        return QString();
    }
    enum UpdateTypes doupdates = NoUpdates;
    std::string results = serialize_contents(nodes.at(0), doupdates);
    return QString::fromStdString(results);
}

QString GumboInterface::get_body_text() 
{
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
    }
    QList<GumboTag> tags = QList<GumboTag>() << GUMBO_TAG_BODY;
    QList<GumboNode*> nodes = get_all_nodes_with_tags(tags);
    if (nodes.count() != 1) {
        return QString();
    }
    QString results = get_local_text_of_node(nodes.at(0));
    return results;
}


QStringList GumboInterface::get_properties(GumboNode* node)
{
    if (node->type != GUMBO_NODE_ELEMENT) {
        return QStringList();
    }
    QStringList properties;
    std::string tagname = get_tag_name(node);
    if (in_set(manifest_properties, tagname)) {
        properties.append(QString::fromStdString(tagname));
    }
    GumboAttribute* attr = gumbo_get_attribute(&node->v.element.attributes, "src");
    if (attr && !QUrl(QString::fromUtf8(attr->value)).isRelative()) {
        properties.append(QString("remote-resources"));
    }
    GumboVector* children = &node->v.element.children;
    for (unsigned int i = 0; i < children->length; ++i) {
        properties.append(get_properties(static_cast<GumboNode*>(children->data[i])));
    }
    return properties;
}


QString GumboInterface::get_qwebpath_to_node(GumboNode* node) 
{
    QStringList path_pieces;
    GumboNode* anode = node;
    while (anode && !((anode->type == GUMBO_NODE_ELEMENT) && (anode->v.element.tag == GUMBO_TAG_HTML))) {
        GumboNode* myparent = anode->parent;
        QString parent_name = QString::fromStdString(get_tag_name(myparent));
        int index;
        QString aname = QString::fromStdString(get_tag_name(anode));
        if (aname == "#text") {
            index = anode->index_within_parent;
        } else {
            // need to find child num in parent as if only elements exist
            GumboVector* children = &myparent->v.element.children;
            int elnum = 0;
            for (unsigned int i=0; i < children->length; i++) {
                GumboNode* child = static_cast<GumboNode*>(children->data[i]);
                if (i == anode->index_within_parent) {
                    break;
                }
                if ((child->type == GUMBO_NODE_ELEMENT) || (child->type == GUMBO_NODE_TEMPLATE)) {
                    elnum++;
                } 
            }
            index = elnum;
        }
        path_pieces.prepend(parent_name + " " +  QString::number(index));
        anode = myparent;
    }
    return path_pieces.join(",");
}


GumboNode* GumboInterface::get_node_from_qwebpath(QString webpath) 
{
    QStringList path_pieces = webpath.split(",", Qt::SkipEmptyParts);
    GumboNode* node = get_root_node();
    GumboNode* end_node = node;
    for (int i=0; i < path_pieces.count() - 1 ; ++i) {
        QString piece = path_pieces.at(i);
        QString name = piece.split(" ")[0];
        int index = piece.split(" ")[1].toInt();
        GumboVector* children = &node->v.element.children;
        GumboNode * next_node = NULL;
        if (children->length > 0) {
            if (path_pieces.at(i+1).startsWith("#text")) {
                // trying to find the right text child of the parent is very difficult
                // It changes depending on what live editing is done in BookView
                // It also requires document.normalize() to be done to merge adjacent text pieces
                // but doing so will remove the cursor/highlight if it is on a text node merged away
                // so restrict this to something same in that same parent element
                if (index >= (int)(children->length)) index = children->length - 1;
                if (index < 0) index = 0;
                next_node = static_cast<GumboNode*>(children->data[index]);
            } else {
                // need to index correct child index when only counting elements
                int elnum = -1;
                for (unsigned int j=0; j < children->length; j++) {
                    GumboNode* child = static_cast<GumboNode*>(children->data[j]);
                    if ((child->type == GUMBO_NODE_ELEMENT) || (child->type == GUMBO_NODE_TEMPLATE)) {
                        elnum++;
                    }
                    if (elnum == index) {
                        next_node = child;
                        break;
                    }
                }
            }
            if (next_node) {
                end_node = next_node;
                node = next_node;
            } else {
                break;
            }
         }
     }
     return end_node;
}

QList<unsigned int> GumboInterface::get_path_to_node(GumboNode* node) 
{
  QList<unsigned int> apath = QList<unsigned int>();
  GumboNode* anode = node;
  while (anode && !((anode->type == GUMBO_NODE_ELEMENT) && (anode->v.element.tag == GUMBO_TAG_HTML))) {
      apath.prepend(anode->index_within_parent);
      anode = anode->parent;
  }
  return apath;
}


GumboNode* GumboInterface::get_node_from_path(QList<unsigned int> & apath) 
{
   GumboNode* dest = get_root_node();
   foreach(unsigned int childnum, apath) {
       if ((dest->type == GUMBO_NODE_ELEMENT) || (dest->type == GUMBO_NODE_TEMPLATE)) {
           GumboVector* children = &dest->v.element.children;
           if (childnum < children->length) {
               dest = static_cast<GumboNode*>(children->data[childnum]);
           } else {
             break;
           }
       } else {
           break;
       }
   }
   return dest;
}


QString GumboInterface::perform_body_updates(const QString & new_body) 
{
    QString result = "";
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
    }
    QList<GumboTag> tags = QList<GumboTag>() << GUMBO_TAG_BODY;
    QList<GumboNode*> nodes = get_all_nodes_with_tags(tags);
    if (nodes.count() != 1) {
        return QString();
    }
    m_newbody = new_body.toStdString();
    enum UpdateTypes doupdates = BodyUpdates;
    std::string utf8out = serialize(m_output->document, doupdates);
    result =  "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + QString::fromStdString(utf8out);
    m_newbody= "";
    return result;
}
    

QList<GumboWellFormedError> GumboInterface::error_check()
{
    QList<GumboWellFormedError> errlist;
    int line_offset = 0;

    // In case we ever have to revert to earlier versions, please note the following
    // additional initialization is needed because Microsoft Visual Studio 2013 (and earlier?)
    // do not properly initialize myoptions from the static const kGumboDefaultOptions defined
    // in the gumbo library.  Instead whatever was in memory at the time is used causing random 
    // issues later on so if reverting remember to keep these specific changes as the bug 
    // they work around took a long long time to track down
    GumboOptions myoptions = kGumboDefaultOptions;
    myoptions.tab_stop = 4;
    myoptions.use_xhtml_rules = true;
    myoptions.stop_on_first_error = false;
    myoptions.max_tree_depth = 400;
    myoptions.max_errors = -1;

    if (!m_source.isEmpty() && (m_output == NULL)) {

        m_utf8src = m_source.toStdString();
        // remove any xml header line and trailing whitespace
        if (m_utf8src.compare(0,5,"<?xml") == 0) {
            size_t end = m_utf8src.find_first_of('>', 0);
            end = m_utf8src.find_first_not_of("\n\r\t\v\f ",end+1);
            m_utf8src.erase(0,end);
            line_offset++;
        }
        // add in epub version specific doctype if missing
        if ((m_utf8src.compare(0,9,"<!DOCTYPE") != 0) && (m_utf8src.compare(0,9,"<!doctype") != 0)) {
            if (m_version.startsWith('3')) {
                m_utf8src.insert(0,"<!DOCTYPE html>\n");
            } else {
                m_utf8src.insert(0, "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n  \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n\n");
            }
            line_offset--;
        }
        m_output = gumbo_parse_with_options(&myoptions, m_utf8src.data(), m_utf8src.length());
    }
    // qDebug() << QString::fromStdString(m_utf8src);
    const GumboVector* errors  = &m_output->errors;
    for (unsigned int i=0; i< errors->length; ++i) {
        GumboError* er = static_cast<GumboError*>(errors->data[i]);
        GumboWellFormedError gperror;
        gperror.line = er->position.line + line_offset;;
        gperror.column = er->position.column;
        // unsigned int typenum = er->type;
        GumboStringBuffer text;
        gumbo_string_buffer_init(&text);
        gumbo_error_to_string(er, &text);
        std::string errmsg(text.data, text.length);
        gperror.message = QString::fromStdString(errmsg);
        // qDebug() << gperror.message;
        gumbo_string_buffer_destroy(&text);
        errlist.append(gperror);
    }
    return errlist;
}


QList<GumboWellFormedError> GumboInterface::fragment_error_check()
{
    QList<GumboWellFormedError> errlist;

    // In case we ever have to revert to earlier versions, please note the following
    // additional initialization is needed because Microsoft Visual Studio 2013 (and earlier?)
    // do not properly initialize myoptions from the static const kGumboDefaultOptions defined
    // in the gumbo library.  Instead whatever was in memory at the time is used causing random 
    // issues later on so if reverting remember to keep these specific changes as the bug 
    // they work around took a long long time to track down
    GumboOptions myoptions = kGumboDefaultOptions;
    myoptions.tab_stop = 4;
    myoptions.use_xhtml_rules = true;
    myoptions.stop_on_first_error = false;
    myoptions.max_tree_depth = 400;
    myoptions.max_errors = -1;

    if (!m_source.isEmpty() && (m_output == NULL)) {

        m_utf8src = m_source.toStdString();
        m_output = gumbo_parse_fragment(&myoptions, m_utf8src.data(), m_utf8src.length(),
                                        GUMBO_TAG_BODY, GUMBO_NAMESPACE_HTML);
    }
    const GumboVector* errors  = &m_output->errors;
    for (unsigned int i=0; i< errors->length; ++i) {
        GumboError* er = static_cast<GumboError*>(errors->data[i]);
        GumboWellFormedError gperror;
        gperror.line = er->position.line;
        gperror.column = er->position.column;
        // unsigned int typenum = er->type;
        GumboStringBuffer text;
        gumbo_string_buffer_init(&text);
        gumbo_error_to_string(er, &text);
        std::string errmsg(text.data, text.length);
        gperror.message = QString::fromStdString(errmsg);
        gumbo_string_buffer_destroy(&text);
        errlist.append(gperror);
    }
    return errlist;
}


QList<GumboNode*> GumboInterface::get_nodes_with_comments(GumboNode * node)
{
    QList<GumboNode*> nodes;
    if (node->type == GUMBO_NODE_COMMENT) {
        nodes.append(node);
        return nodes;
    }
    if (node->type != GUMBO_NODE_ELEMENT) {
        return nodes;
    }
    GumboVector* children = &node->v.element.children;
    for (unsigned int i = 0; i < children->length; ++i) {
        nodes.append(get_nodes_with_comments(static_cast<GumboNode*>(children->data[i])));
    }
    return nodes;
}


QList<GumboNode*> GumboInterface::get_element_nodes_with_prefix(GumboNode * node, const std::string& prefix)
{
    QList<GumboNode*> nodes;
    if (node->type != GUMBO_NODE_ELEMENT) {
        return nodes;
    }
    std::string tag_name = get_tag_name(node);
    if (tag_name.rfind(prefix, 0) == 0) {
        nodes.append(node);
    }
    GumboVector* children = &node->v.element.children;
    for (unsigned int i = 0; i < children->length; ++i) {
        nodes.append(get_element_nodes_with_prefix(static_cast<GumboNode*>(children->data[i]), prefix));
    }
    return nodes;
}


QList<GumboNode*> GumboInterface::get_all_nodes_with_attribute(const QString& attname)
{
    QList<GumboNode*> nodes;
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
        nodes = get_nodes_with_attribute(m_output->root, attname.toUtf8().constData()); 
    }
    return nodes;
}


QList<GumboNode*> GumboInterface::get_nodes_with_attribute(GumboNode* node, const char * attname)
{
  if (node->type != GUMBO_NODE_ELEMENT) {
    return QList<GumboNode*>();
  }
  QList<GumboNode*> nodes;
  GumboAttribute* attr = gumbo_get_attribute(&node->v.element.attributes, attname);
  if (attr) {
      nodes.append(node);
  }
  GumboVector* children = &node->v.element.children;
  for (unsigned int i = 0; i < children->length; ++i) {
      nodes.append(get_nodes_with_attribute(static_cast<GumboNode*>(children->data[i]), attname));
  }
  return nodes;
}


QStringList GumboInterface::get_all_values_for_attribute(const QString& attname)
{
    QStringList attrvals;
    if (!m_source.isEmpty()) {
        if (m_output == NULL) {
            parse();
        }
        attrvals = get_values_for_attr(m_output->root, attname.toUtf8().constData()); 
    }
    return attrvals;
}


QStringList  GumboInterface::get_values_for_attr(GumboNode* node, const char* attr_name) 
{
    if (node->type != GUMBO_NODE_ELEMENT) {
        return QStringList();
    }
    QStringList attr_vals;
    GumboAttribute* attr = gumbo_get_attribute(&node->v.element.attributes, attr_name);
    if (attr != NULL) {
        attr_vals.append(QString::fromUtf8(attr->value));
    }
    GumboVector* children = &node->v.element.children;
    for (unsigned int i = 0; i < children->length; ++i) {
        attr_vals.append(get_values_for_attr(static_cast<GumboNode*>(children->data[i]), attr_name));
    }
    return attr_vals;
}


QHash<QString,QString> GumboInterface::get_attributes_of_node(GumboNode* node)
{
    QHash<QString,QString> node_atts;
    if (node->type != GUMBO_NODE_ELEMENT) {
        return node_atts;
    }
    const GumboVector * attribs = &node->v.element.attributes;
    for (unsigned int i=0; i< attribs->length; ++i) {
        GumboAttribute* attr = static_cast<GumboAttribute*>(attribs->data[i]);
        QString key = QString::fromStdString(get_attribute_name(attr));
        QString val = QString::fromUtf8(attr->value);
        node_atts[key] = val;
    }
    return node_atts;
}


QString GumboInterface::get_local_text_of_node(GumboNode* node)
{
    QString  node_text;
    if (node->type != GUMBO_NODE_ELEMENT) {
        return node_text;
    }
    // handle br tag as special case element tag with a text value
    GumboTag tag = node->v.element.tag;
    if (tag == GUMBO_TAG_BR) {
        node_text = "\n";
        return node_text;
    }
    GumboVector* children = &node->v.element.children;
    for (unsigned int i = 0; i < children->length; ++i) {
        GumboNode* child = static_cast<GumboNode*> (children->data[i]);

        if (child->type == GUMBO_NODE_TEXT) {
            node_text += QString::fromUtf8(child->v.text.text);

        } else if (child->type == GUMBO_NODE_WHITESPACE) {
            // keep all whitespace to keep as close to original as possible
            node_text += QString::fromUtf8(child->v.text.text);

        } else if (child->type == GUMBO_NODE_CDATA) {
            node_text += QString::fromUtf8(child->v.text.text);

        } else if (child->type == GUMBO_NODE_ELEMENT) {
            node_text += get_local_text_of_node(child);
        }
    }
    return node_text;
}


QList<GumboNode*> GumboInterface::get_all_nodes_with_tag(GumboTag tag)
{
    QList<GumboTag> tags;
    tags << tag;
    return  get_all_nodes_with_tags(tags); 
}


QList<GumboNode*> GumboInterface::get_all_nodes_with_tags(const QList<GumboTag> & tags )
{
  QList<GumboNode*> nodes;
  if (!m_source.isEmpty()) {
    if (m_output == NULL) {
      parse();
    }
    nodes = get_nodes_with_tags(m_output->root, tags); 
  }
  return nodes;
}


QList<GumboNode*>  GumboInterface::get_nodes_with_tags(GumboNode* node, const QList<GumboTag> & tags) 
{
  if (node->type != GUMBO_NODE_ELEMENT) {
    return QList<GumboNode*>();
  }
  QList<GumboNode*> nodes;
  GumboTag tag = node ->v.element.tag;
  if (tags.contains(tag)) {
    nodes.append(node);
  }
  GumboVector* children = &node->v.element.children;
  for (unsigned int i = 0; i < children->length; ++i) {
    nodes.append(get_nodes_with_tags(static_cast<GumboNode*>(children->data[i]), tags));
  }
  return nodes;
}


bool GumboInterface::in_set(std::unordered_set<std::string> &s, std::string &key)
{
  return s.find(key) != s.end();
}


void GumboInterface::rtrim(std::string &s) 
{
    s.erase(s.find_last_not_of(" \n\r\t\v\f")+1);
}


void GumboInterface::ltrim(std::string &s)
{
    s.erase(0,s.find_first_not_of(" \n\r\t\v\f"));
}


void GumboInterface::ltrimnewlines(std::string &s)
{
    s.erase(0,s.find_first_not_of("\n\r"));
}


// delete everything up to and including the newline
void GumboInterface::newlinetrim(std::string &s)
{
  size_t pos = s.find("\n");
  if (pos != std::string::npos) {
    s.erase(0, pos+1);
  }
}


void GumboInterface::condense_whitespace(std::string &s)
{
    size_t n = s.length();
    std::string val;
    val.reserve(n);
    std::string wspace = " \n\r\t\v\f";
    char last_c = 'x';
    for (size_t i=0; i < n; i++) {
        char c = s.at(i);
        if (wspace.find(c) != std::string::npos) {
            c = ' ';
        }
        if ((c != ' ') || (last_c != ' ')) {
            val.push_back(c);
        }
        last_c = c;
    }
    s = val;
}


void GumboInterface::replace_all(std::string &s, const char * s1, const char * s2)
{
    std::string t1(s1);
    size_t len = t1.length();
    size_t pos = s.find(t1);
    while (pos != std::string::npos) {
      s.replace(pos, len, s2);
      pos = s.find(t1, pos + len);
    }
}


std::string GumboInterface::update_attribute_value(const std::string &attvalue)
{
    std::string result = attvalue;
    if (attvalue.find(":") != std::string::npos) return result;
    bool has_fragment = attvalue.find("#") != std::string::npos;
    QUrl href(QString::fromStdString(attvalue));
    QString attpath = href.path();
    // handle purely local hrefs here as they do not need to be updated at all
    if (attpath.isEmpty() && has_fragment) return result;
    QString fragment;
    if (has_fragment) {
        fragment = href.fragment();
    }    

    QString dest_oldbkpath;
    if (attpath.isEmpty()) {
        dest_oldbkpath = m_currentbkpath;
    } else {
        dest_oldbkpath = Utility::buildBookPath(attpath, m_currentdir);
    }
    
    // note destination may not have moved but we still need to update
    // the link since we may have moved
    QString dest_newbkpath = m_sourceupdates.value(dest_oldbkpath, dest_oldbkpath);
    if (!dest_newbkpath.isEmpty() && !m_newbookpath.isEmpty()) {
        QString new_path = Utility::buildRelativePath(m_newbookpath, dest_newbkpath);
        QString new_href(Utility::URLEncodePath(new_path));
        if (has_fragment) {
            new_href.append("#");
            new_href.append(QUrl::toPercentEncoding(fragment));
        }

        // if empty then internal link to the top (which is best here?)                                
        if (new_href.isEmpty()) new_href = QFileInfo(dest_newbkpath).fileName();
        // if (new_href.isEmpty()) new_href="#";                                                          

        result =  new_href.toStdString();
    }
    return result;
}


std::string GumboInterface::update_style_urls(const std::string &source)
{
    QString result = QString::fromStdString(source);
    // Now parse the text once looking urls and replacing them where needed
    QRegularExpression reference(
        "(?:(?:src|background|background-image|list-style|list-style-image|border-image|border-image-source|content)\\s*:|@import)\\s*"
        "[^;\\}\\(\"']*"
        "(?:"
        "url\\([\"']?([^\\(\\)\"']*)[\"']?\\)"
        "|"
        "[\"']([^\\(\\)\"']*)[\"']"
        ")");
    int start_index = 0;
    QRegularExpressionMatch mo = reference.match(result, start_index);
    do {
        for (int i = 1; i < reference.captureCount(); ++i) {
            if (mo.captured(i).trimmed().isEmpty()) {
                continue;
            }
            if (mo.captured(i).indexOf(":") != -1) continue;
            QString apath = Utility::URLDecodePath(mo.captured(i));
            QString dest_oldbkpath;
            if (apath.isEmpty()) {
              dest_oldbkpath = m_currentbkpath;
            } else {
              dest_oldbkpath = Utility::buildBookPath(apath, m_currentdir);
            }
            // note destination may not have moved but we still need to update
            // the link
            QString dest_newbkpath = m_sourceupdates.value(dest_oldbkpath, dest_oldbkpath);
            if (!dest_newbkpath.isEmpty() && !m_newbookpath.isEmpty()) {
                QString new_href = Utility::buildRelativePath(m_newbookpath, dest_newbkpath);
                if (new_href.isEmpty()) new_href = QFileInfo(dest_newbkpath).fileName();
                new_href = Utility::URLEncodePath(new_href);
                result.replace(mo.capturedStart(i), mo.capturedLength(i), new_href);
            }
        }
        start_index = mo.capturedEnd();
        mo = reference.match(result, start_index);
    } while (mo.hasMatch());

    return result.toStdString();
}



std::string GumboInterface::substitute_xml_entities_into_text(const std::string &text)
{
    std::string result = text;
    // replacing & must come first 
    replace_all(result, "&", "&amp;");
    replace_all(result, "<", "&lt;");
    replace_all(result, ">", "&gt;");
    return result;
}


std::string GumboInterface::substitute_xml_entities_into_attributes(char quote, const std::string &text)
{
    std::string result = substitute_xml_entities_into_text(text);
    if (quote == '"') {
        replace_all(result,"\"","&quot;");
    } else if (quote == '\'') {
        replace_all(result,"'","&apos;");
    }
    return result;
}


std::string GumboInterface::get_tag_name(GumboNode *node)
{
  std::string tagname;
  if (node->type == GUMBO_NODE_DOCUMENT) {
    tagname = "#document";
    return tagname;
  } else if ((node->type == GUMBO_NODE_TEXT) || (node->type == GUMBO_NODE_WHITESPACE)) {
    tagname = "#text";
    return tagname;
  } else if (node->type == GUMBO_NODE_CDATA) {
    tagname = "#cdata";
    return tagname;
  }
  tagname = gumbo_normalized_tagname(node->v.element.tag);
  if ((tagname.empty()) ||
      (node->v.element.tag_namespace == GUMBO_NAMESPACE_SVG)) {

    // set up to examine original text of tag.
    GumboStringPiece gsp = node->v.element.original_tag;
    gumbo_tag_from_original_text(&gsp);

    // special handling for some svg tag names.
    if (node->v.element.tag_namespace  == GUMBO_NAMESPACE_SVG) {
      const char * data = gumbo_normalize_svg_tagname(&gsp);
      // NOTE: data may not be null-terminated!
      // since case change only - length must be same as original
      // if no replacement found returns null, not original tag!
      if (data != NULL) {
        return std::string(data, gsp.length);
      }
    }
    if (tagname.empty()) {
      tagname = std::string(gsp.data, gsp.length); 
      // replace any quotes in tag name with underscores for safety
      replace_all(tagname, "'", "_");
      replace_all(tagname, "\"", "_");
      return tagname;
    }
  }
  return tagname;
}


// if missing leave it alone
// if epub3 docytpe use it otherwise set it to epub2 docytpe
std::string GumboInterface::build_doctype(GumboNode *node)
{
    std::string results = "";
    if (m_version.startsWith('2')) {
        results.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n");
        results.append("  \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n\n");
        return results;
    } else if (m_version.startsWith('3')) {
        results.append("<!DOCTYPE html>\n\n");
        return results; 
    }
    if (node->v.document.has_doctype) {
        std::string name(node->v.document.name);
        std::string pi(node->v.document.public_identifier);
        std::string si(node->v.document.system_identifier);
        if ((name == "html") && pi.empty() && si.empty()) {
            results.append("<!DOCTYPE html>\n\n");
            return results;
        } else {
            results.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n");
            results.append("  \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n\n");
        }
    }
    return results;
}


// deal properly with foreign namespaced attributes
std::string GumboInterface::get_attribute_name(GumboAttribute * at)
{
    std::string attr_name = at->name;
    GumboAttributeNamespaceEnum attr_ns = at->attr_namespace;
    if ((attr_ns == GUMBO_ATTR_NAMESPACE_NONE) || (attr_name == "xmlns")) {
        return attr_name;
    } 
    attr_name = std::string(attribute_nsprefixes[attr_ns]) + attr_name;
    return attr_name;
}


std::string GumboInterface::build_attributes(GumboAttribute * at, bool no_entities, 
                                             bool run_src_updates, bool run_style_updates)
{
    std::string atts = " ";
    std::string name = get_attribute_name(at);
    std::string local_name = at->name;
    atts.append(name);
    std::string attvalue = at->value;

    if (run_src_updates && (local_name == aHREF || local_name == aSRC || 
                            local_name == aPOSTER || local_name == aDATA)) {
        attvalue = update_attribute_value(attvalue);
    }

    if (run_style_updates && (local_name == "style")) {
        attvalue = update_style_urls(attvalue);
    }

    // we handle empty attribute values like so: alt=""
    char quote = '"';
    std::string qs="\"";

    // verify an original value existed since we create our own attributes
    // and if so determine the original quote character used if any

    if (at->original_value.data) {
        if ( (!attvalue.empty())   || 
             (at->original_value.data[0] == '"') || 
             (at->original_value.data[0] == '\'') ) {

          quote = at->original_value.data[0];
          if (quote == '\'') qs = std::string("'");
          if (quote == '"') qs = std::string("\"");
        }
    }

    atts.append("=");
    atts.append(qs);
    if (no_entities) {
        atts.append(attvalue);
    } else {
        atts.append(substitute_xml_entities_into_attributes(quote, attvalue));
    }
    atts.append(qs);
    return atts;
}


// serialize children of a node
// may be invoked recursively

std::string GumboInterface::serialize_contents(GumboNode* node, enum UpdateTypes doupdates) {
    std::string contents        = "";
    std::string tagname         = get_tag_name(node);
    bool no_entity_substitution = in_set(no_entity_sub, tagname);
    bool keep_whitespace        = in_set(preserve_whitespace, tagname);
    bool is_inline              = in_set(nonbreaking_inline, tagname);
    bool is_structural          = in_set(structural_tags, tagname);

    // build up result for each child, recursively if need be
    GumboVector* children = &node->v.element.children;

    bool inject_newline = false;
    bool in_head_without_title = (tagname == "head");

    for (unsigned int i = 0; i < children->length; ++i) {
        GumboNode* child = static_cast<GumboNode*> (children->data[i]);

        if (child->type == GUMBO_NODE_TEXT) {
            std::string text;
            if (no_entity_substitution) {
                text = std::string(child->v.text.text);
            } else {
                text = substitute_xml_entities_into_text(std::string(child->v.text.text));
            }
            if (inject_newline && !text.empty() && (text.at(0) == '\n')) text.erase(0,1);
            inject_newline = false;
            contents.append(text);

        } else if (child->type == GUMBO_NODE_ELEMENT || child->type == GUMBO_NODE_TEMPLATE) {
            contents.append(serialize(child, doupdates));
            inject_newline = false;
            std::string childname = get_tag_name(child);
            if (in_head_without_title && (childname == "title")) in_head_without_title = false;
            if (!is_inline && !keep_whitespace && !in_set(nonbreaking_inline,childname) && is_structural) {
                contents.append("\n");
                inject_newline = true;
            }

        } else if (child->type == GUMBO_NODE_WHITESPACE) {
            // try to keep all whitespace to keep as close to original as possible
            std::string wspace = std::string(child->v.text.text);
            if (inject_newline) {
                newlinetrim(wspace);
                inject_newline = false;
            }
            contents.append(wspace);
            inject_newline = false;

        } else if (child->type == GUMBO_NODE_CDATA) {
            contents.append("<![CDATA[" + std::string(child->v.text.text) + "]]>");
            inject_newline = false;

        } else if (child->type == GUMBO_NODE_COMMENT) {
            contents.append("<!--" + std::string(child->v.text.text) + "-->");
 
        } else {
            fprintf(stderr, "unknown element of type: %d\n", child->type); 
            inject_newline = false;
        }

    }
    if (in_head_without_title) contents.append("<title></title>");
    return contents;
}


// serialize a GumboNode back to html/xhtml
// may be invoked recursively

std::string GumboInterface::serialize(GumboNode* node, enum UpdateTypes doupdates) {
    // special case the document node
    if (node->type == GUMBO_NODE_DOCUMENT) {
        std::string results = build_doctype(node);
        results.append(serialize_contents(node, doupdates));
        return results;
    }

    std::string close = "";
    std::string closeTag = "";
    std::string atts = "";
    std::string tagname            = get_tag_name(node);
    bool need_special_handling     = in_set(special_handling, tagname);
    bool is_void_tag               = in_set(void_tags, tagname);
    bool no_entity_substitution    = in_set(no_entity_sub, tagname);
    bool is_href_src_tag           = in_set(href_src_tags, tagname);
    bool in_xml_ns                 = node->v.element.tag_namespace != GUMBO_NAMESPACE_HTML;
    // bool is_inline                 = in_set(nonbreaking_inline, tagname);

    // build attr string  
    const GumboVector * attribs = &node->v.element.attributes;
    for (unsigned int i=0; i< attribs->length; ++i) {
        GumboAttribute* at = static_cast<GumboAttribute*>(attribs->data[i]);
        atts.append(build_attributes(at, no_entity_substitution, ((doupdates & SourceUpdates) && is_href_src_tag), (doupdates & StyleUpdates)));
    }

    // Make sure that the xmlns attribute exists as an html tag attribute
    if (tagname == "html") {
      if (atts.find("xmlns=") == std::string::npos) {
        atts.append(" xmlns=\"http://www.w3.org/1999/xhtml\"");
      }
    }

    // determine contents
    std::string contents;

    if ((tagname == "body") && (doupdates & BodyUpdates)) {
        contents = m_newbody;
    } else {
        // serialize your contents
        contents = serialize_contents(node, doupdates);
    }

    // determine closing tag type
    std::string testcontents = contents;
    ltrim(testcontents);
    if (is_void_tag || (in_xml_ns && testcontents.empty())) {
        close = "/";
    } else {
        closeTag = "</" + tagname + ">";
    }

    if ((doupdates & StyleUpdates) && (tagname == "style") && 
        (node->parent->type == GUMBO_NODE_ELEMENT) && 
        (node->parent->v.element.tag == GUMBO_TAG_HEAD)) {
        contents = update_style_urls(contents);
    }

    if (need_special_handling) {
        ltrimnewlines(contents);
        rtrim(contents);
        contents.append("\n");
    }

    // build results
    std::string results;

    if ((doupdates & LinkUpdates) && (tagname == "link") && 
        (node->parent->type == GUMBO_NODE_ELEMENT) && 
        (node->parent->v.element.tag == GUMBO_TAG_HEAD)) {
      return "";
    }

    results.append("<"+tagname+atts+close+">");
    if (need_special_handling) results.append("\n");
    results.append(contents);

    if ((doupdates & LinkUpdates) && (tagname == "head")) {
        results.append(m_newcsslinks);
    }

    results.append(closeTag);
    if (need_special_handling) results.append("\n");
    return results;
}



std::string GumboInterface::prettyprint_contents(GumboNode* node, int lvl, const std::string indent_chars) 
{
    std::string contents        = "";
    std::string tagname         = get_tag_name(node);
    bool no_entity_substitution = in_set(no_entity_sub, tagname);
    bool keep_whitespace        = in_set(preserve_whitespace, tagname);
    bool is_inline              = in_set(nonbreaking_inline, tagname);
    bool is_structural          = in_set(structural_tags, tagname);
    char c                      = indent_chars.at(0);
    int  n                      = indent_chars.length(); 
    std::string indent_space    = std::string((lvl-1)*n,c);
    char last_char              = 'x';
    bool contains_block_tags    = false;

    GumboVector* children = &node->v.element.children;

    if (is_structural || (tagname == "#document")) last_char = '\n';
    bool in_head_without_title = (tagname == "head");

    for (unsigned int i = 0; i < children->length; ++i) {

        GumboNode* child = static_cast<GumboNode*> (children->data[i]);

        if (child->type == GUMBO_NODE_TEXT) {
            std::string val;

            if (no_entity_substitution) {
                val = std::string(child->v.text.text);
            } else {
                val = substitute_xml_entities_into_text(std::string(child->v.text.text));
            }

            // if child of a structual element is text and follows a newline, indent it properly
            if (is_structural && last_char == '\n') {
                contents.append(indent_space);
                ltrim(val);
            }
            if (!keep_whitespace && !is_structural) {
                // okay to condense whitespace
                condense_whitespace(val);
            }
            contents.append(val);

        } else if (child->type == GUMBO_NODE_ELEMENT || child->type == GUMBO_NODE_TEMPLATE) {

            std::string val = prettyprint(child, lvl, indent_chars);
            std::string childname = get_tag_name(child);
            if (in_head_without_title && (childname == "title")) in_head_without_title = false;
            if (!in_set(nonbreaking_inline, childname)) {
                contains_block_tags = true;
                if (last_char != '\n') {
                    contents.append("\n");
                    if (tagname != "head" && tagname != "html") contents.append("\n");
                    last_char='\n';
                }
            }
            // if child of a structual element is inline and follows a newline, indent it properly
            if (is_structural && in_set(nonbreaking_inline, childname) && (last_char == '\n')) {
                contents.append(indent_space);
                ltrim(val);
            }    
            contents.append(val);

        } else if (child->type == GUMBO_NODE_WHITESPACE) {

            if (keep_whitespace) {
                std::string wspace = std::string(child->v.text.text);
                contents.append(wspace);
            } else if (is_inline || in_set(other_text_holders, tagname)) {
                if (std::string(" \t\v\f\r\n").find(last_char) == std::string::npos) {
                    contents.append(std::string(" "));
                }
            }

        } else if (child->type == GUMBO_NODE_CDATA) {
            contents.append("<![CDATA[" + std::string(child->v.text.text) + "]]>");

        } else if (child->type == GUMBO_NODE_COMMENT) {
            contents.append("<!--" + std::string(child->v.text.text) + "-->");
 
        } else {
            fprintf(stderr, "unknown element of type: %d\n", child->type); 
        }

        // update last character of current contents
        if (!contents.empty()) {
            last_char = contents.at(contents.length()-1);
        }

    }

    // inject epmpty title into head if one is missing
    if (in_head_without_title) {
        if (last_char != '\n') contents.append("\n");
        contents.append(indent_space + "<title></title>\n");
        last_char = '\n';
    }

    // treat inline tags containing block tags like a block tag
    if (is_inline && contains_block_tags) {
      if (last_char != '\n') contents.append("\n\n");
      contents.append(indent_space);
    }

    return contents;
}


// prettyprint a GumboNode back to html/xhtml
// may be invoked recursively

std::string GumboInterface::prettyprint(GumboNode* node, int lvl, const std::string indent_chars)
{

    // special case the document node
    if (node->type == GUMBO_NODE_DOCUMENT) {
      std::string results = build_doctype(node);
      results.append(prettyprint_contents(node,lvl+1,indent_chars));
      return results;
    }

    std::string tagname = get_tag_name(node);
    std::string parentname = get_tag_name(node->parent);
    bool in_head = (parentname == "head");

    bool is_structural = in_set(structural_tags, tagname);
    bool is_inline = in_set(nonbreaking_inline, tagname);
    bool in_xml_ns = node->v.element.tag_namespace != GUMBO_NAMESPACE_HTML;

    // build attr string
    std::string atts = "";
    bool no_entity_substitution = in_set(no_entity_sub, tagname);
    const GumboVector * attribs = &node->v.element.attributes;
    for (unsigned int i=0; i< attribs->length; ++i) {
        GumboAttribute* at = static_cast<GumboAttribute*>(attribs->data[i]);
        atts.append(build_attributes(at, no_entity_substitution));
    }

    bool is_void_tag = in_set(void_tags, tagname);

    // get tag contents
    std::string contents = "";
    if (!is_void_tag) {
        if (is_structural && tagname != "html") {
            contents = prettyprint_contents(node, lvl+1, indent_chars);
        } else {
            contents = prettyprint_contents(node, lvl, indent_chars);
        }
    }

    bool keep_whitespace = in_set(preserve_whitespace, tagname);
    if (!keep_whitespace && !is_inline) {
        rtrim(contents);
    }

    std::string testcontents = contents;
    ltrim(testcontents);

    bool single = is_void_tag || (in_xml_ns && testcontents.empty());

    char c = indent_chars.at(0);
    int  n = indent_chars.length(); 
    std::string indent_space = std::string((lvl-1)*n,c);

    // handle self-closed tags with no contents first
    if (single) {
        std::string selfclosetag = "<" + tagname + atts + "/>";
        if (is_inline) {
            // always add newline after br tags when they are children of structural tags
            if ((tagname == "br") && in_set(structural_tags, parentname)) {
              selfclosetag.append("\n");
              if (!in_head && (tagname != "html")) selfclosetag.append("\n");
            }
            return selfclosetag;
        }
        if (!in_head && (tagname != "html")) selfclosetag.append("\n");
        return indent_space + selfclosetag + "\n";
    } 

    // Handle the general case
    std::string results;
    std::string starttag = "<" + tagname +  atts + ">";
    std::string closetag = "</" + tagname + ">";

    if (is_structural) {
        results = indent_space + starttag;
        if (!contents.empty()) {
            results.append("\n" + contents + "\n" + indent_space);
        }  
        results.append(closetag + "\n");
        if (!in_head && (tagname != "html")) results.append("\n");
    } else if (is_inline) {
        results = starttag;
        results.append(contents);
        results.append(closetag);
    } else /** all others */ {
        results = indent_space + starttag;
        if (!keep_whitespace) {
            ltrim(contents);
        }
        results.append(contents);
        results.append(closetag + "\n");
        if (!in_head && (tagname != "html")) results.append("\n");
    }
    return results;
}




// The below are hopefully obsolete now but keep them since
// they are a real pain to recreate and may be needed again
// if other corner cases in gumbo xhtml support are found
#if 0

// handle a few special cases that are hard to deal with insides of gumbo
static QStringList allowed_void_tags = QStringList() << "area"    << "base"     << "basefont" 
                                                     << "bgsound" << "br"       << "col" 
                                                     << "command" << "embed"    << "event-source" 
                                                     << "frame"   << "hr"       << "image" 
                                                     << "img"     << "input"    << "keygen" 
                                                     << "link"    << "menuitem" << "meta" 
                                                     << "param"   << "source"   << "spacer" 
                                                     << "track"   << "wbr";

// Handle the general case
QString GumboInterface::fix_self_closing_tags(const QString &source)
{
    QString newsource = source;
    QRegularExpression selfclosed("<\\s*([a-zA-Z]+)(\\s*[^>/]*)/\\s*>");
    QRegularExpressionMatch match = selfclosed.match(newsource, 0);
    while (match.hasMatch()) {
        if (match.capturedStart() == -1) {
            break;
        }
        QString tag = match.captured(0);
        int sp = match.capturedStart(0);
        int n = match.capturedLength(0);
        QString name = match.captured(1);
        QString atts = match.captured(2);;
        atts = atts.trimmed();
        if (!atts.isEmpty()) {
            atts = " " + atts;
        }
        int nsp = sp + n;
        if (!allowed_void_tags.contains(name)) {
            QString newtag = "<" + name + atts + "></" + name + ">";
            newsource = newsource.replace(sp,n,newtag);
            nsp = sp + newtag.length();
        }
        match = selfclosed.match(newsource, nsp);
    }
    return newsource;
}

// Handle the specific problem of iframe being self-closed
QString GumboInterface::fix_self_closing_tags(const QString &source)
{
    QString newsource = source;
    QRegularExpression selfclosed("<\\s*iframe(\\s*[^>/]*)/\\s*>");
    QRegularExpressionMatch match = selfclosed.match(newsource, 0);
    while (match.hasMatch()) {
        if (match.capturedStart() == -1) {
            break;
        }
        QString tag = match.captured(0);
        int sp = match.capturedStart(0);
        int n = match.capturedLength(0);
        QString atts = match.captured(1);;
        atts = atts.trimmed();
        if (!atts.isEmpty()) {
            atts = " " + atts;
        }
        QString newtag = "<iframe" + atts + "></iframe>";
        newsource = newsource.replace(sp,n,newtag);
        int nsp = sp + newtag.length();
        match = selfclosed.match(newsource, nsp);
    }
    return newsource;
}
#endif