WSL/SLF GitLab Repository

PreviewWindow.cc 58.6 KB
Newer Older
1
2
3
4
5
/*****************************************************************************/
/*  Copyright 2019 WSL Institute for Snow and Avalanche Research  SLF-DAVOS  */
/*****************************************************************************/
/* This file is part of INIshell.
   INIshell is free software: you can redistribute it and/or modify
6
   it under the terms of the GNU General Public License as published by
7
8
9
10
11
12
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   INIshell is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
   GNU General Public License for more details.
14

15
16
   You should have received a copy of the GNU General Public License
   along with INIshell.  If not, see <http://www.gnu.org/licenses/>.
17
18
*/

19
#include "PreviewWindow.h"
20
#include "RememberDialog.h"
21
#include "src/gui_elements/Atomic.h"
22
#include "src/main/colors.h"
23
#include "src/main/common.h"
24
#include "src/main/os.h"
25
#include "src/main/inishell.h"
26
#include "src/main/settings.h"
27

28
#include <QClipboard>
29
#include <QCoreApplication>
30
31
#include <QFile>
#include <QFileDialog>
32
#include <QFileInfo>
33
34
#include <QFont>
#include <QFontDatabase>
35
#include <QGuiApplication>
36
#include <QHostInfo>
37
#include <QKeySequence>
38
#include <QMenuBar>
39
#include <QStatusBar>
Michael Reisecker's avatar
Michael Reisecker committed
40
#include <QTimer>
41

42
43
#include <vector>

44
45
46
#ifdef DEBUG
	#include <iostream>
#endif //def DEBUG
47

48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 * @class KeyPressFilter
 * @brief Key press event listener for the preview text editors.
 * @param[in] object Object the event stems from (the Text Editor).
 * @param[in] event The type of event.
 * @return True if the event was accepted.
 */
bool EditorKeyPressFilter::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() == QEvent::KeyPress) {
		auto *key_event = static_cast<QKeyEvent *>(event);
		if (keyToSequence(key_event) == QKeySequence::Cut) {
			//cut whole line on empty selection:
61
			auto *current_editor( static_cast<QPlainTextEdit *>(object) );
62
63
			current_editor->moveCursor(QTextCursor::StartOfLine);
			current_editor->moveCursor(QTextCursor::Down, QTextCursor::KeepAnchor);
64
65
			current_editor->cut();
			//our convention: cut the line feed, but don't paste it back
66
			//(convenient shortcut combination to move keys around)
67
68
			QClipboard *clipboard = QGuiApplication::clipboard();
			QString clip_text( clipboard->text() );
69
			clip_text.chop(1); //remove trailing newline
70
71
72
73
74
75
76
77
			clipboard->setText(clip_text);
			event->accept();
			return true;
		}
	}
	return QObject::eventFilter(object, event); //pass to actual event of the object
}

78
79
80
81
82
/**
 * @class SyntaxHighlighter
 * @brief Default constructor for a syntax highlighter used in the INI preview.
 * @param[in] textdoc Text document to handle syntax highlighting for.
 */
83
84
85
86
SyntaxHighlighter::SyntaxHighlighter(QTextDocument *textdoc) : QSyntaxHighlighter(textdoc)
{
	HighlightingRule rule;

87
88
89
90
91
92
93
	/*
	 * The SyntaxHighlighter parses a document for INI file syntax and checks the sections
	 * and keys against the curently loaded XML. Sections and keys that are not present
	 * in the XML are highlighted differently.
	 */

	/* unknown sections */
94
	QTextCharFormat format_section;
95
	format_section.setForeground(colors::getQColor("syntax_unknown_section"));
96
	format_section.setFontWeight(QFont::Bold);
97
	rule.pattern = QRegularExpression(R"(.*\)" + Cst::section_open + R"(.*\)" + Cst::section_close + R"(.*)");
98
99
100
	rule.format = format_section;
	rules_.append(rule);

101
	/* unknown keys */
102
103
	QTextCharFormat format_unknown_key;
	format_unknown_key.setForeground(colors::getQColor("syntax_unknown_key"));
Michael Reisecker's avatar
Michael Reisecker committed
104
105
	rule.pattern = QRegularExpression(R"(^\s*[\w|:|*]+(?=\s*=))"); //TODO: only :: but not :
	//TODO: collect and unify all regex handling (e. g. use the same here as in INIParser)
106
	rule.format = format_unknown_key;
107
108
	rules_.append(rule);

109
	/* INI values */
110
	QTextCharFormat format_value;
111
	format_value.setForeground(colors::getQColor("syntax_value"));
112
113
114
115
	rule.pattern = QRegularExpression(R"((?<=\=).*)");
	rule.format = format_value;
	rules_.append(rule);

116

117
118
119
120
121
122
123
	/* populate highlighter with known sections and keys */
	QTextCharFormat format_known_key;
	format_known_key.setForeground(colors::getQColor("syntax_known_key"));
	QTextCharFormat format_known_section;
	format_known_section.setForeground(colors::getQColor("syntax_known_section"));
	format_known_section.setFontWeight(QFont::Bold);

124
	QStringList added_sections_; //to avoid duplicated rules
125
	const QList<Atomic *> panel_list( getMainWindow()->findChildren<Atomic *>() );
126
	for (auto &panel : panel_list) {
Michael Reisecker's avatar
Michael Reisecker committed
127
		if (panel->property("no_ini").toBool()) //e. g. Groups / frames
128
			continue;
129
		QString section, key;
130
		(void) panel->getIniValue(section, key);
131
		key.replace("*", "\\*");
132
		rule.pattern = QRegularExpression("\\" + Cst::section_open + section + "\\" +
133
		    Cst::section_close, QRegularExpression::CaseInsensitiveOption); //TODO: escape only if needed for the set char
134
		rule.format = format_known_section;
135
136
137
138
		if (added_sections_.indexOf(QRegExp(section, Qt::CaseInsensitive)) == -1) {
			rules_.append(rule);
			added_sections_.append(section);
		}
139
140
141
142
		rule.pattern = QRegularExpression(R"(^\s*)" + key + R"((=|\s))", QRegularExpression::CaseInsensitiveOption);
		rule.format = format_known_key;
		rules_.append(rule);
	}
143
	//for dynamic sections we do not need to iterate through the GUI because we have them in a list:
144
	QStringList *dynamic_sections( getMainWindow()->getControlPanel()->getSectionTab()->getDynamicSectionList() );
145
146
147
148
149
150
	for (auto &dyn_sec : *dynamic_sections) { //add all dynamic sections with numeric postfixes
		rule.pattern = QRegularExpression("\\" + Cst::section_open + dyn_sec + "[0-9]+" + "\\" +
			Cst::section_close, QRegularExpression::CaseInsensitiveOption);
		rule.format = format_known_section;
		rules_.append(rule);
	}
151

152
153
154
155
156
157
158
159
160
	/* comments */
	QTextCharFormat format_block_comment;
	format_block_comment.setForeground(colors::getQColor("syntax_comment"));
	rule.pattern = QRegularExpression(R"(^\s*[#;].*)");
	rule.format = format_block_comment;
	rules_.append(rule);
	rule.pattern = QRegularExpression(R"(([#;](?!$).*))");
	rules_.append(rule);

Mathias Bavay's avatar
Mathias Bavay committed
161
162
163
	/* coordinates */
	QTextCharFormat format_coordinate;
	format_coordinate.setForeground(colors::getQColor("coordinate"));
164
 	rule.pattern = QRegularExpression(R"((latlon|xy)\s*\(([-\d\.]+)(?:,)\s*([-\d\.]+)((?:,)\s*([-\d\.]+))?\))");
Mathias Bavay's avatar
Mathias Bavay committed
165
166
167
	rule.format = format_coordinate;
	rules_.append(rule);
	
168
	/* equals sign */
169
170
171
172
	QTextCharFormat format_equal;
	format_equal.setForeground(Qt::black);
	rule.pattern = QRegularExpression(R"(=)");
	rule.format = format_equal;
173
174
175
	rules_.append(rule);
}

176
177
178
179
/**
 * @brief Send a chunk of text through the syntax highlighter.
 * @param[in] text The text to syntax-highlight.
 */
180
181
182
void SyntaxHighlighter::highlightBlock(const QString &text)
{
	for (const HighlightingRule &rule : qAsConst(rules_)) {
183
		QRegularExpressionMatchIterator mit( rule.pattern.globalMatch(text) );
184
		while (mit.hasNext()) { //run trough regex matches and set the stored formats
185
186
187
188
189
190
			QRegularExpressionMatch match = mit.next();
			setFormat(match.capturedStart(), match.capturedLength(), rule.format);
		}
	}
}

191
192
193
194
/**
 * @class PreviewWindow
 * @brief Default constructor for the PreviewWindow.
 * @details This constructor creates a tab bar to show multiple INI file versions in.
Michael Reisecker's avatar
Michael Reisecker committed
195
 * @param[in] parent The PreviewWindow's parent window (the main window).
196
 */
197
198
PreviewWindow::PreviewWindow(QMainWindow *parent) : QMainWindow(parent),
    preview_ini_(getMainWindow()->getLogger())
199
{
200
	editor_key_filter_ = new EditorKeyPressFilter;
201
	file_tabs_ = new QTabWidget;
202
	connect(file_tabs_, &QTabWidget::tabCloseRequested, this, &PreviewWindow::closeTab);
203
	
204
	file_tabs_->setTabsClosable(true);
205
	this->setCentralWidget(file_tabs_);
206
	createMenu();
207
	setAcceptDrops(true);
208

209
	this->setWindowTitle(tr("Preview") + " ~ " + QCoreApplication::applicationName());
210
	createFindBar(); //do last to keep status bar hidden
211
	statusBar()->hide();
212
213
}

214
215
216
217
218
219
220
221
/**
 * @brief Destructor with minimal cleanup.
 */
PreviewWindow::~PreviewWindow()
{
	delete editor_key_filter_;
}

222
223
/**
 * @brief Display the current INI file in a new tab.
224
 * @param[in] infile Optional file name to load instead of the GUI values.
225
 */
226
void PreviewWindow::addIniTab(const QString& infile)
227
{
228
	const bool fromGUI = infile.isNull();
229
	/* get currently set INI values */
230
	QString ini_contents;
231
	if (fromGUI) //load INI from GUI
232
233
234
		loadIniWithGui(); //extend original file's INIParser with GUI values
	else
		preview_ini_.parseFile(infile); //load INI from file system
235

236
	/* text box for the current INI */
237
	const bool setMonospace = (getSetting("user::preview::mono_font", "value") == "TRUE");
238
	auto *preview_editor( new PreviewEdit(setMonospace) );
239
	preview_editor->installEventFilter(editor_key_filter_);
240
241
	preview_editor->setStyleSheet("QPlainTextEdit {background-color: " + colors::getQColor("syntax_background").name() +
		"; color: " + colors::getQColor("syntax_invalid").name() + "}");
242

243
244
	highlighter_ = new SyntaxHighlighter(preview_editor->document());

245
	/* display the current GUI's contents */
246
	QTextStream ss(&ini_contents);
247
	preview_ini_.outputIni(ss);
248
	if (ini_contents.isEmpty()) {
249
250
		ini_contents = tr("#Empty INI file\n");
		previewStatus(tr("Open an application and load an INI file to view contents"));
251
252
253
	} else {
		previewStatus(QString());
		this->statusBar()->hide();
254
	}
255
	preview_editor->setPlainText(ini_contents); //without undo history --> can't undo to empty
256
257
258
259
260
261
262
263
264
	if (!fromGUI) preview_editor->setReadOnly(true); //INIs read directly from file are RO

	bool gui_is_saved = true;
	QString loaded_file( fromGUI? getMainWindow()->getIni()->getFilename() : infile );
	if (loaded_file.isEmpty()) { //pick file name if no INI is opened yet
		loaded_file = QDir::currentPath() + "/" + "unsaved("+QString::number(unsaved_ini_counter_)+").ini";
		unsaved_ini_counter_++;
	}
	if (fromGUI) { //check for difference between last saved (in GUI) and current state
265
		INIParser gui_ini = getMainWindow()->getIniCopy();
266
		(void) getMainWindow()->getControlPanel()->getSectionTab()->setIniValuesFromGui(&gui_ini);
267
		if (getMainWindow()->getIniCopy() != gui_ini)
268
			gui_is_saved = false;
269
	}
270
271
272
273
274
	preview_editor->setFile(loaded_file);
	//if loaded from GUI (i. e. not a different INI preview), and the GUI has not been saved...
	const QString shown_name( preview_editor->getFileName() + ((fromGUI && !gui_is_saved)? " *" : "") );
	file_tabs_->addTab(preview_editor, shown_name); //...open with 'unsaved' asterisk
	file_tabs_->setTabToolTip(file_tabs_->count() - 1, preview_editor->getFullFilePath());
275
	file_tabs_->setCurrentIndex(file_tabs_->count() - 1); //switch to new tab
276
277
278
	preview_editor->setFocus(); //ATT: the first ever focus inexplicably fires a textChanged()
	const int curr_tab_count = file_tabs_->count(); //a const to give to the lambda
	connect(preview_editor, &QPlainTextEdit::textChanged, this, [=]{ textChanged(curr_tab_count - 1); });
279
280
281

	onShowWhitespacesMenuClick((getSetting("user::preview::show_ws", "value") == "TRUE"));
} //TODO: tab completion for INI keys
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297

/**
 * @brief Event listener for when the window is being closed.
 * @details This function allows the user to cancel the closing if there are unsaved
 * changes in the opened INI files.
 * @param[in] event The close event.
 */
void PreviewWindow::closeEvent(QCloseEvent *event)
{
	bool has_unsaved_changes = false; //run through tabs and check for asterisks
	for (int ii = 0; ii < file_tabs_->count(); ++ii) {
		if (file_tabs_->tabText(ii).endsWith("*")) {
			has_unsaved_changes = true;
			break;
		}
	}
298
	if (has_unsaved_changes &&
299
		getSetting("user::warnings::warn_unsaved_preview", "value") == "TRUE") { //at least one tab has unsaved changes
300
301
302
303
304
305
306
		const int cancel = warnOnUnsavedIni();
		if (cancel == QMessageBox::Cancel) {
			event->ignore();
			return;
		}
	}
	event->accept();
307
308
}

309
/**
310
311
 * @brief Event listener for key presses.
 * @details Close the Preview, add tab, or show the logger.
Michael Reisecker's avatar
Michael Reisecker committed
312
 * @param[in] event The key press event that is received.
313
314
315
 */
void PreviewWindow::keyPressEvent(QKeyEvent *event)
{
316
	if (event->key() == Qt::Key_Escape) {
317
		if (this->find_text_->isHidden())
318
319
320
			this->close();
		else
			hideFindBar();
321
322
323
324
325
326
	} else if (keyToSequence(event) == QKeySequence::Print) {
		addIniTab();
	} else if (event->modifiers() == Qt::CTRL && event->key() == Qt::Key_L) {
		getMainWindow()->getLogger()->show();
		getMainWindow()->getLogger()->raise();
	}
327
}
328

329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/**
 * @brief Event listener for drag events.
 * @details This function reacts if a user starts dragging content into the Preview Editor
 * and accepts the dragging.
 * @param[in] event The drag event.
 */
void PreviewWindow::dragEnterEvent(QDragEnterEvent *event)
{
	event->acceptProposedAction();
}

/**
 * @brief Event listener for drop events.
 * @details This is an event listener for the parent preview window, not the text editor itself.
 * As such, the text editor will sill handle its drag & drop functionality accordingly. In order
 * for users to be able to drop files, they need to drop it ouside of the text area. When dragging
 * into the text area however, an info status about this is displayed.
 * @param[in] event The drop event.
 */
void PreviewWindow::dropEvent(QDropEvent *event)
{
	for (const QUrl &url : event->mimeData()->urls()) //run through all files
		addIniTab(url.toLocalFile());
}

354
355
356
357
/**
 * @brief Close an INI file's tab.
 * @param[in] index Index of the tab that is being closed.
 */
358
359
void PreviewWindow::closeTab(int index)
{
360
	//Check for unsaved changes. Note that changes that cancel out leaving the INI file
361
	//unaltered will still trigger the warning (unlike the GUI).
362
	if (file_tabs_->tabText(index).endsWith("*") &&
363
	    getSetting("user::warnings::warn_unsaved_preview", "value") == "TRUE") { //not saved yet
364
365
366
367
368
369
		const int cancel = warnOnUnsavedIni();
		if (cancel == QMessageBox::Cancel)
			return;
	}

	file_tabs_->removeTab(index);
370
371
	if (file_tabs_->count() == 0) {
		unsaved_ini_counter_ = 1; //reset auto-chosen display number
372
		this->close();
373
	}
374
375
}

376
377
378
/**
 * @brief Create the PreviewWindow's menu.
 */
379
380
void PreviewWindow::createMenu()
{
381
	/* FILE menu */
382
	QMenu *menu_file = this->menuBar()->addMenu(tr("&File"));
383
384
385
386
387
	auto *file_open = new QAction(getIcon("document-open"), tr("&Open..."), menu_file);
	file_open->setShortcut( QKeySequence::Open );
	menu_file->addAction(file_open);
	connect(file_open, &QAction::triggered, this, &PreviewWindow::openFile);
	menu_file->addSeparator();
388
	auto *file_save = new QAction(getIcon("document-save"), tr("&Save"), menu_file);
389
	file_save->setShortcut( QKeySequence::Save );
390
391
	menu_file->addAction(file_save);
	connect(file_save, &QAction::triggered, this, &PreviewWindow::saveFile);
392
	auto *file_save_as = new QAction(getIcon("document-save-as"), tr("Save &as..."), menu_file);
393
	file_save_as->setShortcut( QKeySequence::SaveAs );
394
395
	menu_file->addAction(file_save_as);
	connect(file_save_as, &QAction::triggered, this, &PreviewWindow::saveFileAs);
396
	menu_file->addSeparator();
397
398
399
400
401
402
	file_save_and_load_ = new QAction(tr("Save and load into GUI"), menu_file);
	menu_file->addAction(file_save_and_load_);
	connect(file_save_and_load_, &QAction::triggered, this, &PreviewWindow::saveFileAndLoadIntoGui);
	file_load_ = new QAction(tr("Load into GUI"), menu_file);
	menu_file->addAction(file_load_);
	connect(file_load_, &QAction::triggered, this, &PreviewWindow::loadIntoGui);
403
404
405
	menu_file->addSeparator();
	auto *file_backup = new QAction(tr("Quicksave backup"), menu_file);
	menu_file->addAction(file_backup);
406
	file_backup->setShortcut(Qt::CTRL + Qt::ALT + Qt::Key_B);
407
	connect(file_backup, &QAction::triggered, this, &PreviewWindow::quickBackup);
408
409
410
411
	auto *file_close_ = new QAction(getIcon("application-exit"), tr("&Close preview"), menu_file);
	file_close_->setShortcut(Qt::Key_Escape);
	menu_file->addAction(file_close_);
	connect(file_close_, &QAction::triggered, this, [=]{ this->close(); });
412

413
	/* EDIT menu */
414
	QMenu *menu_edit = this->menuBar()->addMenu(tr("&Edit"));
Mathias Bavay's avatar
Mathias Bavay committed
415
	auto *edit_undo = new QAction(getIcon("edit-undo"), tr("Undo"), menu_edit);
416
417
418
	menu_edit->addAction(edit_undo);
	edit_undo->setShortcut(QKeySequence::Undo);
	connect(edit_undo, &QAction::triggered, this, [=]{ getCurrentEditor()->undo(); });
Mathias Bavay's avatar
Mathias Bavay committed
419
	auto *edit_redo = new QAction(getIcon("edit-redo"), tr("Redo"), menu_edit);
420
421
422
423
	menu_edit->addAction(edit_redo);
	edit_redo->setShortcut(QKeySequence::Redo);
	connect(edit_redo, &QAction::triggered, this, [=]{ getCurrentEditor()->redo(); });
	menu_edit->addSeparator();
Mathias Bavay's avatar
Mathias Bavay committed
424
	auto *edit_cut = new QAction(getIcon("edit-cut"), tr("Cut"), menu_edit);
425
426
427
	menu_edit->addAction(edit_cut);
	edit_cut->setShortcut(QKeySequence::Cut);
	connect(edit_cut, &QAction::triggered, this, [=]{ getCurrentEditor()->cut(); });
Mathias Bavay's avatar
Mathias Bavay committed
428
	auto *edit_copy = new QAction(getIcon("edit-copy"), tr("Copy"), menu_edit);
429
430
431
	menu_edit->addAction(edit_copy);
	edit_copy->setShortcut(QKeySequence::Copy);
	connect(edit_copy, &QAction::triggered, this, [=]{ getCurrentEditor()->copy(); });
Mathias Bavay's avatar
Mathias Bavay committed
432
	auto *edit_paste = new QAction(getIcon("edit-paste"), tr("Paste"), menu_edit);
433
434
435
	menu_edit->addAction(edit_paste);
	edit_paste->setShortcut(QKeySequence::Paste);
	connect(edit_paste, &QAction::triggered, this, [=]{ getCurrentEditor()->paste(); });
436
437
	auto *edit_paste_newline = new QAction(tr("Paste to new line"), menu_edit);
	menu_edit->addAction(edit_paste_newline);
438
439
	edit_paste_newline->setShortcut("Alt+" +
	    QKeySequence(QKeySequence::Paste).toString(QKeySequence::NativeText));
440
	connect(edit_paste_newline, &QAction::triggered, this, [=]{ pasteToNewline(); });
Mathias Bavay's avatar
Mathias Bavay committed
441
	auto *edit_select_all = new QAction(getIcon("edit-select-all"), tr("Select all"), menu_edit);
442
443
444
445
446
447
448
449
450
	menu_edit->addAction(edit_select_all);
	edit_select_all->setShortcut(QKeySequence::SelectAll);
	connect(edit_select_all, &QAction::triggered, this, [=]{ getCurrentEditor()->selectAll(); });
	menu_edit->addSeparator();
	auto *edit_find = new QAction(getIcon("edit-find"), tr("&Find text..."), menu_edit);
	menu_edit->addAction(edit_find);
	edit_find->setShortcut(QKeySequence::Find);
	connect(edit_find, &QAction::triggered, this, &PreviewWindow::showFindBar);

451
452
	/* INSERT menu */
	QMenu *menu_insert = this->menuBar()->addMenu(tr("&Insert"));
453
454
455
456
457
458
	auto *edit_insert_header = new QAction(tr("Comment header"), menu_insert);
	menu_insert->addAction(edit_insert_header);
	connect(edit_insert_header, &QAction::triggered, this,
	    [=]{ onInsertMenuClick("insert_header"); });
	menu_insert->addSeparator();
	edit_insert_missing_ = new QAction(tr("Missing keys for GUI"), menu_insert);
459
460
461
	menu_insert->addAction(edit_insert_missing_);
	connect(edit_insert_missing_, &QAction::triggered, this,
	    [=]{ onInsertMenuClick("insert_missing"); });
462
	edit_insert_missing_mandatory_ = new QAction(tr("Mandatory keys for GUI"),
463
464
465
466
467
	     menu_insert);
	menu_insert->addAction(edit_insert_missing_mandatory_);
	connect(edit_insert_missing_mandatory_, &QAction::triggered, this,
	    [=]{ onInsertMenuClick("insert_missing_mandatory"); });

468
	/* TRANSFORM menu */
469
	QMenu *menu_transform = this->menuBar()->addMenu(tr("&Transform"));
470
	/* Whitespaces menu */
471
	auto *transform_whitespaces = new QMenu(tr("Whitespaces"), menu_transform);
472
	transform_whitespaces->setIcon( getIcon("markasblank") );
473
	menu_transform->addMenu(transform_whitespaces);
Mathias Bavay's avatar
Mathias Bavay committed
474
	auto *transform_transform_singlews = new QAction(getIcon("unmarkasblank"), tr("To single spaces"), transform_whitespaces);
475
476
477
	connect(transform_transform_singlews, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_whitespace_singlews"); } );
	transform_whitespaces->addAction(transform_transform_singlews);
478
479
	auto *transform_transform_longestws = new QAction(tr("Adapt to longest keys"),
	    transform_whitespaces);
480
481
482
	connect(transform_transform_longestws, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_whitespace_longestws"); } );
	transform_whitespaces->addAction(transform_transform_longestws);
483
	/* Sort */
484
	auto *transform_sort = new QMenu(tr("Sort"), menu_transform);
Mathias Bavay's avatar
Mathias Bavay committed
485
	transform_sort->setIcon( getIcon("view-sort") );
486
487
488
489
490
491
492
493
494
	menu_transform->addMenu(transform_sort);
	auto *transform_sort_alphabetically = new QAction(tr("Alphabetically"), transform_sort);
	connect(transform_sort_alphabetically, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_sort_alphabetically"); } );
	transform_sort->addAction(transform_sort_alphabetically);
	auto *transform_sort_order = new QAction(tr("In order of INI file"), transform_sort);
	connect(transform_sort_order, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_sort_order"); } );
	transform_sort->addAction(transform_sort_order);
495
	/* Capitalization menu */
496
497
	auto *transform_capitalization = new QMenu(tr("Capitalization"), menu_transform);
	menu_transform->addMenu(transform_capitalization);
498
	auto *transform_capitalization_sections_upper = new QAction(
499
500
501
502
	    tr("Sections to upper case"), transform_capitalization);
	connect(transform_capitalization_sections_upper, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_sections_upper"); } );
	transform_capitalization->addAction(transform_capitalization_sections_upper);
503
	auto *transform_capitalization_sections_lower = new QAction(
504
505
506
507
	    tr("Sections to lower case"), transform_capitalization);
	connect(transform_capitalization_sections_lower, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_sections_lower"); } );
	transform_capitalization->addAction(transform_capitalization_sections_lower);
508
	auto *transform_capitalization_keys_upper = new QAction(
509
510
511
512
	    tr("Keys to upper case"), transform_capitalization);
	connect(transform_capitalization_keys_upper, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_keys_upper"); } );
	transform_capitalization->addAction(transform_capitalization_keys_upper);
513
	auto *transform_capitalization_keys_lower = new QAction(
514
515
516
517
	    tr("Keys to lower case"), transform_capitalization);
	connect(transform_capitalization_keys_lower, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_keys_lower"); } );
	transform_capitalization->addAction(transform_capitalization_keys_lower);
518
	auto *transform_capitalization_values_upper = new QAction(
519
520
521
522
	    tr("Values to upper case"), transform_capitalization);
	connect(transform_capitalization_values_upper, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_values_upper"); } );
	transform_capitalization->addAction(transform_capitalization_values_upper);
523
	auto *transform_capitalization_values_lower = new QAction(
524
525
526
527
528
529
530
	    tr("Values to lower case"), transform_capitalization);
	connect(transform_capitalization_values_lower, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_values_lower"); } );
	transform_capitalization->addAction(transform_capitalization_values_lower);
	transform_capitalization->addSeparator();
	auto *transform_capitalization_upper = new QAction(getIcon("format-text-uppercase"),
	    tr("All to upper case"), transform_capitalization);
531
532
533
	connect(transform_capitalization_upper, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_upper"); } );
	transform_capitalization->addAction(transform_capitalization_upper);
534
535
	auto *transform_capitalization_lower = new QAction(getIcon("format-text-lowercase"),
	    tr("All to lower case"), transform_capitalization);
536
537
538
	connect(transform_capitalization_lower, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_lower"); } );
	transform_capitalization->addAction(transform_capitalization_lower);
539
	/* Comments menu */
540
	auto *transform_comments = new QMenu(tr("Comments"), menu_transform);
541
	transform_comments->setIcon( getIcon("code-context") );
542
	menu_transform->addMenu(transform_comments);
543
544
545
546
547
548
549
550
551
552
	auto *transform_comment_block = new QAction(tr("Comment selection"));
	transform_comments->addAction(transform_comment_block);
	transform_comment_block->setShortcut(Qt::CTRL + Qt::Key_NumberSign);
	connect(transform_comment_block, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comment_block"); });
	auto *transform_uncomment_block = new QAction(tr("Uncomment selection"));
	transform_comments->addAction(transform_uncomment_block);
	transform_uncomment_block->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_NumberSign);
	connect(transform_uncomment_block, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_uncomment_block"); });
553
	transform_comments->addSeparator();
554
	auto *transform_comments_content = new QAction(tr("Comment all content"),
555
	    transform_comments);
556
557
558
	connect(transform_comments_content, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_content"); } );
	transform_comments->addAction(transform_comments_content);
559
	auto *transform_comments_duplicate = new QAction(tr("Duplicate all to comment"),
560
	    transform_comments);
561
	transform_comments_duplicate->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_B);
562
563
564
	connect(transform_comments_duplicate, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_duplicate"); } );
	transform_comments->addAction(transform_comments_duplicate);
565
566
567
568
569
	auto *transform_comments_move_values = new QAction(tr("Move next to values"),
	    transform_comments);
	connect(transform_comments_move_values, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_move_value"); } );
	transform_comments->addAction(transform_comments_move_values);
570
	auto *transform_comments_move_end = new QAction(tr("Collect at bottom"),
571
	    transform_comments);
572
573
574
	connect(transform_comments_move_end, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_move_end"); } );
	transform_comments->addAction(transform_comments_move_end);
Mathias Bavay's avatar
Mathias Bavay committed
575
	auto *transform_comments_trim = new QAction(getIcon("edit-clear-all"), tr("Trim"), transform_comments);
576
577
578
579
	connect(transform_comments_trim, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_trim"); } );
	transform_comments->addAction(transform_comments_trim);
	auto *transform_comments_delete = new QAction(tr("Delete all"), transform_comments);
580
581
582
	connect(transform_comments_delete, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_delete"); } );
	transform_comments->addAction(transform_comments_delete);
583
	transform_comments->addSeparator();
584
585
586
587
588
589
590
591
592
	auto *transform_comments_numbersign = new QAction(tr("Switch to #"), transform_comments);
	connect(transform_comments_numbersign, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_numbersign"); } );
	transform_comments->addAction(transform_comments_numbersign);
	auto *transform_comments_semicolon = new QAction(tr("Switch to ;"), transform_comments);
	connect(transform_comments_semicolon, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_semicolon"); } );
	transform_comments->addAction(transform_comments_semicolon);
	/* Reset menu */
593
	auto *transform_reset = new QMenu(tr("Reset"), menu_transform);
Mathias Bavay's avatar
Mathias Bavay committed
594
	transform_reset->setIcon( getIcon("view-refresh") );
595
	menu_transform->addMenu(transform_reset);
596
597
	auto *transform_reset_original = new QAction(tr("To original INI on file system"),
	    transform_reset);
598
599
600
	connect(transform_reset_original, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_reset_original"); } );
	transform_reset->addAction(transform_reset_original);
601
602
	transform_reset_full_ = new QAction(tr("To full INI with GUI keys"), transform_reset);
	connect(transform_reset_full_, &QAction::triggered, this,
603
	    [=]{ onTransformMenuClick("transform_reset_full"); } );
604
	transform_reset->addAction(transform_reset_full_);
605

606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
	/* CONVERT menu */
	QMenu *menu_convert = this->menuBar()->addMenu(tr("&Convert"));
	QMenu *menu_convert_tabs = new QMenu("&Tabs", menu_convert);
	menu_convert->addMenu(menu_convert_tabs);
	auto *convert_long_spaces_to_tabs = new QAction(tr("8 spaces to tabs"), menu_convert_tabs);
	connect (convert_long_spaces_to_tabs, &QAction::triggered, this,
	    [=]{ onConvertMenuClick("convert_long_spaces_to_tabs"); } );
	menu_convert_tabs->addAction(convert_long_spaces_to_tabs);
	auto *convert_short_spaces_to_tabs = new QAction(tr("4 spaces to tabs"), menu_convert_tabs);
	connect (convert_short_spaces_to_tabs, &QAction::triggered, this,
	    [=]{ onConvertMenuClick("convert_short_spaces_to_tabs"); } );
	menu_convert_tabs->addAction(convert_short_spaces_to_tabs);
	auto *convert_tabs_to_long_spaces = new QAction(tr("Tabs to 8 spaces"), menu_convert_tabs);
	connect (convert_tabs_to_long_spaces, &QAction::triggered, this,
	    [=]{ onConvertMenuClick("convert_tabs_to_long_spaces"); } );
	menu_convert_tabs->addAction(convert_tabs_to_long_spaces);
	auto *convert_tabs_to_short_spaces = new QAction(tr("Tabs to 4 spaces"), menu_convert_tabs);
	connect (convert_tabs_to_short_spaces, &QAction::triggered, this,
	    [=]{ onConvertMenuClick("convert_tabs_to_short_spaces"); } );
	menu_convert_tabs->addAction(convert_tabs_to_short_spaces);

627
	/* VIEW menu */
628
	QMenu *menu_view = this->menuBar()->addMenu(tr("&View"));
629
630
631
632
633
634
635
636
	auto *view_hidden_chars = new QAction(tr("Show &whitespaces"), menu_view);
	view_hidden_chars->setCheckable(true);
	if (getSetting("user::preview::show_ws", "value") == "TRUE")
		view_hidden_chars->setChecked(true);
	connect (view_hidden_chars, &QAction::triggered, this,
	    [=]{ onShowWhitespacesMenuClick(view_hidden_chars->isChecked()); } );
	menu_view->addAction(view_hidden_chars);
	menu_view->addSeparator();
637
	auto *view_new_tab = new QAction(getIcon("tab-new"), tr("&New tab"), menu_view);
638
	view_new_tab->setShortcut(QKeySequence::AddTab);
639
640
	connect(view_new_tab, &QAction::triggered, this, [=]{ addIniTab(); });
	menu_view->addAction(view_new_tab);
641
	auto *view_close_tab = new QAction(getIcon("tab-close"), tr("&Close tab"), menu_view);
642
643
644
	view_close_tab->setShortcut(QKeySequence::Close);
	connect(view_close_tab, &QAction::triggered, this, [=]{ closeTab(file_tabs_->currentIndex()); });
	menu_view->addAction(view_close_tab);
645
646

	/* HELP menu */
647
#if !defined Q_OS_MAC //use extra tab bar that is pushed to the right
648
649
	auto *menu_help_main = new QMenuBar(this->menuBar());
	QMenu *menu_help = menu_help_main->addMenu(tr("&?"));
650
	menu_help_main->addMenu(menu_help);
Michael Reisecker's avatar
Michael Reisecker committed
651
	auto *help = new QAction(getIcon("help-contents"), tr("Preview &help"), menu_help);
652
	help->setShortcut(QKeySequence::HelpContents);
653
	this->menuBar()->setCornerWidget(menu_help_main); //push help menu to the right
654
	menu_help->addAction(help);
655
#else  //normal menu that can be re-ordered by Qt/macOS
656
	auto *menu_help_main = this->menuBar()->addMenu("&?");
Michael Reisecker's avatar
Michael Reisecker committed
657
658
	auto *help = new QAction(getIcon("help-contents"), tr("Preview &help"), menu_help_main);
	help->setMenuRole(QAction::ApplicationSpecificRole);
659
660
	menu_help_main->addAction(help);
#endif
661
662
	connect(help, &QAction::triggered, this,
	    [=]{ getMainWindow()->loadHelp("UI of INIshell", "help-preview"); });
663
664
665
}

/**
666
 * @brief Prepare a panel in the status bar that allows users to search for text in the preview.
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
 */
void PreviewWindow::createFindBar()
{
	find_text_ = new QLineEdit(this);
	connect(find_text_, &QLineEdit::textChanged, this, &PreviewWindow::onFindTextChanged);
	close_find_bar_ = new QToolButton(this);
	close_find_bar_->setIcon(getIcon("window-close"));
	close_find_bar_->setAutoRaise(true);
	connect(close_find_bar_, &QToolButton::clicked, this, [&]{ hideFindBar(); });
	this->statusBar()->addWidget(find_text_, 1);
	this->statusBar()->addWidget(close_find_bar_);
	hideFindBar();
}

/**
 * @brief Show the find bar.
 */
void PreviewWindow::showFindBar()
{
	previewStatus(QString( ));
	statusBar()->show();
	find_text_->show();
	close_find_bar_->show();
	find_text_->setFocus();
	find_text_->selectAll();
}

/**
 * @brief Hide the find bar.
 */
void PreviewWindow::hideFindBar()
{
	find_text_->hide();
	close_find_bar_->hide();
	statusBar()->hide();
702
703
}

704
705
706
707
708
709
710
711
/**
 * @brief Delegated event listener for when the preview text changes.
 * @details A lambda calls this function with the text box index to add an asterisk
 * to the title ("not saved").
 * @param[in] index Index of the tab the text changed in.
 */
void PreviewWindow::textChanged(const int &index)
{
712
	file_tabs_->setTabText(index, getCurrentEditor()->getFileName() + " *");
713
714
}

715
716
717
718
719
720
/**
 * @brief Combine the original file's INIParser with GUI values and
 * set the local copy to access both.
 */
void PreviewWindow::loadIniWithGui()
{
721
	const QString current_app( getMainWindow()->getCurrentApplication() );
722
	preview_ini_ = getMainWindow()->getIniCopy();
723
724
	preview_ini_.clear(true); //only keep unknown keys (which are transported from input to output)

725
	getMainWindow()->getControlPanel()->getSectionTab()->setIniValuesFromGui(&preview_ini_);
726
	file_save_and_load_->setText(tr("Save and load into ") + getMainWindow()->getCurrentApplication());
727
	file_load_->setText(tr("Load into ") + current_app);
728
729
730
	edit_insert_missing_->setText(tr("Missing keys for ") + current_app);
	edit_insert_missing_mandatory_->setText(tr("Mandatory keys for ") + current_app);
	transform_reset_full_->setText(tr("To full INI with %1 keys").arg(current_app));
731
732
}

733
734
735
736
737
738
739
740
/**
 * @brief Write an opened INI file to the file system.
 * @param[in] file_name The path to save to.
 */
void PreviewWindow::writeIniToFile(const QString &file_name)
{
	QFile outfile(file_name);
	if (!outfile.open(QIODevice::WriteOnly)) {
741
		previewStatus(tr("Could not open %1").arg(QDir::toNativeSeparators(file_name)));
742
743
744
		return;
	}
	QTextStream ss(&outfile);
745
	const auto text_box( getCurrentEditor() );
746
747
748
749
	if (text_box)
		ss << text_box->toPlainText();
	outfile.close();

750
751
752
	getCurrentEditor()->setFile(file_name);
	//switch the displayed name to new file (without asterisk):
	file_tabs_->setTabText(file_tabs_->currentIndex(), getCurrentEditor()->getFileName());
753
	previewStatus(tr("Saved to ") + file_name);
754

755
	setSetting("auto::history::last_preview_write", "path", getCurrentEditor()->getFilePath());
756
757
758
759
760
761
762
763
764
}

/**
 * @brief Ask a user if they want to cancel an action.
 * @details This function is called before closing INI tabs with unsaved changes.
 * @return Button the user has clicked.
 */
int PreviewWindow::warnOnUnsavedIni()
{
765
766
767
768
	const QString msg( tr("Preview INI not saved yet") );
	const QString informative( tr("Your INI file preview(s) may contain unsaved changes.") );
	const QFlags<QMessageBox::StandardButton> buttons( QMessageBox::Cancel | QMessageBox::Discard );
	RememberDialog msgNotSaved("user::warnings::warn_unsaved_preview", msg, informative, QString(), buttons, this);
769
770
771
772
	int clicked = msgNotSaved.exec();
	return clicked;
}

773
774
775
776
777
/**
 * @brief Show a temporary status message in the preview window. This text is volatile.
 * @param[in] text Text to show in the status.
 */
void PreviewWindow::previewStatus(const QString &text)
778
{ //temporary message - erased for e. g. on menu hover
779
780
	statusBar()->showMessage(text);
	statusBar()->show(); //might be hidden from closing the find bar
781
	statusBar()->setToolTip(text);
782
783
}

784
/**
785
786
 * @brief Helper function to get the current tab's text editor.
 * @return The text editor currently in view.
787
 */
788
PreviewEdit * PreviewWindow::getCurrentEditor() const
789
{
790
#ifdef DEBUG
791
792
	if (!qobject_cast<PreviewEdit *>(file_tabs_->currentWidget()))
		qDebug() << "PreviewWindow::getCurrentEditor() should have casted to a PreviewEdit but did not";
793
#endif //def DEBUG
794
	return qobject_cast<PreviewEdit *>(file_tabs_->currentWidget());
795
796
}

797
798
799
800
801
802
803
/**
 * @brief Set an editor's text programmatically and add it to the undo history.
 * @details This is a small hack and inserts the text by selecting all and pasting;
 * otherwise this change is not remembered in the document's history.
 * @param[in] editor Editor to set text for.
 * @param[in] text Text to set.
 */
804
void PreviewWindow::setTextWithHistory(QPlainTextEdit *editor, const QString &text)
805
806
807
808
809
810
811
{
	QTextDocument *doc( editor->document() );
	QTextCursor cursor( doc );
	cursor.select(QTextCursor::Document);
	cursor.insertText(text);
}

812
813
814
815
/**
 * @brief Insert missing keys.
 * @details This function looks through the keys in the GUI and adds the
 * ones that are missing.
816
 * @param[in] mode Insert mode (fill missing, fill missing mandatory).
817
 */
818
void PreviewWindow::insertText(const insert_text &mode)
819
{
820
	if (mode == HEADER) {
821
		static const QString marker( QString("#").repeated(60) );
822
823
		const QString year( QDate::currentDate().toString("yyyy") );
		const QString date( QDate::currentDate().toString("yyyy-MM-dd") );
824
		const QString username( os::getLogName() );
825
		const QString user_domain( QHostInfo::localDomainName() );
826
827
828
829
830
831
832
833
		QString copyright("# Copyright ");
		if (!username.isEmpty()) copyright.append(username);
		if (!user_domain.isEmpty()) {
			if (!username.isEmpty()) copyright.append(" - ");
			copyright.append(user_domain);
		}
		if (!username.isEmpty() || !user_domain.isEmpty()) copyright.append(", ");
		copyright.append(year);
834
		for (int ii=copyright.size()+1; ii<marker.size(); ii++)
835
			copyright.append(" ");
Michael Reisecker's avatar
Michael Reisecker committed
836

837
		QString header;
838
		header += marker + "\n";
839
		header += copyright + "#\n";
840
		header += marker + "\n";
841
842
		header += "#" + QCoreApplication::applicationName() + " " + APP_VERSION_STR;
		header += " for " + getMainWindow()->getCurrentApplication() + "\n";
843
844
845
846
847
		header += "#" + date + "\n\n";
		preview_ini_.parseText(getCurrentEditor()->toPlainText().prepend(header));
		return;
	}

848
	INIParser gui_ini(getMainWindow()->getLogger());
849
	getMainWindow()->getControlPanel()->getSectionTab()->setIniValuesFromGui(&gui_ini, true);
850
851
852
	int counter = 0;
	for (auto &sec : *gui_ini.getSections()) {
		for (auto &keyval : sec.getKeyValueList()) {
Michael Reisecker's avatar
Michael Reisecker committed
853
			if (!preview_ini_.hasKeyValue(keyval.first)) {
854
855
856
				if ((mode == MISSING) ||
				    (mode == MISSING_MANDATORY && keyval.second.isMandatory())) {
					QString value( keyval.second.getValue() );
857
					preview_ini_.set(sec.getName(), keyval.first, value);
858
859
860
					counter++;
				}
			}
861
		} //endfor keyval
862
863
864
865
	}
	previewStatus(tr("Inserted %1 keys").arg(counter));
}

866
867
868
869
870
871
872
873
874
875
876
/**
 * @brief Perform whitespaces related transformations on the local INIParser copy.
 * @param[in] mode Type of transformation.
 */
void PreviewWindow::transformWhitespaces(const transform_whitespaces &mode)
{
	switch (mode) {
	case SINGLE_WS:
		for (auto &sec : *preview_ini_.getSections()) {
			for (auto &key : sec.getKeyValueList())
				sec.getKeyValue(key.first)->setKeyValWhitespaces(
877
				    std::vector<QString>( {"", " ", " ", " "} )); //(0)key(1)=(2)value(3)#comment
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
		}
		break;
	case LONGEST_WS:
		for (auto &sec : *preview_ini_.getSections()) {
			int max_key_length = 0;
			for (auto &key : sec.getKeyValueList()) {
				if (!key.second.getValue().isNull() && key.first.length() > max_key_length)
					max_key_length = key.first.length();
			}
			for (auto &key : sec.getKeyValueList()) {
				const int nr_ws = max_key_length - key.first.length() + 1;
				sec.getKeyValue(key.first)->setKeyValWhitespaces(
				    std::vector<QString>( {"", QString(" ").repeated(nr_ws), " ", " "} ) );
			}
		}
	} //switch
}

/**
 * @brief Perform capitalization related transformations on the local INIParser copy.
 * @param[in] mode Type of transformation.
 */
void PreviewWindow::transformCapitalization(const transform_capitalization &mode)
{
902
903
904
905
906
907
908
	const bool lower = (mode == LOWER_CASE || mode == SECTIONS_LOWER ||
	    mode == KEYS_LOWER || mode == VALUES_LOWER);
	const bool value = (mode == VALUES_UPPER || mode == VALUES_LOWER);
	const bool all = (mode == UPPER_CASE || mode == LOWER_CASE);
	const bool section = (mode == SECTIONS_UPPER || mode == SECTIONS_LOWER);

	for (auto &sec : *preview_ini_.getSections()) {
909
		if (section || all)
910
			sec.setName(lower? sec.getName().toLower() : sec.getName().toUpper());
911
		if (!section || all) {
912
913
			for (auto &key : sec.getKeyValueList()) {
				auto *keyvalue = sec.getKeyValue(key.first);
914
915
916
				if (value || all) {
					keyvalue->setValue(lower? keyvalue->getValue().toLower() :
					    keyvalue->getValue().toUpper());
917
918
				}
				if (!value || all) {
919
920
921
922
923
924
					keyvalue->setKey(lower? keyvalue->getKey().toLower() :
					    keyvalue->getKey().toUpper());
				}
			} //endfor key
		} //endif section
	} //endfor sec
925
926
927
928
929
}

/**
 * @brief Perform transformations concerning INI comments on the local INIParser copy.
 * @param[in] mode Type of transformation.
930
 * @return True if at least one comment prefix was removed.
931
 */
932
bool PreviewWindow::transformComments(const transform_comments &mode)
933
{
934
	bool removed_comment = false;
935
936
937
	if (mode == BLOCK_COMMENT || mode == BLOCK_UNCOMMENT) { //block (un)comment
		int first_line, last_line;
		getSelectionMargins(first_line, last_line); //span of selected lines
938
		QStringList lines( getCurrentEditor()->toPlainText().split("\n") );
939
940
941
942
943
944
945
946
947
948
949
		for (int ii = first_line - 1; ii < last_line; ++ii) {
			if (mode == BLOCK_COMMENT) { //add comment prefix
				lines[ii] = "#" + lines[ii];
			} else { //remove comment prefix
				if (lines.at(ii).trimmed().startsWith("#") ||
				    lines.at(ii).trimmed().startsWith(";")) {
					//find first "#" or ";" and delete:
					int prefix_pos = lines.at(ii).indexOf("#");
					if (prefix_pos == -1)
						prefix_pos = lines.at(ii).indexOf(";");
					lines[ii].remove(prefix_pos, 1);
950
					removed_comment = true;