36#include <QFontDatabase>
43#include <Qsci/qscilexer.h>
44#include <Qsci/qscistyle.h>
46#include "moc_qgscodeeditor.cpp"
48using namespace Qt::StringLiterals;
55QMap<QgsCodeEditorColorScheme::ColorRole, QString> QgsCodeEditor::sColorRoleToSettingsKey {
95 : QsciScintilla( parent )
96 , mWidgetTitle( title )
101 if ( !parent && mWidgetTitle.isEmpty() )
103 setWindowTitle( u
"Text Editor"_s );
107 setWindowTitle( mWidgetTitle );
113 mSoftHistory.append( QString() );
116 setHorizontalScrollBarPolicy( Qt::ScrollBarAsNeeded );
118 SendScintilla( SCI_SETADDITIONALSELECTIONTYPING, 1 );
119 SendScintilla( SCI_SETMULTIPASTE, 1 );
120 SendScintilla( SCI_SETVIRTUALSPACEOPTIONS, SCVS_RECTANGULARSELECTION );
125 setAnnotationDisplay( QsciScintilla::AnnotationBoxed );
140 SendScintilla( QsciScintilla::SCI_SETHSCROLLBAR, 0 );
142 setWrapMode( QsciScintilla::WrapCharacter );
149 SendScintilla( QsciScintilla::SCI_SETHSCROLLBAR, 0 );
151 setWrapMode( QsciScintilla::WrapCharacter );
152 SendScintilla( QsciScintilla::SCI_EMPTYUNDOBUFFER );
157#if QSCINTILLA_VERSION < 0x020d03
158 installEventFilter(
this );
161 mLastEditTimer =
new QTimer(
this );
162 mLastEditTimer->setSingleShot(
true );
163 mLastEditTimer->setInterval( 1000 );
164 connect( mLastEditTimer, &QTimer::timeout,
this, &QgsCodeEditor::onLastEditTimeout );
165 connect(
this, &QgsCodeEditor::textChanged, mLastEditTimer, qOverload<>( &QTimer::start ) );
171#if QSCINTILLA_VERSION >= 0x020800 && QSCINTILLA_VERSION < 0x020900
172 if (
event->reason() != Qt::ActiveWindowFocusReason )
186 QFocusEvent newFocusEvent( QEvent::FocusOut, Qt::ActiveWindowFocusReason );
187 QsciScintilla::focusOutEvent( &newFocusEvent );
192 QsciScintilla::focusOutEvent(
event );
202 if ( isListActive() )
204 QsciScintilla::keyPressEvent(
event );
208 if (
event->key() == Qt::Key_Escape )
211 QWidget::keyPressEvent(
event );
215 if (
event->matches( QKeySequence::StandardKey::HelpContents ) )
218 QString text = selectedText();
223 text = wordAtPoint( mapFromGlobal( QCursor::pos() ) );
227 if ( text.isEmpty() )
230 getCursorPosition( &line, &index );
231 text = wordAtLineIndex( line, index );
240 switch (
event->key() )
265 if ( !isReadOnly() && canReformat )
268 if ( !reformatCodeSequence.isEmpty() && reformatCodeSequence.matches(
event->key() |
event->modifiers() ) )
278 if ( !isReadOnly() && canToggle )
281 if ( !toggleCommentCodeSequence.isEmpty() && toggleCommentCodeSequence.matches(
event->key() |
event->modifiers() ) )
289 QsciScintilla::keyPressEvent(
event );
292 if ( !
event->isAutoRepeat() )
304 QMenu *menu = createStandardContextMenu();
305 menu->setAttribute( Qt::WA_DeleteOnClose );
309 menu->addSeparator();
314 QAction *reformatAction =
new QAction( tr(
"Reformat Code" ), menu );
317 reformatAction->setEnabled( !isReadOnly() );
319 menu->addAction( reformatAction );
324 QAction *syntaxCheckAction =
new QAction( tr(
"Check Syntax" ), menu );
327 menu->addAction( syntaxCheckAction );
332 QAction *toggleCommentAction =
new QAction( tr(
"Toggle Comment" ), menu );
335 toggleCommentAction->setEnabled( !isReadOnly() );
337 menu->addAction( toggleCommentAction );
342 menu->exec( mapToGlobal(
event->pos() ) );
348 QMenu *menu =
new QMenu(
this );
349 QMenu *historySubMenu =
new QMenu( tr(
"Command History" ), menu );
355 menu->addMenu( historySubMenu );
356 menu->addSeparator();
358 QAction *copyAction = menu->addAction(
QgsApplication::getThemeIcon(
"mActionEditCopy.svg" ), tr(
"Copy" ),
this, &QgsCodeEditor::copy, QKeySequence::Copy );
359 QAction *pasteAction = menu->addAction(
QgsApplication::getThemeIcon(
"mActionEditPaste.svg" ), tr(
"Paste" ),
this, &QgsCodeEditor::paste, QKeySequence::Paste );
360 copyAction->setEnabled( hasSelectedText() );
361 pasteAction->setEnabled( !QApplication::clipboard()->text().isEmpty() );
365 menu->exec( mapToGlobal(
event->pos() ) );
370 QsciScintilla::contextMenuEvent(
event );
377 if (
event->type() == QEvent::ShortcutOverride )
379 if ( QKeyEvent *keyEvent =
dynamic_cast<QKeyEvent *
>(
event ) )
381 if ( keyEvent->matches( QKeySequence::StandardKey::HelpContents ) )
390 return QsciScintilla::event(
event );
395#if QSCINTILLA_VERSION < 0x020d03
396 if ( watched ==
this &&
event->type() == QEvent::InputMethod )
405 return QsciScintilla::eventFilter( watched,
event );
413 if ( mUseDefaultSettings )
414 return color( role );
416 if ( !mOverrideColors )
422 const QColor
color = mCustomColors.value( role );
429 if ( mUseDefaultSettings )
432 QFont font = QFontDatabase::systemFont( QFontDatabase::FixedFont );
435 if ( !mFontFamily.isEmpty() )
440 font.setPointSize( mFontSize );
444 font.setPointSize( QLabel().font().pointSize() );
448 font.setPointSize( mFontSize );
451 const int fontSize = settings.
value( u
"qgis/stylesheet/fontPointSize"_s, 10 ).toInt();
452 font.setPointSize( fontSize );
455 font.setBold(
false );
482 setCaretLineVisible(
false );
485 setMarginLineNumbers( 1,
true );
486 setMarginWidth( 1,
"00000" );
487 setMarginType( 1, QsciScintilla::MarginType::TextMarginRightJustified );
489 setEdgeMode( QsciScintilla::EdgeNone );
493void QgsCodeEditor::onLastEditTimeout()
495 mLastEditTimer->stop();
499void QgsCodeEditor::setSciWidget()
505 setCaretLineVisible(
true );
511 setBraceMatching( QsciScintilla::SloppyBraceMatch );
518 setFolding( QsciScintilla::NoFoldStyle );
530 setFoldMarginColors( foldColor, foldColor );
532 setAutoIndent(
true );
533 setIndentationWidth( 4 );
534 setTabIndents(
true );
535 setBackspaceUnindents(
true );
538 setAutoCompletionThreshold( 2 );
539 setAutoCompletionSource( QsciScintilla::AcsAPIs );
546 setWindowTitle( title );
566 return tr(
"Expression" );
570 return tr(
"JavaScript" );
574 return tr(
"Python" );
580 return tr(
"Batch" );
595 marginFont.setPointSize( 10 );
596 setMarginLineNumbers( 0,
true );
597 setMarginsFont( marginFont );
615 marginFont.setPointSize( 10 );
617 setMarginsFont( marginFont );
652void QgsCodeEditor::updateFolding()
659 setFolding( QsciScintilla::PlainFoldStyle );
663 setFolding( QsciScintilla::NoFoldStyle );
668bool QgsCodeEditor::readHistoryFile()
670 if ( mHistoryFilePath.isEmpty() || !QFile::exists( mHistoryFilePath ) )
673 QFile file( mHistoryFilePath );
674 if ( file.open( QIODevice::ReadOnly ) )
676 QTextStream stream( &file );
678 while ( !stream.atEnd() )
680 line = stream.readLine();
681 mHistory.append( line );
690void QgsCodeEditor::syncSoftHistory()
692 mSoftHistory = mHistory;
693 mSoftHistory.append( QString() );
694 mSoftHistoryIndex = mSoftHistory.length() - 1;
699 mSoftHistory[mSoftHistoryIndex] = text();
702void QgsCodeEditor::updateHistory(
const QStringList &commands,
bool skipSoftHistory )
704 if ( commands.size() > 1 )
706 mHistory.append( commands );
708 else if ( !commands.value( 0 ).isEmpty() )
710 const QString command = commands.value( 0 );
711 if ( mHistory.empty() || command != mHistory.constLast() )
712 mHistory.append( command );
715 if ( !skipSoftHistory )
734 QMessageBox::information(
this, title, message );
738 QMessageBox::warning(
this, title, message );
742 QMessageBox::critical(
this, title, message );
751 const QString prompt = mInterpreter->promptForState( mInterpreter->currentState() );
752 SendScintilla( QsciScintilla::SCI_MARGINSETTEXT,
static_cast<uintptr_t
>( 0 ), prompt.toUtf8().constData() );
763 mInterpreter = newInterpreter;
770 const int index = std::min( source.length(), target.length() );
776 int refDistanceMore = d0;
777 int refIndexMore = index;
778 if ( index < source.length() - 1 )
783 if ( newDistance <= refDistanceMore )
785 refDistanceMore = newDistance;
787 if ( refIndexMore == source.length() - 1 )
797 int refDistanceLess = d0;
798 int refIndexLess = index;
804 if ( newDistance <= refDistanceLess )
806 refDistanceLess = newDistance;
808 if ( refIndexLess == 0 )
818 if ( refDistanceMore < refDistanceLess )
830 const QString originalText = text();
833 if ( originalText == newText )
837 const int oldScrollValue = verticalScrollBar()->value();
842 removeSelectedText();
845 verticalScrollBar()->setValue( oldScrollValue );
865 int startLine, startPos, endLine, endPos;
866 if ( hasSelectedText() )
868 getSelection( &startLine, &startPos, &endLine, &endPos );
872 getCursorPosition( &startLine, &startPos );
878 bool allEmpty =
true;
879 bool allCommented =
true;
880 int minIndentation = -1;
881 for (
int line = startLine; line <= endLine; line++ )
883 const QString stripped = text( line ).trimmed();
884 if ( !stripped.isEmpty() )
887 if ( !stripped.startsWith( commentPrefix ) )
889 allCommented =
false;
891 if ( minIndentation == -1 || minIndentation > indentation( line ) )
893 minIndentation = indentation( line );
907 const int prefixLength =
static_cast<int>( commentPrefix.length() );
909 const bool startLineEmpty = ( text( startLine ).trimmed().isEmpty() );
910 const bool endLineEmpty = ( text( endLine ).trimmed().isEmpty() );
912 for (
int line = startLine; line <= endLine; line++ )
914 const QString stripped = text( line ).trimmed();
917 if ( stripped.isEmpty() )
924 insertAt( commentPrefix +
' ', line, minIndentation );
925 delta = -( prefixLength + 1 );
929 if ( !stripped.startsWith( commentPrefix ) )
933 if ( stripped.startsWith( commentPrefix +
' ' ) )
935 delta = prefixLength + 1;
939 delta = prefixLength;
941 setSelection( line, indentation( line ), line, indentation( line ) + delta );
942 removeSelectedText();
947 setSelection( startLine, startPos - ( startLineEmpty ? 0 : delta ), endLine, endPos - ( endLineEmpty ? 0 : delta ) );
956 int lineCount = lines();
959 for (
int line = 0; line < lineCount; line++ )
962 const long endLine = SendScintilla( SCI_GETLINEENDPOSITION, line );
964 const long x = SendScintilla( SCI_POINTXFROMPOSITION, 0, endLine );
965 maxWidth = std::max( maxWidth, x );
969 setScrollWidth(
static_cast<int>( maxWidth ) );
974 disconnect(
this, &QgsCodeEditor::textChanged, mLastEditTimer, qOverload<>( &QTimer::start ) );
975 QsciScintilla::setText( text );
976 connect(
this, &QgsCodeEditor::textChanged, mLastEditTimer, qOverload<>( &QTimer::start ) );
983 return mLastEditTimer->interval();
988 mLastEditTimer->setInterval( timeout );
1001 updateHistory( { command } );
1007 mInterpreter->exec( command );
1026 if ( !mHistoryFilePath.isEmpty() && QFile::exists( mHistoryFilePath ) )
1028 QFile file( mHistoryFilePath );
1029 if ( !file.open( QFile::WriteOnly | QFile::Truncate ) )
1031 QgsDebugError( u
"Could not truncate %1"_s.arg( mHistoryFilePath ) );
1040 if ( mHistoryFilePath.isEmpty() )
1043 QFile f( mHistoryFilePath );
1044 if ( !f.open( QFile::WriteOnly | QIODevice::Truncate ) )
1049 QTextStream ts( &f );
1050 for (
const QString &command : std::as_const( mHistory ) )
1052 ts << command +
'\n';
1059 if ( mSoftHistoryIndex < mSoftHistory.length() - 1 && !mSoftHistory.isEmpty() )
1061 mSoftHistoryIndex += 1;
1062 setText( mSoftHistory[mSoftHistoryIndex] );
1069 if ( mSoftHistoryIndex > 0 && !mSoftHistory.empty() )
1071 mSoftHistoryIndex -= 1;
1072 setText( mSoftHistory[mSoftHistoryIndex] );
1080 dialog->setAttribute( Qt::WA_DeleteOnClose );
1083 dialog->activateWindow();
1089 mHistory.removeAt( index );
1090 mSoftHistory.removeAt( index );
1091 if ( index < mSoftHistoryIndex )
1093 mSoftHistoryIndex -= 1;
1094 if ( mSoftHistoryIndex < 0 )
1095 mSoftHistoryIndex = mSoftHistory.length() - 1;
1102 if ( hasSelectedText() )
1104 replaceSelectedText( text );
1109 getCursorPosition( &line, &index );
1110 insertAt( text, line, index );
1111 setCursorPosition( line, index + text.length() );
1121 useDefault = !info.exists();
1124 if ( theme.isEmpty() && useDefault )
1127 const QPalette
pal = qApp->palette();
1132 return pal.color( QPalette::Highlight );
1134 return pal.color( QPalette::HighlightedText );
1139 else if ( theme.isEmpty() )
1144 static const QMap<QgsCodeEditorColorScheme::ColorRole, QString> sColorRoleToIniKey {
1188 return scheme.
color( role );
1196 const QString theme = settings.
value( u
"codeEditor/colorScheme"_s, QString(),
QgsSettings::Gui ).toString();
1201 const QString
color = settings.
value( u
"codeEditor/%1"_s.arg( sColorRoleToSettingsKey.value( role ) ), QString(),
QgsSettings::Gui ).toString();
1209 if (
color.isValid() )
1222 return font.fixedPitch();
1227 QFont font = QFontDatabase::systemFont( QFontDatabase::FixedFont );
1230 if ( !settings.
value( u
"codeEditor/fontfamily"_s, QString(),
QgsSettings::Gui ).toString().isEmpty() )
1237 font.setPointSize( fontSize );
1241 font.setPointSize( QLabel().font().pointSize() );
1245 font.setPointSize( fontSize );
1248 const int fontSize = settings.
value( u
"qgis/stylesheet/fontPointSize"_s, 10 ).toInt();
1249 font.setPointSize( fontSize );
1252 font.setBold(
false );
1259 mUseDefaultSettings =
false;
1260 mOverrideColors = !customColors.isEmpty();
1261 mColorScheme = scheme;
1262 mCustomColors = customColors;
1263 mFontFamily = fontFamily;
1264 mFontSize = fontSize;
1273 markerAdd( lineNumber, MARKER_NUMBER );
1275 font.setItalic(
true );
1277 annotate( lineNumber, warning, styleAnn );
1278 mWarningLines.push_back( lineNumber );
1283 for (
const int line : mWarningLines )
1285 markerDelete( line );
1286 clearAnnotations( line );
1289 mWarningLines.clear();
1296 getCursorPosition( &line, &index );
1297 return line == lines() - 1;
1302 mHistoryFilePath = path;
1308 setCursorPosition( 0, 0 );
1309 ensureCursorVisible();
1310 ensureLineVisible( 0 );
1318 const int endLine = lines() - 1;
1319 const int endLineLength = lineLength( endLine );
1320 setCursorPosition( endLine, endLineLength );
1321 ensureCursorVisible();
1322 ensureLineVisible( endLine );
1330 return static_cast<int>( SendScintilla( SCI_GETCURRENTPOS ) );
1336 lineIndexFromPosition( linearIndex, &line, &index );
1337 setCursorPosition( line, index );
1342 int startLine, startIndex, _;
1343 getSelection( &startLine, &startIndex, &_, &_ );
1344 if ( startLine == -1 )
1348 return positionFromLineIndex( startLine, startIndex );
1353 int endLine, endIndex, _;
1354 getSelection( &_, &_, &endLine, &endIndex );
1355 if ( endLine == -1 )
1359 return positionFromLineIndex( endLine, endIndex );
1364 int startLine, startIndex, endLine, endIndex;
1365 lineIndexFromPosition( start, &startLine, &startIndex );
1366 lineIndexFromPosition( end, &endLine, &endIndex );
1367 setSelection( startLine, startIndex, endLine, endIndex );
1382 if ( wrapMode() == WrapNone )
1394 if ( SendScintilla( SCI_WRAPCOUNT, line ) <= 1 )
1400 const long endLine = SendScintilla( SCI_GETLINEENDPOSITION, line );
1402 const long y = SendScintilla( SCI_POINTYFROMPOSITION, 0, endLine );
1404 return static_cast<int>( SendScintilla( SCI_POSITIONFROMPOINT, 0, y ) );
1411 if ( callTipsStyle() == CallTipsNone || lexer() ==
nullptr )
1416 QsciAbstractAPIs *apis = lexer()->apis();
1421 int pos, commas = 0;
1429 while ( ( ch = getCharacter( pos ) ) !=
'\0' )
1433 else if ( ch ==
')' )
1439 while ( ( ch = getCharacter( pos ) ) !=
'\0' )
1443 else if ( ch ==
'(' && --depth == 0 )
1447 else if ( ch ==
'(' )
1455 SendScintilla( SCI_CALLTIPCANCEL );
1461 int contextStart, lastWordStart;
1462 QStringList context = apiContext( pos, contextStart, lastWordStart );
1464 if ( context.isEmpty() )
1468 context << QString();
1470 QList<int> ctShifts;
1471 QStringList ctEntries = apis->callTips( context, commas, callTipsStyle(), ctShifts );
1473 int nbEntries = ctEntries.count();
1475 if ( nbEntries == 0 )
1478 const int maxNumberOfCallTips = callTipsVisible();
1481 if ( maxNumberOfCallTips > 0 && maxNumberOfCallTips < nbEntries )
1483 ctEntries = ctEntries.mid( 0, maxNumberOfCallTips );
1484 nbEntries = maxNumberOfCallTips;
1490 int nbShifts = ctShifts.count();
1492 if ( maxNumberOfCallTips < 0 && nbEntries > 1 )
1494 shift = ( nbShifts > 0 ? ctShifts.first() : 0 );
1496 ct.prepend(
'\002' );
1500 if ( nbShifts > nbEntries )
1501 nbShifts = nbEntries;
1506 for (
int i = 0; i < nbShifts; ++i )
1508 int sh = ctShifts[i];
1514 ct = ctEntries.join(
"\n" );
1517 QByteArray ctBa = ct.toLatin1();
1518 const char *cts = ctBa.data();
1522 if ( currentWrapPosition != -1 )
1524 SendScintilla( SCI_CALLTIPSHOW, currentWrapPosition, cts );
1532 int ctmin =
static_cast<int>( SendScintilla( SCI_POSITIONFROMLINE, SendScintilla( SCI_LINEFROMPOSITION, ct ) ) );
1533 if ( lastWordStart - shift < ctmin )
1534 lastWordStart = ctmin;
1538 lineIndexFromPosition( lastWordStart, &line, &index );
1539 SendScintilla( SCI_CALLTIPSHOW, positionFromLineIndex( line, index ), cts );
1543 if ( nbEntries > 1 )
1550 astart = strchr( cts,
'(' );
1552 for ( astart = strchr( cts,
',' ); astart && --commas > 0; astart = strchr( astart + 1,
',' ) )
1566 for ( aend = astart; *aend; ++aend )
1570 if ( ch ==
',' && depth == 0 )
1572 else if ( ch ==
'(' )
1574 else if ( ch ==
')' )
1583 if ( astart != aend )
1584 SendScintilla( SCI_CALLTIPSETHLT, astart - cts, aend - cts );
1591char QgsCodeEditor::getCharacter(
int &pos )
const
1596 char ch =
static_cast<char>( SendScintilla( SCI_GETCHARAT, --pos ) );
1599 if ( ch ==
'\n' || ch ==
'\r' )
MessageLevel
Level for messages This will be used both for message log and message bar in application.
@ Warning
Warning message.
@ Critical
Critical/error message.
@ Info
Information message.
@ Success
Used for reporting a successful operation.
@ CheckSyntax
Language supports syntax checking.
@ Reformat
Language supports automatic code reformatting.
@ ToggleComment
Language supports comment toggling.
ScriptLanguage
Scripting languages.
@ QgisExpression
QGIS expressions.
@ Batch
Windows batch files.
@ Unknown
Unknown/other language.
QFlags< ScriptLanguageCapability > ScriptLanguageCapabilities
Script language capabilities.
static QPixmap getThemePixmap(const QString &name, const QColor &foreColor=QColor(), const QColor &backColor=QColor(), int size=16)
Helper to get a theme icon as a pixmap.
static QgsApplication * instance()
Returns the singleton instance of the QgsApplication.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QString themeName()
Set the active theme to the specified theme.
QgsCodeEditorColorScheme scheme(const QString &id) const
Returns the color scheme with matching id.
Defines a color scheme for use in QgsCodeEditor widgets.
@ TripleSingleQuote
Triple single quote color.
@ CommentBlock
Comment block color.
@ QuotedOperator
Quoted operator color.
@ Decoration
Decoration color.
@ Identifier
Identifier color.
@ DoubleQuote
Double quote color.
@ QuotedIdentifier
Quoted identifier color.
@ SelectionForeground
Selection foreground color.
@ CommentLine
Line comment color.
@ FoldIconForeground
Fold icon foreground color.
@ MarginForeground
Margin foreground color.
@ ErrorBackground
Error background color.
@ MatchedBraceBackground
Matched brace background color.
@ Default
Default text color.
@ SearchMatchBackground
Background color for search matches.
@ CaretLine
Caret line color.
@ IndentationGuide
Indentation guide line.
@ Background
Background color.
@ SingleQuote
Single quote color.
@ MarginBackground
Margin background color.
@ SelectionBackground
Selection background color.
@ MatchedBraceForeground
Matched brace foreground color.
@ Operator
Operator color.
@ TripleDoubleQuote
Triple double quote color.
@ FoldIconHalo
Fold icon halo color.
QColor color(ColorRole role) const
Returns the color to use in the editor for the specified role.
A dialog for displaying and managing command history for a QgsCodeEditor widget.
bool eventFilter(QObject *watched, QEvent *event) override
void sessionHistoryCleared()
Emitted when the history of commands run in the current session is cleared.
static const QgsSettingsEntryBool * settingContextHelpHover
void showHistory()
Shows the command history dialog.
int wrapPosition(int line=-1)
Returns the linear position of the start of the last wrapped part for the specified line,...
QgsCodeEditor::Mode mode() const
Returns the code editor mode.
void setCustomAppearance(const QString &scheme=QString(), const QMap< QgsCodeEditorColorScheme::ColorRole, QColor > &customColors=QMap< QgsCodeEditorColorScheme::ColorRole, QColor >(), const QString &fontFamily=QString(), int fontSize=0)
Sets a custom appearance for the widget, disconnecting it from using the standard appearance taken fr...
int editingTimeoutInterval() const
Returns the timeout (in milliseconds) threshold for the editingTimeout() signal to be emitted after a...
@ OutputDisplay
Read only mode for display of command outputs.
@ ScriptEditor
Standard mode, allows for display and edit of entire scripts.
@ CommandInput
Command input mode.
void reformatCode()
Applies code reformatting to the editor.
virtual void toggleComment()
Toggle comment for the selected text.
void contextMenuEvent(QContextMenuEvent *event) override
void clearPersistentHistory()
Clears the entire persistent history of commands run in the editor.
void removeHistoryCommand(int index)
Removes the command at the specified index from the history of the code editor.
static void setColor(QgsCodeEditorColorScheme::ColorRole role, const QColor &color)
Sets the color to use in the editor for the specified role.
void setHistoryFilePath(const QString &path)
Sets the file path to use for recording and retrieving previously executed commands.
void setLinearSelection(int start, int end)
Convenience function to set the selection using linear indexes.
QStringList history() const
Returns the list of commands previously executed in the editor.
static constexpr int SEARCH_RESULT_INDICATOR
Indicator index for search results.
void keyPressEvent(QKeyEvent *event) override
virtual void moveCursorToStart()
Moves the cursor to the start of the document and scrolls to ensure it is visible.
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 persistentHistoryCleared()
Emitted when the persistent history of commands run in the editor is cleared.
void runCommand(const QString &command, bool skipHistory=false)
Runs a command in the editor.
void setText(const QString &text) override
void setFoldingVisible(bool folding)
Set whether the folding controls are visible in the editor.
virtual Qgis::ScriptLanguageCapabilities languageCapabilities() const
Returns the associated scripting language capabilities.
void setEditingTimeoutInterval(int timeout)
Sets the timeout (in milliseconds) threshold for the editingTimeout() signal to be emitted after an e...
void setInterpreter(QgsCodeInterpreter *newInterpreter)
Sets an attached code interpreter for executing commands when the editor is in the QgsCodeEditor::Mod...
@ FoldingControls
Folding controls.
@ ErrorIndicators
Error indicators.
@ LineNumbers
Line numbers.
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 selectionEnd() const
Convenience function to return the end of the selection as a linear index Contrary to the getSelectio...
virtual void initializeLexer()
Called when the dialect specific code lexer needs to be initialized (or reinitialized).
int linearPosition() const
Convenience function to return the cursor position as a linear index.
void setTitle(const QString &title)
Set the widget title.
void setLinearPosition(int position)
Convenience function to set the cursor position as a linear index.
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.
static QFont getMonospaceFont()
Returns the monospaced font to use for code editors.
void showNextCommand()
Shows the next command from the session in the editor.
void focusOutEvent(QFocusEvent *event) override
@ CodeFolding
Indicates that code folding should be enabled for the editor.
@ ImmediatelyUpdateHistory
Indicates that the history file should be immediately updated whenever a command is executed,...
void helpRequested(const QString &word)
Emitted when documentation was requested for the specified word.
bool isCursorOnLastLine() const
Returns true if the cursor is on the last line of the document.
static bool isFixedPitch(const QFont &font)
Returns true if a font is a fixed pitch font.
void updateSoftHistory()
Updates the soft history by storing the current editor text in the history.
void clearSessionHistory()
Clears the history of commands run in the current session.
void insertText(const QString &text)
Insert text at cursor position, or replace any selected text if user has made a selection.
bool writeHistoryFile()
Stores the commands executed in the editor to the persistent history file.
virtual void moveCursorToEnd()
Moves the cursor to the end of the document and scrolls to ensure it is visible.
static QString languageToString(Qgis::ScriptLanguage language)
Returns a user-friendly, translated name of the specified script language.
void setLineNumbersVisible(bool visible)
Sets whether line numbers should be visible in the editor.
void adjustScrollWidth()
Adjust the width of the scroll bar to fit the content.
virtual Qgis::ScriptLanguage language() const
Returns the associated scripting language.
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.
virtual QString reformatCodeString(const QString &string)
Applies code reformatting to a string and returns the result.
QgsCodeInterpreter * interpreter() const
Returns the attached code interpreter, or nullptr if not set.
bool lineNumbersVisible() const
Returns whether line numbers are visible in the editor.
QColor lexerColor(QgsCodeEditorColorScheme::ColorRole role) const
Returns the color to use in the lexer for the specified role.
bool foldingVisible()
Returns true if the folding controls are visible in the editor.
void showPreviousCommand()
Shows the previous command from the session in the editor.
Q_DECL_DEPRECATED void setMarginVisible(bool margin)
Set margin visible state.
void updatePrompt()
Triggers an update of the interactive prompt part of the editor.
void editingTimeout()
Emitted when either:
static QColor defaultColor(QgsCodeEditorColorScheme::ColorRole role, const QString &theme=QString())
Returns the default color for the specified role.
int selectionStart() const
Convenience function to return the start of the selection as a linear index Contrary to the getSelect...
void addWarning(int lineNumber, const QString &warning)
Adds a warning message and indicator to the specified a lineNumber.
virtual bool checkSyntax()
Applies syntax checking to the editor.
static QColor color(QgsCodeEditorColorScheme::ColorRole role)
Returns the color to use in the editor for the specified role.
An interface for code interpreters.
virtual int execCommandImpl(const QString &command)=0
Pure virtual method for executing commands in the interpreter.
int exec(const QString &command)
Executes a command in the interpreter.
virtual ~QgsCodeInterpreter()
static void setFontFamily(QFont &font, const QString &family)
Sets the family for a font object.
static QgsShortcutsManager * shortcutsManager()
Returns the global shortcuts manager, used for managing a QAction and QShortcut sequences.
void optionsChanged()
This signal is emitted whenever the application options have been changed.
static QgsGui * instance()
Returns a pointer to the singleton instance.
static QgsCodeEditorColorSchemeRegistry * codeEditorColorSchemeRegistry()
Returns the global code editor color scheme registry, used for registering the color schemes for QgsC...
A boolean 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.
void remove(const QString &key, QgsSettings::Section section=QgsSettings::NoSection)
Removes the setting key and any sub-settings of key in a section.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
@ CodeReformat
Reformat code.
@ CodeToggleComment
Toggle code comments.
QKeySequence sequenceForCommonAction(CommonAction action) const
Returns the key sequence which is associated with a common action, or an empty sequence if no shortcu...
static int levenshteinDistance(const QString &string1, const QString &string2, bool caseSensitive=false)
Returns the Levenshtein edit distance between two strings.
static QColor decodeColor(const QString &str)
#define BUILTIN_UNREACHABLE
int findMinimalDistanceIndex(const QString &source, const QString &target)
#define QgsDebugError(str)