File: templateparser.cpp

package info (click to toggle)
kdepim 4%3A4.14.1-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 62,764 kB
  • sloc: cpp: 530,022; xml: 5,446; perl: 1,434; sh: 812; ansic: 433; php: 44; makefile: 22
file content (1729 lines) | stat: -rw-r--r-- 70,164 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
/*
 * Copyright (C) 2006 Dmitry Morozhnikov <dmiceman@mail.ru>
 * Copyright (C) 2011 Sudhendu Kumar <sudhendu.kumar.roy@gmail.com>
 *
 * This program 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 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "templateparser.h"
#include "globalsettings_base.h"
#include "customtemplates_kfg.h"
#include "templatesconfiguration_kfg.h"
#include "templatesconfiguration.h"

#include <messagecore/attachment/attachmentcollector.h>
#include <messagecore/misc/imagecollector.h>
#include <messagecore/utils/stringutil.h>

#include <messageviewer/viewer/objecttreeparser.h>

#include <KPIMIdentities/Identity>
#include <KPIMIdentities/IdentityManager>

#include <KCalendarSystem>
#include <KCharsets>
#include <KGlobal>
#include <KLocalizedString>
#include <KMessageBox>
#include <KProcess>
#include <KShell>

#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTextCodec>
#include <QWebFrame>
#include <QWebPage>
#include <QTextDocument>

namespace TemplateParser {

static const int PipeTimeout = 15 * 1000;

QTextCodec *selectCharset( const QStringList &charsets, const QString &text )
{
    foreach ( const QString &name, charsets ) {
        // We use KCharsets::codecForName() instead of QTextCodec::codecForName() here, because
        // the former knows us-ascii is latin1.
        bool ok = true;
        QTextCodec *codec;
        if ( name == QLatin1String( "locale" ) ) {
            codec = QTextCodec::codecForLocale();
        } else {
            codec = KGlobal::charsets()->codecForName( name, ok );
        }
        if( !ok || !codec ) {
            kWarning() << "Could not get text codec for charset" << name;
            continue;
        }
        if( codec->canEncode( text ) ) {
            // Special check for us-ascii (needed because us-ascii is not exactly latin1).
            if( name == QLatin1String( "us-ascii" ) && !KMime::isUsAscii( text ) ) {
                continue;
            }
            kDebug() << "Chosen charset" << name << codec->name();
            return codec;
        }
    }
    kDebug() << "No appropriate charset found.";
    return KGlobal::charsets()->codecForName( QLatin1String("utf-8") );
}

TemplateParser::TemplateParser( const KMime::Message::Ptr &amsg, const Mode amode ) :
    mMode( amode ), mIdentity( 0 ),
    mAllowDecryption( true ),
    mDebug( false ), mQuoteString( QLatin1String("> ") ), m_identityManager( 0 ),
    mWrap( true ),
    mColWrap( 80 ),
    mQuotes( ReplyAsOriginalMessage ),
    mForceCursorPosition(false)
{
    mMsg = amsg;

    mEmptySource = new MessageViewer::EmptySource;
    mEmptySource->setAllowDecryption( mAllowDecryption );

    mOtp = new MessageViewer::ObjectTreeParser( mEmptySource );
    mOtp->setAllowAsync( false );
}

void TemplateParser::setSelection( const QString &selection )
{
    mSelection = selection;
}

void TemplateParser::setAllowDecryption( const bool allowDecryption )
{
    mAllowDecryption = allowDecryption;
    mEmptySource->setAllowDecryption( mAllowDecryption );
}

bool TemplateParser::shouldStripSignature() const
{
    // Only strip the signature when replying, it should be preserved when forwarding
    return ( mMode == Reply || mMode == ReplyAll ) && GlobalSettings::self()->stripSignature();
}

void TemplateParser::setIdentityManager( KPIMIdentities::IdentityManager *ident )
{
    m_identityManager = ident;
}

void TemplateParser::setCharsets( const QStringList &charsets )
{
    m_charsets = charsets;
}

TemplateParser::~TemplateParser()
{
    delete mEmptySource;
}

int TemplateParser::parseQuotes( const QString &prefix, const QString &str,
                                 QString &quote ) const
{
    int pos = prefix.length();
    int len;
    int str_len = str.length();

    // Also allow the german lower double-quote sign as quote separator, not only
    // the standard ASCII quote ("). This fixes bug 166728.
    QList< QChar > quoteChars;
    quoteChars.append( QLatin1Char('"') );
    quoteChars.append( 0x201C );

    QChar prev( QChar::Null );

    pos++;
    len = pos;

    while ( pos < str_len ) {
        QChar c = str[pos];

        pos++;
        len++;

        if ( !prev.isNull() ) {
            quote.append( c );
            prev = QChar::Null;
        } else {
            if ( c == QLatin1Char('\\') ) {
                prev = c;
            } else if ( quoteChars.contains( c ) ) {
                break;
            } else {
                quote.append( c );
            }
        }
    }

    return len;
}

QString TemplateParser::getFName( const QString &str )
{
    // simple logic:
    // if there is ',' in name, than format is 'Last, First'
    // else format is 'First Last'
    // last resort -- return 'name' from 'name@domain'
    int sep_pos;
    QString res;
    if ( ( sep_pos = str.indexOf( QLatin1Char( '@' ) ) ) > 0 ) {
        int i;
        for ( i = ( sep_pos - 1 ); i >= 0; --i ) {
            QChar c = str[i];
            if ( c.isLetterOrNumber() ) {
                res.prepend( c );
            } else {
                break;
            }
        }
    } else if ( ( sep_pos = str.indexOf( QLatin1Char( ',' ) ) ) > 0 ) {
        int i;
        bool begin = false;
        const int strLength( str.length() );
        for ( i = sep_pos; i < strLength; ++i ) {
            QChar c = str[i];
            if ( c.isLetterOrNumber() ) {
                begin = true;
                res.append( c );
            } else if ( begin ) {
                break;
            }
        }
    } else {
        int i;
        const int strLength( str.length() );
        for ( i = 0; i < strLength; ++i ) {
            QChar c = str[i];
            if ( c.isLetterOrNumber() ) {
                res.append( c );
            } else {
                break;
            }
        }
    }
    return res;
}

QString TemplateParser::getLName( const QString &str )
{
    // simple logic:
    // if there is ',' in name, than format is 'Last, First'
    // else format is 'First Last'
    int sep_pos;
    QString res;
    if ( ( sep_pos = str.indexOf( QLatin1Char( ',' ) ) ) > 0 ) {
        int i;
        for ( i = sep_pos; i >= 0; --i ) {
            QChar c = str[i];
            if ( c.isLetterOrNumber() ) {
                res.prepend( c );
            } else {
                break;
            }
        }
    } else {
        if ( ( sep_pos = str.indexOf( QLatin1Char( ' ' ) ) ) > 0 ) {
            bool begin = false;
            const int strLength( str.length() );
            for ( int i = sep_pos; i < strLength; ++i ) {
                QChar c = str[i];
                if ( c.isLetterOrNumber() ) {
                    begin = true;
                    res.append( c );
                } else if ( begin ) {
                    break;
                }
            }
        }
    }
    return res;
}

void TemplateParser::process( const KMime::Message::Ptr &aorig_msg,
                              const Akonadi::Collection & afolder )
{
    if( aorig_msg == 0 ) {
        kDebug() << "aorig_msg == 0!";
        return;
    }
    mOrigMsg = aorig_msg;
    mFolder = afolder;
    const QString tmpl = findTemplate();
    if ( tmpl.isEmpty() ) {
        return;
    }
    processWithTemplate( tmpl );
}

void TemplateParser::process( const QString &tmplName, const KMime::Message::Ptr &aorig_msg,
                              const Akonadi::Collection &afolder )
{
    mForceCursorPosition = false;
    mOrigMsg = aorig_msg;
    mFolder = afolder;
    const QString tmpl = findCustomTemplate( tmplName );
    processWithTemplate( tmpl );
}

void TemplateParser::processWithIdentity( uint uoid, const KMime::Message::Ptr &aorig_msg,
                                          const Akonadi::Collection &afolder )
{
    mIdentity = uoid;
    process( aorig_msg, afolder );
}

void TemplateParser::processWithTemplate( const QString &tmpl )
{
    mOtp->parseObjectTree( mOrigMsg.get() );
    const int tmpl_len = tmpl.length();
    QString plainBody, htmlBody;

    bool dnl = false;
    for ( int i = 0; i < tmpl_len; ++i ) {
        QChar c = tmpl[i];
        // kDebug() << "Next char: " << c;
        if ( c == QLatin1Char('%') ) {
            const QString cmd = tmpl.mid( i + 1 );

            if ( cmd.startsWith( QLatin1Char( '-' ) ) ) {
                // dnl
                kDebug() << "Command: -";
                dnl = true;
                i += 1;

            } else if ( cmd.startsWith( QLatin1String( "REM=" ) ) ) {
                // comments
                kDebug() << "Command: REM=";
                QString q;
                int len = parseQuotes( QLatin1String("REM="), cmd, q );
                i += len;

            } else if ( cmd.startsWith( QLatin1String( "INSERT=" ) ) ) {
                // insert content of specified file as is
                kDebug() << "Command: INSERT=";
                QString q;
                int len = parseQuotes( QLatin1String("INSERT="), cmd, q );
                i += len;
                QString path = KShell::tildeExpand( q );
                QFileInfo finfo( path );
                if ( finfo.isRelative() ) {
                    path = QDir::homePath();
                    path += QLatin1Char('/');
                    path += q;
                }
                QFile file( path );
                if ( file.open( QIODevice::ReadOnly ) ) {
                    const QByteArray content = file.readAll();
                    const QString str = QString::fromLocal8Bit( content, content.size() );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                } else if ( mDebug ) {
                    KMessageBox::error(
                                0,
                                i18nc( "@info",
                                       "Cannot insert content from file %1: %2", path, file.errorString() ) );
                }

            } else if ( cmd.startsWith( QLatin1String( "SYSTEM=" ) ) ) {
                // insert content of specified file as is
                kDebug() << "Command: SYSTEM=";
                QString q;
                int len = parseQuotes( QLatin1String("SYSTEM="), cmd, q );
                i += len;
                const QString pipe_cmd = q;
                const QString str = pipe( pipe_cmd, QString() );
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "PUT=" ) ) ) {
                // insert content of specified file as is
                kDebug() << "Command: PUT=";
                QString q;
                int len = parseQuotes( QLatin1String("PUT="), cmd, q );
                i += len;
                QString path = KShell::tildeExpand( q );
                QFileInfo finfo( path );
                if ( finfo.isRelative() ) {
                    path = QDir::homePath();
                    path += QLatin1Char('/');
                    path += q;
                }
                QFile file( path );
                if ( file.open( QIODevice::ReadOnly ) ) {
                    const QByteArray content = file.readAll();
                    plainBody.append( QString::fromLocal8Bit( content, content.size() ) );

                    const QString body = plainToHtml( QString::fromLocal8Bit( content, content.size() ) );
                    htmlBody.append( body );
                } else if ( mDebug ) {
                    KMessageBox::error(
                                0,
                                i18nc( "@info",
                                       "Cannot insert content from file %1: %2", path, file.errorString() ) );
                }

            } else if ( cmd.startsWith( QLatin1String( "QUOTEPIPE=" ) ) ) {
                // pipe message body through command and insert it as quotation
                kDebug() << "Command: QUOTEPIPE=";
                QString q;
                int len = parseQuotes( QLatin1String("QUOTEPIPE="), cmd, q );
                i += len;
                const QString pipe_cmd = q;
                if ( mOrigMsg ) {
                    const QString plainStr =
                            pipe( pipe_cmd, plainMessageText( shouldStripSignature(), NoSelectionAllowed ) );
                    QString plainQuote = quotedPlainText( plainStr );
                    if ( plainQuote.endsWith( QLatin1Char('\n') ) ) {
                        plainQuote.chop( 1 );
                    }
                    plainBody.append( plainQuote );

                    const QString htmlStr =
                            pipe( pipe_cmd, htmlMessageText( shouldStripSignature(), NoSelectionAllowed ) );
                    const QString htmlQuote = quotedHtmlText( htmlStr );
                    htmlBody.append( htmlQuote );
                }

            } else if ( cmd.startsWith( QLatin1String( "QUOTE" ) ) ) {
                kDebug() << "Command: QUOTE";
                i += strlen( "QUOTE" );
                if ( mOrigMsg ) {
                    QString plainQuote =
                            quotedPlainText( plainMessageText( shouldStripSignature(), SelectionAllowed ) );
                    if ( plainQuote.endsWith( QLatin1Char('\n') ) ) {
                        plainQuote.chop( 1 );
                    }
                    plainBody.append( plainQuote );

                    const QString htmlQuote =
                            quotedHtmlText( htmlMessageText( shouldStripSignature(), SelectionAllowed ) );
                    htmlBody.append( htmlQuote );
                }

            } else if ( cmd.startsWith( QLatin1String( "FORCEDPLAIN" ) ) ) {
                kDebug() << "Command: FORCEDPLAIN";
                mQuotes = ReplyAsPlain;
                i += strlen( "FORCEDPLAIN" );

            } else if ( cmd.startsWith( QLatin1String( "FORCEDHTML" ) ) ) {
                kDebug() << "Command: FORCEDHTML";
                mQuotes = ReplyAsHtml;
                i += strlen( "FORCEDHTML" );

            } else if ( cmd.startsWith( QLatin1String( "QHEADERS" ) ) ) {
                kDebug() << "Command: QHEADERS";
                i += strlen( "QHEADERS" );
                if ( mOrigMsg ) {
                    QString plainQuote =
                            quotedPlainText( QString::fromLatin1(MessageCore::StringUtil::headerAsSendableString( mOrigMsg )) );
                    if ( plainQuote.endsWith( QLatin1Char('\n') ) ) {
                        plainQuote.chop( 1 );
                    }
                    plainBody.append( plainQuote );

                    const QString htmlQuote =
                            quotedHtmlText( QString::fromLatin1(MessageCore::StringUtil::headerAsSendableString( mOrigMsg )) );
                    const QString str = plainToHtml( htmlQuote );
                    htmlBody.append( str );
                }

            } else if ( cmd.startsWith( QLatin1String( "HEADERS" ) ) ) {
                kDebug() << "Command: HEADERS";
                i += strlen( "HEADERS" );
                if ( mOrigMsg ) {
                    const QString str = QString::fromLatin1(MessageCore::StringUtil::headerAsSendableString( mOrigMsg ));
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "TEXTPIPE=" ) ) ) {
                // pipe message body through command and insert it as is
                kDebug() << "Command: TEXTPIPE=";
                QString q;
                int len = parseQuotes( QLatin1String("TEXTPIPE="), cmd, q );
                i += len;
                const QString pipe_cmd = q;
                if ( mOrigMsg ) {
                    const QString plainStr =
                            pipe( pipe_cmd, plainMessageText( shouldStripSignature(), NoSelectionAllowed ) );
                    plainBody.append( plainStr );

                    const QString htmlStr =
                            pipe( pipe_cmd, htmlMessageText( shouldStripSignature(), NoSelectionAllowed ) );
                    htmlBody.append( htmlStr );
                }

            } else if ( cmd.startsWith( QLatin1String( "MSGPIPE=" ) ) ) {
                // pipe full message through command and insert result as is
                kDebug() << "Command: MSGPIPE=";
                QString q;
                int len = parseQuotes( QLatin1String("MSGPIPE="), cmd, q );
                i += len;
                if ( mOrigMsg ) {
                    QString pipe_cmd = q;
                    const QString str = pipe( pipe_cmd, QString::fromLatin1(mOrigMsg->encodedContent()) );
                    plainBody.append( str );

                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "BODYPIPE=" ) ) ) {
                // pipe message body generated so far through command and insert result as is
                kDebug() << "Command: BODYPIPE=";
                QString q;
                int len = parseQuotes( QLatin1String("BODYPIPE="), cmd, q );
                i += len;
                const QString pipe_cmd = q;
                const QString plainStr = pipe( pipe_cmd, plainBody );
                plainBody.append( plainStr );

                const QString htmlStr = pipe( pipe_cmd, htmlBody );
                const QString body = plainToHtml( htmlStr );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "CLEARPIPE=" ) ) ) {
                // pipe message body generated so far through command and
                // insert result as is replacing current body
                kDebug() << "Command: CLEARPIPE=";
                QString q;
                int len = parseQuotes( QLatin1String("CLEARPIPE="), cmd, q );
                i += len;
                const QString pipe_cmd = q;
                const QString plainStr = pipe( pipe_cmd, plainBody );
                plainBody = plainStr;

                const QString htmlStr = pipe( pipe_cmd, htmlBody );
                htmlBody = htmlStr;

                KMime::Headers::Generic *header =
                        new KMime::Headers::Generic( "X-KMail-CursorPos", mMsg.get(),
                                                     QString::number( 0 ), "utf-8" );
                mMsg->setHeader( header );

            } else if ( cmd.startsWith( QLatin1String( "TEXT" ) ) ) {
                kDebug() << "Command: TEXT";
                i += strlen( "TEXT" );
                if ( mOrigMsg ) {
                    const QString plainStr = plainMessageText( shouldStripSignature(), NoSelectionAllowed );
                    plainBody.append( plainStr );

                    const QString htmlStr = htmlMessageText( shouldStripSignature(), NoSelectionAllowed );
                    htmlBody.append( htmlStr );
                }

            } else if ( cmd.startsWith( QLatin1String( "OTEXTSIZE" ) ) ) {
                kDebug() << "Command: OTEXTSIZE";
                i += strlen( "OTEXTSIZE" );
                if ( mOrigMsg ) {
                    const QString str = QString::fromLatin1( "%1" ).arg( mOrigMsg->body().length() );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OTEXT" ) ) ) {
                kDebug() << "Command: OTEXT";
                i += strlen( "OTEXT" );
                if ( mOrigMsg ) {
                    const QString plainStr = plainMessageText( shouldStripSignature(), NoSelectionAllowed );
                    plainBody.append( plainStr );

                    const QString htmlStr = htmlMessageText( shouldStripSignature(), NoSelectionAllowed );
                    htmlBody.append( htmlStr );
                }

            } else if ( cmd.startsWith( QLatin1String( "OADDRESSEESADDR" ) ) ) {
                kDebug() << "Command: OADDRESSEESADDR";
                i += strlen( "OADDRESSEESADDR" );
                if ( mOrigMsg ) {
                    const QString to = mOrigMsg->to()->asUnicodeString();
                    const QString cc = mOrigMsg->cc()->asUnicodeString();
                    if ( !to.isEmpty() ) {
                        QString toLine =  i18nc( "@item:intext email To", "To:" ) + QLatin1Char( ' ' ) + to;
                        plainBody.append( toLine );
                        const QString body = plainToHtml( toLine );
                        htmlBody.append( body );
                    }
                    if ( !to.isEmpty() && !cc.isEmpty() ) {
                        plainBody.append( QLatin1Char( '\n' ) );
                        const QString str = plainToHtml( QString( QLatin1Char( '\n' ) ) );
                        htmlBody.append( str );
                    }
                    if ( !cc.isEmpty() ) {
                        QString ccLine = i18nc( "@item:intext email CC", "CC:" ) + QLatin1Char( ' ' ) +  cc;
                        plainBody.append( ccLine );
                        const QString str = plainToHtml( ccLine );
                        htmlBody.append( str );
                    }
                }

            } else if ( cmd.startsWith( QLatin1String( "CCADDR" ) ) ) {
                kDebug() << "Command: CCADDR";
                i += strlen( "CCADDR" );
                const QString str = mMsg->cc()->asUnicodeString();
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "CCNAME" ) ) ) {
                kDebug() << "Command: CCNAME";
                i += strlen( "CCNAME" );
                const QString str =
                        MessageCore::StringUtil::stripEmailAddr( mMsg->cc()->asUnicodeString( ) );
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "CCFNAME" ) ) ) {
                kDebug() << "Command: CCFNAME";
                i += strlen( "CCFNAME" );
                const QString str =
                        MessageCore::StringUtil::stripEmailAddr( mMsg->cc()->asUnicodeString( ) );
                plainBody.append( getFName( str ) );
                const QString body = plainToHtml( getFName( str ) );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "CCLNAME" ) ) ) {
                kDebug() << "Command: CCLNAME";
                i += strlen( "CCLNAME" );
                const QString str =
                        MessageCore::StringUtil::stripEmailAddr( mMsg->cc()->asUnicodeString( ) );
                plainBody.append( getLName( str ) );
                const QString body = plainToHtml( getLName( str ) );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "TOADDR" ) ) ) {
                kDebug() << "Command: TOADDR";
                i += strlen( "TOADDR" );
                const QString str = mMsg->to()->asUnicodeString();
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "TONAME" ) ) ) {
                kDebug() << "Command: TONAME";
                i += strlen( "TONAME" );
                const QString str =
                        MessageCore::StringUtil::stripEmailAddr( mMsg->to()->asUnicodeString( ) );
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "TOFNAME" ) ) ) {
                kDebug() << "Command: TOFNAME";
                i += strlen( "TOFNAME" );
                const QString str =
                        MessageCore::StringUtil::stripEmailAddr( mMsg->to()->asUnicodeString( ) );
                plainBody.append( getFName( str ) );
                const QString body = plainToHtml( getFName( str ) );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "TOLNAME" ) ) ) {
                kDebug() << "Command: TOLNAME";
                i += strlen( "TOLNAME" );
                const QString str =
                        MessageCore::StringUtil::stripEmailAddr( mMsg->to()->asUnicodeString( ) );
                plainBody.append( getLName( str ) );
                const QString body = plainToHtml( getLName( str ) );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "TOLIST" ) ) ) {
                kDebug() << "Command: TOLIST";
                i += strlen( "TOLIST" );
                const QString str = mMsg->to()->asUnicodeString();
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "FROMADDR" ) ) ) {
                kDebug() << "Command: FROMADDR";
                i += strlen( "FROMADDR" );
                const QString str = mMsg->from()->asUnicodeString();
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "FROMNAME" ) ) ) {
                kDebug() << "Command: FROMNAME";
                i += strlen( "FROMNAME" );
                const QString str =
                        MessageCore::StringUtil::stripEmailAddr( mMsg->from()->asUnicodeString( ) );
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "FROMFNAME" ) ) ) {
                kDebug() << "Command: FROMFNAME";
                i += strlen( "FROMFNAME" );
                const QString str =
                        MessageCore::StringUtil::stripEmailAddr( mMsg->from()->asUnicodeString( ) );
                plainBody.append( getFName( str ) );
                const QString body = plainToHtml( getFName( str ) );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "FROMLNAME" ) ) ) {
                kDebug() << "Command: FROMLNAME";
                i += strlen( "FROMLNAME" );
                const QString str =
                        MessageCore::StringUtil::stripEmailAddr( mMsg->from()->asUnicodeString( ) );
                plainBody.append( getLName( str ) );
                const QString body = plainToHtml( getLName( str ) );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "FULLSUBJECT" ) ) ) {
                kDebug() << "Command: FULLSUBJECT";
                i += strlen( "FULLSUBJECT" );
                const QString str = mMsg->subject()->asUnicodeString();
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "FULLSUBJ" ) ) ) {
                kDebug() << "Command: FULLSUBJ";
                i += strlen( "FULLSUBJ" );
                const QString str = mMsg->subject()->asUnicodeString();
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "MSGID" ) ) ) {
                kDebug() << "Command: MSGID";
                i += strlen( "MSGID" );
                const QString str = mMsg->messageID()->asUnicodeString();
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "OHEADER=" ) ) ) {
                // insert specified content of header from original message
                kDebug() << "Command: OHEADER=";
                QString q;
                int len = parseQuotes( QLatin1String("OHEADER="), cmd, q );
                i += len;
                if ( mOrigMsg ) {
                    const QString hdr = q;
                    const QString str =
                            mOrigMsg->headerByType( hdr.toLocal8Bit() ) ?
                                mOrigMsg->headerByType( hdr.toLocal8Bit() )->asUnicodeString() :
                                QString();
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "HEADER=" ) ) ) {
                // insert specified content of header from current message
                kDebug() << "Command: HEADER=";
                QString q;
                int len = parseQuotes( QLatin1String("HEADER="), cmd, q );
                i += len;
                const QString hdr = q;
                const QString str =
                        mMsg->headerByType( hdr.toLocal8Bit() ) ?
                            mMsg->headerByType( hdr.toLocal8Bit() )->asUnicodeString() :
                            QString();
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "HEADER( " ) ) ) {
                // insert specified content of header from current message
                kDebug() << "Command: HEADER(";
                QRegExp re = QRegExp( QLatin1String("^HEADER\\((.+)\\)") );
                re.setMinimal( true );
                int res = re.indexIn( cmd );
                if ( res != 0 ) {
                    // something wrong
                    i += strlen( "HEADER( " );
                } else {
                    i += re.matchedLength();
                    const QString hdr = re.cap( 1 );
                    const QString str =
                            mMsg->headerByType( hdr.toLocal8Bit() ) ?
                                mMsg->headerByType( hdr.toLocal8Bit() )->asUnicodeString() :
                                QString();
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OCCADDR" ) ) ) {
                kDebug() << "Command: OCCADDR";
                i += strlen( "OCCADDR" );
                if ( mOrigMsg ) {
                    const QString str = mOrigMsg->cc()->asUnicodeString();
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OCCNAME" ) ) ) {
                kDebug() << "Command: OCCNAME";
                i += strlen( "OCCNAME" );
                if ( mOrigMsg ) {
                    const QString str =
                            MessageCore::StringUtil::stripEmailAddr( mOrigMsg->cc()->asUnicodeString( ) );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OCCFNAME" ) ) ) {
                kDebug() << "Command: OCCFNAME";
                i += strlen( "OCCFNAME" );
                if ( mOrigMsg ) {
                    const QString str =
                            MessageCore::StringUtil::stripEmailAddr( mOrigMsg->cc()->asUnicodeString( ) );
                    plainBody.append( getFName( str ) );
                    const QString body = plainToHtml( getFName( str ) );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OCCLNAME" ) ) ) {
                kDebug() << "Command: OCCLNAME";
                i += strlen( "OCCLNAME" );
                if ( mOrigMsg ) {
                    const QString str =
                            MessageCore::StringUtil::stripEmailAddr( mOrigMsg->cc()->asUnicodeString( ) );
                    plainBody.append( getLName( str ) );
                    const QString body = plainToHtml( getLName( str ) );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OTOADDR" ) ) ) {
                kDebug() << "Command: OTOADDR";
                i += strlen( "OTOADDR" );
                if ( mOrigMsg ) {
                    const QString str = mOrigMsg->to()->asUnicodeString();
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OTONAME" ) ) ) {
                kDebug() << "Command: OTONAME";
                i += strlen( "OTONAME" );
                if ( mOrigMsg ) {
                    const QString str =
                            MessageCore::StringUtil::stripEmailAddr( mOrigMsg->to()->asUnicodeString( ) );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OTOFNAME" ) ) ) {
                kDebug() << "Command: OTOFNAME";
                i += strlen( "OTOFNAME" );
                if ( mOrigMsg ) {
                    const QString str =
                            MessageCore::StringUtil::stripEmailAddr( mOrigMsg->to()->asUnicodeString( ) );
                    plainBody.append( getFName( str ) );
                    const QString body = plainToHtml( getFName( str ) );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OTOLNAME" ) ) ) {
                kDebug() << "Command: OTOLNAME";
                i += strlen( "OTOLNAME" );
                if ( mOrigMsg ) {
                    const QString str =
                            MessageCore::StringUtil::stripEmailAddr( mOrigMsg->to()->asUnicodeString( ) );
                    plainBody.append( getLName( str ) );
                    const QString body = plainToHtml( getLName( str ) );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OTOLIST" ) ) ) {
                kDebug() << "Command: OTOLIST";
                i += strlen( "OTOLIST" );
                if ( mOrigMsg ) {
                    const QString str = mOrigMsg->to()->asUnicodeString();
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OTO" ) ) ) {
                kDebug() << "Command: OTO";
                i += strlen( "OTO" );
                if ( mOrigMsg ) {
                    const QString str = mOrigMsg->to()->asUnicodeString();
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OFROMADDR" ) ) ) {
                kDebug() << "Command: OFROMADDR";
                i += strlen( "OFROMADDR" );
                if ( mOrigMsg ) {
                    const QString str = mOrigMsg->from()->asUnicodeString();
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OFROMNAME" ) ) ) {
                kDebug() << "Command: OFROMNAME";
                i += strlen( "OFROMNAME" );
                if ( mOrigMsg ) {
                    const QString str =
                            MessageCore::StringUtil::stripEmailAddr( mOrigMsg->from()->asUnicodeString() );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OFROMFNAME" ) ) ) {
                kDebug() << "Command: OFROMFNAME";
                i += strlen( "OFROMFNAME" );
                if ( mOrigMsg ) {
                    const QString str =
                            MessageCore::StringUtil::stripEmailAddr( mOrigMsg->from()->asUnicodeString() );
                    plainBody.append( getFName( str ) );
                    const QString body = plainToHtml( getFName( str ) );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OFROMLNAME" ) ) ) {
                kDebug() << "Command: OFROMLNAME";
                i += strlen( "OFROMLNAME" );
                if ( mOrigMsg ) {
                    const QString str =
                            MessageCore::StringUtil::stripEmailAddr( mOrigMsg->from()->asUnicodeString() );
                    plainBody.append( getLName( str ) );
                    const QString body = plainToHtml( getLName( str ) );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OFULLSUBJECT" ) ) ) {
                kDebug() << "Command: OFULLSUBJECT";
                i += strlen( "OFULLSUBJECT" );
                if ( mOrigMsg ) {
                    const QString str = mOrigMsg->subject()->asUnicodeString();
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OFULLSUBJ" ) ) ) {
                kDebug() << "Command: OFULLSUBJ";
                i += strlen( "OFULLSUBJ" );
                if ( mOrigMsg ) {
                    const QString str = mOrigMsg->subject()->asUnicodeString();
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OMSGID" ) ) ) {
                kDebug() << "Command: OMSGID";
                i += strlen( "OMSGID" );
                if ( mOrigMsg ) {
                    const QString str = mOrigMsg->messageID()->asUnicodeString();
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "DATEEN" ) ) ) {
                kDebug() << "Command: DATEEN";
                i += strlen( "DATEEN" );
                const QDateTime date = QDateTime::currentDateTime();
                KLocale locale( QLatin1String("C") );
                const QString str = locale.formatDate( date.date(), KLocale::LongDate );
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "DATESHORT" ) ) ) {
                kDebug() << "Command: DATESHORT";
                i += strlen( "DATESHORT" );
                const QDateTime date = QDateTime::currentDateTime();
                const QString str = KGlobal::locale()->formatDate( date.date(), KLocale::ShortDate );
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "DATE" ) ) ) {
                kDebug() << "Command: DATE";
                i += strlen( "DATE" );
                const QDateTime date = QDateTime::currentDateTime();
                const QString str = KGlobal::locale()->formatDate( date.date(), KLocale::LongDate );
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "DOW" ) ) ) {
                kDebug() << "Command: DOW";
                i += strlen( "DOW" );
                const QDateTime date = QDateTime::currentDateTime();
                const QString str = KGlobal::locale()->calendar()->weekDayName( date.date(),
                                                                                KCalendarSystem::LongDayName );
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "TIMELONGEN" ) ) ) {
                kDebug() << "Command: TIMELONGEN";
                i += strlen( "TIMELONGEN" );
                const QDateTime date = QDateTime::currentDateTime();
                KLocale locale( QLatin1String("C") );
                const QString str = locale.formatTime( date.time(), true );
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "TIMELONG" ) ) ) {
                kDebug() << "Command: TIMELONG";
                i += strlen( "TIMELONG" );
                const QDateTime date = QDateTime::currentDateTime();
                const QString str = KGlobal::locale()->formatTime( date.time(), true );
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "TIME" ) ) ) {
                kDebug() << "Command: TIME";
                i += strlen( "TIME" );
                const QDateTime date = QDateTime::currentDateTime();
                const QString str = KGlobal::locale()->formatTime( date.time(), false );
                plainBody.append( str );
                const QString body = plainToHtml( str );
                htmlBody.append( body );

            } else if ( cmd.startsWith( QLatin1String( "ODATEEN" ) ) ) {
                kDebug() << "Command: ODATEEN";
                i += strlen( "ODATEEN" );
                if ( mOrigMsg ) {
                    const QDateTime date = mOrigMsg->date()->dateTime().dateTime();
                    KLocale locale( QLatin1String("C") );
                    const QString str = locale.formatDate( date.date(), KLocale::LongDate );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "ODATESHORT" ) ) ) {
                kDebug() << "Command: ODATESHORT";
                i += strlen( "ODATESHORT" );
                if ( mOrigMsg ) {
                    const QDateTime date = mOrigMsg->date()->dateTime().dateTime();
                    const QString str = KGlobal::locale()->formatDate( date.date(), KLocale::ShortDate );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "ODATE" ) ) ) {
                kDebug() << "Command: ODATE";
                i += strlen( "ODATE" );
                if ( mOrigMsg ) {
                    const QDateTime date = mOrigMsg->date()->dateTime().dateTime();
                    const QString str = KGlobal::locale()->formatDate( date.date(), KLocale::LongDate );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "ODOW" ) ) ) {
                kDebug() << "Command: ODOW";
                i += strlen( "ODOW" );
                if ( mOrigMsg ) {
                    const QDateTime date = mOrigMsg->date()->dateTime().dateTime();
                    const QString str =
                            KGlobal::locale()->calendar()->weekDayName( date.date(), KCalendarSystem::LongDayName );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OTIMELONGEN" ) ) ) {
                kDebug() << "Command: OTIMELONGEN";
                i += strlen( "OTIMELONGEN" );
                if ( mOrigMsg ) {
                    const QDateTime date = mOrigMsg->date()->dateTime().dateTime();
                    KLocale locale( QLatin1String("C") );
                    const QString str = locale.formatTime( date.time(), true );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OTIMELONG" ) ) ) {
                kDebug() << "Command: OTIMELONG";
                i += strlen( "OTIMELONG" );
                if ( mOrigMsg ) {
                    const QDateTime date = mOrigMsg->date()->dateTime().dateTime();
                    const QString str = KGlobal::locale()->formatTime( date.time(), true );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "OTIME" ) ) ) {
                kDebug() << "Command: OTIME";
                i += strlen( "OTIME" );
                if ( mOrigMsg ) {
                    const QDateTime date = mOrigMsg->date()->dateTime().dateTime();
                    const QString str = KGlobal::locale()->formatTime( date.time(), false );
                    plainBody.append( str );
                    const QString body = plainToHtml( str );
                    htmlBody.append( body );
                }

            } else if ( cmd.startsWith( QLatin1String( "BLANK" ) ) ) {
                // do nothing
                kDebug() << "Command: BLANK";
                i += strlen( "BLANK" );

            } else if ( cmd.startsWith( QLatin1String( "NOP" ) ) ) {
                // do nothing
                kDebug() << "Command: NOP";
                i += strlen( "NOP" );

            } else if ( cmd.startsWith( QLatin1String( "CLEAR" ) ) ) {
                // clear body buffer; not too useful yet
                kDebug() << "Command: CLEAR";
                i += strlen( "CLEAR" );
                plainBody.clear();
                htmlBody.clear();
                KMime::Headers::Generic *header =
                        new KMime::Headers::Generic( "X-KMail-CursorPos", mMsg.get(),
                                                     QString::number( 0 ), "utf-8" );
                mMsg->setHeader( header );
            } else if ( cmd.startsWith( QLatin1String( "DEBUGOFF" ) ) ) {
                // turn off debug
                kDebug() << "Command: DEBUGOFF";
                i += strlen( "DEBUGOFF" );
                mDebug = false;

            } else if ( cmd.startsWith( QLatin1String( "DEBUG" ) ) ) {
                // turn on debug
                kDebug() << "Command: DEBUG";
                i += strlen( "DEBUG" );
                mDebug = true;

            } else if ( cmd.startsWith( QLatin1String( "CURSOR" ) ) ) {
                // turn on debug
                kDebug() << "Command: CURSOR";
                int oldI = i;
                i += strlen( "CURSOR" );
                KMime::Headers::Generic *header =
                        new KMime::Headers::Generic( "X-KMail-CursorPos", mMsg.get(),
                                                     QString::number( plainBody.length() ), "utf-8" );
                /* if template is:
         *  FOOBAR
         *  %CURSOR
         *
         * Make sure there is an empty line for the cursor otherwise it will be placed at the end of FOOBAR
         */
                if ( oldI > 0 && tmpl[ oldI - 1 ] == QLatin1Char('\n') && i == tmpl_len - 1 ) {
                    plainBody.append( QLatin1Char('\n') );
                }
                mMsg->setHeader( header );
                mForceCursorPosition = true;
                //FIXME HTML part for header remaining
            } else if ( cmd.startsWith( QLatin1String( "SIGNATURE" ) ) ) {
                kDebug() << "Command: SIGNATURE";
                i += strlen( "SIGNATURE" );
                plainBody.append( getPlainSignature() );
                htmlBody.append( getHtmlSignature() );

            } else {
                // wrong command, do nothing
                plainBody.append( c );
                htmlBody.append( c );
            }

        } else if ( dnl && ( c == QLatin1Char('\n') || c == QLatin1Char('\r') ) ) {
            // skip
            if ( ( tmpl.size() > i+1 ) &&
                 ( ( c == QLatin1Char('\n') && tmpl[i + 1] == QLatin1Char('\r') ) ||
                   ( c == QLatin1Char('\r') && tmpl[i + 1] == QLatin1Char('\n') ) ) ) {
                // skip one more
                i += 1;
            }
            dnl = false;
        } else {
            plainBody.append( c );
            if( c == QLatin1Char('\n') || c == QLatin1Char('\r') ) {
                htmlBody.append( QLatin1String( "<br />" ) );
                htmlBody.append( c );
                if( tmpl.size() > i+1 &&
                        ( ( c == QLatin1Char('\n') && tmpl[i + 1] == QLatin1Char('\r') ) ||
                          ( c == QLatin1Char('\r') && tmpl[i + 1] == QLatin1Char('\n') ) ) ) {
                    htmlBody.append( tmpl[i + 1] );
                    plainBody.append( tmpl[i + 1] );
                    i += 1;
                }
            } else {
                htmlBody.append( c );
            }
        }
    }
    // Clear the HTML body if FORCEDPLAIN has set ReplyAsPlain, OR if,
    // there is no use of FORCED command but a configure setting has ReplyUsingHtml disabled,
    // OR the original mail has no HTML part.
    const KMime::Content *content = mOrigMsg->mainBodyPart( "text/html" );
    if( mQuotes == ReplyAsPlain ||
            ( mQuotes != ReplyAsHtml && !GlobalSettings::self()->replyUsingHtml() ) ||
            (!content || !content->hasContent() ) ) {
        htmlBody.clear();
    } else {
        makeValidHtml( htmlBody );
    }
    addProcessedBodyToMessage( plainBody, htmlBody );
}

QString TemplateParser::getPlainSignature() const
{
    const KPIMIdentities::Identity &identity =
            m_identityManager->identityForUoid( mIdentity );

    if ( identity.isNull() ) {
        return QString();
    }

    KPIMIdentities::Signature signature =
            const_cast<KPIMIdentities::Identity &>( identity ).signature();

    if ( signature.type() == KPIMIdentities::Signature::Inlined &&
         signature.isInlinedHtml() ) {
        return signature.toPlainText();
    } else {
        return signature.rawText();
    }
}
// TODO If %SIGNATURE command is on, then override it with signature from
// "KMail configure->General->identity->signature".
// There should be no two signatures.
QString TemplateParser::getHtmlSignature() const
{
    const KPIMIdentities::Identity &identity =
            m_identityManager->identityForUoid( mIdentity );
    if ( identity.isNull() ) {
        return QString();
    }

    KPIMIdentities::Signature signature =
            const_cast<KPIMIdentities::Identity &>( identity ).signature();

    if ( !signature.isInlinedHtml() ) {
        Qt::escape( signature.rawText() );
        return signature.rawText().replace( QRegExp( QLatin1String("\n") ), QLatin1String("<br />") );
    }
    return signature.rawText();
}

void TemplateParser::addProcessedBodyToMessage( const QString &plainBody,
                                                const QString &htmlBody ) const
{
    // Get the attachments of the original mail
    MessageCore::AttachmentCollector ac;
    ac.collectAttachmentsFrom( mOrigMsg.get() );

    MessageCore::ImageCollector ic;
    ic.collectImagesFrom( mOrigMsg.get() );

    // Now, delete the old content and set the new content, which
    // is either only the new text or the new text with some attachments.
    KMime::Content::List parts = mMsg->contents();
    foreach ( KMime::Content *content, parts ) {
        mMsg->removeContent( content, true/*delete*/ );
    }

    // Set To and CC from the template
    if ( !mTo.isEmpty() ) {
        mMsg->to()->fromUnicodeString( mMsg->to()->asUnicodeString() + QLatin1Char(',') + mTo, "utf-8" );
    }

    if ( !mCC.isEmpty() ) {
        mMsg->cc()->fromUnicodeString( mMsg->cc()->asUnicodeString() + QLatin1Char(',') + mCC, "utf-8" );
    }

    mMsg->contentType()->clear(); // to get rid of old boundary

    const QByteArray boundary = KMime::multiPartBoundary();
    KMime::Content *const mainTextPart =
            htmlBody.isEmpty() ?
                createPlainPartContent( plainBody ) :
                createMultipartAlternativeContent( plainBody, htmlBody );
    mainTextPart->assemble();

    KMime::Content *textPart = mainTextPart;
    if ( !ic.images().empty() ) {
        textPart = createMultipartRelated( ic, mainTextPart );
        textPart->assemble();
    }

    // If we have some attachments, create a multipart/mixed mail and
    // add the normal body as well as the attachments
    KMime::Content *mainPart = textPart;
    if ( !ac.attachments().empty() && mMode == Forward ) {
        mainPart = createMultipartMixed( ac, textPart );
        mainPart->assemble();
    }

    mMsg->setBody( mainPart->encodedBody() );
    mMsg->setHeader( mainPart->contentType() );
    mMsg->setHeader( mainPart->contentTransferEncoding() );
    mMsg->assemble();
    mMsg->parse();
}

KMime::Content *TemplateParser::createMultipartMixed( const MessageCore::AttachmentCollector &ac,
                                                      KMime::Content *textPart ) const
{
    KMime::Content *mixedPart = new KMime::Content( mMsg.get() );
    const QByteArray boundary = KMime::multiPartBoundary();
    mixedPart->contentType()->setMimeType( "multipart/mixed" );
    mixedPart->contentType()->setBoundary( boundary );
    mixedPart->contentTransferEncoding()->setEncoding( KMime::Headers::CE7Bit );
    mixedPart->addContent( textPart );

    int attachmentNumber = 1;
    foreach ( KMime::Content *attachment, ac.attachments() ) {
        mixedPart->addContent( attachment );
        // If the content type has no name or filename parameter, add one, since otherwise the name
        // would be empty in the attachment view of the composer, which looks confusing
        if ( attachment->contentType( false ) ) {
            if ( !attachment->contentType()->hasParameter( QLatin1String("name") ) &&
                 !attachment->contentType()->hasParameter( QLatin1String("filename") ) ) {
                attachment->contentType()->setParameter(
                            QLatin1String("name"), i18nc( "@item:intext", "Attachment %1", attachmentNumber ) );
            }
        }
        attachmentNumber++;
    }
    return mixedPart;
}

KMime::Content *TemplateParser::createMultipartRelated( const MessageCore::ImageCollector &ic,
                                                        KMime::Content *mainTextPart ) const
{
    KMime::Content *relatedPart = new KMime::Content( mMsg.get() );
    const QByteArray boundary = KMime::multiPartBoundary();
    relatedPart->contentType()->setMimeType( "multipart/related" );
    relatedPart->contentType()->setBoundary( boundary );
    relatedPart->contentTransferEncoding()->setEncoding( KMime::Headers::CE7Bit );
    relatedPart->addContent( mainTextPart );
    foreach ( KMime::Content *image, ic.images() ) {
        kWarning() << "Adding" << image->contentID() << "as an embedded image";
        relatedPart->addContent( image );
    }
    return relatedPart;
}

KMime::Content *TemplateParser::createPlainPartContent( const QString &plainBody ) const
{
    KMime::Content *textPart = new KMime::Content( mMsg.get() );
    textPart->contentType()->setMimeType( "text/plain" );
    QTextCodec *charset = selectCharset( m_charsets, plainBody );
    textPart->contentType()->setCharset( charset->name() );
    textPart->contentTransferEncoding()->setEncoding( KMime::Headers::CE8Bit );
    textPart->fromUnicodeString( plainBody );
    return textPart;
}

KMime::Content *TemplateParser::createMultipartAlternativeContent( const QString &plainBody,
                                                                   const QString &htmlBody ) const
{
    KMime::Content *multipartAlternative = new KMime::Content( mMsg.get() );
    multipartAlternative->contentType()->setMimeType( "multipart/alternative" );
    const QByteArray boundary = KMime::multiPartBoundary();
    multipartAlternative->contentType()->setBoundary( boundary );

    KMime::Content *textPart = createPlainPartContent( plainBody );
    multipartAlternative->addContent( textPart );

    KMime::Content *htmlPart = new KMime::Content( mMsg.get() );
    htmlPart->contentType()->setMimeType( "text/html" );
    QTextCodec *charset = selectCharset( m_charsets, htmlBody );
    htmlPart->contentType()->setCharset( charset->name() );
    htmlPart->contentTransferEncoding()->setEncoding( KMime::Headers::CE8Bit );
    htmlPart->fromUnicodeString( htmlBody );
    multipartAlternative->addContent( htmlPart );

    return multipartAlternative;
}

QString TemplateParser::findCustomTemplate( const QString &tmplName )
{
    CTemplates t( tmplName );
    mTo = t.to();
    mCC = t.cC();
    const QString content = t.content();
    if ( !content.isEmpty() ) {
        return content;
    } else {
        return findTemplate();
    }
}

QString TemplateParser::findTemplate()
{
    // kDebug() << "Trying to find template for mode" << mode;

    QString tmpl;

#if 0
    if ( !mFolder.isValid() ) { // find folder message belongs to
        mFolder = mMsg->parentCollection();
        if ( !mFolder.isValid() ) {
            if ( mOrigMsg ) {
                mFolder = mOrigMsg->parentCollection();
            }
            if ( !mFolder.isValid() ) {
                kDebug() << "Oops! No folder for message";
            }
        }
    }
#else
    kDebug() << "AKONADI PORT: Disabled code in  " << Q_FUNC_INFO;
    kDebug() << "Folder found:" << mFolder;
    if ( mFolder.isValid() ) { // only if a folder was found
        QString fid = QString::number( mFolder.id() );
        Templates fconf( fid );
        if ( fconf.useCustomTemplates() ) {   // does folder use custom templates?
            switch( mMode ) {
            case NewMessage:
                tmpl = fconf.templateNewMessage();
                break;
            case Reply:
                tmpl = fconf.templateReply();
                break;
            case ReplyAll:
                tmpl = fconf.templateReplyAll();
                break;
            case Forward:
                tmpl = fconf.templateForward();
                break;
            default:
                kDebug() << "Unknown message mode:" << mMode;
                return QString();
            }
            mQuoteString = fconf.quoteString();
            if ( !tmpl.isEmpty() ) {
                return tmpl;  // use folder-specific template
            }
        }
    }

    if ( !mIdentity ) { // find identity message belongs to
        kDebug() << "AKONADI PORT: verify Akonadi::Item() here  " << Q_FUNC_INFO;

        mIdentity = identityUoid( mMsg );
        if ( !mIdentity && mOrigMsg ) {
            kDebug() << "AKONADI PORT: verify Akonadi::Item() here  " << Q_FUNC_INFO;
            mIdentity = identityUoid( mOrigMsg );
        }
        mIdentity = m_identityManager->identityForUoidOrDefault( mIdentity ).uoid();
        if ( !mIdentity ) {
            kDebug() << "Oops! No identity for message";
        }
    }
    kDebug() << "Identity found:" << mIdentity;

    QString iid;
    if ( mIdentity ) {
        iid = TemplatesConfiguration::configIdString( mIdentity );        // templates ID for that identity
    } else {
        iid = QLatin1String("IDENTITY_NO_IDENTITY"); // templates ID for no identity
    }

    Templates iconf( iid );
    if ( iconf.useCustomTemplates() ) { // does identity use custom templates?
        switch( mMode ) {
        case NewMessage:
            tmpl = iconf.templateNewMessage();
            break;
        case Reply:
            tmpl = iconf.templateReply();
            break;
        case ReplyAll:
            tmpl = iconf.templateReplyAll();
            break;
        case Forward:
            tmpl = iconf.templateForward();
            break;
        default:
            kDebug() << "Unknown message mode:" << mMode;
            return QString();
        }
        mQuoteString = iconf.quoteString();
        if ( !tmpl.isEmpty() ) {
            return tmpl;  // use identity-specific template
        }
    }
#endif

    switch( mMode ) { // use the global template
    case NewMessage:
        tmpl = GlobalSettings::self()->templateNewMessage();
        break;
    case Reply:
        tmpl = GlobalSettings::self()->templateReply();
        break;
    case ReplyAll:
        tmpl = GlobalSettings::self()->templateReplyAll();
        break;
    case Forward:
        tmpl = GlobalSettings::self()->templateForward();
        break;
    default:
        kDebug() << "Unknown message mode:" << mMode;
        return QString();
    }

    mQuoteString = GlobalSettings::self()->quoteString();
    return tmpl;
}

QString TemplateParser::pipe( const QString &cmd, const QString &buf )
{
    KProcess process;
    bool success;

    process.setOutputChannelMode( KProcess::SeparateChannels );
    process.setShellCommand( cmd );
    process.start();
    if ( process.waitForStarted( PipeTimeout ) ) {
        bool finished = false;
        if ( !buf.isEmpty() ) {
            process.write( buf.toLatin1() );
        }
        if ( buf.isEmpty() || process.waitForBytesWritten( PipeTimeout ) ) {
            if ( !buf.isEmpty() ) {
                process.closeWriteChannel();
            }
            if ( process.waitForFinished( PipeTimeout ) ) {
                success = ( process.exitStatus() == QProcess::NormalExit );
                finished = true;
            } else {
                finished = false;
                success = false;
            }
        } else {
            success = false;
            finished = false;
        }

        // The process has started, but did not finish in time. Kill it.
        if ( !finished ) {
            process.kill();
        }
    } else {
        success = false;
    }

    if ( !success && mDebug ) {
        KMessageBox::error(
                    0,
                    i18nc( "@info",
                           "Pipe command <command>%1</command> failed.", cmd ) );
    }

    if ( success ) {
        return QString::fromLatin1(process.readAllStandardOutput());
    } else {
        return QString();
    }
}

void TemplateParser::setWordWrap( bool wrap, int wrapColWidth )
{
    mWrap = wrap;
    mColWrap = wrapColWidth;
}

QString TemplateParser::plainMessageText( bool aStripSignature,
                                          AllowSelection isSelectionAllowed ) const
{
    if ( !mSelection.isEmpty() && ( isSelectionAllowed == SelectionAllowed ) ) {
        return mSelection;
    }

    if ( !mOrigMsg ) {
        return QString();
    }

    QString result = mOtp->plainTextContent();

    if ( result.isEmpty() ) { //HTML-only mails
        result = mOtp->convertedTextContent();
    }

    if ( aStripSignature ) {
        result = MessageCore::StringUtil::stripSignature( result );
    }

    return result;
}

QString TemplateParser::htmlMessageText( bool aStripSignature, AllowSelection isSelectionAllowed )
{
    if( !mSelection.isEmpty() && ( isSelectionAllowed == SelectionAllowed ) ) {
        //TODO implement mSelection for HTML
        return mSelection;
    }

    QString htmlElement = mOtp->htmlContent();

    if ( htmlElement.isEmpty() ) { //plain mails only
        htmlElement = mOtp->convertedHtmlContent();
    }

    QWebPage page;
    page.settings()->setAttribute( QWebSettings::JavascriptEnabled, false );
    page.settings()->setAttribute( QWebSettings::JavaEnabled, false );
    page.settings()->setAttribute( QWebSettings::PluginsEnabled, false );
    page.settings()->setAttribute( QWebSettings::AutoLoadImages, false );

    page.currentFrame()->setHtml( htmlElement );

    //TODO to be tested/verified if this is not an issue
    page.settings()->setAttribute( QWebSettings::JavascriptEnabled, true );
    const QString bodyElement = page.currentFrame()->evaluateJavaScript(
                QLatin1String("document.getElementsByTagName('body')[0].innerHTML") ).toString();

    mHeadElement = page.currentFrame()->evaluateJavaScript(
                QLatin1String("document.getElementsByTagName('head')[0].innerHTML") ).toString();

    page.settings()->setAttribute( QWebSettings::JavascriptEnabled, false );

    if( !bodyElement.isEmpty() ) {
        if ( aStripSignature ) {
            //FIXME strip signature works partially for HTML mails
            return MessageCore::StringUtil::stripSignature( bodyElement );
        }
        return bodyElement;
    }

    if ( aStripSignature ) {
        //FIXME strip signature works partially for HTML mails
        return MessageCore::StringUtil::stripSignature( htmlElement );
    }
    return htmlElement;
}

QString TemplateParser::quotedPlainText( const QString &selection ) const
{
    QString content = selection;
    // Remove blank lines at the beginning:
    const int firstNonWS = content.indexOf( QRegExp( QLatin1String("\\S") ) );
    const int lineStart = content.lastIndexOf( QLatin1Char('\n'), firstNonWS );
    if ( lineStart >= 0 ) {
        content.remove( 0, static_cast<unsigned int>( lineStart ) );
    }

    const QString indentStr =
            MessageCore::StringUtil::formatString( mQuoteString, mOrigMsg->from()->asUnicodeString() );
    if ( GlobalSettings::self()->smartQuote() && mWrap ) {
        content = MessageCore::StringUtil::smartQuote( content, mColWrap - indentStr.length() );
    }
    content.replace( QLatin1Char('\n'), QLatin1Char('\n') + indentStr );
    content.prepend( indentStr );
    content += QLatin1Char('\n');

    return content;
}

QString TemplateParser::quotedHtmlText( const QString &selection ) const
{
    QString content = selection;
    //TODO 1) look for all the variations of <br>  and remove the blank lines
    //2) implement vertical bar for quoted HTML mail.
    //3) After vertical bar is implemented, If a user wants to edit quoted message,
    // then the <blockquote> tags below should open and close as when required.

    //Add blockquote tag, so that quoted message can be differentiated from normal message
    content = QLatin1String("<blockquote>") + content + QLatin1String("</blockquote>");
    return content;
}

uint TemplateParser::identityUoid( const KMime::Message::Ptr &msg ) const
{
    QString idString;
    if ( msg->headerByType( "X-KMail-Identity" ) ) {
        idString = msg->headerByType( "X-KMail-Identity" )->asUnicodeString().trimmed();
    }
    bool ok = false;
    int id = idString.toUInt( &ok );

    if ( !ok || id == 0 ) {
        id = m_identityManager->identityForAddress(
                    msg->to()->asUnicodeString() + QLatin1String(", ") + msg->cc()->asUnicodeString() ).uoid();
    }

    return id;
}

bool TemplateParser::isHtmlSignature() const
{
    const KPIMIdentities::Identity &identity =
            m_identityManager->identityForUoid( mIdentity );

    if ( identity.isNull() ) {
        return false;
    }

    const KPIMIdentities::Signature signature =
            const_cast<KPIMIdentities::Identity &>( identity ).signature();

    return signature.isInlinedHtml();
}

QString TemplateParser::plainToHtml( const QString &body ) const
{
    QString str = body;
    str = Qt::escape( str );
    str.replace( QRegExp( QLatin1String("\n") ), QLatin1String("<br />\n") );
    return str;
}

//TODO implement this function using a DOM tree parser
void TemplateParser::makeValidHtml( QString &body )
{
    QRegExp regEx;
    regEx.setMinimal( true );
    regEx.setPattern( QLatin1String("<html.*>") );

    if ( !body.isEmpty() && !body.contains( regEx ) ) {
        regEx.setPattern( QLatin1String("<body.*>") );
        if ( !body.contains( regEx ) ) {
            body = QLatin1String("<body>") + body + QLatin1String("<br/></body>");
        }
        regEx.setPattern( QLatin1String("<head.*>") );
        if ( !body.contains( regEx ) ) {
            body = QLatin1String("<head>") + mHeadElement + QLatin1String("</head>") + body;
        }
        body = QLatin1String("<html>") + body + QLatin1String("</html>");
    }
}

bool TemplateParser::cursorPositionWasSet() const
{
    return mForceCursorPosition;
}

}