1 /* Copyright (C) 2006 - 2014 Jan Kundrát <jkt@flaska.net>
3 This file is part of the Trojita Qt IMAP e-mail client,
4 http://trojita.flaska.net/
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License as
8 published by the Free Software Foundation; either version 2 of
9 the License or (at your option) version 3 or any later version
10 accepted by the membership of KDE e.V. (or its successor approved
11 by the membership of KDE e.V.), which shall act as a proxy
12 defined in Section 14 of version 3 of the license.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "ReplaceSignature.h"
25 #include <QTextCursor>
26 #include <QTextDocument>
31 void replaceSignature(QTextDocument
*document
, const QString
&newSignature
)
33 // The QTextEdit is set up in such a way as to treat a fully terminated line as a standalone text block,
34 // hence no newlines in the signature separator
35 const QLatin1String
signatureSeperator("-- ");
37 QTextBlock block
= document
->lastBlock();
38 while (block
.isValid() && block
.blockNumber() > 0) {
39 if (block
.text() == signatureSeperator
) {
40 // So this block holds the last signature separator -- great!
43 block
= block
.previous();
46 QTextCursor
cursor(block
);
47 if (block
.text() == signatureSeperator
) {
48 // Remove everything till the end of the document since the end of the previous block
49 if (block
.previous().isValid()) {
50 // Prevent adding newlines when switching signatures
51 block
= block
.previous();
52 cursor
= QTextCursor(block
);
53 cursor
.movePosition(QTextCursor::EndOfBlock
);
55 cursor
.beginEditBlock();
56 cursor
.movePosition(QTextCursor::End
, QTextCursor::KeepAnchor
);
57 cursor
.removeSelectedText();
58 cursor
.endEditBlock();
60 // We have not removed anything, so we have to "fake" an edit action so that we're adding the signature to a correct place
61 block
= document
->lastBlock();
62 cursor
= QTextCursor(block
);
63 cursor
.movePosition(QTextCursor::EndOfBlock
);
64 cursor
.beginEditBlock();
65 cursor
.endEditBlock();
68 if (!newSignature
.isEmpty()) {
69 cursor
.joinPreviousEditBlock();
71 cursor
.insertText(signatureSeperator
);
73 cursor
.insertText(newSignature
);
74 cursor
.endEditBlock();