1/*
2 SPDX-FileCopyrightText: 2008 Paul Giannaros <paul@giannaros.org>
3 SPDX-FileCopyrightText: 2009-2018 Dominik Haumann <dhaumann@kde.org>
4
5 SPDX-License-Identifier: LGPL-2.0-or-later
6*/
7
8#include "kateindentscript.h"
9
10#include <QJSEngine>
11#include <QJSValue>
12
13KateIndentScript::KateIndentScript(const QString &url, const KateIndentScriptHeader &header)
14 : KateScript(url)
15 , m_indentHeader(header)
16{
17}
18
19const KateIndentScriptHeader &KateIndentScript::indentHeader() const
20{
21 return m_indentHeader;
22}
23
24const QString &KateIndentScript::triggerCharacters()
25{
26 // already set, perfect, just return...
27 if (m_triggerCharactersSet) {
28 return m_triggerCharacters;
29 }
30
31 m_triggerCharactersSet = true;
32
33 auto triggerCharacters = global(QStringLiteral("triggerCharacters"));
34 if (!triggerCharacters.isUndefined()) {
35 m_triggerCharacters = triggerCharacters.toString();
36 }
37
38 // qCDebug(LOG_KTE) << "trigger chars: '" << m_triggerCharacters << "'";
39
40 return m_triggerCharacters;
41}
42
43QPair<int, int> KateIndentScript::indent(KTextEditor::ViewPrivate *view, const KTextEditor::Cursor position, QChar typedCharacter, int indentWidth)
44{
45 // if it hasn't loaded or we can't load, return
46 if (!setView(view)) {
47 return qMakePair(value1: -2, value2: -2);
48 }
49
50 clearExceptions();
51 QJSValue indentFunction = function(QStringLiteral("indent"));
52 if (!indentFunction.isCallable()) {
53 return qMakePair(value1: -2, value2: -2);
54 }
55 // add the arguments that we are going to pass to the function
56 QJSValueList arguments;
57 arguments << QJSValue(position.line());
58 arguments << QJSValue(indentWidth);
59 arguments << (typedCharacter.isNull() ? QJSValue(QString()) : QJSValue(QString(typedCharacter)));
60 // get the required indent
61 QJSValue result = indentFunction.call(args: arguments);
62 // error during the calling?
63 if (result.isError()) {
64 displayBacktrace(error: result, QStringLiteral("Error calling indent()"));
65 return qMakePair(value1: -2, value2: -2);
66 }
67 int indentAmount = -2;
68 int alignAmount = -2;
69 if (result.isArray()) {
70 indentAmount = result.property(arrayIndex: 0).toInt();
71 alignAmount = result.property(arrayIndex: 1).toInt();
72 } else {
73 indentAmount = result.toInt();
74 }
75
76 return qMakePair(value1&: indentAmount, value2&: alignAmount);
77}
78

source code of ktexteditor/src/script/kateindentscript.cpp