MCPcopy Create free account
hub / github.com/FreeCAD/FreeCAD / onExecuteInConsole

Method onExecuteInConsole

src/Gui/PythonEditor.cpp:162–229  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

160}
161
162void PythonEditor::onExecuteInConsole()
163{
164 QTextCursor cursor = textCursor();
165 int selStart = cursor.selectionStart();
166 int selEnd = cursor.selectionEnd();
167 QTextBlock block;
168 QString selectedCode;
169
170 for (block = document()->begin(); block.isValid(); block = block.next()) {
171 int pos = block.position();
172 int off = block.length() - 1;
173 if (pos >= selStart || pos + off >= selStart) {
174 if (pos + 1 > selEnd) {
175 break;
176 }
177
178 QString lineText = block.text();
179 selectedCode.append(lineText + QLatin1String("\n"));
180 }
181 }
182
183 if (!selectedCode.isEmpty()) {
184
185 /** Dedent the block of code so that the first selected
186 * line has no indentation, but the remaining lines
187 * keep their indentation relative to that first line.
188 */
189
190 // get the leading whitespace of the first line
191 QStringList lines = selectedCode.split(QLatin1Char('\n'));
192 QString firstLineIndent;
193 for (const QString& line : lines) {
194 if (!line.isEmpty()) {
195 int leadingWhitespace = line.indexOf(QRegularExpression(QLatin1String("\\S")));
196 if (leadingWhitespace > 0) {
197 firstLineIndent = line.left(leadingWhitespace);
198 }
199 break;
200 }
201 }
202
203 // remove that first line whitespace from all the lines
204 for (QString& line : lines) {
205 if (!line.isEmpty() && line.startsWith(firstLineIndent)) {
206 line.remove(0, firstLineIndent.length());
207 }
208 }
209
210 // join the lines into a single QString so we can execute as a single block
211 QString dedentedCode = lines.join(QLatin1Char('\n'));
212
213 if (!dedentedCode.isEmpty()) {
214 try {
215 Gui::Command::doCommand(Gui::Command::Doc, dedentedCode.toStdString().c_str());
216 }
217 catch (const Base::Exception& e) {
218 QString errorMessage = QString::fromStdString(e.what());
219 Base::Console().error(

Callers

nothing calls this directly

Calls 15

leftMethod · 0.80
startsWithMethod · 0.80
toStdStringMethod · 0.80
constDataMethod · 0.80
beginMethod · 0.45
isValidMethod · 0.45
nextMethod · 0.45
positionMethod · 0.45
lengthMethod · 0.45
textMethod · 0.45
appendMethod · 0.45
isEmptyMethod · 0.45

Tested by

no test coverage detected