29#include <QDesktopServices>
39#include <Qsci/qscilexerpython.h>
41#include "moc_qgscodeeditorpython.cpp"
43using namespace Qt::StringLiterals;
45const QMap<QString, QString> QgsCodeEditorPython::sCompletionPairs { {
"(",
")" }, {
"[",
"]" }, {
"{",
"}" }, {
"'",
"'" }, {
"\"",
"\"" } };
46const QStringList QgsCodeEditorPython::sCompletionSingleCharacters {
"`",
"*" };
51 =
new QgsSettingsEntryBool( u
"sort-imports"_s, sTreePythonCodeEditor,
true, u
"Whether imports should be sorted when auto-formatting code"_s );
54 =
new QgsSettingsEntryBool( u
"black-normalize-quotes"_s, sTreePythonCodeEditor,
true, u
"Whether quotes should be normalized when auto-formatting code using black"_s );
56 =
new QgsSettingsEntryString( u
"external-editor"_s, sTreePythonCodeEditor, QString(), u
"Command to launch an external Python code editor. Use the token <file> to insert the filename, <line> to insert line number, and <col> to insert the column number."_s );
64 , mAPISFilesList( filenames )
93 setEdgeMode( QsciScintilla::EdgeLine );
94 setEdgeColumn( settingMaxLineLength->value() );
97 setWhitespaceVisibility( QsciScintilla::WsVisibleAfterIndent );
99 SendScintilla( QsciScintillaBase::SCI_SETPROPERTY,
"highlight.current.word",
"1" );
104 QsciLexerPython *pyLexer =
new QgsQsciLexerPython(
this );
106 pyLexer->setIndentationWarning( QsciLexerPython::Inconsistent );
107 pyLexer->setFoldComments(
true );
108 pyLexer->setFoldQuotes(
true );
110 pyLexer->setDefaultFont( font );
113 pyLexer->setFont( font, -1 );
115 font.setItalic(
true );
116 pyLexer->setFont( font, QsciLexerPython::Comment );
117 pyLexer->setFont( font, QsciLexerPython::CommentBlock );
119 font.setItalic(
false );
120 font.setBold(
true );
121 pyLexer->setFont( font, QsciLexerPython::SingleQuotedString );
122 pyLexer->setFont( font, QsciLexerPython::DoubleQuotedString );
124 pyLexer->setColor(
defaultColor, QsciLexerPython::Default );
142 auto apis = std::make_unique<QsciAPIs>( pyLexer );
145 if ( mAPISFilesList.isEmpty() )
147 if ( settings.
value( u
"pythonConsole/preloadAPI"_s,
true ).toBool() )
150 apis->loadPrepared( mPapFile );
152 else if ( settings.
value( u
"pythonConsole/usePreparedAPIFile"_s,
false ).toBool() )
154 apis->loadPrepared( settings.
value( u
"pythonConsole/preparedAPIFile"_s ).toString() );
158 const QStringList apiPaths = settings.
value( u
"pythonConsole/userAPI"_s ).toStringList();
159 for (
const QString &path : apiPaths )
161 if ( !QFileInfo::exists( path ) )
163 QgsDebugError( u
"The apis file %1 was not found"_s.arg( path ) );
173 else if ( mAPISFilesList.length() == 1 && mAPISFilesList[0].right( 3 ) ==
"pap"_L1 )
175 if ( !QFileInfo::exists( mAPISFilesList[0] ) )
177 QgsDebugError( u
"The apis file %1 not found"_s.arg( mAPISFilesList.at( 0 ) ) );
180 mPapFile = mAPISFilesList[0];
181 apis->loadPrepared( mPapFile );
185 for (
const QString &path : std::as_const( mAPISFilesList ) )
187 if ( !QFileInfo::exists( path ) )
189 QgsDebugError( u
"The apis file %1 was not found"_s.arg( path ) );
198 pyLexer->setAPIs( apis.release() );
202 const int threshold = settings.
value( u
"pythonConsole/autoCompThreshold"_s, 2 ).toInt();
203 setAutoCompletionThreshold( threshold );
204 if ( !settings.
value(
"pythonConsole/autoCompleteEnabled",
true ).toBool() )
206 setAutoCompletionSource( AcsNone );
210 const QString autoCompleteSource = settings.
value( u
"pythonConsole/autoCompleteSource"_s, u
"fromAPI"_s ).toString();
211 if ( autoCompleteSource ==
"fromDoc"_L1 )
212 setAutoCompletionSource( AcsDocument );
213 else if ( autoCompleteSource ==
"fromDocAPI"_L1 )
214 setAutoCompletionSource( AcsAll );
216 setAutoCompletionSource( AcsAPIs );
220 setIndentationsUseTabs(
false );
221 setIndentationGuides(
true );
236 bool autoCloseBracket = settings.
value( u
"/pythonConsole/autoCloseBracket"_s,
true ).toBool();
237 bool autoSurround = settings.
value( u
"/pythonConsole/autoSurround"_s,
true ).toBool();
238 bool autoInsertImport = settings.
value( u
"/pythonConsole/autoInsertImport"_s,
false ).toBool();
241 const QString eText =
event->text();
243 getCursorPosition( &line, &column );
247 if ( hasSelectedText() && autoSurround )
249 if ( sCompletionPairs.contains( eText ) )
251 int startLine, startPos, endLine, endPos;
252 getSelection( &startLine, &startPos, &endLine, &endPos );
255 if ( startLine != endLine && ( eText ==
"\"" || eText ==
"'" ) )
257 replaceSelectedText( QString(
"%1%1%1%2%3%3%3" ).arg( eText, selectedText(), sCompletionPairs[eText] ) );
258 setSelection( startLine, startPos + 3, endLine, endPos + 3 );
262 replaceSelectedText( QString(
"%1%2%3" ).arg( eText, selectedText(), sCompletionPairs[eText] ) );
263 setSelection( startLine, startPos + 1, endLine, endPos + 1 );
268 else if ( sCompletionSingleCharacters.contains( eText ) )
270 int startLine, startPos, endLine, endPos;
271 getSelection( &startLine, &startPos, &endLine, &endPos );
272 replaceSelectedText( QString(
"%1%2%1" ).arg( eText, selectedText() ) );
273 setSelection( startLine, startPos + 1, endLine, endPos + 1 );
283 if ( autoInsertImport && eText ==
" " )
285 const QString lineText = text( line );
286 const thread_local QRegularExpression re( u
"^from [\\w.]+$"_s );
287 if ( re.match( lineText.trimmed() ).hasMatch() )
289 insert( u
" import"_s );
290 setCursorPosition( line, column + 7 );
296 else if ( autoCloseBracket )
302 if (
event->key() == Qt::Key_Backspace )
304 if ( sCompletionPairs.contains( prevChar ) && sCompletionPairs[prevChar] == nextChar )
306 setSelection( line, column - 1, line, column + 1 );
307 removeSelectedText();
320 else if ( sCompletionPairs.key( eText ) !=
"" && nextChar == eText )
322 setCursorPosition( line, column + 1 );
334 && sCompletionPairs.contains( eText )
335 && ( nextChar.isEmpty() || nextChar.at( 0 ).isSpace() || nextChar ==
":" || sCompletionPairs.key( nextChar ) !=
"" ) )
338 if ( !( ( eText ==
"\"" || eText ==
"'" ) && prevChar == eText ) )
341 insert( sCompletionPairs[eText] );
360 const QString formatter = settingCodeFormatter->value();
361 const int maxLineLength = settingMaxLineLength->value();
363 QString newText = string;
365 QStringList missingModules;
367 if ( settingSortImports->value() )
369 const QString defineSortImports = QStringLiteral(
370 "def __qgis_sort_imports(script):\n"
373 " except ImportError:\n"
374 " return '_ImportError'\n"
375 " options={'line_length': %1, 'profile': '%2', 'known_first_party': ['qgis', 'console', 'processing', 'plugins']}\n"
376 " return isort.code(script, **options)\n"
378 .arg( maxLineLength )
379 .arg( formatter ==
"black"_L1 ? u
"black"_s : QString() );
383 QgsDebugError( u
"Error running script: %1"_s.arg( defineSortImports ) );
391 if ( result ==
"_ImportError"_L1 )
393 missingModules << u
"isort"_s;
402 QgsDebugError( u
"Error running script: %1"_s.arg( script ) );
407 if ( formatter ==
"autopep8"_L1 )
409 const int level = settingAutopep8Level->value();
411 const QString defineReformat = QStringLiteral(
412 "def __qgis_reformat(script):\n"
415 " except ImportError:\n"
416 " return '_ImportError'\n"
417 " options={'aggressive': %1, 'max_line_length': %2}\n"
418 " return autopep8.fix_code(script, options=options)\n"
421 .arg( maxLineLength );
425 QgsDebugError( u
"Error running script: %1"_s.arg( defineReformat ) );
433 if ( result ==
"_ImportError"_L1 )
435 missingModules << u
"autopep8"_s;
444 QgsDebugError( u
"Error running script: %1"_s.arg( script ) );
448 else if ( formatter ==
"black"_L1 )
450 const bool normalize = settingBlackNormalizeQuotes->value();
458 const QString defineReformat = QStringLiteral(
459 "def __qgis_reformat(script):\n"
462 " except ImportError:\n"
463 " return '_ImportError'\n"
464 " options={'string_normalization': %1, 'line_length': %2}\n"
465 " return black.format_str(script, mode=black.Mode(**options))\n"
468 .arg( maxLineLength );
472 QgsDebugError( u
"Error running script: %1"_s.arg( defineReformat ) );
480 if ( result ==
"_ImportError"_L1 )
482 missingModules << u
"black"_s;
491 QgsDebugError( u
"Error running script: %1"_s.arg( script ) );
496 if ( !missingModules.empty() )
498 if ( missingModules.size() == 1 )
504 const QString modules = missingModules.join(
", "_L1 );
516 QString text = selectedText();
517 if ( text.isEmpty() )
519 text = wordAtPoint( mapFromGlobal( QCursor::pos() ) );
521 if ( text.isEmpty() )
526 QAction *pyQgisHelpAction =
new QAction(
QgsApplication::getThemeIcon( u
"console/iconHelpConsole.svg"_s ), tr(
"Search Selection in PyQGIS Documentation" ), menu );
528 pyQgisHelpAction->setEnabled( hasSelectedText() );
529 pyQgisHelpAction->setShortcut( QKeySequence::StandardKey::HelpContents );
530 connect( pyQgisHelpAction, &QAction::triggered,
this, [text,
this] {
showApiDocumentation( text ); } );
532 menu->addSeparator();
533 menu->addAction( pyQgisHelpAction );
538 switch ( autoCompletionSource() )
541 autoCompleteFromDocument();
545 autoCompleteFromAPIs();
549 autoCompleteFromAll();
559 mAPISFilesList = filenames;
567 QFile file( script );
568 if ( !file.open( QIODevice::ReadOnly ) )
573 QTextStream in( &file );
574 setText( in.readAll().trimmed() );
589 if ( position >= length() && position > 0 )
591 long style = SendScintilla( QsciScintillaBase::SCI_GETSTYLEAT, position - 1 );
592 return style == QsciLexerPython::Comment
593 || style == QsciLexerPython::TripleSingleQuotedString
594 || style == QsciLexerPython::TripleDoubleQuotedString
595 || style == QsciLexerPython::TripleSingleQuotedFString
596 || style == QsciLexerPython::TripleDoubleQuotedFString
597 || style == QsciLexerPython::UnclosedString;
601 long style = SendScintilla( QsciScintillaBase::SCI_GETSTYLEAT, position );
602 return style == QsciLexerPython::Comment
603 || style == QsciLexerPython::DoubleQuotedString
604 || style == QsciLexerPython::SingleQuotedString
605 || style == QsciLexerPython::TripleSingleQuotedString
606 || style == QsciLexerPython::TripleDoubleQuotedString
607 || style == QsciLexerPython::CommentBlock
608 || style == QsciLexerPython::UnclosedString
609 || style == QsciLexerPython::DoubleQuotedFString
610 || style == QsciLexerPython::SingleQuotedFString
611 || style == QsciLexerPython::TripleSingleQuotedFString
612 || style == QsciLexerPython::TripleDoubleQuotedFString;
623 return text( position - 1, position );
629 if ( position >= length() )
633 return text( position, position + 1 );
660 const QString originalText = text();
662 const QString defineCheckSyntax = QStringLiteral(
663 "def __check_syntax(script):\n"
665 " compile(script.encode('utf-8'), '', 'exec')\n"
666 " except SyntaxError as detail:\n"
667 " eline = detail.lineno or 1\n"
669 " ecolumn = detail.offset or 1\n"
670 " edescr = detail.msg\n"
671 " return '!!!!'.join([str(eline), str(ecolumn), edescr])\n"
677 QgsDebugError( u
"Error running script: %1"_s.arg( defineCheckSyntax ) );
685 if ( result.size() == 0 )
691 const QStringList parts = result.split( u
"!!!!"_s );
692 if ( parts.size() == 3 )
694 const int line = parts.at( 0 ).toInt();
695 const int column = parts.at( 1 ).toInt();
697 setCursorPosition( line, column - 1 );
698 ensureLineVisible( line );
705 QgsDebugError( u
"Error running script: %1"_s.arg( script ) );
717 QString searchText = text;
718 searchText = searchText.replace(
">>> "_L1, QString() ).replace(
"... "_L1, QString() ).trimmed();
720 QRegularExpression qtExpression(
"^Q[A-Z][a-zA-Z]" );
722 if ( qtExpression.match( searchText ).hasMatch() )
724 const QString qtVersion = QString( qVersion() ).split(
'.' ).mid( 0, 2 ).join(
'.' );
725 QString baseUrl = QString(
"https://doc.qt.io/qt-%1" ).arg( qtVersion );
726 QDesktopServices::openUrl( QUrl( u
"%1/%2.html"_s.arg( baseUrl, searchText.toLower() ) ) );
729 const QString qgisVersion = QString(
Qgis::version() ).split(
'.' ).mid( 0, 2 ).join(
'.' );
730 if ( searchText.isEmpty() )
732 QDesktopServices::openUrl( QUrl( u
"https://qgis.org/pyqgis/%1/"_s.arg( qgisVersion ) ) );
736 QDesktopServices::openUrl( QUrl( u
"https://qgis.org/pyqgis/%1/search.html?q=%2"_s.arg( qgisVersion, searchText ) ) );
749QgsQsciLexerPython::QgsQsciLexerPython( QObject *parent )
750 : QsciLexerPython( parent )
753const char *QgsQsciLexerPython::keywords(
int set )
const
757 return "True False and as assert break class continue def del elif else except "
758 "finally for from global if import in is lambda None not or pass "
759 "raise return try while with yield async await nonlocal";
762 return QsciLexerPython::keywords( set );
static QString version()
Version string.
@ Warning
Warning message.
@ CheckSyntax
Language supports syntax checking.
@ Reformat
Language supports automatic code reformatting.
@ ToggleComment
Language supports comment toggling.
ScriptLanguage
Scripting languages.
DocumentationBrowser
Documentation API browser.
@ DeveloperToolsPanel
Embedded webview in the DevTools panel.
QFlags< ScriptLanguageCapability > ScriptLanguageCapabilities
Script language capabilities.
static QString pkgDataPath()
Returns the common root path of all application data directories.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
@ TripleSingleQuote
Triple single quote color.
@ CommentBlock
Comment block color.
@ Decoration
Decoration color.
@ Identifier
Identifier color.
@ DoubleQuote
Double quote color.
@ Default
Default text color.
@ Background
Background color.
@ SingleQuote
Single quote color.
@ Operator
Operator color.
@ TripleDoubleQuote
Triple double quote color.
void autoComplete()
Triggers the autocompletion popup.
QString characterAfterCursor() const
Returns the character after the cursor, or an empty string if the cursor is set at end.
bool isCursorInsideStringLiteralOrComment() const
Check whether the current cursor position is inside a string literal or a comment.
QString reformatCodeString(const QString &string) override
Applies code reformatting to a string and returns the result.
void searchSelectedTextInPyQGISDocs()
Searches the selected text in the official PyQGIS online documentation.
Qgis::ScriptLanguage language() const override
Returns the associated scripting language.
void loadAPIs(const QList< QString > &filenames)
Load APIs from one or more files.
void toggleComment() override
Toggle comment for the selected text.
virtual void showApiDocumentation(const QString &item)
Displays the given text in the official APIs (PyQGIS, C++ QGIS or Qt) documentation.
void initializeLexer() override
Called when the dialect specific code lexer needs to be initialized (or reinitialized).
PRIVATE QgsCodeEditorPython(QWidget *parent=nullptr, const QList< QString > &filenames=QList< QString >(), QgsCodeEditor::Mode mode=QgsCodeEditor::Mode::ScriptEditor, QgsCodeEditor::Flags flags=QgsCodeEditor::Flag::CodeFolding)
Construct a new Python editor.
bool checkSyntax() override
Applies syntax checking to the editor.
void updateCapabilities()
Updates the editor capabilities.
Qgis::ScriptLanguageCapabilities languageCapabilities() const override
Returns the associated scripting language capabilities.
void keyPressEvent(QKeyEvent *event) override
bool loadScript(const QString &script)
Loads a script file.
void populateContextMenu(QMenu *menu) override
Called when the context menu for the widget is about to be shown, after it has been fully populated w...
QString characterBeforeCursor() const
Returns the character before the cursor, or an empty string if cursor is set at start.
QgsCodeEditor::Mode mode() const
Returns the code editor mode.
void keyPressEvent(QKeyEvent *event) override
virtual void populateContextMenu(QMenu *menu)
Called when the context menu for the widget is about to be shown, after it has been fully populated w...
QFlags< Flag > Flags
Flags controlling behavior of code editor.
void setText(const QString &text) override
void runPostLexerConfigurationTasks()
Performs tasks which must be run after a lexer has been set for the widget.
bool event(QEvent *event) override
virtual void showMessage(const QString &title, const QString &message, Qgis::MessageLevel level)
Shows a user facing message (eg a warning message).
int linearPosition() const
Convenience function to return the cursor position as a linear index.
void setTitle(const QString &title)
Set the widget title.
QgsCodeEditor(QWidget *parent=nullptr, const QString &title=QString(), bool folding=false, bool margin=false, QgsCodeEditor::Flags flags=QgsCodeEditor::Flags(), QgsCodeEditor::Mode mode=QgsCodeEditor::Mode::ScriptEditor)
Construct a new code editor.
void clearWarnings()
Clears all warning messages from the editor.
void helpRequested(const QString &word)
Emitted when documentation was requested for the specified word.
void setLineNumbersVisible(bool visible)
Sets whether line numbers should be visible in the editor.
QFont lexerFont() const
Returns the font to use in the lexer.
void toggleLineComments(const QString &commentPrefix)
Toggles comment for selected lines with the given comment prefix.
QColor lexerColor(QgsCodeEditorColorScheme::ColorRole role) const
Returns the color to use in the lexer for the specified role.
static QColor defaultColor(QgsCodeEditorColorScheme::ColorRole role, const QString &theme=QString())
Returns the default color for the specified role.
void addWarning(int lineNumber, const QString &warning)
Adds a warning message and indicator to the specified a lineNumber.
static QString stringToPythonLiteral(const QString &string)
Converts a string to a Python string literal.
static QString variantToPythonLiteral(const QVariant &value)
Converts a variant to a Python literal.
static bool run(const QString &command, const QString &messageOnError=QString())
Execute a Python statement.
static bool eval(const QString &command, QString &result)
Eval a Python statement.
static bool isValid()
Returns true if the runner has an instance (and thus is able to run commands).
A boolean settings entry.
A template class for enum and flag settings entry.
An integer settings entry.
Stores settings for use within QGIS.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)