Python indenter: Skip past empty lines

When trying to determine the indentation for non-empty lines, skip back
past empty lines when trying to find the previous indentation.

This prevents code from being inserted at 0 when pasting in below empty
lines.

Change-Id: I6e13e4146e6637180142c0e0b3f9cdafa89df3e5
Reviewed-by: André Hartmann <aha_1980@gmx.de>
Reviewed-by: hjk <hjk@qt.io>
This commit is contained in:
Friedemann Kleint
2017-09-13 11:08:50 +02:00
parent 3c25b1e3be
commit 7832806439

View File

@@ -28,8 +28,28 @@
#include <texteditor/tabsettings.h> #include <texteditor/tabsettings.h>
#include <algorithm>
namespace PythonEditor { namespace PythonEditor {
static bool isEmptyLine(const QString &t)
{
return std::all_of(t.cbegin(), t.cend(), [] (QChar c) { return c.isSpace(); });
}
static inline bool isEmptyLine(const QTextBlock &block)
{
return isEmptyLine(block.text());
}
static QTextBlock previousNonEmptyBlock(const QTextBlock &block)
{
QTextBlock result = block;
while (result.isValid() && isEmptyLine(result))
result = result.previous();
return result;
}
/** /**
* @brief Does given character change indentation level? * @brief Does given character change indentation level?
* @param ch Any value * @param ch Any value
@@ -46,6 +66,15 @@ int PythonIndenter::indentFor(const QTextBlock &block, const TextEditor::TabSett
if (!previousBlock.isValid()) if (!previousBlock.isValid())
return 0; return 0;
// When pasting in actual code, try to skip back past empty lines to an
// actual code line to find a suitable indentation. This prevents code from
// not being indented when pasting below an empty line.
if (!isEmptyLine(block)) {
const QTextBlock previousNonEmpty = previousNonEmptyBlock(previousBlock);
if (previousNonEmpty.isValid())
previousBlock = previousNonEmpty;
}
QString previousLine = previousBlock.text(); QString previousLine = previousBlock.text();
int indentation = tabSettings.indentationColumn(previousLine); int indentation = tabSettings.indentationColumn(previousLine);