From 78328064395b029bb4c13e87404ed4484c903a79 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Wed, 13 Sep 2017 11:08:50 +0200 Subject: [PATCH] Python indenter: Skip past empty lines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Reviewed-by: hjk --- src/plugins/pythoneditor/pythonindenter.cpp | 29 +++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/plugins/pythoneditor/pythonindenter.cpp b/src/plugins/pythoneditor/pythonindenter.cpp index 70b431368cd..035f1aef7cd 100644 --- a/src/plugins/pythoneditor/pythonindenter.cpp +++ b/src/plugins/pythoneditor/pythonindenter.cpp @@ -28,8 +28,28 @@ #include +#include + 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? * @param ch Any value @@ -46,6 +66,15 @@ int PythonIndenter::indentFor(const QTextBlock &block, const TextEditor::TabSett if (!previousBlock.isValid()) 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(); int indentation = tabSettings.indentationColumn(previousLine);