File indexing completed on 2024-04-28 15:30:41

0001 /*
0002     SPDX-FileCopyrightText: 2008 Paul Giannaros <paul@giannaros.org>
0003     SPDX-FileCopyrightText: 2009-2018 Dominik Haumann <dhaumann@kde.org>
0004 
0005     SPDX-License-Identifier: LGPL-2.0-or-later
0006 */
0007 
0008 #include "kateindentscript.h"
0009 
0010 #include <QJSEngine>
0011 #include <QJSValue>
0012 
0013 #include "katedocument.h"
0014 
0015 KateIndentScript::KateIndentScript(const QString &url, const KateIndentScriptHeader &header)
0016     : KateScript(url)
0017     , m_indentHeader(header)
0018 {
0019 }
0020 
0021 const KateIndentScriptHeader &KateIndentScript::indentHeader() const
0022 {
0023     return m_indentHeader;
0024 }
0025 
0026 const QString &KateIndentScript::triggerCharacters()
0027 {
0028     // already set, perfect, just return...
0029     if (m_triggerCharactersSet) {
0030         return m_triggerCharacters;
0031     }
0032 
0033     m_triggerCharactersSet = true;
0034 
0035     auto triggerCharacters = global(QStringLiteral("triggerCharacters"));
0036     if (!triggerCharacters.isUndefined()) {
0037         m_triggerCharacters = triggerCharacters.toString();
0038     }
0039 
0040     // qCDebug(LOG_KTE) << "trigger chars: '" << m_triggerCharacters << "'";
0041 
0042     return m_triggerCharacters;
0043 }
0044 
0045 QPair<int, int> KateIndentScript::indent(KTextEditor::ViewPrivate *view, const KTextEditor::Cursor position, QChar typedCharacter, int indentWidth)
0046 {
0047     // if it hasn't loaded or we can't load, return
0048     if (!setView(view)) {
0049         return qMakePair(-2, -2);
0050     }
0051 
0052     clearExceptions();
0053     QJSValue indentFunction = function(QStringLiteral("indent"));
0054     if (!indentFunction.isCallable()) {
0055         return qMakePair(-2, -2);
0056     }
0057     // add the arguments that we are going to pass to the function
0058     QJSValueList arguments;
0059     arguments << QJSValue(position.line());
0060     arguments << QJSValue(indentWidth);
0061     arguments << (typedCharacter.isNull() ? QJSValue(QString()) : QJSValue(QString(typedCharacter)));
0062     // get the required indent
0063     QJSValue result = indentFunction.call(arguments);
0064     // error during the calling?
0065     if (result.isError()) {
0066         displayBacktrace(result, QStringLiteral("Error calling indent()"));
0067         return qMakePair(-2, -2);
0068     }
0069     int indentAmount = -2;
0070     int alignAmount = -2;
0071     if (result.isArray()) {
0072         indentAmount = result.property(0).toInt();
0073         alignAmount = result.property(1).toInt();
0074     } else {
0075         indentAmount = result.toInt();
0076     }
0077 
0078     return qMakePair(indentAmount, alignAmount);
0079 }