id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
16,320
Macro.cpp
dail8859_NotepadNext/src/NotepadNext/Macro.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "Macro.h" using namespace Scintilla; Macro::Macro() : name("<Current Recorded Macro>") {} Macro::~Macro() { } void Macro::addMacroStep(Message message, uptr_t wParam, sptr_t lParam) { qInfo(Q_FUNC_INFO); // Combine ReplaceSel messages into a single string if (message == Message::ReplaceSel && !steps.empty() && steps.constLast().message == Message::ReplaceSel) { steps.last().str.append(reinterpret_cast<const char*>(lParam)); } // Combine DeleteBack (backspace) with ReplaceSel else if (message == Message::DeleteBack && !steps.empty() && steps.constLast().message == Message::ReplaceSel) { if (steps.last().str.size() == 1) { // A single char left so just remove the action steps.takeLast(); } else { steps.last().str.chop(1); } } else { steps.append(MacroStep(message, wParam, lParam)); } #ifdef QT_DEBUG for (const MacroStep &step : steps) { qInfo("%s", qUtf8Printable(step.toString())); } #endif } void Macro::addMacroStep(MacroStep step) { steps.append(step); } void Macro::replay(ScintillaNext *editor, int n) const { qInfo(Q_FUNC_INFO); editor->beginUndoAction(); while (n > 0) { for (const MacroStep &step : steps) { step.replay(editor); } --n; } editor->endUndoAction(); } void Macro::replayTillEndOfFile(ScintillaNext *editor) const { qInfo(Q_FUNC_INFO); editor->beginUndoAction(); do { int length = editor->length(); int curPos = editor->currentPos(); replay(editor); // The doc can shrink...yay if (editor->length() < length) { continue; } // The doc can grow... else if(editor->length() > length) { // are we going to catch up? int deltaLength = editor->length() - length; int deltaPos = editor->currentPos() - curPos; if (deltaPos > deltaLength) { // Cursor position is moving forward more than document is growing continue; } } // the file can stay the same else { // is the cursor moving? if (editor->currentPos() != curPos) { continue; } } break; } while (true); editor->endUndoAction(); } QString Macro::getName() const { return name; } void Macro::setName(const QString &value) { name = value; } QDataStream &operator<<(QDataStream& stream, const Macro &macro) { return stream << macro.name << macro.steps; } QDataStream &operator>>(QDataStream& stream, Macro &macro) { return stream >> macro.name >> macro.steps; }
3,490
C++
.cpp
114
24.938596
116
0.630856
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,321
RangeAllocator.cpp
dail8859_NotepadNext/src/NotepadNext/RangeAllocator.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "RangeAllocator.h" RangeAllocator::RangeAllocator(int total) : resource(total) { } void RangeAllocator::disableRange(int start, int end) { resource.fill(true, start, end + 1); } int RangeAllocator::requestResource(const QString name) { // Check to see if this key is allocated yet if (allocation.contains(name)) { return allocation[name]; } for (int i = 0; i < resource.size(); ++i) { if (resource[i] == false) { resource[i] = true; allocation[name] = i; return i; } } Q_ASSERT(false); return -1; }
1,339
C++
.cpp
42
28.02381
73
0.695112
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,322
ScintillaNext.cpp
dail8859_NotepadNext/src/NotepadNext/ScintillaNext.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "ScintillaNext.h" #include "ScintillaCommenter.h" #include "uchardet.h" #include <cinttypes> #include <QDir> #include <QMouseEvent> #include <QSaveFile> #include <QTextCodec> const int CHUNK_SIZE = 1024 * 1024 * 4; // Not sure what is best static QFileDevice::FileError writeToDisk(const QByteArray &data, const QString &path) { qInfo(Q_FUNC_INFO); QFile file(path); if (file.open(QIODevice::WriteOnly)) { if (file.write(data) != -1) { file.close(); return QFileDevice::NoError; } } // If it got to this point there was an error qWarning("writeToDisk() failure code %d: %s", file.error(), qPrintable(file.errorString())); return file.error(); } static bool isNewlineCharacter(char c) { return c == '\n' || c == '\r'; } ScintillaNext::ScintillaNext(QString name, QWidget *parent) : ScintillaEdit(parent), name(name), indicatorResources(INDICATOR_MAX + 1) { // Per the scintilla documentation, some parts of the range are not generally available indicatorResources.disableRange(0, 7); indicatorResources.disableRange(INDICATOR_IME, INDICATOR_IME_MAX); indicatorResources.disableRange(INDICATOR_HISTORY_REVERTED_TO_ORIGIN_INSERTION, INDICATOR_HISTORY_REVERTED_TO_MODIFIED_DELETION); } ScintillaNext::~ScintillaNext() { } ScintillaNext *ScintillaNext::fromFile(const QString &filePath, bool tryToCreate) { QFile file(filePath); ScintillaNext *editor = new ScintillaNext(file.fileName()); if(tryToCreate && !file.exists()) { qInfo("Trying to create %s", qUtf8Printable(filePath)); QDir d; d.mkpath(QFileInfo(file).path()); QFile f(filePath); f.open(QIODevice::WriteOnly); f.close(); } bool readSuccessful = editor->readFromDisk(file); if (!readSuccessful) { delete editor; return Q_NULLPTR; } editor->setFileInfo(filePath); return editor; } int ScintillaNext::allocateIndicator(const QString &name) { return indicatorResources.requestResource(name); } void ScintillaNext::goToRange(const Sci_CharacterRange &range) { qInfo(Q_FUNC_INFO); if (isRangeValid(range)) { // Lines can be folded so make sure they are visible ensureVisible(lineFromPosition(range.cpMin)); ensureVisible(lineFromPosition(range.cpMax)); setSelection(range.cpMin, range.cpMax); scrollRange(range.cpMax, range.cpMin); } } QByteArray ScintillaNext::eolString() const { const int eol = eOLMode(); if (eol == SC_EOL_LF) return QByteArrayLiteral("\n"); else if (eol == SC_EOL_CRLF) return QByteArrayLiteral("\r\n"); else return QByteArrayLiteral("\r"); } bool ScintillaNext::lineIsEmpty(int line) { return (lineEndPosition(line) - positionFromLine(line)) == 0; } void ScintillaNext::deleteLine(int line) { deleteRange(positionFromLine(line), lineLength(line)); } void ScintillaNext::cutAllowLine() { if (selectionEmpty()) { copyAllowLine(); lineDelete(); } else { cut(); } } void ScintillaNext::modifyFoldLevels(int level, int action) { const int totalLines = lineCount(); int line = 0; while (line < totalLines) { int foldFlags = foldLevel(line); // Even though its called fold level it contains several other flags bool isHeader = foldFlags & SC_FOLDLEVELHEADERFLAG; int actualLevel = (foldFlags & SC_FOLDLEVELNUMBERMASK) - SC_FOLDLEVELBASE; if (isHeader && actualLevel == level) { foldLine(line, action); line = lastChild(line, -1) + 1; } else { ++line; } } } void ScintillaNext::foldAllLevels(int level) { modifyFoldLevels(level, SC_FOLDACTION_CONTRACT); } void ScintillaNext::unFoldAllLevels(int level) { modifyFoldLevels(level, SC_FOLDACTION_EXPAND); } void ScintillaNext::deleteLeadingEmptyLines() { while (lineCount() > 1 && lineIsEmpty(0)) { deleteLine(0); } } void ScintillaNext::deleteTrailingEmptyLines() { const int docLength = length(); int position = docLength; while (position > 0 && isNewlineCharacter(charAt(position - 1))) { position--; } deleteRange(position, docLength - position); } bool ScintillaNext::isSavedToDisk() const { return !canSaveToDisk(); } bool ScintillaNext::canSaveToDisk() const { // The buffer can be saved if: // - It is marked as a temporary since as soon as it gets saved it is no longer a temporary buffer // - A modified file // - A missing file since as soon as it is saved it is no longer missing. return temporary || (bufferType == ScintillaNext::New && modify()) || (bufferType == ScintillaNext::File && modify()) || (bufferType == ScintillaNext::FileMissing); } void ScintillaNext::setName(const QString &name) { this->name = name; emit renamed(); } bool ScintillaNext::isFile() const { return bufferType == ScintillaNext::File || bufferType == ScintillaNext::FileMissing; } QFileInfo ScintillaNext::getFileInfo() const { Q_ASSERT(isFile()); return fileInfo; } QString ScintillaNext::getPath() const { Q_ASSERT(isFile()); return QDir::toNativeSeparators(fileInfo.canonicalPath()); } QString ScintillaNext::getFilePath() const { Q_ASSERT(isFile()); return QDir::toNativeSeparators(fileInfo.canonicalFilePath()); } void ScintillaNext::setFoldMarkers(const QString &type) { QMap<QString, QList<int>> map{ {"simple", {SC_MARK_MINUS, SC_MARK_PLUS, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY}}, {"arrow", {SC_MARK_ARROWDOWN, SC_MARK_ARROW, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY}}, {"circle", {SC_MARK_CIRCLEMINUS, SC_MARK_CIRCLEPLUS, SC_MARK_VLINE, SC_MARK_LCORNERCURVE, SC_MARK_CIRCLEPLUSCONNECTED, SC_MARK_CIRCLEMINUSCONNECTED, SC_MARK_TCORNERCURVE }}, {"box", {SC_MARK_BOXMINUS, SC_MARK_BOXPLUS, SC_MARK_VLINE, SC_MARK_LCORNER, SC_MARK_BOXPLUSCONNECTED, SC_MARK_BOXMINUSCONNECTED, SC_MARK_TCORNER }}, }; if (!map.contains(type)) return; const auto types = map[type]; markerDefine(SC_MARKNUM_FOLDEROPEN, types[0]); markerDefine(SC_MARKNUM_FOLDER, types[1]); markerDefine(SC_MARKNUM_FOLDERSUB, types[2]); markerDefine(SC_MARKNUM_FOLDERTAIL, types[3]); markerDefine(SC_MARKNUM_FOLDEREND, types[4]); markerDefine(SC_MARKNUM_FOLDEROPENMID, types[5]); markerDefine(SC_MARKNUM_FOLDERMIDTAIL, types[6]); } void ScintillaNext::close() { emit closed(); deleteLater(); } QFileDevice::FileError ScintillaNext::save() { qInfo(Q_FUNC_INFO); Q_ASSERT(isFile()); emit aboutToSave(); QFileDevice::FileError writeSuccessful = writeToDisk(QByteArray::fromRawData((char*)characterPointer(), textLength()), fileInfo.filePath()); if (writeSuccessful == QFileDevice::NoError) { updateTimestamp(); setSavePoint(); // If this was a temporary file, make sure it is not any more setTemporary(false); emit saved(); } return writeSuccessful; } void ScintillaNext::reload() { Q_ASSERT(isFile()); // Ensure the file still exists. if (!QFile::exists(fileInfo.canonicalFilePath())) { return; } // Remove all the text { const QSignalBlocker blocker(this); setUndoCollection(false); emptyUndoBuffer(); setText(""); setUndoCollection(true); } // NOTE: if the read fails then the buffer will be completely empty...which probably // isn't a good thing, but this should be a rare occurrence. QFile f(fileInfo.canonicalFilePath()); bool readSuccessful = readFromDisk(f); if (readSuccessful) { updateTimestamp(); setSavePoint(); } return; } QFileDevice::FileError ScintillaNext::saveAs(const QString &newFilePath) { bool isRenamed = bufferType == ScintillaNext::New || fileInfo.canonicalFilePath() != newFilePath; emit aboutToSave(); QFileDevice::FileError saveSuccessful = writeToDisk(QByteArray::fromRawData((char*)characterPointer(), textLength()), newFilePath); if (saveSuccessful == QFileDevice::NoError) { setFileInfo(newFilePath); setSavePoint(); // If this was a temporary file, make sure it is not any more setTemporary(false); emit saved(); if (isRenamed) { emit renamed(); } } return saveSuccessful; } QFileDevice::FileError ScintillaNext::saveCopyAs(const QString &filePath) { return writeToDisk(QByteArray::fromRawData((char*)characterPointer(), textLength()), filePath); } bool ScintillaNext::rename(const QString &newFilePath) { emit aboutToSave(); // Write out the buffer to the new path if (saveCopyAs(newFilePath)) { // Remove the old file const QString oldPath = fileInfo.canonicalFilePath(); QFile::remove(oldPath); // Everything worked fine, so update the buffer's info setFileInfo(newFilePath); setSavePoint(); // If this was a temporary file, make sure it is not any more setTemporary(false); emit saved(); emit renamed(); return true; } return false; } ScintillaNext::FileStateChange ScintillaNext::checkFileForStateChange() { if (bufferType == BufferType::New) { return FileStateChange::NoChange; } else if (bufferType == BufferType::File) { // refresh else exists() fails to notice missing file fileInfo.refresh(); if (!fileInfo.exists()) { bufferType = BufferType::FileMissing; emit savePointChanged(false); return FileStateChange::Deleted; } // See if the timestamp changed if (modifiedTime != fileTimestamp()) { return FileStateChange::Modified; } else { return FileStateChange::NoChange; } } else if (bufferType == BufferType::FileMissing) { // See if it reappeared fileInfo.refresh(); if (fileInfo.exists()) { bufferType = BufferType::File; return FileStateChange::Restored; } else { return FileStateChange::NoChange; } } qInfo("type() = %d", bufferType); Q_ASSERT(false); return FileStateChange::NoChange; } bool ScintillaNext::moveToTrash() { if (QFile::exists(fileInfo.canonicalFilePath())) { QFile f(fileInfo.canonicalFilePath()); return f.moveToTrash(); } return false; } void ScintillaNext::toggleCommentSelection() { ScintillaCommenter sc(this); sc.toggleSelection(); } void ScintillaNext::commentLineSelection() { ScintillaCommenter sc(this); sc.commentSelection(); } void ScintillaNext::uncommentLineSelection() { ScintillaCommenter sc(this); sc.uncommentSelection(); } void ScintillaNext::dragEnterEvent(QDragEnterEvent *event) { // Ignore all drag and drop events with urls and let the main application handle it if (event->mimeData()->hasUrls()) { return; } ScintillaEdit::dragEnterEvent(event); } void ScintillaNext::dropEvent(QDropEvent *event) { // Ignore all drag and drop events with urls and let the main application handle it if (event->mimeData()->hasUrls()) { return; } ScintillaEdit::dropEvent(event); } bool ScintillaNext::readFromDisk(QFile &file) { if (!file.exists()) { qWarning("Cannot read \"%s\": doesn't exist", qUtf8Printable(file.fileName())); return false; } if (!file.open(QIODevice::ReadOnly)) { qWarning("QFile::open() failed when opening \"%s\" - error code %d: %s", qUtf8Printable(file.fileName()), file.error(), qUtf8Printable(file.errorString())); return false; } // TODO: figure out what to do if "size" is too big allocate(file.size()); // Turn off undo collection and block signals during loading setUndoCollection(false); blockSignals(true); // TODO disable notifications // modEventMask(SC_MOD_NONE)? QByteArray chunk; qint64 bytesRead; QTextCodec *codec = Q_NULLPTR; QTextCodec::ConverterState state; bool first_read = true; do { // Try to read as much as possible chunk.resize(CHUNK_SIZE); bytesRead = file.read(chunk.data(), CHUNK_SIZE); chunk.resize(bytesRead); qDebug("Read %lld bytes", bytesRead); // TODO: this needs moved out of here. Would make much more sense to have a class (or classes) // responsible for handling low level situations like this to do things like: // - determine encoding // - determine space vs tabs // - determine indentation size if (first_read) { first_read = false; // Search for a BOM mark codec = QTextCodec::codecForUtfText(chunk, Q_NULLPTR); if (codec != Q_NULLPTR) { qDebug("BOM mark found"); } else { qDebug("BOM mark not found, using uchardet"); // Limit decoding to the first 64 kilobytes int detectionSize = qMin(chunk.size(), 64 * 1024); // Use uchardet to try and detect file encoding since no BOM was found uchardet_t encodingDetector = uchardet_new(); if (uchardet_handle_data(encodingDetector, chunk.data(), detectionSize) == 0) { uchardet_data_end(encodingDetector); qDebug("uchardet detected encoding as: '%s'", uchardet_get_charset(encodingDetector)); codec = QTextCodec::codecForName(uchardet_get_charset(encodingDetector)); } else { qDebug("uchardet failure"); } uchardet_delete(encodingDetector); } qDebug("Using codec: '%s'", codec ? codec->name().constData() : ""); } if (codec) { const QByteArray utf8_data = codec->toUnicode(chunk.constData(), chunk.size(), &state).toUtf8(); appendText(utf8_data.size(), utf8_data.constData()); } else { appendText(chunk.size(), chunk.constData()); } } while (!file.atEnd() && status() == SC_STATUS_OK); file.close(); // Restore it back this->blockSignals(false); setUndoCollection(true); // modEventMask(SC_MODEVENTMASKALL)? if (status() != SC_STATUS_OK) { qWarning("something bad happened in document->add_data() %ld", status()); return false; } if (bytesRead == -1) { qWarning("Something bad happened when reading disk %d %s", file.error(), qUtf8Printable(file.errorString())); return false; } if (!QFileInfo(file).isWritable()) { qInfo("Setting file as read-only"); setReadOnly(true); } return true; } QDateTime ScintillaNext::fileTimestamp() { Q_ASSERT(bufferType != ScintillaNext::New); fileInfo.refresh(); qInfo("%s last modified %s", qUtf8Printable(fileInfo.fileName()), qUtf8Printable(fileInfo.lastModified().toString())); return fileInfo.lastModified(); } void ScintillaNext::updateTimestamp() { modifiedTime = fileTimestamp(); } void ScintillaNext::setFileInfo(const QString &filePath) { fileInfo.setFile(filePath); fileInfo.makeAbsolute(); Q_ASSERT(fileInfo.exists()); name = fileInfo.fileName(); bufferType = ScintillaNext::File; updateTimestamp(); } void ScintillaNext::detachFileInfo(const QString &newName) { setName(newName); bufferType = ScintillaNext::New; } void ScintillaNext::setTemporary(bool temp) { temporary = temp; // Fake this signal emit savePointChanged(temporary); }
16,676
C++
.cpp
491
28.173116
181
0.668598
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,323
MacroStep.cpp
dail8859_NotepadNext/src/NotepadNext/MacroStep.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include <QMetaEnum> #include "ScintillaNext.h" #include "MacroStep.h" using namespace Scintilla; QMap<Scintilla::Message, QString> messageData { { Scintilla::Message::Cut, "Cut" }, { Scintilla::Message::Copy, "Copy" }, { Scintilla::Message::Paste, "Paste" }, { Scintilla::Message::Clear, "Clear" }, { Scintilla::Message::ReplaceSel, "Replace Selection" }, //{ Scintilla::Message::AddText, "Add Text" }, //{ Scintilla::Message::InsertText, "Insert Text" }, //{ Scintilla::Message::AppendText, "Append Text" }, { Scintilla::Message::ClearAll, "Clear All" }, { Scintilla::Message::SelectAll, "Select All" }, //{ Scintilla::Message::GotoLine, "GotoLine" }, //{ Scintilla::Message::GotoPos, "GotoPos" }, { Scintilla::Message::SearchAnchor, "Search Anchor" }, { Scintilla::Message::SearchNext, "Search Next" }, { Scintilla::Message::SearchPrev, "Search Prev" }, { Scintilla::Message::LineDown, "Line Down" }, { Scintilla::Message::LineDownExtend, "Line Down Extend" }, { Scintilla::Message::ParaDown, "Para Down" }, { Scintilla::Message::ParaDownExtend, "Para Down Extend" }, { Scintilla::Message::LineUp, "Line Up" }, { Scintilla::Message::LineUpExtend, "Line Up Extend" }, { Scintilla::Message::ParaUp, "Para Up" }, { Scintilla::Message::ParaUpExtend, "Para Up Extend" }, { Scintilla::Message::CharLeft, "Char Left" }, { Scintilla::Message::CharLeftExtend, "Char Left Extend" }, { Scintilla::Message::CharRight, "Char Right" }, { Scintilla::Message::CharRightExtend, "Char Right Extend" }, { Scintilla::Message::WordLeft, "Word Left" }, { Scintilla::Message::WordLeftExtend, "Word Left Extend" }, { Scintilla::Message::WordRight, "WordRight" }, { Scintilla::Message::WordRightExtend, "Word Right Extend" }, { Scintilla::Message::WordPartLeft, "Word Part Left" }, { Scintilla::Message::WordPartLeftExtend, "Word Part Left Extend" }, { Scintilla::Message::WordPartRight, "Word Part Right" }, { Scintilla::Message::WordPartRightExtend, "Word Part Right Extend" }, { Scintilla::Message::WordLeftEnd, "Word Left End" }, { Scintilla::Message::WordLeftEndExtend, "Word Left End Extend" }, { Scintilla::Message::WordRightEnd, "Word Right End" }, { Scintilla::Message::WordRightEndExtend, "Word Right End Extend" }, { Scintilla::Message::Home, "Home" }, { Scintilla::Message::HomeExtend, "Home Extend" }, { Scintilla::Message::LineEnd, "Line End" }, { Scintilla::Message::LineEndExtend, "Line End Extend" }, { Scintilla::Message::HomeWrap, "Home Wrap" }, { Scintilla::Message::HomeWrapExtend, "Home Wrap Extend" }, { Scintilla::Message::LineEndWrap, "Line End Wrap" }, { Scintilla::Message::LineEndWrapExtend, "Line End Wrap Extend" }, { Scintilla::Message::DocumentStart, "Document Start" }, { Scintilla::Message::DocumentStartExtend, "Document Start Extend" }, { Scintilla::Message::DocumentEnd, "Document End" }, { Scintilla::Message::DocumentEndExtend, "Document End Extend" }, //{ Scintilla::Message::StutteredPageUp, "Stuttered Page Up" }, //{ Scintilla::Message::StutteredPageUpExtend, "Stuttered Page Up Extend" }, //{ Scintilla::Message::StutteredPageDown, "Stuttered Page Down" }, //{ Scintilla::Message::StutteredPageDownExtend, "Stuttered Page Down Extend" }, { Scintilla::Message::PageUp, "Page Up" }, { Scintilla::Message::PageUpExtend, "Page Up Extend" }, { Scintilla::Message::PageDown, "Page Down" }, { Scintilla::Message::PageDownExtend, "Page Down Extend" }, { Scintilla::Message::EditToggleOvertype, "Edit Toggle Overtype" }, { Scintilla::Message::Cancel, "Cancel" }, { Scintilla::Message::DeleteBack, "Delete Back" }, { Scintilla::Message::Tab, "Tab" }, { Scintilla::Message::BackTab, "Back Tab" }, { Scintilla::Message::FormFeed, "Form Feed" }, { Scintilla::Message::VCHome, "VC Home" }, { Scintilla::Message::VCHomeExtend, "VC Home Extend" }, { Scintilla::Message::VCHomeWrap, "VC Home Wrap" }, { Scintilla::Message::VCHomeWrapExtend, "VC Home Wrap Extend" }, { Scintilla::Message::VCHomeDisplay, "VCHome Display" }, { Scintilla::Message::VCHomeDisplayExtend, "VC Home Display Extend" }, { Scintilla::Message::DelWordLeft, "Delete Word Left" }, { Scintilla::Message::DelWordRight, "Delete Word Right" }, { Scintilla::Message::DelWordRightEnd, "Delete Word Right End" }, { Scintilla::Message::DelLineLeft, "Delete Line Left" }, { Scintilla::Message::DelLineRight, "Delete Line Right" }, { Scintilla::Message::LineCopy, "Line Copy" }, { Scintilla::Message::LineCut, "Line Cut" }, { Scintilla::Message::LineDelete, "Line Delete" }, { Scintilla::Message::LineTranspose, "Line Transpose" }, { Scintilla::Message::LineReverse, "Line Reverse" }, { Scintilla::Message::LineDuplicate, "Line Duplicate" }, { Scintilla::Message::LowerCase, "Lower Case" }, { Scintilla::Message::UpperCase, "Upper Case" }, { Scintilla::Message::LineScrollDown, "Line Scroll Down" }, { Scintilla::Message::LineScrollUp, "Line Scroll Up" }, { Scintilla::Message::DeleteBackNotLine, "Delete Back Not Line" }, { Scintilla::Message::HomeDisplay, "Home Display" }, { Scintilla::Message::HomeDisplayExtend, "Home Display Extend" }, { Scintilla::Message::LineEndDisplay, "Line End Display" }, { Scintilla::Message::LineEndDisplayExtend, "Line End Display Extend" }, //{ Scintilla::Message::SetSelectionMode, "Set Selection Mode" }, { Scintilla::Message::LineDownRectExtend, "Line Down Rect Extend" }, { Scintilla::Message::LineUpRectExtend, "Line Up Rect Extend" }, { Scintilla::Message::CharLeftRectExtend, "Char Left Rect Extend" }, { Scintilla::Message::CharRightRectExtend, "Char Right Rect Extend" }, { Scintilla::Message::HomeRectExtend, "Home Rect Extend" }, { Scintilla::Message::VCHomeRectExtend, "VC Home Rect Extend" }, { Scintilla::Message::LineEndRectExtend, "Line End Rect Extend" }, { Scintilla::Message::PageUpRectExtend, "Page Up Rect Extend" }, { Scintilla::Message::PageDownRectExtend, "Page Down Rect Extend" }, { Scintilla::Message::SelectionDuplicate, "Selection Duplicate" }, { Scintilla::Message::CopyAllowLine, "Copy Allow Line" }, { Scintilla::Message::VerticalCentreCaret, "Vertical Centre Caret" }, { Scintilla::Message::MoveSelectedLinesUp, "Move Selected Lines Up" }, { Scintilla::Message::MoveSelectedLinesDown, "Move Selected Lines Down" }, { Scintilla::Message::ScrollToStart, "Scroll To Start" }, { Scintilla::Message::ScrollToEnd, "Scroll To End" } }; MacroStep::MacroStep(Message message, uptr_t wParam, sptr_t lParam) : message(message), wParam(wParam) { if (message == Message::ReplaceSel || message == Message::InsertText) { // wParam is 0 for replace, and position for insert this->str = QByteArray(reinterpret_cast<const char*>(lParam)); } else if (message == Message::AddText || message == Message::AppendText) { // wParam is length of text this->str = QByteArray(reinterpret_cast<const char*>(lParam), wParam); } else { this->lParam = lParam; } } MacroStep::~MacroStep() { } QString MacroStep::toString() const { if (MacroStep::MessageHasString(message)) { return QString("MacroStep(%1, %2, \"%3\")") .arg(getName()) .arg(wParam) .arg(str.constData()); } else { return QString("MacroStep(%1, %2, %3)") .arg(getName()) .arg(wParam) .arg(lParam); } } QString MacroStep::getName() const { return MacroStep::NameOfMessage(message); } void MacroStep::replay(ScintillaNext *editor) const { if (MacroStep::MessageHasString(message)) { editor->sends(static_cast<int>(message), wParam, str.constBegin()); } else { editor->send(static_cast<int>(message), wParam, lParam); } } bool MacroStep::MessageHasString(Scintilla::Message message) { return message == Message::ReplaceSel || message == Message::InsertText || message == Message::AddText || message == Message::AppendText; } QString MacroStep::NameOfMessage(Scintilla::Message message) { // Try to find the name in the known list if (messageData.contains(message)) { return messageData[message]; } else { // Default to the list of enums QMetaEnum metaEnum = QMetaEnum::fromType<ScintillaNext::Message>(); return metaEnum.valueToKey(static_cast<int>(message)); } } QList<Message> MacroStep::RecordableMacroMessages() { return messageData.keys(); } QDataStream &operator<<(QDataStream& stream, const MacroStep &macroStep) { // NOTE: Need to force the wParam and lParam into 32 bits due to Scintilla defining // them differently on different systems. stream << macroStep.message << static_cast<quint32>(macroStep.wParam); if (MacroStep::MessageHasString(macroStep.message)) return stream << macroStep.str; else return stream << static_cast<qint32>(macroStep.lParam); } QDataStream &operator>>(QDataStream& stream, MacroStep &macroStep) { // NOTE: Need to force the wParam and lParam into 32 bits due to Scintilla defining // them differently on different systems. quint32 w; qint32 l; stream >> macroStep.message >> w; macroStep.wParam = static_cast<quint32>(w); if (MacroStep::MessageHasString(macroStep.message)) return stream >> macroStep.str; else { stream >> l; macroStep.lParam = static_cast<qint32>(l); return stream; } }
10,504
C++
.cpp
227
41.281938
87
0.681911
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,324
MacroRecorder.cpp
dail8859_NotepadNext/src/NotepadNext/MacroRecorder.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "MacroRecorder.h" #include "ScintillaNext.h" #include <QMetaEnum> using namespace Scintilla; MacroRecorder::MacroRecorder(QObject *parent) : QObject(parent) { } void MacroRecorder::startRecording(ScintillaNext *editor) { this->editor = editor; connect(editor, &ScintillaNext::macroRecord, this, &MacroRecorder::recordMacroStep); // We don't "own" the macro so don't delete it if it is a valid pointer macro = new Macro(); editor->startRecord(); } Macro *MacroRecorder::stopRecording() { disconnect(editor, &ScintillaNext::macroRecord, this, &MacroRecorder::recordMacroStep); editor->stopRecord(); Macro *m = macro; macro = Q_NULLPTR; return m; } void MacroRecorder::recordMacroStep(Message message, uptr_t wParam, sptr_t lParam) { qInfo(Q_FUNC_INFO); macro->addMacroStep(message, wParam, lParam); }
1,600
C++
.cpp
46
32.021739
91
0.749513
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,325
MacroStepTableModel.cpp
dail8859_NotepadNext/src/NotepadNext/MacroStepTableModel.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "MacroStepTableModel.h" MacroStepTableModel::MacroStepTableModel(Macro *m, QObject *parent) : QAbstractTableModel(parent), macro(m) { } QVariant MacroStepTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole) { if (orientation == Qt::Horizontal) { if (section == 0) return tr("Name"); else if (section == 1) return tr("Text"); } } return QVariant(); } int MacroStepTableModel::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : macro->getSteps().size(); } int MacroStepTableModel::columnCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : 2; } QVariant MacroStepTableModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::ToolTipRole) { switch (index.column()) { case 0: if (role == Qt::EditRole) { return static_cast<int>(macro->getSteps()[index.row()].message); } else { return macro->getSteps()[index.row()].getName(); } case 1: return macro->getSteps()[index.row()].str; default: break; } } return QVariant(); } bool MacroStepTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid()) return false; if (role == Qt::EditRole) { switch (index.column()) { case 0: { Scintilla::Message newMessage = static_cast<Scintilla::Message>(value.toInt()); MacroStep &m = macro->getSteps()[index.row()]; m.message = newMessage; if (!MacroStep::MessageHasString(newMessage)) { m.str.clear(); } emit dataChanged(index, index, QVector<int>() << role); return true; } case 1: macro->getSteps()[index.row()].str = value.toString().toUtf8(); emit dataChanged(index, index, QVector<int>() << role); return true; default: break; } } return false; } bool MacroStepTableModel::insertRows(int row, int count, const QModelIndex &parent) { if (count < 1 || row < 0 || row > rowCount(parent)) return false; beginInsertRows(QModelIndex(), row, row + count - 1); for (int r = 0; r < count; ++r) { macro->getSteps().insert(row, MacroStep(Scintilla::Message::ReplaceSel, 0, 0)); } endInsertRows(); return true; } bool MacroStepTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); beginRemoveRows(QModelIndex(), row, row + count - 1); macro->getSteps().remove(row, count); endRemoveRows(); return true; } bool MacroStepTableModel::moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild) { // Source code for this has been copied from QStringListModel::moveRows() if (sourceRow < 0 || sourceRow + count - 1 >= rowCount(sourceParent) || destinationChild <= 0 || destinationChild > rowCount(destinationParent) || sourceRow == destinationChild - 1 || count <= 0) { return false; } if (!beginMoveRows(QModelIndex(), sourceRow, sourceRow + count - 1, QModelIndex(), destinationChild)) return false; /* QList::move assumes that the second argument is the index where the item will end up to i.e. the valid range for that argument is from 0 to QList::size()-1 QAbstractItemModel::moveRows when source and destinations have the same parent assumes that the item will end up being in the row BEFORE the one indicated by destinationChild i.e. the valid range for that argument is from 1 to QList::size() For this reason we remove 1 from destinationChild when using it inside QList */ destinationChild--; const int fromRow = destinationChild < sourceRow ? (sourceRow + count - 1) : sourceRow; while (count--) macro->getSteps().move(fromRow, destinationChild); endMoveRows(); return true; } Qt::ItemFlags MacroStepTableModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::NoItemFlags; if (index.column() == 0) { return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable; } else if (index.column() == 1 && MacroStep::MessageHasString(macro->getSteps()[index.row()].message)) { // The second column is only editable if the macro has a string associated with it return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable; } else { return Qt::ItemIsEnabled; } }
5,786
C++
.cpp
152
30.881579
153
0.635681
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,326
EditorManager.cpp
dail8859_NotepadNext/src/NotepadNext/EditorManager.cpp
/* * This file is part of Notepad Next. * Copyright 2021 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include <QApplication> #include "ApplicationSettings.h" #include "EditorManager.h" #include "ScintillaNext.h" #include "Scintilla.h" // Editor decorators #include "BraceMatch.h" #include "HighlightedScrollBar.h" #include "SmartHighlighter.h" #include "SurroundSelection.h" #include "LineNumbers.h" #include "BetterMultiSelection.h" #include "AutoIndentation.h" #include "AutoCompletion.h" #include "URLFinder.h" #include "BookMarkDecorator.h" const int MARK_HIDELINESBEGIN = 23; const int MARK_HIDELINESEND = 22; const int MARK_HIDELINESUNDERLINE = 21; EditorManager::EditorManager(ApplicationSettings *settings, QObject *parent) : QObject(parent), settings(settings) { connect(this, &EditorManager::editorCreated, this, [=](ScintillaNext *editor) { connect(editor, &ScintillaNext::closed, this, [=]() { emit editorClosed(editor); }); }); connect(settings, &ApplicationSettings::showWrapSymbolChanged, this, [=](bool b) { for (auto &editor : getEditors()) { editor->setWrapVisualFlags(b ? SC_WRAPVISUALFLAG_END : SC_WRAPVISUALFLAG_NONE); } }); connect(settings, &ApplicationSettings::showWhitespaceChanged, this, [=](bool b) { // TODO: could make SCWS_VISIBLEALWAYS configurable via settings. Probably not worth // taking up menu space e.g. show all, show leading, show trailing for (auto &editor : getEditors()) { editor->setViewWS(b ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE); } }); connect(settings, &ApplicationSettings::showEndOfLineChanged, this, [=](bool b) { for (auto &editor : getEditors()) { editor->setViewEOL(b); } }); connect(settings, &ApplicationSettings::showIndentGuideChanged, this, [=](bool b) { for (auto &editor : getEditors()) { editor->setIndentationGuides(b ? SC_IV_LOOKBOTH : SC_IV_NONE); } }); connect(settings, &ApplicationSettings::wordWrapChanged, this, [=](bool b) { if (b) { for (auto &editor : getEditors()) { editor->setWrapMode(SC_WRAP_WORD); } } else { for (auto &editor : getEditors()) { // Store the top line and restore it after the lines have been unwrapped int topLine = editor->docLineFromVisible(editor->firstVisibleLine()); editor->setWrapMode(SC_WRAP_NONE); editor->setFirstVisibleLine(topLine); } } }); connect(settings, &ApplicationSettings::fontNameChanged, this, [=](QString fontName){ for (auto &editor : getEditors()) { for (int i = 0; i <= STYLE_MAX; ++i) { editor->styleSetFont(i, fontName.toUtf8().data()); } } }); connect(settings, &ApplicationSettings::fontSizeChanged, this, [=](int fontSize){ for (auto &editor : getEditors()) { for (int i = 0; i <= STYLE_MAX; ++i) { editor->styleSetSize(i, fontSize); } } }); } ScintillaNext *EditorManager::createEditor(const QString &name) { ScintillaNext *editor = new ScintillaNext(name); manageEditor(editor); return editor; } ScintillaNext *EditorManager::createEditorFromFile(const QString &filePath, bool tryToCreate) { ScintillaNext *editor = ScintillaNext::fromFile(filePath, tryToCreate); if (editor) { manageEditor(editor); } return editor; } ScintillaNext *EditorManager::getEditorByFilePath(const QString &filePath) { QFileInfo newInfo(filePath); newInfo.makeAbsolute(); purgeOldEditorPointers(); for (ScintillaNext *editor : qAsConst(editors)) { if (editor->isFile() && editor->getFileInfo() == newInfo) { return editor; } } return Q_NULLPTR; } void EditorManager::manageEditor(ScintillaNext *editor) { editors.append(QPointer<ScintillaNext>(editor)); setupEditor(editor); emit editorCreated(editor); } void EditorManager::setupEditor(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); editor->clearCmdKey(SCK_INSERT); editor->setFoldMarkers(QStringLiteral("box")); for (int i = SC_MARKNUM_FOLDEREND; i <= SC_MARKNUM_FOLDEROPEN; ++i) { editor->markerSetFore(i, 0xF3F3F3); editor->markerSetBack(i, 0x808080); editor->markerSetBackSelected(i, 0x0000FF); } editor->setIdleStyling(SC_IDLESTYLING_TOVISIBLE); editor->setEndAtLastLine(false); editor->setMultipleSelection(true); editor->setAdditionalSelectionTyping(true); editor->setMultiPaste(SC_MULTIPASTE_EACH); editor->setVirtualSpaceOptions(SCVS_RECTANGULARSELECTION); editor->setMarginLeft(2); editor->setMarginWidthN(0, 30); editor->setMarginMaskN(1, (1<<MARK_HIDELINESBEGIN) | (1<<MARK_HIDELINESEND) | (1<<MARK_HIDELINESUNDERLINE)); editor->setMarginMaskN(2, SC_MASK_FOLDERS); editor->setMarginWidthN(2, 14); editor->markerDefine(MARK_HIDELINESUNDERLINE, SC_MARK_UNDERLINE); editor->markerSetBack(MARK_HIDELINESUNDERLINE, 0x77CC77); editor->markerDefine(MARK_HIDELINESBEGIN, SC_MARK_ARROW); editor->markerDefine(MARK_HIDELINESEND, SC_MARK_ARROWDOWN); editor->setMarginSensitiveN(2, true); editor->setFoldFlags(SC_FOLDFLAG_LINEAFTER_CONTRACTED); editor->setScrollWidthTracking(true); editor->setScrollWidth(1); editor->setTabDrawMode(SCTD_STRIKEOUT); editor->setTabWidth(4); editor->setBackSpaceUnIndents(true); editor->setCaretLineVisible(true); editor->setCaretLineVisibleAlways(true); editor->setCaretWidth(2); editor->setEdgeColour(0x80FFFF); // https://www.scintilla.org/ScintillaDoc.html#ElementColours // SC_ELEMENT_SELECTION_TEXT // SC_ELEMENT_SELECTION_BACK // SC_ELEMENT_SELECTION_ADDITIONAL_TEXT // SC_ELEMENT_SELECTION_ADDITIONAL_BACK // SC_ELEMENT_SELECTION_SECONDARY_TEXT // SC_ELEMENT_SELECTION_SECONDARY_BACK // SC_ELEMENT_SELECTION_INACTIVE_TEXT editor->setElementColour(SC_ELEMENT_SELECTION_INACTIVE_BACK, 0xFFE0E0E0); // SC_ELEMENT_CARET // SC_ELEMENT_CARET_ADDITIONAL editor->setElementColour(SC_ELEMENT_CARET_LINE_BACK, 0xFFFFE8E8); editor->setElementColour(SC_ELEMENT_WHITE_SPACE, 0xFFD0D0D0); // SC_ELEMENT_WHITE_SPACE_BACK // SC_ELEMENT_HOT_SPOT_ACTIVE // SC_ELEMENT_HOT_SPOT_ACTIVE_BACK editor->setElementColour(SC_ELEMENT_FOLD_LINE, 0xFFA0A0A0); // SC_ELEMENT_HIDDEN_LINE editor->setWhitespaceSize(2); editor->setFoldMarginColour(true, 0xFFFFFF); editor->setFoldMarginHiColour(true, 0xE9E9E9); editor->setAutomaticFold(SC_AUTOMATICFOLD_SHOW | SC_AUTOMATICFOLD_CLICK | SC_AUTOMATICFOLD_CHANGE); editor->markerEnableHighlight(true); editor->setCharsDefault(); editor->setWordChars(editor->wordChars() + settings->additionalWordChars().toLatin1()); editor->styleSetFore(STYLE_DEFAULT, 0x000000); editor->styleSetBack(STYLE_DEFAULT, 0xFFFFFF); editor->styleSetSize(STYLE_DEFAULT, settings->fontSize()); editor->styleSetFont(STYLE_DEFAULT, settings->fontName().toUtf8().data()); editor->styleClearAll(); editor->styleSetFore(STYLE_LINENUMBER, 0x808080); editor->styleSetBack(STYLE_LINENUMBER, 0xE4E4E4); editor->styleSetBold(STYLE_LINENUMBER, false); editor->styleSetFore(STYLE_BRACELIGHT, 0x0000FF); editor->styleSetBack(STYLE_BRACELIGHT, 0xFFFFFF); editor->styleSetFore(STYLE_BRACEBAD, 0x000080); editor->styleSetBack(STYLE_BRACEBAD, 0xFFFFFF); editor->styleSetFore(STYLE_INDENTGUIDE, 0xC0C0C0); editor->styleSetBack(STYLE_INDENTGUIDE, 0xFFFFFF); // STYLE_CONTROLCHAR // STYLE_CALLTIP // STYLE_FOLDDISPLAYTEXT editor->setViewWS(settings->showWhitespace() ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE); editor->setViewEOL(settings->showEndOfLine()); editor->setWrapVisualFlags(settings->showWrapSymbol() ? SC_WRAPVISUALFLAG_END : SC_WRAPVISUALFLAG_NONE); editor->setIndentationGuides(settings->showIndentGuide() ? SC_IV_LOOKBOTH : SC_IV_NONE); editor->setWrapMode(settings->wordWrap() ? SC_WRAP_WORD : SC_WRAP_NONE); // Decorators SmartHighlighter *s = new SmartHighlighter(editor); s->setEnabled(true); HighlightedScrollBarDecorator *h = new HighlightedScrollBarDecorator(editor); h->setEnabled(true); BraceMatch *b = new BraceMatch(editor); b->setEnabled(true); LineNumbers *l = new LineNumbers(editor); l->setEnabled(true); SurroundSelection *ss = new SurroundSelection(editor); ss->setEnabled(true); BetterMultiSelection *bms = new BetterMultiSelection(editor); bms->setEnabled(true); AutoIndentation *ai = new AutoIndentation(editor); ai->setEnabled(true); AutoCompletion *ac = new AutoCompletion(editor); ac->setEnabled(true); URLFinder *uf = new URLFinder(editor); uf->setEnabled(true); BookMarkDecorator *bm = new BookMarkDecorator(editor); bm->setEnabled(true); } void EditorManager::purgeOldEditorPointers() { QMutableListIterator<QPointer<ScintillaNext>> it(editors); while (it.hasNext()) { QPointer<ScintillaNext> pointer = it.next(); if (pointer.isNull()) it.remove(); } } QList<QPointer<ScintillaNext> > EditorManager::getEditors() { purgeOldEditorPointers(); return editors; }
10,117
C++
.cpp
247
35.311741
112
0.705672
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,327
LanguageStylesModel.cpp
dail8859_NotepadNext/src/NotepadNext/LanguageStylesModel.cpp
/* * This file is part of Notepad Next. * Copyright 2021 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "LanguageStylesModel.h" #include "ScintillaNext.h" #include "ComboBoxDelegate.h" static inline QRgb convert_color(QRgb c) { const int red = qRed(c); const int green = qGreen(c); const int blue = qBlue(c); return qRgb(blue, green, red); } QList<ComboBoxItem> caseItems{ {"SC_CASE_MIXED", SC_CASE_MIXED}, {"SC_CASE_UPPER", SC_CASE_UPPER}, {"SC_CASE_LOWER", SC_CASE_LOWER}, {"SC_CASE_CAMEL", SC_CASE_CAMEL} }; QString val_to_case_str(int val) { for (const ComboBoxItem &item : caseItems) { if (item.second == val) { return item.first; } } return QString(); } QStringList columns{ "ID", "Name", "Tags", "Description", "Font", "Size", "Fractional", "Bold", "Weight", "Italic", "Underline", "Fore", "Back", "EOL Filled", "Character Set", "Case", "Visible", "Changeable", "Hotspot", }; LanguageStylesModel::LanguageStylesModel(ScintillaNext *editor, QObject *parent) : QAbstractTableModel(parent), editor(editor) { } QVariant LanguageStylesModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole) { if (orientation == Qt::Horizontal) { return columns[section]; } } return QVariant(); } int LanguageStylesModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return editor->namedStyles(); } int LanguageStylesModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return columns.size(); } QVariant LanguageStylesModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role == Qt::DisplayRole || role == Qt::ToolTipRole || role == Qt::EditRole) { switch (index.column()) { case 0: // ID return QString::number(index.row()); case 1: // Name return editor->nameOfStyle(index.row()); case 2: // Tags return editor->tagsOfStyle(index.row()); case 3: // Description return editor->descriptionOfStyle(index.row()); case 4: // Font return editor->styleFont(index.row()); case 5: // Size return (int)editor->styleSize(index.row()); case 6: // Fractional return (int)editor->styleSizeFractional(index.row()); case 7: // Bold if (role == Qt::EditRole) return editor->styleBold(index.row()); else return editor->styleBold(index.row()) ? "True" : "False"; case 8: // Weight return (int)editor->styleWeight(index.row()); case 9: // Italic if (role == Qt::EditRole) return editor->styleItalic(index.row()); else return editor->styleItalic(index.row()) ? "True" : "False"; case 10: // Underline if (role == Qt::EditRole) return editor->styleUnderline(index.row()); else return editor->styleUnderline(index.row()) ? "True" : "False"; case 11: // Fore return QColor(convert_color(editor->styleFore(index.row()))); case 12: // Back return QColor(convert_color(editor->styleBack(index.row()))); case 13: // EOL Filled if (role == Qt::EditRole) return editor->styleEOLFilled(index.row()); else return editor->styleEOLFilled(index.row()) ? "True" : "False"; case 14: // Character Set return (int)editor->styleCharacterSet(index.row()); case 15: // Case if (role == Qt::EditRole) return (int)editor->styleCase(index.row()); else return val_to_case_str(editor->styleCase(index.row())); case 16: // Visible if (role == Qt::EditRole) return editor->styleVisible(index.row()); else return editor->styleVisible(index.row()) ? "True" : "False"; case 17: // Changeable if (role == Qt::EditRole) return editor->styleChangeable(index.row()); else return editor->styleChangeable(index.row()) ? "True" : "False"; case 18: // Hotspot if (role == Qt::EditRole) return editor->styleHotSpot(index.row()); else return editor->styleHotSpot(index.row()) ? "True" : "False"; default: break; } } else if (role == Qt::TextAlignmentRole) { switch (index.column()) { case 0: case 5: case 6: case 8: return Qt::AlignCenter; } } else if (role == Qt::DecorationRole) { if (index.column() == 11) { return QColor(convert_color(editor->styleFore(index.row()))); } else if (index.column() == 12) { return QColor(convert_color(editor->styleBack(index.row()))); } } return QVariant(); } bool LanguageStylesModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid()) return false; if (role == Qt::EditRole) { switch (index.column()) { case 4: // Font editor->styleSetFont(index.row(), value.toString().toLatin1().constData()); break; case 5: // Size editor->styleSetSize(index.row(), value.toInt()); break; case 6: // Fractional editor->styleSetSizeFractional(index.row(), value.toInt()); break; case 7: // Bold editor->styleSetBold(index.row(), value.toBool()); break; case 8: // Weight editor->styleSetWeight(index.row(), value.toInt()); break; case 9: // Italic editor->styleSetItalic(index.row(), value.toBool()); break; case 10: // Underline editor->styleSetUnderline(index.row(), value.toBool()); break; case 11: // Fore editor->styleSetFore(index.row(), convert_color(value.value<QColor>().rgb())); break; case 12: // Back editor->styleSetBack(index.row(), convert_color(value.value<QColor>().rgb())); break; case 13: // EOL Filled editor->styleSetEOLFilled(index.row(), value.toBool()); break; case 15: // Case editor->styleSetCase(index.row(), value.toInt()); break; case 16: // Visible editor->styleSetVisible(index.row(), value.toBool()); break; case 17: // Changeable editor->styleSetChangeable(index.row(), value.toBool()); break; case 18: // Hotspot editor->styleSetHotSpot(index.row(), value.toBool()); break; default: return false; } editor->colourise(0, -1); emit dataChanged(index, index, QVector<int>() << role); return true; } return false; } Qt::ItemFlags LanguageStylesModel::flags(const QModelIndex &index) const { const Qt::ItemFlags default_flags = Qt::ItemIsSelectable | Qt::ItemIsEnabled; if (!index.isValid()) return Qt::NoItemFlags; switch (index.column()) { case 4: // Font case 5: // Size case 6: // Fractional case 7: // Bold case 8: // Weight case 9: // Italic case 10: // Underline case 11: // Fore case 12: // Back case 13: // EOL Filled case 15: // Case case 16: // Visible case 17: // Changeable case 18: // Hotspot return default_flags | Qt::ItemIsEditable; } return default_flags; }
8,778
C++
.cpp
242
26.979339
98
0.564579
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,328
HtmlConverter.cpp
dail8859_NotepadNext/src/NotepadNext/HtmlConverter.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "HtmlConverter.h" #include <QSet> #include <QTextStream> static QByteArray ScintillaColorToCssColor(int color) { int r = color & 0xFF; int g = (color >> 8) & 0xFF; int b = (color >> 16) & 0xFF; return QStringLiteral("rgb(%1, %2, %3)").arg(r).arg(g).arg(b).toLatin1(); } static void StyleToCss(QTextStream &stream, ScintillaNext *editor, int style) { stream << ".s" << style << " {" << Qt::endl; stream << " font-family: '" << editor->styleFont(style) << "';" << Qt::endl; stream << " font-size: " << editor->styleSize(style) << "pt;" << Qt::endl; stream << " color: " << ScintillaColorToCssColor(editor->styleFore(style)) << ";" << Qt::endl; stream << " background: " << ScintillaColorToCssColor(editor->styleBack(style)) << ";" << Qt::endl; if (editor->styleBold(style)) stream << " font-weight: bold;" << Qt::endl; if (editor->styleItalic(style)) stream << " font-style: italic;" << Qt::endl; if (editor->styleUnderline(style)) stream << " text-decoration: underline;" << Qt::endl; stream << "}" << Qt::endl; } static void AddCharEscaped(QTextStream &stream, int ch) { switch (ch) { case '<': stream << QByteArrayLiteral("&lt;"); break; case '>': stream << QByteArrayLiteral("&gt;"); break; case '&': stream << QByteArrayLiteral("&amp;"); break; default: stream << static_cast<char>(ch); } } void HtmlConverter::convertRange(QTextStream &stream, int start, int end) { ensureDocumentStyled(start, end); // Create the raw html and keep track of the used styles QByteArray html; QTextStream html_stream(&html); QSet<int> usedStyles; int currentStyle = -1; for (int i = start; i < end; ++i) { int style = editor->styleAt(i); if (style != currentStyle) { currentStyle = style; usedStyles.insert(currentStyle); html_stream << "</span><span class=\"s" << currentStyle << "\">"; } const int ch = editor->charAt(i); if (ch == '\r'){ if (editor->charAt(i + 1) != '\n') { AddCharEscaped(html_stream, ch); } } else { AddCharEscaped(html_stream, ch); } } html_stream.flush(); // Generate the CSS for just the styles that were used QByteArray css; QTextStream css_stream(&css); for (const int style : usedStyles) { StyleToCss(css_stream, editor, style); } css_stream.flush(); // Generate the entire document stream << "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd\">" << Qt::endl; stream << "<html>" << Qt::endl; stream << "<head>" << Qt::endl; stream << "<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">" << Qt::endl; stream << "<title>Exported from Notepad Next</title>" << Qt::endl; stream << "<!--StartFragment-->" << Qt::endl; stream << "<style type=\"text/css\">" << Qt::endl; stream << "div.main {" << Qt::endl; stream << " white-space: pre;" << Qt::endl; stream << " line-height: 1;" << Qt::endl; stream << "}" << Qt::endl; stream << css; stream << "</style>" << Qt::endl; stream << "</head>" << Qt::endl; stream << "<body>" << Qt::endl; stream << "<div class=\"main\">"; stream << html; stream << "</div>" << Qt::endl; stream << "</body>" << Qt::endl; stream << "<!--EndFragment-->" << Qt::endl; stream << "</html>" << Qt::endl; stream.flush(); }
4,365
C++
.cpp
115
32.556522
143
0.599574
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,329
RecentFilesListMenuBuilder.cpp
dail8859_NotepadNext/src/NotepadNext/RecentFilesListMenuBuilder.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "RecentFilesListMenuBuilder.h" #include <QAction> #include <QMenu> #include <QDir> RecentFilesListMenuBuilder::RecentFilesListMenuBuilder(RecentFilesListManager *manager) : QObject(manager), manager(manager) { } void RecentFilesListMenuBuilder::populateMenu(QMenu *menu) { int i = 0; QList<QAction *> recentFileListActions; for (const QString &file : manager->fileList()) { ++i; QAction *action = new QAction(QString("%1%2: %3").arg(i < 10 ? "&" : "").arg(i).arg(QDir::toNativeSeparators(file)), menu); action->setData(file); connect(action, &QAction::triggered, this, &RecentFilesListMenuBuilder::recentFileActionTriggered); recentFileListActions.append(action); } menu->addActions(recentFileListActions); } void RecentFilesListMenuBuilder::recentFileActionTriggered() { qInfo(Q_FUNC_INFO); const QAction *action = qobject_cast<const QAction *>(sender()); emit fileOpenRequest(action->data().toString()); }
1,735
C++
.cpp
45
35.177778
131
0.73913
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,330
MacroListModel.cpp
dail8859_NotepadNext/src/NotepadNext/MacroListModel.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "MacroListModel.h" MacroListModel::MacroListModel(QObject *parent, MacroManager *mm) : QAbstractListModel(parent), macroManager(mm) { } int MacroListModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return macroManager->availableMacros().size(); } QVariant MacroListModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role == Qt::DisplayRole || role == Qt::ToolTipRole) { return macroManager->availableMacros()[index.row()]->getName(); } return QVariant(); } bool MacroListModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); beginRemoveRows(QModelIndex(), row, row + count - 1); while (count--) { delete macroManager->availableMacros().takeAt(row); } endRemoveRows(); return true; } bool MacroListModel::insertRows(int row, int count, const QModelIndex &parent) { if (count < 1 || row < 0 || row > rowCount(parent)) return false; beginInsertRows(QModelIndex(), row, row + count - 1); for (int r = 0; r < count; ++r) { macroManager->availableMacros().insert(row, new Macro()); } endInsertRows(); return true; } Macro *MacroListModel::macro(const QModelIndex &index) { if (index.isValid()) return macroManager->availableMacros()[index.row()]; else return Q_NULLPTR; }
2,184
C++
.cpp
66
29.318182
78
0.706051
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,331
RecentFilesListManager.cpp
dail8859_NotepadNext/src/NotepadNext/RecentFilesListManager.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "RecentFilesListManager.h" RecentFilesListManager::RecentFilesListManager(QObject *parent) : QObject(parent) { } void RecentFilesListManager::addFile(const QString &filePath) { qInfo(Q_FUNC_INFO); // Attempt to remove it first to make sure it is not added twice removeFile(filePath); // Set a limit on how many can be in the list if (recentFiles.size() >= 10) { recentFiles.removeLast(); } recentFiles.prepend(filePath); } void RecentFilesListManager::removeFile(const QString &filePath) { recentFiles.removeOne(filePath); } void RecentFilesListManager::clear() { // Clear the file list recentFiles.clear(); } QString RecentFilesListManager::mostRecentFile() const { Q_ASSERT(!recentFiles.empty()); return recentFiles.first(); } QStringList RecentFilesListManager::fileList() const { return recentFiles; } void RecentFilesListManager::setFileList(const QStringList &list) { clear(); recentFiles.append(list); }
1,732
C++
.cpp
56
28.125
73
0.755863
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,332
SelectionTracker.cpp
dail8859_NotepadNext/src/NotepadNext/SelectionTracker.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "SelectionTracker.h" #include "ScintillaNext.h" SelectionTracker::SelectionTracker(ScintillaNext *editor) : editor(editor) { saveSelection(); } SelectionTracker::~SelectionTracker() { restoreSelection(); } void SelectionTracker::saveSelection() { caret = editor->selectionNCaret(editor->mainSelection()); anchor = editor->selectionNAnchor(editor->mainSelection()); } void SelectionTracker::restoreSelection() { editor->setSelection(caret, anchor); } void SelectionTracker::trackInsertion(int pos, int length) { if (caret >= pos) { caret += length; } if (anchor >=pos) { anchor += length; } } void SelectionTracker::trackDeletion(int pos, int length) { // Adjust the caret and anchor. Use the min in case they are within the range being deleted if (caret > pos) { caret -= qMin(static_cast<int>(caret - pos), length); } if (anchor > pos) { anchor -= qMin(static_cast<int>(anchor - pos), length); } }
1,735
C++
.cpp
56
27.910714
95
0.721125
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,333
DockedEditor.cpp
dail8859_NotepadNext/src/NotepadNext/DockedEditor.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "DockedEditor.h" #include "DockAreaTabBar.h" #include "DockAreaWidget.h" #include "DockWidgetTab.h" #include "DockComponentsFactory.h" #include "DockedEditorTitleBar.h" #include "DockAreaTitleBar.h" #include "ScintillaNext.h" #include <QUuid> class DockedEditorComponentsFactory : public ads::CDockComponentsFactory { public: ads::CDockAreaTitleBar* createDockAreaTitleBar(ads::CDockAreaWidget* DockArea) const { DockedEditorTitleBar *titleBar = new DockedEditorTitleBar(DockArea); // Disable the built in context menu for the title bar since it has options we don't want titleBar->setContextMenuPolicy(Qt::NoContextMenu); return titleBar; } }; DockedEditor::DockedEditor(QWidget *parent) : QObject(parent) { ads::CDockComponentsFactory::setFactory(new DockedEditorComponentsFactory()); ads::CDockManager::setConfigFlag(ads::CDockManager::AllTabsHaveCloseButton, true); ads::CDockManager::setConfigFlag(ads::CDockManager::AlwaysShowTabs, true); ads::CDockManager::setConfigFlag(ads::CDockManager::OpaqueSplitterResize, true); ads::CDockManager::setConfigFlag(ads::CDockManager::DragPreviewIsDynamic, true); ads::CDockManager::setConfigFlag(ads::CDockManager::DragPreviewShowsContentPixmap, true); ads::CDockManager::setConfigFlag(ads::CDockManager::DockAreaHasCloseButton, false); ads::CDockManager::setConfigFlag(ads::CDockManager::DockAreaHasUndockButton, false); // When tabs title/text elide disabled and lots of tabs opened, tabs menu button will not show // as it only shows when tab title elided. // So disable dynamic tabs menu visibility. ads::CDockManager::setConfigFlag(ads::CDockManager::DockAreaDynamicTabsMenuButtonVisibility, false); ads::CDockManager::setConfigFlag(ads::CDockManager::FocusHighlighting, true); ads::CDockManager::setConfigFlag(ads::CDockManager::EqualSplitOnInsertion, true); ads::CDockManager::setConfigFlag(ads::CDockManager::MiddleMouseButtonClosesTab, true); dockManager = new ads::CDockManager(parent); dockManager->setStyleSheet(""); connect(dockManager, &ads::CDockManager::focusedDockWidgetChanged, this, [=](ads::CDockWidget* old, ads::CDockWidget* now) { Q_UNUSED(old) ScintillaNext *editor = qobject_cast<ScintillaNext *>(now->widget()); currentEditor = editor; editor->grabFocus(); emit editorActivated(editor); }); connect(dockManager, &ads::CDockManager::dockAreaCreated, this, [=](ads::CDockAreaWidget* DockArea) { DockedEditorTitleBar *titleBar = qobject_cast<DockedEditorTitleBar *>(DockArea->titleBar()); connect(titleBar, &DockedEditorTitleBar::doubleClicked, this, &DockedEditor::titleBarDoubleClicked); connect(DockArea->titleBar()->tabBar(), &ads::CDockAreaTabBar::tabMoved, this, [=](int from, int to) { Q_UNUSED(from); Q_UNUSED(to); emit editorOrderChanged(); }); // In theory the order changes when a new dock area is created (e.g. editor is dragged and dropped), // but the dockAreaCreated() signal is triggered before it is actually added to the CDockManager, // so interrogating the dock manager during the signal doesn't help. //emit editorOrderChanged(); }); } ScintillaNext *DockedEditor::getCurrentEditor() const { return currentEditor; } int DockedEditor::count() const { int total = 0; for (int i = 0; i < dockManager->dockAreaCount(); ++i) total += dockManager->dockArea(i)->dockWidgetsCount(); return total; } QVector<ScintillaNext *> DockedEditor::editors() const { QVector<ScintillaNext *> editors; // For each area, for each widget, append it to our list for (const ads::CDockAreaWidget* areaWidget : dockManager->openedDockAreas()) { for (const ads::CDockWidget* dockWidget : areaWidget->dockWidgets()) { editors.append(qobject_cast<ScintillaNext *>(dockWidget->widget())); } } return editors; } void DockedEditor::switchToEditor(const ScintillaNext *editor) { ads::CDockWidget *dockWidget = qobject_cast<ads::CDockWidget *>(editor->parentWidget()); if (dockWidget == Q_NULLPTR) { qWarning() << "Expected editor's parent to be CDockWidget"; } else { dockWidget->raise(); } } void DockedEditor::dockWidgetCloseRequested() { ads::CDockWidget *dockWidget = qobject_cast<ads::CDockWidget *>(sender()); ScintillaNext *editor = qobject_cast<ScintillaNext *>(dockWidget->widget()); emit editorCloseRequested(editor); } ads::CDockAreaWidget *DockedEditor::currentDockArea() const { const ads::CDockWidget *dockWidget = dockManager->focusedDockWidget(); if (dockWidget) { return dockWidget->dockAreaWidget(); } else { return Q_NULLPTR; } } void DockedEditor::addEditor(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); Q_ASSERT(editor != Q_NULLPTR); if (currentEditor == Q_NULLPTR) { currentEditor = editor; } // Create the dock widget for the editor ads::CDockWidget *dockWidget = new ads::CDockWidget(editor->getName()); // Disable elide, elided file names not readable when lots of files opened dockWidget->tabWidget()->setElideMode(Qt::ElideNone); // We need a unique object name. Can't use the name or file path so use a uuid dockWidget->setObjectName(QUuid::createUuid().toString()); dockWidget->setWidget(editor); dockWidget->setFeature(ads::CDockWidget::DockWidgetFeature::DockWidgetDeleteOnClose, true); dockWidget->setFeature(ads::CDockWidget::DockWidgetFeature::CustomCloseHandling, true); dockWidget->setFeature(ads::CDockWidget::DockWidgetFeature::DockWidgetFloatable, false); dockWidget->tabWidget()->setContextMenuPolicy(Qt::CustomContextMenu); connect(dockWidget->tabWidget(), &QWidget::customContextMenuRequested, this, [=](const QPoint &pos) { Q_UNUSED(pos) emit contextMenuRequestedForEditor(editor); }); // Set the tooltip based on the buffer if (editor->isFile()) { dockWidget->tabWidget()->setToolTip(editor->getFilePath()); } else { dockWidget->tabWidget()->setToolTip(editor->getName()); } // Set the icon if (editor->readOnly()) { dockWidget->tabWidget()->setIcon(QIcon(":/icons/readonly.png")); } else { dockWidget->tabWidget()->setIcon(QIcon(editor->canSaveToDisk() ? ":/icons/unsaved.png" : ":/icons/saved.png")); connect(editor, &ScintillaNext::savePointChanged, dockWidget, [=](bool dirty) { const bool actuallyDirty = editor->canSaveToDisk(); const QString iconPath = actuallyDirty ? ":/icons/unsaved.png" : ":/icons/saved.png"; dockWidget->tabWidget()->setIcon(QIcon(iconPath)); }); } connect(editor, &ScintillaNext::closed, dockWidget, &ads::CDockWidget::closeDockWidget); connect(editor, &ScintillaNext::closed, this, [=]() { emit editorClosed(editor); }); connect(editor, &ScintillaNext::renamed, this, [=]() { editorRenamed(editor); }); connect(dockWidget, &ads::CDockWidget::closeRequested, this, &DockedEditor::dockWidgetCloseRequested); dockManager->addDockWidget(ads::CenterDockWidgetArea, dockWidget, currentDockArea()); emit editorAdded(editor); } void DockedEditor::editorRenamed(ScintillaNext *editor) { Q_ASSERT(editor != Q_NULLPTR); ads::CDockWidget *dockWidget = qobject_cast<ads::CDockWidget *>(editor->parentWidget()); dockWidget->setWindowTitle(editor->getName()); if (editor->isFile()) { dockWidget->tabWidget()->setToolTip(editor->getFilePath()); } else { dockWidget->tabWidget()->setToolTip(editor->getName()); } }
8,520
C++
.cpp
184
41.103261
128
0.719942
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,334
QRegexSearch.cpp
dail8859_NotepadNext/src/NotepadNext/QRegexSearch.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "QRegexSearch.h" #include <QtGlobal> #include <QRegularExpression> using namespace Scintilla; #ifdef SCI_OWNREGEX RegexSearchBase *Scintilla::Internal::CreateRegexSearch(CharClassify *charClassTable) { Q_UNUSED(charClassTable); qInfo(Q_FUNC_INFO); return new QRegexSearch(); } #endif QRegexSearch::QRegexSearch() { } Sci::Position QRegexSearch::FindText(Document *doc, Sci::Position minPos, Sci::Position maxPos, const char *s, bool caseSensitive, bool word, bool wordStart, Scintilla::FindOption flags, Sci::Position *length) { // ----------------------------------------------------------------------------------------------------------------------- // NOTE: This section of code has to be very careful about what units of measure is being used. Scintilla wants to operate // in units of bytes (e.g. position 3 is 3 bytes into the text). Qt wants to operate in units of UTF16 chars. The trouble is // when you start using characters that are >1 byte a piece. Meaning position 3 (3 bytes into a file) could be 1 character. // ----------------------------------------------------------------------------------------------------------------------- // Make sure the positiosn are outside of characters minPos = doc->MovePositionOutsideChar(minPos, 1, false); maxPos = doc->MovePositionOutsideChar(maxPos, -1, false); //qInfo(Q_FUNC_INFO); //qInfo("\tminPos %d", minPos); //qInfo("\tmaxPos %d", maxPos); //qInfo("\ts %s", s); //qInfo("\tcaseSensitive %s", caseSensitive ? "true" : "false"); //qInfo("\tword %s", word ? "true" : "false"); //qInfo("\twordStart %s", wordStart ? "true" : "false"); //qInfo("\tflags %d", flags); // No need to search an empty range if (minPos == maxPos) return -1; auto options = QRegularExpression::MultilineOption | QRegularExpression::UseUnicodePropertiesOption; if (!FlagSet(flags, FindOption::MatchCase)) options |= QRegularExpression::CaseInsensitiveOption; // TODO: does (*ANYCRLF) need prepended to the search string? QRegularExpression re(s, options); if (!re.isValid()) return -1; // Invalid regular expression // Get the bytes from the document. No need to go past maxPos bytes // Not actually sure if this copies the data or not const Sci::Position rangeLength = maxPos - minPos; const QString utf8 = QString::fromUtf8(doc->RangePointer(minPos, rangeLength), rangeLength); // NOTE: QString uses UTF16 counts since QChars are 16 bits QRegularExpressionMatch m = re.match(utf8, 0, QRegularExpression::NormalMatch, QRegularExpression::NoMatchOption); if (!m.hasMatch()) return -1; // No match match = m; // NOTE: Returned started is the index into the QString which uses UTF16 const int positionStart = doc->GetRelativePositionUTF16(minPos, match.capturedStart(0)); // Now move ahead however many characters we matched. Again, based on UTF16 count const int positionEnd = doc->GetRelativePositionUTF16(positionStart, match.capturedLength(0)); // The length is the number of bytes that was matched *length = positionEnd - positionStart; return positionStart; } const char *QRegexSearch::SubstituteByPosition(Document *doc, const char *text, Sci::Position *length) { Q_UNUSED(doc); qInfo(Q_FUNC_INFO); Q_ASSERT(match.isValid()); Q_ASSERT(match.hasMatch()); // Get the captured text and replace the match QString newString = match.captured(); newString.replace(match.regularExpression(), QByteArray(text, *length)); // TODO: figure out why this has to be new'd and can't be an instantiated class member if (substituted) { delete substituted; } substituted = new QByteArray(newString.toUtf8()); *length = substituted->length(); return substituted->data(); }
4,611
C++
.cpp
94
44.840426
209
0.683084
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,335
ColorPickerDelegate.cpp
dail8859_NotepadNext/src/NotepadNext/ColorPickerDelegate.cpp
/* * This file is part of Notepad Next. * Copyright 2021 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "ColorPickerDelegate.h" #include <QColorDialog> ColorPickerDelegate::ColorPickerDelegate(QObject *parent) : QStyledItemDelegate(parent) { } QWidget *ColorPickerDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option) Q_UNUSED(index) QColorDialog* colorDialog = new QColorDialog(parent); colorDialog->setModal(true); return colorDialog; } void ColorPickerDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QColorDialog *colorDialog = static_cast<QColorDialog*>(editor); const QColor color = index.model()->data(index, Qt::DecorationRole).value<QColor>(); colorDialog->setCurrentColor(color); } void ColorPickerDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QColorDialog *colorDialog = static_cast<QColorDialog*>(editor); QColor color = colorDialog->selectedColor(); if (color.isValid()) { model->setData(index, color, Qt::EditRole); } }
1,790
C++
.cpp
45
36.866667
127
0.764265
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,336
ComboBoxDelegate.cpp
dail8859_NotepadNext/src/NotepadNext/ComboBoxDelegate.cpp
/* * This file is part of Notepad Next. * Copyright 2021 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "ComboBoxDelegate.h" #include <QComboBox> #include <QApplication> ComboBoxDelegate::ComboBoxDelegate(const QList<ComboBoxItem> &items, QObject *parent) : QStyledItemDelegate(parent), comboBoxItems(items) { } QWidget *ComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option) Q_UNUSED(index) QComboBox *comboBox = new QComboBox(parent); for(const ComboBoxItem &item : comboBoxItems) { comboBox->addItem(item.first, item.second); } return comboBox; } void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QVariant value = index.model()->data(index, Qt::EditRole); QComboBox *comboBox = static_cast<QComboBox*>(editor); comboBox->setCurrentIndex(comboBox->findData(value)); } void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox *comboBox = static_cast<QComboBox*>(editor); QVariant value = comboBox->currentData(); model->setData(index, value, Qt::EditRole); } void ComboBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index) editor->setGeometry(option.rect); } QSize ComboBoxDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option) Q_UNUSED(index) QFontMetrics fm = qApp->fontMetrics(); QSize maxStringSize(0, 0); int &width = maxStringSize.rwidth(); int &height = maxStringSize.rheight(); for(const ComboBoxItem &item : comboBoxItems) { QRect rect = fm.boundingRect(item.first); height = rect.height(); // Heights *should* all be the same width = qMax(rect.width(), width); } QStyleOptionComboBox comobBoxStyleOptions; return qApp->style()->sizeFromContents(QStyle::CT_ComboBox, &comobBoxStyleOptions, maxStringSize, nullptr); }
2,730
C++
.cpp
67
37.238806
128
0.752176
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,337
ScintillaCommenter.cpp
dail8859_NotepadNext/src/NotepadNext/ScintillaCommenter.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "ScintillaCommenter.h" #include "SelectionTracker.h" ScintillaCommenter::ScintillaCommenter(ScintillaNext *editor) : editor(editor), st(editor), ua(editor) { } void ScintillaCommenter::toggleSelection() { editor->forEachLineInSelection(editor->mainSelection(), [&](int line) { toggleLine(line); }); } void ScintillaCommenter::commentSelection() { editor->forEachLineInSelection(editor->mainSelection(), [&](int line) { commentLine(line); }); } void ScintillaCommenter::uncommentSelection() { editor->forEachLineInSelection(editor->mainSelection(), [&](int line) { uncommentLine(line); }); } void ScintillaCommenter::toggleLine(int line) { auto indentPos = editor->lineIndentPosition(line); auto lineEnd = qMin(indentPos + editor->languageSingleLineComment.length(), editor->lineEndPosition(line)); const QByteArray commentText = editor->get_text_range(indentPos, lineEnd); if (commentText == editor->languageSingleLineComment) { editor->deleteRange(indentPos, editor->languageSingleLineComment.length()); st.trackDeletion(indentPos, editor->languageSingleLineComment.length()); } else { if (indentPos == editor->lineEndPosition(line)) { return; } editor->insertText(indentPos, editor->languageSingleLineComment.constData()); st.trackInsertion(indentPos, editor->languageSingleLineComment.length()); } } void ScintillaCommenter::commentLine(int line) { auto indentPos = editor->lineIndentPosition(line); // Don't comment lines with only indentation if (indentPos == editor->lineEndPosition(line)) { return; } editor->insertText(indentPos, editor->languageSingleLineComment.constData()); st.trackInsertion(indentPos, editor->languageSingleLineComment.length()); } void ScintillaCommenter::uncommentLine(int line) { auto indentPos = editor->lineIndentPosition(line); auto lineEnd = qMin(indentPos + editor->languageSingleLineComment.length(), editor->lineEndPosition(line)); const QByteArray commentText = editor->get_text_range(indentPos, lineEnd); if (commentText == editor->languageSingleLineComment) { editor->deleteRange(indentPos, editor->languageSingleLineComment.length()); st.trackDeletion(indentPos, editor->languageSingleLineComment.length()); } }
3,118
C++
.cpp
78
35.871795
111
0.742555
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,338
EditorInspectorDock.cpp
dail8859_NotepadNext/src/NotepadNext/docks/EditorInspectorDock.cpp
/* * This file is part of Notepad Next. * Copyright 2021 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "EditorInspectorDock.h" #include "ui_EditorInspectorDock.h" #include "MainWindow.h" static inline QString toBool(int b) { return b ? QStringLiteral("True") : QStringLiteral("False"); } EditorInspectorDock::EditorInspectorDock(MainWindow *parent) : QDockWidget(parent), ui(new Ui::EditorInspectorDock) { ui->setupUi(this); QTreeWidgetItem *positionInfo = new QTreeWidgetItem(ui->treeWidget); positionInfo->setText(0, tr("Position Information")); positionInfo->setExpanded(true); newItem(positionInfo, tr("Current Position"), [](ScintillaNext *editor) { return QString::number(editor->currentPos()); }); newItem(positionInfo, tr("Current Position (x, y)"), [](ScintillaNext *editor) { return QString("(%1, %2)").arg(editor->pointXFromPosition(editor->currentPos())).arg(editor->pointYFromPosition(editor->currentPos())); }); newItem(positionInfo, tr("Column"), [](ScintillaNext *editor) { return QString::number(editor->column(editor->currentPos())); }); // SCI_GETCHARAT(position pos) → int newItem(positionInfo, tr("Current Style"), [](ScintillaNext *editor) { return QString::number(editor->styleAt(editor->currentPos())); }); newItem(positionInfo, tr("Current Line"), [](ScintillaNext *editor) { return QString::number(editor->lineFromPosition(editor->currentPos()) + 1); }); newItem(positionInfo, tr("Line Length"), [](ScintillaNext *editor) { return QString::number(editor->lineLength(editor->lineFromPosition(editor->currentPos()))); }); newItem(positionInfo, tr("Line End Position"), [](ScintillaNext *editor) { return QString::number(editor->lineEndPosition(editor->lineFromPosition(editor->currentPos()))); }); newItem(positionInfo, tr("Line Indentation"), [](ScintillaNext *editor) { return QString::number(editor->lineIndentation(editor->lineFromPosition(editor->currentPos()))); }); newItem(positionInfo, tr("Line Indent Position"), [](ScintillaNext *editor) { return QString::number(editor->lineIndentPosition(editor->lineFromPosition(editor->currentPos()))); }); QTreeWidgetItem *selInfo = new QTreeWidgetItem(ui->treeWidget); selInfo->setText(0, tr("Selection Information")); selInfo->setExpanded(true); newItem(selInfo, tr("Mode"), [](ScintillaNext *editor) { switch (editor->selectionMode()) { case SC_SEL_STREAM: return QStringLiteral("SC_SEL_STREAM"); case SC_SEL_RECTANGLE: return QStringLiteral("SC_SEL_RECTANGLE"); case SC_SEL_LINES: return QStringLiteral("SC_SEL_LINES"); case SC_SEL_THIN: return QStringLiteral("SC_SEL_THIN"); default: return QStringLiteral(""); } }); newItem(selInfo, tr("Is Rectangle"), [](ScintillaNext *editor) { return toBool(editor->selectionIsRectangle()); }); newItem(selInfo, tr("Selection Empty"), [](ScintillaNext *editor) { return toBool(editor->selectionEmpty()); }); newItem(selInfo, tr("Main Selection"), [](ScintillaNext *editor) { return QString::number(editor->mainSelection()); }); newItem(selInfo, tr("# of Selections"), [](ScintillaNext *editor) { return QString::number(editor->selections()); }); selectionsInfo = new QTreeWidgetItem(selInfo); selectionsInfo->setText(0, tr("Multiple Selections")); selectionsInfo->setExpanded(true); QTreeWidgetItem *documentInfo = new QTreeWidgetItem(ui->treeWidget); documentInfo->setText(0, tr("Document Information")); documentInfo->setExpanded(true); newItem(documentInfo, tr("Length"), [](ScintillaNext *editor) { return QString::number(editor->length()); }); newItem(documentInfo, tr("Line Count"), [](ScintillaNext *editor) { return QString::number(editor->lineCount()); }); QTreeWidgetItem *viewInfo = new QTreeWidgetItem(ui->treeWidget); viewInfo->setText(0, tr("View Information")); viewInfo->setExpanded(true); newItem(viewInfo, tr("Lines on Screen"), [](ScintillaNext *editor) { return QString::number(editor->linesOnScreen()); }); newItem(viewInfo, tr("First Visible Line"), [](ScintillaNext *editor) { return QString::number(editor->firstVisibleLine() + 1); }); newItem(viewInfo, tr("X Offset"), [](ScintillaNext *editor) { return QString::number(editor->xOffset()); }); QTreeWidgetItem *foldInfo = new QTreeWidgetItem(ui->treeWidget); foldInfo->setText(0, tr("Fold Information")); foldInfo->setExpanded(true); newItem(foldInfo, tr("Visible From Doc Line"), [](ScintillaNext *editor) { return QString::number(editor->visibleFromDocLine(editor->lineFromPosition(editor->currentPos())) + 1); }); newItem(foldInfo, tr("Doc Line From Visible"), [](ScintillaNext *editor) { return QString::number(editor->docLineFromVisible(editor->lineFromPosition(editor->currentPos())) + 1); }); newItem(foldInfo, tr("Fold Level"), [](ScintillaNext *editor) { return QString::number((editor->foldLevel(editor->lineFromPosition(editor->currentPos())) & SC_FOLDLEVELNUMBERMASK) - SC_FOLDLEVELBASE); }); newItem(foldInfo, tr("Is Fold Header"), [](ScintillaNext *editor) { return toBool((editor->foldLevel(editor->lineFromPosition(editor->currentPos())) & SC_FOLDLEVELHEADERFLAG) == SC_FOLDLEVELHEADERFLAG); }); newItem(foldInfo, tr("Fold Parent"), [](ScintillaNext *editor) { return QString::number(editor->foldParent(editor->lineFromPosition(editor->currentPos())) + 1); }); newItem(foldInfo, tr("Last Child"), [](ScintillaNext *editor) { return QString::number(editor->lastChild(editor->lineFromPosition(editor->currentPos()), -1) + 1); }); newItem(foldInfo, tr("Contracted Fold Next"), [](ScintillaNext *editor) { return QString::number(editor->contractedFoldNext(editor->lineFromPosition(editor->currentPos())) + 1); }); connect(this, &QDockWidget::visibilityChanged, this, [=](bool visible) { if (visible) { connectToEditor(parent->currentEditor()); connect(parent, &MainWindow::editorActivated, this, &EditorInspectorDock::connectToEditor); } else { disconnectFromEditor(); disconnect(parent, &MainWindow::editorActivated, this, &EditorInspectorDock::connectToEditor); } }); } EditorInspectorDock::~EditorInspectorDock() { delete ui; } void EditorInspectorDock::connectToEditor(ScintillaNext *editor) { disconnectFromEditor(); editorConnection = connect(editor, &ScintillaNext::updateUi, this, &EditorInspectorDock::editorUIUpdated); updateEditorInfo(editor); } void EditorInspectorDock::disconnectFromEditor() { if (editorConnection) { disconnect(editorConnection); } } void EditorInspectorDock::editorUIUpdated(Scintilla::Update updated) { if (FlagSet(updated, Scintilla::Update::Content) || FlagSet(updated, Scintilla::Update::Selection) || FlagSet(updated, Scintilla::Update::VScroll) || FlagSet(updated, Scintilla::Update::HScroll)) { ScintillaNext *editor = qobject_cast<ScintillaNext*>(sender()); updateEditorInfo(editor); } } void EditorInspectorDock::updateEditorInfo(ScintillaNext *editor) { for (const QPair<QTreeWidgetItem *, EditorFunction> &pair : qAsConst(items)) { QTreeWidgetItem *item = pair.first; if (item->parent()->isExpanded()) { EditorFunction func = pair.second; item->setText(1, func(editor)); } } qDeleteAll(selectionsInfo->takeChildren()); for (int i = 0; i < editor->selections(); ++i) { QTreeWidgetItem *selection = new QTreeWidgetItem(selectionsInfo); selection->setText(0, QLatin1Char('#') + QString::number(i)); selection->setExpanded(true); QTreeWidgetItem *caret = new QTreeWidgetItem(selection); caret->setText(0, tr("Caret")); caret->setText(1, QString::number(editor->selectionNCaret(i))); QTreeWidgetItem *anchor = new QTreeWidgetItem(selection); anchor->setText(0, tr("Anchor")); anchor->setText(1, QString::number(editor->selectionNAnchor(i))); QTreeWidgetItem *caretVirtual = new QTreeWidgetItem(selection); caretVirtual->setText(0, tr("Caret Virtual Space")); caretVirtual->setText(1, QString::number(editor->selectionNCaretVirtualSpace(i))); QTreeWidgetItem *anchorVirtual = new QTreeWidgetItem(selection); anchorVirtual->setText(0, tr("Anchor Virtual Space")); anchorVirtual->setText(1, QString::number(editor->selectionNAnchorVirtualSpace(i))); } ui->treeWidget->resizeColumnToContents(0); } void EditorInspectorDock::newItem(QTreeWidgetItem *parent, const QString &label, EditorFunction func) { QTreeWidgetItem *item = new QTreeWidgetItem(parent); item->setText(0, label); items.append(qMakePair(item, func)); }
9,571
C++
.cpp
158
54.544304
224
0.705569
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,339
DebugLogDock.cpp
dail8859_NotepadNext/src/NotepadNext/docks/DebugLogDock.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "DebugLogDock.h" #include "ui_DebugLogDock.h" #include "DebugManager.h" #include <QScrollBar> static QPlainTextEdit *output = Q_NULLPTR; static void debugLogDockMessageHandler(const QString &msg) { output->appendPlainText(msg); } DebugLogDock::DebugLogDock(QWidget *parent) : QDockWidget(parent), ui(new Ui::DebugLogDock) { ui->setupUi(this); output = ui->txtDebugOutput; DebugManager::addMessageHandler(debugLogDockMessageHandler); connect(this, &QDockWidget::visibilityChanged, this, [=](bool visible) { if (visible) { ui->txtDebugOutput->horizontalScrollBar()->setValue(0); } }); } DebugLogDock::~DebugLogDock() { delete ui; }
1,439
C++
.cpp
43
30.395349
76
0.741889
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,340
LuaConsoleDock.cpp
dail8859_NotepadNext/src/NotepadNext/docks/LuaConsoleDock.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "LuaConsoleDock.h" #include "ui_LuaConsoleDock.h" #include "ScintillaNext.h" #include "ILexer.h" #include "Lexilla.h" #include "SciLexer.h" #include "LuaState.h" #include "lua.hpp" #include "LuaExtension.h" #include <QKeyEvent> #include <QVBoxLayout> #define INDIC_BRACEHIGHLIGHT INDIC_CONTAINER static bool inline isBrace(int ch) { return strchr("[]{}()", ch) != NULL; } inline static void raise_error(lua_State *L, const char *errMsg=NULL) { luaL_where(L, 1); if (errMsg) { lua_pushstring(L, errMsg); } else { lua_insert(L, -2); } lua_concat(L, 2); lua_error(L); } static int cf_global_print(lua_State *L) { LuaConsoleDock *dock = static_cast<LuaConsoleDock *>(lua_touserdata(L, lua_upvalueindex(1))); int nargs = lua_gettop(L); lua_getglobal(L, "tostring"); for (int i = 1; i <= nargs; ++i) { if (i > 1) dock->writeToOutput("\t"); const char *argStr = lua_tostring(L, i); if (argStr) { dock->writeToOutput(argStr); } else { lua_pushvalue(L, -1); // tostring lua_pushvalue(L, i); lua_call(L, 1, 1); argStr = lua_tostring(L, -1); if (argStr) { dock->writeToOutput(argStr); } else { raise_error(L, "tostring (called from print) returned a non-string"); } lua_settop(L, nargs + 1); } } dock->writeToOutput("\r\n"); return 0; } LuaConsoleDock::LuaConsoleDock(LuaState *l, QWidget *parent) : QDockWidget(parent), ui(new Ui::LuaConsoleDock) { L = l; // Override print to print to the console lua_pushlightuserdata(L->L, this); lua_pushcclosure(L->L, cf_global_print, 1); lua_setglobal(L->L, "print"); ui->setupUi(this); output = new ScintillaNext(Q_NULLPTR, this); QFrame *line; line = new QFrame(this); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); input = new ScintillaNext(Q_NULLPTR, this); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(output); layout->addWidget(line); layout->addWidget(input); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); QWidget *widget = new QWidget(this); widget->setLayout(layout); setWidget(widget); output->setUndoCollection(false); output->setReadOnly(true); output->setILexer(reinterpret_cast<sptr_t>(CreateLexer("lua"))); output->usePopUp(SC_POPUP_NEVER); output->setMarginWidthN(1, output->textWidth(STYLE_DEFAULT, ">") * 2); output->setMarginTypeN(1, SC_MARGIN_RTEXT); output->styleSetBold(STYLE_LINENUMBER, true); output->setScrollWidth(1); // Have it actually do the lexing input->setILexer(reinterpret_cast<sptr_t>(CreateLexer("lua"))); // Setup Keywords input->setKeyWords(0, "and break do else elseif end false for function goto if in local nil not or repeat return then true until while"); input->setKeyWords(1, "_ENV _G _VERSION assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawlen rawset require select setfenv setmetatable tonumber tostring type unpack xpcall string table math bit32 coroutine io os debug package __index __newindex __call __add __sub __mul __div __mod __pow __unm __concat __len __eq __lt __le __gc __mode"); input->setKeyWords(2, "byte char dump find format gmatch gsub len lower rep reverse sub upper abs acos asin atan atan2 ceil cos cosh deg exp floor fmod frexp ldexp log log10 max min modf pow rad random randomseed sin sinh sqrt tan tanh arshift band bnot bor btest bxor extract lrotate lshift replace rrotate rshift shift string.byte string.char string.dump string.find string.format string.gmatch string.gsub string.len string.lower string.match string.rep string.reverse string.sub string.upper table.concat table.insert table.maxn table.pack table.remove table.sort table.unpack math.abs math.acos math.asin math.atan math.atan2 math.ceil math.cos math.cosh math.deg math.exp math.floor math.fmod math.frexp math.huge math.ldexp math.log math.log10 math.max math.min math.modf math.pi math.pow math.rad math.random math.randomseed math.sin math.sinh math.sqrt math.tan math.tanh bit32.arshift bit32.band bit32.bnot bit32.bor bit32.btest bit32.bxor bit32.extract bit32.lrotate bit32.lshift bit32.replace bit32.rrotate bit32.rshift"); input->setKeyWords(3, "close flush lines read seek setvbuf write clock date difftime execute exit getenv remove rename setlocale time tmpname coroutine.create coroutine.resume coroutine.running coroutine.status coroutine.wrap coroutine.yield io.close io.flush io.input io.lines io.open io.output io.popen io.read io.tmpfile io.type io.write io.stderr io.stdin io.stdout os.clock os.date os.difftime os.execute os.exit os.getenv os.remove os.rename os.setlocale os.time os.tmpname debug.debug debug.getfenv debug.gethook debug.getinfo debug.getlocal debug.getmetatable debug.getregistry debug.getupvalue debug.getuservalue debug.setfenv debug.sethook debug.setlocal debug.setmetatable debug.setupvalue debug.setuservalue debug.traceback debug.upvalueid debug.upvaluejoin package.cpath package.loaded package.loaders package.loadlib package.path package.preload package.seeall"); // Highlight constants //input->setKeyWords(4, join(SciIFaceTable.GetAllConstantNames(), ' ').c_str()); //input->setKeyWords(5, join(NppIFaceTable.GetAllConstantNames(), ' ').c_str()); // Set up some autocomplete junk input->autoCSetIgnoreCase(true); input->autoCSetMaxHeight(8); input->autoCSetCancelAtStart(false); input->indicSetStyle(INDIC_BRACEHIGHLIGHT, INDIC_STRAIGHTBOX); input->indicSetUnder(INDIC_BRACEHIGHLIGHT, true); input->braceHighlightIndicator(true, INDIC_BRACEHIGHLIGHT); input->setIndentationGuides(SC_IV_LOOKBOTH); input->setHScrollBar(false); input->setMarginWidthN(1, input->textWidth(STYLE_DEFAULT, ">") * 2); input->setMarginTypeN(1, SC_MARGIN_RTEXT); input->styleSetBold(STYLE_LINENUMBER, true); input->setMarginLeft(2); input->clearCmdKey('Q' + (SCMOD_CTRL << 16)); input->clearCmdKey('W' + (SCMOD_CTRL << 16)); input->clearCmdKey('E' + (SCMOD_CTRL << 16)); input->clearCmdKey('R' + (SCMOD_CTRL << 16)); input->clearCmdKey('T' + (SCMOD_CTRL << 16)); input->clearCmdKey('O' + (SCMOD_CTRL << 16)); input->clearCmdKey('P' + (SCMOD_CTRL << 16)); input->clearCmdKey('S' + (SCMOD_CTRL << 16)); input->clearCmdKey('D' + (SCMOD_CTRL << 16)); input->clearCmdKey('F' + (SCMOD_CTRL << 16)); input->clearCmdKey('G' + (SCMOD_CTRL << 16)); input->clearCmdKey('H' + (SCMOD_CTRL << 16)); input->clearCmdKey('J' + (SCMOD_CTRL << 16)); input->clearCmdKey('K' + (SCMOD_CTRL << 16)); input->clearCmdKey('L' + (SCMOD_CTRL << 16)); input->clearCmdKey('B' + (SCMOD_CTRL << 16)); input->clearCmdKey('N' + (SCMOD_CTRL << 16)); input->clearCmdKey('M' + (SCMOD_CTRL << 16)); input->clearCmdKey(SCK_RETURN); // don't allow normal new lines input->marginSetText(0, ">"); input->marginSetStyle(0, STYLE_LINENUMBER); setupStyle(input); setupStyle(output); output->styleSetFore(39, 0x0000FF); // For error messages input->setExtraAscent(2); input->setExtraDescent(2); input->setMaximumHeight(input->textHeight(0)); input->installEventFilter(this); connect(input, &ScintillaNext::updateUi, [=](Scintilla::Update flags) { Q_UNUSED(flags); int curPos = input->currentPos(); int bracePos = INVALID_POSITION; // Check on both sides if (isBrace(input->charAt(curPos - 1))) { bracePos = curPos - 1; } else if (isBrace(input->charAt(curPos))) { bracePos = curPos; } // See if we are next to a brace if (bracePos != INVALID_POSITION) { int otherPos = input->braceMatch(bracePos, 0); if (otherPos != INVALID_POSITION) { input->braceHighlight(bracePos, otherPos); } else { input->braceHighlight(INVALID_POSITION, INVALID_POSITION); } } else { input->braceHighlight(INVALID_POSITION, INVALID_POSITION); } }); connect(input, &ScintillaNext::linesAdded, [=](int linesAdded) { if (input->lineCount() > 0) qInfo("lines added %d", linesAdded); }); } LuaConsoleDock::~LuaConsoleDock() { delete ui; } void LuaConsoleDock::writeToOutput(const char *s) { output->setReadOnly(false); output->appendText(strlen(s), s); output->setReadOnly(true); output->documentEnd(); } void LuaConsoleDock::writeErrorToOutput(const char *s) { typedef struct { unsigned char c; unsigned char style; } cell; const int length = static_cast<int>(strlen(s)); QVector<cell> cells(length + 1); for (auto i = 0; i < length; ++i) { cells[i].c = s[i]; cells[i].style = 39; } cells[length].c = 0; cells[length].style = 0; output->setReadOnly(false); output->documentEnd(); output->addStyledText(length * 2, (const char *) cells.constData()); output->setReadOnly(true); output->documentEnd(); } void LuaConsoleDock::runCurrentCommand() { int prevLastLine = output->lineCount(); int newLastLine = 0; Sci_TextRange tr; tr.chrg.cpMin = 0; tr.chrg.cpMax = input->length(); tr.lpstrText = new char[2 * (tr.chrg.cpMax - tr.chrg.cpMin) + 2]; // See documentation input->send(SCI_GETSTYLEDTEXT, 0, (sptr_t) &tr); output->documentEnd(); output->setReadOnly(false); output->addStyledText(2 * (tr.chrg.cpMax - tr.chrg.cpMin), tr.lpstrText); writeToOutput("\r\n"); delete[] tr.lpstrText; newLastLine = output->lineCount(); for (int i = prevLastLine; i < newLastLine; ++i) { output->marginSetText(i - 1, ">"); output->marginSetStyle(i - 1, STYLE_LINENUMBER); } QString text((const char *)input->characterPointer()); //historyAdd(GUI::StringFromUTF8(text).c_str()); input->clearAll(); input->emptyUndoBuffer(); input->marginSetText(0, ">"); input->marginSetStyle(0, STYLE_LINENUMBER); LuaExtension::Instance().OnExecute(text.toLatin1().constData()); } bool LuaConsoleDock::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Return && keyEvent->modifiers() == Qt::NoModifier) { runCurrentCommand(); return true; } } else { // standard event processing return QObject::eventFilter(obj, event); } return false; } void LuaConsoleDock::setupStyle(ScintillaNext *editor) { editor->setEOLMode(SC_EOL_CRLF); editor->styleSetFore(STYLE_DEFAULT, 0x000000); editor->styleSetBack(STYLE_DEFAULT, 0xFFFFFF); editor->styleSetFont(STYLE_DEFAULT, "Courier New"); editor->styleSetSize(STYLE_DEFAULT, 10); editor->styleClearAll(); // Setup the margins editor->setMarginWidthN(0, 0); editor->setMarginWidthN(2, 0); editor->setMarginWidthN(3, 0); editor->setMarginWidthN(4, 0); editor->setCodePage(SC_CP_UTF8); editor->styleSetFore(SCE_LUA_COMMENT, 0x008000); editor->styleSetFore(SCE_LUA_COMMENTLINE, 0x008000); editor->styleSetFore(SCE_LUA_COMMENTDOC, 0x808000); editor->styleSetFore(SCE_LUA_LITERALSTRING, 0x4A0095); editor->styleSetFore(SCE_LUA_PREPROCESSOR, 0x004080); // Technically not used since this is lua 5+ editor->styleSetFore(SCE_LUA_WORD, 0xFF0000); editor->styleSetBold(SCE_LUA_WORD, 1); // for SCI_SETKEYWORDS, 0 editor->styleSetFore(SCE_LUA_NUMBER, 0x0080FF); editor->styleSetFore(SCE_LUA_STRING, 0x808080); editor->styleSetFore(SCE_LUA_CHARACTER, 0x808080); editor->styleSetFore(SCE_LUA_OPERATOR, 0x800000); editor->styleSetBold(SCE_LUA_OPERATOR, 1); editor->styleSetFore(SCE_LUA_WORD2, 0xC08000); editor->styleSetBold(SCE_LUA_WORD2, 1); // for SCI_SETKEYWORDS, 1 editor->styleSetFore(SCE_LUA_WORD3, 0xFF0080); editor->styleSetBold(SCE_LUA_WORD3, 1); // for SCI_SETKEYWORDS, 2 editor->styleSetFore(SCE_LUA_WORD4, 0xA00000); editor->styleSetBold(SCE_LUA_WORD4, 1); editor->styleSetItalic(SCE_LUA_WORD4, 1); // for SCI_SETKEYWORDS, 3 editor->styleSetFore(SCE_LUA_LABEL, 0x008080); editor->styleSetBold(SCE_LUA_LABEL, 1); editor->styleSetFore(SCE_LUA_WORD5, 0x004080); // for SCI_SETKEYWORDS, 4, Scintilla defines editor->styleSetBold(SCE_LUA_WORD5, 1); editor->styleSetFore(SCE_LUA_WORD6, 0x004080); // for SCI_SETKEYWORDS, 5, Notepad++ defines editor->styleSetBold(SCE_LUA_WORD6, 1); }
13,657
C++
.cpp
295
40.613559
1,038
0.686095
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,341
LanguageInspectorDock.cpp
dail8859_NotepadNext/src/NotepadNext/docks/LanguageInspectorDock.cpp
/* * This file is part of Notepad Next. * Copyright 2021 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include <QFontDatabase> #include "LanguageInspectorDock.h" #include "ui_LanguageInspectorDock.h" #include "MainWindow.h" #include "LanguageStylesModel.h" #include "SpinBoxDelegate.h" #include "ColorPickerDelegate.h" #include "ComboBoxDelegate.h" #include "ScintillaNext.h" static QSpinBox *FontSizeSpinBoxFactory() { QSpinBox *editor = new QSpinBox(); editor->setFrame(false); editor->setRange(2, 24); editor->setAlignment(Qt::AlignHCenter); return editor; } static QSpinBox *FontWeightSpinBoxFactory() { QSpinBox *editor = new QSpinBox(); editor->setFrame(false); editor->setRange(100, 2400); editor->setSingleStep(10); editor->setAlignment(Qt::AlignHCenter); return editor; } static QString property_type_to_string(int type) { switch (type) { case SC_TYPE_BOOLEAN: return "Bool"; case SC_TYPE_INTEGER: return "Int"; case SC_TYPE_STRING: return "String"; default: return "unknown"; } } LanguageInspectorDock::LanguageInspectorDock(MainWindow *parent) : QDockWidget(parent), ui(new Ui::LanguageInspectorDock) { ui->setupUi(this); SpinBoxDelegate *fontSizeDelegate = new SpinBoxDelegate(FontSizeSpinBoxFactory, this); ui->tblStyles->setItemDelegateForColumn(5, fontSizeDelegate); SpinBoxDelegate *fontWeightDelegate = new SpinBoxDelegate(FontWeightSpinBoxFactory, this); ui->tblStyles->setItemDelegateForColumn(6, fontWeightDelegate); ColorPickerDelegate *foreColorDelegate = new ColorPickerDelegate(this); ui->tblStyles->setItemDelegateForColumn(11, foreColorDelegate); ColorPickerDelegate *backColorDelegate = new ColorPickerDelegate(this); ui->tblStyles->setItemDelegateForColumn(12, backColorDelegate); QList<ComboBoxItem> caseItems{ {"SC_CASE_MIXED", SC_CASE_MIXED}, {"SC_CASE_UPPER", SC_CASE_UPPER}, {"SC_CASE_LOWER", SC_CASE_LOWER}, {"SC_CASE_CAMEL", SC_CASE_CAMEL} }; ComboBoxDelegate *caseComoboDelegate = new ComboBoxDelegate(caseItems, this); ui->tblStyles->setItemDelegateForColumn(15, caseComoboDelegate); QList<ComboBoxItem> fontNames; #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) for (const QString &font : QFontDatabase::families()) { #else QFontDatabase fontDatabase; for (const QString &font : fontDatabase.families()) { #endif fontNames.append(QPair<QString, QString>(font, font)); } ComboBoxDelegate *fontComboDelegate = new ComboBoxDelegate(fontNames, this); ui->tblStyles->setItemDelegateForColumn(4, fontComboDelegate); connect(this, &QDockWidget::visibilityChanged, this, [=](bool visible) { if (visible) { connectToEditor(parent->currentEditor()); connect(parent, &MainWindow::editorActivated, this, &LanguageInspectorDock::connectToEditor); } else { disconnectFromEditor(); disconnect(parent, &MainWindow::editorActivated, this, &LanguageInspectorDock::connectToEditor); } }); } LanguageInspectorDock::~LanguageInspectorDock() { delete ui; } void LanguageInspectorDock::connectToEditor(ScintillaNext *editor) { disconnectFromEditor(); editorConnection = connect(editor, &ScintillaNext::updateUi, this, &LanguageInspectorDock::updatePositionInfo); documentConnection = connect(editor, &ScintillaNext::lexerChanged, this, [=]() { updateLexerInfo(editor); }); updateLexerInfo(editor); } void LanguageInspectorDock::disconnectFromEditor() { if (editorConnection) { disconnect(editorConnection); } if (documentConnection) { disconnect(documentConnection); } } void LanguageInspectorDock::updatePositionInfo(Scintilla::Update updated) { if (FlagSet(updated, Scintilla::Update::Content) || FlagSet(updated, Scintilla::Update::Selection)) { ScintillaNext *editor = qobject_cast<ScintillaNext*>(sender()); ui->lblInfo->setText(tr("Position %1 Style %2").arg(editor->currentPos()).arg(editor->styleAt(editor->currentPos()))); } } void LanguageInspectorDock::updateLexerInfo(ScintillaNext *editor) { updateLanguageName(editor); updatePropertyInfo(editor); updateKeywordInfo(editor); updateStyleInfo(editor); } void LanguageInspectorDock::updateLanguageName(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); ui->editLanguage->setText(editor->languageName); ui->editLexer->setText(editor->lexerLanguage()); } void LanguageInspectorDock::updatePropertyInfo(ScintillaNext *editor) { const QSignalBlocker blocker(ui->tblProperties); ui->tblProperties->clearContents(); const QString propertyNames = editor->propertyNames(); if (propertyNames.isEmpty()) { ui->tblProperties->setRowCount(0); } else { QStringList propertyNamesList = propertyNames.split('\n'); ui->tblProperties->setRowCount(propertyNamesList.count()); for (int i = 0; i < propertyNamesList.count(); ++i) { const auto property = propertyNamesList[i]; QTableWidgetItem *prop = new QTableWidgetItem(property); QTableWidgetItem *type = new QTableWidgetItem(property_type_to_string(editor->propertyType(property.toLatin1().constData()))); QTableWidgetItem *desc = new QTableWidgetItem(QString(editor->describeProperty(property.toLatin1().constData()))); QTableWidgetItem *val = new QTableWidgetItem(QString(editor->property(property.toLatin1().constData()))); desc->setToolTip(desc->text()); prop->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); type->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); desc->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); val->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable); val->setTextAlignment(Qt::AlignCenter); ui->tblProperties->setItem(i, 0, prop); ui->tblProperties->setItem(i, 1, type); ui->tblProperties->setItem(i, 2, desc); ui->tblProperties->setItem(i, 3, val); } } ui->tblProperties->resizeColumnToContents(0); ui->tblProperties->resizeColumnToContents(1); ui->tblProperties->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); ui->tblProperties->resizeColumnToContents(3); ui->tblProperties->disconnect(); connect(ui->tblProperties, &QTableWidget::itemChanged, this, [=](QTableWidgetItem *item) { const QString property = ui->tblProperties->item(item->row(), 0)->text(); editor->setProperty(property.toLatin1().constData(), item->text().toLatin1().constData()); editor->colourise(0, -1); }); } void LanguageInspectorDock::updateKeywordInfo(ScintillaNext *editor) { ui->tblKeywords->clearContents(); const QString keyWordSetsDescription = QString(editor->describeKeyWordSets()); if (keyWordSetsDescription.isEmpty()) { ui->tblKeywords->setRowCount(0); } else { QStringList keyWordsSets = keyWordSetsDescription.split('\n'); ui->tblKeywords->setRowCount(keyWordsSets.count()); for (int i = 0; i < keyWordsSets.count(); ++i) { auto id = new QTableWidgetItem(QString::number(i)); id->setTextAlignment(Qt::AlignCenter); ui->tblKeywords->setItem(i, 0, id); ui->tblKeywords->setItem(i, 1, new QTableWidgetItem(keyWordsSets[i])); } } ui->tblKeywords->resizeColumnToContents(0); } void LanguageInspectorDock::updateStyleInfo(ScintillaNext *editor) { if (auto model = ui->tblStyles->model()) { model->deleteLater(); } ui->tblStyles->setModel(new LanguageStylesModel(editor)); ui->tblStyles->resizeColumnToContents(0); ui->tblStyles->resizeColumnToContents(1); ui->tblStyles->resizeColumnToContents(5); ui->tblStyles->resizeColumnToContents(6); ui->tblStyles->resizeColumnToContents(7); ui->tblStyles->resizeColumnToContents(8); ui->tblStyles->resizeColumnToContents(9); ui->tblStyles->resizeColumnToContents(10); ui->tblStyles->resizeColumnToContents(11); ui->tblStyles->resizeColumnToContents(12); ui->tblStyles->resizeColumnToContents(13); ui->tblStyles->resizeColumnToContents(14); ui->tblStyles->resizeColumnToContents(15); ui->tblStyles->resizeColumnToContents(16); ui->tblStyles->resizeColumnToContents(17); ui->tblStyles->resizeColumnToContents(18); }
9,208
C++
.cpp
220
36.372727
138
0.71761
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,342
HexViewerDock.cpp
dail8859_NotepadNext/src/NotepadNext/docks/HexViewerDock.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include <QFontDatabase> #include "MainWindow.h" #include "ScintillaNext.h" #include "HexViewerDock.h" #include "ui_HexViewerDock.h" #include "EditorHexViewerTableModel.h" HexViewerDock::HexViewerDock(MainWindow *parent) : QDockWidget(parent), ui(new Ui::HexViewerDock) { ui->setupUi(this); // Set the font of the table to a monospaced font...not sure how best to do this QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont).family(); ui->tblHexView->setFont(font); connect(this, &QDockWidget::visibilityChanged, this, [=](bool visible) { if (visible) { connectToEditor(parent->currentEditor()); connect(parent, &MainWindow::editorActivated, this, &HexViewerDock::connectToEditor); } else { disconnect(parent, &MainWindow::editorActivated, this, &HexViewerDock::connectToEditor); } }); } HexViewerDock::~HexViewerDock() { delete ui; } void HexViewerDock::connectToEditor(ScintillaNext *editor) { if (auto model = ui->tblHexView->model()) { model->deleteLater(); } EditorHexViewerTableModel *model = new EditorHexViewerTableModel(this); model->setEditor(editor); ui->tblHexView->setModel(model); ui->tblHexView->resizeColumnsToContents(); ui->tblHexView->resizeRowsToContents(); }
2,071
C++
.cpp
56
32.982143
100
0.72691
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,343
FileListDock.cpp
dail8859_NotepadNext/src/NotepadNext/docks/FileListDock.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "FileListDock.h" #include "ApplicationSettings.h" #include "ui_FileListDock.h" #include "MainWindow.h" ApplicationSetting<bool> sortByName{"FileList/SortByName", false}; FileListDock::FileListDock(MainWindow *parent) : QDockWidget(parent), ui(new Ui::FileList), window(parent) { qInfo(Q_FUNC_INFO); ui->setupUi(this); ui->btnSettings->addAction(ui->actionSortbyFileName); // Set the initial state ApplicationSettings settings; ui->actionSortbyFileName->setChecked(settings.get(sortByName)); // Track it if it changes connect(ui->actionSortbyFileName, &QAction::toggled, this, [=](bool b) { ApplicationSettings settings; settings.set(sortByName, b); refreshList(); }); connect(this, &QDockWidget::visibilityChanged, this, [=](bool visible) { if (visible) { // Only get events when the dock is visible connect(window->getDockedEditor(), &DockedEditor::editorAdded, this, [=](ScintillaNext *editor) { Q_UNUSED(editor); // The editor could get added on any DockArea and doesn't necessarily get appended to the end of the FileList, so refresh everything refreshList(); }); connect(window->getDockedEditor(), &DockedEditor::editorActivated, this, &FileListDock::selectCurrentEditor); connect(window->getDockedEditor(), &DockedEditor::editorClosed, this, &FileListDock::removeEditor); connect(window->getDockedEditor(), &DockedEditor::editorOrderChanged, this, &FileListDock::refreshList); refreshList(); selectCurrentEditor(); } else { // Disconnect all the editors for(int i = 0; i < ui->listWidget->count(); ++i) { QListWidgetItem* item = ui->listWidget->item(i); const ScintillaNext *other = item->data(Qt::UserRole).value<ScintillaNext *>(); disconnect(other, Q_NULLPTR, this, Q_NULLPTR); } // Don't need to clear it but why not ui->listWidget->clear(); // Don't need events from the docked editor either disconnect(window->getDockedEditor(), Q_NULLPTR, this, Q_NULLPTR); } }); connect(ui->listWidget, &QListWidget::itemClicked, this, &FileListDock::itemClicked); } FileListDock::~FileListDock() { delete ui; } void FileListDock::refreshList() { qInfo(Q_FUNC_INFO); ui->listWidget->clear(); QVector<ScintillaNext*> editors = window->getDockedEditor()->editors(); ApplicationSettings settings; if (settings.get(sortByName)) { std::sort(editors.begin(), editors.end(), [](const ScintillaNext* e1, const ScintillaNext* e2) { return QString::compare(e1->getName(), e2->getName(), Qt::CaseInsensitive) < 0; }); } for (ScintillaNext *editor : editors) { addEditor(editor); } selectCurrentEditor(); } void FileListDock::addEditor(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); QListWidgetItem *item = new QListWidgetItem(editor->getName()); item->setToolTip(editor->getName()); item->setIcon(QIcon(":/icons/saved.png")); item->setData(Qt::UserRole, QVariant::fromValue(editor)); item->setIcon(QIcon(editor->canSaveToDisk() ? ":/icons/unsaved.png" : ":/icons/saved.png")); // Need some notifications from the editor itself // NOTE: Cannot use a lambda here because item is not a QObject, and thus cannot be used as a context for Qt to know // when to cancel the connection. If item was a QObject, the lambda is disconnected when the sender or context is destroyed connect(editor, &ScintillaNext::savePointChanged, this, &FileListDock::editorSavePointChanged, Qt::UniqueConnection); connect(editor, &ScintillaNext::renamed, this, &FileListDock::editorRenamed, Qt::UniqueConnection); ui->listWidget->addItem(item); } void FileListDock::removeEditor(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); QListWidgetItem* item = lookupItemByEditor(editor); if (item) { delete ui->listWidget->takeItem(ui->listWidget->row(item)); } } void FileListDock::selectCurrentEditor() { qInfo(Q_FUNC_INFO); ScintillaNext *editor = window->currentEditor(); QListWidgetItem* item = lookupItemByEditor(editor); if (item) { ui->listWidget->setCurrentItem(item); } } void FileListDock::itemClicked(QListWidgetItem *item) { qInfo(Q_FUNC_INFO); ScintillaNext *editor = item->data(Qt::UserRole).value<ScintillaNext *>(); window->getDockedEditor()->switchToEditor(editor); } void FileListDock::editorSavePointChanged(bool dirty) { Q_UNUSED(dirty); qInfo(Q_FUNC_INFO); ScintillaNext *editor = qobject_cast<ScintillaNext *>(sender()); if (editor) { QListWidgetItem* item = lookupItemByEditor(editor); if (item) { const QString iconPath = editor->canSaveToDisk() ? ":/icons/unsaved.png" : ":/icons/saved.png"; item->setIcon(QIcon(iconPath)); } } } void FileListDock::editorRenamed() { qInfo(Q_FUNC_INFO); ScintillaNext *editor = qobject_cast<ScintillaNext *>(sender()); if (editor) { QListWidgetItem* item = lookupItemByEditor(editor); if (item) { item->setText(editor->getName()); item->setToolTip(editor->getName()); } } } QListWidgetItem *FileListDock::lookupItemByEditor(ScintillaNext *editor) { for(int i = 0; i < ui->listWidget->count(); ++i) { QListWidgetItem* item = ui->listWidget->item(i); const ScintillaNext *other = item->data(Qt::UserRole).value<ScintillaNext *>(); if (other == editor) { return item; } } return Q_NULLPTR; }
6,542
C++
.cpp
162
34.259259
148
0.676508
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,344
SearchResultsDock.cpp
dail8859_NotepadNext/src/NotepadNext/docks/SearchResultsDock.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "SearchResultsDock.h" #include "ScintillaNext.h" #include "ui_SearchResultsDock.h" #include <QKeyEvent> #include <QPointer> #include <QMenu> #include <QShortcut> #include <QClipboard> enum SearchResultData { LineNumber = Qt::UserRole, LinePosStart, LinePosEnd }; SearchResultsDock::SearchResultsDock(QWidget *parent) : QDockWidget(parent), ui(new Ui::SearchResultsDock) { ui->setupUi(this); #ifdef Q_OS_MACOS // Set a slightly larger font on MacOS QFont font("Courier New", 14); ui->treeWidget->setFont(font); #endif // Close the results when escape is pressed new QShortcut(QKeySequence::Cancel, this, this, &SearchResultsDock::close, Qt::WidgetWithChildrenShortcut); connect(ui->treeWidget, &QTreeWidget::itemActivated, this, &SearchResultsDock::itemActivated); connect(ui->treeWidget, &QTreeWidget::itemExpanded, this, &SearchResultsDock::itemExpanded); connect(ui->btnCopyResults, &QPushButton::released,this, &SearchResultsDock::copySearchResultsToClipboard); connect(ui->treeWidget, &QTreeWidget::customContextMenuRequested, this, [=](const QPoint &pos) { QTreeWidgetItem *item = ui->treeWidget->itemAt(pos); if (item == Q_NULLPTR) { return; } // Create the menu and show it QMenu menu(this); menu.addAction(tr("Collapse All"), this, &SearchResultsDock::collapseAll); menu.addAction(tr("Expand All"), this, &SearchResultsDock::expandAll); menu.addSeparator(); menu.addAction(tr("Delete Entry"), this, [=]() { deleteEntry(item); }); menu.addSeparator(); menu.addAction(tr("Delete All"), this, &SearchResultsDock::deleteAll); menu.exec(QCursor::pos()); }); } SearchResultsDock::~SearchResultsDock() { delete ui; } void SearchResultsDock::newSearch(const QString searchTerm) { show(); this->searchTerm = searchTerm; for (int i = 0; i < ui->treeWidget->topLevelItemCount(); ++i) { const QTreeWidgetItem* topLevelItem = ui->treeWidget->topLevelItem(i); ui->treeWidget->collapseItem(topLevelItem); } currentSearch = new QTreeWidgetItem(ui->treeWidget); currentSearch->setBackground(0, QColor(232, 232, 255)); currentSearch->setForeground(0, QColor(0, 0, 170)); currentSearch->setExpanded(true); currentSearch->setFirstColumnSpanned(true); updateSearchStatus(); } void SearchResultsDock::newFileEntry(ScintillaNext *editor) { // Store a QPointer since there is no guarantee this editor will be around later QPointer<ScintillaNext> editor_pointer = editor; totalFileHitCount = 0; currentFilePath = editor->isFile() ? editor->getFilePath() : editor->getName(); currentFile = new QTreeWidgetItem(currentSearch); currentFile->setData(0, Qt::UserRole, QVariant::fromValue(editor_pointer)); currentFile->setBackground(0, QColor(213, 255, 213)); currentFile->setForeground(0, QColor(0, 128, 0)); currentFile->setExpanded(true); currentFile->setFirstColumnSpanned(true); currentFileCount++; updateSearchStatus(); } void SearchResultsDock::newResultsEntry(const QString line, int lineNumber, int startPositionFromBeginning, int endPositionFromBeginning, int hitCount) { QTreeWidgetItem *item = new QTreeWidgetItem(currentFile); // Scintilla internally references line numbers starting at 0, however it needs displayed starting at 1 item->setText(0, QString::number(lineNumber + 1)); item->setData(0, SearchResultData::LineNumber, lineNumber); item->setData(0, SearchResultData::LinePosStart, startPositionFromBeginning); item->setData(0, SearchResultData::LinePosEnd, endPositionFromBeginning); item->setBackground(0, QBrush(QColor(220, 220, 220))); item->setTextAlignment(0, Qt::AlignRight); item->setText(1, line); totalFileHitCount += hitCount; totalHitCount += hitCount; updateSearchStatus(); } void SearchResultsDock::completeSearch() { currentSearch = Q_NULLPTR; currentFile = Q_NULLPTR; currentFileCount = 0; totalFileHitCount = 0; totalHitCount = 0; ui->treeWidget->resizeColumnToContents(0); ui->treeWidget->resizeColumnToContents(1); } void SearchResultsDock::collapseAll() const { ui->treeWidget->collapseAll(); } void SearchResultsDock::expandAll() const { ui->treeWidget->expandAll(); } void SearchResultsDock::deleteEntry(QTreeWidgetItem *item) { QTreeWidgetItem *parent = item->parent(); if (parent != Q_NULLPTR) { parent->removeChild(item); delete item; } else { const int index = ui->treeWidget->indexOfTopLevelItem(item); delete ui->treeWidget->takeTopLevelItem(index); } } void SearchResultsDock::deleteAll() { ui->treeWidget->clear(); } void SearchResultsDock::itemActivated(QTreeWidgetItem *item, int column) { Q_UNUSED(column); // Result entries have no children // Make sure the entry has a parent since search entries can have no children if (item->childCount() == 0 && item->parent() != Q_NULLPTR) { QPointer<ScintillaNext> editor = item->parent()->data(0, Qt::UserRole).value<QPointer<ScintillaNext>>(); // The editor may no longer exist if (editor) { int lineNumber = item->data(0, SearchResultData::LineNumber).toInt(); int startPositionFromBeginning = item->data(0, SearchResultData::LinePosStart).toInt(); int endPositionFromBeginning = item->data(0, SearchResultData::LinePosEnd).toInt(); emit searchResultActivated(editor, lineNumber, startPositionFromBeginning, endPositionFromBeginning); } } } void SearchResultsDock::itemExpanded(QTreeWidgetItem *) { ui->treeWidget->resizeColumnToContents(1); } void SearchResultsDock::updateSearchStatus() { currentSearch->setText(0, QStringLiteral("Search \"%1\" (%L2 hits in %L3 files)").arg(searchTerm).arg(totalHitCount).arg(currentFileCount)); if (currentFile) currentFile->setText(0, QStringLiteral("%1 (%L2 hits)").arg(currentFilePath).arg(totalFileHitCount)); } void SearchResultsDock::copySearchResultsToClipboard() { QStringList results; QTreeWidgetItemIterator it(ui->treeWidget); while (*it) { const QTreeWidgetItem *item = *it; results.append(QStringLiteral("%1 %2").arg(item->text(0)).arg(item->text(1))); ++it; } QGuiApplication::clipboard()->setText(results.join('\n')); }
7,219
C++
.cpp
183
34.896175
151
0.722747
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,345
FolderAsWorkspaceDock.cpp
dail8859_NotepadNext/src/NotepadNext/docks/FolderAsWorkspaceDock.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "FolderAsWorkspaceDock.h" #include "ApplicationSettings.h" #include "ui_FolderAsWorkspaceDock.h" #include <QFileSystemModel> ApplicationSetting<QString> rootPathSetting{"FolderAsWorkspace/RootPath"}; FolderAsWorkspaceDock::FolderAsWorkspaceDock(QWidget *parent) : QDockWidget(parent), ui(new Ui::FolderAsWorkspaceDock), model(new QFileSystemModel(this)) { ui->setupUi(this); ui->treeView->setModel(model); ui->treeView->header()->hideSection(1); ui->treeView->header()->hideSection(2); ui->treeView->header()->hideSection(3); connect(ui->treeView, &QTreeView::doubleClicked, this, [=](const QModelIndex &index) { if (!model->isDir(index)) { emit fileDoubleClicked(model->filePath(index)); } }); ApplicationSettings settings; setRootPath(settings.get(rootPathSetting)); } FolderAsWorkspaceDock::~FolderAsWorkspaceDock() { delete ui; } void FolderAsWorkspaceDock::setRootPath(const QString dir) { ApplicationSettings settings; settings.set(rootPathSetting, dir); model->setRootPath(dir); ui->treeView->setRootIndex(model->index(dir)); } QString FolderAsWorkspaceDock::rootPath() const { return model->rootPath(); }
1,961
C++
.cpp
55
32.327273
90
0.748152
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,346
MacroEditorDialog.cpp
dail8859_NotepadNext/src/NotepadNext/dialogs/MacroEditorDialog.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include <QItemSelectionModel> #include <QMessageBox> #include <QModelIndex> #include "MacroEditorDialog.h" #include "ComboBoxDelegate.h" #include "ui_MacroEditorDialog.h" MacroEditorDialog::MacroEditorDialog(QWidget *parent, MacroManager *mm) : QDialog(parent), ui(new Ui::MacroEditorDialog), macroManager(mm), model(new MacroListModel(this, mm)) { setWindowFlag(Qt::WindowContextHelpButtonHint, false); ui->setupUi(this); ui->listMacros->setModel(model); connect(ui->listMacros->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &MacroEditorDialog::rowChanged); connect(ui->btnCopyMacro, &QPushButton::clicked, this, &MacroEditorDialog::copyCurrentMacro); connect(ui->btnDeleteMacro, &QPushButton::clicked, this, &MacroEditorDialog::deleteCurrentMacro); connect(ui->editMacroName, &QLineEdit::textChanged, this, &MacroEditorDialog::macroNameChanged); connect(ui->btnInsertMacroStep, &QPushButton::clicked, this, &MacroEditorDialog::insertMacroStep); connect(ui->btnDeleteMacroStep, &QPushButton::clicked, this, &MacroEditorDialog::deleteMacroStep); connect(ui->btnMoveMacroStepUp, &QPushButton::clicked, this, &MacroEditorDialog::moveMacroStepUp); connect(ui->btnMoveMacroStepDown, &QPushButton::clicked, this, &MacroEditorDialog::moveMacroStepDown); QList<ComboBoxItem> recordableMacroMessages; for (Scintilla::Message msg : MacroStep::RecordableMacroMessages()) { recordableMacroMessages.append(qMakePair(MacroStep::NameOfMessage(msg), static_cast<int>(msg))); } ui->tblMacroSteps->setItemDelegateForColumn(0, new ComboBoxDelegate(recordableMacroMessages, this)); ui->listMacros->setCurrentIndex(model->index(0)); } MacroEditorDialog::~MacroEditorDialog() { delete ui; } void MacroEditorDialog::rowChanged(const QModelIndex &current, const QModelIndex &previous) { Q_UNUSED(previous); if (!current.isValid()){ ui->editMacroName->setReadOnly(true); ui->editMacroName->clear(); ui->keyMacroShortcut->clear(); if (auto model = ui->tblMacroSteps->model()) { model->deleteLater(); } return; } else { ui->editMacroName->setReadOnly(false); Macro *macro = model->macro(current); ui->editMacroName->setText(macro->getName()); // Replace the existing model if (auto model = ui->tblMacroSteps->model()) { model->deleteLater(); } ui->tblMacroSteps->setModel(new MacroStepTableModel(macro, this)); // Resize some stuff now that we have a new model ui->tblMacroSteps->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); ui->tblMacroSteps->resizeRowsToContents(); ui->tblMacroSteps->resizeColumnToContents(0); } } void MacroEditorDialog::macroNameChanged(const QString &text) { // Ensure there is a non-blank name if (text.trimmed().isEmpty()) { ui->editMacroName->setStyleSheet("QLineEdit{border: 2px solid red}"); return; } else { ui->editMacroName->setStyleSheet(""); } QModelIndex currentIndex = ui->listMacros->selectionModel()->currentIndex(); if (currentIndex.isValid()) { Macro *macro = model->macro(currentIndex); macro->setName(text); // Since the macro was edited directly, need to notify the model this index changed emit model->dataChanged(currentIndex, currentIndex); } } void MacroEditorDialog::deleteCurrentMacro() { QModelIndex currentIndex = ui->listMacros->selectionModel()->currentIndex(); if (currentIndex.isValid()) { const QString macroName = currentIndex.data(Qt::DisplayRole).toString(); QMessageBox::StandardButton reply = QMessageBox::question(this, tr("Delete Macro"), tr("Are you sure you want to delete <b>%1</b>?").arg(macroName)); if (reply == QMessageBox::Yes) { model->removeRow(currentIndex.row()); } } } void MacroEditorDialog::copyCurrentMacro() { QModelIndex currentIndex = ui->listMacros->selectionModel()->currentIndex(); if (currentIndex.isValid()) { Macro *originalMacro = model->macro(currentIndex); model->insertRows(currentIndex.row() + 1, 1); Macro *newMacro = model->macro(model->index(currentIndex.row() + 1)); // TODO: move this into a copy constructor in the Macro class? newMacro->setName(originalMacro->getName() + " " + tr("(Copy)")); for (const MacroStep &step : qAsConst(originalMacro->getSteps())) { newMacro->addMacroStep(step); } // Select the newly created macro ui->listMacros->setCurrentIndex(model->index(currentIndex.row() + 1)); } } void MacroEditorDialog::insertMacroStep() { QModelIndex currentIndex = ui->tblMacroSteps->selectionModel()->currentIndex(); if (currentIndex.isValid()) { ui->tblMacroSteps->model()->insertRows(currentIndex.row() + 1, 1); ui->tblMacroSteps->setCurrentIndex(ui->tblMacroSteps->model()->index(currentIndex.row() + 1, 0)); } else { ui->tblMacroSteps->model()->insertRows(0, 1); ui->tblMacroSteps->setCurrentIndex(ui->tblMacroSteps->model()->index(0, 0)); } // Resize things if needed ui->tblMacroSteps->resizeRowsToContents(); ui->tblMacroSteps->resizeColumnToContents(0); } void MacroEditorDialog::deleteMacroStep() { QModelIndex currentIndex = ui->tblMacroSteps->selectionModel()->currentIndex(); if (currentIndex.isValid()) { ui->tblMacroSteps->model()->removeRow(currentIndex.row()); } } void MacroEditorDialog::moveMacroStepUp() { QModelIndex currentIndex = ui->tblMacroSteps->selectionModel()->currentIndex(); if (currentIndex.isValid() && currentIndex.row() != 0) { // This does not make sense to me, start at the previous index and move it to the next index, but it works ui->tblMacroSteps->model()->moveRow(QModelIndex(), currentIndex.row() - 1, QModelIndex(), currentIndex.row() + 1); } } void MacroEditorDialog::moveMacroStepDown() { QModelIndex currentIndex = ui->tblMacroSteps->selectionModel()->currentIndex(); if (currentIndex.isValid() && currentIndex.row() != ui->tblMacroSteps->model()->rowCount() - 1) { // This also does not make ense, start at the current index and skip two ui->tblMacroSteps->model()->moveRow(QModelIndex(), currentIndex.row(), QModelIndex(), currentIndex.row() + 2); } }
7,248
C++
.cpp
161
39.590062
157
0.707043
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,347
MacroSaveDialog.cpp
dail8859_NotepadNext/src/NotepadNext/dialogs/MacroSaveDialog.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "MacroSaveDialog.h" #include "ui_MacroSaveDialog.h" MacroSaveDialog::MacroSaveDialog(QWidget *parent) : QDialog(parent), ui(new Ui::MacroSaveDialog) { setWindowFlag(Qt::WindowContextHelpButtonHint, false); ui->setupUi(this); connect(ui->editName, &QLineEdit::textChanged, [=](const QString &text) { ui->buttonOk->setEnabled(text.trimmed().size() > 0); }); } MacroSaveDialog::~MacroSaveDialog() { delete ui; } QString MacroSaveDialog::getName() const { return ui->editName->text(); } QKeySequence MacroSaveDialog::getShortcut() const { return ui->keySequenceEdit->keySequence(); }
1,368
C++
.cpp
41
30.707317
77
0.745262
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,348
MainWindow.cpp
dail8859_NotepadNext/src/NotepadNext/dialogs/MainWindow.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "MainWindow.h" #include "BookMarkDecorator.h" #include "URLFinder.h" #include "SessionManager.h" #include "UndoAction.h" #include "ui_MainWindow.h" #include <QFileDialog> #include <QMessageBox> #include <QStringList> #include <QClipboard> #include <QStandardPaths> #include <QWindow> #include <QPushButton> #include <QTimer> #include <QInputDialog> #include <QPrintPreviewDialog> #include <QPrinter> #include <QDirIterator> #include <QProcess> #include <QScreen> #ifdef Q_OS_WIN #include <QSimpleUpdater.h> #include <Windows.h> #endif #include "DockAreaWidget.h" #include "NotepadNextApplication.h" #include "ApplicationSettings.h" #include "ScintillaNext.h" #include "RecentFilesListManager.h" #include "RecentFilesListMenuBuilder.h" #include "EditorManager.h" #include "LuaConsoleDock.h" #include "LanguageInspectorDock.h" #include "EditorInspectorDock.h" #include "FolderAsWorkspaceDock.h" #include "SearchResultsDock.h" #include "DebugLogDock.h" #include "HexViewerDock.h" #include "FileListDock.h" #include "FindReplaceDialog.h" #include "MacroRunDialog.h" #include "MacroSaveDialog.h" #include "PreferencesDialog.h" #include "ColumnEditorDialog.h" #include "QuickFindWidget.h" #include "EditorPrintPreviewRenderer.h" #include "MacroEditorDialog.h" #include "ZoomEventWatcher.h" #include "FileDialogHelpers.h" #include "HtmlConverter.h" #include "RtfConverter.h" #include "FadingIndicator.h" MainWindow::MainWindow(NotepadNextApplication *app) : ui(new Ui::MainWindow), app(app), zoomEventWatcher(new ZoomEventWatcher(this)) { qInfo(Q_FUNC_INFO); setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); applyCustomShortcuts(); qInfo("setupUi Completed"); connect(this, &MainWindow::aboutToClose, this, &MainWindow::saveSettings); // Create and set up the connections to the docked editor dockedEditor = new DockedEditor(this); connect(dockedEditor, &DockedEditor::editorCloseRequested, this, [=](ScintillaNext *editor) { closeFile(editor); }); connect(dockedEditor, &DockedEditor::editorActivated, this, &MainWindow::activateEditor); connect(dockedEditor, &DockedEditor::contextMenuRequestedForEditor, this, &MainWindow::tabBarRightClicked); connect(dockedEditor, &DockedEditor::titleBarDoubleClicked, this, &MainWindow::newFile); // Set up the menus connect(ui->actionNew, &QAction::triggered, this, &MainWindow::newFile); connect(ui->actionOpen, &QAction::triggered, this, &MainWindow::openFileDialog); connect(ui->actionReload, &QAction::triggered, this, &MainWindow::reloadFile); connect(ui->actionClose, &QAction::triggered, this, &MainWindow::closeCurrentFile); connect(ui->actionCloseAll, &QAction::triggered, this, &MainWindow::closeAllFiles); connect(ui->actionExit, &QAction::triggered, this, &MainWindow::close); #ifdef Q_OS_WIN ui->actionExit->setShortcut(QKeySequence("Alt+F4")); #else ui->actionExit->setShortcut(QKeySequence::Quit); #endif connect(ui->actionOpenFolderasWorkspace, &QAction::triggered, this, &MainWindow::openFolderAsWorkspaceDialog); connect(ui->actionCloseAllExceptActive, &QAction::triggered, this, &MainWindow::closeAllExceptActive); connect(ui->actionCloseAllToLeft, &QAction::triggered, this, &MainWindow::closeAllToLeft); connect(ui->actionCloseAllToRight, &QAction::triggered, this, &MainWindow::closeAllToRight); connect(ui->actionSave, &QAction::triggered, this, &MainWindow::saveCurrentFile); connect(ui->actionSaveAs, &QAction::triggered, this, &MainWindow::saveCurrentFileAsDialog); connect(ui->actionSaveCopyAs, &QAction::triggered, this, &MainWindow::saveCopyAsDialog); connect(ui->actionSaveAll, &QAction::triggered, this, &MainWindow::saveAll); connect(ui->actionRename, &QAction::triggered, this, &MainWindow::renameFile); connect(ui->actionExportHtml, &QAction::triggered, this, [=]() { HtmlConverter html(currentEditor()); exportAsFormat(&html, QStringLiteral("HTML files (*.html)")); }); connect(ui->actionExportRtf, &QAction::triggered, this, [=]() { RtfConverter rtf(currentEditor()); exportAsFormat(&rtf, QStringLiteral("RTF Files (*.rtf)")); }); connect(ui->actionPrint, &QAction::triggered, this, &MainWindow::print); connect(ui->actionToggleSingleLineComment, &QAction::triggered, this, [=]() { currentEditor()->toggleCommentSelection(); }); connect(ui->actionSingleLineComment, &QAction::triggered, this, [=]() { currentEditor()->commentLineSelection(); }); connect(ui->actionSingleLineUncomment, &QAction::triggered, this, [=]() { currentEditor()->uncommentLineSelection(); }); connect(ui->actionBase64Encode,&QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); const QByteArray selection = currentEditor()->getSelText(); editor->replaceSel(selection.toBase64().constData()); }); connect(ui->actionURLEncode,&QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); const QByteArray selection = currentEditor()->getSelText(); editor->replaceSel(selection.toPercentEncoding().constData()); }); connect(ui->actionBase64Decode,&QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); const QByteArray selection = editor->getSelText(); if (auto result = QByteArray::fromBase64Encoding(selection)) { editor->replaceSel((*result).constData()); } }); connect(ui->actionURLDecode,&QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); const QByteArray selection = editor->getSelText(); editor->replaceSel(QByteArray::fromPercentEncoding(selection).constData()); }); connect(ui->actionCopyURL, &QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); URLFinder *urlFinder = editor->findChild<URLFinder *>(QString(), Qt::FindDirectChildrenOnly); if (urlFinder && urlFinder->isEnabled()) { urlFinder->copyURLToClipboard(contextMenuPos); } }); connect(ui->actionClearRecentFilesList, &QAction::triggered, app->getRecentFilesListManager(), &RecentFilesListManager::clear); connect(ui->actionMoveToTrash, &QAction::triggered, this, &MainWindow::moveCurrentFileToTrash); RecentFilesListMenuBuilder *recentFileListMenuBuilder = new RecentFilesListMenuBuilder(app->getRecentFilesListManager()); connect(ui->menuRecentFiles, &QMenu::aboutToShow, this, [=]() { // NOTE: its unfortunate that this has to be hard coded, but there's no way // to easily determine what should or shouldn't be there while (ui->menuRecentFiles->actions().size() > 4) { delete ui->menuRecentFiles->actions().takeLast(); } recentFileListMenuBuilder->populateMenu(ui->menuRecentFiles); }); connect(ui->actionRestoreRecentlyClosedFile, &QAction::triggered, this, [=]() { if (app->getRecentFilesListManager()->count() > 0) { openFileList(QStringList() << app->getRecentFilesListManager()->mostRecentFile()); } }); connect(ui->actionOpenAllRecentFiles, &QAction::triggered, this, [=]() { openFileList(app->getRecentFilesListManager()->fileList()); }); connect(recentFileListMenuBuilder, &RecentFilesListMenuBuilder::fileOpenRequest, this, &MainWindow::openFile); QActionGroup *eolActionGroup = new QActionGroup(this); eolActionGroup->addAction(ui->actionWindows); eolActionGroup->addAction(ui->actionUnix); eolActionGroup->addAction(ui->actionMacintosh); connect(ui->actionWindows, &QAction::triggered, this, [=]() { convertEOLs(SC_EOL_CRLF); }); connect(ui->actionUnix, &QAction::triggered, this, [=]() { convertEOLs(SC_EOL_LF); }); connect(ui->actionMacintosh, &QAction::triggered, this, [=]() { convertEOLs(SC_EOL_CR); }); connect(ui->actionUpperCase, &QAction::triggered, this, [=]() { currentEditor()->upperCase(); }); connect(ui->actionLowerCase, &QAction::triggered, this, [=]() { currentEditor()->lowerCase(); }); connect(ui->actionDuplicateCurrentLine, &QAction::triggered, this, [=]() { currentEditor()->lineDuplicate(); }); connect(ui->actionMoveSelectedLinesUp, &QAction::triggered, this, [=]() { currentEditor()->moveSelectedLinesUp(); }); connect(ui->actionMoveSelectedLinesDown, &QAction::triggered, this, [=]() { currentEditor()->moveSelectedLinesDown(); }); connect(ui->actionSplitLines, &QAction::triggered, this, [=]() { currentEditor()->targetFromSelection(); currentEditor()->linesSplit(0); }); connect(ui->actionJoinLines, &QAction::triggered, this, [=]() { currentEditor()->targetFromSelection(); currentEditor()->linesJoin(); }); connect(ui->actionRemoveEmptyLines, &QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); Finder f(editor); const UndoAction ua(editor); f.setSearchText(QStringLiteral("\\R\\R+")); f.setSearchFlags(SCFIND_REGEXP); f.replaceAll(editor->eolString()); // The regex will not entirely remove a blank first line editor->deleteLeadingEmptyLines(); // Regex will also not delete the final blank line editor->deleteTrailingEmptyLines(); }); connect(ui->actionColumnMode, &QAction::triggered, this, [=]() { ColumnEditorDialog *columnEditor = findChild<ColumnEditorDialog *>(QString(), Qt::FindDirectChildrenOnly); if (columnEditor == Q_NULLPTR) { columnEditor = new ColumnEditorDialog(this); } columnEditor->show(); columnEditor->raise(); columnEditor->activateWindow(); }); connect(ui->actionUndo, &QAction::triggered, this, [=]() { currentEditor()->undo(); }); connect(ui->actionRedo, &QAction::triggered, this, [=]() { currentEditor()->redo(); }); connect(ui->actionCut, &QAction::triggered, this, [=]() { currentEditor()->cutAllowLine(); }); connect(ui->actionCopy, &QAction::triggered, this, [=]() { currentEditor()->copyAllowLine(); }); connect(ui->actionDelete, &QAction::triggered, this, [=]() { currentEditor()->clear(); }); connect(ui->actionPaste, &QAction::triggered, this, [=]() { currentEditor()->paste(); }); connect(ui->actionSelectAll, &QAction::triggered, this, [=]() { currentEditor()->selectAll(); }); connect(ui->actionSelectNext, &QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); editor->setSearchFlags(SCFIND_NONE); editor->targetWholeDocument(); editor->multipleSelectAddNext(); }); connect(ui->actionCopyFullPath, &QAction::triggered, this, [=]() { auto editor = currentEditor(); if (editor->isFile()) { QApplication::clipboard()->setText(editor->getFilePath()); } }); connect(ui->actionCopyFileName, &QAction::triggered, this, [=]() { QApplication::clipboard()->setText(currentEditor()->getName()); }); connect(ui->actionCopyFileDirectory, &QAction::triggered, this, [=]() { auto editor = currentEditor(); if (editor->isFile()) { QApplication::clipboard()->setText(editor->getPath()); } }); connect(ui->actionCopyAsHtml, &QAction::triggered, this, [=]() { HtmlConverter html(currentEditor()); copyAsFormat(&html, "text/html"); }); connect(ui->actionCopyAsRtf, &QAction::triggered, this, [=]() { RtfConverter rtf(currentEditor()); copyAsFormat(&rtf, "Rich Text Format"); }); connect(ui->actionIncrease_Indent, &QAction::triggered, this, [=]() { currentEditor()->tab(); }); connect(ui->actionDecrease_Indent, &QAction::triggered, this, [=]() { currentEditor()->backTab(); }); addAction(ui->actionToggleOverType); connect(ui->actionToggleOverType, &QAction::triggered, this, [=]() { currentEditor()->editToggleOvertype(); ui->statusBar->refresh(currentEditor()); }); SearchResultsDock *srDock = new SearchResultsDock(this); addDockWidget(Qt::BottomDockWidgetArea, srDock); srDock->toggleViewAction()->setShortcut(Qt::Key_F7); ui->menuView->addAction(srDock->toggleViewAction()); connect(srDock, &SearchResultsDock::searchResultActivated, this, [=](ScintillaNext *editor, int lineNumber, int startPositionFromBeginning, int endPositionFromBeginning) { dockedEditor->switchToEditor(editor); int linePos = editor->positionFromLine(lineNumber); editor->goToRange({linePos + startPositionFromBeginning, linePos + endPositionFromBeginning}); editor->verticalCentreCaret(); editor->grabFocus(); }); connect(ui->actionFind, &QAction::triggered, this, [=]() { showFindReplaceDialog(FindReplaceDialog::FIND_TAB); }); connect(ui->actionFindNext, &QAction::triggered, this, [=]() { FindReplaceDialog *f = findChild<FindReplaceDialog *>(QString(), Qt::FindDirectChildrenOnly); if (f) { f->performLastSearch(); } }); connect(ui->actionQuickFind, &QAction::triggered, this, [=]() { QuickFindWidget *quickFind = findChild<QuickFindWidget *>(QString(), Qt::FindDirectChildrenOnly); if (quickFind == Q_NULLPTR) { quickFind = new QuickFindWidget(this); } quickFind->setEditor(currentEditor()); quickFind->setFocus(); quickFind->show(); }); connect(ui->actionReplace, &QAction::triggered, this, [=]() { showFindReplaceDialog(FindReplaceDialog::REPLACE_TAB); }); connect(ui->actionGoToLine, &QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); const int currentLine = editor->lineFromPosition(editor->currentPos()) + 1; const int maxLine = editor->lineCount(); bool ok; QInputDialog d = QInputDialog(this); Qt::WindowFlags flags = d.windowFlags() & ~Qt::WindowContextHelpButtonHint; int lineToGoTo = d.getInt(this, tr("Go to line"), tr("Line Number (1 - %1)").arg(maxLine), currentLine, 1, maxLine, 1, &ok, flags); if (ok) { editor->ensureVisible(lineToGoTo - 1); editor->gotoLine(lineToGoTo - 1); editor->verticalCentreCaret(); } }); connect(ui->actionToggleBookmark, &QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); BookMarkDecorator *bookMarkDecorator = editor->findChild<BookMarkDecorator*>(QString(), Qt::FindDirectChildrenOnly); if (bookMarkDecorator && bookMarkDecorator->isEnabled()) { editor->forEachLineInSelection(editor->mainSelection(), [&](int line) { bookMarkDecorator->toggleBookmark(line); }); } }); connect(ui->actionNextBookmark, &QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); BookMarkDecorator *bookMarkDecorator = editor->findChild<BookMarkDecorator*>(QString(), Qt::FindDirectChildrenOnly); if (bookMarkDecorator && bookMarkDecorator->isEnabled()) { int currentLine = editor->lineFromPosition(editor->currentPos()); int nextBookmarkedLine = bookMarkDecorator->nextBookmarkAfter(currentLine + 1); if (nextBookmarkedLine != -1) { editor->ensureVisibleEnforcePolicy(nextBookmarkedLine); editor->gotoLine(nextBookmarkedLine); } } }); connect(ui->actionClearBookmarks, &QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); BookMarkDecorator *bookMarkDecorator = editor->findChild<BookMarkDecorator*>(QString(), Qt::FindDirectChildrenOnly); if (bookMarkDecorator && bookMarkDecorator->isEnabled()) { bookMarkDecorator->clearBookmarks(); } }); connect(ui->actionInvertBookmarks, &QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); BookMarkDecorator *bookMarkDecorator = editor->findChild<BookMarkDecorator*>(QString(), Qt::FindDirectChildrenOnly); if (bookMarkDecorator && bookMarkDecorator->isEnabled()) { for (int line = 0; line < editor->lineCount(); line++) { bookMarkDecorator->toggleBookmark(line); } } }); connect(ui->actionPreviousBookmark, &QAction::triggered, this, [=]() { ScintillaNext *editor = currentEditor(); BookMarkDecorator *bookMarkDecorator = editor->findChild<BookMarkDecorator*>(QString(), Qt::FindDirectChildrenOnly); if (bookMarkDecorator && bookMarkDecorator->isEnabled()) { int currentLine = editor->lineFromPosition(editor->currentPos()); int prevBookmarkedLine = bookMarkDecorator->previousBookMarkBefore(currentLine - 1); if (prevBookmarkedLine != -1) { editor->ensureVisibleEnforcePolicy(prevBookmarkedLine); editor->gotoLine(prevBookmarkedLine); } } }); // The action needs added to the window so it can be triggered via the keyboard addAction(ui->actionNextTab); connect(ui->actionNextTab, &QAction::triggered, this, [=]() { int index = dockedEditor->currentDockArea()->currentIndex(); int total = dockedEditor->currentDockArea()->dockWidgetsCount(); index++; dockedEditor->currentDockArea()->setCurrentIndex(index < total ? index : 0); }); // The action needs added to the window so it can be triggered via the keyboard addAction(ui->actionPreviousTab); connect(ui->actionPreviousTab, &QAction::triggered, this, [=]() { int index = dockedEditor->currentDockArea()->currentIndex(); int total = dockedEditor->currentDockArea()->dockWidgetsCount(); index--; dockedEditor->currentDockArea()->setCurrentIndex(index >= 0 ? index : total - 1); }); ui->pushExitFullScreen->setParent(this); // This is important ui->pushExitFullScreen->setVisible(false); connect(ui->pushExitFullScreen, &QPushButton::clicked, ui->actionFullScreen, &QAction::trigger); connect(ui->actionFullScreen, &QAction::triggered, this, [=](bool b) { static bool wasMaximized; if (b) { // NOTE: don't hide() these as it will cancel their actions they hold ui->menuBar->setMaximumHeight(0); ui->mainToolBar->setMaximumHeight(0); wasMaximized = isMaximized(); if (wasMaximized) { // By default when calling showMaximized() from a full screen state, the window will resize // to its "normal" size and then immediately resize to the "maximized" size which is very ugly. // By calling setGeometry() to the size of the screen, it at least alleviates the ugly animation // going from: fullscreen -> small "normal" size -> full size of screen setGeometry(screen()->availableGeometry()); } showFullScreen(); ui->pushExitFullScreen->setGeometry(width() - 20, 0, 20, 20); ui->pushExitFullScreen->show(); ui->pushExitFullScreen->raise(); } else { ui->menuBar->setMaximumHeight(QWIDGETSIZE_MAX); ui->mainToolBar->setMaximumHeight(QWIDGETSIZE_MAX); if (wasMaximized) showMaximized(); else showNormal(); ui->pushExitFullScreen->hide(); } }); // Show All Characters is just a short cut to toggle whitespace and EOL on ui->actionShowAllCharacters->setChecked(app->getSettings()->showWhitespace() && app->getSettings()->showEndOfLine()); connect(ui->actionShowAllCharacters, &QAction::triggered, app->getSettings(), &ApplicationSettings::setShowWhitespace); connect(ui->actionShowAllCharacters, &QAction::triggered, app->getSettings(), &ApplicationSettings::setShowEndOfLine); // Show White Space ui->actionShowWhitespace->setChecked(app->getSettings()->showWhitespace()); connect(app->getSettings(), &ApplicationSettings::showWhitespaceChanged, ui->actionShowWhitespace, &QAction::setChecked); connect(ui->actionShowWhitespace, &QAction::toggled, app->getSettings(), &ApplicationSettings::setShowWhitespace); // Update the "Show All Character" action connect(ui->actionShowWhitespace, &QAction::toggled, this, [=](bool b) { ui->actionShowAllCharacters->setChecked(b && ui->actionShowEndofLine->isChecked()); }); // Show EOL ui->actionShowEndofLine->setChecked(app->getSettings()->showEndOfLine()); connect(app->getSettings(), &ApplicationSettings::showEndOfLineChanged, ui->actionShowEndofLine, &QAction::setChecked); connect(ui->actionShowEndofLine, &QAction::toggled, app->getSettings(), &ApplicationSettings::setShowEndOfLine); // Update the "Show All Character" action connect(ui->actionShowEndofLine, &QAction::toggled, this, [=](bool b) { ui->actionShowAllCharacters->setChecked(b && ui->actionShowWhitespace->isChecked()); }); // Show Wrap Symbol ui->actionShowWrapSymbol->setChecked(app->getSettings()->showWrapSymbol()); connect(app->getSettings(), &ApplicationSettings::showWrapSymbolChanged, ui->actionShowWrapSymbol, &QAction::setChecked); connect(ui->actionShowWrapSymbol, &QAction::toggled, app->getSettings(), &ApplicationSettings::setShowWrapSymbol); // Show Indentation Guide ui->actionShowIndentGuide->setChecked(app->getSettings()->showIndentGuide()); connect(app->getSettings(), &ApplicationSettings::showIndentGuideChanged, ui->actionShowIndentGuide, &QAction::setChecked); connect(ui->actionShowIndentGuide, &QAction::toggled, app->getSettings(), &ApplicationSettings::setShowIndentGuide); // Word Wrap ui->actionWordWrap->setChecked(app->getSettings()->wordWrap()); connect(app->getSettings(), &ApplicationSettings::wordWrapChanged, ui->actionWordWrap, &QAction::setChecked); connect(ui->actionWordWrap, &QAction::toggled, app->getSettings(), &ApplicationSettings::setWordWrap); // Zooming controls all editors simulaneously connect(ui->actionZoomIn, &QAction::triggered, this, [=]() { for (ScintillaNext *editor : editors()) { editor->zoomIn(); } zoomLevel = currentEditor()->zoom(); showEditorZoomLevelIndicator(); }); connect(ui->actionZoomOut, &QAction::triggered, this, [=]() { for (ScintillaNext *editor : editors()) { editor->zoomOut(); } zoomLevel = currentEditor()->zoom(); showEditorZoomLevelIndicator(); }); connect(ui->actionZoomReset, &QAction::triggered, this, [=]() { for (ScintillaNext *editor : editors()) { editor->setZoom(0); } zoomLevel = 0; showEditorZoomLevelIndicator(); }); // Zoom watcher has detected a zoom event, so just trigger the UI action connect(zoomEventWatcher, &ZoomEventWatcher::zoomIn, ui->actionZoomIn, &QAction::trigger); connect(zoomEventWatcher, &ZoomEventWatcher::zoomOut, ui->actionZoomOut, &QAction::trigger); connect(ui->actionFoldAll, &QAction::triggered, this, [=]() { currentEditor()->foldAll(SC_FOLDACTION_CONTRACT | SC_FOLDACTION_CONTRACT_EVERY_LEVEL); }); connect(ui->actionUnfoldAll, &QAction::triggered, this, [=]() { currentEditor()->foldAll(SC_FOLDACTION_EXPAND | SC_FOLDACTION_CONTRACT_EVERY_LEVEL); }); connect(ui->actionFoldLevel1, &QAction::triggered, this, [=]() { currentEditor()->foldAllLevels(0); }); connect(ui->actionFoldLevel2, &QAction::triggered, this, [=]() { currentEditor()->foldAllLevels(1); }); connect(ui->actionFoldLevel3, &QAction::triggered, this, [=]() { currentEditor()->foldAllLevels(2); }); connect(ui->actionFoldLevel4, &QAction::triggered, this, [=]() { currentEditor()->foldAllLevels(3); }); connect(ui->actionFoldLevel5, &QAction::triggered, this, [=]() { currentEditor()->foldAllLevels(4); }); connect(ui->actionFoldLevel6, &QAction::triggered, this, [=]() { currentEditor()->foldAllLevels(5); }); connect(ui->actionFoldLevel7, &QAction::triggered, this, [=]() { currentEditor()->foldAllLevels(6); }); connect(ui->actionFoldLevel8, &QAction::triggered, this, [=]() { currentEditor()->foldAllLevels(7); }); connect(ui->actionFoldLevel9, &QAction::triggered, this, [=]() { currentEditor()->foldAllLevels(8); }); connect(ui->actionUnfoldLevel1, &QAction::triggered, this, [=]() { currentEditor()->unFoldAllLevels(0); }); connect(ui->actionUnfoldLevel2, &QAction::triggered, this, [=]() { currentEditor()->unFoldAllLevels(1); }); connect(ui->actionUnfoldLevel3, &QAction::triggered, this, [=]() { currentEditor()->unFoldAllLevels(2); }); connect(ui->actionUnfoldLevel4, &QAction::triggered, this, [=]() { currentEditor()->unFoldAllLevels(3); }); connect(ui->actionUnfoldLevel5, &QAction::triggered, this, [=]() { currentEditor()->unFoldAllLevels(4); }); connect(ui->actionUnfoldLevel6, &QAction::triggered, this, [=]() { currentEditor()->unFoldAllLevels(5); }); connect(ui->actionUnfoldLevel7, &QAction::triggered, this, [=]() { currentEditor()->unFoldAllLevels(6); }); connect(ui->actionUnfoldLevel8, &QAction::triggered, this, [=]() { currentEditor()->unFoldAllLevels(7); }); connect(ui->actionUnfoldLevel9, &QAction::triggered, this, [=]() { currentEditor()->unFoldAllLevels(8); }); languageActionGroup = new QActionGroup(this); languageActionGroup->setExclusive(true); connect(ui->actionPreferences, &QAction::triggered, this, [=] { PreferencesDialog *pd = findChild<PreferencesDialog *>(QString(), Qt::FindDirectChildrenOnly); if (pd == Q_NULLPTR) { pd = new PreferencesDialog(app->getSettings(), this); } pd->show(); pd->raise(); pd->activateWindow(); }); // The macro manager has already loaded any saved macros, so it might have some already ui->actionRunMacroMultipleTimes->setEnabled(macroManager.availableMacros().size() > 0); ui->actionEditMacros->setEnabled(macroManager.availableMacros().size() > 0); connect(ui->actionMacroRecording, &QAction::triggered, this, [=](bool b) { if (b) { macroManager.startRecording(currentEditor()); } else { macroManager.stopRecording(); } }); connect(&macroManager, &MacroManager::recordingStarted, this, [=]() { ui->actionMacroRecording->setText(tr("Stop Recording")); // A macro is being recorded so disable some macro options ui->actionPlayback->setEnabled(false); ui->actionRunMacroMultipleTimes->setEnabled(false); ui->actionSaveCurrentRecordedMacro->setEnabled(false); }); connect(&macroManager, &MacroManager::recordingStopped, this, [=]() { ui->actionMacroRecording->setText(tr("Start Recording")); // Only enable these if the macro manager recorded a valid macro ui->actionPlayback->setEnabled(macroManager.hasCurrentUnsavedMacro()); ui->actionSaveCurrentRecordedMacro->setEnabled(macroManager.hasCurrentUnsavedMacro()); // The macro manager might have other macros ui->actionRunMacroMultipleTimes->setEnabled(macroManager.availableMacros().size() > 0 || macroManager.hasCurrentUnsavedMacro()); }); connect(ui->actionPlayback, &QAction::triggered, this, [=]() { macroManager.replayCurrentMacro(currentEditor()); }); connect(ui->actionSaveCurrentRecordedMacro, &QAction::triggered, this, [=]() { MacroSaveDialog macroSaveDialog; macroSaveDialog.show(); macroSaveDialog.raise(); macroSaveDialog.activateWindow(); if (macroSaveDialog.exec() == QDialog::Accepted) { // We have at least 1 saved macro at this point ui->actionEditMacros->setEnabled(true); // The macro has been saved so disable save option ui->actionSaveCurrentRecordedMacro->setEnabled(false); // TODO: does the macro name already exist? Make the user retry macroManager.saveCurrentMacro(macroSaveDialog.getName()); // TODO handle shortcuts if (!macroSaveDialog.getShortcut().isEmpty()) { // do something with msd.getShortcut().isEmpty() } } }); connect(ui->actionRunMacroMultipleTimes, &QAction::triggered, this, [=]() { MacroRunDialog *macroRunDialog = findChild<MacroRunDialog *>(QString(), Qt::FindDirectChildrenOnly); if (macroRunDialog == Q_NULLPTR) { macroRunDialog = new MacroRunDialog(this, &macroManager); connect(macroRunDialog, &MacroRunDialog::execute, this, [=](Macro *macro, int times) { if (times > 0) macro->replay(currentEditor(), times); else if (times == -1) macro->replayTillEndOfFile(currentEditor()); }); } macroRunDialog->show(); macroRunDialog->raise(); macroRunDialog->activateWindow(); }); connect(ui->actionEditMacros, &QAction::triggered, this, [=]() { MacroEditorDialog med(this, &macroManager); med.show(); med.raise(); med.activateWindow(); med.exec(); ui->actionEditMacros->setEnabled(macroManager.availableMacros().size() > 0); }); connect(ui->menuMacro, &QMenu::aboutToShow, this, [=]() { // NOTE: its unfortunate that this has to be hard coded, but there's no way // to easily determine what should or shouldn't be there while (ui->menuMacro->actions().size() > 6) { delete ui->menuMacro->actions().takeLast(); } for (const Macro *m : macroManager.availableMacros()) { ui->menuMacro->addAction(m->getName(), [=]() { m->replay(currentEditor()); }); } }); ui->actionAboutQt->setIcon(QPixmap(QLatin1String(":/qt-project.org/qmessagebox/images/qtlogo-64.png"))); connect(ui->actionAboutQt, &QAction::triggered, &QApplication::aboutQt); ui->actionAboutNotepadNext->setShortcut(QKeySequence::HelpContents); connect(ui->actionAboutNotepadNext, &QAction::triggered, this, [=]() { QMessageBox::about(this, QString(), QStringLiteral("<h3>%1 v%2%3</h3>" "<p>%4</p>" "<p>This program does stuff.</p>" R"(<p>This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.</p> <p>This program 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 GNU General Public License for more details.</p> <p>You should have received a copy of the GNU General Public License along with this program. If not, see &lt;<a href="https://www.gnu.org/licenses/">https://www.gnu.org/licenses/</a>&gt;.</p>)") .arg(QApplication::applicationDisplayName(), APP_VERSION, APP_DISTRIBUTION, QStringLiteral(APP_COPYRIGHT).toHtmlEscaped())); }); #ifdef Q_OS_WIN connect(ui->actionShowInExplorer, &QAction::triggered, this, [=]() { QStringList arguments; arguments << "/select," << QDir::toNativeSeparators(currentEditor()->getFileInfo().canonicalFilePath()); QProcess::startDetached("explorer", arguments); }); connect(ui->actionOpenCommandPromptHere, &QAction::triggered, this, [=]() { QStringList arguments; arguments << "/c" << "start" << "/d" << QDir::toNativeSeparators(currentEditor()->getFileInfo().dir().canonicalPath()) << "cmd"; QProcess::startDetached(QStringLiteral("cmd"), arguments); }); #endif EditorInspectorDock *editorInspectorDock = new EditorInspectorDock(this); editorInspectorDock->hide(); addDockWidget(Qt::RightDockWidgetArea, editorInspectorDock); LanguageInspectorDock *languageInspectorDock = new LanguageInspectorDock(this); languageInspectorDock->hide(); addDockWidget(Qt::RightDockWidgetArea, languageInspectorDock); LuaConsoleDock *luaConsoleDock = new LuaConsoleDock(app->getLuaState(), this); luaConsoleDock->hide(); addDockWidget(Qt::BottomDockWidgetArea, luaConsoleDock); DebugLogDock *debugLogDock = new DebugLogDock(this); debugLogDock->hide(); addDockWidget(Qt::RightDockWidgetArea, debugLogDock); HexViewerDock *hexViewerDock = new HexViewerDock(this); hexViewerDock->hide(); addDockWidget(Qt::RightDockWidgetArea, hexViewerDock); ui->menuHelp->insertActions(ui->menuHelp->actions().at(0), { luaConsoleDock->toggleViewAction(), languageInspectorDock->toggleViewAction(), editorInspectorDock->toggleViewAction(), debugLogDock->toggleViewAction(), hexViewerDock->toggleViewAction() }); FolderAsWorkspaceDock *fawDock = new FolderAsWorkspaceDock(this); fawDock->hide(); addDockWidget(Qt::LeftDockWidgetArea, fawDock); ui->menuView->addAction(fawDock->toggleViewAction()); connect(fawDock, &FolderAsWorkspaceDock::fileDoubleClicked, this, &MainWindow::openFile); FileListDock *fileListDock = new FileListDock(this); fileListDock->hide(); addDockWidget(Qt::LeftDockWidgetArea, fileListDock); ui->menuView->addAction(fileListDock->toggleViewAction()); connect(app->getSettings(), &ApplicationSettings::showMenuBarChanged, this, [=](bool showMenuBar) { // Don't 'hide' it, else the actions won't be enabled ui->menuBar->setMaximumHeight(showMenuBar ? QWIDGETSIZE_MAX : 0); }); connect(app->getSettings(), &ApplicationSettings::showToolBarChanged, ui->mainToolBar, &QToolBar::setVisible); connect(app->getSettings(), &ApplicationSettings::showStatusBarChanged, ui->statusBar, &QStatusBar::setVisible); // It seems restoreState() does not affect the status bar so set it manually ui->statusBar->setVisible(app->getSettings()->showStatusBar()); setupLanguageMenu(); applyStyleSheet(); restoreSettings(); initUpdateCheck(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::applyCustomShortcuts() { ApplicationSettings *settings = app->getSettings(); settings->beginGroup("Shortcuts"); for (const QString &actionName : settings->childKeys()) { QAction *action = findChild<QAction *>(QStringLiteral("action") + actionName, Qt::FindDirectChildrenOnly); const QString shortcutString = settings->value(actionName).toString(); if (action != Q_NULLPTR) { action->setShortcut(QKeySequence(shortcutString)); } else { qWarning() << "Cannot find action" << actionName; } } settings->endGroup(); } void MainWindow::setupLanguageMenu() { qInfo(Q_FUNC_INFO); QStringList language_names = app->getLanguages(); int i = 0; while (i < language_names.size()) { QList<QAction *> actions; int j = i; // Get all consecutive names that start with the same letter // NOTE: this loop always runs once since i == j the first time while (j < language_names.size() && language_names[i][0].toUpper() == language_names[j][0].toUpper()) { const QString key = language_names[j]; QAction *action = new QAction(key); action->setCheckable(true); action->setData(key); connect(action, &QAction::triggered, this, &MainWindow::languageMenuTriggered); languageActionGroup->addAction(action); actions.append(action); ++j; } if (actions.size() == 1) { ui->menuLanguage->addActions(actions); } else { // Create a sub menu with the actions QMenu *compactMenu = new QMenu(actions[0]->text().at(0).toUpper()); compactMenu->addActions(actions); ui->menuLanguage->addMenu(compactMenu); } i = j; } } ScintillaNext *MainWindow::currentEditor() const { return dockedEditor->getCurrentEditor(); } int MainWindow::editorCount() const { return dockedEditor->count(); } QVector<ScintillaNext *> MainWindow::editors() const { // NOTE: this will need re-evaluated in the future. // So far it has been assumed 1 ScintillaNext instance is 1 DockedEditor widget instance. // If in the future a ScintillaNext can be cloned then the DockedEditor could return // the same ScintillaNext instance multiple times since 1 ScintillaNext could mean >= 1 DockedEditor widget instance return dockedEditor->editors(); } void MainWindow::newFile() { qInfo(Q_FUNC_INFO); static int count = 1; // NOTE: in theory need to check all editors in the editorManager to future proof this. // If there is another window it would need to check those too to see if New X exists. The editor // manager would encompass all editors forever { QString newFileName = tr("New %1").arg(count++); bool canUseName = true; for (const ScintillaNext *editor : editors()) { if (!editor->isFile() && editor->getName() == newFileName) { canUseName = false; break; } } if (canUseName) { app->getEditorManager()->createEditor(newFileName); break; } } } // One unedited, new blank document ScintillaNext *MainWindow::getInitialEditor() { if (editorCount() == 1) { ScintillaNext *editor = currentEditor(); // If the editor has had ANY modifications, then don't call it an initial editor if (!editor->isFile() && !editor->canUndo() && !editor->canRedo()) { return editor; } } return Q_NULLPTR; } void MainWindow::openFileList(const QStringList &fileNames) { qInfo(Q_FUNC_INFO); if (fileNames.size() == 0) return; ScintillaNext *initialEditor = getInitialEditor(); const ScintillaNext *mostRecentEditor = Q_NULLPTR; for (const QString &filePath : fileNames) { qInfo("%s", qUtf8Printable(filePath)); // Search currently open editors to see if it is already open ScintillaNext *editor = app->getEditorManager()->getEditorByFilePath(filePath); if (editor == Q_NULLPTR) { QFileInfo fileInfo(filePath); if (!fileInfo.isFile()) { auto reply = QMessageBox::question(this, tr("Create File"), tr("<b>%1</b> does not exist. Do you want to create it?").arg(filePath)); if (reply == QMessageBox::Yes) { editor = app->getEditorManager()->createEditorFromFile(filePath, true); } else { // Make sure it is not still in the recent files list still. // Normally when a file is opened it is removed from the file list, // but if a user doesn't want to create the file, remove it explicitly. app->getRecentFilesListManager()->removeFile(filePath); continue; } } else { editor = app->getEditorManager()->createEditorFromFile(filePath); } } if (editor) { mostRecentEditor = editor; } } // If any were successful, switch to the last one if (mostRecentEditor) { dockedEditor->switchToEditor(mostRecentEditor); } if (initialEditor) { initialEditor->close(); } } bool MainWindow::checkEditorsBeforeClose(const QVector<ScintillaNext *> &editors) { for (ScintillaNext *editor : editors) { if (!editor->isSavedToDisk()) { // Switch to it dockedEditor->switchToEditor(editor); // Ask the user what to do QString message = tr("Save file <b>%1</b>?").arg(editor->getName()); auto reply = QMessageBox::question(this, tr("Save File"), message, QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save); if (reply == QMessageBox::Cancel) { // Stop checking and let the caller know return false; } else if (reply == QMessageBox::Save) { bool didFileGetSaved = saveFile(editor); // The user might have canceled the save file dialog so just stop now if (didFileGetSaved == false) { // Stop checking and let the caller know return false; } } } } // Everything is fine return true; } void MainWindow::openFileDialog() { QString dialogDir; const QString filter = app->getFileDialogFilter(); const ScintillaNext *editor = currentEditor(); // Use the path if possible if (editor->isFile()) { dialogDir = editor->getPath(); } QStringList fileNames = FileDialogHelpers::getOpenFileNames(this, QString(), dialogDir, filter); openFileList(fileNames); } void MainWindow::openFile(const QString &filePath) { openFileList(QStringList() << filePath); } void MainWindow::openFolderAsWorkspaceDialog() { QString dialogDir; const ScintillaNext *editor = currentEditor(); // Use the path if possible if (editor->isFile()) { dialogDir = editor->getPath(); } QString dir = QFileDialog::getExistingDirectory(this, tr("Open Folder as Workspace"), dialogDir, QFileDialog::ShowDirsOnly); if (!dir.isEmpty()) { FolderAsWorkspaceDock *fawDock = findChild<FolderAsWorkspaceDock *>(); fawDock->setRootPath(dir); fawDock->setVisible(true); } } void MainWindow::reloadFile() { auto editor = currentEditor(); if (!editor->isFile() && !editor->isSavedToDisk()) { return; } const QString filePath = editor->getFilePath(); auto reply = QMessageBox::question(this, tr("Reload File"), tr("Are you sure you want to reload <b>%1</b>? Any unsaved changes will be lost.").arg(filePath)); if (reply == QMessageBox::Yes) { editor->reload(); } } void MainWindow::closeCurrentFile() { closeFile(currentEditor()); } void MainWindow::closeFile(ScintillaNext *editor) { // Early out. If we aren't exiting on last tab closed, and it exists, there's no point in continuing if (!app->getSettings()->exitOnLastTabClosed() && getInitialEditor() != Q_NULLPTR) { return; } if(editor->isSavedToDisk()) { editor->close(); } else { // The user needs be asked what to do about this file, so switch to it dockedEditor->switchToEditor(editor); QString message = tr("Save file <b>%1</b>?").arg(editor->getName()); auto reply = QMessageBox::question(this, tr("Save File"), message, QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save); if (reply == QMessageBox::Cancel) { return; } if (reply == QMessageBox::Save) { bool didFileGetSaved = saveFile(editor); // The user might have canceled the save file dialog so just stop now if (didFileGetSaved == false) return; } editor->close(); } // If the last document was closed, figure out what to do next if (editorCount() == 0) { if (app->getSettings()->exitOnLastTabClosed()) { close(); } else { newFile(); } } } void MainWindow::closeAllFiles() { if (!checkEditorsBeforeClose(editors())) { return; } // Ask the manager to close the editors the dockedEditor knows about for (ScintillaNext *editor : editors()) { editor->close(); } newFile(); } void MainWindow::closeAllExceptActive() { auto e = currentEditor(); auto editor_list = editors(); editor_list.removeOne(e); if (checkEditorsBeforeClose(editor_list)) { for (ScintillaNext *editor : editor_list) { editor->close(); } } } void MainWindow::closeAllToLeft() { const int index = dockedEditor->currentDockArea()->currentIndex(); QVector<ScintillaNext *> editors; for (int i = 0; i < index; ++i) { auto editor = qobject_cast<ScintillaNext *>(dockedEditor->currentDockArea()->dockWidget(i)->widget()); editors.append(editor); } if (checkEditorsBeforeClose(editors)) { for (ScintillaNext *editor : editors) { editor->close(); } } } void MainWindow::closeAllToRight() { const int index = dockedEditor->currentDockArea()->currentIndex(); const int total = dockedEditor->currentDockArea()->dockWidgetsCount(); QVector<ScintillaNext *> editors; for (int i = index + 1; i < total; ++i) { auto editor = qobject_cast<ScintillaNext *>(dockedEditor->currentDockArea()->dockWidget(i)->widget()); editors.append(editor); } if (checkEditorsBeforeClose(editors)) { for (ScintillaNext *editor : editors) { editor->close(); } } } bool MainWindow::saveCurrentFile() { return saveFile(currentEditor()); } bool MainWindow::saveFile(ScintillaNext *editor) { if (editor->isSavedToDisk()) return true; if (!editor->isFile()) { // Switch to the editor and show the saveas dialog dockedEditor->switchToEditor(editor); return saveCurrentFileAsDialog(); } else { QFileDevice::FileError error = editor->save(); if (error == QFileDevice::NoError) { return true; } else { showSaveErrorMessage(editor, error); return false; } } } bool MainWindow::saveCurrentFileAsDialog() { QString dialogDir; const QString filter = app->getFileDialogFilter(); ScintillaNext *editor = currentEditor(); // Use the file path if possible if (editor->isFile()) { dialogDir = editor->getFilePath(); } QString selectedFilter = app->getFileDialogFilterForLanguage(editor->languageName); QString fileName = FileDialogHelpers::getSaveFileName(this, QString(), dialogDir, filter, &selectedFilter); if (fileName.size() == 0) { return false; } // TODO: distinguish between the above case (i.e. the user cancels the dialog) and a failure // calling editor->saveAs() as it might fail. return saveFileAs(editor, fileName); } bool MainWindow::saveCurrentFileAs(const QString &fileName) { return saveFileAs(currentEditor(), fileName); } bool MainWindow::saveFileAs(ScintillaNext *editor, const QString &fileName) { qInfo("saveFileAs(%s)", qUtf8Printable(fileName)); QFileDevice::FileError error = editor->saveAs(fileName); if (error == QFileDevice::NoError) { return true; } else { showSaveErrorMessage(editor, error); return false; } } bool MainWindow::saveCopyAsDialog() { QString dialogDir; const QString filter = app->getFileDialogFilter(); const ScintillaNext* editor = currentEditor(); // Use the file path if possible if (editor->isFile()) { dialogDir = editor->getFilePath(); } QString selectedFilter = app->getFileDialogFilterForLanguage(editor->languageName); QString fileName = FileDialogHelpers::getSaveFileName(this, tr("Save a Copy As"), dialogDir, filter, &selectedFilter); if (fileName.size() == 0) { return false; } return saveCopyAs(fileName); } bool MainWindow::saveCopyAs(const QString &fileName) { auto editor = currentEditor(); QFileDevice::FileError error = editor->saveCopyAs(fileName); if (error == QFileDevice::NoError) { return true; } else { showSaveErrorMessage(editor, error); return false; } } void MainWindow::saveAll() { for (ScintillaNext *editor : editors()) { saveFile(editor); } } void MainWindow::exportAsFormat(Converter *converter, const QString &filter) { const QString fileName = FileDialogHelpers::getSaveFileName(this, tr("Export As"), QString(), filter + ";;All files (*)"); if (fileName.isEmpty()) { return; } QFile f(fileName); f.open(QIODevice::WriteOnly); QTextStream s(&f); converter->convert(s); f.close(); } void MainWindow::copyAsFormat(Converter *converter, const QString &mimeType) { // This is not ideal as we are *assuming* the converter is currently associated with the currentEditor() ScintillaNext *editor = currentEditor(); QByteArray buffer; QTextStream stream(&buffer); if (editor->selectionEmpty()) converter->convert(stream); else { converter->convertRange(stream, editor->selectionStart(), editor->selectionEnd()); } QMimeData *mimeData = new QMimeData(); mimeData->setData(mimeType, buffer); QApplication::clipboard()->setMimeData(mimeData); } void MainWindow::renameFile() { ScintillaNext *editor = currentEditor(); if (editor->isFile()) { const QString filter = app->getFileDialogFilter(); QString selectedFilter = app->getFileDialogFilterForLanguage(editor->languageName); QString fileName = FileDialogHelpers::getSaveFileName(this, tr("Rename"), editor->getFilePath(), filter, &selectedFilter); if (fileName.isEmpty()) { return; } // TODO // The new fileName might be to one of the existing editors. //auto otherEditor = app->getEditorByFilePath(fileName); bool renameSuccessful = editor->rename(fileName); Q_UNUSED(renameSuccessful) } else { bool ok; QString text = QInputDialog::getText(this, tr("Rename"), tr("Name:"), QLineEdit::Normal, editor->getName(), &ok); if (ok && !text.isEmpty()) { editor->setName(text); } } } void MainWindow::moveCurrentFileToTrash() { ScintillaNext *editor = currentEditor(); moveFileToTrash(editor); } void MainWindow::moveFileToTrash(ScintillaNext *editor) { Q_ASSERT(editor->isFile()); const QString filePath = editor->getFilePath(); auto reply = QMessageBox::question(this, tr("Delete File"), tr("Are you sure you want to move <b>%1</b> to the trash?").arg(filePath)); if (reply == QMessageBox::Yes) { if (editor->moveToTrash()) { closeCurrentFile(); // Since the file no longer exists, specifically remove it from the recent files list app->getRecentFilesListManager()->removeFile(editor->getFilePath()); } else { QMessageBox::warning(this, tr("Error Deleting File"), tr("Something went wrong deleting <b>%1</b>?").arg(filePath)); } } } void MainWindow::print() { QPrintPreviewDialog printDialog(this, Qt::Window); EditorPrintPreviewRenderer renderer(currentEditor()); connect(&printDialog, &QPrintPreviewDialog::paintRequested, &renderer, &EditorPrintPreviewRenderer::render); // TODO: load/save the page layout that was used and reload it next time //preview.printer()->setPageLayout( /* todo */ ); printDialog.printer()->setPageMargins(QMarginsF(.5, .5, .5, .5), QPageLayout::Inch); connect(&printDialog, &QPrintPreviewDialog::accepted, this, [&]() { qInfo() << printDialog.printer()->pageLayout(); }); printDialog.exec(); } void MainWindow::convertEOLs(int eolMode) { ScintillaNext *editor = currentEditor(); // TODO: does convertEOLs trigger SCN_MODIFIED notifications? If so can these be turned off to increase performance? editor->convertEOLs(eolMode); editor->setEOLMode(eolMode); updateEOLBasedUi(editor); // There's no simple Scintilla notification that the EOL mode has changed // So tell the status bar to refresh its info ui->statusBar->refresh(editor); } void MainWindow::showFindReplaceDialog(int index) { ScintillaNext *editor = currentEditor(); FindReplaceDialog *frd = findChild<FindReplaceDialog *>(QString(), Qt::FindDirectChildrenOnly); if (frd == Q_NULLPTR) { frd = new FindReplaceDialog(determineSearchResultsHandler(), this); } else { frd->setSearchResultsHandler(determineSearchResultsHandler()); } // TODO: if dockedEditor::editorActivated() is fired, or if the editor get closed // the FindReplaceDialog's editor pointer needs updated... // Get any selected text if (!editor->selectionEmpty()) { int selection = editor->mainSelection(); int start = editor->selectionNStart(selection); int end = editor->selectionNEnd(selection); if (end > start) { auto selText = editor->get_text_range(start, end); frd->setFindString(QString::fromUtf8(selText)); } } else { int start = editor->wordStartPosition(editor->currentPos(), true); int end = editor->wordEndPosition(editor->currentPos(), true); if (end > start) { editor->setSelectionStart(start); editor->setSelectionEnd(end); auto selText = editor->get_text_range(start, end); frd->setFindString(QString::fromUtf8(selText)); } } frd->setTab(index); frd->show(); frd->raise(); frd->activateWindow(); } void MainWindow::updateFileStatusBasedUi(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); bool isFile = editor->isFile(); QString fileName; if (isFile) { fileName = editor->getFilePath(); } else { fileName = editor->getName(); } QString title = QStringLiteral("[*]%1").arg(fileName); if (app->isRunningAsAdmin()) { title += QStringLiteral(" - [%1]").arg(tr("Administrator")); } setWindowTitle(title); ui->actionReload->setEnabled(isFile); ui->actionMoveToTrash->setEnabled(isFile); ui->actionCopyFullPath->setEnabled(isFile); ui->actionCopyFileDirectory->setEnabled(isFile); ui->actionShowInExplorer->setEnabled(isFile); ui->actionOpenCommandPromptHere->setEnabled(isFile); } bool MainWindow::isAnyUnsaved() const { for (const ScintillaNext *editor : editors()) { if (!editor->isSavedToDisk()) { return true; } } return false; } void MainWindow::updateEOLBasedUi(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); switch(editor->eOLMode()) { case SC_EOL_CR: ui->actionMacintosh->setChecked(true); break; case SC_EOL_CRLF: ui->actionWindows->setChecked(true); break; case SC_EOL_LF: ui->actionUnix->setChecked(true); break; } } void MainWindow::updateSaveStatusBasedUi(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); bool isDirty = !editor->isSavedToDisk(); setWindowModified(isDirty); ui->actionSave->setEnabled(isDirty); ui->actionSaveAll->setEnabled(isDirty || isAnyUnsaved()); if (editorCount() == 1) { bool ableToClose = editor->isFile() || isDirty; ui->actionClose->setEnabled(ableToClose); ui->actionCloseAll->setEnabled(ableToClose); } else { ui->actionClose->setEnabled(true); ui->actionCloseAll->setEnabled(true); } } void MainWindow::updateEditorPositionBasedUi() { const int index = dockedEditor->currentDockArea()->currentIndex(); const int total = dockedEditor->currentDockArea()->dockWidgetsCount(); ui->actionCloseAllToLeft->setEnabled(index > 0); ui->actionCloseAllToRight->setEnabled(index < (total - 1)); ui->actionCloseAllExceptActive->setEnabled(editorCount() > 1); } void MainWindow::updateLanguageBasedUi(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); const QString language_name = editor->languageName; for (QAction *action : languageActionGroup->actions()) { if (action->data().toString() == language_name) { action->setChecked(true); // Found one, so we are completely done return; } } // The above loop did not set any action as checked, so make sure they are all unchecked now for (QAction *action : languageActionGroup->actions()) { if (action->isChecked()) { action->setChecked(false); } } } void MainWindow::updateGui(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); updateFileStatusBasedUi(editor); updateSaveStatusBasedUi(editor); updateEOLBasedUi(editor); updateEditorPositionBasedUi(); updateSelectionBasedUi(editor); updateContentBasedUi(editor); updateLanguageBasedUi(editor); } void MainWindow::updateDocumentBasedUi(Scintilla::Update updated) { ScintillaNext *editor = qobject_cast<ScintillaNext *>(sender()); // TODO: what if this is triggered by an editor that is not the active editor? if (Scintilla::FlagSet(updated, Scintilla::Update::Content)) { updateSelectionBasedUi(editor); } if (Scintilla::FlagSet(updated, Scintilla::Update::Content) || Scintilla::FlagSet(updated, Scintilla::Update::Selection)) { updateContentBasedUi(editor); } } void MainWindow::updateSelectionBasedUi(ScintillaNext *editor) { ui->actionUndo->setEnabled(editor->canUndo()); ui->actionRedo->setEnabled(editor->canRedo()); } void MainWindow::updateContentBasedUi(ScintillaNext *editor) { bool hasAnySelections = !editor->selectionEmpty(); ui->actionPaste->setEnabled(editor->canPaste()); ui->actionLowerCase->setEnabled(hasAnySelections); ui->actionUpperCase->setEnabled(hasAnySelections); ui->actionBase64Encode->setEnabled(hasAnySelections); ui->actionURLEncode->setEnabled(hasAnySelections); ui->actionBase64Decode->setEnabled(hasAnySelections); ui->actionURLDecode->setEnabled(hasAnySelections); } void MainWindow::detectLanguage(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); if (!editor->isFile()) { // Default to some specific language if it is not a file. setLanguage(editor, "Text"); return; } else { const QString language_name = app->detectLanguage(editor); setLanguage(editor, language_name); } return; } void MainWindow::activateEditor(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); checkFileForModification(editor); updateGui(editor); emit editorActivated(editor); } void MainWindow::applyStyleSheet() { qInfo(Q_FUNC_INFO); QString sheet; QFile f(":/stylesheets/npp.css"); qInfo() << "Loading stylesheet: " << f.fileName(); f.open(QFile::ReadOnly); sheet = f.readAll(); f.close(); // If there is a "custom.css" file where the ini is located, load it as a style sheet addition QString directoryPath = QFileInfo(app->getSettings()->fileName()).absolutePath(); QString fullPath = QDir(directoryPath).filePath("custom.css"); if (QFile::exists(fullPath)) { QFile custom(fullPath); qInfo() << "Loading stylesheet: " << custom.fileName(); custom.open(QFile::ReadOnly); sheet += custom.readAll(); custom.close(); } setStyleSheet(sheet); } void MainWindow::setLanguage(ScintillaNext *editor, const QString &languageName) { qInfo(Q_FUNC_INFO); qInfo("Language Name: %s", qUtf8Printable(languageName)); app->setEditorLanguage(editor, languageName); } void MainWindow::bringWindowToForeground() { qInfo(Q_FUNC_INFO); // There doesn't seem to be a cross platform way to force the window to the foreground #ifdef Q_OS_WIN HWND hWnd = reinterpret_cast<HWND>(effectiveWinId()); if (hWnd) { // I have no idea what this does, but it seems to work on Windows // References: // https://stackoverflow.com/questions/916259/win32-bring-a-window-to-top // https://github.com/notepad-plus-plus/notepad-plus-plus/blob/ebe7648ee1a5a560d4fc65297cbdcf08055e56e3/PowerEditor/src/winmain.cpp#L596 HWND hCurWnd = GetForegroundWindow(); DWORD threadId = GetCurrentThreadId(); DWORD procId = GetWindowThreadProcessId(hCurWnd, NULL); int sw = 0; if (IsZoomed(hWnd)) { sw = SW_MAXIMIZE; } else if (IsIconic(hWnd)) { sw = SW_RESTORE; } if (sw != 0) { ShowWindow(hWnd, sw); } AttachThreadInput(procId, threadId, TRUE); SetForegroundWindow(hWnd); SetFocus(hWnd); AttachThreadInput(procId, threadId, FALSE); } #else setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive); raise(); activateWindow(); #endif } bool MainWindow::checkFileForModification(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); auto state = editor->checkFileForStateChange(); if (state == ScintillaNext::NoChange) { return false; } else if (state == ScintillaNext::Modified) { qInfo("ScintillaNext::Modified"); editor->reload(); } else if (state == ScintillaNext::Deleted) { qInfo("ScintillaNext::Deleted"); } else if (state == ScintillaNext::Restored) { qInfo("ScintillaNext::Restored"); } return true; } void MainWindow::showSaveErrorMessage(ScintillaNext *editor, QFileDevice::FileError error) { const QString name = editor->isFile() ? editor->getFilePath() : editor->getName(); QMessageBox::warning(this, tr("Error Saving File"), tr("An error occurred when saving <b>%1</b><br><br>Error: %2").arg(name, qt_error_string(error))); } void MainWindow::showEditorZoomLevelIndicator() { // Not sure if Scintilla's zoom level matches up to an exact percentage, but visibly this is close FadingIndicator::showText(currentEditor(), tr("Zoom: %1%").arg(zoomLevel * 10 + 100)); } void MainWindow::saveSettings() const { qInfo(Q_FUNC_INFO); ApplicationSettings *settings = app->getSettings(); settings->setValue("MainWindow/geometry", saveGeometry()); settings->setValue("MainWindow/windowState", saveState()); settings->setValue("Editor/ZoomLevel", zoomLevel); } void MainWindow::restoreSettings() { qInfo(Q_FUNC_INFO); ApplicationSettings *settings = app->getSettings(); zoomLevel = settings->value("Editor/ZoomLevel", 0).toInt(); } ISearchResultsHandler *MainWindow::determineSearchResultsHandler() { // Determine what will get the search results if (app->getSettings()->combineSearchResults()) { searchResults.reset(new SearchResultsCollector(findChild<SearchResultsDock *>())); return searchResults.data(); } else { return findChild<SearchResultsDock *>(); } } void MainWindow::restoreWindowState() { ApplicationSettings *settings = app->getSettings(); restoreGeometry(settings->value("MainWindow/geometry").toByteArray()); restoreState(settings->value("MainWindow/windowState").toByteArray()); // Always hide the dock no matter how the application was closed SearchResultsDock *srDock = findChild<SearchResultsDock *>(); srDock->hide(); } void MainWindow::switchToEditor(const ScintillaNext *editor) { dockedEditor->switchToEditor(editor); } void MainWindow::focusIn() { qInfo(Q_FUNC_INFO); if (checkFileForModification(currentEditor())) { updateGui(currentEditor()); } } void MainWindow::addEditor(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); detectLanguage(editor); // These should only ever occur for the focused editor?? // TODO: look at editor inspector as an example to ensure updates are only coming from one editor. // Can save the connection objects and disconnected from them and only connect to the editor as it is activated. connect(editor, &ScintillaNext::savePointChanged, this, [=]() { updateSaveStatusBasedUi(editor); }); connect(editor, &ScintillaNext::renamed, this, [=]() { detectLanguage(editor); }); connect(editor, &ScintillaNext::renamed, this, [=]() { updateFileStatusBasedUi(editor); }); connect(editor, &ScintillaNext::updateUi, this, &MainWindow::updateDocumentBasedUi); // Watch for any zoom events (Ctrl+Scroll or pinch-to-zoom (Qt translates it as Ctrl+Scroll)) so that the event // can be handled before the ScintillaEditBase widget, so that it can be applied to all editors to keep zoom level equal. // NOTE: Need to install this on the scroll area's viewport, not on the editor widget itself...that was painful to learn editor->viewport()->installEventFilter(zoomEventWatcher); editor->setZoom(zoomLevel); editor->setContextMenuPolicy(Qt::CustomContextMenu); connect(editor, &ScintillaNext::customContextMenuRequested, this, [=](const QPoint &pos) { contextMenuPos = editor->send(SCI_POSITIONFROMPOINT, pos.x(), pos.y()); QMenu *menu = new QMenu(this); menu->setAttribute(Qt::WA_DeleteOnClose); URLFinder *urlFinder = editor->findChild<URLFinder *>(QString(), Qt::FindDirectChildrenOnly); if (urlFinder && urlFinder->isEnabled() && urlFinder->isURL(contextMenuPos)) { menu->addAction(ui->actionCopyURL); menu->addSeparator(); } menu->addAction(ui->actionCut); menu->addAction(ui->actionCopy); menu->addAction(ui->actionPaste); menu->addAction(ui->actionDelete); menu->addSeparator(); menu->addAction(ui->actionSelectAll); menu->addSeparator(); menu->addAction(ui->actionBase64Encode); menu->addAction(ui->actionURLEncode); menu->addSeparator(); menu->addAction(ui->actionBase64Decode); menu->addAction(ui->actionURLDecode); menu->popup(QCursor::pos()); }); // The editor has been entirely configured at this point, so add it to the docked editor dockedEditor->addEditor(editor); } void MainWindow::checkForUpdates(bool silent) { #ifdef Q_OS_WIN qInfo(Q_FUNC_INFO); QString url = "https://github.com/dail8859/NotepadNext/raw/master/updates.json"; QSimpleUpdater::getInstance()->checkForUpdates(url); if (!silent) { connect(QSimpleUpdater::getInstance(), &QSimpleUpdater::checkingFinished, this, &MainWindow::checkForUpdatesFinished, Qt::UniqueConnection); } else { disconnect(QSimpleUpdater::getInstance(), &QSimpleUpdater::checkingFinished, this, &MainWindow::checkForUpdatesFinished); } app->getSettings()->setValue("App/LastUpdateCheck", QDateTime::currentDateTime()); #else Q_UNUSED(silent); #endif } void MainWindow::checkForUpdatesFinished(QString url) { #ifdef Q_OS_WIN if (!QSimpleUpdater::getInstance()->getUpdateAvailable(url)) { QMessageBox::information(this, QString(), tr("No updates are available at this time.")); } #endif } void MainWindow::initUpdateCheck() { #ifdef Q_OS_WIN #ifdef QT_DEBUG if (true) { #else QSettings registry(QSettings::NativeFormat, QSettings::UserScope, QApplication::organizationName(), QApplication::applicationName()); const bool autoUpdatesEnabled = registry.value("AutoUpdate", 0).toBool(); qInfo("AutoUpdates: %d", autoUpdatesEnabled); if (autoUpdatesEnabled) { #endif connect(ui->actionCheckForUpdates, &QAction::triggered, this, &MainWindow::checkForUpdates); // A bit after startup, see if we need to automatically check for an update QTimer::singleShot(15000, this, [=]() { ApplicationSettings settings; QDateTime dt = settings.value("App/LastUpdateCheck", QDateTime::currentDateTime()).toDateTime(); if (dt.isValid()) { qInfo("Last checked for updates at: %s", qUtf8Printable(dt.toString())); if (dt.addDays(7) < QDateTime::currentDateTime()) { checkForUpdates(true); } } }); } else { ui->actionCheckForUpdates->setDisabled(true); ui->actionCheckForUpdates->setVisible(false); } #else ui->actionCheckForUpdates->setDisabled(true); ui->actionCheckForUpdates->setVisible(false); #endif } void MainWindow::closeEvent(QCloseEvent *event) { const SessionManager *sessionManager = app->getSessionManager(); QVector<ScintillaNext *> e; // Check all editors to see if the session manager will not handle it for (auto editor : editors()) { if (!sessionManager->willFileGetStoredInSession(editor)) { e.append(editor); } } if (!checkEditorsBeforeClose(e)) { event->ignore(); return; } emit aboutToClose(); event->accept(); QMainWindow::closeEvent(event); } void MainWindow::dragEnterEvent(QDragEnterEvent *event) { qInfo(Q_FUNC_INFO); // NOTE: for urls these can be dragged anywhere in the application, editor, tabs, menu // because the ScintillaNext editor ignores urls so they can be handled by the main // application // Text dragging within the editor object itself is handled by Scintilla, but if the text // is dragged to other parts (tabs, menu, etc) it will be handled by the application to // create a new editor from the text. // Accept urls and text if (event->mimeData()->hasUrls() || event->mimeData()->hasText()) { event->acceptProposedAction(); } else { event->ignore(); } } void MainWindow::dropEvent(QDropEvent *event) { qInfo(Q_FUNC_INFO); if (event->mimeData()->hasUrls()) { // Get the urls into a stringlist QStringList fileNames; for (const QUrl &url : event->mimeData()->urls()) { if (url.isLocalFile()) { QFileInfo info(url.toLocalFile()); if (info.exists()) { if (info.isDir()) { QDirIterator it(url.toLocalFile(), QDir::Files, QDirIterator::FollowSymlinks| QDirIterator::Subdirectories); while (it.hasNext()) { fileNames << it.next(); } } else { fileNames.append(url.toLocalFile()); } } } } openFileList(fileNames); bringWindowToForeground(); event->acceptProposedAction(); } else if (event->mimeData()->hasText()) { if (event->source()) { // if it is from an editor, remove the text ScintillaNext *sn = qobject_cast<ScintillaNext *>(event->source()); if (sn) { sn->replaceSel(""); } } newFile(); currentEditor()->setText(event->mimeData()->text().toLocal8Bit().constData()); bringWindowToForeground(); event->acceptProposedAction(); } else { event->ignore(); } } void MainWindow::tabBarRightClicked(ScintillaNext *editor) { qInfo(Q_FUNC_INFO); // Focus on the correct tab dockedEditor->switchToEditor(editor); // Create the menu QMenu *menu = new QMenu(this); menu->setAttribute(Qt::WA_DeleteOnClose); // Default actions QStringList actionNames{ "Close", "CloseAllExceptActive", "CloseAllToLeft", "CloseAllToRight", "", "Save", "SaveAs", "Rename", "", "Reload", "", #ifdef Q_OS_WIN "ShowInExplorer", "OpenCommandPromptHere", "", #endif "CopyFullPath", "CopyFileName", "CopyFileDirectory" }; // If the entry exists in the settings, use that ApplicationSettings *settings = app->getSettings(); if (settings->contains("Gui/TabBarContextMenu")) { actionNames = settings->value("Gui/TabBarContextMenu").toStringList(); } // Populate the menu for (const QString &actionName : actionNames) { if (actionName.isEmpty()) { menu->addSeparator(); } else { QAction *a = findChild<QAction *>(QStringLiteral("action") + actionName, Qt::FindDirectChildrenOnly); if (a != Q_NULLPTR) { menu->addAction(a); } else { qWarning() << "Cannot locate menu named" << actionName; } } } // Show it menu->popup(QCursor::pos()); } void MainWindow::languageMenuTriggered() { const QAction *act = qobject_cast<QAction *>(sender()); auto editor = currentEditor(); QVariant v = act->data(); setLanguage(editor, v.toString()); }
73,779
C++
.cpp
1,681
36.906603
722
0.667243
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,349
PreferencesDialog.cpp
dail8859_NotepadNext/src/NotepadNext/dialogs/PreferencesDialog.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "PreferencesDialog.h" #include "NotepadNextApplication.h" #include "TranslationManager.h" #include "ui_PreferencesDialog.h" #include <QMessageBox> PreferencesDialog::PreferencesDialog(ApplicationSettings *settings, QWidget *parent) : QDialog(parent, Qt::Tool), ui(new Ui::PreferencesDialog), settings(settings) { ui->setupUi(this); QIcon icon = style()->standardIcon(QStyle::SP_MessageBoxInformation); QPixmap pixmap = icon.pixmap(QSize(16, 16)); ui->labelAppRestartIcon->setPixmap(pixmap); ui->labelAppRestartIcon->hide(); ui->labelAppRestart->hide(); MapSettingToCheckBox(ui->checkBoxMenuBar, &ApplicationSettings::showMenuBar, &ApplicationSettings::setShowMenuBar, &ApplicationSettings::showMenuBarChanged); MapSettingToCheckBox(ui->checkBoxToolBar, &ApplicationSettings::showToolBar, &ApplicationSettings::setShowToolBar, &ApplicationSettings::showToolBarChanged); MapSettingToCheckBox(ui->checkBoxStatusBar, &ApplicationSettings::showStatusBar, &ApplicationSettings::setShowStatusBar, &ApplicationSettings::showStatusBarChanged); MapSettingToCheckBox(ui->checkBoxRecenterSearchDialog, &ApplicationSettings::centerSearchDialog, &ApplicationSettings::setCenterSearchDialog, &ApplicationSettings::centerSearchDialogChanged); MapSettingToGroupBox(ui->gbxRestorePreviousSession, &ApplicationSettings::restorePreviousSession, &ApplicationSettings::setRestorePreviousSession, &ApplicationSettings::restorePreviousSessionChanged); connect(ui->gbxRestorePreviousSession, &QGroupBox::toggled, this, [=](bool checked) { if (!checked) { ui->checkBoxUnsavedFiles->setChecked(false); ui->checkBoxRestoreTempFiles->setChecked(false); } else { QMessageBox::warning(this, tr("Warning"), tr("This feature is experimental and it should not be considered safe for critically important work. It may lead to possible data loss. Use at your own risk.")); } }); MapSettingToCheckBox(ui->checkBoxUnsavedFiles, &ApplicationSettings::restoreUnsavedFiles, &ApplicationSettings::setRestoreUnsavedFiles, &ApplicationSettings::restoreUnsavedFilesChanged); MapSettingToCheckBox(ui->checkBoxRestoreTempFiles, &ApplicationSettings::restoreTempFiles, &ApplicationSettings::setRestoreTempFiles, &ApplicationSettings::restoreTempFilesChanged); MapSettingToCheckBox(ui->checkBoxCombineSearchResults, &ApplicationSettings::combineSearchResults, &ApplicationSettings::setCombineSearchResults, &ApplicationSettings::combineSearchResultsChanged); populateTranslationComboBox(); connect(ui->comboBoxTranslation, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int index) { settings->setTranslation(ui->comboBoxTranslation->itemData(index).toString()); showApplicationRestartRequired(); }); MapSettingToCheckBox(ui->checkBoxExitOnLastTabClosed, &ApplicationSettings::exitOnLastTabClosed, &ApplicationSettings::setExitOnLastTabClosed, &ApplicationSettings::exitOnLastTabClosedChanged); ui->fcbDefaultFont->setCurrentFont(QFont(settings->fontName())); connect(ui->fcbDefaultFont, &QFontComboBox::currentFontChanged, this, [=](const QFont &f) { settings->setFontName(f.family()); }); connect(settings, &ApplicationSettings::fontNameChanged, this, [=](QString fontName){ ui->fcbDefaultFont->setCurrentFont(QFont(fontName)); }); ui->spbDefaultFontSize->setValue(settings->fontSize()); connect(ui->spbDefaultFontSize, QOverload<int>::of(&QSpinBox::valueChanged), settings, &ApplicationSettings::setFontSize); connect(settings, &ApplicationSettings::fontSizeChanged, ui->spbDefaultFontSize, &QSpinBox::setValue); } PreferencesDialog::~PreferencesDialog() { delete ui; } void PreferencesDialog::showApplicationRestartRequired() const { ui->labelAppRestartIcon->show(); ui->labelAppRestart->show(); } template<typename Func1, typename Func2, typename Func3> void PreferencesDialog::MapSettingToCheckBox(QCheckBox *checkBox, Func1 getter, Func2 setter, Func3 notifier) const { // Get the value and set the checkbox state checkBox->setChecked(std::bind(getter, settings)()); // Set up two way connection connect(settings, notifier, checkBox, &QCheckBox::setChecked); connect(checkBox, &QCheckBox::toggled, settings, setter); } template<typename Func1, typename Func2, typename Func3> void PreferencesDialog::MapSettingToGroupBox(QGroupBox *groupBox, Func1 getter, Func2 setter, Func3 notifier) const { // Get the value and set the checkbox state groupBox->setChecked(std::bind(getter, settings)()); // Set up two way connection connect(settings, notifier, groupBox, &QGroupBox::setChecked); connect(groupBox, &QGroupBox::toggled, settings, setter); } void PreferencesDialog::populateTranslationComboBox() { NotepadNextApplication *app = qobject_cast<NotepadNextApplication *>(qApp); // Add the system default at the top ui->comboBoxTranslation->addItem(QStringLiteral("%1 (%2)").arg(tr("<System Default>"), QLocale::system().name()), QStringLiteral("")); // TODO: sort this list and keep the system default at the top for (const auto &localeName : app->getTranslationManager()->availableTranslations()) { QLocale locale(localeName); const QString localeDisplay = TranslationManager::FormatLocaleTerritoryAndLanguage(locale); ui->comboBoxTranslation->addItem(QStringLiteral("%1 (%2)").arg(localeDisplay, localeName), localeName); } // Select the current one int index = ui->comboBoxTranslation->findData(settings->translation()); if (index != -1) { ui->comboBoxTranslation->setCurrentIndex(index); } }
6,478
C++
.cpp
112
53.339286
215
0.77105
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,350
FindReplaceDialog.cpp
dail8859_NotepadNext/src/NotepadNext/dialogs/FindReplaceDialog.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "FindReplaceDialog.h" #include "ApplicationSettings.h" #include "ui_FindReplaceDialog.h" #include <QStatusBar> #include <QLineEdit> #include <QKeyEvent> #include "ScintillaNext.h" #include "MainWindow.h" static void convertToExtended(QString &str) { str.replace("\\r", "\r"); str.replace("\\n", "\n"); str.replace("\\t", "\t"); str.replace("\\0", "\0"); str.replace("\\\\", "\\"); // TODO: more } FindReplaceDialog::FindReplaceDialog(ISearchResultsHandler *searchResults, MainWindow *window) : QDialog(window, Qt::Dialog), ui(new Ui::FindReplaceDialog), searchResultsHandler(searchResults), finder(new Finder(window->currentEditor())) { qInfo(Q_FUNC_INFO); // Turn off the help button on the dialog setWindowFlag(Qt::WindowContextHelpButtonHint, false); ui->setupUi(this); // Get the current editor, and keep up the reference setEditor(window->currentEditor()); connect(window, &MainWindow::editorActivated, this, &FindReplaceDialog::setEditor); tabBar = new QTabBar(); tabBar->addTab(tr("Find")); tabBar->addTab(tr("Replace")); tabBar->setExpanding(false); qobject_cast<QVBoxLayout *>(layout())->insertWidget(0, tabBar); connect(tabBar, &QTabBar::currentChanged, this, &FindReplaceDialog::changeTab); statusBar = new QStatusBar(); statusBar->setSizeGripEnabled(false); // the dialog has one already qobject_cast<QVBoxLayout *>(layout())->insertWidget(-1, statusBar); // Disable auto completion ui->comboFind->setCompleter(nullptr); ui->comboReplace->setCompleter(nullptr); // If the selection changes highlight the text connect(ui->comboFind, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), ui->comboFind->lineEdit(), &QLineEdit::selectAll); connect(ui->comboReplace, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), ui->comboReplace->lineEdit(), &QLineEdit::selectAll); // Force focus on the find text box connect(this, &FindReplaceDialog::windowActivated, [=]() { ui->comboFind->setFocus(); ui->comboFind->lineEdit()->selectAll(); }); connect(this, &QDialog::rejected, [=]() { statusBar->clearMessage(); savePosition(); }); connect(ui->radioRegexSearch, &QRadioButton::toggled, this, [=](bool checked) { ui->checkBoxBackwardsDirection->setDisabled(checked); ui->checkBoxMatchWholeWord->setDisabled(checked); ui->checkBoxRegexMatchesNewline->setEnabled(checked); }); connect(ui->radioOnLosingFocus, &QRadioButton::toggled, this, &FindReplaceDialog::adjustOpacityWhenLosingFocus); connect(ui->radioAlways, &QRadioButton::toggled, this, &FindReplaceDialog::adjustOpacityAlways); connect(ui->transparency, &QGroupBox::toggled, this, &FindReplaceDialog::transparencyToggled); connect(ui->buttonFind, &QPushButton::clicked, this, &FindReplaceDialog::find); connect(ui->buttonCount, &QPushButton::clicked, this, &FindReplaceDialog::count); connect(ui->buttonFindAllInCurrent, &QPushButton::clicked, this, [=]() { prepareToPerformSearch(); searchResultsHandler->newSearch(findString()); findAllInCurrentDocument(); searchResultsHandler->completeSearch(); close(); }); connect(ui->buttonFindAllInDocuments, &QPushButton::clicked, this, [=]() { prepareToPerformSearch(); searchResultsHandler->newSearch(findString()); findAllInDocuments(); searchResultsHandler->completeSearch(); close(); }); connect(ui->buttonReplace, &QPushButton::clicked, this, &FindReplaceDialog::replace); connect(ui->buttonReplaceAll, &QPushButton::clicked, this, &FindReplaceDialog::replaceAll); connect(ui->buttonReplaceAllInDocuments, &QPushButton::clicked, this, [=]() { prepareToPerformSearch(true); QString replaceText = replaceString(); if (ui->radioExtendedSearch->isChecked()) { convertToExtended(replaceText); } int count = 0; ScintillaNext *current_editor = editor; MainWindow *window = qobject_cast<MainWindow *>(parent()); for(ScintillaNext *editor : window->editors()) { setEditor(editor); count += finder->replaceAll(replaceText); } setEditor(current_editor); showMessage(tr("Replaced %Ln matches", "", count), "green"); }); connect(ui->buttonClose, &QPushButton::clicked, this, &FindReplaceDialog::close); loadSettings(); connect(qApp, &QApplication::aboutToQuit, this, &FindReplaceDialog::saveSettings); changeTab(tabBar->currentIndex()); } FindReplaceDialog::~FindReplaceDialog() { delete ui; delete finder; } void FindReplaceDialog::setFindString(const QString &string) { ui->comboFind->setCurrentText(string); ui->comboFind->lineEdit()->selectAll(); } void FindReplaceDialog::setTab(int tab) { tabBar->setCurrentIndex(tab); } bool FindReplaceDialog::event(QEvent *event) { if (event->type() == QEvent::WindowActivate) { emit windowActivated(); } else if (event->type() == QEvent::WindowDeactivate) { emit windowDeactivated(); } return QDialog::event(event); } void FindReplaceDialog::showEvent(QShowEvent *event) { qInfo(Q_FUNC_INFO); if (!isFirstTime) restorePosition(); isFirstTime = false; QDialog::showEvent(event); } static void updateComboList(QComboBox *comboBox, const QString &text) { // Block the signals while it is manipulated const QSignalBlocker blocker(comboBox); // Remove it if it is in the list, add it to beginning, and select it comboBox->removeItem(comboBox->findText(text)); comboBox->insertItem(0, text); comboBox->setCurrentIndex(0); } void FindReplaceDialog::updateFindList(const QString &text) { if (!text.isEmpty()) updateComboList(ui->comboFind, text); } void FindReplaceDialog::updateReplaceList(const QString &text) { updateComboList(ui->comboReplace, text); } void FindReplaceDialog::find() { qInfo(Q_FUNC_INFO); prepareToPerformSearch(); Sci_CharacterRange range; if(!ui->checkBoxBackwardsDirection->isChecked()) { range = finder->findNext(); } else{ range = finder->findPrev(); } if (ScintillaNext::isRangeValid(range)) { if (finder->didLatestSearchWrapAround()) { showMessage(tr("The end of the document has been reached. Found 1st occurrence from the top."), "green"); } // TODO: Handle zero length matches better if (range.cpMin == range.cpMax) { qWarning() << "0 length match at" << range.cpMin; } editor->goToRange(range); } else { showMessage(tr("No matches found."), "red"); } } void FindReplaceDialog::findAllInCurrentDocument() { qInfo(Q_FUNC_INFO); bool firstMatch = true; QString text = findString(); finder->setSearchText(text); finder->forEachMatch([&](int start, int end){ // Only add the file entry if there was a valid search result if (firstMatch) { searchResultsHandler->newFileEntry(editor); firstMatch = false; } const int line = editor->lineFromPosition(start); const int lineStartPosition = editor->positionFromLine(line); const int lineEndPosition = editor->lineEndPosition(line); const int startPositionFromBeginning = start - lineStartPosition; const int endPositionFromBeginning = end - lineStartPosition; QString lineText = editor->get_text_range(lineStartPosition, lineEndPosition); searchResultsHandler->newResultsEntry(lineText, line, startPositionFromBeginning, endPositionFromBeginning); return end; }); } void FindReplaceDialog::findAllInDocuments() { qInfo(Q_FUNC_INFO); ScintillaNext *current_editor = editor; MainWindow *window = qobject_cast<MainWindow *>(parent()); for(ScintillaNext *editor : window->editors()) { setEditor(editor); findAllInCurrentDocument(); } setEditor(current_editor); } void FindReplaceDialog::replace() { qInfo(Q_FUNC_INFO); prepareToPerformSearch(); QString replaceText = replaceString(); if (ui->radioExtendedSearch->isChecked()) { convertToExtended(replaceText); } Sci_CharacterRange range = finder->replaceSelectionIfMatch(replaceText); if (ScintillaNext::isRangeValid(range)) { showMessage(tr("1 occurrence was replaced"), "blue"); } Sci_CharacterRange next_match = finder->findNext(); if (ScintillaNext::isRangeValid(next_match)) { editor->goToRange(next_match); } else { showMessage(tr("No more occurrences were found"), "red"); ui->comboFind->setFocus(); ui->comboFind->lineEdit()->selectAll(); } } void FindReplaceDialog::replaceAll() { qInfo(Q_FUNC_INFO); prepareToPerformSearch(true); QString replaceText = replaceString(); if (ui->radioExtendedSearch->isChecked()) { convertToExtended(replaceText); } int count = finder->replaceAll(replaceText); showMessage(tr("Replaced %Ln matches", "", count), "green"); } void FindReplaceDialog::count() { qInfo(Q_FUNC_INFO); prepareToPerformSearch(); int total = finder->count(); showMessage(tr("Found %Ln matches", "", total), "green"); } void FindReplaceDialog::setEditor(ScintillaNext *editor) { this->editor = editor; finder->setEditor(editor); } void FindReplaceDialog::performLastSearch() { editor->goToRange(finder->findNext()); } void FindReplaceDialog::adjustOpacity(int value) { qInfo(Q_FUNC_INFO); setWindowOpacity(value * .01); } void FindReplaceDialog::transparencyToggled(bool on) { qInfo(Q_FUNC_INFO); if (on) { if (ui->radioOnLosingFocus->isChecked()) { adjustOpacityWhenLosingFocus(true); adjustOpacityAlways(false); } else { adjustOpacityWhenLosingFocus(false); adjustOpacityAlways(true); } } else { adjustOpacityWhenLosingFocus(false); adjustOpacityAlways(false); adjustOpacity(100); } } void FindReplaceDialog::adjustOpacityWhenLosingFocus(bool checked) { qInfo(Q_FUNC_INFO); if (checked) { connect(this, &FindReplaceDialog::windowActivated, [=]() { this->adjustOpacity(100); }); connect(this, &FindReplaceDialog::windowDeactivated, [=]() { this->adjustOpacity(ui->horizontalSlider->value()); }); adjustOpacity(100); } else { disconnect(this, &FindReplaceDialog::windowActivated, nullptr, nullptr); disconnect(this, &FindReplaceDialog::windowDeactivated, nullptr, nullptr); } } void FindReplaceDialog::adjustOpacityAlways(bool checked) { qInfo(Q_FUNC_INFO); if (checked) { connect(ui->horizontalSlider, &QSlider::valueChanged, this, &FindReplaceDialog::adjustOpacity); adjustOpacity(ui->horizontalSlider->value()); } else { disconnect(ui->horizontalSlider, &QSlider::valueChanged, this, &FindReplaceDialog::adjustOpacity); } } void FindReplaceDialog::changeTab(int index) { if (index == 0) { ui->labelReplaceWith->setMaximumHeight(0); ui->comboReplace->setMaximumHeight(0); // The combo box isn't actually "hidden", so adjust the focus policy so it does not get tabbed to ui->comboReplace->setFocusPolicy(Qt::NoFocus); ui->buttonReplace->hide(); ui->buttonReplaceAll->hide(); ui->buttonReplaceAllInDocuments->hide(); ui->buttonCount->show(); ui->buttonFindAllInCurrent->show(); ui->buttonFindAllInDocuments->show(); } else if (index == 1) { ui->labelReplaceWith->setMaximumHeight(QWIDGETSIZE_MAX); ui->comboReplace->setMaximumHeight(QWIDGETSIZE_MAX); ui->comboReplace->setFocusPolicy(Qt::StrongFocus); // Reset its focus policy ui->buttonReplace->show(); ui->buttonReplaceAll->show(); ui->buttonReplaceAllInDocuments->show(); ui->buttonCount->hide(); ui->buttonFindAllInCurrent->hide(); ui->buttonFindAllInDocuments->hide(); } ui->comboFind->setFocus(); ui->comboFind->lineEdit()->selectAll(); } QString FindReplaceDialog::findString() { return ui->comboFind->currentText(); } QString FindReplaceDialog::replaceString() { return ui->comboReplace->currentText(); } void FindReplaceDialog::setSearchResultsHandler(ISearchResultsHandler *searchResults) { this->searchResultsHandler = searchResults; } void FindReplaceDialog::prepareToPerformSearch(bool replace) { qInfo(Q_FUNC_INFO); QString findText = findString(); updateFindList(findText); if (replace) { QString replaceText = replaceString(); updateReplaceList(replaceText); } statusBar->clearMessage(); if (ui->radioExtendedSearch->isChecked()) { convertToExtended(findText); //convertToExtended(replaceText); } finder->setWrap(ui->checkBoxWrapAround->isChecked()); finder->setSearchFlags(computeSearchFlags()); finder->setSearchText(findText); } void FindReplaceDialog::loadSettings() { qInfo(Q_FUNC_INFO); ApplicationSettings settings; settings.beginGroup("FindReplaceDialog"); ui->comboFind->addItems(settings.value("RecentSearchList").toStringList()); ui->comboReplace->addItems(settings.value("RecentReplaceList").toStringList()); ui->checkBoxBackwardsDirection->setChecked(settings.value("Backwards").toBool()); ui->checkBoxMatchWholeWord->setChecked(settings.value("WholeWord").toBool()); ui->checkBoxMatchCase->setChecked(settings.value("MatchCase").toBool()); ui->checkBoxWrapAround->setChecked(settings.value("WrapAround", true).toBool()); if (settings.contains("SearchMode")) { const QString searchMode = settings.value("SearchMode").toString(); if (searchMode == "normal") ui->radioNormalSearch->setChecked(true); else if (searchMode == "extended") ui->radioExtendedSearch->setChecked(true); else ui->radioRegexSearch->setChecked(true); } ui->checkBoxRegexMatchesNewline->setChecked(settings.value("DotMatchesNewline").toBool()); ui->transparency->setChecked(settings.value("TransparencyUsed").toBool()); if (ui->transparency->isChecked()) { ui->horizontalSlider->setValue(settings.value("Transparency", 70).toInt()); if (settings.value("TransparencyMode").toString() == "focus") { ui->radioOnLosingFocus->setChecked(true); } else { ui->radioAlways->setChecked(true); } } settings.endGroup(); } void FindReplaceDialog::saveSettings() { qInfo(Q_FUNC_INFO); ApplicationSettings settings; settings.beginGroup("FindReplaceDialog"); settings.remove(""); // clear out any previous keys QStringList recentSearches; for (int i = 0; i < ui->comboFind->count(); ++i) { recentSearches << ui->comboFind->itemText(i); } settings.setValue("RecentSearchList", recentSearches); recentSearches.clear(); for (int i = 0; i < ui->comboReplace->count(); ++i) { recentSearches << ui->comboReplace->itemText(i); } settings.setValue("RecentReplaceList", recentSearches); settings.setValue("Backwards", ui->checkBoxBackwardsDirection->isChecked()); settings.setValue("WholeWord", ui->checkBoxMatchWholeWord->isChecked()); settings.setValue("MatchCase", ui->checkBoxMatchCase->isChecked()); settings.setValue("WrapAround", ui->checkBoxWrapAround->isChecked()); if (ui->radioNormalSearch->isChecked()) settings.setValue("SearchMode", "normal"); else if (ui->radioExtendedSearch->isChecked()) settings.setValue("SearchMode", "extended"); else if (ui->radioRegexSearch->isChecked()) settings.setValue("SearchMode", "regex"); settings.setValue("DotMatchesNewline", ui->checkBoxRegexMatchesNewline->isChecked()); settings.setValue("TransparencyUsed", ui->transparency->isChecked()); if (ui->transparency->isChecked()) { settings.setValue("Transparency", ui->horizontalSlider->value()); settings.setValue("TransparencyMode", ui->radioOnLosingFocus->isChecked() ? "focus" : "always"); } settings.endGroup(); } void FindReplaceDialog::savePosition() { qInfo(Q_FUNC_INFO); lastClosedPosition = pos(); } void FindReplaceDialog::restorePosition() { qInfo(Q_FUNC_INFO); ApplicationSettings settings; if (settings.centerSearchDialog()) { const QPoint centerPoint = parentWidget()->geometry().center(); move(centerPoint - rect().center()); } else { move(lastClosedPosition); } } int FindReplaceDialog::computeSearchFlags() { int flags = 0; if (ui->checkBoxMatchWholeWord->isChecked()) flags |= SCFIND_WHOLEWORD; if (ui->checkBoxMatchCase->isChecked()) flags |= SCFIND_MATCHCASE; if (ui->radioRegexSearch->isChecked()) flags |= SCFIND_REGEXP; return flags; } void FindReplaceDialog::showMessage(const QString &message, const QString &color) { statusBar->setStyleSheet(QStringLiteral("color: %1").arg(color)); statusBar->showMessage(message); }
18,217
C++
.cpp
485
31.956701
154
0.693396
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,351
MacroRunDialog.cpp
dail8859_NotepadNext/src/NotepadNext/dialogs/MacroRunDialog.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "MacroManager.h" #include "MacroRunDialog.h" #include "ui_MacroRunDialog.h" MacroRunDialog::MacroRunDialog(QWidget *parent, MacroManager *mm) : QDialog(parent, Qt::Tool), ui(new Ui::MacroRunDialog), macroManager(mm) { ui->setupUi(this); connect(ui->buttonRun, &QPushButton::clicked, this, [=]() { Macro *selectedMacro = ui->comboBox->currentData().value<Macro*>(); int times = -1; // for end of file if (ui->radioExecute->isChecked()) { times = ui->spinTimes->value(); } emit execute(selectedMacro, times); }); } MacroRunDialog::~MacroRunDialog() { delete ui; } void MacroRunDialog::showEvent(QShowEvent *event) { ui->comboBox->clear(); if (macroManager->hasCurrentUnsavedMacro()) { ui->comboBox->addItem(macroManager->getCurrentMacro()->getName(), QVariant::fromValue(macroManager->getCurrentMacro())); } for (Macro *macro : macroManager->availableMacros()) { ui->comboBox->addItem(macro->getName(), QVariant::fromValue(macro)); } QDialog::showEvent(event); }
1,830
C++
.cpp
50
32.62
128
0.706282
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,352
ColumnEditorDialog.cpp
dail8859_NotepadNext/src/NotepadNext/dialogs/ColumnEditorDialog.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "ColumnEditorDialog.h" #include "UndoAction.h" #include "ui_ColumnEditorDialog.h" ColumnEditorDialog::ColumnEditorDialog(MainWindow *parent) : QDialog(parent), ui(new Ui::ColumnEditorDialog), parent(parent) { setWindowFlag(Qt::WindowContextHelpButtonHint, false); ui->setupUi(this); ui->sbxStart->setMaximum(std::numeric_limits<int>::max()); ui->sbxStart->setMinimum(std::numeric_limits<int>::min()); ui->sbxStep->setMaximum(std::numeric_limits<int>::max()); ui->sbxStep->setMinimum(std::numeric_limits<int>::min()); connect(ui->gbxText, &QGroupBox::toggled, ui->gbxNumbers, [=](bool on) { ui->gbxNumbers->setChecked(!on); }); connect(ui->gbxNumbers, &QGroupBox::toggled, ui->gbxText, [=](bool on) { ui->gbxText->setChecked(!on); }); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, [=]() { if (ui->gbxText->isChecked() && !ui->txtText->text().isEmpty()) { insertTextStartingAtCurrentColumn([=]() { return ui->txtText->text(); }); } else if (ui->gbxNumbers->isChecked()) { int currentValue = ui->sbxStart->value(); insertTextStartingAtCurrentColumn([&currentValue, this]() { const QString s = QString::number(currentValue); currentValue += ui->sbxStep->value(); return s; }); } }); ui->txtText->setFocus(); } ColumnEditorDialog::~ColumnEditorDialog() { delete ui; } void ColumnEditorDialog::insertTextStartingAtCurrentColumn(const std::function<QString ()> &f) { ScintillaNext *editor = parent->currentEditor(); if (editor->selectionMode() == SC_SEL_STREAM && editor->selections() == 1 && editor->selectionEmpty()) { const int currentPos = editor->selectionNCaret(0); // If the cursor is in virtual space, the call to selectionNCaretVirtualSpace will be > 0 const int currentColumn = editor->column(currentPos) + editor->selectionNCaretVirtualSpace(0); const UndoAction ua(editor); for (int line = editor->lineFromPosition(currentPos); line < editor->lineCount(); ++line) { insertTextAtColumn(editor, line, currentColumn, f()); } } else/* if (editor->selectionMode() == SC_SEL_RECTANGLE || editor->selections() > 0)*/ { const int totalSelections = editor->selections(); // TODO: sort selections from top to bottom? const UndoAction ua(editor); for(int selection = 0; selection < totalSelections; ++selection) { const int start = editor->selectionNStart(selection) + editor->selectionNStartVirtualSpace(selection); const int end = editor->selectionNEnd(selection) + editor->selectionNEndVirtualSpace(selection); editor->setTargetRange(start, end); editor->replaceTarget(-1, f().toUtf8().constData()); } } } void ColumnEditorDialog::insertTextAtColumn(ScintillaNext *editor, int line, int column, const QString &str) { const int lineEndPosition = editor->lineEndPosition(line); const int lineEndColumn = editor->column(lineEndPosition); // If the line does not end past the needed column, then use the left over as virtual space if (lineEndColumn < column) { editor->setTargetRange(lineEndPosition, lineEndPosition); editor->setTargetStartVirtualSpace(column - lineEndColumn); editor->setTargetEndVirtualSpace(column - lineEndColumn); } else { const int pos = editor->findColumn(line, column); editor->setTargetRange(pos, pos); } editor->replaceTarget(-1, str.toUtf8().constData()); }
4,405
C++
.cpp
96
39.75
114
0.682147
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,353
StatusLabel.cpp
dail8859_NotepadNext/src/NotepadNext/widgets/StatusLabel.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "StatusLabel.h"
755
C++
.cpp
18
39.888889
73
0.760218
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,354
EditorInfoStatusBar.cpp
dail8859_NotepadNext/src/NotepadNext/widgets/EditorInfoStatusBar.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "EditorInfoStatusBar.h" #include "MainWindow.h" #include "StatusLabel.h" EditorInfoStatusBar::EditorInfoStatusBar(QMainWindow *window) : QStatusBar(window) { // Set up the status bar docType = new StatusLabel(); addWidget(docType, 1); docSize = new StatusLabel(200); addPermanentWidget(docSize, 0); docPos = new StatusLabel(250); addPermanentWidget(docPos, 0); eolFormat = new StatusLabel(100); addPermanentWidget(eolFormat, 0); unicodeType = new StatusLabel(125); addPermanentWidget(unicodeType, 0); overType = new StatusLabel(25); addPermanentWidget(overType, 0); /* docType->setContextMenuPolicy(Qt::CustomContextMenu); connect(docType, &QLabel::customContextMenuRequested, [=](const QPoint &pos) { ui->menuLanguage->popup(docType->mapToGlobal(pos)); }); eolFormat->setContextMenuPolicy(Qt::CustomContextMenu); connect(eolFormat, &QLabel::customContextMenuRequested, [=](const QPoint &pos) { ui->menuEOLConversion->popup(eolFormat->mapToGlobal(pos)); }); */ MainWindow *w = qobject_cast<MainWindow *>(window); connect(w, &MainWindow::editorActivated, this, &EditorInfoStatusBar::connectToEditor); connect(qobject_cast<StatusLabel*>(overType), &StatusLabel::clicked, w, [=]() { ScintillaNext *editor = w->currentEditor(); editor->editToggleOvertype(); updateOverType(editor); }); } void EditorInfoStatusBar::refresh(ScintillaNext *editor) { updateDocumentSize(editor); updateSelectionInfo(editor); updateLanguage(editor); updateEol(editor); updateEncoding(editor); updateOverType(editor); } void EditorInfoStatusBar::connectToEditor(ScintillaNext *editor) { // Remove any previous connections disconnect(editorUiUpdated); disconnect(documentLexerChanged); // Connect to the new editor editorUiUpdated = connect(editor, &ScintillaNext::updateUi, this, &EditorInfoStatusBar::editorUpdated); documentLexerChanged = connect(editor, &ScintillaNext::lexerChanged, this, [=]() { updateLanguage(editor); }); refresh(editor); } void EditorInfoStatusBar::editorUpdated(Scintilla::Update updated) { ScintillaNext *editor = qobject_cast<ScintillaNext *>(sender()); if (Scintilla::FlagSet(updated, Scintilla::Update::Content)) { updateDocumentSize(editor); } if (Scintilla::FlagSet(updated, Scintilla::Update::Content) || Scintilla::FlagSet(updated, Scintilla::Update::Selection)) { updateSelectionInfo(editor); } } void EditorInfoStatusBar::updateDocumentSize(ScintillaNext *editor) { QString sizeText = tr("Length: %L1 Lines: %L2").arg(editor->length()).arg(editor->lineCount()); docSize->setText(sizeText); } void EditorInfoStatusBar::updateSelectionInfo(ScintillaNext *editor) { QString selectionText; if (editor->selections() > 1) { selectionText = tr("Sel: N/A"); } else { int start = editor->selectionStart(); int end = editor->selectionEnd(); int lines = editor->lineFromPosition(end) - editor->lineFromPosition(start); if (end > start) lines++; selectionText = tr("Sel: %L1 | %L2").arg(editor->countCharacters(start, end)).arg(lines); } const int pos = editor->currentPos(); QString positionText = tr("Ln: %L1 Col: %L2 ").arg(editor->lineFromPosition(pos) + 1).arg(editor->column(pos) + 1); docPos->setText(positionText + selectionText); } void EditorInfoStatusBar::updateLanguage(ScintillaNext *editor) { docType->setText(editor->languageName); } void EditorInfoStatusBar::updateEol(ScintillaNext *editor) { // No good way to keep these in sync with the Main Window menu items :( switch(editor->eOLMode()) { case SC_EOL_CR: eolFormat->setText(tr("Macintosh (CR)")); break; case SC_EOL_CRLF: eolFormat->setText(tr("Windows (CR LF)")); break; case SC_EOL_LF: eolFormat->setText(tr("Unix (LF)")); break; } } void EditorInfoStatusBar::updateEncoding(ScintillaNext *editor) { switch(editor->codePage()) { case 0: unicodeType->setText(tr("ANSI")); break; case SC_CP_UTF8: unicodeType->setText(tr("UTF-8")); break; default: unicodeType->setText(QString::number(editor->codePage())); break; } } void EditorInfoStatusBar::updateOverType(ScintillaNext *editor) { bool overtype = editor->overtype(); if (overtype) { //: This is a short abbreviation to indicate characters will be replaced when typing overType->setText(tr("OVR")); } else { //: This is a short abbreviation to indicate characters will be inserted when typing overType->setText(tr("INS")); } }
5,553
C++
.cpp
151
31.953642
127
0.702365
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,355
SmartHighlighter.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/SmartHighlighter.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "SmartHighlighter.h" using namespace Scintilla; SmartHighlighter::SmartHighlighter(ScintillaNext *editor) : EditorDecorator(editor) { setObjectName("SmartHighlighter"); indicator = editor->allocateIndicator("smart_highlighter"); editor->indicSetFore(indicator, 0x00FF00); editor->indicSetStyle(indicator, INDIC_ROUNDBOX); editor->indicSetOutlineAlpha(indicator, 150); editor->indicSetAlpha(indicator, 100); editor->indicSetUnder(indicator, true); } void SmartHighlighter::notify(const NotificationData *pscn) { if (pscn->nmhdr.code == Notification::UpdateUI && (FlagSet(pscn->updated, Update::Content) || FlagSet(pscn->updated, Update::Selection))) { highlightCurrentView(); } } void SmartHighlighter::highlightCurrentView() { editor->setIndicatorCurrent(indicator); editor->indicatorClearRange(0, editor->length()); if (editor->selectionEmpty()) { return; } const int mainSelection = editor->mainSelection(); const int selectionStart = editor->selectionNStart(mainSelection); const int selectionEnd = editor->selectionNEnd(mainSelection); // Make sure the current selection is valid if (selectionStart == selectionEnd) { return; } const int curPos = editor->currentPos(); const int wordStart = editor->wordStartPosition(curPos, true); const int wordEnd = editor->wordEndPosition(wordStart, true); // Make sure the selection is on word boundaries if (wordStart == wordEnd || wordStart != selectionStart || wordEnd != selectionEnd) { return; } const QByteArray selText = editor->get_text_range(selectionStart, selectionEnd); // TODO: Handle large files. By default Notepad++ only monitors the text on screen. However, // that will not work when using a highlighted scroll bar. Testing with small files seems to // have minimal impact. For large files, Qt can have a timer set to 0 to do heavier processing. // Using threads seems to be a bit overkill and too burdensome to do it properly. //const int startLine = editor->firstVisibleLine(); //const int linesOnScreen = editor->linesOnScreen(); //const int startPos = editor->positionFromLine(startLine); //const int endPos = editor->lineEndPosition(startLine + linesOnScreen); // TODO: skip hidden or folded lines? Sci_TextToFind ttf {{0, (Sci_PositionCR)editor->length()}, selText.constData(), {-1, -1}}; const int flags = SCFIND_MATCHCASE | SCFIND_WHOLEWORD; while (editor->send(SCI_FINDTEXT, flags, (sptr_t)&ttf) != -1) { editor->indicatorFillRange(ttf.chrgText.cpMin, ttf.chrgText.cpMax - ttf.chrgText.cpMin); ttf.chrg.cpMin = ttf.chrgText.cpMax; } }
3,468
C++
.cpp
74
42.567568
143
0.731476
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,356
EditorConfigAppDecorator.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/EditorConfigAppDecorator.cpp
/* * This file is part of Notepad Next. * Copyright 2021 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "EditorConfigAppDecorator.h" #include "EditorManager.h" #include "ScintillaNext.h" #include "Finder.h" #include "EditorConfig.h" class PreventUnfolding { public: explicit PreventUnfolding(ScintillaNext *editor) : editor(editor) { foldFlags = editor->automaticFold(); editor->setAutomaticFold(0); } ~PreventUnfolding() { editor->setAutomaticFold(foldFlags); } private: ScintillaNext *editor; int foldFlags; }; EditorConfigAppDecorator::EditorConfigAppDecorator(NotepadNextApplication *app) : ApplicationDecorator(app) { EditorManager *manager = app->getEditorManager(); connect(manager, &EditorManager::editorCreated, this, &EditorConfigAppDecorator::doEditorConfig); // TODO: on editor reload } void EditorConfigAppDecorator::doEditorConfig(ScintillaNext *editor) { if (this->isEnabled()) { if (editor->isFile()) { EditorConfigSettings settings = EditorConfig::getFileSettings(editor->getFilePath()); qDebug() << "EditorConfig settings for:" << editor->getFilePath(); for(auto &setting : settings.toStdMap()) { qDebug() << setting.first << "=" << setting.second; } if (settings.contains(QStringLiteral("indent_style"))) { if (settings[QStringLiteral("indent_style")] == QStringLiteral("tab")) editor->setUseTabs(true); else if (settings[QStringLiteral("indent_style")] == QStringLiteral("space")) editor->setUseTabs(false); // Set a flag so that the tab/spaces won't get overridden editor->QObject::setProperty("nn_skip_usetabs", "EditorConfig"); } if (settings.contains(QStringLiteral("indent_size")) && settings[QStringLiteral("indent_size")].toInt() > 0) { editor->setIndent(settings[QStringLiteral("indent_size")].toInt()); } if (settings.contains(QStringLiteral("tab_width")) && settings[QStringLiteral("tab_width")].toInt() > 0) { editor->setTabWidth(settings[QStringLiteral("tab_width")].toInt()); // Set a flag so that the tab width won't get overridden editor->QObject::setProperty("nn_skip_tabwidth", "EditorConfig"); } if (settings.contains(QStringLiteral("end_of_line"))) { if (settings[QStringLiteral("end_of_line")] == QStringLiteral("lf")) editor->setEOLMode(SC_EOL_LF); else if (settings[QStringLiteral("end_of_line")] == QStringLiteral("cr")) editor->setEOLMode(SC_EOL_CR); else if (settings[QStringLiteral("end_of_line")] == QStringLiteral("crlf")) editor->setEOLMode(SC_EOL_CRLF); } if (settings.contains(QStringLiteral("trim_trailing_whitespace"))) { if (settings[QStringLiteral("trim_trailing_whitespace")] == QStringLiteral("true")) { connect(editor, &ScintillaNext::aboutToSave, this, &EditorConfigAppDecorator::trimTrailingWhitespace); } } if (settings.contains(QStringLiteral("insert_final_newline"))) { if (settings[QStringLiteral("insert_final_newline")] == QStringLiteral("true")) { connect(editor, &ScintillaNext::aboutToSave, this, &EditorConfigAppDecorator::ensureFinalNewline); } else if (settings[QStringLiteral("insert_final_newline")] == QStringLiteral("false")) { connect(editor, &ScintillaNext::aboutToSave, this, &EditorConfigAppDecorator::ensureNoFinalNewline); } } } } } void EditorConfigAppDecorator::trimTrailingWhitespace() { ScintillaNext *editor = qobject_cast<ScintillaNext *>(sender()); Finder f(editor); const PreventUnfolding pu(editor); // NOTE: see note in QRegexSearch about (*ANYCRLF) f.setSearchText("(*ANYCRLF)[ \t]+$"); f.setSearchFlags(SCFIND_REGEXP); f.replaceAll(""); } void EditorConfigAppDecorator::ensureFinalNewline() { ScintillaNext *editor = qobject_cast<ScintillaNext *>(sender()); const PreventUnfolding pu(editor); const int lastLine = editor->lineCount() - 1; const int lastLineLength = editor->lineEndPosition(lastLine) - editor->positionFromLine(lastLine); if (lastLineLength != 0) { switch (editor->eOLMode()) { case SC_EOL_CRLF: editor->appendText(2, "\r\n"); break; case SC_EOL_CR: editor->appendText(1, "\r"); break; case SC_EOL_LF: editor->appendText(1, "\n"); break; } } } void EditorConfigAppDecorator::ensureNoFinalNewline() { ScintillaNext *editor = qobject_cast<ScintillaNext *>(sender()); const PreventUnfolding pu(editor); editor->deleteTrailingEmptyLines(); }
5,645
C++
.cpp
123
37.731707
124
0.654056
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,357
URLFinder.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/URLFinder.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include <QDesktopServices> #include <QTimer> #include <QUrl> #include "URLFinder.h" URLFinder::URLFinder(ScintillaNext *editor) : EditorDecorator(editor), timer(new QTimer(this)) { // Setup the indicator indicator = editor->allocateIndicator("url_finder"); editor->indicSetStyle(indicator, INDIC_PLAIN); editor->indicSetFore(indicator, 0xFF0000); editor->indicSetHoverStyle(indicator, INDIC_DOTS); editor->indicSetHoverFore(indicator, 0xFF0000); // Resizing the window could reveal more text connect(editor, &ScintillaNext::resized, timer, qOverload<>(&QTimer::start)); timer->setInterval(200); timer->setSingleShot(true); connect(timer, &QTimer::timeout, this, &URLFinder::findURLs); } void URLFinder::findURLs() { //qInfo(Q_FUNC_INFO); editor->setIndicatorCurrent(indicator); editor->indicatorClearRange(0, editor->length()); int currentLine = editor->docLineFromVisible(editor->firstVisibleLine()); int linesLeftToProcess = editor->linesOnScreen(); const int flags = SCFIND_REGEXP; while(linesLeftToProcess >= 0 && currentLine < editor->lineCount()) { // Should only happen if the line is hidden if (!editor->lineVisible(currentLine)) { currentLine++; continue; } const int startPos = editor->positionFromLine(currentLine); const int endPos = editor->lineEndPosition(currentLine); QByteArray reg = QByteArrayLiteral(R"(\bhttps?://[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*))"); Sci_TextToFind ttf {{startPos, (Sci_PositionCR)endPos}, reg.constData(), {-1, -1}}; while (editor->send(SCI_FINDTEXT, flags, (sptr_t)&ttf) != -1) { const int startUrl = ttf.chrgText.cpMin; int endUrl = ttf.chrgText.cpMax; // Though technically certain characters are allowed in the URL such as brackets, parenthesis, etc // this adds a bit of logic to trim off the end character based on if something is in front if it, for example // [https://example.com] probably shouldn't include the last bracket since it starts with an opening bracket. if (startUrl > 0) { const int prevChar = static_cast<int>(editor->charAt(startUrl - 1)); const int nextChar = static_cast<int>(editor->charAt(endUrl - 1)); if ((prevChar == '(' && nextChar == ')') || (prevChar == '[' && nextChar == ']') || (prevChar == '<' && nextChar == '>') || (prevChar == '"' && nextChar == '"')) { endUrl--; } } editor->indicatorFillRange(startUrl, endUrl - startUrl); ttf.chrg.cpMin = endUrl; } // If a line is wrapped, skip however many lines it takes up on the screen linesLeftToProcess -= editor->wrapCount(currentLine); // If the current line is a fold header and the fold is not expanded, skip if (((editor->foldLevel(currentLine) & SC_FOLDLEVELHEADERFLAG) == SC_FOLDLEVELHEADERFLAG) && (!editor->foldExpanded(currentLine))) { currentLine = editor->lastChild(currentLine, -1) + 1; } else { currentLine++; } } } void URLFinder::notify(const Scintilla::NotificationData *pscn) { // TODO: handle editor folding/unfolding // Currently there is no generic notification for this // Reprocess any time the content was updated or the editor was vertically scrolled if ((pscn->nmhdr.code == Scintilla::Notification::UpdateUI)) { if (FlagSet(pscn->updated, Scintilla::Update::VScroll)) { timer->start(); } } else if (pscn->nmhdr.code == Scintilla::Notification::Modified) { if (FlagSet(pscn->modificationType, Scintilla::ModificationFlags::InsertText) || FlagSet(pscn->modificationType, Scintilla::ModificationFlags::DeleteText)) { timer->start(); } } else if (pscn->nmhdr.code == Scintilla::Notification::Zoom) { timer->start(); } else if (pscn->nmhdr.code == Scintilla::Notification::IndicatorClick && FlagSet(pscn->modifiers, Scintilla::KeyMod::Ctrl)) { const int indicators = editor->indicatorAllOnFor(pscn->position); if (indicators & (1 << indicator)) { const int indicatorStart = editor->indicatorStart(indicator, pscn->position); const int indicatorEnd = editor->indicatorEnd(indicator, pscn->position); QUrl url(editor->get_text_range(indicatorStart, indicatorEnd)); if (url.isValid()) { qInfo("URL hotspot click: \"%s\"", editor->get_text_range(indicatorStart, indicatorEnd).constData()); QDesktopServices::openUrl(url); } else { qWarning("Invalid url \"%s\"", qUtf8Printable(url.errorString())); } } } } bool URLFinder::isURL(int position) const { const int indicators = editor->indicatorAllOnFor(position); return indicators & (1 << indicator); } void URLFinder::copyURLToClipboard(int position) const { const int indicatorStart = editor->indicatorStart(indicator, position); const int indicatorEnd = editor->indicatorEnd(indicator, position); QUrl url(editor->get_text_range(indicatorStart, indicatorEnd)); if (url.isValid()) { qInfo("Copy URL to clipboard: \"%s\"", editor->get_text_range(indicatorStart, indicatorEnd).constData()); editor->copyRange(indicatorStart, indicatorEnd); } else { qWarning("Invalid url \"%s\"", qUtf8Printable(url.errorString())); } }
6,451
C++
.cpp
137
39.656934
165
0.650756
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,358
SurroundSelection.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/SurroundSelection.cpp
/* * This file is part of Notepad Next. * Copyright 2020 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "SurroundSelection.h" #include <QEvent> #include <QKeyEvent> SurroundSelection::SurroundSelection(ScintillaNext *editor) : EditorDecorator(editor) { setObjectName("SurroundSelection"); editor->installEventFilter(this); } bool SurroundSelection::eventFilter(QObject *obj, QEvent *event) { Q_UNUSED(obj) if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (editor->selectionEmpty() == false) { switch (keyEvent->key()) { case Qt::Key_Apostrophe: surroundSelections('\'', '\''); return true; case Qt::Key_QuoteDbl: surroundSelections('"', '"'); return true; case Qt::Key_QuoteLeft: surroundSelections('`', '`'); return true; case Qt::Key_ParenLeft: case Qt::Key_ParenRight: surroundSelections('(', ')'); return true; case Qt::Key_BraceLeft: case Qt::Key_BraceRight: surroundSelections('{', '}'); return true; case Qt::Key_BracketLeft: case Qt::Key_BracketRight: surroundSelections('[', ']'); return true; } } } return false; } void SurroundSelection::notify(const Scintilla::NotificationData *pscn) { Q_UNUSED(pscn) } void SurroundSelection::surroundSelections(const char ch1, const char ch2) { std::vector<std::pair<int, int>> selections; int num = editor->selections(); for (int i = 0; i < num; ++i) { int start = editor->selectionNStart(i); int end = editor->selectionNEnd(i); if (start != end /* && editor.LineFromPosition(start) == editor.LineFromPosition(end) */) selections.push_back(std::make_pair(start, end)); } // Sort so they are replaced top to bottom std::sort(selections.begin(), selections.end()); editor->beginUndoAction(); editor->clearSelections(); int offset = 0; for (size_t i = 0; i < selections.size(); ++i) { const auto &selection = selections[i]; editor->setTargetRange(selection.first + offset, selection.second + offset); QByteArray target = editor->targetText(); // Add in the characters target.push_front(ch1); target.push_back(ch2); editor->replaceTarget(target.length(), target.data()); // leave cursor at end of insertion if (i == 0) editor->setSelection(selection.second + offset + 1, selection.first + offset + 1); else editor->addSelection(selection.second + offset + 1, selection.first + offset + 1); offset += 2; // Add 2 since the replaced string is 2 chars longer } editor->endUndoAction(); }
3,611
C++
.cpp
95
30.536842
97
0.626109
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,359
ApplicationDecorator.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/ApplicationDecorator.cpp
/* * This file is part of Notepad Next. * Copyright 2021 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "ApplicationDecorator.h" void ApplicationDecorator::setEnabled(bool b) { enabled = b; emit stateChanged(enabled); }
863
C++
.cpp
23
35.347826
73
0.761051
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,360
LineNumbers.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/LineNumbers.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "LineNumbers.h" using namespace Scintilla; static inline int countDigits(quint32 x) { // Ugly but efficient return (x < 10 ? 1 : (x < 100 ? 2 : (x < 1000 ? 3 : (x < 10000 ? 4 : (x < 100000 ? 5 : (x < 1000000 ? 6 : (x < 10000000 ? 7 : (x < 100000000 ? 8 : (x < 1000000000 ? 9 : 10))))))))); } LineNumbers::LineNumbers(ScintillaNext *editor) : EditorDecorator(editor) { editor->setMarginWidthN(0, 0); connect(this, &EditorDecorator::stateChanged, editor, [=](bool b) { if (b) { adjustMarginWidth(); } else { editor->setMarginWidthN(0, 0); } }); } void LineNumbers::adjustMarginWidth() { int lineCount = editor->lineCount(); int pixelWidth = 8 + (qMax(countDigits(lineCount), 3)) * editor->textWidth(STYLE_LINENUMBER, "8"); editor->setMarginWidthN(0, pixelWidth); } void LineNumbers::notify(const NotificationData *pscn) { if ((pscn->nmhdr.code == Notification::UpdateUI && FlagSet(pscn->updated, Update::VScroll)) || (pscn->nmhdr.code == Notification::Zoom)) { adjustMarginWidth(); } }
1,935
C++
.cpp
58
28.37931
142
0.64794
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,361
AutoCompletion.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/AutoCompletion.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "AutoCompletion.h" #include <QSet> using namespace Scintilla; AutoCompletion::AutoCompletion(ScintillaNext *editor) : EditorDecorator(editor) { editor->autoCSetOrder(SC_ORDER_PERFORMSORT); editor->autoCSetMaxHeight(10); } void AutoCompletion::notify(const NotificationData *pscn) { if (pscn->nmhdr.code == Notification::CharAdded) { if (editor->autoCActive()) return; showAutoCompletion(); } } void AutoCompletion::showAutoCompletion() { int curPos = editor->currentPos(); int startPos = editor->wordStartPosition(curPos, true); int endPos = editor->wordEndPosition(curPos, true); // Need a minimum number of characters to trigger auto completion if ((curPos - startPos) < 3) return; const QByteArray current_word = editor->get_text_range(startPos, curPos); const QByteArray regex = "\\b" + current_word + "[\\w]*"; QSet<QByteArray> words; editor->setSearchFlags(SCFIND_REGEXP | SCFIND_MATCHCASE); // Don't want to find the word that's currently being typed // Find everything before this word editor->forEachMatchInRange(regex, [&](int start, int end) { words.insert(editor->get_text_range(start, end)); return end; }, { 0, startPos}); // Find everything after this word editor->forEachMatchInRange(regex, [&](int start, int end) { words.insert(editor->get_text_range(start, end)); return end; }, { endPos, (Sci_PositionCR)editor->length()}); if (!words.isEmpty()) { editor->autoCShow(current_word.length(), words.values().join(' ')); } }
2,360
C++
.cpp
61
34.409836
77
0.706088
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,362
BookMarkDecorator.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/BookMarkDecorator.cpp
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "BookMarkDecorator.h" const int MARK_BOOKMARK = 24; const int MARGIN = 1; BookMarkDecorator::BookMarkDecorator(ScintillaNext *editor) : EditorDecorator(editor) { editor->markerSetAlpha(MARK_BOOKMARK, 70); editor->markerDefine(MARK_BOOKMARK, SC_MARK_BOOKMARK); editor->markerSetFore(MARK_BOOKMARK, 0xFF2020); editor->markerSetBack(MARK_BOOKMARK, 0xFF2020); int mask = editor->marginMaskN(MARGIN); editor->setMarginMaskN(MARGIN, (1 << MARK_BOOKMARK) | mask); editor->setMarginSensitiveN(MARGIN, true); } void BookMarkDecorator::toggleBookmark(int line) { if (editor->markerGet(line) & (1 << MARK_BOOKMARK)) { // The marker can be set multiple times, so keep deleting it till it is no longer set while (editor->markerGet(line) & (1 << MARK_BOOKMARK)) { editor->markerDelete(line, MARK_BOOKMARK); } } else { editor->markerAdd(line, MARK_BOOKMARK); } } int BookMarkDecorator::nextBookmarkAfter(int line) { int nextMarkedLine = editor->markerNext(line, 1 << MARK_BOOKMARK); if (nextMarkedLine == -1) { return editor->markerNext(0, 1 << MARK_BOOKMARK); } else { return nextMarkedLine; } } int BookMarkDecorator::previousBookMarkBefore(int line) { int prevMarkedLine = editor->markerPrevious(line, 1 << MARK_BOOKMARK); if (prevMarkedLine == -1) { return editor->markerPrevious(editor->lineCount(), 1 << MARK_BOOKMARK); } else { return prevMarkedLine; } } void BookMarkDecorator::clearBookmarks() { editor->markerDeleteAll(MARK_BOOKMARK); } QList<int> BookMarkDecorator::bookMarkedLines() const { QList<int> bookMarkedLines; int line = 0; forever { line = editor->markerNext(line, 1 << MARK_BOOKMARK); if (line != -1) { bookMarkedLines.append(line); line++; } else { break; } } return bookMarkedLines; } void BookMarkDecorator::setBookMarkedLines(QList<int> &lines) { for(const int i : lines) { editor->markerAdd(i, MARK_BOOKMARK); } } void BookMarkDecorator::notify(const Scintilla::NotificationData *pscn) { if (pscn->nmhdr.code == Scintilla::Notification::MarginClick) { if (pscn->margin == MARGIN) { int line = editor->lineFromPosition(pscn->position); toggleBookmark(line); } } }
3,158
C++
.cpp
98
27.530612
93
0.687377
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,363
BetterMultiSelection.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/BetterMultiSelection.cpp
/* * This file is part of Notepad Next. * Copyright 2021 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include <QEvent> #include <QKeyEvent> #include "BetterMultiSelection.h" struct Selection { int caret; int anchor; Selection(int caret, int anchor) : caret(caret), anchor(anchor) {} int start() const { return qMin(caret, anchor); } int end() const { return qMax(caret, anchor); } int length() const { return end() - start(); } void set(int pos) { anchor = caret = pos; } void offset(int offset) { anchor += offset; caret += offset; } }; template<typename It> It uniquify(It begin, It const end) { std::vector<It> v; v.reserve(static_cast<size_t>(std::distance(begin, end))); for (It i = begin; i != end; ++i) v.push_back(i); std::sort(v.begin(), v.end(), [](const auto &lhs, const auto &rhs) { return (*lhs).start() < (*rhs).start() || (!((*rhs).start() < (*lhs).start()) && (*lhs).end() < (*rhs).end()); }); v.erase(std::unique(v.begin(), v.end(), [](const auto &lhs, const auto &rhs) { return (*lhs).start() == (*rhs).start() && (*lhs).end() == (*rhs).end(); }), v.end()); std::sort(v.begin(), v.end()); size_t j = 0; for (It i = begin; i != end && j != v.size(); ++i) { if (i == v[j]) { using std::iter_swap; iter_swap(i, begin); ++j; ++begin; } } return begin; } BetterMultiSelection::BetterMultiSelection(ScintillaNext *editor) : EditorDecorator(editor) { setObjectName("BetterMultiSelection"); // Allow insertion of autocompletion at each cursor editor->autoCSetMulti(SC_MULTIAUTOC_EACH); editor->installEventFilter(this); } bool BetterMultiSelection::eventFilter(QObject *obj, QEvent *event) { Q_UNUSED(obj) if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); bool isAltPresssed = (keyEvent->modifiers() & Qt::AltModifier); bool isControlPresssed = (keyEvent->modifiers() & Qt::ControlModifier); bool isShiftPressed = (keyEvent->modifiers() & Qt::ShiftModifier); if (isAltPresssed) return false; if (editor->selections() > 1) { if (isControlPresssed) { if (keyEvent->key() == Qt::Key_Left) { EditSelections(SimpleEdit(isShiftPressed ? SCI_WORDLEFTEXTEND : SCI_WORDLEFT)); return true; } else if (keyEvent->key() == Qt::Key_Right) { EditSelections(SimpleEdit(isShiftPressed ? SCI_WORDRIGHTENDEXTEND : SCI_WORDRIGHT)); return true; } else if (keyEvent->key() == Qt::Key_Back) { EditSelections(SimpleEdit(SCI_DELWORDLEFT)); return true; } else if (keyEvent->key() == Qt::Key_Delete) { EditSelections(SimpleEdit(SCI_DELWORDRIGHT)); return true; } //else if (keyEvent->key() == Qt::Key_X || keyEvent->key() == Qt::Key_C) { // if (CopyToClipboard(editor)) { // if (keyEvent->key() == Qt::Key_X) { // EditSelections(SimpleEdit(SCI_DELETEBACK)); // } // return true; // } //} //else if (keyEvent->key() == Qt::Key_V) { // if (Paste(editor)) { // return true; // } //} } else { if (keyEvent->key() == Qt::Key_Escape) { int caret = editor->selectionNCaret(editor->mainSelection()); editor->setSelection(caret, caret); return true; } else if (keyEvent->key() == Qt::Key_Left) { EditSelections(SimpleEdit(isShiftPressed ? SCI_CHARLEFTEXTEND : SCI_CHARLEFT)); return true; } else if (keyEvent->key() == Qt::Key_Right) { EditSelections(SimpleEdit(isShiftPressed ? SCI_CHARRIGHTEXTEND : SCI_CHARRIGHT)); return true; } else if (keyEvent->key() == Qt::Key_Home) { EditSelections(SimpleEdit(isShiftPressed ? SCI_VCHOMEWRAPEXTEND : SCI_VCHOMEWRAP)); return true; } else if (keyEvent->key() == Qt::Key_End) { EditSelections(SimpleEdit(isShiftPressed ? SCI_LINEENDWRAPEXTEND : SCI_LINEENDWRAP)); return true; } else if (keyEvent->key() == Qt::Key_Return) { if (!editor->autoCActive()) { EditSelections(SimpleEdit(SCI_NEWLINE)); return true; } // else just let Scintilla handle the insertion of autocompletion } else if (keyEvent->key() == Qt::Key_Up) { if (!editor->autoCActive()) { EditSelections(SimpleEdit(isShiftPressed ? SCI_LINEUPEXTEND : SCI_LINEUP)); return true; } // else just let Scintilla handle the navigation of autocompletion } else if (keyEvent->key() == Qt::Key_Down) { if (!editor->autoCActive()) { EditSelections(SimpleEdit(isShiftPressed ? SCI_LINEDOWNEXTEND : SCI_LINEDOWN)); return true; } // else just let Scintilla handle the navigation of autocompletion } } } } return false; } void BetterMultiSelection::notify(const Scintilla::NotificationData *pscn) { Q_UNUSED(pscn); } QVector<Selection> BetterMultiSelection::GetSelections() { QVector<Selection> selections; int num = editor->selections(); for (int i = 0; i < num; ++i) { int caret = editor->selectionNCaret(i); int anchor = editor->selectionNAnchor(i); selections.append(Selection{ caret, anchor }); } return selections; } void BetterMultiSelection::SetSelections(const QVector<Selection> &selections) { for (auto i = 0; i < selections.size(); ++i) { if (i == 0) editor->setSelection(selections[i].caret, selections[i].anchor); else editor->addSelection(selections[i].caret, selections[i].anchor); } } void BetterMultiSelection::EditSelections(std::function<void(Selection &selection)> edit) { auto selections = GetSelections(); editor->clearSelections(); std::sort(selections.begin(), selections.end(), [](const auto &lhs, const auto &rhs) { return lhs.start() < rhs.start() || (!(rhs.start() < lhs.start()) && lhs.end() < rhs.end()); }); editor->beginUndoAction(); int totalOffset = 0; for (auto &selection : selections) { selection.offset(totalOffset); const int length = editor->length(); edit(selection); totalOffset += editor->length() - length; } editor->endUndoAction(); selections.erase(uniquify(selections.begin(), selections.end()), selections.end()); SetSelections(selections); } std::function<void(Selection &selection)> BetterMultiSelection::SimpleEdit(int message) { return [=](Selection &selection) { editor->setSelection(selection.caret, selection.anchor); editor->send(message); selection.caret = editor->selectionNCaret(0); selection.anchor = editor->selectionNAnchor(0); }; }
8,449
C++
.cpp
200
31.85
118
0.560901
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,364
HighlightedScrollBar.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/HighlightedScrollBar.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include <QPainter> #include "HighlightedScrollBar.h" using namespace Scintilla; const int DEFAULT_TICK_HEIGHT = 3; const int DEFAULT_TICK_PADDING = 3; const QColor CURSOR_SELECTION_COLOR = QColor(0, 0, 0, 25); const QColor CURSOR_CARET_COLOR = QColor(0, 0, 0, 100); HighlightedScrollBarDecorator::HighlightedScrollBarDecorator(ScintillaNext *editor) : EditorDecorator(editor), scrollBar(new HighlightedScrollBar(editor, Qt::Vertical, editor)) { connect(scrollBar, &QScrollBar::valueChanged, editor, &ScintillaEdit::scrollVertical); editor->setVerticalScrollBar(scrollBar); } HighlightedScrollBarDecorator::~HighlightedScrollBarDecorator() { } void HighlightedScrollBarDecorator::notify(const NotificationData *pscn) { if (pscn->nmhdr.code == Notification::UpdateUI && (FlagSet(pscn->updated, Update::Content) || FlagSet(pscn->updated, Update::Selection))) { scrollBar->update(); } else if (pscn->nmhdr.code == Notification::Modified && FlagSet(pscn->modificationType, ModificationFlags::ChangeMarker)) { scrollBar->update(); } } HighlightedScrollBar::HighlightedScrollBar(ScintillaNext *editor, Qt::Orientation orientation, QWidget *parent) : QScrollBar(orientation, parent), editor(editor) { smartHighlighterIndicator = editor->allocateIndicator("smart_highlighter"); } void HighlightedScrollBar::paintEvent(QPaintEvent *event) { // Paint the default scrollbar first QScrollBar::paintEvent(event); QPainter p(this); drawMarker(p, 24); drawIndicator(p, smartHighlighterIndicator); drawCursors(p); } void HighlightedScrollBar::drawMarker(QPainter &p, int marker) { // NOTE: SCI_MARKERGETBACK doesn't exist...so can't use the marker color int curLine = 0; while ((curLine = editor->markerNext(curLine, 1 << marker)) != -1) { drawTickMark(p, lineToScrollBarY(curLine), DEFAULT_TICK_HEIGHT, QColor(100, 100, 255)); curLine++; } } void HighlightedScrollBar::drawIndicator(QPainter &p, int indicator) { int curPos = editor->indicatorEnd(indicator, 0); int color = editor->indicFore(indicator); if (curPos > 0) { while ((curPos = editor->indicatorEnd(indicator, curPos)) < editor->length()) { drawTickMark(p, posToScrollBarY(curPos), DEFAULT_TICK_HEIGHT, color); curPos = editor->indicatorEnd(indicator, curPos); } } } void HighlightedScrollBar::drawCursors(QPainter &p) { for (int i = 0; i < editor->selections() ; i++) { int startCaretY = posToScrollBarY(editor->selectionNCaret(i)); int startAnchorY = posToScrollBarY(editor->selectionNAnchor(i)); if (startCaretY != startAnchorY) { drawTickMark(p, startAnchorY, startCaretY - startAnchorY, CURSOR_SELECTION_COLOR); } drawTickMark(p, startCaretY, DEFAULT_TICK_HEIGHT, CURSOR_CARET_COLOR); } } void HighlightedScrollBar::drawTickMark(QPainter &p, int y, int height, QColor color) { p.fillRect(rect().x() + DEFAULT_TICK_PADDING, y + scrollbarArrowHeight(), rect().width() - (DEFAULT_TICK_PADDING * 2), height, color); } int HighlightedScrollBar::posToScrollBarY(int pos) const { int line = editor->visibleFromDocLine(editor->lineFromPosition(pos)); return lineToScrollBarY(line); } int HighlightedScrollBar::lineToScrollBarY(int line) const { int lineCount = editor->visibleFromDocLine(editor->lineCount()); if (!editor->endAtLastLine()) { lineCount += editor->linesOnScreen(); } return static_cast<double>(line) / lineCount * (rect().height() - scrollbarArrowHeight() * 2); } int HighlightedScrollBar::scrollbarArrowHeight() const { // NOTE: There is no official way to get the height of the scrollbar arrow buttons, however for now we can // assume that the buttons are square, meaning the height of them will be the same as the width of // the scroll bar. return rect().width(); }
4,664
C++
.cpp
111
38.099099
143
0.73236
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,365
BraceMatch.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/BraceMatch.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "Sci_Position.h" #include "BraceMatch.h" using namespace Scintilla; BraceMatch::BraceMatch(ScintillaNext *editor) : EditorDecorator(editor) { setObjectName("BraceMatch"); const int braceHighlight = editor->allocateIndicator("brace_highlight"); const int braceBadlight = editor->allocateIndicator("brace_badlight"); editor->indicSetStyle(braceHighlight, INDIC_FULLBOX); editor->indicSetFore(braceHighlight, 0x999999); editor->indicSetAlpha(braceHighlight, 100); editor->indicSetOutlineAlpha(braceHighlight, 200); editor->indicSetUnder(braceHighlight, true); editor->braceHighlightIndicator(true, braceHighlight); editor->indicSetStyle(braceBadlight, INDIC_FULLBOX); editor->indicSetFore(braceBadlight, 0x0000FF); editor->indicSetAlpha(braceBadlight, 100); editor->indicSetOutlineAlpha(braceBadlight, 200); editor->indicSetUnder(braceBadlight, true); editor->braceBadLightIndicator(true, braceBadlight); connect(this, &EditorDecorator::stateChanged, [=](bool b) { if (b) { doHighlighting(); } else { clearHighlighting(); } }); } void BraceMatch::doHighlighting() { static const QList<char> braces = {'[', ']', '(', ')', '{', '}'}; const Sci_Position pos = static_cast<Sci_Position>(editor->currentPos()); // Check the character before the caret first int match = editor->braceMatch(pos - 1, 0); if (match != INVALID_POSITION) { editor->braceHighlight(pos - 1, match); editor->setHighlightGuide(editor->column(editor->lineIndentPosition(editor->lineFromPosition(pos - 1)))); } else { // Check the character after the caret match = editor->braceMatch(pos, 0); if (match != INVALID_POSITION) { editor->braceHighlight(pos, match); editor->setHighlightGuide(editor->column(editor->lineIndentPosition(editor->lineFromPosition(pos)))); } else { // Nothing was found, now check to see if we need to badlight something // by checking the characters char c = static_cast<char>(editor->charAt(pos - 1)); if (braces.contains(c)) { editor->braceBadLight(pos - 1); } else { c = static_cast<char>(editor->charAt(pos)); if (braces.contains(c)) { editor->braceBadLight(pos); } else { clearHighlighting(); } } } } } void BraceMatch::clearHighlighting() { editor->braceHighlight(INVALID_POSITION, INVALID_POSITION); editor->setHighlightGuide(0); } void BraceMatch::notify(const NotificationData *pscn) { if (pscn->nmhdr.code == Notification::UpdateUI) { if (FlagSet(pscn->updated, Update::Content) || FlagSet(pscn->updated, Update::Selection)) { doHighlighting(); } } }
3,717
C++
.cpp
96
32.010417
114
0.662413
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,366
AutoIndentation.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/AutoIndentation.cpp
/* * This file is part of Notepad Next. * Copyright 2021 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "AutoIndentation.h" using namespace Scintilla; AutoIndentation::AutoIndentation(ScintillaNext *editor) : EditorDecorator(editor) { } void AutoIndentation::notify(const NotificationData *pscn) { if (pscn->nmhdr.code == Notification::CharAdded) { const int ch = pscn->ch; const int eolMode = editor->eOLMode(); if (((eolMode == SC_EOL_CRLF || eolMode == SC_EOL_LF) && ch == '\n') || (eolMode == SC_EOL_CR && ch == '\r')) { autoIndentLine(editor->lineFromPosition(editor->currentPos())); } } } void AutoIndentation::autoIndentLine(int line) const { const int previousLine = line - 1; const int previousIndentation = editor->lineIndentation(previousLine); if (previousIndentation > 0) { editor->setLineIndentation(line, previousIndentation); editor->gotoPos(editor->findColumn(line, previousIndentation)); } }
1,639
C++
.cpp
42
35.333333
119
0.717884
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,367
EditorDecorator.cpp
dail8859_NotepadNext/src/NotepadNext/decorators/EditorDecorator.cpp
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #include "EditorDecorator.h" void EditorDecorator::setEnabled(bool b) { enabled = b; if (enabled) { connect(editor, &ScintillaEdit::notify, this, &EditorDecorator::notify); } else { disconnect(editor, nullptr, this, nullptr); } emit stateChanged(enabled); }
1,030
C++
.cpp
29
32.413793
80
0.733936
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,373
TestLexers.cxx
dail8859_NotepadNext/src/lexilla/test/TestLexers.cxx
// Lexilla lexer library /** @file TestLexers.cxx ** Test lexers through Lexilla. **/ // Copyright 2019 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cassert> #include <string> #include <string_view> #include <vector> #include <map> #include <optional> #include <algorithm> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <filesystem> #include "ILexer.h" #include "Lexilla.h" #include "LexillaAccess.h" #include "TestDocument.h" namespace { constexpr char MakeLowerCase(char c) noexcept { if (c >= 'A' && c <= 'Z') { return c - 'A' + 'a'; } else { return c; } } [[maybe_unused]] void LowerCaseAZ(std::string &s) { std::transform(s.begin(), s.end(), s.begin(), MakeLowerCase); } int IntFromString(std::u32string_view s) noexcept { if (s.empty()) { return 0; } const bool negate = s.front() == '-'; if (negate) { s.remove_prefix(1); } int value = 0; while (!s.empty()) { value = value * 10 + s.front() - '0'; s.remove_prefix(1); } return negate ? -value : value; } bool PatternMatch(std::u32string_view pattern, std::u32string_view text) noexcept { if (pattern == text) { return true; } else if (pattern.empty()) { return false; } else if (pattern.front() == '\\') { pattern.remove_prefix(1); if (pattern.empty()) { // Escape with nothing being escaped return false; } if (text.empty()) { return false; } if (pattern.front() == text.front()) { pattern.remove_prefix(1); text.remove_prefix(1); return PatternMatch(pattern, text); } return false; } else if (pattern.front() == '*') { pattern.remove_prefix(1); if (!pattern.empty() && pattern.front() == '*') { pattern.remove_prefix(1); // "**" matches anything including "/" while (!text.empty()) { if (PatternMatch(pattern, text)) { return true; } text.remove_prefix(1); } } else { while (!text.empty()) { if (PatternMatch(pattern, text)) { return true; } if (text.front() == '/') { // "/" not matched by single "*" return false; } text.remove_prefix(1); } } assert(text.empty()); // Consumed whole text with wildcard so match if pattern consumed return pattern.empty(); } else if (text.empty()) { return false; } else if (pattern.front() == '?') { if (text.front() == '/') { return false; } pattern.remove_prefix(1); text.remove_prefix(1); return PatternMatch(pattern, text); } else if (pattern.front() == '[') { pattern.remove_prefix(1); if (pattern.empty()) { return false; } const bool positive = pattern.front() != '!'; if (!positive) { pattern.remove_prefix(1); if (pattern.empty()) { return false; } } bool inSet = false; if (!pattern.empty() && pattern.front() == ']') { // First is allowed to be ']' if (pattern.front() == text.front()) { inSet = true; } pattern.remove_prefix(1); } char32_t start = 0; while (!pattern.empty() && pattern.front() != ']') { if (pattern.front() == '-') { pattern.remove_prefix(1); if (!pattern.empty()) { const char32_t end = pattern.front(); if ((text.front() >= start) && (text.front() <= end)) { inSet = true; } } } else if (pattern.front() == text.front()) { inSet = true; } if (!pattern.empty()) { start = pattern.front(); pattern.remove_prefix(1); } } if (!pattern.empty()) { pattern.remove_prefix(1); } if (inSet != positive) { return false; } text.remove_prefix(1); return PatternMatch(pattern, text); } else if (pattern.front() == '{') { if (pattern.length() < 2) { return false; } const size_t endParen = pattern.find('}'); if (endParen == std::u32string_view::npos) { // Malformed {x} pattern return false; } std::u32string_view parenExpression = pattern.substr(1, endParen - 1); bool inSet = false; const size_t dotdot = parenExpression.find(U".."); if (dotdot != std::u32string_view::npos) { // Numeric range: {10..20} const std::u32string_view firstRange = parenExpression.substr(0, dotdot); const std::u32string_view lastRange = parenExpression.substr(dotdot+2); if (firstRange.empty() || lastRange.empty()) { // Malformed {s..e} range pattern return false; } const size_t endInteger = text.find_last_of(U"-0123456789"); if (endInteger == std::u32string_view::npos) { // No integer in text return false; } const std::u32string_view intPart = text.substr(0, endInteger+1); const int first = IntFromString(firstRange); const int last = IntFromString(lastRange); const int value = IntFromString(intPart); if ((value >= first) && (value <= last)) { inSet = true; text.remove_prefix(intPart.length()); } } else { // Alternates: {a,b,cd} size_t comma = parenExpression.find(','); for (;;) { const bool finalAlt = comma == std::u32string_view::npos; const std::u32string_view oneAlt = finalAlt ? parenExpression : parenExpression.substr(0, comma); if (oneAlt == text.substr(0, oneAlt.length())) { // match inSet = true; text.remove_prefix(oneAlt.length()); break; } if (finalAlt) { break; } parenExpression.remove_prefix(oneAlt.length() + 1); comma = parenExpression.find(','); } } if (!inSet) { return false; } pattern.remove_prefix(endParen + 1); return PatternMatch(pattern, text); } else if (pattern.front() == text.front()) { pattern.remove_prefix(1); text.remove_prefix(1); return PatternMatch(pattern, text); } return false; } bool PathMatch(std::string pattern, std::string relPath) { #if defined(_WIN32) // Convert Windows path separators to Unix std::replace(relPath.begin(), relPath.end(), '\\', '/'); #endif #if defined(_WIN32) || defined(__APPLE__) // Case-insensitive, only does ASCII but fine for test example files LowerCaseAZ(pattern); LowerCaseAZ(relPath); #endif const std::u32string patternU32 = UTF32FromUTF8(pattern); const std::u32string relPathU32 = UTF32FromUTF8(relPath); if (PatternMatch(patternU32, relPathU32)) { return true; } const size_t lastSlash = relPathU32.rfind('/'); if (lastSlash == std::string::npos) { return false; } // Match against just filename const std::u32string fileNameU32 = relPathU32.substr(lastSlash+1); return PatternMatch(patternU32, fileNameU32); } constexpr std::string_view suffixStyled = ".styled"; constexpr std::string_view suffixFolded = ".folded"; constexpr std::string_view lexerPrefix = "lexer.*"; constexpr std::string_view prefixIf = "if "; constexpr std::string_view prefixMatch = "match "; constexpr std::string_view prefixEqual = "= "; constexpr std::string_view prefixComment = "#"; std::string ReadFile(std::filesystem::path path) { std::ifstream ifs(path, std::ios::binary); std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); return content; } std::string MarkedDocument(const Scintilla::IDocument *pdoc) { assert(pdoc); std::ostringstream os(std::ios::binary); char prevStyle = -1; for (Sci_Position pos = 0; pos < pdoc->Length(); pos++) { const char styleNow = pdoc->StyleAt(pos); if (styleNow != prevStyle) { const unsigned char uStyleNow = styleNow; const unsigned int uiStyleNow = uStyleNow; os << "{" << uiStyleNow << "}"; prevStyle = styleNow; } char ch = '\0'; pdoc->GetCharRange(&ch, pos, 1); os << ch; } return os.str(); } void PrintLevel(std::ostringstream &os, int level) { const int levelNow = level & 0xFFF; const int levelNext = level >> 16; const int levelFlags = (level >> 12) & 0xF; char foldSymbol = ' '; if (level & 0x2000) foldSymbol = '+'; else if (levelNow > 0x400) foldSymbol = '|'; os << std::hex << " " << levelFlags << " " << std::setw(3) << levelNow << " " << std::setw(3) << levelNext << " " << foldSymbol << " "; } std::string FoldedDocument(const Scintilla::IDocument *pdoc) { assert(pdoc); std::ostringstream os(std::ios::binary); Sci_Position linePrev = -1; char ch = '\0'; for (Sci_Position pos = 0; pos < pdoc->Length(); pos++) { const Sci_Position lineNow = pdoc->LineFromPosition(pos); if (linePrev < lineNow) { PrintLevel(os, pdoc->GetLevel(lineNow)); linePrev = lineNow; } pdoc->GetCharRange(&ch, pos, 1); os << ch; } if (ch == '\n') { // Extra empty line PrintLevel(os, pdoc->GetLevel(linePrev + 1)); } return os.str(); } std::pair<std::string, std::string> MarkedAndFoldedDocument(const Scintilla::IDocument *pdoc) { return { MarkedDocument(pdoc), FoldedDocument(pdoc) }; } std::vector<std::string> StringSplit(const std::string_view &text, int separator) { std::vector<std::string> vs(text.empty() ? 0 : 1); for (std::string_view::const_iterator it = text.begin(); it != text.end(); ++it) { if (*it == separator) { vs.push_back(std::string()); } else { vs.back() += *it; } } return vs; } constexpr bool IsSpaceOrTab(char ch) noexcept { return (ch == ' ') || (ch == '\t'); } void PrintRanges(const std::vector<bool> &v) { std::cout << " "; std::optional<size_t> startRange; for (size_t style = 0; style <= v.size(); style++) { // Goes one past size so that final range is closed if ((style < v.size()) && v.at(style)) { if (!startRange) { startRange = style; } } else if (startRange) { const size_t endRange = style - 1; std::cout << *startRange; if (*startRange != endRange) { std::cout << "-" << endRange; } std::cout << " "; startRange.reset(); } } std::cout << "\n"; } class PropertyMap { std::string Evaluate(std::string_view text) { if (text.find(' ') != std::string_view::npos) { if (text.starts_with(prefixEqual)) { const std::string_view sExpressions = text.substr(prefixEqual.length()); std::vector<std::string> parts = StringSplit(sExpressions, ';'); if (parts.size() > 1) { for (size_t part = 1; part < parts.size(); part++) { if (parts.at(part) != parts.at(0)) { return "0"; } } return "1"; } } return {}; } else { std::optional<std::string> value = GetProperty(text); if (value) { return *value; } return {}; } } std::string Expand(std::string withVars) { constexpr size_t maxVars = 100; size_t varStart = withVars.rfind("$("); for (size_t count = 0; (count < maxVars) && (varStart != std::string::npos); count++) { const size_t varEnd = withVars.find(')', varStart + 2); if (varEnd == std::string::npos) { break; } const std::string_view whole = withVars; const std::string_view var = whole.substr(varStart + 2, varEnd - (varStart + 2)); const std::string val = Evaluate(var); withVars.erase(varStart, varEnd - varStart + 1); withVars.insert(varStart, val); varStart = withVars.rfind("$("); } return withVars; } std::vector<std::string> GetFilePatterns(const std::string &key) const { std::vector<std::string> exts; // Malformed patterns are skipped if we require the whole prefix here; // a fuzzy search lets us collect and report them const size_t patternStart = key.find('*'); if (patternStart == std::string::npos) return exts; const std::string patterns = key.substr(patternStart); for (const std::string &pat : StringSplit(patterns, ';')) { // Only accept patterns in the form *.xyz if (pat.starts_with("*.") && pat.length() > 2) { exts.push_back(pat.substr(1)); } else { std::cout << "\n" << "Ignoring bad file pattern '" << pat << "' in list " << patterns << "\n"; } } return exts; } bool ProcessLine(std::string_view text, bool ifIsTrue) { // If clause ends with first non-indented line if (!ifIsTrue && (text.empty() || IsSpaceOrTab(text.at(0)))) { return false; } ifIsTrue = true; if (text.starts_with(prefixIf)) { const std::string value = Expand(std::string(text.substr(prefixIf.length()))); if (value == "0" || value == "") { ifIsTrue = false; } } else if (text.starts_with(prefixMatch)) { std::optional<std::string> fileNameExt = GetProperty("FileNameExt"); if (fileNameExt) { std::string pattern(text.substr(prefixMatch.length())); // Remove trailing white space while (!pattern.empty() && IsSpaceOrTab(pattern.back())) { pattern.pop_back(); } ifIsTrue = PathMatch(pattern, *fileNameExt); } else { ifIsTrue = false; } } else { while (!text.empty() && IsSpaceOrTab(text.at(0))) { text.remove_prefix(1); } if (text.starts_with(prefixComment)) { return ifIsTrue; } const size_t positionEquals = text.find("="); if (positionEquals != std::string::npos) { const std::string key(text.substr(0, positionEquals)); const std::string_view value = text.substr(positionEquals + 1); properties[key] = value; } } return ifIsTrue; } public: using PropMap = std::map<std::string, std::string>; PropMap properties; void ReadFromFile(std::filesystem::path path) { bool ifIsTrue = true; std::ifstream ifs(path); std::string line; std::string logicalLine; while (std::getline(ifs, line)) { if (line.ends_with("\r")) { // Accidentally have \r\n line ends on Unix system line.pop_back(); } logicalLine += line; if (logicalLine.ends_with("\\")) { logicalLine.pop_back(); } else { ifIsTrue = ProcessLine(logicalLine, ifIsTrue); logicalLine.clear(); } } } std::optional<std::string> GetProperty(std::string_view key) const { const PropMap::const_iterator prop = properties.find(std::string(key)); if (prop == properties.end()) return std::nullopt; else return prop->second; } std::optional<std::string> GetPropertyForFile(std::string_view keyPrefix, std::string_view fileName) const { for (auto const &[key, val] : properties) { if (key.starts_with(keyPrefix)) { const std::string keySuffix = key.substr(keyPrefix.length()); if (fileName.ends_with(keySuffix)) { return val; } else if (key.find(';') != std::string::npos) { // It may be the case that a suite of test files with various extensions are // meant to share a common configuration, so try to find a matching // extension in a delimited list, e.g., lexer.*.html;*.php;*.asp=hypertext for (const std::string &ext : GetFilePatterns(key)) { if (fileName.ends_with(ext)) { return val; } } } } } return std::nullopt; } std::optional<int> GetPropertyValue(std::string_view key) const { std::optional<std::string> value = GetProperty(key); try { if (value) return std::stoi(value->c_str()); } catch (std::invalid_argument &) { // Just return empty } return {}; } }; size_t FirstLineDifferent(std::string_view a, std::string_view b) { size_t i = 0; while (i < std::min(a.size(), b.size()) && a.at(i) == b.at(i)) { i++; } return std::count(a.begin(), a.begin() + i, '\n'); } bool CheckSame(std::string_view augmentedText, std::string_view augmentedTextNew, std::string_view item, std::string_view suffix, const std::filesystem::path &path) { if (augmentedTextNew == augmentedText) { return true; } const size_t lineNumber = FirstLineDifferent(augmentedText, augmentedTextNew) + 1; std::cout << "\n" << path.string() << ":" << lineNumber << ":"; const std::string differenceType = augmentedText.empty() ? "new" : "different"; std::cout << " has " << differenceType << " " << item << "\n\n"; std::filesystem::path pathNew = path; pathNew += suffix; pathNew += ".new"; std::ofstream ofs(pathNew, std::ios::binary); ofs << augmentedTextNew; return false; } int Substitute(std::string &s, const std::string &sFind, const std::string &sReplace) { int c = 0; const size_t lenFind = sFind.size(); const size_t lenReplace = sReplace.size(); size_t posFound = s.find(sFind); while (posFound != std::string::npos) { s.replace(posFound, lenFind, sReplace); posFound = s.find(sFind, posFound + lenReplace); c++; } return c; } int WindowsToUnix(std::string &s) { return Substitute(s, "\r\n", "\n"); } int UnixToWindows(std::string &s) { return Substitute(s, "\n", "\r\n"); } const std::string BOM = "\xEF\xBB\xBF"; void StyleLineByLine(TestDocument &doc, Scintilla::ILexer5 *plex) { assert(plex); Scintilla::IDocument *pdoc = &doc; const Sci_Position lines = doc.LineFromPosition(doc.Length()); Sci_Position startLine = 0; for (Sci_Position line = 0; line <= lines; line++) { const Sci_Position endLine = doc.LineStart(line + 1); int styleStart = 0; if (startLine > 0) styleStart = doc.StyleAt(startLine - 1); plex->Lex(startLine, endLine - startLine, styleStart, pdoc); plex->Fold(startLine, endLine - startLine, styleStart, pdoc); startLine = endLine; } } bool TestCRLF(std::filesystem::path path, const std::string s, Scintilla::ILexer5 *plex, bool disablePerLineTests) { assert(plex); bool success = true; // Convert all line ends to \r\n to check if styles change between \r and \n which makes // it difficult to test on different platforms when files may have line ends changed. std::string text = s; WindowsToUnix(text); const bool originalIsUnix = text == s; std::string textUnix = text; UnixToWindows(text); TestDocument doc; doc.Set(text); Scintilla::IDocument *pdoc = &doc; assert(pdoc); plex->Lex(0, pdoc->Length(), 0, pdoc); plex->Fold(0, pdoc->Length(), 0, pdoc); const auto [styledText, foldedText] = MarkedAndFoldedDocument(pdoc); int prevStyle = -1; Sci_Position line = 1; for (Sci_Position pos = 0; pos < pdoc->Length(); pos++) { const int styleNow = pdoc->StyleAt(pos); char ch = '\0'; pdoc->GetCharRange(&ch, pos, 1); if (ch == '\n') { if (styleNow != prevStyle) { std::cout << path.string() << ":" << line << ":" << " different styles between \\r and \\n at " << pos << ": " << prevStyle << ", " << styleNow << "\n"; success = false; } line++; } prevStyle = styleNow; } // Lex and fold with \n line ends then check result is same TestDocument docUnix; docUnix.Set(textUnix); Scintilla::IDocument *pdocUnix = &docUnix; assert(pdocUnix); plex->Lex(0, pdocUnix->Length(), 0, pdocUnix); plex->Fold(0, pdocUnix->Length(), 0, pdocUnix); auto [styledTextUnix, foldedTextUnix] = MarkedAndFoldedDocument(pdocUnix); // Convert results from \n to \r\n run UnixToWindows(styledTextUnix); UnixToWindows(foldedTextUnix); if (styledText != styledTextUnix) { std::cout << "\n" << path.string() << ":1: has different styles with \\n versus \\r\\n line ends\n\n"; success = false; } if (foldedText != foldedTextUnix) { std::cout << "\n" << path.string() << ":1: has different folds with \\n versus \\r\\n line ends\n\n"; success = false; } // Test line by line lexing/folding with Unix \n line ends if (!disablePerLineTests && !originalIsUnix) { StyleLineByLine(docUnix, plex); auto [styledTextNewPerLine, foldedTextNewPerLine] = MarkedAndFoldedDocument(pdocUnix); // Convert results from \n to \r\n run UnixToWindows(styledTextNewPerLine); UnixToWindows(foldedTextNewPerLine); if (!CheckSame(styledTextUnix, styledTextNewPerLine, "per-line styles \\n", suffixStyled, path)) { success = false; } if (!CheckSame(foldedTextUnix, foldedTextNewPerLine, "per-line folds \\n", suffixFolded, path)) { success = false; } } plex->Release(); return success; } void TestILexer(Scintilla::ILexer5 *plex) { assert(plex); // Test each method of the ILexer interface. // Mostly ensures there are no crashes when calling methods. // Some methods are tested later (Release, Lex, Fold). // PrivateCall performs arbitrary actions so is not safe to call. [[maybe_unused]] const int version = plex->Version(); assert(version == Scintilla::lvRelease5); [[maybe_unused]] const char *language = plex->GetName(); assert(language); [[maybe_unused]] const int ident = plex->GetIdentifier(); assert(ident >= 0); [[maybe_unused]] const char *propertyNames = plex->PropertyNames(); assert(propertyNames); [[maybe_unused]] const int propertyType = plex->PropertyType("unknown"); assert(propertyType >= 0 && propertyType <= 2); [[maybe_unused]] const char *propertyDescription = plex->DescribeProperty("unknown"); assert(propertyDescription); [[maybe_unused]] const Sci_Position invalidation = plex->PropertySet("unknown", "unknown"); assert(invalidation == 0 || invalidation == -1); [[maybe_unused]] const char *wordListDescription = plex->DescribeWordListSets(); assert(wordListDescription); [[maybe_unused]] const Sci_Position invalidationWordList = plex->WordListSet(9, "unknown"); assert(invalidationWordList == 0 || invalidationWordList == -1); [[maybe_unused]] const int lineEndTypes = plex->LineEndTypesSupported(); assert(lineEndTypes == 0 || lineEndTypes == 1); if (std::string_view bases = plex->GetSubStyleBases(); !bases.empty()) { // Allocate a substyle for each possible style while (!bases.empty()) { constexpr int newStyles = 3; const int base = bases.front(); const int baseStyle = plex->AllocateSubStyles(base, newStyles); [[maybe_unused]] const int styleBack = plex->StyleFromSubStyle(baseStyle); assert(styleBack == base); plex->SetIdentifiers(baseStyle, "int nullptr"); [[maybe_unused]] const int start = plex->SubStylesStart(base); assert(start == baseStyle); [[maybe_unused]] const int len = plex->SubStylesLength(base); assert(len == newStyles); bases.remove_prefix(1); } plex->FreeSubStyles(); } [[maybe_unused]] const int primary = plex->PrimaryStyleFromStyle(2); assert(primary == 2); [[maybe_unused]] const int distance = plex->DistanceToSecondaryStyles(); assert(distance >= 0); // Just see if crashes - nullptr is valid return to indicate not present. [[maybe_unused]] const char *propertyUnknownValue = plex->PropertyGet("unknown"); const int styles = plex->NamedStyles(); for (int style = 0; style < styles; style++) { [[maybe_unused]] const char *name = plex->NameOfStyle(style); assert(name); [[maybe_unused]] const char *tags = plex->TagsOfStyle(style); assert(tags); [[maybe_unused]] const char *description = plex->DescriptionOfStyle(style); assert(description); } } bool SetProperties(Scintilla::ILexer5 *plex, const std::string &language, const PropertyMap &propertyMap, std::filesystem::path path) { assert(plex); const std::string fileName = path.filename().string(); if (std::string_view bases = plex->GetSubStyleBases(); !bases.empty()) { // Allocate a substyle for each possible style while (!bases.empty()) { const int baseStyle = bases.front(); // substyles.cpp.11=2 const std::string base = std::to_string(baseStyle); const std::string substylesForBase = "substyles." + language + "." + base; std::optional<std::string> substylesN = propertyMap.GetProperty(substylesForBase); if (substylesN) { const int substyles = atoi(substylesN->c_str()); const int baseStyleNum = plex->AllocateSubStyles(baseStyle, substyles); // substylewords.11.1.$(file.patterns.cpp)=std map string vector for (int kw = 0; kw < substyles; kw++) { const std::string substyleWords = "substylewords." + base + "." + std::to_string(kw + 1) + ".*"; const std::optional<std::string> keywordN = propertyMap.GetPropertyForFile(substyleWords, fileName); if (keywordN) { plex->SetIdentifiers(baseStyleNum + kw, keywordN->c_str()); } } } bases.remove_prefix(1); } } // Set keywords, keywords2, ... keywords9, for this file for (int kw = 0; kw < 10; kw++) { std::string kwChoice("keywords"); if (kw > 0) { kwChoice.push_back(static_cast<char>('1' + kw)); } kwChoice.append(".*"); std::optional<std::string> keywordN = propertyMap.GetPropertyForFile(kwChoice, fileName); if (keywordN) { // New lexer object has all word lists empty so check null effect from setting empty const Sci_Position changedEmpty = plex->WordListSet(kw, ""); if (changedEmpty != -1) { std::cout << path.string() << ":1: does not return -1 for null WordListSet(" << kw << ")\n"; return false; } const Sci_Position changedAt = plex->WordListSet(kw, keywordN->c_str()); if (keywordN->empty()) { if (changedAt != -1) { std::cout << path.string() << ":1: does not return -1 for WordListSet(" << kw << ") to same empty" << "\n"; return false; } } else { if (changedAt == -1) { std::cout << path.string() << ":1: returns -1 for WordListSet(" << kw << ")\n"; return false; } } } } // Set parameters of lexer for (auto const &[key, val] : propertyMap.properties) { if (key.starts_with("lexer.*")) { // Ignore as processed earlier } else if (key.starts_with("keywords")) { // Ignore as processed earlier } else if (key.starts_with("substyle")) { // Ignore as processed earlier } else { plex->PropertySet(key.c_str(), val.c_str()); } } return true; } bool TestFile(const std::filesystem::path &path, const PropertyMap &propertyMap) { // Find and create correct lexer std::optional<std::string> language = propertyMap.GetPropertyForFile(lexerPrefix, path.filename().string()); if (!language) { std::cout << "\n" << path.string() << ":1: has no language\n\n"; return false; } Scintilla::ILexer5 *plex = Lexilla::MakeLexer(*language); if (!plex) { std::cout << "\n" << path.string() << ":1: has no lexer for " << *language << "\n\n"; return false; } TestILexer(plex); if (!SetProperties(plex, *language, propertyMap, path)) { return false; } std::string text = ReadFile(path); if (text.starts_with(BOM)) { text.erase(0, BOM.length()); } std::filesystem::path pathStyled = path; pathStyled += suffixStyled; const std::string styledText = ReadFile(pathStyled); std::filesystem::path pathFolded = path; pathFolded += suffixFolded; const std::string foldedText = ReadFile(pathFolded); const int repeatLex = propertyMap.GetPropertyValue("testlexers.repeat.lex").value_or(1); const int repeatFold = propertyMap.GetPropertyValue("testlexers.repeat.fold").value_or(1); TestDocument doc; doc.Set(text); Scintilla::IDocument *pdoc = &doc; assert(pdoc); for (int i = 0; i < repeatLex; i++) { plex->Lex(0, pdoc->Length(), 0, pdoc); } for (int i = 0; i < repeatFold; i++) { plex->Fold(0, pdoc->Length(), 0, pdoc); } bool success = true; const auto [styledTextNew, foldedTextNew] = MarkedAndFoldedDocument(pdoc); if (!CheckSame(styledText, styledTextNew, "styles", suffixStyled, path)) { success = false; } if (!CheckSame(foldedText, foldedTextNew, "folds", suffixFolded, path)) { success = false; } if (propertyMap.GetPropertyValue("testlexers.list.styles").value_or(0)) { std::vector<bool> used(0x100); for (Sci_Position pos = 0; pos < pdoc->Length(); pos++) { const unsigned char uchStyle = pdoc->StyleAt(pos); const unsigned style = uchStyle; used.at(style) = true; } PrintRanges(used); } const std::optional<int> perLineDisable = propertyMap.GetPropertyValue("testlexers.per.line.disable"); const bool disablePerLineTests = perLineDisable.value_or(false); plex->Release(); // Test line by line lexing/folding if (success && !disablePerLineTests) { TestDocument docPerLine; docPerLine.Set(text); Scintilla::ILexer5 *plexPerLine = Lexilla::MakeLexer(*language); if (!SetProperties(plexPerLine, *language, propertyMap, path)) { return false; } StyleLineByLine(docPerLine, plexPerLine); const auto [styledTextNewPerLine, foldedTextNewPerLine] = MarkedAndFoldedDocument(&docPerLine); success = success && CheckSame(styledText, styledTextNewPerLine, "per-line styles", suffixStyled, path); success = success && CheckSame(foldedText, foldedTextNewPerLine, "per-line folds", suffixFolded, path); } if (success) { Scintilla::ILexer5 *plexCRLF = Lexilla::MakeLexer(*language); SetProperties(plexCRLF, *language, propertyMap, path.filename().string()); success = TestCRLF(path, text, plexCRLF, disablePerLineTests); } return success; } bool TestDirectory(std::filesystem::path directory, std::filesystem::path basePath) { bool success = true; for (auto &p : std::filesystem::directory_iterator(directory)) { if (!p.is_directory()) { const std::string extension = p.path().extension().string(); if (extension != ".properties" && extension != suffixStyled && extension != ".new" && extension != suffixFolded) { const std::filesystem::path relativePath = p.path().lexically_relative(basePath); std::cout << "Lexing " << relativePath.string() << '\n'; PropertyMap properties; properties.properties["FileNameExt"] = p.path().filename().string(); properties.ReadFromFile(directory / "SciTE.properties"); if (!TestFile(p, properties)) { success = false; } } } } return success; } bool AccessLexilla(std::filesystem::path basePath) { if (!std::filesystem::exists(basePath)) { std::cout << "No examples at " << basePath.string() << "\n"; return false; } bool success = true; for (auto &p : std::filesystem::recursive_directory_iterator(basePath)) { if (p.is_directory()) { //std::cout << p.path().string() << '\n'; if (!TestDirectory(p, basePath)) { success = false; } } } return success; } std::filesystem::path FindLexillaDirectory(std::filesystem::path startDirectory) { // Search up from startDirectory for a directory named "lexilla" or containing a "bin" subdirectory std::filesystem::path directory = startDirectory; while (!directory.empty()) { //std::cout << "Searching " << directory.string() << "\n"; const std::filesystem::path parent = directory.parent_path(); const std::filesystem::path localLexilla = directory / "lexilla"; const std::filesystem::directory_entry entry(localLexilla); if (entry.is_directory()) { std::cout << "Found Lexilla at " << entry.path().string() << "\n"; return localLexilla; } const std::filesystem::path localBin = directory / "bin"; const std::filesystem::directory_entry entryBin(localBin); if (entryBin.is_directory()) { std::cout << "Found Lexilla at " << directory.string() << "\n"; return directory; } if (parent == directory) { std::cout << "Reached root at " << directory.string() << "\n"; return std::filesystem::path(); } directory = parent; } return std::filesystem::path(); } } int main(int argc, char **argv) { bool success = false; const std::filesystem::path baseDirectory = FindLexillaDirectory(std::filesystem::current_path()); if (!baseDirectory.empty()) { #if !defined(LEXILLA_STATIC) const std::filesystem::path sharedLibrary = baseDirectory / "bin" / LEXILLA_LIB; if (!Lexilla::Load(sharedLibrary.string())) { std::cout << "Failed to load " << sharedLibrary << "\n"; return 1; // Indicate failure } #endif std::filesystem::path examplesDirectory = baseDirectory / "test" / "examples"; for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { examplesDirectory = argv[i]; } } success = AccessLexilla(examplesDirectory); } return success ? 0 : 1; }
31,107
C++
.cxx
916
30.829694
166
0.672837
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,374
TestDocument.cxx
dail8859_NotepadNext/src/lexilla/test/TestDocument.cxx
// Lexilla lexer library /** @file TestDocument.cxx ** Lexer testing. **/ // Copyright 2019 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cassert> #include <string> #include <string_view> #include <vector> #include <algorithm> #include <iostream> #include "ILexer.h" #include "TestDocument.h" namespace { const unsigned char UTF8BytesOfLead[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 00 - 0F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 10 - 1F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 20 - 2F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 30 - 3F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 40 - 4F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 50 - 5F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 60 - 6F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 70 - 7F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 80 - 8F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 90 - 9F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // A0 - AF 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // B0 - BF 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0 - CF 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // D0 - DF 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // E0 - EF 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // F0 - FF }; int UnicodeFromUTF8(const unsigned char *us) noexcept { assert(us); switch (UTF8BytesOfLead[us[0]]) { case 1: return us[0]; case 2: return ((us[0] & 0x1F) << 6) + (us[1] & 0x3F); case 3: return ((us[0] & 0xF) << 12) + ((us[1] & 0x3F) << 6) + (us[2] & 0x3F); default: return ((us[0] & 0x7) << 18) + ((us[1] & 0x3F) << 12) + ((us[2] & 0x3F) << 6) + (us[3] & 0x3F); } } inline constexpr bool UTF8IsTrailByte(unsigned char ch) noexcept { return (ch >= 0x80) && (ch < 0xc0); } constexpr unsigned char TrailByteValue(unsigned char c) { // The top 2 bits are 0b10 to indicate a trail byte. // The lower 6 bits contain the value. return c & 0b0011'1111; } } std::u32string UTF32FromUTF8(std::string_view svu8) { std::u32string ret; for (size_t i = 0; i < svu8.length();) { unsigned char ch = svu8.at(i); const unsigned int byteCount = UTF8BytesOfLead[ch]; unsigned int value = 0; if (i + byteCount > svu8.length()) { // Trying to read past end ret.push_back(ch); break; } i++; switch (byteCount) { case 1: value = ch; break; case 2: value = (ch & 0x1F) << 6; ch = svu8.at(i++); value += TrailByteValue(ch); break; case 3: value = (ch & 0xF) << 12; ch = svu8.at(i++); value += TrailByteValue(ch) << 6; ch = svu8.at(i++); value += TrailByteValue(ch); break; default: value = (ch & 0x7) << 18; ch = svu8.at(i++); value += TrailByteValue(ch) << 12; ch = svu8.at(i++); value += TrailByteValue(ch) << 6; ch = svu8.at(i++); value += TrailByteValue(ch); break; } ret.push_back(value); } return ret; } void TestDocument::Set(std::string_view sv) { text = sv; textStyles.resize(text.size() + 1); lineStarts.clear(); endStyled = 0; lineStarts.push_back(0); for (size_t pos = 0; pos < text.length(); pos++) { if (text.at(pos) == '\n') { lineStarts.push_back(pos + 1); } } if (lineStarts.back() != Length()) { lineStarts.push_back(Length()); } lineStates.resize(lineStarts.size() + 1); lineLevels.resize(lineStarts.size(), 0x400); } #if defined(_MSC_VER) // IDocument interface does not specify noexcept so best to not add it to implementation #pragma warning(disable: 26440) #endif Sci_Position TestDocument::MaxLine() const noexcept { return lineStarts.size() - 1; } int SCI_METHOD TestDocument::Version() const { return Scintilla::dvRelease4; } void SCI_METHOD TestDocument::SetErrorStatus(int) { } Sci_Position SCI_METHOD TestDocument::Length() const { return text.length(); } void SCI_METHOD TestDocument::GetCharRange(char *buffer, Sci_Position position, Sci_Position lengthRetrieve) const { text.copy(buffer, lengthRetrieve, position); } char SCI_METHOD TestDocument::StyleAt(Sci_Position position) const { if (position < 0) { return 0; } return textStyles.at(position); } Sci_Position SCI_METHOD TestDocument::LineFromPosition(Sci_Position position) const { if (position >= Length()) { return MaxLine(); } const std::vector<Sci_Position>::const_iterator it = std::lower_bound(lineStarts.begin(), lineStarts.end(), position); Sci_Position line = it - lineStarts.begin(); if (*it > position) line--; return line; } Sci_Position SCI_METHOD TestDocument::LineStart(Sci_Position line) const { if (line < 0) { return 0; } if (line >= static_cast<Sci_Position>(lineStarts.size())) { return Length(); } return lineStarts.at(line); } int SCI_METHOD TestDocument::GetLevel(Sci_Position line) const { return lineLevels.at(line); } int SCI_METHOD TestDocument::SetLevel(Sci_Position line, int level) { if (line == static_cast<Sci_Position>(lineLevels.size())) { return 0x400; } return lineLevels.at(line) = level; } int SCI_METHOD TestDocument::GetLineState(Sci_Position line) const { return lineStates.at(line); } int SCI_METHOD TestDocument::SetLineState(Sci_Position line, int state) { return lineStates.at(line) = state; } void SCI_METHOD TestDocument::StartStyling(Sci_Position position) { endStyled = position; } bool SCI_METHOD TestDocument::SetStyleFor(Sci_Position length, char style) { for (Sci_Position i = 0; i < length; i++) { textStyles.at(endStyled) = style; endStyled++; } return true; } bool SCI_METHOD TestDocument::SetStyles(Sci_Position length, const char *styles) { assert(styles); for (Sci_Position i = 0; i < length; i++) { textStyles.at(endStyled) = styles[i]; endStyled++; } return true; } void SCI_METHOD TestDocument::DecorationSetCurrentIndicator(int) { // Not implemented as no way to read decorations } void SCI_METHOD TestDocument::DecorationFillRange(Sci_Position, int, Sci_Position) { // Not implemented as no way to read decorations } void SCI_METHOD TestDocument::ChangeLexerState(Sci_Position, Sci_Position) { // Not implemented as no watcher to trigger } int SCI_METHOD TestDocument::CodePage() const { // Always UTF-8 for now return 65001; } bool SCI_METHOD TestDocument::IsDBCSLeadByte(char) const { // Always UTF-8 for now return false; } const char *SCI_METHOD TestDocument::BufferPointer() { return text.c_str(); } int SCI_METHOD TestDocument::GetLineIndentation(Sci_Position) { // Never actually called - lexers use Accessor::IndentAmount return 0; } Sci_Position SCI_METHOD TestDocument::LineEnd(Sci_Position line) const { const Sci_Position maxLine = MaxLine(); if (line == maxLine || line == maxLine+1) { return text.length(); } assert(line < maxLine); Sci_Position position = LineStart(line + 1); position--; // Back over CR or LF // When line terminator is CR+LF, may need to go back one more if ((position > LineStart(line)) && (text.at(position - 1) == '\r')) { position--; } return position; } Sci_Position SCI_METHOD TestDocument::GetRelativePosition(Sci_Position positionStart, Sci_Position characterOffset) const { Sci_Position pos = positionStart; if (characterOffset < 0) { while (characterOffset < 0) { if (pos <= 0) { return -1; } unsigned char previousByte = text.at(pos - 1); if (previousByte < 0x80) { pos--; characterOffset++; } else { while ((pos > 1) && UTF8IsTrailByte(previousByte)) { pos--; previousByte = text.at(pos - 1); } pos--; // text[pos] is now a character start characterOffset++; } } return pos; } assert(characterOffset >= 0); // TODO: invalid UTF-8 while (characterOffset > 0) { Sci_Position width = 0; GetCharacterAndWidth(pos, &width); pos += width; characterOffset--; } return pos; } int SCI_METHOD TestDocument::GetCharacterAndWidth(Sci_Position position, Sci_Position *pWidth) const { // TODO: invalid UTF-8 if ((position < 0) || (position >= Length())) { // Return NULs before document start and after document end if (pWidth) { *pWidth = 1; } return '\0'; } const unsigned char leadByte = text.at(position); if (leadByte < 0x80) { if (pWidth) { *pWidth = 1; } return leadByte; } const int widthCharBytes = UTF8BytesOfLead[leadByte]; unsigned char charBytes[] = { leadByte,0,0,0 }; for (int b = 1; b < widthCharBytes; b++) { charBytes[b] = text.at(position + b); } if (pWidth) { *pWidth = widthCharBytes; } return UnicodeFromUTF8(charBytes); }
8,616
C++
.cxx
287
27.56446
123
0.657295
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,375
testOptionSet.cxx
dail8859_NotepadNext/src/lexilla/test/unit/testOptionSet.cxx
/** @file testOptionSet.cxx ** Unit Tests for Lexilla internal data structures ** Tests OptionSet. **/ #include <string> #include <string_view> #include <vector> #include <map> #include "Scintilla.h" #include "OptionSet.h" #include "catch.hpp" using namespace Lexilla; // Test OptionSet. namespace { // Simple example options structure with each type: string, bool, int struct Options { std::string so; bool bo = false; int io = 0; }; const char *const denseWordLists[] = { "Keywords 1", "Keywords 2", "Keywords 3", "Keywords 4", nullptr, }; const char *const sparseWordLists[] = { "", "", "Keywords 1", "", "Keywords 2", nullptr, }; } using Catch::Matchers::Equals; TEST_CASE("OptionSet") { OptionSet<Options> os; Options options; SECTION("IsEmptyInitially") { REQUIRE_THAT(os.PropertyNames(), Equals("")); } SECTION("MissingOption") { // Check for not present option REQUIRE_FALSE(os.PropertyGet("missing")); REQUIRE(SC_TYPE_BOOLEAN == os.PropertyType("missing")); REQUIRE_FALSE(os.PropertySet(&options, "missing", "1")); } SECTION("Define") { os.DefineProperty("string.option", &Options::so, "StringOption"); REQUIRE_THAT(os.PropertyGet("string.option"), Equals("")); REQUIRE(SC_TYPE_STRING == os.PropertyType("string.option")); REQUIRE_THAT(os.DescribeProperty("string.option"), Equals("StringOption")); os.DefineProperty("bool.option", &Options::bo, "BoolOption"); REQUIRE_THAT(os.PropertyGet("bool.option"), Equals("")); REQUIRE(SC_TYPE_BOOLEAN == os.PropertyType("bool.option")); REQUIRE_THAT(os.DescribeProperty("bool.option"), Equals("BoolOption")); os.DefineProperty("int.option", &Options::io, "IntOption"); REQUIRE_THAT(os.PropertyGet("int.option"), Equals("")); REQUIRE(SC_TYPE_INTEGER == os.PropertyType("int.option")); REQUIRE_THAT(os.DescribeProperty("int.option"), Equals("IntOption")); // This is really a set and could be reordered but is currently in definition order REQUIRE_THAT(os.PropertyNames(), Equals("string.option\nbool.option\nint.option")); } SECTION("Set") { os.DefineProperty("string.option", &Options::so, "StringOption"); REQUIRE_THAT(os.PropertyGet("string.option"), Equals("")); REQUIRE(os.PropertySet(&options, "string.option", "string")); REQUIRE_THAT(os.PropertyGet("string.option"), Equals("string")); // Setting to same as before returns false REQUIRE_FALSE(os.PropertySet(&options, "string.option", "string")); REQUIRE(os.PropertySet(&options, "string.option", "anotherString")); REQUIRE_THAT(os.PropertyGet("string.option"), Equals("anotherString")); os.DefineProperty("bool.option", &Options::so, "BoolOption"); REQUIRE(os.PropertySet(&options, "bool.option", "1")); REQUIRE_THAT(os.PropertyGet("bool.option"), Equals("1")); // Setting to same as before returns false REQUIRE_FALSE(os.PropertySet(&options, "bool.option", "1")); REQUIRE(os.PropertySet(&options, "bool.option", "0")); os.DefineProperty("int.option", &Options::so, "IntOption"); REQUIRE(os.PropertySet(&options, "int.option", "2")); REQUIRE_THAT(os.PropertyGet("int.option"), Equals("2")); // Setting to same as before returns false REQUIRE_FALSE(os.PropertySet(&options, "int.option", "2")); REQUIRE(os.PropertySet(&options, "int.option", "3")); } // WordListSets feature is really completely separate from options SECTION("WordListSets") { REQUIRE_THAT(os.DescribeWordListSets(), Equals("")); os.DefineWordListSets(denseWordLists); REQUIRE_THAT(os.DescribeWordListSets(), Equals("Keywords 1\nKeywords 2\nKeywords 3\nKeywords 4")); OptionSet<Options> os2; REQUIRE_THAT(os2.DescribeWordListSets(), Equals("")); os2.DefineWordListSets(sparseWordLists); REQUIRE_THAT(os2.DescribeWordListSets(), Equals("\n\nKeywords 1\n\nKeywords 2")); } }
3,802
C++
.cxx
100
35.48
85
0.724429
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,376
testWordList.cxx
dail8859_NotepadNext/src/lexilla/test/unit/testWordList.cxx
/** @file testWordList.cxx ** Unit Tests for Lexilla internal data structures ** Tests WordList, WordClassifier, and SubStyles **/ #include <cassert> #include <string> #include <string_view> #include <vector> #include <map> #include "WordList.h" #include "CharacterSet.h" #include "SubStyles.h" #include "catch.hpp" using namespace Lexilla; // Test WordList. TEST_CASE("WordList") { WordList wl; SECTION("IsEmptyInitially") { REQUIRE(0 == wl.Length()); REQUIRE(!wl.InList("struct")); } SECTION("InList") { wl.Set("else struct"); REQUIRE(2 == wl.Length()); REQUIRE(wl.InList("struct")); REQUIRE(!wl.InList("class")); } SECTION("StringInList") { wl.Set("else struct"); std::string sStruct = "struct"; REQUIRE(wl.InList(sStruct)); std::string sClass = "class"; REQUIRE(!wl.InList(sClass)); } SECTION("InListUnicode") { // "cheese" in English // "kase" ('k', 'a with diaeresis', 's', 'e') in German // "syr", ('CYRILLIC SMALL LETTER ES', 'CYRILLIC SMALL LETTER YERU', 'CYRILLIC SMALL LETTER ER') in Russian wl.Set("cheese \x6b\xc3\xa4\x73\x65 \xd1\x81\xd1\x8b\xd1\x80"); REQUIRE(3 == wl.Length()); REQUIRE(wl.InList("cheese")); REQUIRE(wl.InList("\x6b\xc3\xa4\x73\x65")); REQUIRE(wl.InList("\xd1\x81\xd1\x8b\xd1\x80")); } SECTION("Set") { // Check whether Set returns whether it has changed correctly const bool changed = wl.Set("else struct"); REQUIRE(changed); // Changing to same thing const bool changed2 = wl.Set("else struct"); REQUIRE(!changed2); // Changed order shouldn't be seen as a change const bool changed3 = wl.Set("struct else"); REQUIRE(!changed3); // Removing word is a change const bool changed4 = wl.Set("struct"); REQUIRE(changed4); } SECTION("WordAt") { wl.Set("else struct"); REQUIRE_THAT(wl.WordAt(0), Catch::Matchers::Equals("else")); } SECTION("InListAbbreviated") { wl.Set("else stru~ct w~hile \xd1\x81~\xd1\x8b\xd1\x80"); REQUIRE(wl.InListAbbreviated("else", '~')); REQUIRE(wl.InListAbbreviated("struct", '~')); REQUIRE(wl.InListAbbreviated("stru", '~')); REQUIRE(wl.InListAbbreviated("struc", '~')); REQUIRE(!wl.InListAbbreviated("str", '~')); REQUIRE(wl.InListAbbreviated("while", '~')); REQUIRE(wl.InListAbbreviated("wh", '~')); // TODO: Next line fails but should allow single character prefixes //REQUIRE(wl.InListAbbreviated("w", '~')); REQUIRE(!wl.InListAbbreviated("", '~')); // Russian syr REQUIRE(wl.InListAbbreviated("\xd1\x81\xd1\x8b\xd1\x80", '~')); } SECTION("InListAbridged") { wl.Set("list w.~.active bo~k a~z ~_frozen \xd1\x81~\xd1\x80"); REQUIRE(wl.InListAbridged("list", '~')); REQUIRE(wl.InListAbridged("w.front.active", '~')); REQUIRE(wl.InListAbridged("w.x.active", '~')); REQUIRE(wl.InListAbridged("w..active", '~')); REQUIRE(!wl.InListAbridged("w.active", '~')); REQUIRE(!wl.InListAbridged("w.x.closed", '~')); REQUIRE(wl.InListAbridged("book", '~')); REQUIRE(wl.InListAbridged("bok", '~')); REQUIRE(!wl.InListAbridged("bk", '~')); REQUIRE(wl.InListAbridged("a_frozen", '~')); REQUIRE(wl.InListAbridged("_frozen", '~')); REQUIRE(!wl.InListAbridged("frozen", '~')); REQUIRE(wl.InListAbridged("abcz", '~')); REQUIRE(wl.InListAbridged("abz", '~')); REQUIRE(wl.InListAbridged("az", '~')); // Russian syr REQUIRE(wl.InListAbridged("\xd1\x81\xd1\x8b\xd1\x80", '~')); } } // Test WordClassifier. TEST_CASE("WordClassifier") { constexpr int base = 1; constexpr int key = 10; constexpr int type = 11; constexpr int other = 40; WordClassifier wc(1); SECTION("Base") { REQUIRE(wc.Base() == base); wc.Allocate(key, 2); REQUIRE(wc.Start() == key); REQUIRE(wc.Last() == type); REQUIRE(wc.Length() == 2); REQUIRE(wc.IncludesStyle(key)); REQUIRE(wc.IncludesStyle(type)); REQUIRE(!wc.IncludesStyle(other)); wc.Clear(); REQUIRE(wc.Base() == base); REQUIRE(wc.Start() == 0); REQUIRE(wc.Last() == -1); REQUIRE(wc.Length() == 0); } SECTION("ValueFor") { wc.Allocate(key, 2); wc.SetIdentifiers(key, "else if then", false); wc.SetIdentifiers(type, "double float int long", false); REQUIRE(wc.ValueFor("if") == key); REQUIRE(wc.ValueFor("double") == type); REQUIRE(wc.ValueFor("fish") < 0); wc.RemoveStyle(type); REQUIRE(wc.ValueFor("double") < 0); } } // Test SubStyles. TEST_CASE("SubStyles") { constexpr char bases[] = "\002\005"; constexpr int base = 2; constexpr int base2 = 5; constexpr int styleFirst = 0x80; constexpr int stylesAvailable = 0x40; constexpr int distanceToSecondary = 0x40; SubStyles subStyles(bases, styleFirst, stylesAvailable, distanceToSecondary); SECTION("All") { REQUIRE(subStyles.DistanceToSecondaryStyles() == distanceToSecondary); // Before allocation REQUIRE(subStyles.Start(base) == 0); const int startSubStyles = subStyles.Allocate(base, 3); REQUIRE(startSubStyles == styleFirst); REQUIRE(subStyles.Start(base) == styleFirst); REQUIRE(subStyles.Length(base) == 3); REQUIRE(subStyles.BaseStyle(128) == 2); // Not a substyle so returns argument. REQUIRE(subStyles.BaseStyle(96) == 96); REQUIRE(subStyles.FirstAllocated() == styleFirst); REQUIRE(subStyles.LastAllocated() == styleFirst + 3 - 1); subStyles.SetIdentifiers(styleFirst, "int long size_t"); const WordClassifier &wc = subStyles.Classifier(base); REQUIRE(wc.ValueFor("int") == styleFirst); REQUIRE(wc.ValueFor("double") < 0); // Add second set of substyles which shouldn't affect first const int startSecondSet = subStyles.Allocate(base2, 2); constexpr int expectedStylesSecond = styleFirst + 3; REQUIRE(startSecondSet == expectedStylesSecond); REQUIRE(subStyles.Start(base) == styleFirst); REQUIRE(subStyles.Start(base2) == expectedStylesSecond); REQUIRE(subStyles.LastAllocated() == styleFirst + 5 - 1); // Clear and check that earlier call no longer works subStyles.Free(); REQUIRE(subStyles.Start(base) == 0); } }
5,937
C++
.cxx
169
32.337278
109
0.694148
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,377
testPropSetSimple.cxx
dail8859_NotepadNext/src/lexilla/test/unit/testPropSetSimple.cxx
/** @file testPropSetSimple.cxx ** Unit Tests for Lexilla internal data structures **/ #include <string> #include <string_view> #include "PropSetSimple.h" #include "catch.hpp" using namespace Lexilla; // Test PropSetSimple. namespace { constexpr const char *propertyName = "lexer.tex.comment.process"; constexpr const char *propertyValue = "1"; } TEST_CASE("PropSetSimple") { SECTION("IsEmptyInitially") { PropSetSimple pss; const char *value = pss.Get(propertyName); REQUIRE_THAT(value, Catch::Matchers::Equals("")); } SECTION("SetAndGet") { PropSetSimple pss; pss.Set(propertyName, propertyValue); const char *value = pss.Get(propertyName); REQUIRE_THAT(value, Catch::Matchers::Equals(propertyValue)); } SECTION("GetInt") { PropSetSimple pss; const int valueStart = pss.GetInt(propertyName); REQUIRE(0 == valueStart); const int valueDefault = pss.GetInt(propertyName, 3); REQUIRE(3 == valueDefault); pss.Set(propertyName, propertyValue); const int value = pss.GetInt(propertyName); REQUIRE(1 == value); } }
1,060
C++
.cxx
36
27.027778
65
0.749753
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,378
testCharacterSet.cxx
dail8859_NotepadNext/src/lexilla/test/unit/testCharacterSet.cxx
/** @file testCharacterSet.cxx ** Unit Tests for Lexilla internal data structures **/ #include <cstdlib> #include <cassert> #include <string_view> #include "CharacterSet.h" #include "catch.hpp" using namespace Lexilla; // Test CharacterSet. TEST_CASE("CharacterSet") { SECTION("IsEmptyInitially") { CharacterSet cs; for (int i=0; i<0x80; i++) { REQUIRE(!cs.Contains(i)); } } SECTION("InitialSet") { CharacterSet cs(CharacterSet::setDigits); for (int i=0; i<0x80; i++) { if (i >= '0' && i <= '9') REQUIRE(cs.Contains(i)); else REQUIRE(!cs.Contains(i)); } } SECTION("Set") { CharacterSet cs; cs.Add('a'); for (int i=0; i<0x80; i++) { if (i == 'a') REQUIRE(cs.Contains(i)); else REQUIRE(!cs.Contains(i)); } } SECTION("After") { CharacterSet cs; REQUIRE(!cs.Contains(0x100)); CharacterSet cs2(CharacterSet::setNone, "", 0x80, true); REQUIRE(cs2.Contains(0x100)); } } TEST_CASE("Functions") { SECTION("IsASpace") { REQUIRE(IsASpace(' ')); REQUIRE(!IsASpace('a')); REQUIRE(IsASpaceOrTab(' ')); REQUIRE(!IsASpaceOrTab('a')); } SECTION("IsADigit") { REQUIRE(!IsADigit(' ')); REQUIRE(!IsADigit('a')); REQUIRE(IsADigit('7')); REQUIRE(IsADigit('7', 16)); REQUIRE(IsADigit('A', 16)); REQUIRE(IsADigit('a', 16)); REQUIRE(!IsADigit('8', 8)); } SECTION("IsASCII") { REQUIRE(IsASCII(' ')); REQUIRE(IsASCII('a')); REQUIRE(!IsASCII(-1)); REQUIRE(!IsASCII(128)); } SECTION("IsUpperOrLowerCase") { REQUIRE(IsLowerCase('a')); REQUIRE(!IsLowerCase('A')); REQUIRE(!IsUpperCase('a')); REQUIRE(IsUpperCase('A')); REQUIRE(IsUpperOrLowerCase('a')); REQUIRE(IsUpperOrLowerCase('A')); REQUIRE(!IsUpperOrLowerCase('9')); REQUIRE(IsAlphaNumeric('9')); REQUIRE(IsAlphaNumeric('a')); REQUIRE(IsAlphaNumeric('A')); REQUIRE(!IsAlphaNumeric(' ')); REQUIRE(!IsAlphaNumeric('+')); } SECTION("isoperator") { REQUIRE(isspacechar(' ')); REQUIRE(!isspacechar('a')); REQUIRE(!iswordchar(' ')); REQUIRE(iswordchar('a')); REQUIRE(iswordchar('A')); REQUIRE(iswordchar('.')); REQUIRE(iswordchar('_')); REQUIRE(!iswordstart(' ')); REQUIRE(iswordstart('a')); REQUIRE(iswordstart('A')); REQUIRE(iswordstart('_')); REQUIRE(!isoperator('a')); REQUIRE(isoperator('+')); } SECTION("MakeUpperCase") { REQUIRE(MakeUpperCase(' ') == ' '); REQUIRE(MakeUpperCase('A') == 'A'); REQUIRE(MakeUpperCase('a') == 'A'); REQUIRE(MakeLowerCase(' ') == ' '); REQUIRE(MakeLowerCase('A') == 'a'); REQUIRE(MakeLowerCase('a') == 'a'); } SECTION("CompareCaseInsensitive") { REQUIRE(CompareCaseInsensitive(" ", " ") == 0); REQUIRE(CompareCaseInsensitive("A", "A") == 0); REQUIRE(CompareCaseInsensitive("a", "A") == 0); REQUIRE(CompareCaseInsensitive("b", "A") != 0); REQUIRE(CompareCaseInsensitive("aa", "A") != 0); REQUIRE(CompareNCaseInsensitive(" ", " ", 1) == 0); REQUIRE(CompareNCaseInsensitive("b", "A", 1) != 0); REQUIRE(CompareNCaseInsensitive("aa", "A", 1) == 0); } SECTION("EqualCaseInsensitive") { REQUIRE(EqualCaseInsensitive(" ", " ")); REQUIRE(EqualCaseInsensitive("A", "A")); REQUIRE(EqualCaseInsensitive("a", "A")); REQUIRE(!EqualCaseInsensitive("b", "A")); REQUIRE(!EqualCaseInsensitive("aa", "A")); REQUIRE(!EqualCaseInsensitive("a", "AA")); } }
3,324
C++
.cxx
121
24.528926
58
0.652379
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,381
testLexerSimple.cxx
dail8859_NotepadNext/src/lexilla/test/unit/testLexerSimple.cxx
/** @file testLexerSimple.cxx ** Unit Tests for Lexilla internal data structures **/ #include <cassert> #include <string> #include <string_view> #include "ILexer.h" #include "Scintilla.h" #include "PropSetSimple.h" #include "LexerModule.h" #include "LexerBase.h" #include "LexerSimple.h" #include "catch.hpp" using namespace Lexilla; // Test LexerSimple. namespace { constexpr const char *propertyName = "lexer.tex.comment.process"; constexpr const char *propertyValue = "1"; void ColouriseDocument(Sci_PositionU, Sci_Position, int, WordList *[], Accessor &) { // Do no styling } LexerModule lmSimpleExample(123456, ColouriseDocument, "simpleexample"); } TEST_CASE("LexerSimple") { SECTION("Identifier") { LexerSimple lexSimple(&lmSimpleExample); REQUIRE(lexSimple.GetIdentifier() == 123456); } SECTION("Identifier") { LexerSimple lexSimple(&lmSimpleExample); REQUIRE_THAT(lexSimple.GetName(), Catch::Matchers::Equals("simpleexample")); } SECTION("SetAndGet") { LexerSimple lexSimple(&lmSimpleExample); // New setting -> 0 const Sci_Position pos0 = lexSimple.PropertySet(propertyName, "8"); REQUIRE(pos0 == 0); // Changed setting -> 0 const Sci_Position pos1 = lexSimple.PropertySet(propertyName, propertyValue); REQUIRE(pos1 == 0); // Same setting -> -1 const Sci_Position pos2 = lexSimple.PropertySet(propertyName, propertyValue); REQUIRE(pos2 == -1); const char *value = lexSimple.PropertyGet(propertyName); REQUIRE_THAT(propertyValue, Catch::Matchers::Equals(value)); } }
1,536
C++
.cxx
47
30.404255
84
0.757143
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,382
testInList.cxx
dail8859_NotepadNext/src/lexilla/test/unit/testInList.cxx
/** @file testInList.cxx ** Unit Tests for Lexilla internal data structures **/ #include <cstdlib> #include <cassert> #include <string_view> #include <initializer_list> #include "InList.h" #include "catch.hpp" using namespace Lexilla; // Test InList. TEST_CASE("InList") { SECTION("Basic") { REQUIRE(InList("dog", {"cat", "dog", "frog"})); REQUIRE(!InList("fly", {"cat", "dog", "frog"})); REQUIRE(InListCaseInsensitive("DOG", {"cat", "dog", "frog"})); REQUIRE(!InListCaseInsensitive("fly", {"cat", "dog", "frog"})); } }
541
C++
.cxx
19
26.368421
65
0.672515
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,384
94Template.cxx
dail8859_NotepadNext/src/lexilla/test/examples/cpp/94Template.cxx
// Test JavaScript template expressions for issue 94 // Basic var basic = `${identifier}`; // Nested var nested = ` ${ ` ${ 1 } ` } `; // With escapes var xxx = { '1': `\`\u0020\${a${1 + 1}b}`, '2': `\${a${ `b${1 + 2}c`.charCodeAt(2) }d}`, '3': `\${a${ `b${ `c${ JSON.stringify({ '4': {}, }) }d` }e` }f}`, }; // Original request fetchOptions.body = ` { "accountNumber" : "248796", "customerType" : "Shipper", "destinationCity" : "${order.destination.city}", "destinationState" : "${order.destination.stateProvince}", "destinationZip" : ${order.destination.postalCode}, "paymentType" : "Prepaid", "shipmentInfo" : { "items" : [ { "shipmentClass" : "50", "shipmentWeight" : "${order.totalWeight.toString()}" } ] } }`;
759
C++
.cxx
27
25.518519
96
0.583791
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,385
Bug2245.cxx
dail8859_NotepadNext/src/lexilla/test/examples/cpp/Bug2245.cxx
int i; #if 1 i=1; # i=2; #else i=3; #endif i=4; #elif 1 i=5; #else i=6;
72
C++
.cxx
13
4.538462
7
0.627119
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,386
149KeywordCase.cxx
dail8859_NotepadNext/src/lexilla/test/examples/cpp/149KeywordCase.cxx
// SCE_C_WORD2 (16) second // SCE_C_IDENTIFIER (11) Second // SCE_C_IDENTIFIER (11) upper // SCE_C_WORD2 (16) Upper
119
C++
.cxx
8
13.5
24
0.703704
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,387
130NonAsciiKeyword.cxx
dail8859_NotepadNext/src/lexilla/test/examples/cpp/130NonAsciiKeyword.cxx
// coding: utf-8 // All three following symbols should highlight as keywords cheese käse сыр // Lookalikes with ASCII so should not highlight: сыp cыp
159
C++
.cxx
8
17.875
59
0.818182
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,388
x.cxx
dail8859_NotepadNext/src/lexilla/test/examples/cpp/x.cxx
#!/usr/bin/env node // A demonstration program #include <stdio.h> #if 0 /* */ #define DUMMY() \ if (1); #endif // Test preprocessor expressions with parentheses #if ((0)) a #elif ((1)) b #endif /** @file LexCPP.cxx <file> <file >filename</file> LexCPP.cxx. </file> **/ /** Unknown doc keywords so in SCE_C_COMMENTDOCKEYWORDERROR: @wrong LexCPP.cxx <wrong>filename</wrong> Next line should not start a keyword but before 5.4.1 did and caused bad styling or a crash depending on range lexed < **/ #define M\ \ // Test preprocessor active branches feature #if HAVE_COLOUR // Active #endif #if NOT_HAVE_COLOUR // Inactive #endif #if FEATURE==2 // Active #endif #if FEATURE==3 // Inactive #endif #if VERSION(1,2)==3 // Active #endif #if VERSION(1,2)==4 // Inactive #endif #undef HAVE_COLOUR #if HAVE_COLOUR // Inactive #endif #define MULTIPLY(a,b) a*b #if MULTIPLY(2,3)==6 // Active #endif int main() { double x[] = {3.14159,6.02e23,1.6e-19,1.0+1}; int y[] = {75,0113,0x4b}; printf("hello world %d %g\n", y[0], x[0]); // JavaScript regular expression (14) tests let a = /a/; let b = /[a-z]+/gi; /a|b/i.test("baby"); // arrow function () => /a|b/i.test("baby"); // Escape sequence (27) tests printf("\'\"\?\\\a\b\f\n\r\t\v \P"); printf("\0a \013a \019"); printf("\x013ac \xdz"); printf("\ua34df \uz"); printf("\Ua34df7833 \Uz"); }
1,368
C++
.cxx
71
17.661972
117
0.675
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,389
AllStyles.cxx
dail8859_NotepadNext/src/lexilla/test/examples/cpp/AllStyles.cxx
// Enumerate all primary styles: 0 to 27 and secondary styles 64 to 91 // default=0 // comment=1 /* */ /* commentline=2 */ // example line // commentdoc=3 /** */ // number=4 123 // word=5 int // string=6 "string" // character=7 'c' // uuid=8 uuid(3fd43029-1354-42f0-a5be-4a484c9c5250) // preprocessor=9 #define xxx 1 // operator=10 {} // identifier=11 identifier // stringeol=12 " // verbatim=13 @"verbatim" // regex=14 (/regex/) // commentlinedoc=15 /// example // word2=16 second // commentdockeyword=17 /** @file */ // commentdockeyworderror=18 /** @wrongkey */ // globalclass=19 global // stringraw=20 R"( )" // tripleverbatim=21 """ xx """ // hashquotedstring=22 #" xx " // preprocessorcomment=23 #define /* comment */ // preprocessorcommentdoc=24 #define /** comment */ // userliteral=25 1_date_ // taskmarker=26 /* TODO: sleep */ // escapesequence=27 "\001 \b" // identifier substyles.11.1=128 vector // identifier substyles.11.2=129 std // commentdockeyword substyles.17.1=130 /** @module */ // Secondary styles inside preprocessor excluded section #if 0 // default=0 // comment=1 /* */ /* commentline=2 */ // example line // commentdoc=3 /** */ // number=4 123 // word=5 int // string=6 "string" // character=7 'c' // uuid=8 uuid(3fd43029-1354-42f0-a5be-4a484c9c5250) // preprocessor=9 #define xxx 1 // operator=10 {} // identifier=11 identifier // stringeol=12 " // verbatim=13 @"verbatim" // regex=14 (/regex/) // commentlinedoc=15 /// example // word2=16 second // commentdockeyword=17 /** @file */ // commentdockeyworderror=18 /** @wrongkey */ // globalclass=19 global // stringraw=20 R"( )" // tripleverbatim=21 """ xx """ // hashquotedstring=22 #" xx " // preprocessorcomment=23 #define /* comment */ // preprocessorcommentdoc=24 #define /** comment */ // userliteral=25 1_date_ // taskmarker=26 /* TODO: sleep */ // escapesequence=27 "\001 \b" // identifier substyles.75.1=192 vector // identifier substyles.75.2=193 std // commentdockeyword substyles.81.1=194 /** @module */ #endif
2,072
C++
.cxx
126
14.865079
70
0.716498
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,390
SimpleLexer.cxx
dail8859_NotepadNext/src/lexilla/examples/SimpleLexer/SimpleLexer.cxx
// A simple lexer /** @file SimpleLexer.cxx ** A lexer that follows the Lexilla protocol to allow it to be used from Lexilla clients like SciTE. ** The lexer applies alternating styles (0,1) to bytes of the text. **/ // Copyright 2021 by Neil Hodgson <neilh@scintilla.org> // This file is in the public domain. // If the public domain is not possible in your location then it can also be used under the same // license as Scintilla. https://www.scintilla.org/License.txt // Windows/MSVC // cl -std:c++17 -EHsc -LD -I ../../../scintilla/include -I ../../include -I ../../lexlib SimpleLexer.cxx ../../lexlib/*.cxx // macOS/clang // clang++ -dynamiclib --std=c++17 -I ../../../scintilla/include -I ../../include -I ../../lexlib SimpleLexer.cxx ../../lexlib/*.cxx -o SimpleLexer.dylib // Linux/g++ // g++ -fPIC -shared --std=c++17 -I ../../../scintilla/include -I ../../include -I ../../lexlib SimpleLexer.cxx ../../lexlib/*.cxx -o SimpleLexer.so /* It can be demonstrated in SciTE like this, substituting the actual shared library location as lexilla.path: lexilla.path=.;C:\u\hg\lexilla\examples\SimpleLexer\SimpleLexer.dll lexer.*.xx=simple style.simple.1=fore:#FF0000 */ #include <stdlib.h> #include <string.h> #include <assert.h> #include <string> #include <string_view> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" // Lexilla.h should not be included here as it declares statically linked functions without the __declspec( dllexport ) #include "WordList.h" #include "PropSetSimple.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" #include "LexerBase.h" using namespace Scintilla; using namespace Lexilla; class LexerSimple : public LexerBase { public: LexerSimple() { } void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override { try { Accessor astyler(pAccess, &props); if (length > 0) { astyler.StartAt(startPos); astyler.StartSegment(startPos); for (unsigned int k=0; k<length; k++) { astyler.ColourTo(startPos+k, (startPos+k)%2); } } astyler.Flush(); } catch (...) { // Should not throw into caller as may be compiled with different compiler or options pAccess->SetErrorStatus(SC_STATUS_FAILURE); } } void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override { } static ILexer5 *LexerFactorySimple() { try { return new LexerSimple(); } catch (...) { // Should not throw into caller as may be compiled with different compiler or options return nullptr; } } }; #if defined(_WIN32) #define EXPORT_FUNCTION __declspec(dllexport) #define CALLING_CONVENTION __stdcall #else #define EXPORT_FUNCTION __attribute__((visibility("default"))) #define CALLING_CONVENTION #endif static const char *lexerName = "simple"; extern "C" { EXPORT_FUNCTION int CALLING_CONVENTION GetLexerCount() { return 1; } EXPORT_FUNCTION void CALLING_CONVENTION GetLexerName(unsigned int index, char *name, int buflength) { *name = 0; if ((index == 0) && (buflength > static_cast<int>(strlen(lexerName)))) { strcpy(name, lexerName); } } EXPORT_FUNCTION LexerFactoryFunction CALLING_CONVENTION GetLexerFactory(unsigned int index) { if (index == 0) return LexerSimple::LexerFactorySimple; else return 0; } EXPORT_FUNCTION Scintilla::ILexer5* CALLING_CONVENTION CreateLexer(const char *name) { if (0 == strcmp(name, lexerName)) { return LexerSimple::LexerFactorySimple(); } return nullptr; } EXPORT_FUNCTION const char * CALLING_CONVENTION GetNameSpace() { return "example"; } }
4,009
C++
.cxx
104
33.134615
153
0.667181
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
16,392
LexAccessor.cxx
dail8859_NotepadNext/src/lexilla/lexlib/LexAccessor.cxx
// Scintilla source code edit control /** @file LexAccessor.cxx ** Interfaces between Scintilla and lexers. **/ // Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cassert> #include <cstring> #include <string> #include <algorithm> #include "ILexer.h" #include "LexAccessor.h" #include "CharacterSet.h" using namespace Lexilla; namespace Lexilla { bool LexAccessor::MatchIgnoreCase(Sci_Position pos, const char *s) { assert(s); for (; *s; s++, pos++) { if (*s != MakeLowerCase(SafeGetCharAt(pos))) { return false; } } return true; } void LexAccessor::GetRange(Sci_PositionU startPos_, Sci_PositionU endPos_, char *s, Sci_PositionU len) const { assert(s); assert(startPos_ <= endPos_ && len != 0); memset(s, '\0', len); endPos_ = std::min(endPos_, startPos_ + len - 1); endPos_ = std::min(endPos_, static_cast<Sci_PositionU>(lenDoc)); len = endPos_ - startPos_; if (startPos_ >= static_cast<Sci_PositionU>(startPos) && endPos_ <= static_cast<Sci_PositionU>(endPos)) { const char * const p = buf + (startPos_ - startPos); memcpy(s, p, len); } else { pAccess->GetCharRange(s, startPos_, len); } } void LexAccessor::GetRangeLowered(Sci_PositionU startPos_, Sci_PositionU endPos_, char *s, Sci_PositionU len) const { assert(s); GetRange(startPos_, endPos_, s, len); while (*s) { if (*s >= 'A' && *s <= 'Z') { *s += 'a' - 'A'; } ++s; } } std::string LexAccessor::GetRange(Sci_PositionU startPos_, Sci_PositionU endPos_) const { assert(startPos_ < endPos_); endPos_ = std::min(endPos_, static_cast<Sci_PositionU>(lenDoc)); const Sci_PositionU len = endPos_ - startPos_; std::string s(len, '\0'); GetRange(startPos_, endPos_, s.data(), len + 1); return s; } std::string LexAccessor::GetRangeLowered(Sci_PositionU startPos_, Sci_PositionU endPos_) const { assert(startPos_ < endPos_); endPos_ = std::min(endPos_, static_cast<Sci_PositionU>(lenDoc)); const Sci_PositionU len = endPos_ - startPos_; std::string s(len, '\0'); GetRangeLowered(startPos_, endPos_, s.data(), len + 1); return s; } }
2,161
C++
.cxx
65
31.261538
117
0.696882
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
16,399
InList.cxx
dail8859_NotepadNext/src/lexilla/lexlib/InList.cxx
// Scintilla source code edit control /** @file InList.cxx ** Check if a string is in a list. **/ // Copyright 2024 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cassert> #include <string> #include <string_view> #include <initializer_list> #include "InList.h" #include "CharacterSet.h" namespace Lexilla { bool InList(std::string_view value, std::initializer_list<std::string_view> list) noexcept { for (const std::string_view element : list) { if (value == element) { return true; } } return false; } bool InListCaseInsensitive(std::string_view value, std::initializer_list<std::string_view> list) noexcept { for (const std::string_view element : list) { if (EqualCaseInsensitive(value, element)) { return true; } } return false; } }
861
C++
.cxx
30
26.733333
107
0.743932
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,419
LexAsciidoc.cxx
dail8859_NotepadNext/src/lexilla/lexers/LexAsciidoc.cxx
/****************************************************************** * LexAsciidoc.cxx * * A simple Asciidoc lexer for scintilla. * * Based on the LexMarkdown.cxx by Jon Strait - jstrait@moonloop.net * * The License.txt file describes the conditions under which this * software may be distributed. * *****************************************************************/ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <string> #include <string_view> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" using namespace Lexilla; namespace { typedef struct { bool start; int len1; int len2; const char *name; } MacroItem; static const MacroItem MacroList[] = { // Directives {true, 5, 2, "ifdef::"}, {true, 6, 2, "ifeval::"}, {true, 6, 2, "ifndef::"}, {true, 5, 2, "endif::"}, // Macros {true, 5, 2, "audio::"}, {true, 7, 2, "include::"}, {true, 5, 2, "image::"}, {true, 5, 2, "video::"}, {false, 8, 1, "asciimath:"}, {false, 3, 1, "btn:"}, {false, 5, 1, "image:"}, {false, 3, 1, "kbd:"}, {false, 9, 1, "latexmath:"}, {false, 4, 1, "link:"}, {false, 6, 1, "mailto:"}, {false, 4, 1, "menu:"}, {false, 4, 1, "pass:"}, {false, 4, 1, "stem:"}, {false, 4, 1, "xref:"}, // Admonitions {true, 7, 1, "CAUTION:"}, {true, 9, 1, "IMPORTANT:"}, {true, 4, 1, "NOTE:"}, {true, 3, 1, "TIP:"}, {true, 7, 1, "WARNING:"}, {false, 0, 0, NULL} }; constexpr bool IsNewline(const int ch) { // sc.GetRelative(i) returns '\0' if out of range return (ch == '\n' || ch == '\r' || ch == '\0'); } } static bool AtTermStart(StyleContext &sc) { return sc.currentPos == 0 || sc.chPrev == 0 || isspacechar(sc.chPrev); } static void ColorizeAsciidocDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList **, Accessor &styler) { bool freezeCursor = false; StyleContext sc(startPos, static_cast<Sci_PositionU>(length), initStyle, styler); while (sc.More()) { // Skip past escaped characters if (sc.ch == '\\') { sc.Forward(); continue; } // Skip newline. if (IsNewline(sc.ch)) { // Newline doesn't end blocks if (sc.state != SCE_ASCIIDOC_CODEBK && \ sc.state != SCE_ASCIIDOC_PASSBK && \ sc.state != SCE_ASCIIDOC_COMMENTBK && \ sc.state != SCE_ASCIIDOC_LITERALBK) { sc.SetState(SCE_ASCIIDOC_DEFAULT); } sc.Forward(); continue; } // Conditional state-based actions switch (sc.state) { // Strong case SCE_ASCIIDOC_STRONG1: if (sc.ch == '*' && sc.chPrev != ' ') { sc.Forward(); sc.SetState(SCE_ASCIIDOC_DEFAULT); freezeCursor = true; } break; case SCE_ASCIIDOC_STRONG2: if (sc.Match("**") && sc.chPrev != ' ') { sc.Forward(2); sc.SetState(SCE_ASCIIDOC_DEFAULT); freezeCursor = true; } break; // Emphasis case SCE_ASCIIDOC_EM1: if (sc.ch == '_' && sc.chPrev != ' ') { sc.Forward(); sc.SetState(SCE_ASCIIDOC_DEFAULT); freezeCursor = true; } break; case SCE_ASCIIDOC_EM2: if (sc.Match("__") && sc.chPrev != ' ') { sc.Forward(2); sc.SetState(SCE_ASCIIDOC_DEFAULT); freezeCursor = true; } break; // Link case SCE_ASCIIDOC_LINK: if (sc.ch == ']' && sc.chPrev != '\\') { sc.SetState(SCE_ASCIIDOC_DEFAULT); } break; // Code block case SCE_ASCIIDOC_CODEBK: if (sc.atLineStart && sc.Match("----") && IsNewline(sc.GetRelative(4))) { sc.Forward(4); sc.SetState(SCE_ASCIIDOC_DEFAULT); } break; // Passthrough block case SCE_ASCIIDOC_PASSBK: if (sc.atLineStart && sc.Match("++++") && IsNewline(sc.GetRelative(4))) { sc.Forward(4); sc.SetState(SCE_ASCIIDOC_DEFAULT); } break; // Comment block case SCE_ASCIIDOC_COMMENTBK: if (sc.atLineStart && sc.Match("////") && IsNewline(sc.GetRelative(4))) { sc.Forward(4); sc.SetState(SCE_ASCIIDOC_DEFAULT); } break; // Literal case SCE_ASCIIDOC_LITERAL: if (sc.ch == '+' && sc.chPrev != '\\') { sc.SetState(SCE_ASCIIDOC_DEFAULT); } break; // Literal block case SCE_ASCIIDOC_LITERALBK: if (sc.atLineStart && sc.Match("....") && IsNewline(sc.GetRelative(4))) { sc.Forward(4); sc.SetState(SCE_ASCIIDOC_DEFAULT); } break; // Attribute case SCE_ASCIIDOC_ATTRIB: if (sc.ch == ':' && sc.chPrev != ' ' && sc.chNext == ' ') { sc.Forward(); sc.SetState(SCE_ASCIIDOC_ATTRIBVAL); } break; // Macro case SCE_ASCIIDOC_MACRO: if (sc.ch == ']' && sc.chPrev != '\\') { sc.SetState(SCE_ASCIIDOC_DEFAULT); } break; // Default case SCE_ASCIIDOC_DEFAULT: // Headers if (sc.atLineStart && sc.Match("====== ")) { sc.SetState(SCE_ASCIIDOC_HEADER6); sc.Forward(6); } else if (sc.atLineStart && sc.Match("===== ")) { sc.SetState(SCE_ASCIIDOC_HEADER5); sc.Forward(5); } else if (sc.atLineStart && sc.Match("==== ")) { sc.SetState(SCE_ASCIIDOC_HEADER4); sc.Forward(4); } else if (sc.atLineStart && sc.Match("=== ")) { sc.SetState(SCE_ASCIIDOC_HEADER3); sc.Forward(3); } else if (sc.atLineStart && sc.Match("== ")) { sc.SetState(SCE_ASCIIDOC_HEADER2); sc.Forward(2); } else if (sc.atLineStart && sc.Match("= ")) { sc.SetState(SCE_ASCIIDOC_HEADER1); sc.Forward(1); } // Unordered list item else if (sc.atLineStart && sc.Match("****** ")) { sc.SetState(SCE_ASCIIDOC_ULIST_ITEM); sc.Forward(6); sc.SetState(SCE_ASCIIDOC_DEFAULT); } else if (sc.atLineStart && sc.Match("***** ")) { sc.SetState(SCE_ASCIIDOC_ULIST_ITEM); sc.Forward(5); sc.SetState(SCE_ASCIIDOC_DEFAULT); } else if (sc.atLineStart && sc.Match("**** ")) { sc.SetState(SCE_ASCIIDOC_ULIST_ITEM); sc.Forward(4); sc.SetState(SCE_ASCIIDOC_DEFAULT); } else if (sc.atLineStart && sc.Match("*** ")) { sc.SetState(SCE_ASCIIDOC_ULIST_ITEM); sc.Forward(3); sc.SetState(SCE_ASCIIDOC_DEFAULT); } else if (sc.atLineStart && sc.Match("** ")) { sc.SetState(SCE_ASCIIDOC_ULIST_ITEM); sc.Forward(2); sc.SetState(SCE_ASCIIDOC_DEFAULT); } else if (sc.atLineStart && sc.Match("* ")) { sc.SetState(SCE_ASCIIDOC_ULIST_ITEM); sc.Forward(1); sc.SetState(SCE_ASCIIDOC_DEFAULT); } // Ordered list item else if (sc.atLineStart && sc.Match("...... ")) { sc.SetState(SCE_ASCIIDOC_OLIST_ITEM); sc.Forward(6); sc.SetState(SCE_ASCIIDOC_DEFAULT); } else if (sc.atLineStart && sc.Match("..... ")) { sc.SetState(SCE_ASCIIDOC_OLIST_ITEM); sc.Forward(5); sc.SetState(SCE_ASCIIDOC_DEFAULT); } else if (sc.atLineStart && sc.Match(".... ")) { sc.SetState(SCE_ASCIIDOC_OLIST_ITEM); sc.Forward(4); sc.SetState(SCE_ASCIIDOC_DEFAULT); } else if (sc.atLineStart && sc.Match("... ")) { sc.SetState(SCE_ASCIIDOC_OLIST_ITEM); sc.Forward(3); sc.SetState(SCE_ASCIIDOC_DEFAULT); } else if (sc.atLineStart && sc.Match(".. ")) { sc.SetState(SCE_ASCIIDOC_OLIST_ITEM); sc.Forward(2); sc.SetState(SCE_ASCIIDOC_DEFAULT); } else if (sc.atLineStart && sc.Match(". ")) { sc.SetState(SCE_ASCIIDOC_OLIST_ITEM); sc.Forward(1); sc.SetState(SCE_ASCIIDOC_DEFAULT); } // Blockquote else if (sc.atLineStart && sc.Match("> ")) { sc.SetState(SCE_ASCIIDOC_BLOCKQUOTE); sc.Forward(); } // Link else if (!sc.atLineStart && sc.ch == '[' && sc.chPrev != '\\' && sc.chNext != ' ') { sc.Forward(); sc.SetState(SCE_ASCIIDOC_LINK); freezeCursor = true; } // Code block else if (sc.atLineStart && sc.Match("----") && IsNewline(sc.GetRelative(4))) { sc.SetState(SCE_ASCIIDOC_CODEBK); sc.Forward(4); } // Passthrough block else if (sc.atLineStart && sc.Match("++++") && IsNewline(sc.GetRelative(4))) { sc.SetState(SCE_ASCIIDOC_PASSBK); sc.Forward(4); } // Comment block else if (sc.atLineStart && sc.Match("////") && IsNewline(sc.GetRelative(4))) { sc.SetState(SCE_ASCIIDOC_COMMENTBK); sc.Forward(4); } // Comment else if (sc.atLineStart && sc.Match("//")) { sc.SetState(SCE_ASCIIDOC_COMMENT); sc.Forward(); } // Literal else if (sc.ch == '+' && sc.chPrev != '\\' && sc.chNext != ' ' && AtTermStart(sc)) { sc.Forward(); sc.SetState(SCE_ASCIIDOC_LITERAL); freezeCursor = true; } // Literal block else if (sc.atLineStart && sc.Match("....") && IsNewline(sc.GetRelative(4))) { sc.SetState(SCE_ASCIIDOC_LITERALBK); sc.Forward(4); } // Attribute else if (sc.atLineStart && sc.ch == ':' && sc.chNext != ' ') { sc.SetState(SCE_ASCIIDOC_ATTRIB); } // Strong else if (sc.Match("**") && sc.GetRelative(2) != ' ') { sc.SetState(SCE_ASCIIDOC_STRONG2); sc.Forward(); } else if (sc.ch == '*' && sc.chNext != ' ' && AtTermStart(sc)) { sc.SetState(SCE_ASCIIDOC_STRONG1); } // Emphasis else if (sc.Match("__") && sc.GetRelative(2) != ' ') { sc.SetState(SCE_ASCIIDOC_EM2); sc.Forward(); } else if (sc.ch == '_' && sc.chNext != ' ' && AtTermStart(sc)) { sc.SetState(SCE_ASCIIDOC_EM1); } // Macro else if (sc.atLineStart && sc.ch == '[' && sc.chNext != ' ') { sc.Forward(); sc.SetState(SCE_ASCIIDOC_MACRO); freezeCursor = true; } else { int i = 0; bool found = false; while (!found && MacroList[i].name != NULL) { if (MacroList[i].start) found = sc.atLineStart && sc.Match(MacroList[i].name); else found = sc.Match(MacroList[i].name); if (found) { sc.SetState(SCE_ASCIIDOC_MACRO); sc.Forward(MacroList[i].len1); sc.SetState(SCE_ASCIIDOC_DEFAULT); if (MacroList[i].len2 > 1) sc.Forward(MacroList[i].len2 - 1); } i++; } } break; } // Advance if not holding back the cursor for this iteration. if (!freezeCursor) sc.Forward(); freezeCursor = false; } sc.Complete(); } extern const LexerModule lmAsciidoc(SCLEX_ASCIIDOC, ColorizeAsciidocDoc, "asciidoc");
13,158
C++
.cxx
365
23.964384
96
0.459773
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,435
LexZig.cxx
dail8859_NotepadNext/src/lexilla/lexers/LexZig.cxx
// Scintilla source code edit control /** @file LexZig.cxx ** Lexer for Zig language. **/ // Based on Zufu Liu's Notepad4 Zig lexer // Modified for Scintilla by Jiri Techet, 2024 // The License.txt file describes the conditions under which this software may be distributed. #include <cassert> #include <cstring> #include <string> #include <string_view> #include <vector> #include <map> #include <algorithm> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" #include "OptionSet.h" #include "DefaultLexer.h" using namespace Scintilla; using namespace Lexilla; namespace { // Use an unnamed namespace to protect the functions and classes from name conflicts constexpr bool IsAGraphic(int ch) noexcept { // excludes C0 control characters and whitespace return ch > 32 && ch < 127; } constexpr bool IsIdentifierStart(int ch) noexcept { return IsUpperOrLowerCase(ch) || ch == '_'; } constexpr bool IsIdentifierStartEx(int ch) noexcept { return IsIdentifierStart(ch) || ch >= 0x80; } constexpr bool IsNumberStart(int ch, int chNext) noexcept { return IsADigit(ch) || (ch == '.' && IsADigit(chNext)); } constexpr bool IsIdentifierChar(int ch) noexcept { return IsAlphaNumeric(ch) || ch == '_'; } constexpr bool IsNumberContinue(int chPrev, int ch, int chNext) noexcept { return ((ch == '+' || ch == '-') && (chPrev == 'e' || chPrev == 'E')) || (ch == '.' && chNext != '.'); } constexpr bool IsDecimalNumber(int chPrev, int ch, int chNext) noexcept { return IsIdentifierChar(ch) || IsNumberContinue(chPrev, ch, chNext); } constexpr bool IsIdentifierCharEx(int ch) noexcept { return IsIdentifierChar(ch) || ch >= 0x80; } // https://ziglang.org/documentation/master/#Escape-Sequences struct EscapeSequence { int outerState = SCE_ZIG_DEFAULT; int digitsLeft = 0; bool brace = false; // highlight any character as escape sequence. void resetEscapeState(int state, int chNext) noexcept { outerState = state; digitsLeft = 1; brace = false; if (chNext == 'x') { digitsLeft = 3; } else if (chNext == 'u') { digitsLeft = 5; } } void resetEscapeState(int state) noexcept { outerState = state; digitsLeft = 1; brace = false; } bool atEscapeEnd(int ch) noexcept { --digitsLeft; return digitsLeft <= 0 || !IsAHeXDigit(ch); } }; enum { ZigLineStateMaskLineComment = 1, // line comment ZigLineStateMaskMultilineString = 1 << 1, // multiline string }; struct FoldLineState { int lineComment; int multilineString; constexpr explicit FoldLineState(int lineState) noexcept: lineComment(lineState & ZigLineStateMaskLineComment), multilineString((lineState >> 1) & 1) { } }; enum class KeywordType { None = SCE_ZIG_DEFAULT, Function = SCE_ZIG_FUNCTION, }; enum { KeywordIndex_Primary = 0, KeywordIndex_Secondary = 1, KeywordIndex_Tertiary = 2, KeywordIndex_Type = 3, }; // Options used for LexerZig struct OptionsZig { bool fold = false; }; const char *const zigWordListDesc[] = { "Primary keywords", "Secondary keywords", "Tertiary keywords", "Global type definitions", nullptr }; struct OptionSetZig : public OptionSet<OptionsZig> { OptionSetZig() { DefineProperty("fold", &OptionsZig::fold); DefineWordListSets(zigWordListDesc); } }; LexicalClass lexicalClasses[] = { // Lexer ZIG SCLEX_ZIG SCE_ZIG_: 0, "SCE_ZIG_DEFAULT", "default", "White space", 1, "SCE_ZIG_COMMENTLINE", "comment line", "Comment: //", 2, "SCE_ZIG_COMMENTLINEDOC", "comment line documentation", "Comment: ///", 3, "SCE_ZIG_COMMENTLINETOP", "comment line documentation", "Comment: //!", 4, "SCE_ZIG_NUMBER", "literal numeric", "Number", 5, "SCE_ZIG_OPERATOR", "operator", "Operator", 6, "SCE_ZIG_CHARACTER", "literal string character", "Single quoted string", 7, "SCE_ZIG_STRING", "literal string", "Double quoted string", 8, "SCE_ZIG_MULTISTRING", "literal string multiline", "Multiline string introduced by two backslashes", 9, "SCE_ZIG_ESCAPECHAR", "literal string escapesequence", "Escape sequence", 10, "SCE_ZIG_IDENTIFIER", "identifier", "Identifier", 11, "SCE_ZIG_FUNCTION", "identifier", "Function definition", 12, "SCE_ZIG_BUILTIN_FUNCTION", "identifier", "Builtin function", 13, "SCE_ZIG_KW_PRIMARY", "keyword", "Primary keywords", 14, "SCE_ZIG_KW_SECONDARY", "identifier", "Secondary keywords", 15, "SCE_ZIG_KW_TERTIARY", "identifier", "Tertiary keywords", 16, "SCE_ZIG_KW_TYPE", "identifier", "Global types", }; class LexerZig : public DefaultLexer { WordList keywordsPrimary; WordList keywordsSecondary; WordList keywordsTertiary; WordList keywordsTypes; OptionsZig options; OptionSetZig osZig; public: LexerZig(const char *languageName_, int language_) : DefaultLexer(languageName_, language_, lexicalClasses, std::size(lexicalClasses)) { } // Deleted so LexerZig objects can not be copied. LexerZig(const LexerZig &) = delete; LexerZig(LexerZig &&) = delete; void operator=(const LexerZig &) = delete; void operator=(LexerZig &&) = delete; ~LexerZig() override = default; void SCI_METHOD Release() override { delete this; } int SCI_METHOD Version() const override { return lvRelease5; } const char *SCI_METHOD PropertyNames() override { return osZig.PropertyNames(); } int SCI_METHOD PropertyType(const char *name) override { return osZig.PropertyType(name); } const char *SCI_METHOD DescribeProperty(const char *name) override { return osZig.DescribeProperty(name); } Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override; const char *SCI_METHOD PropertyGet(const char *key) override { return osZig.PropertyGet(key); } const char *SCI_METHOD DescribeWordListSets() override { return osZig.DescribeWordListSets(); } Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override; void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void *SCI_METHOD PrivateCall(int, void *) override { return nullptr; } void BacktrackToStart(const LexAccessor &styler, int stateMask, Sci_PositionU &startPos, Sci_Position &lengthDoc, int &initStyle); Sci_PositionU LookbackNonWhite(LexAccessor &styler, Sci_PositionU startPos, int &chPrevNonWhite, int &stylePrevNonWhite); static ILexer5 *LexerFactoryZig() { return new LexerZig("zig", SCLEX_ZIG); } }; Sci_Position SCI_METHOD LexerZig::PropertySet(const char *key, const char *val) { if (osZig.PropertySet(&options, key, val)) { return 0; } return -1; } Sci_Position SCI_METHOD LexerZig::WordListSet(int n, const char *wl) { WordList *wordListN = nullptr; switch (n) { case 0: wordListN = &keywordsPrimary; break; case 1: wordListN = &keywordsSecondary; break; case 2: wordListN = &keywordsTertiary; break; case 3: wordListN = &keywordsTypes; break; default: break; } Sci_Position firstModification = -1; if (wordListN && wordListN->Set(wl, false)) { firstModification = 0; } return firstModification; } void LexerZig::Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument *pAccess) { Accessor styler(pAccess, nullptr); KeywordType kwType = KeywordType::None; int visibleChars = 0; int lineState = 0; EscapeSequence escSeq; StyleContext sc(startPos, lengthDoc, initStyle, styler); while (sc.More()) { switch (sc.state) { case SCE_ZIG_OPERATOR: sc.SetState(SCE_ZIG_DEFAULT); break; case SCE_ZIG_NUMBER: if (!IsDecimalNumber(sc.chPrev, sc.ch, sc.chNext)) { sc.SetState(SCE_ZIG_DEFAULT); } break; case SCE_ZIG_IDENTIFIER: case SCE_ZIG_BUILTIN_FUNCTION: if (!IsIdentifierCharEx(sc.ch)) { if (sc.state == SCE_ZIG_IDENTIFIER) { char s[64]; sc.GetCurrent(s, sizeof(s)); if (kwType != KeywordType::None) { sc.ChangeState(static_cast<int>(kwType)); } else if (keywordsPrimary.InList(s)) { sc.ChangeState(SCE_ZIG_KW_PRIMARY); kwType = KeywordType::None; if (strcmp(s, "fn") == 0) { kwType = KeywordType::Function; } } else if (keywordsSecondary.InList(s)) { sc.ChangeState(SCE_ZIG_KW_SECONDARY); } else if (keywordsTertiary.InList(s)) { sc.ChangeState(SCE_ZIG_KW_TERTIARY); } else if (keywordsTypes.InList(s)) { sc.ChangeState(SCE_ZIG_KW_TYPE); } } if (sc.state != SCE_ZIG_KW_PRIMARY) { kwType = KeywordType::None; } sc.SetState(SCE_ZIG_DEFAULT); } break; case SCE_ZIG_CHARACTER: case SCE_ZIG_STRING: case SCE_ZIG_MULTISTRING: if (sc.atLineStart) { sc.SetState(SCE_ZIG_DEFAULT); } else if (sc.ch == '\\' && sc.state != SCE_ZIG_MULTISTRING) { escSeq.resetEscapeState(sc.state, sc.chNext); sc.SetState(SCE_ZIG_ESCAPECHAR); sc.Forward(); if (sc.Match('u', '{')) { escSeq.brace = true; escSeq.digitsLeft = 9; sc.Forward(); } } else if ((sc.ch == '\'' && sc.state == SCE_ZIG_CHARACTER) || (sc.ch == '\"' && sc.state == SCE_ZIG_STRING)) { sc.ForwardSetState(SCE_ZIG_DEFAULT); } else if (sc.state != SCE_ZIG_CHARACTER) { if (sc.ch == '{' || sc.ch == '}') { if (sc.ch == sc.chNext) { escSeq.resetEscapeState(sc.state); sc.SetState(SCE_ZIG_ESCAPECHAR); sc.Forward(); } } } break; case SCE_ZIG_ESCAPECHAR: if (escSeq.atEscapeEnd(sc.ch)) { if (escSeq.brace && sc.ch == '}') { sc.Forward(); } sc.SetState(escSeq.outerState); continue; } break; case SCE_ZIG_COMMENTLINE: case SCE_ZIG_COMMENTLINEDOC: case SCE_ZIG_COMMENTLINETOP: if (sc.atLineStart) { sc.SetState(SCE_ZIG_DEFAULT); } break; } if (sc.state == SCE_ZIG_DEFAULT) { if (sc.Match('/', '/')) { if (visibleChars == 0) { lineState = ZigLineStateMaskLineComment; } sc.SetState(SCE_ZIG_COMMENTLINE); sc.Forward(2); if (sc.ch == '!') { sc.ChangeState(SCE_ZIG_COMMENTLINETOP); } else if (sc.ch == '/' && sc.chNext != '/') { sc.ChangeState(SCE_ZIG_COMMENTLINEDOC); } } else if (sc.Match('\\', '\\')) { lineState = ZigLineStateMaskMultilineString; sc.SetState(SCE_ZIG_MULTISTRING); } else if (sc.ch == '\"') { sc.SetState(SCE_ZIG_STRING); } else if (sc.ch == '\'') { sc.SetState(SCE_ZIG_CHARACTER); } else if (IsNumberStart(sc.ch, sc.chNext)) { sc.SetState(SCE_ZIG_NUMBER); } else if ((sc.ch == '@' && IsIdentifierStartEx(sc.chNext)) || IsIdentifierStartEx(sc.ch)) { sc.SetState((sc.ch == '@') ? SCE_ZIG_BUILTIN_FUNCTION : SCE_ZIG_IDENTIFIER); } else if (IsAGraphic(sc.ch)) { sc.SetState(SCE_ZIG_OPERATOR); } } if (visibleChars == 0 && !isspacechar(sc.ch)) { visibleChars++; } if (sc.atLineEnd) { styler.SetLineState(sc.currentLine, lineState); lineState = 0; kwType = KeywordType::None; visibleChars = 0; } sc.Forward(); } sc.Complete(); } void LexerZig::Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument *pAccess) { if (!options.fold) return; Accessor styler(pAccess, nullptr); const Sci_PositionU endPos = startPos + lengthDoc; Sci_Position lineCurrent = styler.GetLine(startPos); while (lineCurrent > 0) { lineCurrent--; startPos = styler.LineStart(lineCurrent); initStyle = (startPos > 0) ? styler.StyleIndexAt(startPos) : 0; if (!AnyOf(initStyle, SCE_ZIG_MULTISTRING, SCE_ZIG_COMMENTLINE, SCE_ZIG_COMMENTLINEDOC, SCE_ZIG_COMMENTLINETOP)) { break; } } FoldLineState foldPrev(0); int levelCurrent = SC_FOLDLEVELBASE; if (lineCurrent > 0) { levelCurrent = styler.LevelAt(lineCurrent - 1) >> 16; foldPrev = FoldLineState(styler.GetLineState(lineCurrent - 1)); } int levelNext = levelCurrent; FoldLineState foldCurrent(styler.GetLineState(lineCurrent)); Sci_PositionU lineStartNext = styler.LineStart(lineCurrent + 1); lineStartNext = std::min(lineStartNext, endPos); while (startPos < endPos) { initStyle = styler.StyleIndexAt(startPos); if (initStyle == SCE_ZIG_OPERATOR) { const char ch = styler[startPos]; if (ch == '{' || ch == '[' || ch == '(') { levelNext++; } else if (ch == '}' || ch == ']' || ch == ')') { levelNext--; } } ++startPos; if (startPos == lineStartNext) { const FoldLineState foldNext(styler.GetLineState(lineCurrent + 1)); levelNext = std::max(levelNext, SC_FOLDLEVELBASE); if (foldCurrent.lineComment) { levelNext += foldNext.lineComment - foldPrev.lineComment; } else if (foldCurrent.multilineString) { levelNext += foldNext.multilineString - foldPrev.multilineString; } const int levelUse = levelCurrent; int lev = levelUse | (levelNext << 16); if (levelUse < levelNext) { lev |= SC_FOLDLEVELHEADERFLAG; } styler.SetLevel(lineCurrent, lev); lineCurrent++; lineStartNext = styler.LineStart(lineCurrent + 1); lineStartNext = std::min(lineStartNext, endPos); levelCurrent = levelNext; foldPrev = foldCurrent; foldCurrent = foldNext; } } } } // unnamed namespace end extern const LexerModule lmZig(SCLEX_ZIG, LexerZig::LexerFactoryZig, "zig", zigWordListDesc);
13,267
C++
.cxx
410
29.280488
131
0.703718
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,442
LexLua.cxx
dail8859_NotepadNext/src/lexilla/lexers/LexLua.cxx
// Scintilla source code edit control /** @file LexLua.cxx ** Lexer for Lua language. ** ** Written by Paul Winwood. ** Folder by Alexey Yutkin. ** Modified by Marcos E. Wurzius & Philippe Lhoste **/ #include <cstdlib> #include <cassert> #include <cstring> #include <string> #include <string_view> #include <vector> #include <map> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" #include "OptionSet.h" #include "SubStyles.h" #include "DefaultLexer.h" using namespace Scintilla; using namespace Lexilla; namespace { // Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ], // return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on. // The maximum number of '=' characters allowed is 254. int LongDelimCheck(StyleContext &sc) { constexpr int maximumEqualCharacters = 254; int sep = 1; while (sc.GetRelative(sep) == '=' && sep <= maximumEqualCharacters) sep++; if (sc.GetRelative(sep) == sc.ch) return sep; return 0; } const char *const luaWordListDesc[] = { "Keywords", "Basic functions", "String, (table) & math functions", "(coroutines), I/O & system facilities", "user1", "user2", "user3", "user4", nullptr }; const char styleSubable[] = { SCE_LUA_IDENTIFIER, 0 }; const LexicalClass lexicalClasses[] = { // Lexer Lua SCLEX_LUA SCE_LUA_: 0, "SCE_LUA_DEFAULT", "default", "White space: Visible only in View Whitespace mode (or if it has a back colour)", 1, "SCE_LUA_COMMENT", "comment", "Block comment (Lua 5.0)", 2, "SCE_LUA_COMMENTLINE", "comment line", "Line comment", 3, "SCE_LUA_COMMENTDOC", "comment documentation", "Doc comment", 4, "SCE_LUA_NUMBER", "literal numeric", "Number", 5, "SCE_LUA_WORD", "keyword", "Keyword", 6, "SCE_LUA_STRING", "literal string", "(Double quoted) String", 7, "SCE_LUA_CHARACTER", "literal string character", "Character (Single quoted string)", 8, "SCE_LUA_LITERALSTRING", "literal string", "Literal string", 9, "SCE_LUA_PREPROCESSOR", "preprocessor", "Preprocessor (obsolete in Lua 4.0 and up)", 10, "SCE_LUA_OPERATOR", "operator", "Operators", 11, "SCE_LUA_IDENTIFIER", "identifier", "Identifier (everything else...)", 12, "SCE_LUA_STRINGEOL", "error literal string", "End of line where string is not closed", 13, "SCE_LUA_WORD2", "identifier", "Other keywords", 14, "SCE_LUA_WORD3", "identifier", "Other keywords", 15, "SCE_LUA_WORD4", "identifier", "Other keywords", 16, "SCE_LUA_WORD5", "identifier", "Other keywords", 17, "SCE_LUA_WORD6", "identifier", "Other keywords", 18, "SCE_LUA_WORD7", "identifier", "Other keywords", 19, "SCE_LUA_WORD8", "identifier", "Other keywords", 20, "SCE_LUA_LABEL", "label", "Labels", }; // Options used for LexerLua struct OptionsLua { bool foldCompact = true; }; struct OptionSetLua : public OptionSet<OptionsLua> { OptionSetLua() { DefineProperty("fold.compact", &OptionsLua::foldCompact); DefineWordListSets(luaWordListDesc); } }; class LexerLua : public DefaultLexer { WordList keywords; WordList keywords2; WordList keywords3; WordList keywords4; WordList keywords5; WordList keywords6; WordList keywords7; WordList keywords8; OptionsLua options; OptionSetLua osLua; SubStyles subStyles{styleSubable}; public: explicit LexerLua() : DefaultLexer("lua", SCLEX_LUA, lexicalClasses, std::size(lexicalClasses)) { } LexerLua(const LexerLua &) = delete; LexerLua(LexerLua &&) = delete; LexerLua &operator=(const LexerLua &) = delete; LexerLua &operator=(LexerLua &&) = delete; ~LexerLua() override = default; void SCI_METHOD Release() noexcept override { delete this; } [[nodiscard]] int SCI_METHOD Version() const noexcept override { return lvRelease5; } const char *SCI_METHOD PropertyNames() noexcept override { return osLua.PropertyNames(); } int SCI_METHOD PropertyType(const char *name) override { return osLua.PropertyType(name); } const char *SCI_METHOD DescribeProperty(const char *name) override { return osLua.DescribeProperty(name); } Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override; const char *SCI_METHOD PropertyGet(const char *key) override { return osLua.PropertyGet(key); } const char *SCI_METHOD DescribeWordListSets() noexcept override { return osLua.DescribeWordListSets(); } Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override; void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; int SCI_METHOD AllocateSubStyles(int styleBase, int numberStyles) override { return subStyles.Allocate(styleBase, numberStyles); } int SCI_METHOD SubStylesStart(int styleBase) override { return subStyles.Start(styleBase); } int SCI_METHOD SubStylesLength(int styleBase) override { return subStyles.Length(styleBase); } int SCI_METHOD StyleFromSubStyle(int subStyle) override { const int styleBase = subStyles.BaseStyle(subStyle); return styleBase; } int SCI_METHOD PrimaryStyleFromStyle(int style) override { return style; } void SCI_METHOD FreeSubStyles() override { subStyles.Free(); } void SCI_METHOD SetIdentifiers(int style, const char *identifiers) override { subStyles.SetIdentifiers(style, identifiers); } int SCI_METHOD DistanceToSecondaryStyles() override { return 0; } const char *SCI_METHOD GetSubStyleBases() override { return styleSubable; } static ILexer5 *LexerFactoryLua() { return new LexerLua(); } }; Sci_Position SCI_METHOD LexerLua::PropertySet(const char *key, const char *val) { if (osLua.PropertySet(&options, key, val)) { return 0; } return -1; } Sci_Position SCI_METHOD LexerLua::WordListSet(int n, const char *wl) { WordList *wordListN = nullptr; switch (n) { case 0: wordListN = &keywords; break; case 1: wordListN = &keywords2; break; case 2: wordListN = &keywords3; break; case 3: wordListN = &keywords4; break; case 4: wordListN = &keywords5; break; case 5: wordListN = &keywords6; break; case 6: wordListN = &keywords7; break; case 7: wordListN = &keywords8; break; default: break; } Sci_Position firstModification = -1; if (wordListN) { if (wordListN->Set(wl)) { firstModification = 0; } } return firstModification; } constexpr int maskSeparator = 0xFF; constexpr int maskStringWs = 0x100; constexpr int maskDocComment = 0x200; void LexerLua::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) { LexAccessor styler(pAccess); // Accepts accented characters const CharacterSet setWordStart(CharacterSet::setAlpha, "_", true); const CharacterSet setWord(CharacterSet::setAlphaNum, "_", true); // Not exactly following number definition (several dots are seen as OK, etc.) // but probably enough in most cases. [pP] is for hex floats. const CharacterSet setNumber(CharacterSet::setDigits, ".-+abcdefpABCDEFP"); const CharacterSet setExponent("eEpP"); const CharacterSet setLuaOperator("*/-+()={}~[];<>,.^%:#&|"); const CharacterSet setEscapeSkip("\"'\\"); const WordClassifier &classifierIdentifiers = subStyles.Classifier(SCE_LUA_IDENTIFIER); Sci_Position currentLine = styler.GetLine(startPos); // Initialize long string [[ ... ]] or block comment --[[ ... ]], // if we are inside such a string. Block comment was introduced in Lua 5.0, // blocks with separators [=[ ... ]=] in Lua 5.1. // Continuation of a string (\z whitespace escaping) is controlled by stringWs. int sepCount = 0; int stringWs = 0; int lastLineDocComment = 0; if ((currentLine > 0) && AnyOf(initStyle, SCE_LUA_DEFAULT, SCE_LUA_LITERALSTRING, SCE_LUA_COMMENT, SCE_LUA_COMMENTDOC, SCE_LUA_STRING, SCE_LUA_CHARACTER)) { const int lineState = styler.GetLineState(currentLine - 1); sepCount = lineState & maskSeparator; stringWs = lineState & maskStringWs; lastLineDocComment = lineState & maskDocComment; } // results of identifier/keyword matching Sci_Position idenPos = 0; Sci_Position idenStartCharWidth = 0; Sci_Position idenWordPos = 0; int idenStyle = SCE_LUA_IDENTIFIER; bool foundGoto = false; // Do not leak onto next line if (AnyOf(initStyle, SCE_LUA_STRINGEOL, SCE_LUA_COMMENTLINE, SCE_LUA_COMMENTDOC, SCE_LUA_PREPROCESSOR)) { initStyle = SCE_LUA_DEFAULT; } StyleContext sc(startPos, length, initStyle, styler); if (startPos == 0 && sc.ch == '#' && sc.chNext == '!') { // shbang line: "#!" is a comment only if located at the start of the script sc.SetState(SCE_LUA_COMMENTLINE); } for (; sc.More(); sc.Forward()) { if (sc.atLineEnd) { // Update the line state, so it can be seen by next line currentLine = styler.GetLine(sc.currentPos); switch (sc.state) { case SCE_LUA_DEFAULT: case SCE_LUA_LITERALSTRING: case SCE_LUA_COMMENT: case SCE_LUA_COMMENTDOC: case SCE_LUA_STRING: case SCE_LUA_CHARACTER: // Inside a literal string, block comment or string, we set the line state styler.SetLineState(currentLine, lastLineDocComment | stringWs | sepCount); break; default: // Reset the line state styler.SetLineState(currentLine, 0); break; } } if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) { // Prevent SCE_LUA_STRINGEOL from leaking back to previous line sc.SetState(SCE_LUA_STRING); } // Handle string line continuation if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) && sc.ch == '\\') { if (sc.chNext == '\n' || sc.chNext == '\r') { sc.Forward(); if (sc.ch == '\r' && sc.chNext == '\n') { sc.Forward(); } continue; } } // Determine if the current state should terminate. if (sc.state == SCE_LUA_OPERATOR) { if (sc.ch == ':' && sc.chPrev == ':') { // :: <label> :: forward scan sc.Forward(); Sci_Position ln = 0; while (IsASpaceOrTab(sc.GetRelativeChar(ln))) // skip over spaces/tabs ln++; const Sci_Position ws1 = ln; if (setWordStart.Contains(sc.GetRelativeChar(ln))) { char cLabel = 0; std::string s; while (setWord.Contains(cLabel = sc.GetRelativeChar(ln))) { // get potential label s.push_back(cLabel); ln++; } const Sci_Position lbl = ln; if (!keywords.InList(s)) { while (IsASpaceOrTab(sc.GetRelativeChar(ln))) // skip over spaces/tabs ln++; const Sci_Position ws2 = ln - lbl; if (sc.GetRelativeChar(ln) == ':' && sc.GetRelativeChar(ln + 1) == ':') { // final :: found, complete valid label construct sc.ChangeState(SCE_LUA_LABEL); if (ws1) { sc.SetState(SCE_LUA_DEFAULT); sc.ForwardBytes(ws1); } sc.SetState(SCE_LUA_LABEL); sc.ForwardBytes(lbl - ws1); if (ws2) { sc.SetState(SCE_LUA_DEFAULT); sc.ForwardBytes(ws2); } sc.SetState(SCE_LUA_LABEL); sc.ForwardBytes(2); } } } } sc.SetState(SCE_LUA_DEFAULT); } else if (sc.state == SCE_LUA_NUMBER) { // We stop the number definition on non-numerical non-dot non-eEpP non-sign non-hexdigit char if (!setNumber.Contains(sc.ch)) { sc.SetState(SCE_LUA_DEFAULT); } else if (sc.ch == '-' || sc.ch == '+') { if (!setExponent.Contains(sc.chPrev)) sc.SetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_IDENTIFIER) { idenPos -= idenStartCharWidth; // commit already-scanned identifier/word parts if (idenWordPos > 0) { idenWordPos--; sc.ChangeState(idenStyle); sc.ForwardBytes(idenWordPos); idenPos -= idenWordPos; if (idenPos > 0) { sc.SetState(SCE_LUA_IDENTIFIER); sc.ForwardBytes(idenPos); } } else { sc.ForwardBytes(idenPos); } sc.SetState(SCE_LUA_DEFAULT); if (foundGoto) { // goto <label> forward scan while (IsASpaceOrTab(sc.ch) && !sc.atLineEnd) sc.Forward(); if (setWordStart.Contains(sc.ch)) { sc.SetState(SCE_LUA_LABEL); sc.Forward(); while (setWord.Contains(sc.ch)) sc.Forward(); std::string s; sc.GetCurrentString(s, StyleContext::Transform::none); if (keywords.InList(s)) // labels cannot be keywords sc.ChangeState(SCE_LUA_WORD); } sc.SetState(SCE_LUA_DEFAULT); } } else if (AnyOf(sc.state, SCE_LUA_COMMENTLINE, SCE_LUA_COMMENTDOC, SCE_LUA_PREPROCESSOR)) { if (sc.atLineEnd) { sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_STRING) { if (stringWs) { if (!IsASpace(sc.ch)) stringWs = 0; } if (sc.ch == '\\') { if (setEscapeSkip.Contains(sc.chNext)) { sc.Forward(); } else if (sc.chNext == 'z') { sc.Forward(); stringWs = maskStringWs; } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (stringWs == 0 && sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.state == SCE_LUA_CHARACTER) { if (stringWs) { if (!IsASpace(sc.ch)) stringWs = 0; } if (sc.ch == '\\') { if (setEscapeSkip.Contains(sc.chNext)) { sc.Forward(); } else if (sc.chNext == 'z') { sc.Forward(); stringWs = maskStringWs; } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_LUA_DEFAULT); } else if (stringWs == 0 && sc.atLineEnd) { sc.ChangeState(SCE_LUA_STRINGEOL); sc.ForwardSetState(SCE_LUA_DEFAULT); } } else if (sc.ch == ']' && (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT)) { const int sep = LongDelimCheck(sc); if (sep == sepCount) { // ]=]-style delim sc.Forward(sep); sc.ForwardSetState(SCE_LUA_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_LUA_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_LUA_NUMBER); if (sc.ch == '0' && AnyOf(sc.chNext, 'x', 'X')) { sc.Forward(); } } else if (setWordStart.Contains(sc.ch)) { // For matching various identifiers with dots and colons, multiple // matches are done as identifier segments are added. Longest match is // set to a word style. The non-matched part is in identifier style. std::string ident; idenPos = 0; idenStartCharWidth = sc.width; idenWordPos = 0; idenStyle = SCE_LUA_IDENTIFIER; foundGoto = false; char cNext = 0; do { char cIdent = 0; const Sci_Position idenPosOld = idenPos; std::string identSeg; identSeg += sc.GetRelativeChar(idenPos++); while (setWord.Contains(cIdent = sc.GetRelativeChar(idenPos))) { identSeg += cIdent; idenPos++; } if (keywords.InList(identSeg) && (idenPosOld > 0)) { idenPos = idenPosOld - 1; // keywords cannot mix ident.pop_back(); break; } ident += identSeg; int newStyle = SCE_LUA_IDENTIFIER; if (keywords.InList(ident)) { newStyle = SCE_LUA_WORD; } else if (keywords2.InList(ident)) { newStyle = SCE_LUA_WORD2; } else if (keywords3.InList(ident)) { newStyle = SCE_LUA_WORD3; } else if (keywords4.InList(ident)) { newStyle = SCE_LUA_WORD4; } else if (keywords5.InList(ident)) { newStyle = SCE_LUA_WORD5; } else if (keywords6.InList(ident)) { newStyle = SCE_LUA_WORD6; } else if (keywords7.InList(ident)) { newStyle = SCE_LUA_WORD7; } else if (keywords8.InList(ident)) { newStyle = SCE_LUA_WORD8; } else { const int subStyle = classifierIdentifiers.ValueFor(ident); if (subStyle >= 0) { newStyle = subStyle; } } if (newStyle != SCE_LUA_IDENTIFIER) { idenStyle = newStyle; idenWordPos = idenPos; } if (idenStyle == SCE_LUA_WORD) // keywords cannot mix break; cNext = sc.GetRelativeChar(idenPos + 1); if ((cIdent == '.' || cIdent == ':') && setWordStart.Contains(cNext)) { ident += cIdent; idenPos++; } else { cNext = 0; } } while (cNext); if ((idenStyle == SCE_LUA_WORD) && (ident == "goto")) { foundGoto = true; } sc.SetState(SCE_LUA_IDENTIFIER); } else if (sc.ch == '\"') { sc.SetState(SCE_LUA_STRING); stringWs = 0; } else if (sc.ch == '\'') { sc.SetState(SCE_LUA_CHARACTER); stringWs = 0; } else if (sc.ch == '[') { sepCount = LongDelimCheck(sc); if (sepCount == 0) { sc.SetState(SCE_LUA_OPERATOR); } else { sc.SetState(SCE_LUA_LITERALSTRING); sc.Forward(sepCount); } } else if (sc.Match('-', '-')) { sc.SetState(lastLineDocComment ? SCE_LUA_COMMENTDOC : SCE_LUA_COMMENTLINE); if (sc.Match("--[")) { sc.Forward(2); sepCount = LongDelimCheck(sc); if (sepCount > 0) { sc.ChangeState(SCE_LUA_COMMENT); sc.Forward(sepCount); } } else if (sc.Match("---")) { sc.SetState(SCE_LUA_COMMENTDOC); lastLineDocComment = maskDocComment; } else { sc.Forward(); } } else if (sc.atLineStart && sc.Match('$')) { sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code } else if (setLuaOperator.Contains(sc.ch)) { sc.SetState(SCE_LUA_OPERATOR); } if (!AnyOf(sc.state, SCE_LUA_DEFAULT, SCE_LUA_COMMENTDOC)) { lastLineDocComment = 0; } } } sc.Complete(); } void LexerLua::Fold(Sci_PositionU startPos_, Sci_Position length, int initStyle, IDocument *pAccess) { LexAccessor styler(pAccess); const Sci_Position startPos = startPos_; const Sci_Position lengthDoc = startPos + length; int visibleChars = 0; Sci_Position lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; const bool foldCompact = options.foldCompact; int style = initStyle; int styleNext = styler.StyleIndexAt(startPos); for (Sci_Position i = startPos; i < lengthDoc; i++) { const char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); const int stylePrev = style; style = styleNext; if ((i + 1) < lengthDoc) { // Only read styles that have been set, otherwise treat style as continuing styleNext = styler.StyleIndexAt(i + 1); } const bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_LUA_WORD) { // Fixed list of folding words: if, do, function, repeat, end, until // Must fix up next line with initial characters if any new words added. if ((style != stylePrev) && AnyOf(ch, 'i', 'd', 'f', 'e', 'r', 'u')) { constexpr Sci_Position maxFoldWord = 9; // "function"sv.length() + 1 std::string s; for (Sci_Position j = 0; j < maxFoldWord; j++) { if (!iswordchar(styler[i + j])) { break; } s.push_back(styler[i + j]); } if (s == "if" || s == "do" || s == "function" || s == "repeat") { levelCurrent++; } if (s == "end" || s == "until") { levelCurrent--; } } } else if (style == SCE_LUA_OPERATOR) { if (ch == '{' || ch == '(') { levelCurrent++; } else if (ch == '}' || ch == ')') { levelCurrent--; } } else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) { if (stylePrev != style) { levelCurrent++; } else if (styleNext != style) { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) { lev |= SC_FOLDLEVELWHITEFLAG; } if ((levelCurrent > levelPrev) && (visibleChars > 0)) { lev |= SC_FOLDLEVELHEADERFLAG; } if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) { visibleChars++; } } // Fill in the real level of the next line, keeping the current flags as they will be filled in later const int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } } extern const LexerModule lmLua(SCLEX_LUA, LexerLua::LexerFactoryLua, "lua", luaWordListDesc);
20,134
C++
.cxx
609
29.310345
133
0.669745
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,445
LexTroff.cxx
dail8859_NotepadNext/src/lexilla/lexers/LexTroff.cxx
// Scintilla source code edit control /** @file LexTroff.cxx ** Lexer for the Troff typesetting language. ** This should work for Groff, Heirloom Troff and Neatroff and consequently ** for man pages. ** ** There are a number of restrictions: ** Escapes are not interpreted everywhere e.g. as part of command names. ** For the same reasons, changing control characters via `.cc` or `.c2` will ** not affect lexing - subsequent requests will not be styled correctly. ** Luckily this feature is rarely used. ** Line feeds cannot be escaped everywhere - this would require a state machine ** for all parsing. ** However, the C lexer has the same restriction. ** It is impossible to predict which macro argument is a numeric expression or where ** the number is actually treated as text. ** Also, escapes with levels of indirection (eg. `\\$1`) cannot currently ** be highlighted, as it is impossible to predict the context in which an ** expansion will be used. ** Indirect blocks (.ami, .ami1, .dei and .dei1) cannot be folded. ** No effort is done to highlight any of the preprocessors (tbl, pic, grap...). **/ // Copyright 2022-2024 by Robin Haberkorn <robin.haberkorn@googlemail.com> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <ctype.h> #include <string> #include <string_view> #include <algorithm> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" using namespace Lexilla; // Can be used as the line state to detect continuations // across calls to ColouriseTroffDoc(). enum TroffState { DEFAULT = 0, // REQUEST/COMMAND on a line means that it is a command line with continuation. REQUEST, COMMAND, // Flow control request with continuation FLOW_CONTROL, // Inside "ignore input" block (usually .ig) IGNORE }; static Sci_PositionU TroffEscapeBracketSize(Sci_PositionU startLine, Sci_PositionU endPos, Accessor &styler); static Sci_PositionU TroffEscapeQuoteSize(Sci_PositionU startLine, Sci_PositionU endPos, Accessor &styler); static Sci_PositionU ColouriseTroffEscape(Sci_PositionU startLine, Sci_PositionU endPos, Accessor &styler, WordList *keywordlists[], TroffState state); static void ColouriseTroffLine(Sci_PositionU startLine, Sci_PositionU endPos, Accessor &styler, WordList *keywordlists[], TroffState state); // For all escapes that take a one character (\*x), two character (\*(xy) or // arbitrary number of characters (\*[...]). static Sci_PositionU TroffEscapeBracketSize(Sci_PositionU startLine, Sci_PositionU endPos, Accessor &styler) { if (startLine > endPos) { return 0; } if (styler[startLine] == '(') { // two character name return std::min((Sci_PositionU)3, endPos-startLine+1); } if (styler[startLine] != '[') { // one character name return 1; } // name with arbitrary size between [...] Sci_PositionU i = startLine+1; while (i <= endPos) { if (styler[i] == ']') { return i-startLine+1; } if (styler[i] != '\\') { // not an escape i++; continue; } if (++i > endPos) { break; } // NOTE: Other escapes are not interpreted within \x[...]. switch (styler[i]) { case '*': // string register case '$': // macro argument case 'V': // environment variable case 'n': // numeric register i += 1; i += TroffEscapeBracketSize(i, endPos, styler); break; case 'A': // Is there a string with this name? case 'B': // Is there a register with this name? case 'R': // register increase i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); break; default: i += TroffEscapeBracketSize(i, endPos, styler); } } return endPos-startLine+1; } // For all escapes that take an argument in quotes, as in \v'...'. // Actually, this works with any character as a delimiter. static Sci_PositionU TroffEscapeQuoteSize(Sci_PositionU startLine, Sci_PositionU endPos, Accessor &styler) { if (startLine > endPos) { return 0; } char delim = styler[startLine]; Sci_PositionU i = startLine+1; while (i <= endPos) { if (styler[i] == delim) { return i-startLine+1; } if (styler[i] != '\\') { // not an escape i++; continue; } if (++i > endPos) { break; } // NOTE: Other escapes are not interpreted within \x'...'. switch (styler[i]) { case '*': // string register case '$': // macro argument case 'V': // environment variable case 'n': // numeric register i += 1; i += TroffEscapeBracketSize(i, endPos, styler); break; case 'A': // Is there a string with this name? case 'B': // Is there a register with this name? case 'R': // register increase i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); break; default: i += TroffEscapeBracketSize(i, endPos, styler); } } return endPos-startLine+1; } static Sci_PositionU ColouriseTroffEscape(Sci_PositionU startLine, Sci_PositionU endPos, Accessor &styler, WordList *keywordlists[], TroffState state) { Sci_PositionU i = startLine; Sci_Position curLine = styler.GetLine(startLine); if (styler[i] != '\\') { // not an escape - still consume one character return 1; } styler.ColourTo(i-1, SCE_TROFF_DEFAULT); i++; if (i > endPos) { return i-startLine; } switch (styler[i]) { case '"': // ordinary end of line comment styler.ColourTo(endPos, SCE_TROFF_COMMENT); return endPos-startLine+1; case '#': // \# comments will also "swallow" the EOL characters similar to // an escape at the end of line. // They are usually used only to comment entire lines, but we support // them after command lines anyway. styler.ColourTo(endPos, SCE_TROFF_COMMENT); // Next line will be a continuation styler.SetLineState(curLine, state); return endPos-startLine+1; case '*': // String register i += 1; i += TroffEscapeBracketSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_STRING); break; case '$': // Macro parameter i += 1; i += TroffEscapeBracketSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_MACRO); break; case 'V': // Environment variable i += 1; i += TroffEscapeBracketSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_ENV); break; case 'f': case 'F': // Font change i += 1; i += TroffEscapeBracketSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_FONT); break; case 'n': // Number register i += 1; if (styler[i] == '+' || styler[i] == '-') { i += 1; } if (i > endPos) { break; } i += TroffEscapeBracketSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_NUMBER); break; case 'g': case 'k': i += 1; i += TroffEscapeBracketSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_NUMBER); break; case 'R': // Number register increase i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_NUMBER); break; case 'm': case 'M': // Colour change i += 1; i += TroffEscapeBracketSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_COLOUR); break; case 'O': // Nested suppressions i += 1; i += TroffEscapeBracketSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_SUPPRESSION); break; case 's': // Type size // This is special in supporting both a +/- prefix directly // after \s and both the [...] and '...' syntax. i += 1; if (i > endPos) { break; } if (styler[i] == '+' || styler[i] == '-') { i += 1; } if (styler[i] == '\'') { i += TroffEscapeQuoteSize(i, endPos, styler); } else if (styler[i] == '(') { // You can place a +/- even after the opening brace as in \s(+12. // Otherwise this could be handled by TroffEscapeBracketSize(). i += 1; if (i > endPos) { break; } if (styler[i] == '+' || styler[i] == '-') { i += 1; } i += std::min((Sci_PositionU)2, endPos-i); } else { i += TroffEscapeBracketSize(i, endPos, styler); } styler.ColourTo(i-1, SCE_TROFF_ESCAPE_SIZE); break; case '{': // Opening code block i += 1; styler.ColourTo(i-1, SCE_TROFF_OPERATOR); // Groff actually supports commands immediately // following the opening brace as in `\{.tm`. // That's only why \{\ will actually treat the next line // as an ordinary command again. ColouriseTroffLine(i, endPos, styler, keywordlists, state); return endPos-startLine+1; case '}': // Closing code block // This exists only for the rare case of closing a // block in the middle of a line. i += 1; styler.ColourTo(i-1, SCE_TROFF_OPERATOR); break; case '\n': case '\r': // Escape newline styler.ColourTo(endPos, SCE_TROFF_ESCAPE_GLYPH); i += 1; // Next line will be a continuation styler.SetLineState(curLine, state); break; case '!': // transparent line styler.ColourTo(endPos, SCE_TROFF_ESCAPE_TRANSPARENT); return endPos-startLine+1; case '?': // Transparent embed until \? i++; while (i <= endPos) { if (styler.Match(i, "\\?")) { i += 2; break; } i++; } styler.ColourTo(i-1, SCE_TROFF_ESCAPE_TRANSPARENT); break; case 'b': // pile of chars i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_GLYPH); break; case 'A': case 'B': // Valid identifier or register? i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_ISVALID); break; case 'C': case 'N': // additional glyphs i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_GLYPH); break; case 'D': case 'l': case 'L': // drawing commands i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_DRAW); break; case 'h': case 'v': // horizontal/vertical movement i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_MOVE); break; case 'H': // font height i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_HEIGHT); break; case 'o': // overstrike i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_OVERSTRIKE); break; case 'S': // slant i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_SLANT); break; case 'w': // width of string i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_WIDTH); break; case 'x': // increase vertical spacing i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_VSPACING); break; case 'X': // device control commands i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_DEVICE); break; case 'Y': // device control commands i += 1; i += TroffEscapeBracketSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_DEVICE); break; case 'Z': // format string without moving i += 1; i += TroffEscapeQuoteSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_NOMOVE); break; case 'z': // Zero-width format i += std::min((Sci_PositionU)2, endPos-i); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_NOMOVE); break; default: i += TroffEscapeBracketSize(i, endPos, styler); styler.ColourTo(i-1, SCE_TROFF_ESCAPE_GLYPH); } return i-startLine; } static Sci_PositionU ColouriseTroffNumber(Sci_PositionU startLine, Sci_PositionU endPos, Accessor &styler) { Sci_PositionU i = startLine; if (!isdigit(styler[i])) { // not a digit return 0; } styler.ColourTo(i-1, SCE_TROFF_DEFAULT); i++; while (i <= endPos && isdigit(styler[i])) { i++; } if (i > endPos) { goto done; } if (styler[i] == '.') { i++; while (i <= endPos && isdigit(styler[i])) { i++; } if (i > endPos) { goto done; } } // Unit is part of number if (strchr("ciPpmMnuvsf", styler[i])) { i++; } done: styler.ColourTo(i-1, SCE_TROFF_NUMBER); return i-startLine; } static void ColouriseTroffLine(Sci_PositionU startLine, Sci_PositionU endPos, Accessor &styler, WordList *keywordlists[], TroffState state) { WordList &requests = *keywordlists[0]; WordList &flowControlCond = *keywordlists[1]; WordList &flowControlNocond = *keywordlists[2]; WordList &ignoreBlocks = *keywordlists[3]; Sci_PositionU i = startLine; if (startLine > endPos) { return; } Sci_Position curLine = styler.GetLine(startLine); // If the line state was not DEFAULT (i.e. the line had a continuation) // and the corresponding escape is erased, we must make sure that // the line state becomes DEFAULT again. styler.SetLineState(curLine, TroffState::DEFAULT); if (state == TroffState::IGNORE) { // Inside "ignore input" blocks if (styler[i] == '.') { i++; // Groff does not appear to allow spaces after the dot on // lines ending ignore blocks. #if 0 while (i <= endPos && isspacechar(styler[i])) { i++; } #endif Sci_PositionU startCommand = i; while (i <= endPos && !isspacechar(styler[i])) { i++; } // Check whether this is the end of the block by backtracking. // The alternative would be to maintain a per-lexer data structure // of ignore blocks along with their "end-mac" parameters. if (i > startCommand) { std::string endmac = styler.GetRange(startCommand, i); if (endmac == ".") { endmac.clear(); } // We styled right up to the "end-mac" argument or EOL. Sci_PositionU startEndmac = startLine; int style; while ((style = styler.BufferStyleAt(startEndmac-1)) != SCE_TROFF_REQUEST && style != SCE_TROFF_COMMAND) { startEndmac--; } Sci_PositionU endEndmac = startEndmac; while (!isspacechar(styler.SafeGetCharAt(endEndmac))) { endEndmac++; } std::string buf = endEndmac > startEndmac ? styler.GetRange(startEndmac, endEndmac) : ""; if (buf == endmac) { // Found the end of the ignore block. // This line can be an ordinary request or macro, // so we completely restyle it. state = TroffState::DEFAULT; ColouriseTroffLine(startLine, endPos, styler, keywordlists, state); return; } } } styler.ColourTo(endPos, SCE_TROFF_IGNORE); styler.SetLineState(curLine, TroffState::IGNORE); return; } if (state == TroffState::FLOW_CONTROL) { // Allow leading spaces only in continuations of flow control requests. while (i <= endPos && isspacechar(styler[i])) { i++; } } // NOTE: The control characters can theoretically be changed via `.cc` and `.c2`. // This is seldom done and in principle it makes Roff unparseable since there is // no way to determine whether one of those commands has been executed without // executing the entire code which may run forever (halting problem). // So not supporting alternate control characters is simply a necessary restriction of this lexer. if ((state == TroffState::DEFAULT || state == TroffState::FLOW_CONTROL) && (styler[i] == '.' || styler[i] == '\'')) { // Control line // TODO: It may make sense to highlight the non-breaking control character (') in // a separate style. i++; while (i <= endPos && isspacechar(styler[i])) { i++; } Sci_PositionU startCommand = i; while (i <= endPos && !isspacechar(styler[i])) { i++; // FIXME: Highlight escapes in this position? } if (startCommand == i) { // lone dot without anything following styler.ColourTo(endPos, SCE_TROFF_REQUEST); return; } std::string buf = styler.GetRange(startCommand, i); if (buf == "\\\"") { // Handling .\" separately makes sure that the entire line including // the leading dot is highlighted as a comment styler.ColourTo(endPos, SCE_TROFF_COMMENT); return; } if (buf == "\\}") { // Handling .\} separately makes sure it is styled like // the opening \{ braces. styler.ColourTo(endPos, SCE_TROFF_OPERATOR); return; } // Ignore blocks if (ignoreBlocks.InList(buf)) { // It's important to style right up to the optional end-mac argument, // since we use the SCE_TROFF_REQUEST/COMMAND style to check for block ends (see above). while (i <= endPos && isspacechar(styler[i]) && styler[i] != '\n' && styler[i] != '\r') { i++; } styler.ColourTo(i-1, requests.InList(buf) ? SCE_TROFF_REQUEST : SCE_TROFF_COMMAND); styler.ColourTo(endPos, SCE_TROFF_DEFAULT); // Next line will be an ignore block styler.SetLineState(curLine, TroffState::IGNORE); return; } // Flow control without conditionals if (flowControlNocond.InList(buf)) { styler.ColourTo(i-1, requests.InList(buf) ? SCE_TROFF_REQUEST : SCE_TROFF_COMMAND); state = TroffState::FLOW_CONTROL; styler.ColourTo(i-1, SCE_TROFF_DEFAULT); ColouriseTroffLine(i, endPos, styler, keywordlists, state); return; } // It is tempting to treat flow control requests like ordinary requests, // but you cannot really predict the beginning of the next command. // Eg. .if 'FOO'.tm' .tm BAR // We therefore have to parse at least the apostrophe expressions // and keep track of escapes. if (flowControlCond.InList(buf)) { styler.ColourTo(i-1, requests.InList(buf) ? SCE_TROFF_REQUEST : SCE_TROFF_COMMAND); while (i <= endPos && isspacechar(styler[i])) { i++; } if (i > endPos) { return; } if (styler[i] == '!') { i++; styler.ColourTo(i-1, SCE_TROFF_OPERATOR); } if (i > endPos) { return; } if (styler[i] == '\'') { // string comparison: 's1's2' // FIXME: Should be highlighted? // However, none of the conditionals are currently highlighted. i++; while (i <= endPos && styler[i] != '\'') { i += ColouriseTroffEscape(i, endPos, styler, keywordlists, state); } if (i > endPos) { return; } i++; while (i <= endPos && styler[i] != '\'') { i += ColouriseTroffEscape(i, endPos, styler, keywordlists, state); } if (i > endPos) { return; } i++; } else { // Everything else - including numeric expressions - // can contain spaces only in escapes and inside balanced round braces. int braceLevel = 0; while (i <= endPos && (braceLevel > 0 || !isspacechar(styler[i]))) { Sci_PositionU numLen; switch (styler[i]) { case '(': braceLevel++; i++; break; case ')': braceLevel--; i++; break; default: numLen = ColouriseTroffNumber(i, endPos, styler); i += numLen; if (numLen > 0) { break; } i += ColouriseTroffEscape(i, endPos, styler, keywordlists, state); } } } state = TroffState::FLOW_CONTROL; styler.ColourTo(i-1, SCE_TROFF_DEFAULT); ColouriseTroffLine(i, endPos, styler, keywordlists, state); return; } // remaining non-flow-control requests and commands state = requests.InList(buf) ? TroffState::REQUEST : TroffState::COMMAND; styler.ColourTo(i-1, state == TroffState::REQUEST ? SCE_TROFF_REQUEST : SCE_TROFF_COMMAND); } // Text line, request/command parameters including continuations while (i <= endPos) { if (state == TroffState::COMMAND && styler[i] == '"') { // Macro or misc command line arguments - assume that double-quoted strings // actually denote arguments. // FIXME: Allow escape linebreaks on the end of strings? // This would require another TroffState. styler.ColourTo(i-1, SCE_TROFF_DEFAULT); i++; while (i <= endPos && styler[i] != '"') { styler.ColourTo(i-1, SCE_TROFF_STRING); i += ColouriseTroffEscape(i, endPos, styler, keywordlists, state); } if (styler[i] == '"') { i++; } styler.ColourTo(i-1, SCE_TROFF_STRING); continue; } if (state == TroffState::COMMAND || state == TroffState::REQUEST) { // Numbers are supposed to be highlighted on every command line. // FIXME: Not all requests actually treat numbers specially. // Theoretically, we have to parse on a per-request basis. Sci_PositionU numLen; numLen = ColouriseTroffNumber(i, endPos, styler); i += numLen; if (numLen > 0) { continue; } } i += ColouriseTroffEscape(i, endPos, styler, keywordlists, state); } styler.ColourTo(endPos, SCE_TROFF_DEFAULT); } static void ColouriseTroffDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *keywordlists[], Accessor &styler) { styler.StartAt(startPos); Sci_PositionU startLine = startPos; Sci_Position curLine = styler.GetLine(startLine); styler.StartSegment(startLine); // NOTE: startPos will always be at the beginning of a line for (Sci_PositionU i = startPos; i < startPos + length; i++) { // NOTE: The CR in CRLF counts into the current line. bool atEOL = (styler[i] == '\r' && styler.SafeGetCharAt(i+1) != '\n') || styler[i] == '\n'; if (atEOL || i == startPos + length - 1) { // If the previous line had a continuation, the current line // is parsed like an argument to the command that had that continuation. TroffState state = curLine > 0 ? (TroffState)styler.GetLineState(curLine-1) : TroffState::DEFAULT; // End of line (or of line buffer) met, colourise it ColouriseTroffLine(startLine, i, styler, keywordlists, state); startLine = i + 1; curLine++; } } } static void FoldTroffDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *keywordlists[], Accessor &styler) { WordList &endmacBlocks = *keywordlists[4]; Sci_PositionU endPos = startPos + length; Sci_Position lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; int styleNext = styler.StyleAt(startPos); std::string requestName; for (Sci_PositionU i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || ch == '\n'; if (style == SCE_TROFF_OPERATOR && ch == '\\') { if (chNext == '{') { levelCurrent++; } else if (chNext == '}') { levelCurrent--; } } else if (style != SCE_TROFF_IGNORE && styleNext == SCE_TROFF_IGNORE) { // Beginning of ignore block levelCurrent++; } else if (style == SCE_TROFF_IGNORE && styleNext != SCE_TROFF_IGNORE) { // End of ignore block // The end-mac line will not be folded, which is probably okay // since it could start the next ignore block or could be any command that is // executed. // This is not handled by the endmac block handling below // since the `.ig` syntax is different. // FIXME: Fold at least `..` lines. levelCurrent--; } else if ((style == SCE_TROFF_REQUEST || style == SCE_TROFF_COMMAND) && !isspacechar(ch)) { requestName.push_back(ch); } if (!atEOL) { continue; } int lev = levelPrev; if (requestName.length() > 1) { if (endmacBlocks.InList(requestName.substr(1))) { // beginning of block levelCurrent++; } else { // potential end of block // This parsing could be avoided if we kept a list // line numbers and end-mac strings. // The parsing here could also be simplified if // we highlighted the end-mac strings in ColouriseTroffLine(). std::string endmac = requestName.substr(1); if (endmac == ".") { endmac.clear(); } // find start of block Sci_Position startLine = lineCurrent; while (startLine > 0 && styler.LevelAt(startLine-1) >= levelCurrent) { startLine--; } if (startLine) { Sci_Position startEndmac = styler.LineStart(startLine); int reqStyle; // skip the request/command name while ((reqStyle = styler.StyleAt(startEndmac)) == SCE_TROFF_REQUEST || reqStyle == SCE_TROFF_COMMAND) { startEndmac++; } while (isspacechar(styler.SafeGetCharAt(startEndmac))) { startEndmac++; } // skip the macro name while (!isspacechar(styler.SafeGetCharAt(startEndmac))) { startEndmac++; } while (isspacechar(styler.SafeGetCharAt(startEndmac)) && styler[startEndmac] != '\n' && styler[startEndmac] != '\r') { startEndmac++; } Sci_Position endEndmac = startEndmac; while (!isspacechar(styler.SafeGetCharAt(endEndmac))) { endEndmac++; } std::string buf = endEndmac > startEndmac ? styler.GetRange(startEndmac, endEndmac) : ""; if (buf == endmac) { // FIXME: Better fold the previous line unless it is `..`. levelCurrent--; } } } } else if (foldCompact && requestName == ".") { // lone dot ona line has no effect lev |= SC_FOLDLEVELWHITEFLAG; } if (levelCurrent > levelPrev) { lev |= SC_FOLDLEVELHEADERFLAG; } if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; requestName.clear(); } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } static const char * const troffWordLists[] = { "Predefined requests", "Flow control requests/commands with conditionals", "Flow control requests/commands without conditionals", "Requests and commands, initiating ignore blocks", "Requests and commands with end-macros", NULL, }; extern const LexerModule lmTroff(SCLEX_TROFF, ColouriseTroffDoc, "troff", FoldTroffDoc, troffWordLists);
26,455
C++
.cxx
824
27.902913
104
0.658955
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,463
LexVB.cxx
dail8859_NotepadNext/src/lexilla/lexers/LexVB.cxx
// Scintilla source code edit control /** @file LexVB.cxx ** Lexer for Visual Basic and VBScript. **/ // Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cstdlib> #include <cassert> #include <cstring> #include <string> #include <string_view> #include <map> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" #include "OptionSet.h" #include "DefaultLexer.h" using namespace Scintilla; using namespace Lexilla; namespace { // Internal state, highlighted as number constexpr int SCE_B_FILENUMBER = SCE_B_DEFAULT + 100; bool IsVBComment(Accessor &styler, Sci_Position pos, Sci_Position len) { return len > 0 && styler[pos] == '\''; } constexpr bool IsTypeCharacter(int ch) noexcept { return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$'; } // Extended to accept accented characters constexpr bool IsAWordChar(int ch) noexcept { return !IsASCII(ch) || (IsAlphaNumeric(ch) || ch == '.' || ch == '_'); } constexpr bool IsAWordStart(int ch) noexcept { return !IsASCII(ch) || (IsUpperOrLowerCase(ch) || ch == '_'); } constexpr bool IsANumberChar(int ch) noexcept { // Not exactly following number definition (several dots are seen as OK, etc.) // but probably enough in most cases. return IsAHeXDigit(ch) || AnyOf(ch, '.', '-', '+', '_'); } // Options used for LexerVB struct OptionsVB { bool fold = false; bool allowMultilineStr = false; }; const char * const vbWordListDesc[] = { "Keywords", "user1", "user2", "user3", nullptr }; struct OptionSetVB : public OptionSet<OptionsVB> { OptionSetVB() { DefineProperty("fold", &OptionsVB::fold); DefineProperty("lexer.vb.strings.multiline", &OptionsVB::allowMultilineStr, "Set to 1 to allow strings to continue over line ends."); DefineWordListSets(vbWordListDesc); } }; LexicalClass lexicalClasses[] = { // Lexer vb SCLEX_VB SCE_B_: 0, "SCE_B_DEFAULT", "default", "White space", 1, "SCE_B_COMMENT", "comment", "Comment: '", 2, "SCE_B_NUMBER", "literal numeric", "Number", 3, "SCE_B_KEYWORD", "keyword", "Keyword", 4, "SCE_B_STRING", "literal string", "Double quoted string", 5, "SCE_B_PREPROCESSOR", "preprocessor", "Preprocessor", 6, "SCE_B_OPERATOR", "operator", "Operators", 7, "SCE_B_IDENTIFIER", "identifier", "Identifiers", 8, "SCE_B_DATE", "literal date", "Date", 9, "SCE_B_STRINGEOL", "error literal string", "End of line where string is not closed", 10, "SCE_B_KEYWORD2", "identifier", "Keywords2", 11, "SCE_B_KEYWORD3", "identifier", "Keywords3", 12, "SCE_B_KEYWORD4", "identifier", "Keywords4", }; class LexerVB : public DefaultLexer { bool vbScriptSyntax; WordList keywords; WordList keywords2; WordList keywords3; WordList keywords4; OptionsVB options; OptionSetVB osVB; public: LexerVB(const char *languageName_, int language_, bool vbScriptSyntax_) : DefaultLexer(languageName_, language_, lexicalClasses, std::size(lexicalClasses)), vbScriptSyntax(vbScriptSyntax_) { } // Deleted so LexerVB objects can not be copied. LexerVB(const LexerVB &) = delete; LexerVB(LexerVB &&) = delete; void operator=(const LexerVB &) = delete; void operator=(LexerVB &&) = delete; ~LexerVB() override = default; void SCI_METHOD Release() override { delete this; } int SCI_METHOD Version() const override { return lvRelease5; } const char *SCI_METHOD PropertyNames() override { return osVB.PropertyNames(); } int SCI_METHOD PropertyType(const char *name) override { return osVB.PropertyType(name); } const char *SCI_METHOD DescribeProperty(const char *name) override { return osVB.DescribeProperty(name); } Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override; const char *SCI_METHOD PropertyGet(const char *key) override { return osVB.PropertyGet(key); } const char *SCI_METHOD DescribeWordListSets() override { return osVB.DescribeWordListSets(); } Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override; void CheckIdentifier(Lexilla::StyleContext &sc); void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void *SCI_METHOD PrivateCall(int, void *) override { return nullptr; } static ILexer5 *LexerFactoryVB() { return new LexerVB("vb", SCLEX_VB, false); } static ILexer5 *LexerFactoryVBScript() { return new LexerVB("vbscript", SCLEX_VBSCRIPT, true); } }; Sci_Position SCI_METHOD LexerVB::PropertySet(const char *key, const char *val) { if (osVB.PropertySet(&options, key, val)) { return 0; } return -1; } Sci_Position SCI_METHOD LexerVB::WordListSet(int n, const char *wl) { WordList *wordListN = nullptr; switch (n) { case 0: wordListN = &keywords; break; case 1: wordListN = &keywords2; break; case 2: wordListN = &keywords3; break; case 3: wordListN = &keywords4; break; default: break; } Sci_Position firstModification = -1; if (wordListN && wordListN->Set(wl, true)) { firstModification = 0; } return firstModification; } void LexerVB::CheckIdentifier(StyleContext &sc) { // In Basic (except VBScript), a variable name or a function name // can end with a special character indicating the type of the value // held or returned. bool skipType = false; if (!vbScriptSyntax && IsTypeCharacter(sc.ch)) { sc.Forward(); // Skip it skipType = true; } if (sc.ch == ']') { sc.Forward(); } char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (skipType) { s[strlen(s) - 1] = '\0'; } if (strcmp(s, "rem") == 0) { sc.ChangeState(SCE_B_COMMENT); } else { if (keywords.InList(s)) { sc.ChangeState(SCE_B_KEYWORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_B_KEYWORD2); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_B_KEYWORD3); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_B_KEYWORD4); } // Else, it is really an identifier... sc.SetState(SCE_B_DEFAULT); } } void LexerVB::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) { Accessor styler(pAccess, nullptr); styler.StartAt(startPos); int visibleChars = 0; int fileNbDigits = 0; // Do not leak onto next line if (initStyle == SCE_B_STRINGEOL || initStyle == SCE_B_COMMENT || initStyle == SCE_B_PREPROCESSOR) { initStyle = SCE_B_DEFAULT; } StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.state == SCE_B_OPERATOR) { sc.SetState(SCE_B_DEFAULT); } else if (sc.state == SCE_B_IDENTIFIER) { if (!IsAWordChar(sc.ch)) { CheckIdentifier(sc); } } else if (sc.state == SCE_B_NUMBER) { // We stop the number definition on non-numerical non-dot non-eE non-sign char // Also accepts A-F for hex. numbers if (!IsANumberChar(sc.ch)) { sc.SetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_STRING) { // VB doubles quotes to preserve them, so just end this string // state now as a following quote will start again if (sc.ch == '\"') { if (sc.chNext == '\"') { sc.Forward(); } else { if (MakeLowerCase(sc.chNext) == 'c') { sc.Forward(); } sc.ForwardSetState(SCE_B_DEFAULT); } } else if (sc.atLineEnd && !options.allowMultilineStr) { visibleChars = 0; sc.ChangeState(SCE_B_STRINGEOL); sc.ForwardSetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_COMMENT) { if (sc.atLineEnd) { visibleChars = 0; sc.ForwardSetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_PREPROCESSOR) { if (sc.atLineEnd) { visibleChars = 0; sc.ForwardSetState(SCE_B_DEFAULT); } } else if (sc.state == SCE_B_FILENUMBER) { if (IsADigit(sc.ch)) { fileNbDigits++; if (fileNbDigits > 3) { sc.ChangeState(SCE_B_DATE); } } else if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ',') { // Regular uses: Close #1; Put #1, ...; Get #1, ... etc. // Too bad if date is format #27, Oct, 2003# or something like that... // Use regular number state sc.ChangeState(SCE_B_NUMBER); sc.SetState(SCE_B_DEFAULT); } else if (sc.ch == '#') { sc.ChangeState(SCE_B_DATE); sc.ForwardSetState(SCE_B_DEFAULT); } else { sc.ChangeState(SCE_B_DATE); } if (sc.state != SCE_B_FILENUMBER) { fileNbDigits = 0; } } else if (sc.state == SCE_B_DATE) { if (sc.atLineEnd) { visibleChars = 0; sc.ChangeState(SCE_B_STRINGEOL); sc.ForwardSetState(SCE_B_DEFAULT); } else if (sc.ch == '#') { sc.ForwardSetState(SCE_B_DEFAULT); } } if (sc.state == SCE_B_DEFAULT) { if (sc.ch == '\'') { sc.SetState(SCE_B_COMMENT); } else if (sc.ch == '\"') { sc.SetState(SCE_B_STRING); } else if (sc.ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line sc.SetState(SCE_B_PREPROCESSOR); } else if (sc.ch == '#') { // It can be a date literal, ending with #, or a file number, from 1 to 511 // The date literal depends on the locale, so anything can go between #'s. // Can be #January 1, 1993# or #1 Jan 93# or #05/11/2003#, etc. // So we set the FILENUMBER state, and switch to DATE if it isn't a file number sc.SetState(SCE_B_FILENUMBER); } else if (sc.ch == '&' && MakeLowerCase(sc.chNext) == 'h') { // Hexadecimal number sc.SetState(SCE_B_NUMBER); sc.Forward(); } else if (sc.ch == '&' && MakeLowerCase(sc.chNext) == 'o') { // Octal number sc.SetState(SCE_B_NUMBER); sc.Forward(); } else if (sc.ch == '&' && MakeLowerCase(sc.chNext) == 'b') { // Binary number sc.SetState(SCE_B_NUMBER); sc.Forward(); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_B_NUMBER); } else if (IsAWordStart(sc.ch) || (sc.ch == '[')) { sc.SetState(SCE_B_IDENTIFIER); } else if (isoperator(sc.ch) || (sc.ch == '\\')) { // Integer division sc.SetState(SCE_B_OPERATOR); } } if (sc.atLineEnd) { visibleChars = 0; } if (!IsASpace(sc.ch)) { visibleChars++; } } if (sc.state == SCE_B_IDENTIFIER && !IsAWordChar(sc.ch)) { CheckIdentifier(sc); } sc.Complete(); } void LexerVB::Fold(Sci_PositionU startPos, Sci_Position length, int, IDocument *pAccess) { if (!options.fold) return; Accessor styler(pAccess, nullptr); const Sci_Position endPos = startPos + length; // Backtrack to previous line in case need to fix its fold status Sci_Position lineCurrent = styler.GetLine(startPos); if (startPos > 0) { if (lineCurrent > 0) { lineCurrent--; startPos = styler.LineStart(lineCurrent); } } int spaceFlags = 0; int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsVBComment); char chNext = styler[startPos]; for (Sci_Position i = startPos; i < endPos; i++) { const char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) { int lev = indentCurrent; const int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsVBComment); if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { // Only non whitespace lines can be headers if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } else if (indentNext & SC_FOLDLEVELWHITEFLAG) { // Line after is blank so check the next - maybe should continue further? int spaceFlags2 = 0; const int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsVBComment); if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) { lev |= SC_FOLDLEVELHEADERFLAG; } } } indentCurrent = indentNext; styler.SetLevel(lineCurrent, lev); lineCurrent++; } } } } extern const LexerModule lmVB(SCLEX_VB, LexerVB::LexerFactoryVB, "vb", vbWordListDesc); extern const LexerModule lmVBScript(SCLEX_VBSCRIPT, LexerVB::LexerFactoryVBScript, "vbscript", vbWordListDesc);
12,247
C++
.cxx
371
30.002695
111
0.681933
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,494
LexX12.cxx
dail8859_NotepadNext/src/lexilla/lexers/LexX12.cxx
// Scintilla Lexer for X12 // @file LexX12.cxx // Written by Iain Clarke, IMCSoft & Inobiz AB. // X12 official documentation is behind a paywall, but there's a description of the syntax here: // http://www.rawlinsecconsulting.com/x12tutorial/x12syn.html // This code is subject to the same license terms as the rest of the scintilla project: // The License.txt file describes the conditions under which this software may be distributed. // // Header order must match order in scripts/HeaderOrder.txt #include <cstdlib> #include <cassert> #include <cstring> #include <cctype> #include <string> #include <string_view> #include <vector> #include <algorithm> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "LexerModule.h" #include "DefaultLexer.h" using namespace Scintilla; using namespace Lexilla; class LexerX12 : public DefaultLexer { public: LexerX12(); virtual ~LexerX12() {} // virtual destructor, as we inherit from ILexer static ILexer5 *Factory() { return new LexerX12; } int SCI_METHOD Version() const override { return lvRelease5; } void SCI_METHOD Release() override { delete this; } const char * SCI_METHOD PropertyNames() override { return "fold"; } int SCI_METHOD PropertyType(const char *) override { return SC_TYPE_BOOLEAN; // Only one property! } const char * SCI_METHOD DescribeProperty(const char *name) override { if (!strcmp(name, "fold")) return "Whether to apply folding to document or not"; return ""; } Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override { if (!strcmp(key, "fold")) { m_bFold = strcmp(val, "0") ? true : false; return 0; } return -1; } const char * SCI_METHOD PropertyGet(const char *) override { return ""; } const char * SCI_METHOD DescribeWordListSets() override { return ""; } Sci_Position SCI_METHOD WordListSet(int, const char *) override { return -1; } void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void * SCI_METHOD PrivateCall(int, void *) override { return NULL; } protected: struct Terminator { int Style = SCE_X12_BAD; Sci_PositionU pos = 0; Sci_PositionU length = 0; int FoldChange = 0; }; Terminator InitialiseFromISA(IDocument *pAccess); Sci_PositionU FindPreviousSegmentStart(IDocument *pAccess, Sci_Position startPos) const; Terminator DetectSegmentHeader(IDocument *pAccess, Sci_PositionU pos) const; Terminator FindNextTerminator(IDocument *pAccess, Sci_PositionU pos, bool bJustSegmentTerminator = false) const; bool m_bFold = false; char m_SeparatorSubElement = 0; char m_SeparatorElement = 0; std::string m_SeparatorSegment; // might be multiple characters std::string m_LineFeed; }; extern const LexerModule lmX12(SCLEX_X12, LexerX12::Factory, "x12"); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// LexerX12::LexerX12() : DefaultLexer("x12", SCLEX_X12) { } void LexerX12::Lex(Sci_PositionU startPos, Sci_Position length, int, IDocument *pAccess) { Sci_PositionU posFinish = startPos + length; Terminator T = InitialiseFromISA(pAccess); if (T.Style == SCE_X12_BAD) { if (T.pos < startPos) T.pos = startPos; // we may be colouring in batches. pAccess->StartStyling(startPos); pAccess->SetStyleFor(T.pos - startPos, SCE_X12_ENVELOPE); pAccess->SetStyleFor(posFinish - T.pos, SCE_X12_BAD); return; } // Look backwards for a segment start or a document beginning Sci_PositionU posCurrent = FindPreviousSegmentStart (pAccess, startPos); // Style buffer, so we're not issuing loads of notifications pAccess->StartStyling(posCurrent); while (posCurrent < posFinish) { // Look for first element marker, so we can denote segment T = DetectSegmentHeader(pAccess, posCurrent); if (T.Style == SCE_X12_BAD) break; pAccess->SetStyleFor(T.pos - posCurrent, T.Style); pAccess->SetStyleFor(T.length, SCE_X12_SEP_ELEMENT); posCurrent = T.pos + T.length; while (T.Style != SCE_X12_BAD && T.Style != SCE_X12_SEGMENTEND) // Break on bad or segment ending { T = FindNextTerminator(pAccess, posCurrent, false); if (T.Style == SCE_X12_BAD) break; int Style = T.Style; pAccess->SetStyleFor(T.pos - posCurrent, SCE_X12_DEFAULT); pAccess->SetStyleFor(T.length, Style); posCurrent = T.pos + T.length; } if (T.Style == SCE_X12_BAD) break; } pAccess->SetStyleFor(posFinish - posCurrent, SCE_X12_BAD); } void LexerX12::Fold(Sci_PositionU startPos, Sci_Position length, int, IDocument *pAccess) { if (!m_bFold) return; // Are we even foldable? // check for cr,lf,cr+lf. if (m_LineFeed.empty()) return; Sci_PositionU posFinish = startPos + length; // Look backwards for a segment start or a document beginning startPos = FindPreviousSegmentStart(pAccess, startPos); Terminator T; Sci_PositionU currLine = pAccess->LineFromPosition(startPos); int levelCurrentStyle = SC_FOLDLEVELBASE; int indentCurrent = 0; if (currLine > 0) { levelCurrentStyle = pAccess->GetLevel(currLine - 1); // bottom 12 bits are level indentCurrent = levelCurrentStyle & (SC_FOLDLEVELBASE - 1); // indent from previous line Sci_PositionU posLine = pAccess->LineStart(currLine - 1); T = DetectSegmentHeader(pAccess, posLine); indentCurrent += T.FoldChange; } while (startPos < posFinish) { T = DetectSegmentHeader(pAccess, startPos); int indentNext = indentCurrent + T.FoldChange; if (indentNext < 0) indentNext = 0; levelCurrentStyle = (T.FoldChange > 0) ? (SC_FOLDLEVELBASE | SC_FOLDLEVELHEADERFLAG) : SC_FOLDLEVELBASE; currLine = pAccess->LineFromPosition(startPos); pAccess->SetLevel(currLine, levelCurrentStyle | indentCurrent); T = FindNextTerminator(pAccess, startPos, true); if (T.Style == SCE_X12_BAD) break; startPos = T.pos + T.length; indentCurrent = indentNext; } } LexerX12::Terminator LexerX12::InitialiseFromISA(IDocument *pAccess) { Sci_Position length = pAccess->Length(); if (length <= 108) return { SCE_X12_BAD, 0 }; pAccess->GetCharRange(&m_SeparatorElement, 3, 1); pAccess->GetCharRange(&m_SeparatorSubElement, 104, 1); // Look for GS, as that's the next segment. Anything between 105 and GS/IEA is our segment separator. Sci_Position posNextSegment; char bufSegment[3] = { 0 }; for (posNextSegment = 105; posNextSegment < length - 3; posNextSegment++) { pAccess->GetCharRange(bufSegment, posNextSegment, 3); if (!memcmp (bufSegment, "GS", 2) || !memcmp(bufSegment, "IEA", 3)) { m_SeparatorSegment.resize(posNextSegment - 105); pAccess->GetCharRange(&m_SeparatorSegment.at(0), 105, posNextSegment - 105); // Is some of that CR+LF? size_t nPos = m_SeparatorSegment.find_last_not_of("\r\n"); m_LineFeed = m_SeparatorSegment.substr(nPos + 1); m_SeparatorSegment = m_SeparatorSegment.substr(0, nPos + 1); break; } } if (m_SeparatorSegment.empty() && m_LineFeed.empty()) { return { SCE_X12_BAD, 105 }; } // Validate we have an element separator, and it's not silly! if (m_SeparatorElement == '\0' || m_SeparatorElement == '\n' || m_SeparatorElement == '\r') return { SCE_X12_BAD, 3 }; // Validate we have an element separator, and it's not silly! if (m_SeparatorSubElement == '\0' || m_SeparatorSubElement == '\n' || m_SeparatorSubElement == '\r') return { SCE_X12_BAD, 103 }; if (m_SeparatorElement == m_SeparatorSubElement) return { SCE_X12_BAD, 104 }; for (auto& c : m_SeparatorSegment) { if (m_SeparatorElement == c) return { SCE_X12_BAD, 105 }; if (m_SeparatorSubElement == c) return { SCE_X12_BAD, 105 }; } // Check we have element markers at all the right places! ISA element has fixed entries. std::vector<Sci_PositionU> ElementMarkers = { 3, 6, 17, 20, 31, 34, 50, 53, 69, 76, 81, 83, 89, 99, 101, 103 }; for (auto i : ElementMarkers) { char c; pAccess->GetCharRange(&c, i, 1); if (c != m_SeparatorElement) return { SCE_X12_BAD, i }; } // Check we have no element markers anywhere else! for (Sci_PositionU i = 0; i < 105; i++) { if (std::find(ElementMarkers.begin(), ElementMarkers.end(), i) != ElementMarkers.end()) continue; char c; pAccess->GetCharRange(&c, i, 1); if (c == m_SeparatorElement) return { SCE_X12_BAD, i }; } return { SCE_X12_ENVELOPE }; } Sci_PositionU LexerX12::FindPreviousSegmentStart(IDocument *pAccess, Sci_Position startPos) const { Sci_PositionU length = pAccess->Length(); std::string bufTest = m_SeparatorSegment + m_LineFeed; // quick way of making the lengths the same std::string bufCompare = bufTest; for (; startPos > 0; startPos--) { if (startPos + bufTest.size() > length) continue; pAccess->GetCharRange(&bufTest.at(0), startPos, bufTest.size()); if (bufTest == bufCompare) { return startPos + bufTest.size(); } } // We didn't find a ', so just go with the beginning return 0; } LexerX12::Terminator LexerX12::DetectSegmentHeader(IDocument *pAccess, Sci_PositionU pos) const { Sci_PositionU Length = pAccess->Length(); Length -= pos; char c, Buf[4] = { 0 }; // max 3 + separator for (Sci_PositionU posOffset = 0; posOffset < std::size(Buf) && posOffset < Length; posOffset++) { pAccess->GetCharRange(&c, pos + posOffset, 1); if (c != m_SeparatorElement) { Buf[posOffset] = c; continue; } // check for special segments, involved in folding start/stop. if (memcmp(Buf, "ISA", 3) == 0) return { SCE_X12_ENVELOPE, pos + posOffset, 1, +1 }; if (memcmp(Buf, "IEA", 3) == 0) return { SCE_X12_ENVELOPE, pos + posOffset, 1, -1 }; if (memcmp(Buf, "GS", 2) == 0) return { SCE_X12_FUNCTIONGROUP, pos + posOffset, 1, +1 }; if (memcmp(Buf, "GE", 2) == 0) return { SCE_X12_FUNCTIONGROUP, pos + posOffset, 1, -1 }; if (memcmp(Buf, "ST", 2) == 0) return { SCE_X12_TRANSACTIONSET, pos + posOffset, 1, +1 }; if (memcmp(Buf, "SE", 2) == 0) return { SCE_X12_TRANSACTIONSET, pos + posOffset, 1, -1 }; return { SCE_X12_SEGMENTHEADER, pos + posOffset, 1, 0 }; } return { SCE_X12_BAD, pos, 0, 0 }; } LexerX12::Terminator LexerX12::FindNextTerminator(IDocument *pAccess, Sci_PositionU pos, bool bJustSegmentTerminator) const { char c; Sci_PositionU length = pAccess->Length(); std::string bufTestSegment = m_SeparatorSegment; // quick way of making the lengths the same std::string bufTestLineFeed = m_LineFeed; // quick way of making the lengths the same while (pos < (Sci_PositionU)length) { pAccess->GetCharRange(&c, pos, 1); if (pos + m_SeparatorSegment.size() > length) bufTestSegment.clear(); // going up - so once we can't get this, we're done with the buffer. else if (!bufTestSegment.empty()) pAccess->GetCharRange(&bufTestSegment.at(0), pos, bufTestSegment.size()); if (pos + m_LineFeed.size() > length) bufTestLineFeed.clear(); // going up - so once we can't get this, we're done with the buffer. else if (!bufTestLineFeed.empty()) pAccess->GetCharRange(&bufTestLineFeed.at(0), pos, bufTestLineFeed.size()); if (!bJustSegmentTerminator && c == m_SeparatorElement) return { SCE_X12_SEP_ELEMENT, pos, 1 }; else if (!bJustSegmentTerminator && c == m_SeparatorSubElement) return { SCE_X12_SEP_SUBELEMENT, pos, 1 }; else if (!m_SeparatorSegment.empty() && bufTestSegment == m_SeparatorSegment) { if (m_LineFeed.empty()) return { SCE_X12_SEGMENTEND, pos, m_SeparatorSegment.size() }; // is this the end? if (pos + m_SeparatorSegment.size() == length) return { SCE_X12_SEGMENTEND, pos, m_SeparatorSegment.size() }; // Check if we're followed by a linefeed. if (pos + m_SeparatorSegment.size() + m_LineFeed.size() > length) return { SCE_X12_BAD, pos }; bufTestSegment = m_LineFeed; pAccess->GetCharRange(&bufTestSegment.at(0), pos + m_SeparatorSegment.size(), bufTestSegment.size()); if (bufTestSegment == m_LineFeed) return { SCE_X12_SEGMENTEND, pos, m_SeparatorSegment.size() + m_LineFeed.size() }; break; } else if (m_SeparatorSegment.empty() && bufTestLineFeed == m_LineFeed) { return { SCE_X12_SEGMENTEND, pos, m_LineFeed.size() }; } pos++; } return { SCE_X12_BAD, pos }; }
12,326
C++
.cxx
341
33.486804
123
0.705769
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,501
LexGDScript.cxx
dail8859_NotepadNext/src/lexilla/lexers/LexGDScript.cxx
// Scintilla source code edit control /** @file LexGDScript.cxx ** Lexer for GDScript. **/ // Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org> // Heavily modified later for GDScript // The License.txt file describes the conditions under which this software may be distributed. #include <cstdlib> #include <cassert> #include <cstring> #include <string> #include <string_view> #include <vector> #include <map> #include <algorithm> #include <functional> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "StringCopy.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "CharacterCategory.h" #include "LexerModule.h" #include "OptionSet.h" #include "SubStyles.h" #include "DefaultLexer.h" using namespace Scintilla; using namespace Lexilla; namespace { enum kwType { kwOther, kwClass, kwDef, kwExtends}; constexpr int indicatorWhitespace = 1; bool IsGDStringStart(int ch) { return (ch == '\'' || ch == '"'); } bool IsGDComment(Accessor &styler, Sci_Position pos, Sci_Position len) { return len > 0 && styler[pos] == '#'; } constexpr bool IsGDSingleQuoteStringState(int st) noexcept { return ((st == SCE_GD_CHARACTER) || (st == SCE_GD_STRING)); } constexpr bool IsGDTripleQuoteStringState(int st) noexcept { return ((st == SCE_GD_TRIPLE) || (st == SCE_GD_TRIPLEDOUBLE)); } char GetGDStringQuoteChar(int st) noexcept { if ((st == SCE_GD_CHARACTER) || (st == SCE_GD_TRIPLE)) return '\''; if ((st == SCE_GD_STRING) || (st == SCE_GD_TRIPLEDOUBLE)) return '"'; return '\0'; } /* Return the state to use for the string starting at i; *nextIndex will be set to the first index following the quote(s) */ int GetGDStringState(Accessor &styler, Sci_Position i, Sci_PositionU *nextIndex) { char ch = styler.SafeGetCharAt(i); char chNext = styler.SafeGetCharAt(i + 1); if (ch != '"' && ch != '\'') { *nextIndex = i + 1; return SCE_GD_DEFAULT; } if (ch == chNext && ch == styler.SafeGetCharAt(i + 2)) { *nextIndex = i + 3; if (ch == '"') return SCE_GD_TRIPLEDOUBLE; else return SCE_GD_TRIPLE; } else { *nextIndex = i + 1; if (ch == '"') return SCE_GD_STRING; else return SCE_GD_CHARACTER; } } int GetGDStringState(int ch) { if (ch != '"' && ch != '\'') return SCE_GD_DEFAULT; if (ch == '"') return SCE_GD_STRING; else return SCE_GD_CHARACTER; } inline bool IsAWordChar(int ch, bool unicodeIdentifiers) { if (IsASCII(ch)) return (IsAlphaNumeric(ch) || ch == '.' || ch == '_'); if (!unicodeIdentifiers) return false; return IsXidContinue(ch); } inline bool IsANodePathChar(int ch, bool unicodeIdentifiers) { if (IsASCII(ch)) return (IsAlphaNumeric(ch) || ch == '_' || ch == '/' || ch =='%'); if (!unicodeIdentifiers) return false; return IsXidContinue(ch); } inline bool IsAWordStart(int ch, bool unicodeIdentifiers) { if (IsASCII(ch)) return (IsUpperOrLowerCase(ch) || ch == '_'); if (!unicodeIdentifiers) return false; return IsXidStart(ch); } bool IsFirstNonWhitespace(Sci_Position pos, Accessor &styler) { const Sci_Position line = styler.GetLine(pos); const Sci_Position start_pos = styler.LineStart(line); for (Sci_Position i = start_pos; i < pos; i++) { const char ch = styler[i]; if (!(ch == ' ' || ch == '\t')) return false; } return true; } // Options used for LexerGDScript struct OptionsGDScript { int whingeLevel; bool base2or8Literals; bool stringsOverNewline; bool keywords2NoSubIdentifiers; bool fold; bool foldQuotes; bool foldCompact; bool unicodeIdentifiers; OptionsGDScript() noexcept { whingeLevel = 0; base2or8Literals = true; stringsOverNewline = false; keywords2NoSubIdentifiers = false; fold = false; foldQuotes = false; foldCompact = false; unicodeIdentifiers = true; } }; const char *const gdscriptWordListDesc[] = { "Keywords", "Highlighted identifiers", nullptr }; struct OptionSetGDScript : public OptionSet<OptionsGDScript> { OptionSetGDScript() { DefineProperty("lexer.gdscript.whinge.level", &OptionsGDScript::whingeLevel, "For GDScript code, checks whether indenting is consistent. " "The default, 0 turns off indentation checking, " "1 checks whether each line is potentially inconsistent with the previous line, " "2 checks whether any space characters occur before a tab character in the indentation, " "3 checks whether any spaces are in the indentation, and " "4 checks for any tab characters in the indentation. " "1 is a good level to use."); DefineProperty("lexer.gdscript.literals.binary", &OptionsGDScript::base2or8Literals, "Set to 0 to not recognise binary and octal literals: 0b1011 0o712."); DefineProperty("lexer.gdscript.strings.over.newline", &OptionsGDScript::stringsOverNewline, "Set to 1 to allow strings to span newline characters."); DefineProperty("lexer.gdscript.keywords2.no.sub.identifiers", &OptionsGDScript::keywords2NoSubIdentifiers, "When enabled, it will not style keywords2 items that are used as a sub-identifier. " "Example: when set, will not highlight \"foo.open\" when \"open\" is a keywords2 item."); DefineProperty("fold", &OptionsGDScript::fold); DefineProperty("fold.gdscript.quotes", &OptionsGDScript::foldQuotes, "This option enables folding multi-line quoted strings when using the GDScript lexer."); DefineProperty("fold.compact", &OptionsGDScript::foldCompact); DefineProperty("lexer.gdscript.unicode.identifiers", &OptionsGDScript::unicodeIdentifiers, "Set to 0 to not recognise Unicode identifiers."); DefineWordListSets(gdscriptWordListDesc); } }; const char styleSubable[] = { SCE_GD_IDENTIFIER, 0 }; LexicalClass lexicalClasses[] = { // Lexer GDScript SCLEX_GDSCRIPT SCE_GD_: 0, "SCE_GD_DEFAULT", "default", "White space", 1, "SCE_GD_COMMENTLINE", "comment line", "Comment", 2, "SCE_GD_NUMBER", "literal numeric", "Number", 3, "SCE_GD_STRING", "literal string", "String", 4, "SCE_GD_CHARACTER", "literal string", "Single quoted string", 5, "SCE_GD_WORD", "keyword", "Keyword", 6, "SCE_GD_TRIPLE", "literal string", "Triple quotes", 7, "SCE_GD_TRIPLEDOUBLE", "literal string", "Triple double quotes", 8, "SCE_GD_CLASSNAME", "identifier", "Class name definition", 9, "SCE_GD_FUNCNAME", "identifier", "Function or method name definition", 10, "SCE_GD_OPERATOR", "operator", "Operators", 11, "SCE_GD_IDENTIFIER", "identifier", "Identifiers", 12, "SCE_GD_COMMENTBLOCK", "comment", "Comment-blocks", 13, "SCE_GD_STRINGEOL", "error literal string", "End of line where string is not closed", 14, "SCE_GD_WORD2", "identifier", "Highlighted identifiers", 15, "SCE_GD_ANNOTATION", "annotation", "Annotations", 16, "SCE_GD_NODEPATH", "path", "Node path", }; } class LexerGDScript : public DefaultLexer { WordList keywords; WordList keywords2; OptionsGDScript options; OptionSetGDScript osGDScript; enum { ssIdentifier }; SubStyles subStyles{styleSubable}; public: explicit LexerGDScript() : DefaultLexer("gdscript", SCLEX_GDSCRIPT, lexicalClasses, ELEMENTS(lexicalClasses)) { } ~LexerGDScript() override { } void SCI_METHOD Release() override { delete this; } int SCI_METHOD Version() const override { return lvRelease5; } const char *SCI_METHOD PropertyNames() override { return osGDScript.PropertyNames(); } int SCI_METHOD PropertyType(const char *name) override { return osGDScript.PropertyType(name); } const char *SCI_METHOD DescribeProperty(const char *name) override { return osGDScript.DescribeProperty(name); } Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override; const char * SCI_METHOD PropertyGet(const char *key) override { return osGDScript.PropertyGet(key); } const char *SCI_METHOD DescribeWordListSets() override { return osGDScript.DescribeWordListSets(); } Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override; void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void *SCI_METHOD PrivateCall(int, void *) override { return nullptr; } int SCI_METHOD LineEndTypesSupported() override { return SC_LINE_END_TYPE_UNICODE; } int SCI_METHOD AllocateSubStyles(int styleBase, int numberStyles) override { return subStyles.Allocate(styleBase, numberStyles); } int SCI_METHOD SubStylesStart(int styleBase) override { return subStyles.Start(styleBase); } int SCI_METHOD SubStylesLength(int styleBase) override { return subStyles.Length(styleBase); } int SCI_METHOD StyleFromSubStyle(int subStyle) override { const int styleBase = subStyles.BaseStyle(subStyle); return styleBase; } int SCI_METHOD PrimaryStyleFromStyle(int style) override { return style; } void SCI_METHOD FreeSubStyles() override { subStyles.Free(); } void SCI_METHOD SetIdentifiers(int style, const char *identifiers) override { subStyles.SetIdentifiers(style, identifiers); } int SCI_METHOD DistanceToSecondaryStyles() override { return 0; } const char *SCI_METHOD GetSubStyleBases() override { return styleSubable; } static ILexer5 *LexerFactoryGDScript() { return new LexerGDScript(); } private: void ProcessLineEnd(StyleContext &sc, bool &inContinuedString); }; Sci_Position SCI_METHOD LexerGDScript::PropertySet(const char *key, const char *val) { if (osGDScript.PropertySet(&options, key, val)) { return 0; } return -1; } Sci_Position SCI_METHOD LexerGDScript::WordListSet(int n, const char *wl) { WordList *wordListN = nullptr; switch (n) { case 0: wordListN = &keywords; break; case 1: wordListN = &keywords2; break; default: break; } Sci_Position firstModification = -1; if (wordListN) { WordList wlNew; wlNew.Set(wl); if (*wordListN != wlNew) { wordListN->Set(wl); firstModification = 0; } } return firstModification; } void LexerGDScript::ProcessLineEnd(StyleContext &sc, bool &inContinuedString) { if ((sc.state == SCE_GD_DEFAULT) || IsGDTripleQuoteStringState(sc.state)) { // Perform colourisation of white space and triple quoted strings at end of each line to allow // tab marking to work inside white space and triple quoted strings sc.SetState(sc.state); } if (IsGDSingleQuoteStringState(sc.state)) { if (inContinuedString || options.stringsOverNewline) { inContinuedString = false; } else { sc.ChangeState(SCE_GD_STRINGEOL); sc.ForwardSetState(SCE_GD_DEFAULT); } } } void SCI_METHOD LexerGDScript::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) { Accessor styler(pAccess, nullptr); const Sci_Position endPos = startPos + length; // Backtrack to previous line in case need to fix its tab whinging Sci_Position lineCurrent = styler.GetLine(startPos); if (startPos > 0) { if (lineCurrent > 0) { lineCurrent--; // Look for backslash-continued lines while (lineCurrent > 0) { const Sci_Position eolPos = styler.LineStart(lineCurrent) - 1; const int eolStyle = styler.StyleAt(eolPos); if (eolStyle == SCE_GD_STRING || eolStyle == SCE_GD_CHARACTER || eolStyle == SCE_GD_STRINGEOL) { lineCurrent -= 1; } else { break; } } startPos = styler.LineStart(lineCurrent); } initStyle = startPos == 0 ? SCE_GD_DEFAULT : styler.StyleAt(startPos - 1); } initStyle = initStyle & 31; if (initStyle == SCE_GD_STRINGEOL) { initStyle = SCE_GD_DEFAULT; } kwType kwLast = kwOther; int spaceFlags = 0; styler.IndentAmount(lineCurrent, &spaceFlags, IsGDComment); bool base_n_number = false; const WordClassifier &classifierIdentifiers = subStyles.Classifier(SCE_GD_IDENTIFIER); StyleContext sc(startPos, endPos - startPos, initStyle, styler); bool indentGood = true; Sci_Position startIndicator = sc.currentPos; bool inContinuedString = false; bool percentIsNodePath = false; int nodePathStringState = SCE_GD_DEFAULT; for (; sc.More(); sc.Forward()) { if (sc.atLineStart) { styler.IndentAmount(lineCurrent, &spaceFlags, IsGDComment); indentGood = true; if (options.whingeLevel == 1) { indentGood = (spaceFlags & wsInconsistent) == 0; } else if (options.whingeLevel == 2) { indentGood = (spaceFlags & wsSpaceTab) == 0; } else if (options.whingeLevel == 3) { indentGood = (spaceFlags & wsSpace) == 0; } else if (options.whingeLevel == 4) { indentGood = (spaceFlags & wsTab) == 0; } if (!indentGood) { styler.IndicatorFill(startIndicator, sc.currentPos, indicatorWhitespace, 0); startIndicator = sc.currentPos; } } if (sc.atLineEnd) { percentIsNodePath = false; ProcessLineEnd(sc, inContinuedString); lineCurrent++; if (!sc.More()) break; } bool needEOLCheck = false; if (sc.state == SCE_GD_OPERATOR) { kwLast = kwOther; sc.SetState(SCE_GD_DEFAULT); } else if (sc.state == SCE_GD_NUMBER) { if (!IsAWordChar(sc.ch, false) && !(!base_n_number && ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E')))) { sc.SetState(SCE_GD_DEFAULT); } } else if (sc.state == SCE_GD_IDENTIFIER) { if ((sc.ch == '.') || (!IsAWordChar(sc.ch, options.unicodeIdentifiers))) { char s[100]; sc.GetCurrent(s, sizeof(s)); int style = SCE_GD_IDENTIFIER; if (keywords.InList(s)) { style = SCE_GD_WORD; } else if (kwLast == kwClass) { style = SCE_GD_CLASSNAME; } else if (kwLast == kwDef) { style = SCE_GD_FUNCNAME; } else if (keywords2.InList(s)) { if (options.keywords2NoSubIdentifiers) { // We don't want to highlight keywords2 // that are used as a sub-identifier, // i.e. not open in "foo.open". const Sci_Position pos = styler.GetStartSegment() - 1; if (pos < 0 || (styler.SafeGetCharAt(pos, '\0') != '.')) style = SCE_GD_WORD2; } else { style = SCE_GD_WORD2; } } else { const int subStyle = classifierIdentifiers.ValueFor(s); if (subStyle >= 0) { style = subStyle; } } sc.ChangeState(style); sc.SetState(SCE_GD_DEFAULT); if (style == SCE_GD_WORD) { if (0 == strcmp(s, "class")) kwLast = kwClass; else if (0 == strcmp(s, "func")) kwLast = kwDef; else if (0 == strcmp(s, "extends")) kwLast = kwExtends; else kwLast = kwOther; } else { kwLast = kwOther; } } } else if ((sc.state == SCE_GD_COMMENTLINE) || (sc.state == SCE_GD_COMMENTBLOCK)) { if (sc.ch == '\r' || sc.ch == '\n') { sc.SetState(SCE_GD_DEFAULT); } } else if (sc.state == SCE_GD_ANNOTATION) { if (!IsAWordStart(sc.ch, options.unicodeIdentifiers)) { sc.SetState(SCE_GD_DEFAULT); } } else if (sc.state == SCE_GD_NODEPATH) { if (nodePathStringState != SCE_GD_DEFAULT) { if (sc.ch == GetGDStringQuoteChar(nodePathStringState) ) { nodePathStringState = SCE_GD_DEFAULT; } } else { if (IsGDStringStart(sc.ch)) { nodePathStringState = GetGDStringState(sc.ch); } else if (!IsANodePathChar(sc.ch, options.unicodeIdentifiers)) { sc.SetState(SCE_GD_DEFAULT); } } } else if (IsGDSingleQuoteStringState(sc.state)) { if (sc.ch == '\\') { if ((sc.chNext == '\r') && (sc.GetRelative(2) == '\n')) { sc.Forward(); } if (sc.chNext == '\n' || sc.chNext == '\r') { inContinuedString = true; } else { // Don't roll over the newline. sc.Forward(); } } else if (sc.ch == GetGDStringQuoteChar(sc.state)) { sc.ForwardSetState(SCE_GD_DEFAULT); needEOLCheck = true; } } else if (sc.state == SCE_GD_TRIPLE) { if (sc.ch == '\\') { sc.Forward(); } else if (sc.Match(R"(''')")) { sc.Forward(); sc.Forward(); sc.ForwardSetState(SCE_GD_DEFAULT); needEOLCheck = true; } } else if (sc.state == SCE_GD_TRIPLEDOUBLE) { if (sc.ch == '\\') { sc.Forward(); } else if (sc.Match(R"(""")")) { sc.Forward(); sc.Forward(); sc.ForwardSetState(SCE_GD_DEFAULT); needEOLCheck = true; } } if (!indentGood && !IsASpaceOrTab(sc.ch)) { styler.IndicatorFill(startIndicator, sc.currentPos, indicatorWhitespace, 1); startIndicator = sc.currentPos; indentGood = true; } // State exit code may have moved on to end of line if (needEOLCheck && sc.atLineEnd) { ProcessLineEnd(sc, inContinuedString); lineCurrent++; styler.IndentAmount(lineCurrent, &spaceFlags, IsGDComment); if (!sc.More()) break; } // Check for a new state starting character if (sc.state == SCE_GD_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { if (sc.ch == '0' && (sc.chNext == 'x' || sc.chNext == 'X')) { base_n_number = true; sc.SetState(SCE_GD_NUMBER); } else if (sc.ch == '0' && (sc.chNext == 'o' || sc.chNext == 'O' || sc.chNext == 'b' || sc.chNext == 'B')) { if (options.base2or8Literals) { base_n_number = true; sc.SetState(SCE_GD_NUMBER); } else { sc.SetState(SCE_GD_NUMBER); sc.ForwardSetState(SCE_GD_IDENTIFIER); } } else { base_n_number = false; sc.SetState(SCE_GD_NUMBER); } } else if ((sc.ch == '$') || (sc.ch == '%' && (percentIsNodePath || IsFirstNonWhitespace(sc.currentPos, styler)))) { percentIsNodePath = false; sc.SetState(SCE_GD_NODEPATH); } else if (isoperator(sc.ch) || sc.ch == '`') { percentIsNodePath = !((sc.ch == ')') || (sc.ch == ']') || (sc.ch == '}')); sc.SetState(SCE_GD_OPERATOR); } else if (sc.ch == '#') { sc.SetState(sc.chNext == '#' ? SCE_GD_COMMENTBLOCK : SCE_GD_COMMENTLINE); } else if (sc.ch == '@') { if (IsFirstNonWhitespace(sc.currentPos, styler)) sc.SetState(SCE_GD_ANNOTATION); else sc.SetState(SCE_GD_OPERATOR); } else if (IsGDStringStart(sc.ch)) { Sci_PositionU nextIndex = 0; sc.SetState(GetGDStringState(styler, sc.currentPos, &nextIndex)); while (nextIndex > (sc.currentPos + 1) && sc.More()) { sc.Forward(); } } else if (IsAWordStart(sc.ch, options.unicodeIdentifiers)) { sc.SetState(SCE_GD_IDENTIFIER); } } } styler.IndicatorFill(startIndicator, sc.currentPos, indicatorWhitespace, 0); sc.Complete(); } static bool IsCommentLine(Sci_Position line, Accessor &styler) { const Sci_Position pos = styler.LineStart(line); const Sci_Position eol_pos = styler.LineStart(line + 1) - 1; for (Sci_Position i = pos; i < eol_pos; i++) { const char ch = styler[i]; if (ch == '#') return true; else if (ch != ' ' && ch != '\t') return false; } return false; } static bool IsQuoteLine(Sci_Position line, const Accessor &styler) { const int style = styler.StyleAt(styler.LineStart(line)) & 31; return IsGDTripleQuoteStringState(style); } void SCI_METHOD LexerGDScript::Fold(Sci_PositionU startPos, Sci_Position length, int /*initStyle - unused*/, IDocument *pAccess) { if (!options.fold) return; Accessor styler(pAccess, nullptr); const Sci_Position maxPos = startPos + length; const Sci_Position maxLines = (maxPos == styler.Length()) ? styler.GetLine(maxPos) : styler.GetLine(maxPos - 1); // Requested last line const Sci_Position docLines = styler.GetLine(styler.Length()); // Available last line // Backtrack to previous non-blank line so we can determine indent level // for any white space lines (needed esp. within triple quoted strings) // and so we can fix any preceding fold level (which is why we go back // at least one line in all cases) int spaceFlags = 0; Sci_Position lineCurrent = styler.GetLine(startPos); int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, nullptr); while (lineCurrent > 0) { lineCurrent--; indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, nullptr); if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG) && (!IsCommentLine(lineCurrent, styler)) && (!IsQuoteLine(lineCurrent, styler))) break; } int indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK; // Set up initial loop state startPos = styler.LineStart(lineCurrent); int prev_state = SCE_GD_DEFAULT & 31; if (lineCurrent >= 1) prev_state = styler.StyleAt(startPos - 1) & 31; int prevQuote = options.foldQuotes && IsGDTripleQuoteStringState(prev_state); // Process all characters to end of requested range or end of any triple quote //that hangs over the end of the range. Cap processing in all cases // to end of document (in case of unclosed quote at end). while ((lineCurrent <= docLines) && ((lineCurrent <= maxLines) || prevQuote)) { // Gather info int lev = indentCurrent; Sci_Position lineNext = lineCurrent + 1; int indentNext = indentCurrent; int quote = false; if (lineNext <= docLines) { // Information about next line is only available if not at end of document indentNext = styler.IndentAmount(lineNext, &spaceFlags, nullptr); const Sci_Position lookAtPos = (styler.LineStart(lineNext) == styler.Length()) ? styler.Length() - 1 : styler.LineStart(lineNext); const int style = styler.StyleAt(lookAtPos) & 31; quote = options.foldQuotes && IsGDTripleQuoteStringState(style); } const bool quote_start = (quote && !prevQuote); const bool quote_continue = (quote && prevQuote); if (!quote || !prevQuote) indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK; if (quote) indentNext = indentCurrentLevel; if (indentNext & SC_FOLDLEVELWHITEFLAG) indentNext = SC_FOLDLEVELWHITEFLAG | indentCurrentLevel; if (quote_start) { // Place fold point at start of triple quoted string lev |= SC_FOLDLEVELHEADERFLAG; } else if (quote_continue || prevQuote) { // Add level to rest of lines in the string lev = lev + 1; } // Skip past any blank lines for next indent level info; we skip also // comments (all comments, not just those starting in column 0) // which effectively folds them into surrounding code rather // than screwing up folding. If comments end file, use the min // comment indent as the level after int minCommentLevel = indentCurrentLevel; while (!quote && (lineNext < docLines) && ((indentNext & SC_FOLDLEVELWHITEFLAG) || (IsCommentLine(lineNext, styler)))) { if (IsCommentLine(lineNext, styler) && indentNext < minCommentLevel) { minCommentLevel = indentNext; } lineNext++; indentNext = styler.IndentAmount(lineNext, &spaceFlags, nullptr); } const int levelAfterComments = ((lineNext < docLines) ? indentNext & SC_FOLDLEVELNUMBERMASK : minCommentLevel); const int levelBeforeComments = std::max(indentCurrentLevel, levelAfterComments); // Now set all the indent levels on the lines we skipped // Do this from end to start. Once we encounter one line // which is indented more than the line after the end of // the comment-block, use the level of the block before Sci_Position skipLine = lineNext; int skipLevel = levelAfterComments; while (--skipLine > lineCurrent) { const int skipLineIndent = styler.IndentAmount(skipLine, &spaceFlags, nullptr); if (options.foldCompact) { if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments) skipLevel = levelBeforeComments; const int whiteFlag = skipLineIndent & SC_FOLDLEVELWHITEFLAG; styler.SetLevel(skipLine, skipLevel | whiteFlag); } else { if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments && !(skipLineIndent & SC_FOLDLEVELWHITEFLAG) && !IsCommentLine(skipLine, styler)) skipLevel = levelBeforeComments; styler.SetLevel(skipLine, skipLevel); } } // Set fold header on non-quote line if (!quote && !(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) lev |= SC_FOLDLEVELHEADERFLAG; } // Keep track of triple quote state of previous line prevQuote = quote; // Set fold level for this line and move to next line styler.SetLevel(lineCurrent, options.foldCompact ? lev : lev & ~SC_FOLDLEVELWHITEFLAG); indentCurrent = indentNext; lineCurrent = lineNext; } // NOTE: Cannot set level of last line here because indentCurrent doesn't have // header flag set; the loop above is crafted to take care of this case! //styler.SetLevel(lineCurrent, indentCurrent); } extern const LexerModule lmGDScript(SCLEX_GDSCRIPT, LexerGDScript::LexerFactoryGDScript, "gdscript", gdscriptWordListDesc);
24,506
C++
.cxx
672
33.032738
136
0.701597
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,522
LexDart.cxx
dail8859_NotepadNext/src/lexilla/lexers/LexDart.cxx
// Scintilla source code edit control /** @file LexDart.cxx ** Lexer for Dart. **/ // Based on Zufu Liu's Notepad4 Dart lexer // Modified for Scintilla by Jiri Techet, 2024 // The License.txt file describes the conditions under which this software may be distributed. #include <cassert> #include <cstring> #include <string> #include <string_view> #include <vector> #include <map> #include <algorithm> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" #include "OptionSet.h" #include "DefaultLexer.h" using namespace Scintilla; using namespace Lexilla; namespace { // Use an unnamed namespace to protect the functions and classes from name conflicts constexpr bool IsEOLChar(int ch) noexcept { return ch == '\r' || ch == '\n'; } constexpr bool IsAGraphic(int ch) noexcept { // excludes C0 control characters and whitespace return ch > 32 && ch < 127; } constexpr bool IsIdentifierChar(int ch) noexcept { return IsAlphaNumeric(ch) || ch == '_'; } constexpr bool IsIdentifierStart(int ch) noexcept { return IsUpperOrLowerCase(ch) || ch == '_'; } constexpr bool IsNumberContinue(int chPrev, int ch, int chNext) noexcept { return ((ch == '+' || ch == '-') && (chPrev == 'e' || chPrev == 'E')) || (ch == '.' && chNext != '.'); } constexpr bool IsNumberStart(int ch, int chNext) noexcept { return IsADigit(ch) || (ch == '.' && IsADigit(chNext)); } constexpr bool IsDecimalNumber(int chPrev, int ch, int chNext) noexcept { return IsIdentifierChar(ch) || IsNumberContinue(chPrev, ch, chNext); } struct EscapeSequence { int outerState = SCE_DART_DEFAULT; int digitsLeft = 0; bool brace = false; // highlight any character as escape sequence. bool resetEscapeState(int state, int chNext) noexcept { if (IsEOLChar(chNext)) { return false; } outerState = state; brace = false; digitsLeft = (chNext == 'x')? 3 : ((chNext == 'u') ? 5 : 1); return true; } bool atEscapeEnd(int ch) noexcept { --digitsLeft; return digitsLeft <= 0 || !IsAHeXDigit(ch); } }; constexpr bool IsDartIdentifierStart(int ch) noexcept { return IsIdentifierStart(ch) || ch == '$'; } constexpr bool IsDartIdentifierChar(int ch) noexcept { return IsIdentifierChar(ch) || ch == '$'; } constexpr bool IsDefinableOperator(int ch) noexcept { // https://github.com/dart-lang/sdk/blob/main/sdk/lib/core/symbol.dart return AnyOf(ch, '+', '-', '*', '/', '%', '~', '&', '|', '^', '<', '>', '=', '[', ']'); } constexpr bool IsSpaceEquiv(int state) noexcept { return state == SCE_DART_DEFAULT || state == SCE_DART_COMMENTLINE || state == SCE_DART_COMMENTLINEDOC || state == SCE_DART_COMMENTBLOCK || state == SCE_DART_COMMENTBLOCKDOC; } constexpr bool IsTripleString(int state) noexcept { return state == SCE_DART_TRIPLE_STRING_SQ || state == SCE_DART_TRIPLE_STRING_DQ || state == SCE_DART_TRIPLE_RAWSTRING_SQ || state == SCE_DART_TRIPLE_RAWSTRING_DQ; } constexpr bool IsDoubleQuoted(int state) noexcept { return state == SCE_DART_STRING_DQ || state == SCE_DART_RAWSTRING_DQ || state == SCE_DART_TRIPLE_STRING_DQ || state == SCE_DART_TRIPLE_RAWSTRING_DQ; } constexpr bool IsRaw(int state) noexcept { return state == SCE_DART_RAWSTRING_SQ || state == SCE_DART_RAWSTRING_DQ || state == SCE_DART_TRIPLE_RAWSTRING_SQ || state == SCE_DART_TRIPLE_RAWSTRING_DQ; } constexpr int GetStringQuote(int state) noexcept { return IsDoubleQuoted(state) ? '\"' : '\''; } enum { DartLineStateMaskLineComment = 1, // line comment DartLineStateMaskImport = (1 << 1), // import DartLineStateMaskInterpolation = (1 << 2), // string interpolation }; // string interpolating state struct InterpolatingState { int state; int braceCount; }; struct FoldLineState { int lineComment; int packageImport; constexpr explicit FoldLineState(int lineState) noexcept: lineComment(lineState & DartLineStateMaskLineComment), packageImport((lineState >> 1) & 1) { } }; // Options used for LexerDart struct OptionsDart { bool fold = false; }; const char * const dartWordListDesc[] = { "Primary keywords", "Secondary keywords", "Tertiary keywords", "Global type definitions", nullptr }; struct OptionSetDart : public OptionSet<OptionsDart> { OptionSetDart() { DefineProperty("fold", &OptionsDart::fold); DefineWordListSets(dartWordListDesc); } }; LexicalClass lexicalClasses[] = { // Lexer DART SCLEX_DART SCE_DART_: 0, "SCE_DART_DEFAULT", "default", "White space", 1, "SCE_DART_COMMENTLINE", "comment line", "Comment: //", 2, "SCE_DART_COMMENTLINEDOC", "comment line documentation", "Comment: ///", 3, "SCE_DART_COMMENTBLOCK", "comment", "Comment: /* */", 4, "SCE_DART_COMMENTBLOCKDOC", "comment documentation", "Comment: /** */", 5, "SCE_DART_STRING_SQ", "literal string", "Single quoted string", 6, "SCE_DART_STRING_DQ", "literal string", "Double quoted string", 7, "SCE_DART_TRIPLE_STRING_SQ", "literal string multiline", "Single quoted multiline string", 8, "SCE_DART_TRIPLE_STRING_DQ", "literal string multiline", "Double quoted multiline string", 9, "SCE_DART_RAWSTRING_SQ", "literal string raw", "Single quoted raw string", 10, "SCE_DART_RAWSTRING_DQ", "literal string raw", "Double quoted raw string", 11, "SCE_DART_TRIPLE_RAWSTRING_SQ", "literal string multiline raw", "Single quoted multiline raw string", 12, "SCE_DART_TRIPLE_RAWSTRING_DQ", "literal string multiline raw", "Double quoted multiline raw string", 13, "SCE_DART_ESCAPECHAR", "literal string escapesequence", "Escape sequence", 14, "SCE_DART_IDENTIFIER", "identifier", "Identifier", 15, "SCE_DART_IDENTIFIER_STRING", "identifier interpolated", "Identifier following $ inside strings", 16, "SCE_DART_OPERATOR", "operator", "Operator", 17, "SCE_DART_OPERATOR_STRING", "operator interpolated", "Braces following $ inside string", 18, "SCE_DART_SYMBOL_IDENTIFIER", "identifier symbol", "Symbol name introduced by #", 19, "SCE_DART_SYMBOL_OPERATOR", "operator symbol", "Operator introduced by #", 20, "SCE_DART_NUMBER", "literal numeric", "Number", 21, "SCE_DART_KEY", "key", "Keys preceding ':' and named parameters", 22, "SCE_DART_METADATA", "preprocessor", "Metadata introduced by @", 23, "SCE_DART_KW_PRIMARY", "keyword", "Primary keywords", 24, "SCE_DART_KW_SECONDARY", "identifier", "Secondary keywords", 25, "SCE_DART_KW_TERTIARY", "identifier", "Tertiary keywords", 26, "SCE_DART_KW_TYPE", "identifier", "Global types", }; class LexerDart : public DefaultLexer { WordList keywordsPrimary; WordList keywordsSecondary; WordList keywordsTertiary; WordList keywordsTypes; OptionsDart options; OptionSetDart osDart; public: LexerDart(const char *languageName_, int language_) : DefaultLexer(languageName_, language_, lexicalClasses, std::size(lexicalClasses)) { } // Deleted so LexerDart objects can not be copied. LexerDart(const LexerDart &) = delete; LexerDart(LexerDart &&) = delete; void operator=(const LexerDart &) = delete; void operator=(LexerDart &&) = delete; ~LexerDart() override = default; void SCI_METHOD Release() override { delete this; } int SCI_METHOD Version() const override { return lvRelease5; } const char *SCI_METHOD PropertyNames() override { return osDart.PropertyNames(); } int SCI_METHOD PropertyType(const char *name) override { return osDart.PropertyType(name); } const char *SCI_METHOD DescribeProperty(const char *name) override { return osDart.DescribeProperty(name); } Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override; const char *SCI_METHOD PropertyGet(const char *key) override { return osDart.PropertyGet(key); } const char *SCI_METHOD DescribeWordListSets() override { return osDart.DescribeWordListSets(); } Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override; void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void *SCI_METHOD PrivateCall(int, void *) override { return nullptr; } void BacktrackToStart(const LexAccessor &styler, int stateMask, Sci_PositionU &startPos, Sci_Position &lengthDoc, int &initStyle); Sci_PositionU LookbackNonWhite(LexAccessor &styler, Sci_PositionU startPos, int &chPrevNonWhite, int &stylePrevNonWhite); static ILexer5 *LexerFactoryDart() { return new LexerDart("dart", SCLEX_DART); } }; Sci_Position SCI_METHOD LexerDart::PropertySet(const char *key, const char *val) { if (osDart.PropertySet(&options, key, val)) { return 0; } return -1; } Sci_Position SCI_METHOD LexerDart::WordListSet(int n, const char *wl) { WordList *wordListN = nullptr; switch (n) { case 0: wordListN = &keywordsPrimary; break; case 1: wordListN = &keywordsSecondary; break; case 2: wordListN = &keywordsTertiary; break; case 3: wordListN = &keywordsTypes; break; default: break; } Sci_Position firstModification = -1; if (wordListN && wordListN->Set(wl, false)) { firstModification = 0; } return firstModification; } void LexerDart::BacktrackToStart(const LexAccessor &styler, int stateMask, Sci_PositionU &startPos, Sci_Position &lengthDoc, int &initStyle) { const Sci_Position currentLine = styler.GetLine(startPos); if (currentLine != 0) { Sci_Position line = currentLine - 1; int lineState = styler.GetLineState(line); while ((lineState & stateMask) != 0 && line != 0) { --line; lineState = styler.GetLineState(line); } if ((lineState & stateMask) == 0) { ++line; } if (line != currentLine) { const Sci_PositionU endPos = startPos + lengthDoc; startPos = (line == 0) ? 0 : styler.LineStart(line); lengthDoc = endPos - startPos; initStyle = (startPos == 0) ? 0 : styler.StyleAt(startPos - 1); } } } Sci_PositionU LexerDart::LookbackNonWhite(LexAccessor &styler, Sci_PositionU startPos, int &chPrevNonWhite, int &stylePrevNonWhite) { do { --startPos; const unsigned style = styler.StyleAt(startPos); if (!IsSpaceEquiv(style)) { stylePrevNonWhite = style; chPrevNonWhite = static_cast<unsigned char>(styler[startPos]); break; } } while (startPos != 0); return startPos; } void LexerDart::Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument *pAccess) { Accessor styler(pAccess, nullptr); int lineStateLineType = 0; int commentLevel = 0; // nested block comment level std::vector<InterpolatingState> interpolatingStack; int visibleChars = 0; int chBefore = 0; int chPrevNonWhite = 0; EscapeSequence escSeq; if (startPos != 0) { // backtrack to the line where interpolation starts BacktrackToStart(styler, DartLineStateMaskInterpolation, startPos, lengthDoc, initStyle); } StyleContext sc(startPos, lengthDoc, initStyle, styler); if (sc.currentLine > 0) { const int lineState = styler.GetLineState(sc.currentLine - 1); commentLevel = lineState >> 4; } if (startPos == 0) { if (sc.Match('#', '!')) { // Shell Shebang at beginning of file sc.SetState(SCE_DART_COMMENTLINE); sc.Forward(); lineStateLineType = DartLineStateMaskLineComment; } } else if (IsSpaceEquiv(initStyle)) { LookbackNonWhite(styler, startPos, chPrevNonWhite, initStyle); chBefore = chPrevNonWhite; } while (sc.More()) { switch (sc.state) { case SCE_DART_OPERATOR: case SCE_DART_OPERATOR_STRING: sc.SetState(SCE_DART_DEFAULT); break; case SCE_DART_NUMBER: if (!IsDecimalNumber(sc.chPrev, sc.ch, sc.chNext)) { sc.SetState(SCE_DART_DEFAULT); } break; case SCE_DART_IDENTIFIER: case SCE_DART_IDENTIFIER_STRING: case SCE_DART_METADATA: case SCE_DART_SYMBOL_IDENTIFIER: if (!IsDartIdentifierChar(sc.ch) || (sc.ch == '$' && sc.state == SCE_DART_IDENTIFIER_STRING)) { if (sc.state == SCE_DART_METADATA || sc.state == SCE_DART_SYMBOL_IDENTIFIER) { if (sc.ch == '.') { const int state = sc.state; sc.SetState(SCE_DART_OPERATOR); sc.ForwardSetState(state); continue; } } else { char s[64]; sc.GetCurrent(s, sizeof(s)); const int state = sc.state; if (state == SCE_DART_IDENTIFIER_STRING) { sc.SetState(escSeq.outerState); continue; } else if (keywordsPrimary.InList(s)) { sc.ChangeState(SCE_DART_KW_PRIMARY); if (strcmp(s, "import") == 0 || strcmp(s, "part") == 0) { if (visibleChars == sc.LengthCurrent()) { lineStateLineType = DartLineStateMaskImport; } } } else if (keywordsSecondary.InList(s)) { sc.ChangeState(SCE_DART_KW_SECONDARY); } else if (keywordsTertiary.InList(s)) { sc.ChangeState(SCE_DART_KW_TERTIARY); } else if (keywordsTypes.InList(s)) { sc.ChangeState(SCE_DART_KW_TYPE); } else if (state == SCE_DART_IDENTIFIER && sc.ch == ':') { if (chBefore == ',' || chBefore == '{' || chBefore == '(') { sc.ChangeState(SCE_DART_KEY); // map key or named parameter } } } sc.SetState(SCE_DART_DEFAULT); } break; case SCE_DART_SYMBOL_OPERATOR: if (!IsDefinableOperator(sc.ch)) { sc.SetState(SCE_DART_DEFAULT); } break; case SCE_DART_COMMENTLINE: case SCE_DART_COMMENTLINEDOC: if (sc.atLineStart) { sc.SetState(SCE_DART_DEFAULT); } break; case SCE_DART_COMMENTBLOCK: case SCE_DART_COMMENTBLOCKDOC: if (sc.Match('*', '/')) { sc.Forward(); --commentLevel; if (commentLevel == 0) { sc.ForwardSetState(SCE_DART_DEFAULT); } } else if (sc.Match('/', '*')) { sc.Forward(); ++commentLevel; } break; case SCE_DART_STRING_SQ: case SCE_DART_STRING_DQ: case SCE_DART_TRIPLE_STRING_SQ: case SCE_DART_TRIPLE_STRING_DQ: case SCE_DART_RAWSTRING_SQ: case SCE_DART_RAWSTRING_DQ: case SCE_DART_TRIPLE_RAWSTRING_SQ: case SCE_DART_TRIPLE_RAWSTRING_DQ: if (sc.atLineStart && !IsTripleString(sc.state)) { sc.SetState(SCE_DART_DEFAULT); } else if (sc.ch == '\\' && !IsRaw(sc.state)) { if (escSeq.resetEscapeState(sc.state, sc.chNext)) { sc.SetState(SCE_DART_ESCAPECHAR); sc.Forward(); if (sc.Match('u', '{')) { escSeq.brace = true; escSeq.digitsLeft = 7; // Unicode code point sc.Forward(); } } } else if (sc.ch == '$' && !IsRaw(sc.state)) { escSeq.outerState = sc.state; sc.SetState(SCE_DART_OPERATOR_STRING); sc.Forward(); if (sc.ch == '{') { interpolatingStack.push_back({escSeq.outerState, 1}); } else if (sc.ch != '$' && IsDartIdentifierStart(sc.ch)) { sc.SetState(SCE_DART_IDENTIFIER_STRING); } else { // error sc.SetState(escSeq.outerState); continue; } } else if (sc.ch == GetStringQuote(sc.state) && (!IsTripleString(sc.state) || (sc.Match(IsDoubleQuoted(sc.state) ? R"(""")" : R"(''')")))) { if (IsTripleString(sc.state)) { sc.Forward(2); } sc.Forward(); sc.SetState(SCE_DART_DEFAULT); } break; case SCE_DART_ESCAPECHAR: if (escSeq.atEscapeEnd(sc.ch)) { if (escSeq.brace && sc.ch == '}') { sc.Forward(); } sc.SetState(escSeq.outerState); continue; } break; } if (sc.state == SCE_DART_DEFAULT) { if (sc.ch == '/' && (sc.chNext == '/' || sc.chNext == '*')) { const int chNext = sc.chNext; sc.SetState((chNext == '/') ? SCE_DART_COMMENTLINE : SCE_DART_COMMENTBLOCK); sc.Forward(2); if (sc.ch == chNext && sc.chNext != chNext) { if (sc.state == SCE_DART_COMMENTLINE) { sc.ChangeState(SCE_DART_COMMENTLINEDOC); } else { sc.ChangeState(SCE_DART_COMMENTBLOCKDOC); } } if (chNext == '/') { if (visibleChars == 0) { lineStateLineType = DartLineStateMaskLineComment; } } else { commentLevel = 1; } continue; } if (sc.ch == 'r' && (sc.chNext == '\'' || sc.chNext == '"')) { sc.SetState((sc.chNext == '\'') ? SCE_DART_RAWSTRING_SQ : SCE_DART_RAWSTRING_DQ); sc.Forward(2); if (sc.chPrev == '\'' && sc.Match('\'', '\'')) { sc.ChangeState(SCE_DART_TRIPLE_RAWSTRING_SQ); sc.Forward(2); } else if (sc.chPrev == '"' && sc.Match('"', '"')) { sc.ChangeState(SCE_DART_TRIPLE_RAWSTRING_DQ); sc.Forward(2); } continue; } if (sc.ch == '"') { if (sc.Match(R"(""")")) { sc.SetState(SCE_DART_TRIPLE_STRING_DQ); sc.Forward(2); } else { chBefore = chPrevNonWhite; sc.SetState(SCE_DART_STRING_DQ); } } else if (sc.ch == '\'') { if (sc.Match(R"(''')")) { sc.SetState(SCE_DART_TRIPLE_STRING_SQ); sc.Forward(2); } else { chBefore = chPrevNonWhite; sc.SetState(SCE_DART_STRING_SQ); } } else if (IsNumberStart(sc.ch, sc.chNext)) { sc.SetState(SCE_DART_NUMBER); } else if ((sc.ch == '@' || sc.ch == '#') && IsDartIdentifierStart(sc.chNext)) { sc.SetState((sc.ch == '@') ? SCE_DART_METADATA : SCE_DART_SYMBOL_IDENTIFIER); } else if (IsDartIdentifierStart(sc.ch)) { chBefore = chPrevNonWhite; sc.SetState(SCE_DART_IDENTIFIER); } else if (sc.ch == '#' && IsDefinableOperator(sc.chNext)) { sc.SetState(SCE_DART_SYMBOL_OPERATOR); } else if (IsAGraphic(sc.ch)) { sc.SetState(SCE_DART_OPERATOR); if (!interpolatingStack.empty() && AnyOf(sc.ch, '{', '}')) { InterpolatingState &current = interpolatingStack.back(); if (sc.ch == '{') { current.braceCount += 1; } else { current.braceCount -= 1; if (current.braceCount == 0) { sc.ChangeState(SCE_DART_OPERATOR_STRING); sc.ForwardSetState(current.state); interpolatingStack.pop_back(); continue; } } } } } if (!isspacechar(sc.ch)) { visibleChars++; if (!IsSpaceEquiv(sc.state)) { chPrevNonWhite = sc.ch; } } if (sc.atLineEnd) { int lineState = (commentLevel << 4) | lineStateLineType; if (!interpolatingStack.empty()) { lineState |= DartLineStateMaskInterpolation; } styler.SetLineState(sc.currentLine, lineState); lineStateLineType = 0; visibleChars = 0; } sc.Forward(); } sc.Complete(); } void LexerDart::Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument *pAccess) { if (!options.fold) return; Accessor styler(pAccess, nullptr); const Sci_PositionU endPos = startPos + lengthDoc; Sci_Position lineCurrent = styler.GetLine(startPos); while (lineCurrent > 0) { lineCurrent--; startPos = styler.LineStart(lineCurrent); initStyle = (startPos > 0) ? styler.StyleIndexAt(startPos) : 0; if (initStyle != SCE_DART_COMMENTBLOCKDOC && initStyle != SCE_DART_COMMENTBLOCK && initStyle != SCE_DART_TRIPLE_RAWSTRING_SQ && initStyle != SCE_DART_TRIPLE_RAWSTRING_DQ && initStyle != SCE_DART_TRIPLE_STRING_SQ && initStyle != SCE_DART_TRIPLE_STRING_DQ) break; } FoldLineState foldPrev(0); int levelCurrent = SC_FOLDLEVELBASE; if (lineCurrent > 0) { levelCurrent = styler.LevelAt(lineCurrent - 1) >> 16; foldPrev = FoldLineState(styler.GetLineState(lineCurrent - 1)); } int levelNext = levelCurrent; FoldLineState foldCurrent(styler.GetLineState(lineCurrent)); Sci_PositionU lineStartNext = styler.LineStart(lineCurrent + 1); lineStartNext = std::min(lineStartNext, endPos); char chNext = styler[startPos]; int styleNext = styler.StyleIndexAt(startPos); int style = initStyle; while (startPos < endPos) { const char ch = chNext; const int stylePrev = style; style = styleNext; chNext = styler[++startPos]; styleNext = styler.StyleIndexAt(startPos); switch (style) { case SCE_DART_COMMENTBLOCKDOC: case SCE_DART_COMMENTBLOCK: { const int level = (ch == '/' && chNext == '*') ? 1 : ((ch == '*' && chNext == '/') ? -1 : 0); if (level != 0) { levelNext += level; startPos++; chNext = styler[startPos]; styleNext = styler.StyleIndexAt(startPos); } } break; case SCE_DART_TRIPLE_RAWSTRING_SQ: case SCE_DART_TRIPLE_RAWSTRING_DQ: case SCE_DART_TRIPLE_STRING_SQ: case SCE_DART_TRIPLE_STRING_DQ: if (style != stylePrev && !AnyOf(stylePrev, SCE_DART_ESCAPECHAR, SCE_DART_OPERATOR_STRING, SCE_DART_IDENTIFIER_STRING)) { levelNext++; } if (style != styleNext && !AnyOf(styleNext, SCE_DART_ESCAPECHAR, SCE_DART_OPERATOR_STRING, SCE_DART_IDENTIFIER_STRING)) { levelNext--; } break; case SCE_DART_OPERATOR: case SCE_DART_OPERATOR_STRING: if (ch == '{' || ch == '[' || ch == '(') { levelNext++; } else if (ch == '}' || ch == ']' || ch == ')') { levelNext--; } break; } if (startPos == lineStartNext) { const FoldLineState foldNext(styler.GetLineState(lineCurrent + 1)); levelNext = std::max(levelNext, SC_FOLDLEVELBASE); if (foldCurrent.lineComment) { levelNext += foldNext.lineComment - foldPrev.lineComment; } else if (foldCurrent.packageImport) { levelNext += foldNext.packageImport - foldPrev.packageImport; } const int levelUse = levelCurrent; int lev = levelUse | (levelNext << 16); if (levelUse < levelNext) { lev |= SC_FOLDLEVELHEADERFLAG; } styler.SetLevel(lineCurrent, lev); lineCurrent++; lineStartNext = styler.LineStart(lineCurrent + 1); lineStartNext = std::min(lineStartNext, endPos); levelCurrent = levelNext; foldPrev = foldCurrent; foldCurrent = foldNext; } } } } // unnamed namespace end extern const LexerModule lmDart(SCLEX_DART, LexerDart::LexerFactoryDart, "dart", dartWordListDesc);
21,476
C++
.cxx
629
30.758347
142
0.687638
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,526
LexillaAccess.cxx
dail8859_NotepadNext/src/lexilla/access/LexillaAccess.cxx
// SciTE - Scintilla based Text Editor /** @file LexillaAccess.cxx ** Interface to loadable lexers. ** Maintains a list of lexer library paths and CreateLexer functions. ** If list changes then load all the lexer libraries and find the functions. ** When asked to create a lexer, call each function until one succeeds. **/ // Copyright 2019 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cstring> #include <string> #include <string_view> #include <vector> #include <set> #if !defined(_WIN32) #include <dlfcn.h> #else #include <windows.h> #endif #include "ILexer.h" #include "Lexilla.h" #include "LexillaAccess.h" namespace { #if defined(_WIN32) typedef FARPROC Function; typedef HMODULE Module; constexpr const char *pathSeparator = "\\"; #else typedef void *Function; typedef void *Module; constexpr const char *pathSeparator = "/"; #endif /// Generic function to convert from a Function(void* or FARPROC) to a function pointer. /// This avoids undefined and conditionally defined behaviour. template<typename T> T FunctionPointer(Function function) noexcept { static_assert(sizeof(T) == sizeof(function)); T fp {}; memcpy(&fp, &function, sizeof(T)); return fp; } #if defined(_WIN32) std::wstring WideStringFromUTF8(std::string_view sv) { const int sLength = static_cast<int>(sv.length()); const int cchWide = ::MultiByteToWideChar(CP_UTF8, 0, sv.data(), sLength, nullptr, 0); std::wstring sWide(cchWide, 0); ::MultiByteToWideChar(CP_UTF8, 0, sv.data(), sLength, sWide.data(), cchWide); return sWide; } #endif // Turn off deprecation checks as LexillaAccess deprecates its wrapper over // the deprecated LexerNameFromID. Thus use within LexillaAccess is intentional. #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #else #pragma warning(disable: 4996) #endif std::string directoryLoadDefault; std::string lastLoaded; struct LexLibrary { Lexilla::CreateLexerFn fnCL; Lexilla::LexerNameFromIDFn fnLNFI; Lexilla::GetLibraryPropertyNamesFn fnGLPN; Lexilla::SetLibraryPropertyFn fnSLP; std::string nameSpace; }; std::vector<LexLibrary> libraries; std::vector<std::string> lexers; std::vector<std::string> libraryProperties; Function FindSymbol(Module m, const char *symbol) noexcept { #if defined(_WIN32) return ::GetProcAddress(m, symbol); #else return dlsym(m, symbol); #endif } Lexilla::CreateLexerFn pCreateLexerDefault = nullptr; bool NameContainsDot(std::string_view path) noexcept { for (std::string_view::const_reverse_iterator it = path.crbegin(); it != path.crend(); ++it) { if (*it == '.') return true; if (*it == '/' || *it == '\\') return false; } return false; } constexpr bool HasPrefix(std::string_view s, std::string_view prefix) noexcept { return (s.size() >= prefix.size()) && (prefix == s.substr(0, prefix.size())); } } void Lexilla::SetDefault(CreateLexerFn pCreate) noexcept { pCreateLexerDefault = pCreate; } void Lexilla::SetDefaultDirectory(std::string_view directory) { directoryLoadDefault = directory; } bool Lexilla::Load(std::string_view sharedLibraryPaths) { if (sharedLibraryPaths == lastLoaded) { return !libraries.empty(); } std::string_view paths = sharedLibraryPaths; lexers.clear(); libraries.clear(); while (!paths.empty()) { const size_t separator = paths.find_first_of(';'); std::string path(paths.substr(0, separator)); if (separator == std::string::npos) { paths.remove_prefix(paths.size()); } else { paths.remove_prefix(separator + 1); } if (path == ".") { if (directoryLoadDefault.empty()) { path = ""; } else { path = directoryLoadDefault; path += pathSeparator; } path += LEXILLA_LIB; } if (!NameContainsDot(path)) { // No '.' in name so add extension path.append(LEXILLA_EXTENSION); } #if defined(_WIN32) // Convert from UTF-8 to wide characters std::wstring wsPath = WideStringFromUTF8(path); Module lexillaDL = ::LoadLibraryW(wsPath.c_str()); #else Module lexillaDL = dlopen(path.c_str(), RTLD_LAZY); #endif if (lexillaDL) { GetLexerCountFn fnLexerCount = FunctionPointer<GetLexerCountFn>( FindSymbol(lexillaDL, LEXILLA_GETLEXERCOUNT)); GetLexerNameFn fnLexerName = FunctionPointer<GetLexerNameFn>( FindSymbol(lexillaDL, LEXILLA_GETLEXERNAME)); if (fnLexerCount && fnLexerName) { const int nLexers = fnLexerCount(); for (int i = 0; i < nLexers; i++) { char name[100] = ""; fnLexerName(i, name, sizeof(name)); lexers.push_back(name); } } CreateLexerFn fnCL = FunctionPointer<CreateLexerFn>( FindSymbol(lexillaDL, LEXILLA_CREATELEXER)); LexerNameFromIDFn fnLNFI = FunctionPointer<LexerNameFromIDFn>( FindSymbol(lexillaDL, LEXILLA_LEXERNAMEFROMID)); GetLibraryPropertyNamesFn fnGLPN = FunctionPointer<GetLibraryPropertyNamesFn>( FindSymbol(lexillaDL, LEXILLA_GETLIBRARYPROPERTYNAMES)); SetLibraryPropertyFn fnSLP = FunctionPointer<SetLibraryPropertyFn>( FindSymbol(lexillaDL, LEXILLA_SETLIBRARYPROPERTY)); GetNameSpaceFn fnGNS = FunctionPointer<GetNameSpaceFn>( FindSymbol(lexillaDL, LEXILLA_GETNAMESPACE)); std::string nameSpace; if (fnGNS) { nameSpace = fnGNS(); nameSpace += LEXILLA_NAMESPACE_SEPARATOR; } LexLibrary lexLib { fnCL, fnLNFI, fnGLPN, fnSLP, nameSpace }; libraries.push_back(lexLib); } } lastLoaded = sharedLibraryPaths; std::set<std::string> nameSet; for (const LexLibrary &lexLib : libraries) { if (lexLib.fnGLPN) { const char *cpNames = lexLib.fnGLPN(); if (cpNames) { std::string_view names = cpNames; while (!names.empty()) { const size_t separator = names.find_first_of('\n'); std::string name(names.substr(0, separator)); nameSet.insert(name); if (separator == std::string::npos) { names.remove_prefix(names.size()); } else { names.remove_prefix(separator + 1); } } } } } // Standard Lexilla does not have any properties so can't be added to set. libraryProperties = std::vector<std::string>(nameSet.begin(), nameSet.end()); return !libraries.empty(); } Scintilla::ILexer5 *Lexilla::MakeLexer(std::string_view languageName) { std::string sLanguageName(languageName); // Ensure NUL-termination // First, try to match namespace then name suffix for (const LexLibrary &lexLib : libraries) { if (lexLib.fnCL && !lexLib.nameSpace.empty()) { if (HasPrefix(languageName, lexLib.nameSpace)) { Scintilla::ILexer5 *pLexer = lexLib.fnCL(sLanguageName.substr(lexLib.nameSpace.size()).c_str()); if (pLexer) { return pLexer; } } } } // If no match with namespace, try to just match name for (const LexLibrary &lexLib : libraries) { if (lexLib.fnCL) { Scintilla::ILexer5 *pLexer = lexLib.fnCL(sLanguageName.c_str()); if (pLexer) { return pLexer; } } } if (pCreateLexerDefault) { return pCreateLexerDefault(sLanguageName.c_str()); } #if defined(LEXILLA_STATIC) Scintilla::ILexer5 *pLexer = CreateLexer(sLanguageName.c_str()); if (pLexer) { return pLexer; } #endif return nullptr; } std::vector<std::string> Lexilla::Lexers() { return lexers; } std::string Lexilla::NameFromID(int identifier) { for (const LexLibrary &lexLib : libraries) { if (lexLib.fnLNFI) { const char *name = lexLib.fnLNFI(identifier); if (name) { return name; } } } return std::string(); } std::vector<std::string> Lexilla::LibraryProperties() { return libraryProperties; } void Lexilla::SetProperty(const char *key, const char *value) { for (const LexLibrary &lexLib : libraries) { if (lexLib.fnSLP) { lexLib.fnSLP(key, value); } } // Standard Lexilla does not have any properties so don't set. }
7,815
C++
.cxx
252
28.242063
100
0.727357
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
16,532
testCharacterCategoryMap.cxx
dail8859_NotepadNext/src/scintilla/test/unit/testCharacterCategoryMap.cxx
/** @file testCharacterCategoryMap.cxx ** Unit Tests for Scintilla internal data structures **/ #include <cstddef> #include <cstring> #include <stdexcept> #include <string_view> #include <vector> #include <optional> #include <algorithm> #include <memory> #include "Debugging.h" #include "CharacterCategoryMap.h" #include "catch.hpp" using namespace Scintilla; using namespace Scintilla::Internal; // Test CharacterCategoryMap. TEST_CASE("CharacterCategoryMap") { const CharacterCategoryMap ccm; SECTION("LowerCaseLetter") { const CharacterCategory cc = ccm.CategoryFor('a'); REQUIRE(cc == CharacterCategory::ccLl); } SECTION("All") { REQUIRE(ccm.CategoryFor('A') == CharacterCategory::ccLu); REQUIRE(ccm.CategoryFor('a') == CharacterCategory::ccLl); REQUIRE(ccm.CategoryFor(0x01C5) == CharacterCategory::ccLt); REQUIRE(ccm.CategoryFor(0x0E46) == CharacterCategory::ccLm); REQUIRE(ccm.CategoryFor(0x4E00) == CharacterCategory::ccLo); REQUIRE(ccm.CategoryFor(0x0300) == CharacterCategory::ccMn); REQUIRE(ccm.CategoryFor(0x0903) == CharacterCategory::ccMc); REQUIRE(ccm.CategoryFor(0x20E0) == CharacterCategory::ccMe); REQUIRE(ccm.CategoryFor('7') == CharacterCategory::ccNd); REQUIRE(ccm.CategoryFor(0x2160) == CharacterCategory::ccNl); REQUIRE(ccm.CategoryFor(0x00BC) == CharacterCategory::ccNo); REQUIRE(ccm.CategoryFor('_') == CharacterCategory::ccPc); REQUIRE(ccm.CategoryFor('-') == CharacterCategory::ccPd); REQUIRE(ccm.CategoryFor('(') == CharacterCategory::ccPs); REQUIRE(ccm.CategoryFor('}') == CharacterCategory::ccPe); REQUIRE(ccm.CategoryFor(0x00AB) == CharacterCategory::ccPi); REQUIRE(ccm.CategoryFor(0x00BB) == CharacterCategory::ccPf); REQUIRE(ccm.CategoryFor('"') == CharacterCategory::ccPo); REQUIRE(ccm.CategoryFor('+') == CharacterCategory::ccSm); REQUIRE(ccm.CategoryFor('$') == CharacterCategory::ccSc); REQUIRE(ccm.CategoryFor(0x02C2) == CharacterCategory::ccSk); REQUIRE(ccm.CategoryFor(0x00A6) == CharacterCategory::ccSo); REQUIRE(ccm.CategoryFor(' ') == CharacterCategory::ccZs); REQUIRE(ccm.CategoryFor(0x2028) == CharacterCategory::ccZl); REQUIRE(ccm.CategoryFor(0x2029) == CharacterCategory::ccZp); REQUIRE(ccm.CategoryFor('\n') == CharacterCategory::ccCc); REQUIRE(ccm.CategoryFor(0x00AD) == CharacterCategory::ccCf); REQUIRE(ccm.CategoryFor(0xD800) == CharacterCategory::ccCs); REQUIRE(ccm.CategoryFor(0xE000) == CharacterCategory::ccCo); REQUIRE(ccm.CategoryFor(0xFFFE) == CharacterCategory::ccCn); } }
2,521
C++
.cxx
56
42.446429
62
0.759395
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,534
testGeometry.cxx
dail8859_NotepadNext/src/scintilla/test/unit/testGeometry.cxx
/** @file testGeometry.cxx ** Unit Tests for Scintilla internal data structures **/ #include <cstdint> #include "Geometry.h" #include "catch.hpp" using namespace Scintilla; using namespace Scintilla::Internal; // Test Geometry. TEST_CASE("Point") { SECTION("Point") { constexpr Point pt(1.0, 2.0); REQUIRE(pt.x == 1.0); REQUIRE(pt.y == 2.0); constexpr Point pti = Point::FromInts(1, 2); REQUIRE(pt == pti); constexpr Point pt2 = pt + pt; REQUIRE(pt != pt2); constexpr Point ptBack = pt2 - pt; REQUIRE(pt == ptBack); } } TEST_CASE("Interval") { SECTION("Interval") { constexpr Interval interval { 1.0, 2.0 }; REQUIRE(interval.left == 1.0); REQUIRE(interval.right == 2.0); REQUIRE(interval.Width() == 1.0); REQUIRE(!interval.Empty()); constexpr Interval empty { 4.0, 4.0 }; REQUIRE(empty.Empty()); REQUIRE(empty.Width() == 0.0); REQUIRE(!(interval == empty)); REQUIRE(!(interval.Intersects(empty))); constexpr Interval inside { 1.7, 1.8 }; REQUIRE(interval.Intersects(inside)); constexpr Interval straddles { 1.7, 2.8 }; REQUIRE(interval.Intersects(straddles)); } SECTION("Interval") { constexpr Interval interval1{ 1.0, 3.0 }; constexpr Interval interval2{ 2.0, 4.0 }; REQUIRE(Intersection(interval1, interval2) == Interval{ 2.0, 3.0 }); } } TEST_CASE("PRectangle") { SECTION("PRectangle") { constexpr PRectangle rc(1.0, 2.0, 3.0, 4.0); REQUIRE(rc.left == 1.0); REQUIRE(rc.top == 2.0); REQUIRE(rc.right == 3.0); REQUIRE(rc.bottom == 4.0); REQUIRE(rc.Width() == 2.0); REQUIRE(rc.Height() == 2.0); REQUIRE(!rc.Empty()); constexpr PRectangle rci = PRectangle::FromInts(1, 2, 3, 4); REQUIRE(rc == rci); constexpr PRectangle rcEmpty; REQUIRE(rcEmpty.Empty()); } SECTION("Contains") { constexpr PRectangle rc(1.0, 2.0, 3.0, 4.0); constexpr Point pt(1.5, 2.5); REQUIRE(rc.Contains(pt)); REQUIRE(rc.ContainsWholePixel(pt)); constexpr Point ptNearEdge(2.9, 2.5); REQUIRE(rc.Contains(ptNearEdge)); REQUIRE(!rc.ContainsWholePixel(ptNearEdge)); constexpr Point ptOutside(1.5, 20.5); REQUIRE(!rc.Contains(ptOutside)); REQUIRE(!rc.ContainsWholePixel(ptOutside)); constexpr PRectangle rcInside(1.5, 2.0, 2.5, 4.0); REQUIRE(rc.Contains(rcInside)); REQUIRE(rc.Intersects(rcInside)); constexpr PRectangle rcIntersects(1.5, 2.0, 3.5, 4.0); REQUIRE(!rc.Contains(rcIntersects)); REQUIRE(rc.Intersects(rcIntersects)); constexpr PRectangle rcSeparate(11.0, 12.0, 13.0, 14.0); REQUIRE(!rc.Contains(rcSeparate)); REQUIRE(!rc.Intersects(rcSeparate)); constexpr Point ptCentre = rc.Centre(); REQUIRE(ptCentre == Point(2.0, 3.0)); } SECTION("Move") { PRectangle rc(1.0, 2.0, 3.0, 4.0); rc.Move(1.0, 10.0); REQUIRE(rc == PRectangle(2.0, 12.0, 4.0, 14.0)); } SECTION("Inset") { constexpr PRectangle rc(1.0, 2.0, 3.0, 4.0); constexpr PRectangle rcInset = rc.Inset(0.5); REQUIRE(rcInset == PRectangle(1.5, 2.5, 2.5, 3.5)); constexpr PRectangle rcInsetPt = rc.Inset(Point(0.25, 0.5)); REQUIRE(rcInsetPt == PRectangle(1.25, 2.5, 2.75, 3.5)); } SECTION("Clamp") { constexpr PRectangle rc(1.0, 2.0, 3.0, 4.0); const PRectangle cutBottom = Clamp(rc, Edge::bottom, 3.5); REQUIRE(cutBottom == PRectangle(1.0, 2.0, 3.0, 3.5)); const PRectangle justBottom = Side(rc, Edge::bottom, 0.5); REQUIRE(justBottom == PRectangle(1.0, 3.5, 3.0, 4.0)); constexpr PRectangle rcInset = rc.Inset(0.5); REQUIRE(rcInset == PRectangle(1.5, 2.5, 2.5, 3.5)); constexpr PRectangle rcInsetPt = rc.Inset(Point(0.25, 0.5)); REQUIRE(rcInsetPt == PRectangle(1.25, 2.5, 2.75, 3.5)); const Interval bounds = HorizontalBounds(rcInsetPt); REQUIRE(bounds == Interval{ 1.25, 2.75 }); const PRectangle applyBounds = Intersection(rc, bounds); REQUIRE(applyBounds == PRectangle(1.25, 2.0, 2.75, 4.0)); } SECTION("PixelAlign") { // Whole pixels REQUIRE(PixelAlign(1.0, 1) == 1.0); REQUIRE(PixelAlignFloor(1.0, 1) == 1.0); REQUIRE(PixelAlignCeil(1.0, 1) == 1.0); REQUIRE(PixelAlign(1.25, 1) == 1.0); REQUIRE(PixelAlignFloor(1.25, 1) == 1.0); REQUIRE(PixelAlignCeil(1.25, 1) == 2.0); REQUIRE(PixelAlign(1.5, 1) == 2.0); REQUIRE(PixelAlignFloor(1.5, 1) == 1.0); REQUIRE(PixelAlignCeil(1.5, 1) == 2.0); REQUIRE(PixelAlign(1.75, 1) == 2.0); REQUIRE(PixelAlignFloor(1.75, 1) == 1.0); REQUIRE(PixelAlignCeil(1.75, 1) == 2.0); REQUIRE(PixelAlign(Point(1.75, 1.25), 1) == Point(2.0, 1.0)); REQUIRE(PixelAlign(Point(1.5, 1.0), 1) == Point(2.0, 1.0)); // Half pixels REQUIRE(PixelAlign(1.0, 2) == 1.0); REQUIRE(PixelAlignFloor(1.0, 2) == 1.0); REQUIRE(PixelAlignCeil(1.0, 2) == 1.0); REQUIRE(PixelAlign(1.25, 2) == 1.5); REQUIRE(PixelAlignFloor(1.25, 2) == 1.0); REQUIRE(PixelAlignCeil(1.25, 2) == 1.5); REQUIRE(PixelAlign(1.5, 2) == 1.5); REQUIRE(PixelAlignFloor(1.5, 2) == 1.5); REQUIRE(PixelAlignCeil(1.5, 2) == 1.5); REQUIRE(PixelAlign(1.75, 2) == 2.0); REQUIRE(PixelAlignFloor(1.75, 2) == 1.5); REQUIRE(PixelAlignCeil(1.75, 2) == 2.0); REQUIRE(PixelAlign(Point(1.75, 1.25), 2) == Point(2.0, 1.5)); REQUIRE(PixelAlign(Point(1.5, 1.0), 2) == Point(1.5, 1.0)); // x->round, y->floored REQUIRE(PixelAlign(PRectangle(1.0, 1.25, 1.5, 1.75), 1) == PRectangle(1.0, 1.0, 2.0, 1.0)); REQUIRE(PixelAlign(PRectangle(1.0, 1.25, 1.5, 1.75), 2) == PRectangle(1.0, 1.0, 1.5, 1.5)); // x->outside(floor left, ceil right), y->floored REQUIRE(PixelAlignOutside(PRectangle(1.1, 1.25, 1.6, 1.75), 1) == PRectangle(1.0, 1.0, 2.0, 1.0)); REQUIRE(PixelAlignOutside(PRectangle(1.1, 1.25, 1.6, 1.75), 2) == PRectangle(1.0, 1.0, 2.0, 1.5)); } } TEST_CASE("ColourRGBA") { SECTION("ColourRGBA") { constexpr ColourRGBA colour(0x10203040); constexpr ColourRGBA colourFromRGB(0x40, 0x30, 0x20, 0x10); REQUIRE(colour == colourFromRGB); REQUIRE(colour.GetRed() == 0x40); REQUIRE(colour.GetGreen() == 0x30); REQUIRE(colour.GetBlue() == 0x20); REQUIRE(colour.GetAlpha() == 0x10); REQUIRE(!colour.IsOpaque()); REQUIRE(colour.AsInteger() == 0x10203040); REQUIRE(ColourRGBA(colour, 0x80) == ColourRGBA(0x40, 0x30, 0x20, 0x80)); REQUIRE(ColourRGBA::FromRGB(0x203040) == ColourRGBA(0x40, 0x30, 0x20, 0xff)); REQUIRE(ColourRGBA::FromIpRGB(0x203040) == ColourRGBA(0x40, 0x30, 0x20, 0xff)); constexpr ColourRGBA colour01(0x00ff00ff); REQUIRE(colour01.GetRedComponent() == 1.0); REQUIRE(colour01.GetGreenComponent() == 0.0); REQUIRE(colour01.GetBlueComponent() == 1.0); REQUIRE(colour01.GetAlphaComponent() == 0.0); // Opaque colours constexpr ColourRGBA colourRGB(0xff203040); REQUIRE(colourRGB.IsOpaque()); constexpr ColourRGBA colourOpaque(0x40, 0x30, 0x20, 0xff); REQUIRE(colourRGB == colourOpaque); REQUIRE(colourRGB.OpaqueRGB() == 0x203040); REQUIRE(colourRGB.WithoutAlpha() == ColourRGBA(0x40, 0x30, 0x20, 0)); } SECTION("Mixing") { constexpr ColourRGBA colourMin(0x10, 0x20, 0x30, 0x40); constexpr ColourRGBA colourMax(0x30, 0x60, 0x90, 0xC0); constexpr ColourRGBA colourMid(0x20, 0x40, 0x60, 0x80); REQUIRE(colourMin.MixedWith(colourMax) == colourMid); REQUIRE(colourMin.MixedWith(colourMax, 0.5) == colourMid); // 3/4 between min and max constexpr ColourRGBA colour75(0x28, 0x50, 0x78, 0xA0); REQUIRE(colourMin.MixedWith(colourMax, 0.75) == colour75); } }
7,317
C++
.cxx
187
36.101604
100
0.681375
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,535
testPartitioning.cxx
dail8859_NotepadNext/src/scintilla/test/unit/testPartitioning.cxx
/** @file testPartitioning.cxx ** Unit Tests for Scintilla internal data structures **/ #include <cstddef> #include <cstring> #include <stdexcept> #include <string_view> #include <vector> #include <optional> #include <algorithm> #include <memory> #include "Debugging.h" #include "Position.h" #include "SplitVector.h" #include "Partitioning.h" #include "catch.hpp" using namespace Scintilla::Internal; // Test Partitioning. TEST_CASE("CompileCopying Partitioning") { // These are compile-time tests to check that basic copy and move // operations are defined correctly. SECTION("CopyingMoving") { Partitioning<int> s; Partitioning<int> s2; // Copy constructor const Partitioning<int> sa(s); // Copy assignment Partitioning<int> sb; sb = s; // Move constructor const Partitioning<int> sc(std::move(s)); // Move assignment Partitioning<int> sd; sd = (std::move(s2)); } } TEST_CASE("Partitioning") { Partitioning<Sci::Position> part; SECTION("IsEmptyInitially") { REQUIRE(1 == part.Partitions()); REQUIRE(0 == part.PositionFromPartition(part.Partitions())); REQUIRE(0 == part.PartitionFromPosition(0)); } SECTION("SimpleInsert") { part.InsertText(0, 1); REQUIRE(1 == part.Partitions()); REQUIRE(1 == part.PositionFromPartition(part.Partitions())); } SECTION("TwoPartitions") { part.InsertText(0, 2); part.InsertPartition(1, 1); REQUIRE(2 == part.Partitions()); REQUIRE(0 == part.PositionFromPartition(0)); REQUIRE(1 == part.PositionFromPartition(1)); REQUIRE(2 == part.PositionFromPartition(2)); } SECTION("MoveStart") { part.InsertText(0, 3); part.InsertPartition(1, 2); part.SetPartitionStartPosition(1,1); REQUIRE(2 == part.Partitions()); REQUIRE(0 == part.PositionFromPartition(0)); REQUIRE(1 == part.PositionFromPartition(1)); REQUIRE(3 == part.PositionFromPartition(2)); part.Check(); } SECTION("InsertAgain") { part.InsertText(0, 3); part.InsertPartition(1, 2); part.InsertText(0,3); part.InsertText(1,2); REQUIRE(2 == part.Partitions()); REQUIRE(0 == part.PositionFromPartition(0)); REQUIRE(5 == part.PositionFromPartition(1)); REQUIRE(8 == part.PositionFromPartition(2)); part.Check(); } SECTION("InsertMultiple") { part.InsertText(0, 10); const Sci::Position positions[] { 2, 5, 7 }; part.InsertPartitions(1, positions, std::size(positions)); REQUIRE(4 == part.Partitions()); REQUIRE(0 == part.PositionFromPartition(0)); REQUIRE(2 == part.PositionFromPartition(1)); REQUIRE(5 == part.PositionFromPartition(2)); REQUIRE(7 == part.PositionFromPartition(3)); REQUIRE(10 == part.PositionFromPartition(4)); part.Check(); } SECTION("InsertMultipleWithCast") { part.InsertText(0, 9); REQUIRE(1 == part.Partitions()); const ptrdiff_t positionsp[]{ 2, 4, 6, 8 }; part.InsertPartitionsWithCast(1, positionsp, std::size(positionsp)); REQUIRE(5 == part.Partitions()); REQUIRE(0 == part.PositionFromPartition(0)); REQUIRE(2 == part.PositionFromPartition(1)); REQUIRE(4 == part.PositionFromPartition(2)); REQUIRE(6 == part.PositionFromPartition(3)); REQUIRE(8 == part.PositionFromPartition(4)); REQUIRE(9 == part.PositionFromPartition(5)); part.Check(); } SECTION("InsertReversed") { part.InsertText(0, 3); part.InsertPartition(1, 2); part.InsertText(1,2); part.InsertText(0,3); REQUIRE(2 == part.Partitions()); REQUIRE(0 == part.PositionFromPartition(0)); REQUIRE(5 == part.PositionFromPartition(1)); REQUIRE(8 == part.PositionFromPartition(2)); part.Check(); } SECTION("InverseSearch") { part.InsertText(0, 3); part.InsertPartition(1, 2); part.SetPartitionStartPosition(1,1); REQUIRE(2 == part.Partitions()); REQUIRE(0 == part.PositionFromPartition(0)); REQUIRE(1 == part.PositionFromPartition(1)); REQUIRE(3 == part.PositionFromPartition(2)); REQUIRE(0 == part.PartitionFromPosition(0)); REQUIRE(1 == part.PartitionFromPosition(1)); REQUIRE(1 == part.PartitionFromPosition(2)); REQUIRE(1 == part.PartitionFromPosition(3)); part.Check(); } SECTION("DeletePartition") { part.InsertText(0, 2); part.InsertPartition(1, 1); part.RemovePartition(1); REQUIRE(1 == part.Partitions()); REQUIRE(0 == part.PositionFromPartition(0)); REQUIRE(2 == part.PositionFromPartition(1)); part.Check(); } SECTION("DeleteAll") { part.InsertText(0, 3); part.InsertPartition(1, 2); part.SetPartitionStartPosition(1,1); part.DeleteAll(); // Back to initial state REQUIRE(1 == part.Partitions()); REQUIRE(0 == part.PositionFromPartition(part.Partitions())); } SECTION("TestBackwards") { part.InsertText(0, 10); part.InsertPartition(1, 3); part.InsertPartition(2, 6); part.InsertPartition(3, 9); part.InsertText(2,4); part.InsertText(1,2); part.InsertText(0,3); REQUIRE(4 == part.Partitions()); REQUIRE(0 == part.PositionFromPartition(0)); REQUIRE(6 == part.PositionFromPartition(1)); REQUIRE(11 == part.PositionFromPartition(2)); REQUIRE(18 == part.PositionFromPartition(3)); REQUIRE(19 == part.PositionFromPartition(4)); part.Check(); } SECTION("TestMany") { // Provoke backstep call part.InsertText(0, 42); for (int i=0; i<20; i++) { part.InsertPartition(i+1, (i+1) * 2); } for (int i=20; i>0; i--) { part.InsertText(i,2); } REQUIRE(21 == part.Partitions()); for (int i=1; i<20; i++) { REQUIRE((i*4 - 2) == part.PositionFromPartition(i)); REQUIRE(i == part.PartitionFromPosition(i*4 - 2)); } part.InsertText(19,2); REQUIRE(3 == part.PartitionFromPosition(10)); part.InsertText(0,2); part.InsertText(0,-2); part.RemovePartition(1); REQUIRE(0 == part.PositionFromPartition(0)); REQUIRE(6 == part.PositionFromPartition(1)); REQUIRE(10 == part.PositionFromPartition(2)); part.RemovePartition(10); REQUIRE(46 == part.PositionFromPartition(10)); REQUIRE(10 == part.PartitionFromPosition(46)); REQUIRE(50 == part.PositionFromPartition(11)); REQUIRE(11 == part.PartitionFromPosition(50)); part.Check(); } }
6,016
C++
.cxx
192
28.526042
70
0.713916
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,536
testCharClassify.cxx
dail8859_NotepadNext/src/scintilla/test/unit/testCharClassify.cxx
/** @file testCharClassify.cxx ** Unit Tests for Scintilla internal data structures **/ #include <cstring> #include <string_view> #include <vector> #include <optional> #include <algorithm> #include <memory> #include <iostream> #include "Debugging.h" #include "CharClassify.h" #include "catch.hpp" using namespace Scintilla::Internal; // Test CharClassify. class CharClassifyTest { protected: CharClassifyTest() { pcc = std::make_unique<CharClassify>(); for (int ch = 0; ch < 256; ch++) { if (ch == '\r' || ch == '\n') charClass[ch] = CharacterClass::newLine; else if (ch < 0x20 || ch == ' ' || ch == '\x7f') charClass[ch] = CharacterClass::space; else if (ch >= 0x80 || isalnum(ch) || ch == '_') charClass[ch] = CharacterClass::word; else charClass[ch] = CharacterClass::punctuation; } } // Avoid warnings, deleted so never called. CharClassifyTest(const CharClassifyTest &) = delete; std::unique_ptr<CharClassify> pcc; CharacterClass charClass[256] {}; static const char* GetClassName(CharacterClass charClass) noexcept { switch(charClass) { #define CASE(c) case CharacterClass::c: return #c CASE(space); CASE(newLine); CASE(word); CASE(punctuation); #undef CASE default: return "<unknown>"; } } }; TEST_CASE_METHOD(CharClassifyTest, "Defaults") { for (int i = 0; i < 256; i++) { if (charClass[i] != pcc->GetClass(i)) std::cerr << "Character " << i << " should be class " << GetClassName(charClass[i]) << ", but got " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE(charClass[i] == pcc->GetClass(i)); } } TEST_CASE_METHOD(CharClassifyTest, "Custom") { unsigned char buf[2] = {0, 0}; for (int i = 0; i < 256; i++) { const CharacterClass thisClass = static_cast<CharacterClass>(i % 4); buf[0] = i; pcc->SetCharClasses(buf, thisClass); charClass[i] = thisClass; } for (int i = 0; i < 256; i++) { if (charClass[i] != pcc->GetClass(i)) std::cerr << "Character " << i << " should be class " << GetClassName(charClass[i]) << ", but got " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE(charClass[i] == pcc->GetClass(i)); } } TEST_CASE_METHOD(CharClassifyTest, "CharsOfClass") { unsigned char buf[2] = {0, 0}; for (int i = 1; i < 256; i++) { const CharacterClass thisClass = static_cast<CharacterClass>(i % 4); buf[0] = i; pcc->SetCharClasses(buf, thisClass); charClass[i] = thisClass; } for (int classVal = 0; classVal < 4; ++classVal) { const CharacterClass thisClass = static_cast<CharacterClass>(classVal % 4); const int size = pcc->GetCharsOfClass(thisClass, nullptr); std::vector<unsigned char> buffer(size+1); const unsigned char *pBuffer = buffer.data(); pcc->GetCharsOfClass(thisClass, buffer.data()); for (int i = 1; i < 256; i++) { if (charClass[i] == thisClass) { if (!memchr(pBuffer, i, size)) std::cerr << "Character " << i << " should be class " << GetClassName(thisClass) << ", but was not in GetCharsOfClass;" << " it is reported to be " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE(memchr(pBuffer, i, size)); } else { if (memchr(pBuffer, i, size)) std::cerr << "Character " << i << " should not be class " << GetClassName(thisClass) << ", but was in GetCharsOfClass" << " it is reported to be " << GetClassName(pcc->GetClass(i)) << std::endl; REQUIRE_FALSE(memchr(pBuffer, i, size)); } } } }
3,475
C++
.cxx
111
28.099099
77
0.64906
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,537
testCellBuffer.cxx
dail8859_NotepadNext/src/scintilla/test/unit/testCellBuffer.cxx
/** @file testCellBuffer.cxx ** Unit Tests for Scintilla internal data structures **/ #include <cstddef> #include <cassert> #include <cstring> #include <stdexcept> #include <string> #include <string_view> #include <vector> #include <optional> #include <algorithm> #include <memory> #include "ScintillaTypes.h" #include "Debugging.h" #include "Position.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "SparseVector.h" #include "ChangeHistory.h" #include "CellBuffer.h" #include "UndoHistory.h" #include "catch.hpp" using namespace Scintilla; using namespace Scintilla::Internal; // Test CellBuffer. bool Equal(const char *ptr, std::string_view sv) noexcept { return memcmp(ptr, sv.data(), sv.length()) == 0; } TEST_CASE("ScrapStack") { ScrapStack ss; SECTION("Push") { const char *t = ss.Push("abc", 3); REQUIRE(memcmp(t, "abc", 3) == 0); ss.MoveBack(3); const char *text = ss.CurrentText(); REQUIRE(memcmp(text, "abc", 3) == 0); ss.MoveForward(1); const char *text2 = ss.CurrentText(); REQUIRE(memcmp(text2, "bc", 2) == 0); ss.SetCurrent(1); const char *text3 = ss.CurrentText(); REQUIRE(memcmp(text3, "bc", 2) == 0); const char *text4 = ss.TextAt(2); REQUIRE(memcmp(text4, "c", 1) == 0); ss.Clear(); const char *text5 = ss.Push("1", 1); REQUIRE(memcmp(text5, "1", 1) == 0); } } TEST_CASE("CellBuffer") { constexpr std::string_view sText = "Scintilla"; constexpr Sci::Position sLength = sText.length(); CellBuffer cb(true, false); SECTION("InsertOneLine") { bool startSequence = false; const char *cpChange = cb.InsertString(0, sText.data(), sLength, startSequence); REQUIRE(startSequence); REQUIRE(sLength == cb.Length()); REQUIRE(Equal(cpChange, sText)); REQUIRE(1 == cb.Lines()); REQUIRE(0 == cb.LineStart(0)); REQUIRE(0 == cb.LineFromPosition(0)); REQUIRE(sLength == cb.LineStart(1)); REQUIRE(0 == cb.LineFromPosition(static_cast<int>(sLength))); REQUIRE(cb.CanUndo()); REQUIRE(!cb.CanRedo()); } SECTION("InsertTwoLines") { constexpr std::string_view sText2 = "Two\nLines"; constexpr Sci::Position sLength2 = sText2.length(); bool startSequence = false; const char *cpChange = cb.InsertString(0, sText2.data(), sLength2, startSequence); REQUIRE(startSequence); REQUIRE(sLength2 == cb.Length()); REQUIRE(Equal(cpChange, sText2)); REQUIRE(2 == cb.Lines()); REQUIRE(0 == cb.LineStart(0)); REQUIRE(0 == cb.LineFromPosition(0)); REQUIRE(4 == cb.LineStart(1)); REQUIRE(1 == cb.LineFromPosition(5)); REQUIRE(sLength2 == cb.LineStart(2)); REQUIRE(1 == cb.LineFromPosition(sLength2)); REQUIRE(cb.CanUndo()); REQUIRE(!cb.CanRedo()); } SECTION("LineEnds") { // Check that various line ends produce correct result from LineEnd. cb.SetLineEndTypes(LineEndType::Unicode); bool startSequence = false; { // Unix \n constexpr std::string_view sText2 = "Two\nLines"; constexpr Sci::Position sLength2 = sText2.length(); cb.InsertString(0, sText2.data(), sLength2, startSequence); REQUIRE(3 == cb.LineEnd(0)); REQUIRE(sLength2 == cb.LineEnd(1)); cb.DeleteChars(0, sLength2, startSequence); } { // Windows \r\n constexpr std::string_view sText2 = "Two\r\nLines"; constexpr Sci::Position sLength2 = sText2.length(); cb.InsertString(0, sText2.data(), sLength2, startSequence); REQUIRE(3 == cb.LineEnd(0)); REQUIRE(sLength2 == cb.LineEnd(1)); cb.DeleteChars(0, sLength2, startSequence); } { // Old macOS \r constexpr std::string_view sText2 = "Two\rLines"; constexpr Sci::Position sLength2 = sText2.length(); cb.InsertString(0, sText2.data(), sLength2, startSequence); REQUIRE(3 == cb.LineEnd(0)); REQUIRE(sLength2 == cb.LineEnd(1)); cb.DeleteChars(0, sLength2, startSequence); } { // Unicode NEL is U+0085 \xc2\x85 constexpr std::string_view sText2 = "Two\xc2\x85Lines"; constexpr Sci::Position sLength2 = sText2.length(); cb.InsertString(0, sText2.data(), sLength2, startSequence); REQUIRE(3 == cb.LineEnd(0)); REQUIRE(sLength2 == cb.LineEnd(1)); cb.DeleteChars(0, sLength2, startSequence); } { // Unicode LS line separator is U+2028 \xe2\x80\xa8 constexpr std::string_view sText2 = "Two\xe2\x80\xa8Lines"; constexpr Sci::Position sLength2 = sText2.length(); cb.InsertString(0, sText2.data(), sLength2, startSequence); REQUIRE(3 == cb.LineEnd(0)); REQUIRE(sLength2 == cb.LineEnd(1)); cb.DeleteChars(0, sLength2, startSequence); } cb.SetLineEndTypes(LineEndType::Default); } SECTION("UndoOff") { REQUIRE(cb.IsCollectingUndo()); cb.SetUndoCollection(false); REQUIRE(!cb.IsCollectingUndo()); bool startSequence = false; const char *cpChange = cb.InsertString(0, sText.data(), sLength, startSequence); REQUIRE(!startSequence); REQUIRE(sLength == cb.Length()); REQUIRE(Equal(cpChange, sText)); REQUIRE(!cb.CanUndo()); REQUIRE(!cb.CanRedo()); } SECTION("UndoRedo") { constexpr std::string_view sTextDeleted = "ci"; constexpr std::string_view sTextAfterDeletion = "Sntilla"; bool startSequence = false; const char *cpChange = cb.InsertString(0, sText.data(), sLength, startSequence); REQUIRE(startSequence); REQUIRE(sLength == cb.Length()); REQUIRE(Equal(cpChange, sText)); REQUIRE(Equal(cb.BufferPointer(), sText)); REQUIRE(cb.CanUndo()); REQUIRE(!cb.CanRedo()); const char *cpDeletion = cb.DeleteChars(1, 2, startSequence); REQUIRE(startSequence); REQUIRE(Equal(cpDeletion, sTextDeleted)); REQUIRE(Equal(cb.BufferPointer(), sTextAfterDeletion)); REQUIRE(cb.CanUndo()); REQUIRE(!cb.CanRedo()); int steps = cb.StartUndo(); REQUIRE(steps == 1); cb.PerformUndoStep(); REQUIRE(Equal(cb.BufferPointer(), sText)); REQUIRE(cb.CanUndo()); REQUIRE(cb.CanRedo()); steps = cb.StartUndo(); REQUIRE(steps == 1); cb.PerformUndoStep(); REQUIRE(cb.Length() == 0); REQUIRE(!cb.CanUndo()); REQUIRE(cb.CanRedo()); steps = cb.StartRedo(); REQUIRE(steps == 1); cb.PerformRedoStep(); REQUIRE(Equal(cb.BufferPointer(), sText)); REQUIRE(cb.CanUndo()); REQUIRE(cb.CanRedo()); steps = cb.StartRedo(); REQUIRE(steps == 1); cb.PerformRedoStep(); REQUIRE(Equal(cb.BufferPointer(), sTextAfterDeletion)); REQUIRE(cb.CanUndo()); REQUIRE(!cb.CanRedo()); cb.DeleteUndoHistory(); REQUIRE(!cb.CanUndo()); REQUIRE(!cb.CanRedo()); } SECTION("LineEndTypes") { REQUIRE(cb.GetLineEndTypes() == LineEndType::Default); cb.SetLineEndTypes(LineEndType::Unicode); REQUIRE(cb.GetLineEndTypes() == LineEndType::Unicode); cb.SetLineEndTypes(LineEndType::Default); REQUIRE(cb.GetLineEndTypes() == LineEndType::Default); } SECTION("ReadOnly") { REQUIRE(!cb.IsReadOnly()); cb.SetReadOnly(true); REQUIRE(cb.IsReadOnly()); bool startSequence = false; cb.InsertString(0, sText.data(), sLength, startSequence); REQUIRE(cb.Length() == 0); } } bool Equal(const Action &a, ActionType at, Sci::Position position, std::string_view value) noexcept { // Currently ignores mayCoalesce since this is not set consistently when following // start action implies it. if (a.at != at) return false; if (a.position != position) return false; if (a.lenData != static_cast<Sci::Position>(value.length())) return false; if (memcmp(a.data, value.data(), a.lenData) != 0) return false; return true; } bool EqualContainerAction(const Action &a, Sci::Position token) noexcept { // Currently ignores mayCoalesce if (a.at != ActionType::container) return false; if (a.position != token) return false; if (a.lenData != 0) return false; if (a.data) return false; return true; } void TentativeUndo(UndoHistory &uh) noexcept { const int steps = uh.TentativeSteps(); for (int step = 0; step < steps; step++) { /* const Action &actionStep = */ uh.GetUndoStep(); uh.CompletedUndoStep(); } uh.TentativeCommit(); } TEST_CASE("ScaledVector") { ScaledVector sv; SECTION("ScalingUp") { sv.ReSize(1); REQUIRE(sv.SizeInBytes() == 1); REQUIRE(sv.ValueAt(0) == 0); sv.SetValueAt(0, 1); REQUIRE(sv.ValueAt(0) == 1); REQUIRE(sv.SignedValueAt(0) == 1); sv.ClearValueAt(0); REQUIRE(sv.ValueAt(0) == 0); // Check boundary of 1-byte values sv.SetValueAt(0, 0xff); REQUIRE(sv.ValueAt(0) == 0xff); REQUIRE(sv.SizeInBytes() == 1); // Require expansion to 2 byte elements sv.SetValueAt(0, 0x100); REQUIRE(sv.ValueAt(0) == 0x100); REQUIRE(sv.SizeInBytes() == 2); // Only ever expands, never diminishes element size sv.SetValueAt(0, 0xff); REQUIRE(sv.ValueAt(0) == 0xff); REQUIRE(sv.SizeInBytes() == 2); // Check boundary of 2-byte values sv.SetValueAt(0, 0xffff); REQUIRE(sv.ValueAt(0) == 0xffff); REQUIRE(sv.SizeInBytes() == 2); // Require expansion to 2 byte elements sv.SetValueAt(0, 0x10000); REQUIRE(sv.ValueAt(0) == 0x10000); REQUIRE(sv.SizeInBytes() == 3); // Check that its not just simple bit patterns that work sv.SetValueAt(0, 0xd4381); REQUIRE(sv.ValueAt(0) == 0xd4381); // Add a second item sv.ReSize(2); REQUIRE(sv.SizeInBytes() == 6); // Truncate sv.Truncate(1); REQUIRE(sv.SizeInBytes() == 3); REQUIRE(sv.ValueAt(0) == 0xd4381); sv.Clear(); REQUIRE(sv.Size() == 0); sv.PushBack(); REQUIRE(sv.Size() == 1); REQUIRE(sv.SizeInBytes() == 3); sv.SetValueAt(0, 0x1fd4381); REQUIRE(sv.SizeInBytes() == 4); REQUIRE(sv.ValueAt(0) == 0x1fd4381); } } TEST_CASE("UndoHistory") { UndoHistory uh; SECTION("Basics") { REQUIRE(uh.IsSavePoint()); REQUIRE(uh.AfterSavePoint()); REQUIRE(!uh.BeforeSavePoint()); REQUIRE(!uh.BeforeReachableSavePoint()); REQUIRE(!uh.CanUndo()); REQUIRE(!uh.CanRedo()); bool startSequence = false; const char *val = uh.AppendAction(ActionType::insert, 0, "ab", 2, startSequence, true); REQUIRE(memcmp(val, "ab", 2) == 0); REQUIRE(startSequence); REQUIRE(!uh.IsSavePoint()); REQUIRE(uh.AfterSavePoint()); REQUIRE(uh.CanUndo()); REQUIRE(!uh.CanRedo()); val = uh.AppendAction(ActionType::remove, 0, "ab", 2, startSequence, true); REQUIRE(memcmp(val, "ab", 2) == 0); REQUIRE(startSequence); // Undoing { const int steps = uh.StartUndo(); REQUIRE(steps == 1); const Action action = uh.GetUndoStep(); REQUIRE(Equal(action, ActionType::remove, 0, "ab")); uh.CompletedUndoStep(); } { const int steps = uh.StartUndo(); REQUIRE(steps == 1); const Action action = uh.GetUndoStep(); REQUIRE(Equal(action, ActionType::insert, 0, "ab")); uh.CompletedUndoStep(); } REQUIRE(uh.IsSavePoint()); // Redoing { const int steps = uh.StartRedo(); REQUIRE(steps == 1); const Action action = uh.GetRedoStep(); REQUIRE(Equal(action, ActionType::insert, 0, "ab")); uh.CompletedRedoStep(); } { const int steps = uh.StartRedo(); REQUIRE(steps == 1); const Action action = uh.GetRedoStep(); REQUIRE(Equal(action, ActionType::remove, 0, "ab")); uh.CompletedRedoStep(); } REQUIRE(!uh.IsSavePoint()); } SECTION("EnsureTruncationAfterUndo") { REQUIRE(uh.Actions() == 0); bool startSequence = false; uh.AppendAction(ActionType::insert, 0, "ab", 2, startSequence, true); REQUIRE(uh.Actions() == 1); uh.AppendAction(ActionType::insert, 2, "cd", 2, startSequence, true); REQUIRE(uh.Actions() == 2); REQUIRE(uh.CanUndo()); REQUIRE(!uh.CanRedo()); // Undoing const int steps = uh.StartUndo(); REQUIRE(steps == 2); uh.GetUndoStep(); uh.CompletedUndoStep(); REQUIRE(uh.Actions() == 2); // Not truncated until forward action uh.GetUndoStep(); uh.CompletedUndoStep(); REQUIRE(uh.Actions() == 2); // Perform action which should truncate history uh.AppendAction(ActionType::insert, 0, "12", 2, startSequence, true); REQUIRE(uh.Actions() == 1); } SECTION("Coalesce") { bool startSequence = false; const char *val = uh.AppendAction(ActionType::insert, 0, "ab", 2, startSequence, true); REQUIRE(memcmp(val, "ab", 2) == 0); REQUIRE(startSequence); REQUIRE(!uh.IsSavePoint()); REQUIRE(uh.AfterSavePoint()); REQUIRE(uh.CanUndo()); REQUIRE(!uh.CanRedo()); val = uh.AppendAction(ActionType::insert, 2, "cd", 2, startSequence, true); REQUIRE(memcmp(val, "cd", 2) == 0); REQUIRE(!startSequence); // Undoing { const int steps = uh.StartUndo(); REQUIRE(steps == 2); const Action action2 = uh.GetUndoStep(); REQUIRE(Equal(action2, ActionType::insert, 2, "cd")); uh.CompletedUndoStep(); const Action action1 = uh.GetUndoStep(); REQUIRE(Equal(action1, ActionType::insert, 0, "ab")); uh.CompletedUndoStep(); } REQUIRE(uh.IsSavePoint()); // Redoing { const int steps = uh.StartRedo(); REQUIRE(steps == 2); const Action action1 = uh.GetRedoStep(); REQUIRE(Equal(action1, ActionType::insert, 0, "ab")); uh.CompletedRedoStep(); const Action action2 = uh.GetRedoStep(); REQUIRE(Equal(action2, ActionType::insert, 2, "cd")); uh.CompletedRedoStep(); } REQUIRE(!uh.IsSavePoint()); } SECTION("SimpleContainer") { bool startSequence = false; const char *val = uh.AppendAction(ActionType::container, 1000, nullptr, 0, startSequence, true); REQUIRE(startSequence); REQUIRE(!val); val = uh.AppendAction(ActionType::container, 1001, nullptr, 0, startSequence, true); REQUIRE(!startSequence); REQUIRE(!val); } SECTION("CoalesceContainer") { bool startSequence = false; const char *val = uh.AppendAction(ActionType::insert, 0, "ab", 2, startSequence, true); REQUIRE(memcmp(val, "ab", 2) == 0); REQUIRE(startSequence); val = uh.AppendAction(ActionType::container, 1000, nullptr, 0, startSequence, true); REQUIRE(!startSequence); // container actions do not have text data, just the token store in position REQUIRE(!val); uh.AppendAction(ActionType::container, 1001, nullptr, 0, startSequence, true); REQUIRE(!startSequence); // This is a coalescible change since the container actions are skipped to determine compatibility val = uh.AppendAction(ActionType::insert, 2, "cd", 2, startSequence, true); REQUIRE(memcmp(val, "cd", 2) == 0); REQUIRE(!startSequence); // Break the sequence with a non-coalescible container action uh.AppendAction(ActionType::container, 1002, nullptr, 0, startSequence, false); REQUIRE(startSequence); { const int steps = uh.StartUndo(); REQUIRE(steps == 1); const Action actionContainer = uh.GetUndoStep(); REQUIRE(EqualContainerAction(actionContainer, 1002)); REQUIRE(actionContainer.mayCoalesce == false); uh.CompletedUndoStep(); } { const int steps = uh.StartUndo(); REQUIRE(steps == 4); const Action actionInsert = uh.GetUndoStep(); REQUIRE(Equal(actionInsert, ActionType::insert, 2, "cd")); uh.CompletedUndoStep(); { const Action actionContainer = uh.GetUndoStep(); REQUIRE(EqualContainerAction(actionContainer, 1001)); uh.CompletedUndoStep(); } { const Action actionContainer = uh.GetUndoStep(); REQUIRE(EqualContainerAction(actionContainer, 1000)); uh.CompletedUndoStep(); } { const Action actionInsert1 = uh.GetUndoStep(); REQUIRE(Equal(actionInsert1, ActionType::insert, 0, "ab")); uh.CompletedUndoStep(); } } // Reached beginning REQUIRE(!uh.CanUndo()); } SECTION("Grouping") { uh.BeginUndoAction(); bool startSequence = false; const char *val = uh.AppendAction(ActionType::insert, 0, "ab", 2, startSequence, true); REQUIRE(memcmp(val, "ab", 2) == 0); REQUIRE(startSequence); REQUIRE(!uh.IsSavePoint()); REQUIRE(uh.AfterSavePoint()); REQUIRE(uh.CanUndo()); REQUIRE(!uh.CanRedo()); val = uh.AppendAction(ActionType::remove, 0, "ab", 2, startSequence, true); REQUIRE(memcmp(val, "ab", 2) == 0); REQUIRE(!startSequence); val = uh.AppendAction(ActionType::insert, 0, "cde", 3, startSequence, true); REQUIRE(memcmp(val, "cde", 3) == 0); REQUIRE(!startSequence); uh.EndUndoAction(); // Undoing { const int steps = uh.StartUndo(); REQUIRE(steps == 3); const Action action3 = uh.GetUndoStep(); REQUIRE(Equal(action3, ActionType::insert, 0, "cde")); uh.CompletedUndoStep(); const Action action2 = uh.GetUndoStep(); REQUIRE(Equal(action2, ActionType::remove, 0, "ab")); uh.CompletedUndoStep(); const Action action1 = uh.GetUndoStep(); REQUIRE(Equal(action1, ActionType::insert, 0, "ab")); uh.CompletedUndoStep(); } REQUIRE(uh.IsSavePoint()); // Redoing { const int steps = uh.StartRedo(); REQUIRE(steps == 3); const Action action1 = uh.GetRedoStep(); REQUIRE(Equal(action1, ActionType::insert, 0, "ab")); uh.CompletedRedoStep(); const Action action2 = uh.GetRedoStep(); REQUIRE(Equal(action2, ActionType::remove, 0, "ab")); uh.CompletedRedoStep(); const Action action3 = uh.GetRedoStep(); REQUIRE(Equal(action3, ActionType::insert, 0, "cde")); uh.CompletedRedoStep(); } REQUIRE(!uh.IsSavePoint()); } SECTION("DeepGroup") { uh.BeginUndoAction(); uh.BeginUndoAction(); bool startSequence = false; const char *val = uh.AppendAction(ActionType::insert, 0, "ab", 2, startSequence, true); REQUIRE(memcmp(val, "ab", 2) == 0); REQUIRE(startSequence); val = uh.AppendAction(ActionType::container, 1000, nullptr, 0, startSequence, false); REQUIRE(!val); REQUIRE(!startSequence); val = uh.AppendAction(ActionType::remove, 0, "ab", 2, startSequence, true); REQUIRE(memcmp(val, "ab", 2) == 0); REQUIRE(!startSequence); val = uh.AppendAction(ActionType::insert, 0, "cde", 3, startSequence, true); REQUIRE(memcmp(val, "cde", 3) == 0); REQUIRE(!startSequence); uh.EndUndoAction(); uh.EndUndoAction(); const int steps = uh.StartUndo(); REQUIRE(steps == 4); } SECTION("Tentative") { REQUIRE(!uh.TentativeActive()); REQUIRE(uh.TentativeSteps() == -1); uh.TentativeStart(); REQUIRE(uh.TentativeActive()); REQUIRE(uh.TentativeSteps() == 0); bool startSequence = false; uh.AppendAction(ActionType::insert, 0, "ab", 2, startSequence, true); REQUIRE(uh.TentativeActive()); REQUIRE(uh.TentativeSteps() == 1); REQUIRE(uh.CanUndo()); uh.TentativeCommit(); REQUIRE(!uh.TentativeActive()); REQUIRE(uh.TentativeSteps() == -1); REQUIRE(uh.CanUndo()); // TentativeUndo is the other important operation but it is performed by Document so add a local equivalent uh.TentativeStart(); uh.AppendAction(ActionType::remove, 0, "ab", 2, startSequence, false); uh.AppendAction(ActionType::insert, 0, "ab", 2, startSequence, true); REQUIRE(uh.TentativeActive()); // The first TentativeCommit didn't seal off the first action so it is still undoable REQUIRE(uh.TentativeSteps() == 2); REQUIRE(uh.CanUndo()); TentativeUndo(uh); REQUIRE(!uh.TentativeActive()); REQUIRE(uh.TentativeSteps() == -1); REQUIRE(uh.CanUndo()); } } TEST_CASE("UndoActions") { UndoActions ua; SECTION("Basics") { ua.PushBack(); REQUIRE(ua.SSize() == 1); ua.Create(0, ActionType::insert, 0, 2, false); REQUIRE(ua.AtStart(0)); REQUIRE(ua.LengthTo(0) == 0); REQUIRE(ua.AtStart(1)); REQUIRE(ua.LengthTo(1) == 2); ua.PushBack(); REQUIRE(ua.SSize() == 2); ua.Create(0, ActionType::insert, 0, 2, false); REQUIRE(ua.SSize() == 2); ua.Truncate(1); REQUIRE(ua.SSize() == 1); ua.Clear(); REQUIRE(ua.SSize() == 0); } } TEST_CASE("CharacterIndex") { CellBuffer cb(true, false); SECTION("Setup") { REQUIRE(cb.LineCharacterIndex() == LineCharacterIndexType::None); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 0); cb.SetUTF8Substance(true); cb.AllocateLineCharacterIndex(LineCharacterIndexType::Utf16); REQUIRE(cb.LineCharacterIndex() == LineCharacterIndexType::Utf16); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 0); cb.ReleaseLineCharacterIndex(LineCharacterIndexType::Utf16); REQUIRE(cb.LineCharacterIndex() == LineCharacterIndexType::None); } SECTION("Insertion") { cb.SetUTF8Substance(true); cb.AllocateLineCharacterIndex(LineCharacterIndexType::Utf16 | LineCharacterIndexType::Utf32); bool startSequence = false; cb.InsertString(0, "a", 1, startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 1); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 1); constexpr std::string_view hwair = "\xF0\x90\x8D\x88"; cb.InsertString(0, hwair.data(), hwair.length(), startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 3); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 2); } SECTION("Deletion") { cb.SetUTF8Substance(true); cb.AllocateLineCharacterIndex(LineCharacterIndexType::Utf16 | LineCharacterIndexType::Utf32); bool startSequence = false; constexpr std::string_view hwair = "a\xF0\x90\x8D\x88z"; cb.InsertString(0, hwair.data(), hwair.length(), startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 4); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 3); cb.DeleteChars(5, 1, startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 3); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 2); cb.DeleteChars(1, 4, startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 1); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 1); } SECTION("Insert Complex") { cb.SetUTF8Substance(true); cb.SetLineEndTypes(LineEndType::Unicode); cb.AllocateLineCharacterIndex(LineCharacterIndexType::Utf16 | LineCharacterIndexType::Utf32); bool startSequence = false; // 3 lines of text containing 8 bytes constexpr std::string_view data = "a\n\xF0\x90\x8D\x88\nz"; cb.InsertString(0, data.data(), data.length(), startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 2); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 5); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf16) == 6); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 2); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf32) == 4); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf32) == 5); // Insert a new line at end -> "a\n\xF0\x90\x8D\x88\nz\n" 4 lines // Last line empty cb.InsertString(data.length(), "\n", 1, startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 2); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 5); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf16) == 7); REQUIRE(cb.IndexLineStart(4, LineCharacterIndexType::Utf16) == 7); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 2); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf32) == 4); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf32) == 6); REQUIRE(cb.IndexLineStart(4, LineCharacterIndexType::Utf32) == 6); // Insert a new line before end -> "a\n\xF0\x90\x8D\x88\nz\n\n" 5 lines cb.InsertString(data.length(), "\n", 1, startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 2); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 5); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf16) == 7); REQUIRE(cb.IndexLineStart(4, LineCharacterIndexType::Utf16) == 8); REQUIRE(cb.IndexLineStart(5, LineCharacterIndexType::Utf16) == 8); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 2); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf32) == 4); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf32) == 6); REQUIRE(cb.IndexLineStart(4, LineCharacterIndexType::Utf32) == 7); REQUIRE(cb.IndexLineStart(5, LineCharacterIndexType::Utf32) == 7); // Insert a valid 3-byte UTF-8 character at start -> // "\xE2\x82\xACa\n\xF0\x90\x8D\x88\nz\n\n" 5 lines constexpr std::string_view euro = "\xE2\x82\xAC"; cb.InsertString(0, euro.data(), euro.length(), startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 3); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 6); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf16) == 8); REQUIRE(cb.IndexLineStart(4, LineCharacterIndexType::Utf16) == 9); REQUIRE(cb.IndexLineStart(5, LineCharacterIndexType::Utf16) == 9); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 3); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf32) == 5); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf32) == 7); REQUIRE(cb.IndexLineStart(4, LineCharacterIndexType::Utf32) == 8); REQUIRE(cb.IndexLineStart(5, LineCharacterIndexType::Utf32) == 8); // Insert a lone lead byte implying a 3 byte character at start of line 2 -> // "\xE2\x82\xACa\n\EF\xF0\x90\x8D\x88\nz\n\n" 5 lines // Should be treated as a single byte character constexpr std::string_view lead = "\xEF"; cb.InsertString(5, lead.data(), lead.length(), startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 3); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 7); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf16) == 9); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 3); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf32) == 6); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf32) == 8); // Insert an ASCII lead byte inside the 3-byte initial character -> // "\xE2!\x82\xACa\n\EF\xF0\x90\x8D\x88\nz\n\n" 5 lines // It should b treated as a single character and should cause the // byte before and the 2 bytes after also be each treated as singles // so 3 more characters on line 0. constexpr std::string_view ascii = "!"; cb.InsertString(1, ascii.data(), ascii.length(), startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 6); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 10); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 6); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf32) == 9); // Insert a NEL after the '!' to trigger the utf8 line end case -> // "\xE2!\xC2\x85 \x82\xACa\n \EF\xF0\x90\x8D\x88\n z\n\n" 5 lines constexpr std::string_view nel = "\xC2\x85"; cb.InsertString(2, nel.data(), nel.length(), startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 3); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 7); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf16) == 11); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 3); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf32) == 7); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf32) == 10); } SECTION("Delete Multiple lines") { cb.SetUTF8Substance(true); cb.AllocateLineCharacterIndex(LineCharacterIndexType::Utf16 | LineCharacterIndexType::Utf32); bool startSequence = false; // 3 lines of text containing 8 bytes constexpr std::string_view data = "a\n\xF0\x90\x8D\x88\nz\nc"; cb.InsertString(0, data.data(), data.length(), startSequence); // Delete first 2 new lines -> "az\nc" cb.DeleteChars(1, data.length() - 4, startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 3); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 4); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 3); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf32) == 4); } SECTION("Delete Complex") { cb.SetUTF8Substance(true); cb.AllocateLineCharacterIndex(LineCharacterIndexType::Utf16 | LineCharacterIndexType::Utf32); bool startSequence = false; // 3 lines of text containing 8 bytes constexpr std::string_view data = "a\n\xF0\x90\x8D\x88\nz"; cb.InsertString(0, data.data(), data.length(), startSequence); // Delete lead byte from character on line 1 -> // "a\n\x90\x8D\x88\nz" // line 1 becomes 4 single byte characters cb.DeleteChars(2, 1, startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 2); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 6); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf16) == 7); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 2); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf32) == 6); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf32) == 7); // Delete first new line -> // "a\x90\x8D\x88\nz" // Only 2 lines with line 0 containing 5 single byte characters cb.DeleteChars(1, 1, startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 5); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 6); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 5); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf32) == 6); // Restore lead byte from character on line 0 making a 4-byte character -> // "a\xF0\x90\x8D\x88\nz" constexpr std::string_view lead4 = "\xF0"; cb.InsertString(1, lead4.data(), lead4.length(), startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 4); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 5); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf32) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf32) == 3); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf32) == 4); } SECTION("Insert separates new line bytes") { cb.SetUTF8Substance(true); cb.AllocateLineCharacterIndex(LineCharacterIndexType::Utf16 | LineCharacterIndexType::Utf32); bool startSequence = false; // 2 lines of text containing 4 bytes constexpr std::string_view data = "a\r\nb"; cb.InsertString(0, data.data(), data.length(), startSequence); // 3 lines of text containing 5 bytes -> // "a\r!\nb" constexpr std::string_view ascii = "!"; cb.InsertString(2, ascii.data(), ascii.length(), startSequence); REQUIRE(cb.IndexLineStart(0, LineCharacterIndexType::Utf16) == 0); REQUIRE(cb.IndexLineStart(1, LineCharacterIndexType::Utf16) == 2); REQUIRE(cb.IndexLineStart(2, LineCharacterIndexType::Utf16) == 4); REQUIRE(cb.IndexLineStart(3, LineCharacterIndexType::Utf16) == 5); } } TEST_CASE("ChangeHistory") { ChangeHistory il; struct Spanner { Sci::Position position = 0; Sci::Position length = 0; }; SECTION("Start") { REQUIRE(il.Length() == 0); REQUIRE(il.DeletionCount(0,0) == 0); REQUIRE(il.EditionAt(0) == 0); REQUIRE(il.EditionEndRun(0) == 0); REQUIRE(il.EditionDeletesAt(0) == 0); REQUIRE(il.EditionNextDelete(0) == 1); } SECTION("Some Space") { il.Insert(0, 10, false, true); REQUIRE(il.Length() == 10); REQUIRE(il.DeletionCount(0,10) == 0); REQUIRE(il.EditionAt(0) == 0); REQUIRE(il.EditionEndRun(0) == 10); REQUIRE(il.EditionDeletesAt(0) == 0); REQUIRE(il.EditionNextDelete(0) == 10); REQUIRE(il.EditionDeletesAt(10) == 0); REQUIRE(il.EditionNextDelete(10) == 11); } SECTION("An insert") { il.Insert(0, 7, false, true); il.SetSavePoint(); il.Insert(2, 3, true, true); REQUIRE(il.Length() == 10); REQUIRE(il.DeletionCount(0,10) == 0); REQUIRE(il.EditionAt(0) == 0); REQUIRE(il.EditionEndRun(0) == 2); REQUIRE(il.EditionAt(2) == 2); REQUIRE(il.EditionEndRun(2) == 5); REQUIRE(il.EditionAt(5) == 0); REQUIRE(il.EditionEndRun(5) == 10); REQUIRE(il.EditionAt(10) == 0); REQUIRE(il.EditionDeletesAt(0) == 0); REQUIRE(il.EditionNextDelete(0) == 10); REQUIRE(il.EditionDeletesAt(10) == 0); } SECTION("A delete") { il.Insert(0, 10, false, true); il.SetSavePoint(); il.DeleteRangeSavingHistory(2, 3, true, false); REQUIRE(il.Length() == 7); REQUIRE(il.DeletionCount(0,7) == 1); REQUIRE(il.EditionAt(0) == 0); REQUIRE(il.EditionEndRun(0) == 7); REQUIRE(il.EditionAt(7) == 0); REQUIRE(il.EditionDeletesAt(0) == 0); const EditionSet one{ 2 }; REQUIRE(il.EditionNextDelete(0) == 2); REQUIRE(il.EditionDeletesAt(2) == 2); REQUIRE(il.EditionNextDelete(2) == 7); REQUIRE(il.EditionDeletesAt(7) == 0); } SECTION("Insert, delete, and undo") { il.Insert(0, 9, false, true); il.SetSavePoint(); il.Insert(3, 1, true, true); REQUIRE(il.EditionEndRun(0) == 3); REQUIRE(il.EditionAt(3) == 2); REQUIRE(il.EditionEndRun(3) == 4); REQUIRE(il.EditionAt(4) == 0); il.DeleteRangeSavingHistory(2, 3, true, false); REQUIRE(il.Length() == 7); REQUIRE(il.DeletionCount(0,7) == 1); REQUIRE(il.EditionAt(0) == 0); REQUIRE(il.EditionEndRun(0) == 7); REQUIRE(il.EditionAt(7) == 0); REQUIRE(il.EditionDeletesAt(0) == 0); const EditionSet one{ 2 }; REQUIRE(il.EditionNextDelete(0) == 2); REQUIRE(il.EditionDeletesAt(2) == 2); REQUIRE(il.EditionNextDelete(2) == 7); REQUIRE(il.EditionDeletesAt(7) == 0); // Undo in detail (normally inside CellBuffer::PerformUndoStep) il.UndoDeleteStep(2, 3, false); REQUIRE(il.Length() == 10); REQUIRE(il.DeletionCount(0, 10) == 0); // The insertion has reappeared REQUIRE(il.EditionEndRun(0) == 3); REQUIRE(il.EditionAt(3) == 2); REQUIRE(il.EditionEndRun(3) == 4); REQUIRE(il.EditionAt(4) == 0); } SECTION("Deletes") { il.Insert(0, 10, false, true); il.SetSavePoint(); il.DeleteRangeSavingHistory(2, 3, true, false); REQUIRE(il.Length() == 7); REQUIRE(il.DeletionCount(0,7) == 1); REQUIRE(il.EditionDeletesAt(0) == 0); REQUIRE(il.EditionNextDelete(0) == 2); REQUIRE(il.EditionDeletesAt(2) == 2); REQUIRE(il.EditionNextDelete(2) == 7); REQUIRE(il.EditionDeletesAt(7) == 0); il.DeleteRangeSavingHistory(2, 1, true, false); REQUIRE(il.Length() == 6); REQUIRE(il.DeletionCount(0,6) == 2); REQUIRE(il.EditionDeletesAt(0) == 0); REQUIRE(il.EditionNextDelete(0) == 2); REQUIRE(il.EditionDeletesAt(2) == 2); REQUIRE(il.EditionNextDelete(2) == 6); REQUIRE(il.EditionDeletesAt(6) == 0); // Undo in detail (normally inside CellBuffer::PerformUndoStep) il.UndoDeleteStep(2, 1, false); REQUIRE(il.Length() == 7); REQUIRE(il.DeletionCount(0, 7) == 1); // Undo in detail (normally inside CellBuffer::PerformUndoStep) il.UndoDeleteStep(2, 3, false); REQUIRE(il.Length() == 10); REQUIRE(il.DeletionCount(0, 10) == 0); } SECTION("Deletes 101") { // Deletes that hit the start and end permanent positions il.Insert(0, 3, false, true); il.SetSavePoint(); REQUIRE(il.DeletionCount(0, 2) == 0); il.DeleteRangeSavingHistory(1, 1, true, false); REQUIRE(il.DeletionCount(0,2) == 1); const EditionSet at1 = { {2, 1} }; REQUIRE(il.DeletionsAt(1) == at1); il.DeleteRangeSavingHistory(1, 1, false, false); REQUIRE(il.DeletionCount(0,1) == 2); const EditionSet at2 = { {2, 1}, {3, 1} }; REQUIRE(il.DeletionsAt(1) == at2); il.DeleteRangeSavingHistory(0, 1, false, false); const EditionSet at3 = { {2, 1}, {3, 2} }; REQUIRE(il.DeletionsAt(0) == at3); REQUIRE(il.DeletionCount(0,0) == 3); // Undo them il.UndoDeleteStep(0, 1, false); REQUIRE(il.DeletionCount(0, 1) == 2); REQUIRE(il.DeletionsAt(1) == at2); il.UndoDeleteStep(1, 1, false); REQUIRE(il.DeletionCount(0, 2) == 1); REQUIRE(il.DeletionsAt(1) == at1); il.UndoDeleteStep(1, 1, false); REQUIRE(il.DeletionCount(0, 3) == 0); } SECTION("Deletes Stack") { std::vector<Spanner> spans = { {5, 1}, {4, 3}, {1, 1}, {1, 1}, {0, 1}, {0, 3}, }; // Deletes that hit the start and end permanent positions il.Insert(0, 10, false, true); REQUIRE(il.Length() == 10); il.SetSavePoint(); REQUIRE(il.DeletionCount(0, 10) == 0); for (size_t i = 0; i < std::size(spans); i++) { il.DeleteRangeSavingHistory(spans[i].position, spans[i].length, false, false); } REQUIRE(il.Length() == 0); for (size_t j = 0; j < std::size(spans); j++) { const size_t i = std::size(spans) - j - 1; il.UndoDeleteStep(spans[i].position, spans[i].length, false); } REQUIRE(il.DeletionCount(0, 10) == 0); REQUIRE(il.Length() == 10); } SECTION("Delete Contiguous Backward") { // Deletes that touch constexpr Sci::Position length = 20; constexpr Sci::Position rounds = 8; il.Insert(0, length, false, true); REQUIRE(il.Length() == length); il.SetSavePoint(); for (Sci::Position i = 0; i < rounds; i++) { il.DeleteRangeSavingHistory(9-i, 1, false, false); } constexpr Sci::Position lengthAfterDeletions = length - rounds; REQUIRE(il.Length() == lengthAfterDeletions); REQUIRE(il.DeletionCount(0, lengthAfterDeletions) == rounds); for (Sci::Position j = 0; j < rounds; j++) { il.UndoDeleteStep(2+j, 1, false); } // Restored to original REQUIRE(il.DeletionCount(0, length) == 0); REQUIRE(il.Length() == length); } SECTION("Delete Contiguous Forward") { // Deletes that touch constexpr size_t length = 20; constexpr size_t rounds = 8; il.Insert(0, length, false, true); REQUIRE(il.Length() == length); il.SetSavePoint(); for (size_t i = 0; i < rounds; i++) { il.DeleteRangeSavingHistory(2,1, false, false); } constexpr size_t lengthAfterDeletions = length - rounds; REQUIRE(il.Length() == lengthAfterDeletions); REQUIRE(il.DeletionCount(0, lengthAfterDeletions) == rounds); for (size_t j = 0; j < rounds; j++) { il.UndoDeleteStep(2, 1, false); } // Restored to original REQUIRE(il.Length() == length); REQUIRE(il.DeletionCount(0, length) == 0); } } struct InsertionResult { Sci::Position position; Sci::Position length; int state; bool operator==(const InsertionResult &other) const noexcept { return position == other.position && length == other.length && state == other.state; } }; std::ostream &operator << (std::ostream &os, InsertionResult const &value) { os << value.position << " " << value.length << " " << value.state; return os; } using Insertions = std::vector<InsertionResult>; std::ostream &operator << (std::ostream &os, Insertions const &value) { os << "("; for (const InsertionResult &el : value) { os << "(" << el << ") "; } os << ")"; return os; } Insertions HistoryInsertions(const CellBuffer &cb) { Insertions result; Sci::Position startPos = 0; while (startPos < cb.Length()) { const Sci::Position endPos = cb.EditionEndRun(startPos); const int ed = cb.EditionAt(startPos); if (ed) { result.push_back({ startPos, endPos - startPos, ed }); } startPos = endPos; } return result; } struct DeletionResult { Sci::Position position; int state; bool operator==(const DeletionResult &other) const noexcept { return position == other.position && state == other.state; } }; std::ostream &operator << (std::ostream &os, DeletionResult const &value) { os << value.position << " " << value.state; return os; } using Deletions = std::vector<DeletionResult>; std::ostream &operator << (std::ostream &os, Deletions const &value) { os << "("; for (const DeletionResult &el : value) { os << "(" << el << ") "; } os << ")"; return os; } Deletions HistoryDeletions(const CellBuffer &cb) { Deletions result; Sci::Position positionDeletion = 0; while (positionDeletion <= cb.Length()) { const unsigned int editions = cb.EditionDeletesAt(positionDeletion); if (editions & 1) { result.push_back({ positionDeletion, 1 }); } if (editions & 2) { result.push_back({ positionDeletion, 2 }); } if (editions & 4) { result.push_back({ positionDeletion, 3 }); } if (editions & 8) { result.push_back({ positionDeletion, 4 }); } positionDeletion = cb.EditionNextDelete(positionDeletion); } return result; } struct History { Insertions insertions; Deletions deletions; bool operator==(const History &other) const { return insertions == other.insertions && deletions == other.deletions; } }; std::ostream &operator << (std::ostream &os, History const &value) { os << value.insertions << " " << value.deletions; return os; } History HistoryOf(const CellBuffer &cb) { return { HistoryInsertions(cb), HistoryDeletions(cb) }; } void UndoBlock(CellBuffer &cb) { const int steps = cb.StartUndo(); for (int step = 0; step < steps; step++) { cb.PerformUndoStep(); } } void RedoBlock(CellBuffer &cb) { const int steps = cb.StartRedo(); for (int step = 0; step < steps; step++) { cb.PerformRedoStep(); } } TEST_CASE("CellBufferWithChangeHistory") { SECTION("StraightUndoRedoSaveRevertRedo") { CellBuffer cb(true, false); cb.SetUndoCollection(false); constexpr std::string_view sInsert = "abcdefghijklmnopqrstuvwxyz"; bool startSequence = false; cb.InsertString(0, sInsert.data(), sInsert.length(), startSequence); cb.SetUndoCollection(true); cb.SetSavePoint(); cb.ChangeHistorySet(true); const History history0 { {}, {} }; REQUIRE(HistoryOf(cb) == history0); // 1 cb.InsertString(4, "_", 1, startSequence); const History history1{ {{4, 1, 3}}, {} }; REQUIRE(HistoryOf(cb) == history1); // 2 cb.DeleteChars(2, 1, startSequence); const History history2{ {{3, 1, 3}}, {{2, 3}} }; REQUIRE(HistoryOf(cb) == history2); // 3 cb.InsertString(1, "[!]", 3, startSequence); const History history3{ { {1, 3, 3}, {6, 1, 3} }, { {5, 3} } }; REQUIRE(HistoryOf(cb) == history3); // 4 cb.DeleteChars(2, 1, startSequence); // Inside an insertion const History history4{ { {1, 2, 3}, {5, 1, 3} }, { {2, 3}, {4, 3} }}; REQUIRE(HistoryOf(cb) == history4); // 5 Delete all the insertions and deletions cb.DeleteChars(1, 6, startSequence); // Inside an insertion const History history5{ { }, { {1, 3} } }; REQUIRE(HistoryOf(cb) == history5); // Undo all UndoBlock(cb); REQUIRE(HistoryOf(cb) == history4); UndoBlock(cb); REQUIRE(HistoryOf(cb) == history3); UndoBlock(cb); REQUIRE(HistoryOf(cb) == history2); UndoBlock(cb); REQUIRE(HistoryOf(cb) == history1); UndoBlock(cb); REQUIRE(HistoryOf(cb) == history0); // Redo all RedoBlock(cb); REQUIRE(HistoryOf(cb) == history1); RedoBlock(cb); REQUIRE(HistoryOf(cb) == history2); RedoBlock(cb); REQUIRE(HistoryOf(cb) == history3); RedoBlock(cb); REQUIRE(HistoryOf(cb) == history4); RedoBlock(cb); REQUIRE(HistoryOf(cb) == history5); cb.SetSavePoint(); const History history5s{ { }, { {1, 2} } }; REQUIRE(HistoryOf(cb) == history5s); // Change past save point cb.InsertString(4, "123", 3, startSequence); const History history6{ { {4, 3, 3} }, { {1, 2} } }; REQUIRE(HistoryOf(cb) == history6); // Undo to save point: same as 5 but with save state instead of unsaved UndoBlock(cb); REQUIRE(HistoryOf(cb) == history5s); // Reverting past save point, similar to 4 but with most saved and // reverted delete at 1 UndoBlock(cb); // Reinsert most of original changes const History history4s{ { {1, 2, 4}, {3, 2, 1}, {5, 1, 4}, {6, 1, 1} }, { {2, 2}, {4, 2} } }; REQUIRE(HistoryOf(cb) == history4s); UndoBlock(cb); // Reinsert "!", const History history3s{ { {1, 3, 4}, {4, 2, 1}, {6, 1, 4}, {7, 1, 1} }, { {5, 2} } }; REQUIRE(HistoryOf(cb) == history3s); UndoBlock(cb); // Revert insertion of [!] const History history2s{ { {1, 2, 1}, {3, 1, 4}, {4, 1, 1} }, { {1, 1}, {2, 2} } }; REQUIRE(HistoryOf(cb) == history2s); UndoBlock(cb); // Revert deletion, inserts at 2 const History history1s{ { {1, 3, 1}, {4, 1, 4}, {5, 1, 1} }, { {1, 1} } }; REQUIRE(HistoryOf(cb) == history1s); UndoBlock(cb); // Revert insertion of _ at 4, drops middle insertion run // So merges down to 1 insertion const History history0s{ { {1, 4, 1} }, { {1, 1}, {4, 1} } }; REQUIRE(HistoryOf(cb) == history0s); // At origin but with changes from disk // Now redo the steps RedoBlock(cb); REQUIRE(HistoryOf(cb) == history1s); RedoBlock(cb); REQUIRE(HistoryOf(cb) == history2s); RedoBlock(cb); REQUIRE(HistoryOf(cb) == history3s); RedoBlock(cb); REQUIRE(HistoryOf(cb) == history4s); RedoBlock(cb); REQUIRE(HistoryOf(cb) == history5s); RedoBlock(cb); REQUIRE(HistoryOf(cb) == history6); } SECTION("Detached") { CellBuffer cb(true, false); cb.SetUndoCollection(false); constexpr std::string_view sInsert = "abcdefghijklmnopqrstuvwxyz"; bool startSequence = false; cb.InsertString(0, sInsert.data(), sInsert.length(), startSequence); cb.SetUndoCollection(true); cb.SetSavePoint(); cb.ChangeHistorySet(true); const History history0{ {}, {} }; REQUIRE(HistoryOf(cb) == history0); // 1 cb.InsertString(4, "_", 1, startSequence); const History history1{ {{4, 1, 3}}, {} }; REQUIRE(HistoryOf(cb) == history1); // 2 cb.DeleteChars(2, 1, startSequence); const History history2{ {{3, 1, 3}}, {{2, 3}} }; REQUIRE(HistoryOf(cb) == history2); cb.SetSavePoint(); UndoBlock(cb); const History history1s{ {{2, 1, 1}, {4, 1, 2}}, {} }; REQUIRE(HistoryOf(cb) == history1s); cb.InsertString(6, "()", 2, startSequence); const History detached2{ {{2, 1, 1}, {4, 1, 2}, {6, 2, 3}}, {} }; REQUIRE(HistoryOf(cb) == detached2); cb.DeleteChars(9, 3, startSequence); const History detached3{ {{2, 1, 1}, {4, 1, 2}, {6, 2, 3}}, {{9,3}} }; REQUIRE(HistoryOf(cb) == detached3); UndoBlock(cb); REQUIRE(HistoryOf(cb) == detached2); UndoBlock(cb); const History detached1{ {{2, 1, 1}, {4, 1, 2}}, {} }; REQUIRE(HistoryOf(cb) == detached1); UndoBlock(cb); const History detached0{ {{2, 1, 1}}, {{4,1}} }; REQUIRE(HistoryOf(cb) == detached0); REQUIRE(!cb.CanUndo()); RedoBlock(cb); REQUIRE(HistoryOf(cb) == detached1); RedoBlock(cb); REQUIRE(HistoryOf(cb) == detached2); RedoBlock(cb); REQUIRE(HistoryOf(cb) == detached3); } } namespace { void PushUndoAction(CellBuffer &cb, int type, Sci::Position pos, std::string_view sv) { cb.PushUndoActionType(type, pos); cb.ChangeLastUndoActionText(sv.length(), sv.data()); } } TEST_CASE("CellBufferLoadUndoHistory") { CellBuffer cb(false, false); constexpr int remove = 1; constexpr int insert = 0; SECTION("Basics") { cb.SetUndoCollection(false); constexpr std::string_view sInsert = "abcdef"; bool startSequence = false; cb.InsertString(0, sInsert.data(), sInsert.length(), startSequence); cb.SetUndoCollection(true); cb.ChangeHistorySet(true); // Create an undo history that matches the contents at current point 2 // So, 2 actions; current point; 2 actions // a_cdef PushUndoAction(cb, remove, 1, "_"); // acdef PushUndoAction(cb, insert, 1, "b"); // abcdef -> current PushUndoAction(cb, remove, 3, "d"); // abcef -> save PushUndoAction(cb, insert, 3, "*"); // abc*ef cb.SetUndoSavePoint(3); cb.SetUndoDetach(-1); cb.SetUndoTentative(-1); cb.SetUndoCurrent(2); // 2nd insertion is removed from change history as it isn't visible and isn't saved // 2nd deletion is visible (as insertion) as it was saved but then reverted to original // 1st insertion and 1st deletion are both visible as saved const History hist{ {{1, 1, changeSaved}, {3, 1, changeRevertedOriginal}}, {{2, changeSaved}} }; REQUIRE(HistoryOf(cb) == hist); } SECTION("Detached") { cb.SetUndoCollection(false); constexpr std::string_view sInsert = "a-b=cdef"; bool startSequence = false; cb.InsertString(0, sInsert.data(), sInsert.length(), startSequence); cb.SetUndoCollection(true); cb.ChangeHistorySet(true); // Create an undo history that matches the contents at current point 2 which detached at 1 // So, insert saved; insert detached; current point // abcdef PushUndoAction(cb, insert, 1, "-"); // a-bcdef PushUndoAction(cb, insert, 3, "="); // a-b=cdef cb.SetUndoSavePoint(-1); cb.SetUndoDetach(1); cb.SetUndoTentative(-1); cb.SetUndoCurrent(2); // This doesn't show elements due to undo. // There was also a modified delete (reverting the insert) at 3 in the original but that is missing. const History hist{ {{1, 1, changeSaved}, {3, 1, changeModified}}, {} }; REQUIRE(HistoryOf(cb) == hist); } } namespace { // Implement low quality reproducible pseudo-random numbers. // Pseudo-random algorithm based on R. G. Dromey "How to Solve it by Computer" page 122. class RandomSequence { static constexpr int mult = 109; static constexpr int incr = 853; static constexpr int modulus = 4096; int randomValue = 127; public: int Next() noexcept { randomValue = (mult * randomValue + incr) % modulus; return randomValue; } }; } #if 1 TEST_CASE("CellBufferLong") { // Call methods on CellBuffer pseudo-randomly trying to trigger assertion failures CellBuffer cb(true, false); SECTION("Random") { RandomSequence rseq; for (size_t i = 0; i < 20000; i++) { const int r = rseq.Next() % 10; if (r <= 2) { // 30% // Insert text const Sci::Position pos = rseq.Next() % (cb.Length() + 1); const int len = rseq.Next() % 10 + 1; std::string sInsert; for (int j = 0; j < len; j++) { sInsert.push_back(static_cast<char>('a' + j)); } bool startSequence = false; cb.InsertString(pos, sInsert.c_str(), len, startSequence); } else if (r <= 5) { // 30% // Delete Text const Sci::Position pos = rseq.Next() % (cb.Length() + 1); const int len = rseq.Next() % 10 + 1; if (pos + len <= cb.Length()) { bool startSequence = false; cb.DeleteChars(pos, len, startSequence); } } else if (r <= 8) { // 30% // Undo or redo const bool undo = rseq.Next() % 2 == 1; if (undo) { UndoBlock(cb); } else { RedoBlock(cb); } } else { // 10% // Save cb.SetSavePoint(); } } } } #endif
51,542
C++
.cxx
1,395
33.855197
109
0.699523
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,540
testRESearch.cxx
dail8859_NotepadNext/src/scintilla/test/unit/testRESearch.cxx
/** @file testRESearch.cxx ** Unit Tests for Scintilla internal data structures **/ #include <cstddef> #include <cstring> #include <stdexcept> #include <string> #include <string_view> #include <vector> #include <array> #include <optional> #include <algorithm> #include <memory> #include "ScintillaTypes.h" #include "Debugging.h" #include "Position.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "CellBuffer.h" #include "CharClassify.h" #include "RESearch.h" #include "catch.hpp" using namespace Scintilla; using namespace Scintilla::Internal; class StringCI : public CharacterIndexer { std::string s; public: explicit StringCI(std::string_view sv_) : s(sv_) { } virtual ~StringCI() = default; [[nodiscard]] Sci::Position Length() const noexcept { return s.length(); } char CharAt(Sci::Position index) const override { return s.at(index); } Sci::Position MovePositionOutsideChar(Sci::Position pos, [[maybe_unused]] Sci::Position moveDir) const noexcept override { return pos; } [[nodiscard]] std::string GetCharRange(Sci::Position position, Sci::Position lengthRetrieve) const { return s.substr(position, lengthRetrieve); } }; // Test RESearch. TEST_CASE("RESearch") { CharClassify cc; constexpr std::string_view sTextSpace = "Scintilla "; constexpr std::string_view pattern = "[a-z]+"; SECTION("Compile") { RESearch re(&cc); const char *msg = re.Compile(pattern.data(), pattern.length(), true, false); REQUIRE(nullptr == msg); } SECTION("Bug2413") { // Check for https://sourceforge.net/p/scintilla/bugs/2413/ RESearch re(&cc); constexpr std::string_view BOW = "\\<"; constexpr std::string_view EOW = "\\>"; const char *msg = re.Compile(BOW.data(), BOW.length(), true, false); REQUIRE(nullptr == msg); msg = re.Compile(EOW.data(), EOW.length(), true, false); REQUIRE(nullptr == msg); } SECTION("Execute") { RESearch re(&cc); re.Compile(pattern.data(), pattern.length(), true, false); const StringCI sci(sTextSpace); const int x = re.Execute(sci, 0, sci.Length()); REQUIRE(x == 1); REQUIRE(re.bopat[0] == 1); REQUIRE(re.eopat[0] == sci.Length() - 1); } SECTION("Grab") { RESearch re(&cc); re.Compile(pattern.data(), pattern.length(), true, false); const StringCI sci(sTextSpace); re.Execute(sci, 0, sci.Length()); const std::string pat = sci.GetCharRange(re.bopat[0], re.eopat[0] - re.bopat[0]); REQUIRE(pat == "cintilla"); } }
2,462
C++
.cxx
82
27.853659
123
0.711628
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,543
testDocument.cxx
dail8859_NotepadNext/src/scintilla/test/unit/testDocument.cxx
/** @file testDocument.cxx ** Unit Tests for Scintilla internal data structures **/ #include <cstddef> #include <cstring> #include <stdexcept> #include <string_view> #include <vector> #include <set> #include <optional> #include <algorithm> #include <memory> #include <iostream> #include <fstream> #include <iomanip> #include "ScintillaTypes.h" #include "ILoader.h" #include "ILexer.h" #include "Debugging.h" #include "CharacterCategoryMap.h" #include "Position.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "CellBuffer.h" #include "CharClassify.h" #include "Decoration.h" #include "CaseFolder.h" #include "Document.h" #include "catch.hpp" using namespace Scintilla; using namespace Scintilla::Internal; // set global locale to pass std::regex related tests // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63776 struct GlobalLocaleInitializer { GlobalLocaleInitializer() { try { std::locale::global(std::locale("en_US.UTF-8")); } catch (...) {} } } globalLocaleInitializer; // Test Document. struct Folding { int from; int to; int length; }; // Table of case folding for non-ASCII bytes in Windows Latin code page 1252 const Folding foldings1252[] = { {0x8a, 0x9a, 0x01}, {0x8c, 0x9c, 0x01}, {0x8e, 0x9e, 0x01}, {0x9f, 0xff, 0x01}, {0xc0, 0xe0, 0x17}, {0xd8, 0xf8, 0x07}, }; // Table of case folding for non-ASCII bytes in Windows Russian code page 1251 const Folding foldings1251[] = { {0x80, 0x90, 0x01}, {0x81, 0x83, 0x01}, {0x8a, 0x9a, 0x01}, {0x8c, 0x9c, 0x04}, {0xa1, 0xa2, 0x01}, {0xa3, 0xbc, 0x01}, {0xa5, 0xb4, 0x01}, {0xa8, 0xb8, 0x01}, {0xaa, 0xba, 0x01}, {0xaf, 0xbf, 0x01}, {0xb2, 0xb3, 0x01}, {0xbd, 0xbe, 0x01}, {0xc0, 0xe0, 0x20}, }; std::string ReadFile(const std::string &path) { std::ifstream ifs(path, std::ios::binary); std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); return content; } struct Match { Sci::Position location = 0; Sci::Position length = 0; constexpr Match() = default; constexpr Match(Sci::Position location_, Sci::Position length_=0) : location(location_), length(length_) { } constexpr bool operator==(const Match &other) const { return location == other.location && length == other.length; } }; std::ostream &operator << (std::ostream &os, Match const &value) { os << value.location << "," << value.length; return os; } struct DocPlus { Document document; DocPlus(std::string_view svInitial, int codePage) : document(DocumentOption::Default) { SetCodePage(codePage); document.InsertString(0, svInitial); } void SetCodePage(int codePage) { document.SetDBCSCodePage(codePage); if (codePage == CpUtf8) { document.SetCaseFolder(std::make_unique<CaseFolderUnicode>()); } else { // This case folder will not handle many DBCS cases. Scintilla uses platform-specific code for DBCS // case folding which can not easily be inserted in platform-independent tests. std::unique_ptr<CaseFolderTable> pcft = std::make_unique<CaseFolderTable>(); document.SetCaseFolder(std::move(pcft)); } } void SetSBCSFoldings(const Folding *foldings, size_t length) { std::unique_ptr<CaseFolderTable> pcft = std::make_unique<CaseFolderTable>(); for (size_t block = 0; block < length; block++) { for (int fold = 0; fold < foldings[block].length; fold++) { pcft->SetTranslation(foldings[block].from + fold, foldings[block].to + fold); } } document.SetCaseFolder(std::move(pcft)); } Sci::Position FindNeedle(std::string_view needle, FindOption options, Sci::Position *length) { assert(*length == static_cast<Sci::Position>(needle.length())); return document.FindText(0, document.Length(), needle.data(), options, length); } Sci::Position FindNeedleReverse(std::string_view needle, FindOption options, Sci::Position *length) { assert(*length == static_cast<Sci::Position>(needle.length())); return document.FindText(document.Length(), 0, needle.data(), options, length); } Match FindString(Sci::Position minPos, Sci::Position maxPos, std::string_view needle, FindOption flags) { Sci::Position lengthFinding = needle.length(); const Sci::Position location = document.FindText(minPos, maxPos, needle.data(), flags, &lengthFinding); return { location, lengthFinding }; } std::string Substitute(std::string_view substituteText) { Sci::Position lengthsubstitute = substituteText.length(); std::string substituted = document.SubstituteByPosition(substituteText.data(), &lengthsubstitute); assert(lengthsubstitute == static_cast<Sci::Position>(substituted.length())); return substituted; } void MoveGap(Sci::Position gapNew) { // Move gap to gapNew by inserting document.InsertString(gapNew, "!", 1); // Remove insertion document.DeleteChars(gapNew, 1); } [[nodiscard]] std::string Contents() const { const Sci::Position length = document.Length(); std::string contents(length, 0); document.GetCharRange(contents.data(), 0, length); return contents; } }; void TimeTrace(std::string_view sv, const Catch::Timer &tikka) { std::cout << sv << std::setw(5) << tikka.getElapsedMilliseconds() << " milliseconds" << std::endl; } TEST_CASE("Document") { constexpr std::string_view sText = "Scintilla"; constexpr Sci::Position sLength = sText.length(); constexpr FindOption rePosix = FindOption::RegExp | FindOption::Posix; constexpr FindOption reCxx11 = FindOption::RegExp | FindOption::Cxx11RegEx; SECTION("InsertOneLine") { DocPlus doc("", 0); const Sci::Position length = doc.document.InsertString(0, sText); REQUIRE(sLength == doc.document.Length()); REQUIRE(length == sLength); REQUIRE(1 == doc.document.LinesTotal()); REQUIRE(0 == doc.document.LineStart(0)); REQUIRE(0 == doc.document.LineFromPosition(0)); REQUIRE(0 == doc.document.LineStartPosition(0)); REQUIRE(sLength == doc.document.LineStart(1)); REQUIRE(0 == doc.document.LineFromPosition(static_cast<int>(sLength))); REQUIRE(doc.document.CanUndo()); REQUIRE(!doc.document.CanRedo()); } // Search ranges are from first argument to just before second argument // Arguments are expected to be at character boundaries and will be tweaked if // part way through a character. SECTION("SearchInLatin") { DocPlus doc("abcde", 0); // a b c d e constexpr std::string_view finding = "b"; Sci::Position lengthFinding = finding.length(); Sci::Position location = doc.FindNeedle(finding, FindOption::MatchCase, &lengthFinding); REQUIRE(location == 1); location = doc.FindNeedleReverse(finding, FindOption::MatchCase, &lengthFinding); REQUIRE(location == 1); location = doc.document.FindText(0, 2, finding.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == 1); location = doc.document.FindText(0, 1, finding.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == -1); } SECTION("SearchInBothSegments") { DocPlus doc("ab-ab", 0); // a b - a b constexpr std::string_view finding = "ab"; for (int gapPos = 0; gapPos <= 5; gapPos++) { doc.MoveGap(gapPos); Sci::Position lengthFinding = finding.length(); Sci::Position location = doc.document.FindText(0, doc.document.Length(), finding.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == 0); location = doc.document.FindText(2, doc.document.Length(), finding.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == 3); } } SECTION("InsensitiveSearchInLatin") { DocPlus doc("abcde", 0); // a b c d e constexpr std::string_view finding = "B"; Sci::Position lengthFinding = finding.length(); Sci::Position location = doc.FindNeedle(finding, FindOption::None, &lengthFinding); REQUIRE(location == 1); location = doc.FindNeedleReverse(finding, FindOption::None, &lengthFinding); REQUIRE(location == 1); location = doc.document.FindText(0, 2, finding.data(), FindOption::None, &lengthFinding); REQUIRE(location == 1); location = doc.document.FindText(0, 1, finding.data(), FindOption::None, &lengthFinding); REQUIRE(location == -1); } SECTION("InsensitiveSearchIn1252") { // In Windows Latin, code page 1252, C6 is AE and E6 is ae DocPlus doc("tru\xc6s\xe6t", 0); // t r u AE s ae t doc.SetSBCSFoldings(foldings1252, std::size(foldings1252)); // Search for upper-case AE std::string_view finding = "\xc6"; Sci::Position lengthFinding = finding.length(); Sci::Position location = doc.FindNeedle(finding, FindOption::None, &lengthFinding); REQUIRE(location == 3); location = doc.document.FindText(4, doc.document.Length(), finding.data(), FindOption::None, &lengthFinding); REQUIRE(location == 5); location = doc.FindNeedleReverse(finding, FindOption::None, &lengthFinding); REQUIRE(location == 5); // Search for lower-case ae finding = "\xe6"; location = doc.FindNeedle(finding, FindOption::None, &lengthFinding); REQUIRE(location == 3); location = doc.document.FindText(4, doc.document.Length(), finding.data(), FindOption::None, &lengthFinding); REQUIRE(location == 5); location = doc.FindNeedleReverse(finding, FindOption::None, &lengthFinding); REQUIRE(location == 5); } SECTION("Search2InLatin") { // Checks that the initial '_' and final 'f' are ignored since they are outside the search bounds DocPlus doc("_abcdef", 0); // _ a b c d e f constexpr std::string_view finding = "cd"; Sci::Position lengthFinding = finding.length(); const size_t docLength = doc.document.Length() - 1; Sci::Position location = doc.document.FindText(1, docLength, finding.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == 3); location = doc.document.FindText(docLength, 1, finding.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == 3); location = doc.document.FindText(docLength, 1, "bc", FindOption::MatchCase, &lengthFinding); REQUIRE(location == 2); location = doc.document.FindText(docLength, 1, "ab", FindOption::MatchCase, &lengthFinding); REQUIRE(location == 1); location = doc.document.FindText(docLength, 1, "de", FindOption::MatchCase, &lengthFinding); REQUIRE(location == 4); location = doc.document.FindText(docLength, 1, "_a", FindOption::MatchCase, &lengthFinding); REQUIRE(location == -1); location = doc.document.FindText(docLength, 1, "ef", FindOption::MatchCase, &lengthFinding); REQUIRE(location == -1); lengthFinding = 3; location = doc.document.FindText(docLength, 1, "cde", FindOption::MatchCase, &lengthFinding); REQUIRE(location == 3); } SECTION("SearchInUTF8") { DocPlus doc("ab\xCE\x93" "d", CpUtf8); // a b gamma d constexpr std::string_view finding = "b"; Sci::Position lengthFinding = finding.length(); Sci::Position location = doc.FindNeedle(finding, FindOption::MatchCase, &lengthFinding); REQUIRE(location == 1); location = doc.document.FindText(doc.document.Length(), 0, finding.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == 1); location = doc.document.FindText(0, 1, finding.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == -1); // Check doesn't try to follow a lead-byte past the search end constexpr std::string_view findingUTF = "\xCE\x93"; lengthFinding = findingUTF.length(); location = doc.document.FindText(0, 4, findingUTF.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == 2); // Only succeeds as 3 is partway through character so adjusted to 4 location = doc.document.FindText(0, 3, findingUTF.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == 2); location = doc.document.FindText(0, 2, findingUTF.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == -1); } SECTION("InsensitiveSearchInUTF8") { DocPlus doc("ab\xCE\x93" "d", CpUtf8); // a b gamma d constexpr std::string_view finding = "b"; Sci::Position lengthFinding = finding.length(); Sci::Position location = doc.FindNeedle(finding, FindOption::None, &lengthFinding); REQUIRE(location == 1); location = doc.document.FindText(doc.document.Length(), 0, finding.data(), FindOption::None, &lengthFinding); REQUIRE(location == 1); constexpr std::string_view findingUTF = "\xCE\x93"; lengthFinding = findingUTF.length(); location = doc.FindNeedle(findingUTF, FindOption::None, &lengthFinding); REQUIRE(location == 2); location = doc.document.FindText(doc.document.Length(), 0, findingUTF.data(), FindOption::None, &lengthFinding); REQUIRE(location == 2); location = doc.document.FindText(0, 4, findingUTF.data(), FindOption::None, &lengthFinding); REQUIRE(location == 2); // Only succeeds as 3 is partway through character so adjusted to 4 location = doc.document.FindText(0, 3, findingUTF.data(), FindOption::None, &lengthFinding); REQUIRE(location == 2); location = doc.document.FindText(0, 2, findingUTF.data(), FindOption::None, &lengthFinding); REQUIRE(location == -1); } SECTION("SearchInShiftJIS") { // {CJK UNIFIED IDEOGRAPH-9955} is two bytes: {0xE9, 'b'} in Shift-JIS // The 'b' can be incorrectly matched by the search string 'b' when the search // does not iterate the text correctly. DocPlus doc("ab\xe9" "b ", 932); // a b {CJK UNIFIED IDEOGRAPH-9955} {space} constexpr std::string_view finding = "b"; // Search forwards Sci::Position lengthFinding = finding.length(); Sci::Position location = doc.FindNeedle(finding, FindOption::MatchCase, &lengthFinding); REQUIRE(location == 1); // Search backwards lengthFinding = finding.length(); location = doc.document.FindText(doc.document.Length(), 0, finding.data(), FindOption::MatchCase, &lengthFinding); REQUIRE(location == 1); } SECTION("InsensitiveSearchInShiftJIS") { // {CJK UNIFIED IDEOGRAPH-9955} is two bytes: {0xE9, 'b'} in Shift-JIS // The 'b' can be incorrectly matched by the search string 'b' when the search // does not iterate the text correctly. DocPlus doc("ab\xe9" "b ", 932); // a b {CJK UNIFIED IDEOGRAPH-9955} {space} constexpr std::string_view finding = "b"; // Search forwards Sci::Position lengthFinding = finding.length(); Sci::Position location = doc.FindNeedle(finding, FindOption::None, &lengthFinding); REQUIRE(location == 1); // Search backwards lengthFinding = finding.length(); location = doc.document.FindText(doc.document.Length(), 0, finding.data(), FindOption::None, &lengthFinding); REQUIRE(location == 1); constexpr std::string_view finding932 = "\xe9" "b"; // Search forwards lengthFinding = finding932.length(); location = doc.FindNeedle(finding932, FindOption::None, &lengthFinding); REQUIRE(location == 2); // Search backwards lengthFinding = finding932.length(); location = doc.document.FindText(doc.document.Length(), 0, finding932.data(), FindOption::None, &lengthFinding); REQUIRE(location == 2); location = doc.document.FindText(0, 3, finding932.data(), FindOption::None, &lengthFinding); REQUIRE(location == 2); location = doc.document.FindText(0, 2, finding932.data(), FindOption::None, &lengthFinding); REQUIRE(location == -1); // Can not test case mapping of double byte text as folder available here does not implement this } SECTION("GetCharacterAndWidth DBCS") { Document doc(DocumentOption::Default); doc.SetDBCSCodePage(932); REQUIRE(doc.CodePage() == 932); const Sci::Position length = doc.InsertString(0, "H\x84\xff\x84H", 5); // This text is invalid in code page 932. // A reasonable interpretation is as 4 items: 2 characters and 2 character fragments // The last item is a 2-byte CYRILLIC CAPITAL LETTER ZE character // H [84] [FF] ZE REQUIRE(5 == length); REQUIRE(5 == doc.Length()); Sci::Position width = 0; // test GetCharacterAndWidth() int ch = doc.GetCharacterAndWidth(0, &width); REQUIRE(width == 1); REQUIRE(ch == 'H'); ch = doc.GetCharacterAndWidth(1, &width); REQUIRE(width == 1); REQUIRE(ch == 0x84); width = 0; ch = doc.GetCharacterAndWidth(2, &width); REQUIRE(width == 1); REQUIRE(ch == 0xff); width = 0; ch = doc.GetCharacterAndWidth(3, &width); REQUIRE(width == 2); REQUIRE(ch == 0x8448); // test LenChar() width = doc.LenChar(0); REQUIRE(width == 1); width = doc.LenChar(1); REQUIRE(width == 1); width = doc.LenChar(2); REQUIRE(width == 1); width = doc.LenChar(3); REQUIRE(width == 2); // test MovePositionOutsideChar() Sci::Position pos = doc.MovePositionOutsideChar(1, 1); REQUIRE(pos == 1); pos = doc.MovePositionOutsideChar(2, 1); REQUIRE(pos == 2); pos = doc.MovePositionOutsideChar(3, 1); REQUIRE(pos == 3); pos = doc.MovePositionOutsideChar(4, 1); REQUIRE(pos == 5); pos = doc.MovePositionOutsideChar(1, -1); REQUIRE(pos == 1); pos = doc.MovePositionOutsideChar(2, -1); REQUIRE(pos == 2); pos = doc.MovePositionOutsideChar(3, -1); REQUIRE(pos == 3); pos = doc.MovePositionOutsideChar(4, -1); REQUIRE(pos == 3); // test NextPosition() pos = doc.NextPosition(0, 1); REQUIRE(pos == 1); pos = doc.NextPosition(1, 1); REQUIRE(pos == 2); pos = doc.NextPosition(2, 1); REQUIRE(pos == 3); pos = doc.NextPosition(3, 1); REQUIRE(pos == 5); pos = doc.NextPosition(1, -1); REQUIRE(pos == 0); pos = doc.NextPosition(2, -1); REQUIRE(pos == 1); pos = doc.NextPosition(3, -1); REQUIRE(pos == 2); pos = doc.NextPosition(5, -1); REQUIRE(pos == 3); } SECTION("NextPosition Valid DBCS") { Document doc(DocumentOption::Default); doc.SetDBCSCodePage(932); REQUIRE(doc.CodePage() == 932); // This text is valid in code page 932. // O p e n = U+958B Ku ( O ) U+7DE8 - // U+958B open // U+7DE8 arrange constexpr std::string_view japaneseText = "Open=\x8aJ\x82\xad(O)\x95\xd2-"; const Sci::Position length = doc.InsertString(0, japaneseText); REQUIRE(length == 15); // Forwards REQUIRE(doc.NextPosition( 0, 1) == 1); REQUIRE(doc.NextPosition( 1, 1) == 2); REQUIRE(doc.NextPosition( 2, 1) == 3); REQUIRE(doc.NextPosition( 3, 1) == 4); REQUIRE(doc.NextPosition( 4, 1) == 5); REQUIRE(doc.NextPosition( 5, 1) == 7); // Double byte REQUIRE(doc.NextPosition( 6, 1) == 7); REQUIRE(doc.NextPosition( 7, 1) == 9); // Double byte REQUIRE(doc.NextPosition( 8, 1) == 9); REQUIRE(doc.NextPosition( 9, 1) == 10); REQUIRE(doc.NextPosition(10, 1) == 11); REQUIRE(doc.NextPosition(11, 1) == 12); REQUIRE(doc.NextPosition(12, 1) == 14); // Double byte REQUIRE(doc.NextPosition(13, 1) == 14); REQUIRE(doc.NextPosition(14, 1) == 15); REQUIRE(doc.NextPosition(15, 1) == 15); // Backwards REQUIRE(doc.NextPosition( 0, -1) == 0); REQUIRE(doc.NextPosition( 1, -1) == 0); REQUIRE(doc.NextPosition( 2, -1) == 1); REQUIRE(doc.NextPosition( 3, -1) == 2); REQUIRE(doc.NextPosition( 4, -1) == 3); REQUIRE(doc.NextPosition( 5, -1) == 4); REQUIRE(doc.NextPosition( 6, -1) == 5); // Double byte REQUIRE(doc.NextPosition( 7, -1) == 5); REQUIRE(doc.NextPosition( 8, -1) == 7); // Double byte REQUIRE(doc.NextPosition( 9, -1) == 7); REQUIRE(doc.NextPosition(10, -1) == 9); REQUIRE(doc.NextPosition(11, -1) == 10); REQUIRE(doc.NextPosition(12, -1) == 11); REQUIRE(doc.NextPosition(13, -1) == 12); // Double byte REQUIRE(doc.NextPosition(14, -1) == 12); REQUIRE(doc.NextPosition(15, -1) == 14); } SECTION("RegexSearchAndSubstitution") { DocPlus doc("\n\r\r\n 1a\xCE\x93z \n\r\r\n 2b\xCE\x93y \n\r\r\n", CpUtf8);// 1a gamma z 2b gamma y const Sci::Position docLength = doc.document.Length(); Match match; constexpr std::string_view finding = R"(\d+(\w+))"; constexpr std::string_view substituteText = R"(\t\1\n)"; constexpr std::string_view longest = "\\w+"; std::string substituted; match = doc.FindString(0, docLength, finding, rePosix); REQUIRE(match == Match(5, 5)); substituted = doc.Substitute(substituteText); REQUIRE(substituted == "\ta\xCE\x93z\n"); match = doc.FindString(docLength, 0, finding, rePosix); REQUIRE(match == Match(16, 5)); substituted = doc.Substitute(substituteText); REQUIRE(substituted == "\tb\xCE\x93y\n"); match = doc.FindString(docLength, 0, longest, rePosix); REQUIRE(match == Match(16, 5)); #ifndef NO_CXX11_REGEX match = doc.FindString(0, docLength, finding, reCxx11); REQUIRE(match == Match(5, 5)); substituted = doc.Substitute(substituteText); REQUIRE(substituted == "\ta\xCE\x93z\n"); match = doc.FindString(docLength, 0, finding, reCxx11); REQUIRE(match == Match(16, 5)); substituted = doc.Substitute(substituteText); REQUIRE(substituted == "\tb\xCE\x93y\n"); match = doc.FindString(docLength, 0, longest, reCxx11); REQUIRE(match == Match(16, 5)); #endif } SECTION("RegexAssertion") { DocPlus doc("ab cd ef\r\ngh ij kl", CpUtf8); const Sci::Position docLength = doc.document.Length(); Match match; constexpr std::string_view findingBOL = "^"; match = doc.FindString(0, docLength, findingBOL, rePosix); REQUIRE(match == Match(0)); match = doc.FindString(1, docLength, findingBOL, rePosix); REQUIRE(match == Match(10)); match = doc.FindString(docLength, 0, findingBOL, rePosix); REQUIRE(match == Match(10)); match = doc.FindString(docLength - 1, 0, findingBOL, rePosix); REQUIRE(match == Match(10)); #ifndef NO_CXX11_REGEX match = doc.FindString(0, docLength, findingBOL, reCxx11); REQUIRE(match == Match(0)); match = doc.FindString(1, docLength, findingBOL, reCxx11); REQUIRE(match == Match(10)); match = doc.FindString(docLength, 0, findingBOL, reCxx11); REQUIRE(match == Match(10)); match = doc.FindString(docLength - 1, 0, findingBOL, reCxx11); REQUIRE(match == Match(10)); #endif constexpr std::string_view findingEOL = "$"; match = doc.FindString(0, docLength, findingEOL, rePosix); REQUIRE(match == Match(8)); match = doc.FindString(1, docLength, findingEOL, rePosix); REQUIRE(match == Match(8)); match = doc.FindString(docLength, 0, findingEOL, rePosix); REQUIRE(match == Match(18)); match = doc.FindString(docLength - 1, 0, findingEOL, rePosix); REQUIRE(match == Match(8)); #if !defined(NO_CXX11_REGEX) && !defined(_LIBCPP_VERSION) match = doc.FindString(0, docLength, findingEOL, reCxx11); REQUIRE(match == Match(8)); match = doc.FindString(1, docLength, findingEOL, reCxx11); REQUIRE(match == Match(8)); match = doc.FindString(docLength, 0, findingEOL, reCxx11); REQUIRE(match == Match(18)); match = doc.FindString(docLength - 1, 0, findingEOL, reCxx11); REQUIRE(match == Match(8)); #endif constexpr std::string_view findingBOW = "\\<"; match = doc.FindString(0, docLength, findingBOW, rePosix); REQUIRE(match == Match(0)); match = doc.FindString(1, docLength, findingBOW, rePosix); REQUIRE(match == Match(3)); match = doc.FindString(docLength, 0, findingBOW, rePosix); REQUIRE(match == Match(16)); match = doc.FindString(docLength - 1, 0, findingBOW, rePosix); REQUIRE(match == Match(16)); constexpr std::string_view findingEOW = "\\>"; match = doc.FindString(0, docLength, findingEOW, rePosix); REQUIRE(match == Match(2)); match = doc.FindString(1, docLength, findingEOW, rePosix); REQUIRE(match == Match(2)); match = doc.FindString(docLength, 0, findingEOW, rePosix); REQUIRE(match == Match(18)); match = doc.FindString(docLength - 1, 0, findingEOW, rePosix); REQUIRE(match == Match(15)); constexpr std::string_view findingEOWEOL = "\\>$"; match = doc.FindString(0, docLength, findingEOWEOL, rePosix); REQUIRE(match == Match(8)); match = doc.FindString(10, docLength, findingEOWEOL, rePosix); REQUIRE(match == Match(18)); #ifndef NO_CXX11_REGEX constexpr std::string_view findingWB = "\\b"; match = doc.FindString(0, docLength, findingWB, reCxx11); REQUIRE(match == Match(0)); match = doc.FindString(1, docLength, findingWB, reCxx11); REQUIRE(match == Match(2)); match = doc.FindString(docLength, 0, findingWB, reCxx11); #ifdef _LIBCPP_VERSION REQUIRE(match == Match(16)); #else REQUIRE(match == Match(18)); #endif match = doc.FindString(docLength - 1, 0, findingWB, reCxx11); REQUIRE(match == Match(16)); constexpr std::string_view findingNWB = "\\B"; match = doc.FindString(0, docLength, findingNWB, reCxx11); REQUIRE(match == Match(1)); match = doc.FindString(1, docLength, findingNWB, reCxx11); REQUIRE(match == Match(1)); #ifdef _LIBCPP_VERSION match = doc.FindString(docLength, 0, findingNWB, reCxx11); REQUIRE(match == Match(18)); match = doc.FindString(docLength - 1, 0, findingNWB, reCxx11); REQUIRE(match == Match(14)); #else match = doc.FindString(docLength, 0, findingNWB, reCxx11); REQUIRE(match == Match(17)); match = doc.FindString(docLength - 1, 0, findingNWB, reCxx11); REQUIRE(match == Match(17)); #endif #endif } SECTION("RegexContextualAssertion") { // For std::regex, check the use of assertions next to text in forward direction // These are more common than empty assertions DocPlus doc("ab cd ef\r\ngh ij kl", CpUtf8); const Sci::Position docLength = doc.document.Length(); Match match; #ifndef NO_CXX11_REGEX match = doc.FindString(0, docLength, "^[a-z]", reCxx11); REQUIRE(match == Match(0, 1)); match = doc.FindString(1, docLength, "^[a-z]", reCxx11); REQUIRE(match == Match(10, 1)); match = doc.FindString(0, docLength, "[a-z]$", reCxx11); REQUIRE(match == Match(7, 1)); match = doc.FindString(10, docLength, "[a-z]$", reCxx11); REQUIRE(match == Match(17, 1)); match = doc.FindString(0, docLength, "\\b[a-z]", reCxx11); REQUIRE(match == Match(0, 1)); match = doc.FindString(1, docLength, "\\b[a-z]", reCxx11); REQUIRE(match == Match(3, 1)); match = doc.FindString(0, docLength, "[a-z]\\b", reCxx11); REQUIRE(match == Match(1, 1)); match = doc.FindString(2, docLength, "[a-z]\\b", reCxx11); REQUIRE(match == Match(4, 1)); match = doc.FindString(0, docLength, "\\B[a-z]", reCxx11); REQUIRE(match == Match(1, 1)); match = doc.FindString(1, docLength, "\\B[a-z]", reCxx11); REQUIRE(match == Match(1, 1)); match = doc.FindString(0, docLength, "[a-z]\\B", reCxx11); REQUIRE(match == Match(0, 1)); match = doc.FindString(2, docLength, "[a-z]\\B", reCxx11); REQUIRE(match == Match(3, 1)); #endif } SECTION("RESearchMovePositionOutsideCharUTF8") { DocPlus doc(" a\xCE\x93\xCE\x93z ", CpUtf8);// a gamma gamma z const Sci::Position docLength = doc.document.Length(); constexpr std::string_view finding = R"([a-z](\w)\1)"; Match match = doc.FindString(0, docLength, finding, rePosix); REQUIRE(match == Match(1, 5)); constexpr std::string_view substituteText = R"(\t\1\n)"; std::string substituted = doc.Substitute(substituteText); REQUIRE(substituted == "\t\xCE\x93\n"); #ifndef NO_CXX11_REGEX match = doc.FindString(0, docLength, finding, reCxx11); REQUIRE(match == Match(1, 5)); substituted = doc.Substitute(substituteText); REQUIRE(substituted == "\t\xCE\x93\n"); #endif } SECTION("RESearchMovePositionOutsideCharDBCS") { DocPlus doc(" \x98\x61xx 1aa\x83\xA1\x83\xA1z ", 932);// U+548C xx 1aa gamma gamma z const Sci::Position docLength = doc.document.Length(); Match match = doc.FindString(0, docLength, R"([a-z](\w)\1)", rePosix); REQUIRE(match == Match(8, 5)); constexpr std::string_view substituteText = R"(\t\1\n)"; std::string substituted = doc.Substitute(substituteText); REQUIRE(substituted == "\t\x83\xA1\n"); match = doc.FindString(0, docLength, R"(\w([a-z])\1)", rePosix); REQUIRE(match == Match(6, 3)); substituted = doc.Substitute(substituteText); REQUIRE(substituted == "\ta\n"); } } TEST_CASE("DocumentUndo") { // These tests check that Undo reports the end of coalesced deletes constexpr std::string_view sText = "Scintilla"; DocPlus doc(sText, 0); SECTION("CheckDeleteForwards") { // Delete forwards like the Del key doc.document.DeleteUndoHistory(); doc.document.DeleteChars(1, 1); doc.document.DeleteChars(1, 1); doc.document.DeleteChars(1, 1); const Sci::Position position = doc.document.Undo(); REQUIRE(position == 4); // End of reinsertion REQUIRE(!doc.document.CanUndo()); // Exhausted undo stack REQUIRE(doc.document.CanRedo()); } SECTION("CheckDeleteBackwards") { // Delete backwards like the backspace key doc.document.DeleteUndoHistory(); doc.document.DeleteChars(5, 1); doc.document.DeleteChars(4, 1); doc.document.DeleteChars(3, 1); const Sci::Position position = doc.document.Undo(); REQUIRE(position == 6); // End of reinsertion REQUIRE(!doc.document.CanUndo()); // Exhausted undo stack } SECTION("CheckBothWays") { // Delete backwards like the backspace key doc.document.DeleteUndoHistory(); // Like having the caret at position 5 then doc.document.DeleteChars(5, 1); // Del doc.document.DeleteChars(4, 1); // Backspace doc.document.DeleteChars(4, 1); // Del doc.document.DeleteChars(3, 1); // Backspace const Sci::Position position = doc.document.Undo(); REQUIRE(position == 7); // End of reinsertion, Start at 5, 2*Del REQUIRE(!doc.document.CanUndo()); // Exhausted undo stack } SECTION("CheckInsert") { // Insertions are only coalesced when following previous doc.document.DeleteUndoHistory(); doc.document.InsertString(1, "1"); doc.document.InsertString(2, "2"); doc.document.InsertString(3, "3"); REQUIRE(doc.Contents() == "S123cintilla"); const Sci::Position position = doc.document.Undo(); REQUIRE(position == 1); // Start of insertions REQUIRE(!doc.document.CanUndo()); // Exhausted undo stack } SECTION("CheckGrouped") { // Check that position returned for group is that at end of first deletion set // Also include a container undo action. doc.document.DeleteUndoHistory(); doc.document.BeginUndoAction(); // At 1, 2*Del so end of initial deletion sequence is 3 doc.document.DeleteChars(1, 1); // 'c' doc.document.DeleteChars(1, 1); // 'i' doc.document.AddUndoAction(99, true); doc.document.InsertString(1, "1"); doc.document.DeleteChars(4, 2); // 'il' doc.document.BeginUndoAction(); REQUIRE(doc.Contents() == "S1ntla"); const Sci::Position position = doc.document.Undo(); REQUIRE(position == 3); // Start of insertions REQUIRE(!doc.document.CanUndo()); // Exhausted undo stack } } TEST_CASE("Words") { SECTION("WordsInText") { const DocPlus doc(" abc ", 0); REQUIRE(doc.document.IsWordAt(1, 4)); REQUIRE(!doc.document.IsWordAt(0, 1)); REQUIRE(!doc.document.IsWordAt(1, 2)); const DocPlus docPunct(" [!] ", 0); REQUIRE(docPunct.document.IsWordAt(1, 4)); REQUIRE(!docPunct.document.IsWordAt(0, 1)); REQUIRE(!docPunct.document.IsWordAt(1, 2)); const DocPlus docMixed(" -ab ", 0); // '-' is punctuation, 'ab' is word REQUIRE(docMixed.document.IsWordAt(2, 4)); REQUIRE(docMixed.document.IsWordAt(1, 4)); REQUIRE(docMixed.document.IsWordAt(1, 2)); REQUIRE(!docMixed.document.IsWordAt(1, 3)); // 3 is between a and b so not word edge // Scintilla's word definition just examines the ends const DocPlus docOverSpace(" a b ", 0); REQUIRE(docOverSpace.document.IsWordAt(1, 4)); } SECTION("WordsAtEnds") { const DocPlus doc("a c", 0); REQUIRE(doc.document.IsWordAt(0, 1)); REQUIRE(doc.document.IsWordAt(2, 3)); const DocPlus docEndSpace(" a c ", 0); REQUIRE(!docEndSpace.document.IsWordAt(0, 2)); REQUIRE(!docEndSpace.document.IsWordAt(3, 5)); } } TEST_CASE("SafeSegment") { SECTION("Short") { const DocPlus doc("", 0); // all encoding: break before or after last space constexpr std::string_view text = "12 "; const size_t length = doc.document.SafeSegment(text); REQUIRE(length <= text.length()); REQUIRE(text[length - 1] == '2'); REQUIRE(text[length] == ' '); } SECTION("ASCII") { const DocPlus doc("", 0); // all encoding: break before or after last space std::string_view text = "12 3 \t45"; size_t length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == ' '); REQUIRE(text[length] == '\t'); // UTF-8 and ASCII: word and punctuation boundary in middle of text text = "(IsBreakSpace(text[j]))"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == 'j'); REQUIRE(text[length] == ']'); // UTF-8 and ASCII: word and punctuation boundary near start of text text = "(IsBreakSpace"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == '('); REQUIRE(text[length] == 'I'); // UTF-8 and ASCII: word and punctuation boundary near end of text text = "IsBreakSpace)"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == 'e'); REQUIRE(text[length] == ')'); // break before last character text = "JapaneseJa"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == 'J'); REQUIRE(text[length] == 'a'); } SECTION("UTF-8") { const DocPlus doc("", CpUtf8); // break before last character: no trail byte std::string_view text = "JapaneseJa"; size_t length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == 'J'); REQUIRE(text[length] == 'a'); // break before last character: 1 trail byte text = "Japanese\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xc2\xa9"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == '\x9e'); REQUIRE(text[length] == '\xc2'); // break before last character: 2 trail bytes text = "Japanese\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == '\xac'); REQUIRE(text[length] == '\xe8'); // break before last character: 3 trail bytes text = "Japanese\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\xf0\x9f\x98\x8a"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == '\x9e'); REQUIRE(text[length] == '\xf0'); } SECTION("DBCS Shift-JIS") { const DocPlus doc("", 932); // word and punctuation boundary in middle of text: single byte std::string_view text = "(IsBreakSpace(text[j]))"; size_t length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == 'j'); REQUIRE(text[length] == ']'); // word and punctuation boundary in middle of text: double byte text = "(IsBreakSpace(text[\x8c\xea]))"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == '\xea'); REQUIRE(text[length] == ']'); // word and punctuation boundary near start of text text = "(IsBreakSpace"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == '('); REQUIRE(text[length] == 'I'); // word and punctuation boundary near end of text: single byte text = "IsBreakSpace)"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == 'e'); REQUIRE(text[length] == ')'); // word and punctuation boundary near end of text: double byte text = "IsBreakSpace\x8c\xea)"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == '\xea'); REQUIRE(text[length] == ')'); // break before last character: single byte text = "JapaneseJa"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == 'J'); REQUIRE(text[length] == 'a'); // break before last character: double byte text = "Japanese\x93\xfa\x96\x7b\x8c\xea"; length = doc.document.SafeSegment(text); REQUIRE(text[length - 1] == '\x7b'); REQUIRE(text[length] == '\x8c'); } } TEST_CASE("PerLine") { SECTION("LineMarkers") { DocPlus doc("1\n2\n", CpUtf8); REQUIRE(doc.document.LinesTotal() == 3); const int mh1 = doc.document.AddMark(0, 0); const int mh2 = doc.document.AddMark(1, 1); const int mh3 = doc.document.AddMark(2, 2); REQUIRE(mh1 != -1); REQUIRE(mh2 != -1); REQUIRE(mh3 != -1); REQUIRE(doc.document.AddMark(3, 3) == -1); // delete first character, no change REQUIRE(doc.document.CharAt(0) == '1'); doc.document.DeleteChars(0, 1); REQUIRE(doc.document.LinesTotal() == 3); REQUIRE(doc.document.MarkerHandleFromLine(0, 0) == mh1); REQUIRE(doc.document.MarkerHandleFromLine(0, 1) == -1); REQUIRE(doc.document.MarkerHandleFromLine(1, 0) == mh2); REQUIRE(doc.document.MarkerHandleFromLine(1, 1) == -1); // delete first line, so merged REQUIRE(doc.document.CharAt(0) == '\n'); doc.document.DeleteChars(0, 1); REQUIRE(doc.document.CharAt(0) == '2'); const std::set handleSet {mh1, mh2}; const int handle1 = doc.document.MarkerHandleFromLine(0, 0); const int handle2 = doc.document.MarkerHandleFromLine(0, 1); REQUIRE(handle1 != handle2); REQUIRE(handleSet.count(handle1) == 1); REQUIRE(handleSet.count(handle2) == 1); REQUIRE(doc.document.MarkerHandleFromLine(0, 2) == -1); REQUIRE(doc.document.MarkerHandleFromLine(1, 0) == mh3); REQUIRE(doc.document.MarkerHandleFromLine(1, 1) == -1); } SECTION("LineAnnotation") { DocPlus doc("1\n2\n", CpUtf8); REQUIRE(doc.document.LinesTotal() == 3); Sci::Position length = doc.document.Length(); doc.document.AnnotationSetText(0, "1"); doc.document.AnnotationSetText(1, "1\n2"); doc.document.AnnotationSetText(2, "1\n2\n3"); REQUIRE(doc.document.AnnotationLines(0) == 1); REQUIRE(doc.document.AnnotationLines(1) == 2); REQUIRE(doc.document.AnnotationLines(2) == 3); REQUIRE(doc.document.AnnotationLines(3) == 0); // delete last line length -= 1; doc.document.DeleteChars(length, 1); // Deleting the last line moves its 3-line annotation to previous line, // deleting the 2-line annotation of the previous line. REQUIRE(doc.document.LinesTotal() == 2); REQUIRE(doc.document.AnnotationLines(0) == 1); REQUIRE(doc.document.AnnotationLines(1) == 3); REQUIRE(doc.document.AnnotationLines(2) == 0); // delete last character, no change length -= 1; REQUIRE(doc.document.CharAt(length) == '2'); doc.document.DeleteChars(length, 1); REQUIRE(doc.document.LinesTotal() == 2); REQUIRE(doc.document.AnnotationLines(0) == 1); REQUIRE(doc.document.AnnotationLines(1) == 3); REQUIRE(doc.document.AnnotationLines(2) == 0); } }
37,701
C++
.cxx
911
38.5236
131
0.702936
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,548
HanjaDic.cxx
dail8859_NotepadNext/src/scintilla/win32/HanjaDic.cxx
// Scintilla source code edit control /** @file HanjaDic.cxx ** Korean Hanja Dictionary ** Convert between Korean Hanja and Hangul by COM interface. **/ // Copyright 2015 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <string> #include <string_view> #include <memory> #define WIN32_LEAN_AND_MEAN 1 #include <windows.h> #include <ole2.h> #include "WinTypes.h" #include "HanjaDic.h" namespace Scintilla::Internal::HanjaDict { interface IRadical; interface IHanja; interface IStrokes; enum HANJA_TYPE { HANJA_UNKNOWN = 0, HANJA_K0 = 1, HANJA_K1 = 2, HANJA_OTHER = 3 }; interface IHanjaDic : IUnknown { STDMETHOD(OpenMainDic)(); STDMETHOD(CloseMainDic)(); STDMETHOD(GetHanjaWords)(BSTR bstrHangul, SAFEARRAY* ppsaHanja, VARIANT_BOOL* pfFound); STDMETHOD(GetHanjaChars)(unsigned short wchHangul, BSTR* pbstrHanjaChars, VARIANT_BOOL* pfFound); STDMETHOD(HanjaToHangul)(BSTR bstrHanja, BSTR* pbstrHangul); STDMETHOD(GetHanjaType)(unsigned short wchHanja, HANJA_TYPE* pHanjaType); STDMETHOD(GetHanjaSense)(unsigned short wchHanja, BSTR* pbstrSense); STDMETHOD(GetRadicalID)(short SeqNumOfRadical, short* pRadicalID, unsigned short* pwchRadical); STDMETHOD(GetRadical)(short nRadicalID, IRadical** ppIRadical); STDMETHOD(RadicalIDToHanja)(short nRadicalID, unsigned short* pwchRadical); STDMETHOD(GetHanja)(unsigned short wchHanja, IHanja** ppIHanja); STDMETHOD(GetStrokes)(short nStrokes, IStrokes** ppIStrokes); STDMETHOD(OpenDefaultCustomDic)(); STDMETHOD(OpenCustomDic)(BSTR bstrPath, long* plUdr); STDMETHOD(CloseDefaultCustomDic)(); STDMETHOD(CloseCustomDic)(long lUdr); STDMETHOD(CloseAllCustomDics)(); STDMETHOD(GetDefaultCustomHanjaWords)(BSTR bstrHangul, SAFEARRAY** ppsaHanja, VARIANT_BOOL* pfFound); STDMETHOD(GetCustomHanjaWords)(long lUdr, BSTR bstrHangul, SAFEARRAY** ppsaHanja, VARIANT_BOOL* pfFound); STDMETHOD(PutDefaultCustomHanjaWord)(BSTR bstrHangul, BSTR bstrHanja); STDMETHOD(PutCustomHanjaWord)(long lUdr, BSTR bstrHangul, BSTR bstrHanja); STDMETHOD(MaxNumOfRadicals)(short* pVal); STDMETHOD(MaxNumOfStrokes)(short* pVal); STDMETHOD(DefaultCustomDic)(long* pVal); STDMETHOD(DefaultCustomDic)(long pVal); STDMETHOD(MaxHanjaType)(HANJA_TYPE* pHanjaType); STDMETHOD(MaxHanjaType)(HANJA_TYPE pHanjaType); }; extern "C" const GUID __declspec(selectany) IID_IHanjaDic = { 0xad75f3ac, 0x18cd, 0x48c6, { 0xa2, 0x7d, 0xf1, 0xe9, 0xa7, 0xdc, 0xe4, 0x32 } }; class ScopedBSTR { BSTR bstr = nullptr; public: ScopedBSTR() noexcept = default; explicit ScopedBSTR(const OLECHAR *psz) noexcept : bstr(SysAllocString(psz)) { } explicit ScopedBSTR(OLECHAR character) noexcept : bstr(SysAllocStringLen(&character, 1)) { } // Deleted so ScopedBSTR objects can not be copied. Moves are OK. ScopedBSTR(const ScopedBSTR &) = delete; ScopedBSTR &operator=(const ScopedBSTR &) = delete; // Moves are OK. ScopedBSTR(ScopedBSTR &&) = default; ScopedBSTR &operator=(ScopedBSTR &&) = default; ~ScopedBSTR() { SysFreeString(bstr); } BSTR get() const noexcept { return bstr; } void reset(BSTR value=nullptr) noexcept { // https://en.cppreference.com/w/cpp/memory/unique_ptr/reset BSTR const old = bstr; bstr = value; SysFreeString(old); } }; class HanjaDic { std::unique_ptr<IHanjaDic, UnknownReleaser> HJinterface; bool OpenHanjaDic(LPCOLESTR lpszProgID) noexcept { CLSID CLSID_HanjaDic; HRESULT hr = CLSIDFromProgID(lpszProgID, &CLSID_HanjaDic); if (SUCCEEDED(hr)) { IHanjaDic *instance = nullptr; hr = CoCreateInstance(CLSID_HanjaDic, nullptr, CLSCTX_INPROC_SERVER, IID_IHanjaDic, reinterpret_cast<LPVOID *>(&instance)); if (SUCCEEDED(hr) && instance) { HJinterface.reset(instance); hr = instance->OpenMainDic(); return SUCCEEDED(hr); } } return false; } public: bool Open() noexcept { return OpenHanjaDic(OLESTR("imkrhjd.hanjadic")) || OpenHanjaDic(OLESTR("mshjdic.hanjadic")); } void Close() const noexcept { HJinterface->CloseMainDic(); } bool IsHanja(wchar_t hanja) const noexcept { HANJA_TYPE hanjaType = HANJA_UNKNOWN; const HRESULT hr = HJinterface->GetHanjaType(hanja, &hanjaType); return SUCCEEDED(hr) && hanjaType > HANJA_UNKNOWN; } bool HanjaToHangul(const ScopedBSTR &bstrHanja, ScopedBSTR &bstrHangul) const noexcept { BSTR result = nullptr; const HRESULT hr = HJinterface->HanjaToHangul(bstrHanja.get(), &result); bstrHangul.reset(result); return SUCCEEDED(hr); } }; bool GetHangulOfHanja(std::wstring &inout) noexcept { // Convert every hanja to hangul. // Return whether any character been converted. // Hanja linked to different notes in Hangul have different codes, // so current character based conversion is enough. // great thanks for BLUEnLIVE. bool changed = false; HanjaDic dict; if (dict.Open()) { for (wchar_t &character : inout) { if (dict.IsHanja(character)) { // Pass hanja only! ScopedBSTR bstrHangul; if (dict.HanjaToHangul(ScopedBSTR(character), bstrHangul)) { changed = true; character = *(bstrHangul.get()); } } } dict.Close(); } return changed; } }
5,166
C++
.cxx
141
34.219858
106
0.764729
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
16,560
DBCS.cxx
dail8859_NotepadNext/src/scintilla/src/DBCS.cxx
// Scintilla source code edit control /** @file DBCS.cxx ** Functions to handle DBCS double byte encodings like Shift-JIS. **/ // Copyright 2017 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include "DBCS.h" using namespace Scintilla::Internal; namespace Scintilla::Internal { bool DBCSIsLeadByte(int codePage, char ch) noexcept { // Byte ranges found in Wikipedia articles with relevant search strings in each case const unsigned char uch = ch; switch (codePage) { case 932: // Shift_jis return ((uch >= 0x81) && (uch <= 0x9F)) || ((uch >= 0xE0) && (uch <= 0xFC)); // Lead bytes F0 to FC may be a Microsoft addition. case 936: // GBK return (uch >= 0x81) && (uch <= 0xFE); case 949: // Korean Wansung KS C-5601-1987 return (uch >= 0x81) && (uch <= 0xFE); case 950: // Big5 return (uch >= 0x81) && (uch <= 0xFE); case 1361: // Korean Johab KS C-5601-1992 return ((uch >= 0x84) && (uch <= 0xD3)) || ((uch >= 0xD8) && (uch <= 0xDE)) || ((uch >= 0xE0) && (uch <= 0xF9)); } return false; } bool IsDBCSValidSingleByte(int codePage, int ch) noexcept { switch (codePage) { case 932: return ch == 0x80 || (ch >= 0xA0 && ch <= 0xDF) || (ch >= 0xFD); default: return false; } } }
1,325
C++
.cxx
47
25.765957
94
0.65775
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
16,567
Geometry.cxx
dail8859_NotepadNext/src/scintilla/src/Geometry.cxx
// Scintilla source code edit control /** @file Geometry.cxx ** Helper functions for geometric calculations. **/ // Copyright 2020 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cstdint> #include <cmath> #include <algorithm> #include "Geometry.h" namespace { constexpr unsigned int Mixed(unsigned char a, unsigned char b, double proportion) noexcept { return static_cast<unsigned int>(a + proportion * (b - a)); } } namespace Scintilla::Internal { PRectangle Clamp(PRectangle rc, Edge edge, XYPOSITION position) noexcept { switch (edge) { case Edge::left: return PRectangle(std::clamp(position, rc.left, rc.right), rc.top, rc.right, rc.bottom); case Edge::top: return PRectangle(rc.left, std::clamp(position, rc.top, rc.bottom), rc.right, rc.bottom); case Edge::right: return PRectangle(rc.left, rc.top, std::clamp(position, rc.left, rc.right), rc.bottom); case Edge::bottom: default: return PRectangle(rc.left, rc.top, rc.right, std::clamp(position, rc.top, rc.bottom)); } } PRectangle Side(PRectangle rc, Edge edge, XYPOSITION size) noexcept { switch (edge) { case Edge::left: return PRectangle(rc.left, rc.top, std::min(rc.left + size, rc.right), rc.bottom); case Edge::top: return PRectangle(rc.left, rc.top, rc.right, std::min(rc.top + size, rc.bottom)); case Edge::right: return PRectangle(std::max(rc.left, rc.right - size), rc.top, rc.right, rc.bottom); case Edge::bottom: default: return PRectangle(rc.left, std::max(rc.top, rc.bottom - size), rc.right, rc.bottom); } } Interval Intersection(Interval a, Interval b) noexcept { const XYPOSITION leftMax = std::max(a.left, b.left); const XYPOSITION rightMin = std::min(a.right, b.right); // If the result would have a negative width. make empty instead. const XYPOSITION rightResult = (rightMin >= leftMax) ? rightMin : leftMax; return { leftMax, rightResult }; } PRectangle Intersection(PRectangle rc, Interval horizontalBounds) noexcept { const Interval intersection = Intersection(HorizontalBounds(rc), horizontalBounds); return PRectangle(intersection.left, rc.top, intersection.right, rc.bottom); } Interval HorizontalBounds(PRectangle rc) noexcept { return { rc.left, rc.right }; } XYPOSITION PixelAlign(XYPOSITION xy, int pixelDivisions) noexcept { return std::round(xy * pixelDivisions) / pixelDivisions; } XYPOSITION PixelAlignFloor(XYPOSITION xy, int pixelDivisions) noexcept { return std::floor(xy * pixelDivisions) / pixelDivisions; } XYPOSITION PixelAlignCeil(XYPOSITION xy, int pixelDivisions) noexcept { return std::ceil(xy * pixelDivisions) / pixelDivisions; } Point PixelAlign(const Point &pt, int pixelDivisions) noexcept { return Point( PixelAlign(pt.x, pixelDivisions), PixelAlign(pt.y, pixelDivisions)); } PRectangle PixelAlign(const PRectangle &rc, int pixelDivisions) noexcept { // Move left and right side to nearest pixel to avoid blurry visuals. // The top and bottom should be integers but floor them to make sure. // `pixelDivisions` is commonly 1 except for 'retina' displays where it is 2. // On retina displays, the positions should be moved to the nearest device // pixel which is the nearest half logical pixel. return PRectangle( PixelAlign(rc.left, pixelDivisions), PixelAlignFloor(rc.top, pixelDivisions), PixelAlign(rc.right, pixelDivisions), PixelAlignFloor(rc.bottom, pixelDivisions)); } PRectangle PixelAlignOutside(const PRectangle &rc, int pixelDivisions) noexcept { // Move left and right side to extremes (floor(left) ceil(right)) to avoid blurry visuals. return PRectangle( PixelAlignFloor(rc.left, pixelDivisions), PixelAlignFloor(rc.top, pixelDivisions), PixelAlignCeil(rc.right, pixelDivisions), PixelAlignFloor(rc.bottom, pixelDivisions)); } ColourRGBA ColourRGBA::MixedWith(ColourRGBA other) const noexcept { const unsigned int red = (GetRed() + other.GetRed()) / 2; const unsigned int green = (GetGreen() + other.GetGreen()) / 2; const unsigned int blue = (GetBlue() + other.GetBlue()) / 2; const unsigned int alpha = (GetAlpha() + other.GetAlpha()) / 2; return ColourRGBA(red, green, blue, alpha); } ColourRGBA ColourRGBA::MixedWith(ColourRGBA other, double proportion) const noexcept { return ColourRGBA( Mixed(GetRed(), other.GetRed(), proportion), Mixed(GetGreen(), other.GetGreen(), proportion), Mixed(GetBlue(), other.GetBlue(), proportion), Mixed(GetAlpha(), other.GetAlpha(), proportion)); } }
4,514
C++
.cxx
105
40.961905
94
0.762534
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
16,569
ChangeHistory.cxx
dail8859_NotepadNext/src/scintilla/src/ChangeHistory.cxx
// Scintilla source code edit control /** @file ChangeHistory.cxx ** Manages a history of changes in a document. **/ // Copyright 2022 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cstddef> #include <cstdlib> #include <cassert> #include <stdexcept> #include <vector> #include <set> #include <algorithm> #include <memory> #include "ScintillaTypes.h" #include "Debugging.h" #include "Position.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "SparseVector.h" #include "ChangeHistory.h" namespace Scintilla::Internal { void ChangeStack::Clear() noexcept { steps.clear(); changes.clear(); } void ChangeStack::AddStep() { steps.push_back(0); } namespace { constexpr bool InsertionSpanSameDeletion(const ChangeSpan &is, Sci::Position positionDeletion, int edition) { // Equal except for count return is.direction == ChangeSpan::Direction::deletion && is.start == positionDeletion && is.length == 0 && is.edition == edition; } } void ChangeStack::PushDeletion(Sci::Position positionDeletion, const EditionCount &ec) { steps.back() += ec.count; if (changes.empty() || !InsertionSpanSameDeletion(changes.back(), positionDeletion, ec.edition)) { changes.push_back({ positionDeletion, 0, ec.edition, ec.count, ChangeSpan::Direction::deletion }); } else { changes.back().count += ec.count; } } void ChangeStack::PushInsertion(Sci::Position positionInsertion, Sci::Position length, int edition) { steps.back()++; changes.push_back({ positionInsertion, length, edition, 1, ChangeSpan::Direction::insertion }); } int ChangeStack::PopStep() noexcept { const int spans = steps.back(); steps.pop_back(); return spans; } ChangeSpan ChangeStack::PopSpan(int maxSteps) noexcept { ChangeSpan span = changes.back(); const int remove = std::min(maxSteps, span.count); if (span.count == remove) { changes.pop_back(); } else { changes.back().count -= remove; span.count = remove; } return span; } void ChangeStack::SetSavePoint() noexcept { // Switch changeUnsaved to changeSaved for (ChangeSpan &x : changes) { if (x.edition == changeModified) { x.edition = changeSaved; } } } void ChangeStack::Check() const noexcept { #ifdef _DEBUG // Ensure count in steps same as insertions; int sizeSteps = 0; for (const int c : steps) { sizeSteps += c; } int sizeInsertions = 0; for (const ChangeSpan &is: changes) { sizeInsertions += is.count; } assert(sizeSteps == sizeInsertions); #endif } void ChangeLog::Clear(Sci::Position length) { changeStack.Clear(); insertEdition.DeleteAll(); deleteEdition.DeleteAll(); InsertSpace(0, length); } void ChangeLog::InsertSpace(Sci::Position position, Sci::Position insertLength) { assert(insertEdition.Length() == deleteEdition.Length()); insertEdition.InsertSpace(position, insertLength); deleteEdition.InsertSpace(position, insertLength); } void ChangeLog::DeleteRange(Sci::Position position, Sci::Position deleteLength) { insertEdition.DeleteRange(position, deleteLength); const EditionSetOwned &editions = deleteEdition.ValueAt(position); if (editions) { const EditionSet savedEditions = *editions; deleteEdition.DeleteRange(position, deleteLength); EditionSetOwned reset = std::make_unique<EditionSet>(savedEditions); deleteEdition.SetValueAt(position, std::move(reset)); } else { deleteEdition.DeleteRange(position, deleteLength); } assert(insertEdition.Length() == deleteEdition.Length()); } void ChangeLog::Insert(Sci::Position start, Sci::Position length, int edition) { insertEdition.FillRange(start, edition, length); } void ChangeLog::CollapseRange(Sci::Position position, Sci::Position deleteLength) { const Sci::Position positionMax = position + deleteLength; Sci::Position positionDeletion = position + 1; while (positionDeletion <= positionMax) { const EditionSetOwned &editions = deleteEdition.ValueAt(positionDeletion); if (editions) { for (const EditionCount &ec : *editions) { PushDeletionAt(position, ec); } EditionSetOwned empty; deleteEdition.SetValueAt(positionDeletion, std::move(empty)); } positionDeletion = deleteEdition.PositionNext(positionDeletion); } } namespace { // EditionSets have repeat counts on items so push and pop may just // manipulate the count field or may push/pop items. void EditionSetPush(EditionSet &set, EditionCount ec) { if (set.empty() || (set.back().edition != ec.edition)) { set.push_back(ec); } else { set.back().count += ec.count; } } void EditionSetPop(EditionSet &set) noexcept { if (set.back().count == 1) { set.pop_back(); } else { set.back().count--; } } int EditionSetCount(const EditionSet &set) noexcept { int count = 0; for (const EditionCount &ec : set) { count += ec.count; } return count; } } void ChangeLog::PushDeletionAt(Sci::Position position, EditionCount ec) { if (!deleteEdition.ValueAt(position)) { deleteEdition.SetValueAt(position, std::make_unique<EditionSet>()); } EditionSetPush(*deleteEdition.ValueAt(position), ec); } void ChangeLog::InsertFrontDeletionAt(Sci::Position position, EditionCount ec) { if (!deleteEdition.ValueAt(position)) { deleteEdition.SetValueAt(position, std::make_unique<EditionSet>()); } const EditionSetOwned &editions = deleteEdition.ValueAt(position); editions->insert(editions->begin(), ec); } void ChangeLog::SaveRange(Sci::Position position, Sci::Position length) { // Save insertEdition range into undo stack changeStack.AddStep(); Sci::Position positionInsertion = position; const ptrdiff_t editionStart = insertEdition.ValueAt(positionInsertion); if (editionStart == 0) { positionInsertion = insertEdition.EndRun(positionInsertion); } const Sci::Position positionMax = position + length; while (positionInsertion < positionMax) { const Sci::Position positionEndInsertion = insertEdition.EndRun(positionInsertion); changeStack.PushInsertion(positionInsertion, std::min(positionEndInsertion, positionMax) - positionInsertion, insertEdition.ValueAt(positionInsertion)); positionInsertion = insertEdition.EndRun(positionEndInsertion); } Sci::Position positionDeletion = position + 1; while (positionDeletion <= positionMax) { const EditionSetOwned &editions = deleteEdition.ValueAt(positionDeletion); if (editions) { for (const EditionCount &ec : *editions) { changeStack.PushDeletion(positionDeletion, ec); } } positionDeletion = deleteEdition.PositionNext(positionDeletion); } } void ChangeLog::PopDeletion(Sci::Position position, Sci::Position deleteLength) { // Just performed InsertSpace(position, deleteLength) so *this* element in // deleteEdition moved forward by deleteLength EditionSetOwned eso = deleteEdition.Extract(position + deleteLength); deleteEdition.SetValueAt(position, std::move(eso)); const EditionSetOwned &editions = deleteEdition.ValueAt(position); assert(editions); EditionSetPop(*editions); const int inserts = changeStack.PopStep(); for (int i = 0; i < inserts;) { const ChangeSpan span = changeStack.PopSpan(inserts); if (span.direction == ChangeSpan::Direction::insertion) { assert(span.count == 1); // Insertions are never compressed insertEdition.FillRange(span.start, span.edition, span.length); i++; } else { assert(editions); assert(editions->back().edition == span.edition); for (int j = 0; j < span.count; j++) { EditionSetPop(*editions); } // Iterating backwards (pop) through changeStack, reverse order of insertion // and original deletion list. // Therefore need to insert at front to recreate original order. InsertFrontDeletionAt(span.start, { span.edition, span.count }); i += span.count; } } if (editions->empty()) { deleteEdition.SetValueAt(position, EditionSetOwned{}); } } void ChangeLog::SaveHistoryForDelete(Sci::Position position, Sci::Position deleteLength) { assert(position >= 0); assert(deleteLength >= 0); assert(position + deleteLength <= Length()); SaveRange(position, deleteLength); CollapseRange(position, deleteLength); } void ChangeLog::DeleteRangeSavingHistory(Sci::Position position, Sci::Position deleteLength) { SaveHistoryForDelete(position, deleteLength); DeleteRange(position, deleteLength); } void ChangeLog::SetSavePoint() { // Switch changeUnsaved to changeSaved changeStack.SetSavePoint(); const Sci::Position length = insertEdition.Length(); for (Sci::Position startRun = 0; startRun < length;) { const Sci::Position endRun = insertEdition.EndRun(startRun); if (insertEdition.ValueAt(startRun) == changeModified) { insertEdition.FillRange(startRun, changeSaved, endRun - startRun); } startRun = endRun; } for (Sci::Position positionDeletion = 0; positionDeletion <= length;) { const EditionSetOwned &editions = deleteEdition.ValueAt(positionDeletion); if (editions) { for (EditionCount &ec : *editions) { if (ec.edition == changeModified) { ec.edition = changeSaved; } } } positionDeletion = deleteEdition.PositionNext(positionDeletion); } } Sci::Position ChangeLog::Length() const noexcept { return insertEdition.Length(); } size_t ChangeLog::DeletionCount(Sci::Position start, Sci::Position length) const noexcept { const Sci::Position end = start + length; size_t count = 0; while (start <= end) { const EditionSetOwned &editions = deleteEdition.ValueAt(start); if (editions) { count += EditionSetCount(*editions); } start = deleteEdition.PositionNext(start); } return count; } void ChangeLog::Check() const noexcept { assert(insertEdition.Length() == deleteEdition.Length()); changeStack.Check(); } ChangeHistory::ChangeHistory(Sci::Position length) { changeLog.Clear(length); } void ChangeHistory::Insert(Sci::Position position, Sci::Position insertLength, bool collectingUndo, bool beforeSave) { Check(); changeLog.InsertSpace(position, insertLength); const int edition = collectingUndo ? (beforeSave ? changeSaved : changeModified) : changeOriginal; changeLog.Insert(position, insertLength, edition); if (changeLogReversions) { changeLogReversions->InsertSpace(position, insertLength); if (beforeSave) { changeLogReversions->PopDeletion(position, insertLength); } } Check(); } void ChangeHistory::DeleteRange(Sci::Position position, Sci::Position deleteLength, bool reverting) { Check(); assert(DeletionCount(position, deleteLength-1) == 0); changeLog.DeleteRange(position, deleteLength); if (changeLogReversions) { changeLogReversions->DeleteRangeSavingHistory(position, deleteLength); if (reverting) { changeLogReversions->PushDeletionAt(position, { changeRevertedOriginal, 1 }); } } Check(); } void ChangeHistory::DeleteRangeSavingHistory(Sci::Position position, Sci::Position deleteLength, bool beforeSave, bool isDetached) { changeLog.DeleteRangeSavingHistory(position, deleteLength); changeLog.PushDeletionAt(position, { beforeSave ? changeSaved : changeModified, 1 }); if (changeLogReversions) { if (isDetached) { changeLogReversions->SaveHistoryForDelete(position, deleteLength); } changeLogReversions->DeleteRange(position, deleteLength); } Check(); } void ChangeHistory::StartReversion() { if (!changeLogReversions) { changeLogReversions = std::make_unique<ChangeLog>(); changeLogReversions->Clear(changeLog.Length()); } Check(); } void ChangeHistory::EndReversion() noexcept { changeLogReversions.reset(); Check(); } void ChangeHistory::SetSavePoint() { changeLog.SetSavePoint(); EndReversion(); } void ChangeHistory::UndoDeleteStep(Sci::Position position, Sci::Position deleteLength, bool isDetached) { Check(); changeLog.InsertSpace(position, deleteLength); changeLog.PopDeletion(position, deleteLength); if (changeLogReversions) { changeLogReversions->InsertSpace(position, deleteLength); if (!isDetached) { changeLogReversions->Insert(position, deleteLength, 1); } } Check(); } Sci::Position ChangeHistory::Length() const noexcept { return changeLog.Length(); } void ChangeHistory::SetEpoch(int epoch) noexcept { historicEpoch = epoch; } void ChangeHistory::EditionCreateHistory(Sci::Position start, Sci::Position length) { if (start <= changeLog.Length()) { if (length) { changeLog.insertEdition.FillRange(start, historicEpoch, length); } else { changeLog.PushDeletionAt(start, { historicEpoch, 1 }); } } } // Editions: // <0 History // 0 Original unchanged // 1 Reverted to origin // 2 Saved // 3 Unsaved // 4 Reverted to change int ChangeHistory::EditionAt(Sci::Position pos) const noexcept { const int edition = changeLog.insertEdition.ValueAt(pos); if (changeLogReversions) { const int editionReversion = changeLogReversions->insertEdition.ValueAt(pos); if (editionReversion) { if (edition < 0) // Historical revision return changeRevertedOriginal; return edition ? changeRevertedToChange : changeRevertedOriginal; } } return edition; } Sci::Position ChangeHistory::EditionEndRun(Sci::Position pos) const noexcept { if (changeLogReversions) { assert(changeLogReversions->Length() == changeLog.Length()); const Sci::Position nextReversion = changeLogReversions->insertEdition.EndRun(pos); const Sci::Position next = changeLog.insertEdition.EndRun(pos); return std::min(next, nextReversion); } return changeLog.insertEdition.EndRun(pos); } // Produce a 4-bit value from the deletions at a position unsigned int ChangeHistory::EditionDeletesAt(Sci::Position pos) const noexcept { unsigned int editionSet = 0; const EditionSetOwned &editionSetDeletions = changeLog.deleteEdition.ValueAt(pos); if (editionSetDeletions) { for (const EditionCount &ec : *editionSetDeletions) { editionSet = editionSet | (1u << (ec.edition-1)); } } if (changeLogReversions) { const EditionSetOwned &editionSetReversions = changeLogReversions->deleteEdition.ValueAt(pos); if (editionSetReversions) { // If there is no saved or modified -> revertedToOrigin if (!(editionSet & (bitSaved | bitModified))) { editionSet = editionSet | bitRevertedToOriginal; } else { editionSet = editionSet | bitRevertedToModified; } } } return editionSet; } Sci::Position ChangeHistory::EditionNextDelete(Sci::Position pos) const noexcept { const Sci::Position next = changeLog.deleteEdition.PositionNext(pos); if (changeLogReversions) { const Sci::Position nextReversion = changeLogReversions->deleteEdition.PositionNext(pos); return std::min(next, nextReversion); } return next; } size_t ChangeHistory::DeletionCount(Sci::Position start, Sci::Position length) const noexcept { return changeLog.DeletionCount(start, length); } EditionSet ChangeHistory::DeletionsAt(Sci::Position pos) const { const EditionSetOwned &editions = changeLog.deleteEdition.ValueAt(pos); if (editions) { return *editions; } return {}; } void ChangeHistory::Check() noexcept { changeLog.Check(); if (changeLogReversions) { changeLogReversions->Check(); assert(changeLogReversions->Length() == changeLog.Length()); } } }
15,064
C++
.cxx
439
32.031891
132
0.767097
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,577
CellBuffer.cxx
dail8859_NotepadNext/src/scintilla/src/CellBuffer.cxx
// Scintilla source code edit control /** @file CellBuffer.cxx ** Manages a buffer of cells. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cstddef> #include <cstdlib> #include <cassert> #include <cstring> #include <cstdio> #include <cstdarg> #include <climits> #include <stdexcept> #include <string> #include <string_view> #include <vector> #include <optional> #include <algorithm> #include <memory> #include "ScintillaTypes.h" #include "Debugging.h" #include "Position.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "SparseVector.h" #include "ChangeHistory.h" #include "CellBuffer.h" #include "UndoHistory.h" #include "UniConversion.h" namespace Scintilla::Internal { struct CountWidths { // Measures the number of characters in a string divided into those // from the Base Multilingual Plane and those from other planes. Sci::Position countBasePlane; Sci::Position countOtherPlanes; explicit CountWidths(Sci::Position countBasePlane_=0, Sci::Position countOtherPlanes_=0) noexcept : countBasePlane(countBasePlane_), countOtherPlanes(countOtherPlanes_) { } CountWidths operator-() const noexcept { return CountWidths(-countBasePlane, -countOtherPlanes); } Sci::Position WidthUTF32() const noexcept { // All code points take one code unit in UTF-32. return countBasePlane + countOtherPlanes; } Sci::Position WidthUTF16() const noexcept { // UTF-16 takes 2 code units for other planes return countBasePlane + 2 * countOtherPlanes; } void CountChar(int lenChar) noexcept { if (lenChar == 4) { countOtherPlanes++; } else { countBasePlane++; } } }; class ILineVector { public: virtual void Init() = 0; virtual void SetPerLine(PerLine *pl) noexcept = 0; virtual void InsertText(Sci::Line line, Sci::Position delta) noexcept = 0; virtual void InsertLine(Sci::Line line, Sci::Position position, bool lineStart) = 0; virtual void InsertLines(Sci::Line line, const Sci::Position *positions, size_t lines, bool lineStart) = 0; virtual void SetLineStart(Sci::Line line, Sci::Position position) noexcept = 0; virtual void RemoveLine(Sci::Line line) = 0; virtual Sci::Line Lines() const noexcept = 0; virtual void AllocateLines(Sci::Line lines) = 0; virtual Sci::Line LineFromPosition(Sci::Position pos) const noexcept = 0; virtual Sci::Position LineStart(Sci::Line line) const noexcept = 0; virtual void InsertCharacters(Sci::Line line, CountWidths delta) noexcept = 0; virtual void SetLineCharactersWidth(Sci::Line line, CountWidths width) noexcept = 0; virtual Scintilla::LineCharacterIndexType LineCharacterIndex() const noexcept = 0; virtual bool AllocateLineCharacterIndex(Scintilla::LineCharacterIndexType lineCharacterIndex, Sci::Line lines) = 0; virtual bool ReleaseLineCharacterIndex(Scintilla::LineCharacterIndexType lineCharacterIndex) = 0; virtual Sci::Position IndexLineStart(Sci::Line line, Scintilla::LineCharacterIndexType lineCharacterIndex) const noexcept = 0; virtual Sci::Line LineFromPositionIndex(Sci::Position pos, Scintilla::LineCharacterIndexType lineCharacterIndex) const noexcept = 0; virtual ~ILineVector() {} }; } using namespace Scintilla; using namespace Scintilla::Internal; template <typename POS> class LineStartIndex { // line_cast(): cast Sci::Line to either 32-bit or 64-bit value // This avoids warnings from Visual C++ Code Analysis and shortens code static constexpr POS line_cast(Sci::Line pos) noexcept { return static_cast<POS>(pos); } public: int refCount; Partitioning<POS> starts; LineStartIndex() : refCount(0), starts(4) { // Minimal initial allocation } bool Allocate(Sci::Line lines) { refCount++; Sci::Position length = starts.PositionFromPartition(starts.Partitions()); for (Sci::Line line = starts.Partitions(); line < lines; line++) { // Produce an ascending sequence that will be filled in with correct widths later length++; starts.InsertPartition(line_cast(line), line_cast(length)); } return refCount == 1; } bool Release() { if (refCount == 1) { starts.DeleteAll(); } refCount--; return refCount == 0; } bool Active() const noexcept { return refCount > 0; } Sci::Position LineWidth(Sci::Line line) const noexcept { return starts.PositionFromPartition(line_cast(line) + 1) - starts.PositionFromPartition(line_cast(line)); } void SetLineWidth(Sci::Line line, Sci::Position width) noexcept { const Sci::Position widthCurrent = LineWidth(line); starts.InsertText(line_cast(line), line_cast(width - widthCurrent)); } void AllocateLines(Sci::Line lines) { if (lines > starts.Partitions()) { starts.ReAllocate(lines); } } void InsertLines(Sci::Line line, Sci::Line lines) { // Insert multiple lines with each temporarily 1 character wide. // The line widths will be fixed up by later measuring code. const POS lineAsPos = line_cast(line); const POS lineStart = starts.PositionFromPartition(lineAsPos - 1) + 1; for (POS l = 0; l < line_cast(lines); l++) { starts.InsertPartition(lineAsPos + l, lineStart + l); } } }; template <typename POS> class LineVector : public ILineVector { Partitioning<POS> starts; PerLine *perLine; LineStartIndex<POS> startsUTF16; LineStartIndex<POS> startsUTF32; LineCharacterIndexType activeIndices; void SetActiveIndices() noexcept { activeIndices = (startsUTF32.Active() ? LineCharacterIndexType::Utf32 : LineCharacterIndexType::None) | (startsUTF16.Active() ? LineCharacterIndexType::Utf16 : LineCharacterIndexType::None); } // pos_cast(): cast Sci::Line and Sci::Position to either 32-bit or 64-bit value // This avoids warnings from Visual C++ Code Analysis and shortens code static constexpr POS pos_cast(Sci::Position pos) noexcept { return static_cast<POS>(pos); } // line_from_pos_cast(): return 32-bit or 64-bit value as Sci::Line // This avoids warnings from Visual C++ Code Analysis and shortens code static constexpr Sci::Line line_from_pos_cast(POS line) noexcept { return static_cast<Sci::Line>(line); } public: LineVector() : starts(256), perLine(nullptr), activeIndices(LineCharacterIndexType::None) { } void Init() override { starts.DeleteAll(); if (perLine) { perLine->Init(); } startsUTF32.starts.DeleteAll(); startsUTF16.starts.DeleteAll(); } void SetPerLine(PerLine *pl) noexcept override { perLine = pl; } void InsertText(Sci::Line line, Sci::Position delta) noexcept override { starts.InsertText(pos_cast(line), pos_cast(delta)); } void InsertLine(Sci::Line line, Sci::Position position, bool lineStart) override { const POS lineAsPos = pos_cast(line); starts.InsertPartition(lineAsPos, pos_cast(position)); if (activeIndices != LineCharacterIndexType::None) { if (FlagSet(activeIndices, LineCharacterIndexType::Utf32)) { startsUTF32.InsertLines(line, 1); } if (FlagSet(activeIndices, LineCharacterIndexType::Utf16)) { startsUTF16.InsertLines(line, 1); } } if (perLine) { if ((line > 0) && lineStart) line--; perLine->InsertLine(line); } } void InsertLines(Sci::Line line, const Sci::Position *positions, size_t lines, bool lineStart) override { const POS lineAsPos = pos_cast(line); if constexpr (sizeof(Sci::Position) == sizeof(POS)) { starts.InsertPartitions(lineAsPos, positions, lines); } else { starts.InsertPartitionsWithCast(lineAsPos, positions, lines); } if (activeIndices != LineCharacterIndexType::None) { if (FlagSet(activeIndices, LineCharacterIndexType::Utf32)) { startsUTF32.InsertLines(line, lines); } if (FlagSet(activeIndices, LineCharacterIndexType::Utf16)) { startsUTF16.InsertLines(line, lines); } } if (perLine) { if ((line > 0) && lineStart) line--; perLine->InsertLines(line, lines); } } void SetLineStart(Sci::Line line, Sci::Position position) noexcept override { starts.SetPartitionStartPosition(pos_cast(line), pos_cast(position)); } void RemoveLine(Sci::Line line) override { starts.RemovePartition(pos_cast(line)); if (FlagSet(activeIndices, LineCharacterIndexType::Utf32)) { startsUTF32.starts.RemovePartition(pos_cast(line)); } if (FlagSet(activeIndices, LineCharacterIndexType::Utf16)) { startsUTF16.starts.RemovePartition(pos_cast(line)); } if (perLine) { perLine->RemoveLine(line); } } Sci::Line Lines() const noexcept override { return line_from_pos_cast(starts.Partitions()); } void AllocateLines(Sci::Line lines) override { if (lines > Lines()) { starts.ReAllocate(lines); if (FlagSet(activeIndices, LineCharacterIndexType::Utf32)) { startsUTF32.AllocateLines(lines); } if (FlagSet(activeIndices, LineCharacterIndexType::Utf16)) { startsUTF16.AllocateLines(lines); } } } Sci::Line LineFromPosition(Sci::Position pos) const noexcept override { return line_from_pos_cast(starts.PartitionFromPosition(pos_cast(pos))); } Sci::Position LineStart(Sci::Line line) const noexcept override { return starts.PositionFromPartition(pos_cast(line)); } void InsertCharacters(Sci::Line line, CountWidths delta) noexcept override { if (FlagSet(activeIndices, LineCharacterIndexType::Utf32)) { startsUTF32.starts.InsertText(pos_cast(line), pos_cast(delta.WidthUTF32())); } if (FlagSet(activeIndices, LineCharacterIndexType::Utf16)) { startsUTF16.starts.InsertText(pos_cast(line), pos_cast(delta.WidthUTF16())); } } void SetLineCharactersWidth(Sci::Line line, CountWidths width) noexcept override { if (FlagSet(activeIndices, LineCharacterIndexType::Utf32)) { assert(startsUTF32.starts.Partitions() == starts.Partitions()); startsUTF32.SetLineWidth(line, width.WidthUTF32()); } if (FlagSet(activeIndices, LineCharacterIndexType::Utf16)) { assert(startsUTF16.starts.Partitions() == starts.Partitions()); startsUTF16.SetLineWidth(line, width.WidthUTF16()); } } LineCharacterIndexType LineCharacterIndex() const noexcept override { return activeIndices; } bool AllocateLineCharacterIndex(LineCharacterIndexType lineCharacterIndex, Sci::Line lines) override { const LineCharacterIndexType activeIndicesStart = activeIndices; if (FlagSet(lineCharacterIndex, LineCharacterIndexType::Utf32)) { startsUTF32.Allocate(lines); assert(startsUTF32.starts.Partitions() == starts.Partitions()); } if (FlagSet(lineCharacterIndex, LineCharacterIndexType::Utf16)) { startsUTF16.Allocate(lines); assert(startsUTF16.starts.Partitions() == starts.Partitions()); } SetActiveIndices(); return activeIndicesStart != activeIndices; } bool ReleaseLineCharacterIndex(LineCharacterIndexType lineCharacterIndex) override { const LineCharacterIndexType activeIndicesStart = activeIndices; if (FlagSet(lineCharacterIndex, LineCharacterIndexType::Utf32)) { startsUTF32.Release(); } if (FlagSet(lineCharacterIndex, LineCharacterIndexType::Utf16)) { startsUTF16.Release(); } SetActiveIndices(); return activeIndicesStart != activeIndices; } Sci::Position IndexLineStart(Sci::Line line, LineCharacterIndexType lineCharacterIndex) const noexcept override { if (lineCharacterIndex == LineCharacterIndexType::Utf32) { return startsUTF32.starts.PositionFromPartition(pos_cast(line)); } else { return startsUTF16.starts.PositionFromPartition(pos_cast(line)); } } Sci::Line LineFromPositionIndex(Sci::Position pos, LineCharacterIndexType lineCharacterIndex) const noexcept override { if (lineCharacterIndex == LineCharacterIndexType::Utf32) { return line_from_pos_cast(startsUTF32.starts.PartitionFromPosition(pos_cast(pos))); } else { return line_from_pos_cast(startsUTF16.starts.PartitionFromPosition(pos_cast(pos))); } } }; CellBuffer::CellBuffer(bool hasStyles_, bool largeDocument_) : hasStyles(hasStyles_), largeDocument(largeDocument_) { readOnly = false; utf8Substance = false; utf8LineEnds = LineEndType::Default; collectingUndo = true; uh = std::make_unique<UndoHistory>(); if (largeDocument) plv = std::make_unique<LineVector<Sci::Position>>(); else plv = std::make_unique<LineVector<int>>(); } CellBuffer::~CellBuffer() noexcept = default; char CellBuffer::CharAt(Sci::Position position) const noexcept { return substance.ValueAt(position); } unsigned char CellBuffer::UCharAt(Sci::Position position) const noexcept { return substance.ValueAt(position); } void CellBuffer::GetCharRange(char *buffer, Sci::Position position, Sci::Position lengthRetrieve) const { if (lengthRetrieve <= 0) return; if (position < 0) return; if ((position + lengthRetrieve) > substance.Length()) { Platform::DebugPrintf("Bad GetCharRange %.0f for %.0f of %.0f\n", static_cast<double>(position), static_cast<double>(lengthRetrieve), static_cast<double>(substance.Length())); return; } substance.GetRange(buffer, position, lengthRetrieve); } char CellBuffer::StyleAt(Sci::Position position) const noexcept { return hasStyles ? style.ValueAt(position) : '\0'; } void CellBuffer::GetStyleRange(unsigned char *buffer, Sci::Position position, Sci::Position lengthRetrieve) const { if (lengthRetrieve < 0) return; if (position < 0) return; if (!hasStyles) { std::fill(buffer, buffer + lengthRetrieve, static_cast<unsigned char>(0)); return; } if ((position + lengthRetrieve) > style.Length()) { Platform::DebugPrintf("Bad GetStyleRange %.0f for %.0f of %.0f\n", static_cast<double>(position), static_cast<double>(lengthRetrieve), static_cast<double>(style.Length())); return; } style.GetRange(reinterpret_cast<char *>(buffer), position, lengthRetrieve); } const char *CellBuffer::BufferPointer() { return substance.BufferPointer(); } const char *CellBuffer::RangePointer(Sci::Position position, Sci::Position rangeLength) noexcept { return substance.RangePointer(position, rangeLength); } Sci::Position CellBuffer::GapPosition() const noexcept { return substance.GapPosition(); } SplitView CellBuffer::AllView() const noexcept { const size_t length = substance.Length(); size_t length1 = substance.GapPosition(); if (length1 == 0) { // Assign segment2 to segment1 / length1 to avoid useless test against 0 length1 length1 = length; } return SplitView { substance.ElementPointer(0), length1, substance.ElementPointer(length1) - length1, length }; } // The char* returned is to an allocation owned by the undo history const char *CellBuffer::InsertString(Sci::Position position, const char *s, Sci::Position insertLength, bool &startSequence) { // InsertString and DeleteChars are the bottleneck though which all changes occur const char *data = s; if (!readOnly) { if (collectingUndo) { // Save into the undo/redo stack, but only the characters - not the formatting // This takes up about half load time data = uh->AppendAction(ActionType::insert, position, s, insertLength, startSequence); } BasicInsertString(position, s, insertLength); if (changeHistory) { changeHistory->Insert(position, insertLength, collectingUndo, uh->BeforeReachableSavePoint()); } } return data; } bool CellBuffer::SetStyleAt(Sci::Position position, char styleValue) noexcept { if (!hasStyles) { return false; } const char curVal = style.ValueAt(position); if (curVal != styleValue) { style.SetValueAt(position, styleValue); return true; } else { return false; } } bool CellBuffer::SetStyleFor(Sci::Position position, Sci::Position lengthStyle, char styleValue) noexcept { if (!hasStyles) { return false; } bool changed = false; PLATFORM_ASSERT(lengthStyle == 0 || (lengthStyle > 0 && lengthStyle + position <= style.Length())); while (lengthStyle--) { const char curVal = style.ValueAt(position); if (curVal != styleValue) { style.SetValueAt(position, styleValue); changed = true; } position++; } return changed; } // The char* returned is to an allocation owned by the undo history const char *CellBuffer::DeleteChars(Sci::Position position, Sci::Position deleteLength, bool &startSequence) { // InsertString and DeleteChars are the bottleneck though which all changes occur PLATFORM_ASSERT(deleteLength > 0); const char *data = nullptr; if (!readOnly) { if (collectingUndo) { // Save into the undo/redo stack, but only the characters - not the formatting // The gap would be moved to position anyway for the deletion so this doesn't cost extra data = substance.RangePointer(position, deleteLength); data = uh->AppendAction(ActionType::remove, position, data, deleteLength, startSequence); } if (changeHistory) { changeHistory->DeleteRangeSavingHistory(position, deleteLength, uh->BeforeReachableSavePoint(), uh->AfterOrAtDetachPoint()); } BasicDeleteChars(position, deleteLength); } return data; } Sci::Position CellBuffer::Length() const noexcept { return substance.Length(); } void CellBuffer::Allocate(Sci::Position newSize) { if (!largeDocument && (newSize > INT32_MAX)) { throw std::runtime_error("CellBuffer::Allocate: size of standard document limited to 2G."); } substance.ReAllocate(newSize); if (hasStyles) { style.ReAllocate(newSize); } } void CellBuffer::SetUTF8Substance(bool utf8Substance_) noexcept { utf8Substance = utf8Substance_; } void CellBuffer::SetLineEndTypes(LineEndType utf8LineEnds_) { if (utf8LineEnds != utf8LineEnds_) { const LineCharacterIndexType indexes = plv->LineCharacterIndex(); utf8LineEnds = utf8LineEnds_; ResetLineEnds(); AllocateLineCharacterIndex(indexes); } } bool CellBuffer::ContainsLineEnd(const char *s, Sci::Position length) const noexcept { unsigned char chBeforePrev = 0; unsigned char chPrev = 0; for (Sci::Position i = 0; i < length; i++) { const unsigned char ch = s[i]; if ((ch == '\r') || (ch == '\n')) { return true; } else if (utf8LineEnds == LineEndType::Unicode) { if (UTF8IsMultibyteLineEnd(chBeforePrev, chPrev, ch)) { return true; } } chBeforePrev = chPrev; chPrev = ch; } return false; } void CellBuffer::SetPerLine(PerLine *pl) noexcept { plv->SetPerLine(pl); } LineCharacterIndexType CellBuffer::LineCharacterIndex() const noexcept { return plv->LineCharacterIndex(); } void CellBuffer::AllocateLineCharacterIndex(LineCharacterIndexType lineCharacterIndex) { if (utf8Substance) { if (plv->AllocateLineCharacterIndex(lineCharacterIndex, Lines())) { // Changed so recalculate whole file RecalculateIndexLineStarts(0, Lines() - 1); } } } void CellBuffer::ReleaseLineCharacterIndex(LineCharacterIndexType lineCharacterIndex) { plv->ReleaseLineCharacterIndex(lineCharacterIndex); } Sci::Line CellBuffer::Lines() const noexcept { return plv->Lines(); } void CellBuffer::AllocateLines(Sci::Line lines) { plv->AllocateLines(lines); } Sci::Position CellBuffer::LineStart(Sci::Line line) const noexcept { if (line < 0) return 0; else if (line >= Lines()) return Length(); else return plv->LineStart(line); } Sci::Position CellBuffer::LineEnd(Sci::Line line) const noexcept { if (line >= Lines() - 1) { return LineStart(line + 1); } else { Sci::Position position = LineStart(line + 1); if (LineEndType::Unicode == GetLineEndTypes()) { const unsigned char bytes[] = { UCharAt(position - 3), UCharAt(position - 2), UCharAt(position - 1), }; if (UTF8IsSeparator(bytes)) { return position - UTF8SeparatorLength; } if (UTF8IsNEL(bytes + 1)) { return position - UTF8NELLength; } } position--; // Back over CR or LF // When line terminator is CR+LF, may need to go back one more if ((position > LineStart(line)) && (CharAt(position - 1) == '\r')) { position--; } return position; } } Sci::Line CellBuffer::LineFromPosition(Sci::Position pos) const noexcept { return plv->LineFromPosition(pos); } Sci::Position CellBuffer::IndexLineStart(Sci::Line line, LineCharacterIndexType lineCharacterIndex) const noexcept { return plv->IndexLineStart(line, lineCharacterIndex); } Sci::Line CellBuffer::LineFromPositionIndex(Sci::Position pos, LineCharacterIndexType lineCharacterIndex) const noexcept { return plv->LineFromPositionIndex(pos, lineCharacterIndex); } bool CellBuffer::IsReadOnly() const noexcept { return readOnly; } void CellBuffer::SetReadOnly(bool set) noexcept { readOnly = set; } bool CellBuffer::IsLarge() const noexcept { return largeDocument; } bool CellBuffer::HasStyles() const noexcept { return hasStyles; } void CellBuffer::SetSavePoint() { uh->SetSavePoint(); if (changeHistory) { changeHistory->SetSavePoint(); } } bool CellBuffer::IsSavePoint() const noexcept { return uh->IsSavePoint(); } void CellBuffer::TentativeStart() noexcept { uh->TentativeStart(); } void CellBuffer::TentativeCommit() noexcept { uh->TentativeCommit(); } int CellBuffer::TentativeSteps() noexcept { return uh->TentativeSteps(); } bool CellBuffer::TentativeActive() const noexcept { return uh->TentativeActive(); } // Without undo void CellBuffer::InsertLine(Sci::Line line, Sci::Position position, bool lineStart) { plv->InsertLine(line, position, lineStart); } void CellBuffer::RemoveLine(Sci::Line line) { plv->RemoveLine(line); } bool CellBuffer::UTF8LineEndOverlaps(Sci::Position position) const noexcept { const unsigned char bytes[] = { static_cast<unsigned char>(substance.ValueAt(position-2)), static_cast<unsigned char>(substance.ValueAt(position-1)), static_cast<unsigned char>(substance.ValueAt(position)), static_cast<unsigned char>(substance.ValueAt(position+1)), }; return UTF8IsSeparator(bytes) || UTF8IsSeparator(bytes+1) || UTF8IsNEL(bytes+1); } bool CellBuffer::UTF8IsCharacterBoundary(Sci::Position position) const { assert(position >= 0 && position <= Length()); if (position > 0) { std::string back; for (int i = 0; i < UTF8MaxBytes; i++) { const Sci::Position posBack = position - i; if (posBack < 0) { return false; } back.insert(0, 1, substance.ValueAt(posBack)); if (!UTF8IsTrailByte(back.front())) { if (i > 0) { // Have reached a non-trail const int cla = UTF8Classify(back); if ((cla & UTF8MaskInvalid) || (cla != i)) { return false; } } break; } } } if (position < Length()) { const unsigned char fore = substance.ValueAt(position); if (UTF8IsTrailByte(fore)) { return false; } } return true; } void CellBuffer::ResetLineEnds() { // Reinitialize line data -- too much work to preserve const Sci::Line lines = plv->Lines(); plv->Init(); plv->AllocateLines(lines); constexpr Sci::Position position = 0; const Sci::Position length = Length(); plv->InsertText(0, length); Sci::Line lineInsert = 1; constexpr bool atLineStart = true; unsigned char chBeforePrev = 0; unsigned char chPrev = 0; for (Sci::Position i = 0; i < length; i++) { const unsigned char ch = substance.ValueAt(position + i); if (ch == '\r') { InsertLine(lineInsert, (position + i) + 1, atLineStart); lineInsert++; } else if (ch == '\n') { if (chPrev == '\r') { // Patch up what was end of line plv->SetLineStart(lineInsert - 1, (position + i) + 1); } else { InsertLine(lineInsert, (position + i) + 1, atLineStart); lineInsert++; } } else if (utf8LineEnds == LineEndType::Unicode) { if (UTF8IsMultibyteLineEnd(chBeforePrev, chPrev, ch)) { InsertLine(lineInsert, (position + i) + 1, atLineStart); lineInsert++; } } chBeforePrev = chPrev; chPrev = ch; } } namespace { CountWidths CountCharacterWidthsUTF8(std::string_view sv) noexcept { CountWidths cw; size_t remaining = sv.length(); while (remaining > 0) { const int utf8Status = UTF8Classify(sv); const int lenChar = utf8Status & UTF8MaskWidth; cw.CountChar(lenChar); sv.remove_prefix(lenChar); remaining -= lenChar; } return cw; } } bool CellBuffer::MaintainingLineCharacterIndex() const noexcept { return plv->LineCharacterIndex() != LineCharacterIndexType::None; } void CellBuffer::RecalculateIndexLineStarts(Sci::Line lineFirst, Sci::Line lineLast) { std::string text; Sci::Position posLineEnd = LineStart(lineFirst); for (Sci::Line line = lineFirst; line <= lineLast; line++) { // Find line start and end, retrieve text of line, count characters and update line width const Sci::Position posLineStart = posLineEnd; posLineEnd = LineStart(line+1); const Sci::Position width = posLineEnd - posLineStart; text.resize(width); GetCharRange(text.data(), posLineStart, width); const CountWidths cw = CountCharacterWidthsUTF8(text); plv->SetLineCharactersWidth(line, cw); } } void CellBuffer::BasicInsertString(Sci::Position position, const char *s, Sci::Position insertLength) { if (insertLength == 0) return; PLATFORM_ASSERT(insertLength > 0); const unsigned char chAfter = substance.ValueAt(position); bool breakingUTF8LineEnd = false; if (utf8LineEnds == LineEndType::Unicode && UTF8IsTrailByte(chAfter)) { breakingUTF8LineEnd = UTF8LineEndOverlaps(position); } const Sci::Line linePosition = plv->LineFromPosition(position); Sci::Line lineInsert = linePosition + 1; // A simple insertion is one that inserts valid text on a single line at a character boundary bool simpleInsertion = false; const bool maintainingIndex = MaintainingLineCharacterIndex(); // Check for breaking apart a UTF-8 sequence and inserting invalid UTF-8 if (utf8Substance && maintainingIndex) { // Actually, don't need to check that whole insertion is valid just that there // are no potential fragments at ends. simpleInsertion = UTF8IsCharacterBoundary(position) && UTF8IsValid(std::string_view(s, insertLength)); } substance.InsertFromArray(position, s, 0, insertLength); if (hasStyles) { style.InsertValue(position, insertLength, 0); } const bool atLineStart = plv->LineStart(lineInsert-1) == position; // Point all the lines after the insertion point further along in the buffer plv->InsertText(lineInsert-1, insertLength); unsigned char chBeforePrev = substance.ValueAt(position - 2); unsigned char chPrev = substance.ValueAt(position - 1); if (chPrev == '\r' && chAfter == '\n') { // Splitting up a crlf pair at position InsertLine(lineInsert, position, false); lineInsert++; } if (breakingUTF8LineEnd) { RemoveLine(lineInsert); } constexpr size_t PositionBlockSize = 128; Sci::Position positions[PositionBlockSize]{}; size_t nPositions = 0; const Sci::Line lineStart = lineInsert; // s may not NULL-terminated, ensure *ptr == '\n' or *next == '\n' is valid. const char *const end = s + insertLength - 1; const char *ptr = s; unsigned char ch = 0; if (chPrev == '\r' && *ptr == '\n') { ++ptr; // Patch up what was end of line plv->SetLineStart(lineInsert - 1, (position + ptr - s)); simpleInsertion = false; } if (ptr < end) { uint8_t eolTable[256]{}; eolTable[static_cast<uint8_t>('\n')] = 1; eolTable[static_cast<uint8_t>('\r')] = 2; if (utf8LineEnds == LineEndType::Unicode) { // see UniConversion.h for LS, PS and NEL eolTable[0x85] = 4; eolTable[0xa8] = 3; eolTable[0xa9] = 3; } do { // skip to line end ch = *ptr++; uint8_t type; while ((type = eolTable[ch]) == 0 && ptr < end) { chBeforePrev = chPrev; chPrev = ch; ch = *ptr++; } switch (type) { case 2: // '\r' if (*ptr == '\n') { ++ptr; } [[fallthrough]]; case 1: // '\n' positions[nPositions++] = position + ptr - s; if (nPositions == PositionBlockSize) { plv->InsertLines(lineInsert, positions, nPositions, atLineStart); lineInsert += nPositions; nPositions = 0; } break; case 3: case 4: // LS, PS and NEL if ((type == 3 && chPrev == 0x80 && chBeforePrev == 0xe2) || (type == 4 && chPrev == 0xc2)) { positions[nPositions++] = position + ptr - s; if (nPositions == PositionBlockSize) { plv->InsertLines(lineInsert, positions, nPositions, atLineStart); lineInsert += nPositions; nPositions = 0; } } break; } chBeforePrev = chPrev; chPrev = ch; } while (ptr < end); } if (nPositions != 0) { plv->InsertLines(lineInsert, positions, nPositions, atLineStart); lineInsert += nPositions; } ch = *end; if (ptr == end) { ++ptr; if (ch == '\r' || ch == '\n') { InsertLine(lineInsert, (position + ptr - s), atLineStart); lineInsert++; } else if (utf8LineEnds == LineEndType::Unicode && !UTF8IsAscii(ch)) { if (UTF8IsMultibyteLineEnd(chBeforePrev, chPrev, ch)) { InsertLine(lineInsert, (position + ptr - s), atLineStart); lineInsert++; } } } // Joining two lines where last insertion is cr and following substance starts with lf if (chAfter == '\n') { if (ch == '\r') { // End of line already in buffer so drop the newly created one RemoveLine(lineInsert - 1); simpleInsertion = false; } } else if (utf8LineEnds == LineEndType::Unicode && !UTF8IsAscii(chAfter)) { chBeforePrev = chPrev; chPrev = ch; // May have end of UTF-8 line end in buffer and start in insertion for (int j = 0; j < UTF8SeparatorLength-1; j++) { const unsigned char chAt = substance.ValueAt(position + insertLength + j); const unsigned char back3[3] = {chBeforePrev, chPrev, chAt}; if (UTF8IsSeparator(back3)) { InsertLine(lineInsert, (position + insertLength + j) + 1, atLineStart); lineInsert++; } if ((j == 0) && UTF8IsNEL(back3+1)) { InsertLine(lineInsert, (position + insertLength + j) + 1, atLineStart); lineInsert++; } chBeforePrev = chPrev; chPrev = chAt; } } if (maintainingIndex) { if (simpleInsertion && (lineInsert == lineStart)) { const CountWidths cw = CountCharacterWidthsUTF8(std::string_view(s, insertLength)); plv->InsertCharacters(linePosition, cw); } else { RecalculateIndexLineStarts(linePosition, lineInsert - 1); } } } void CellBuffer::BasicDeleteChars(Sci::Position position, Sci::Position deleteLength) { if (deleteLength == 0) return; Sci::Line lineRecalculateStart = Sci::invalidPosition; if ((position == 0) && (deleteLength == substance.Length())) { // If whole buffer is being deleted, faster to reinitialise lines data // than to delete each line. plv->Init(); } else { // Have to fix up line positions before doing deletion as looking at text in buffer // to work out which lines have been removed const Sci::Line linePosition = plv->LineFromPosition(position); Sci::Line lineRemove = linePosition + 1; plv->InsertText(lineRemove-1, - (deleteLength)); const unsigned char chPrev = substance.ValueAt(position - 1); const unsigned char chBefore = chPrev; unsigned char chNext = substance.ValueAt(position); // Check for breaking apart a UTF-8 sequence // Needs further checks that text is UTF-8 or that some other break apart is occurring if (utf8Substance && MaintainingLineCharacterIndex()) { const Sci::Position posEnd = position + deleteLength; const Sci::Line lineEndRemove = plv->LineFromPosition(posEnd); const bool simpleDeletion = (linePosition == lineEndRemove) && UTF8IsCharacterBoundary(position) && UTF8IsCharacterBoundary(posEnd); if (simpleDeletion) { std::string text(deleteLength, '\0'); GetCharRange(text.data(), position, deleteLength); if (UTF8IsValid(text)) { // Everything is good const CountWidths cw = CountCharacterWidthsUTF8(text); plv->InsertCharacters(linePosition, -cw); } else { lineRecalculateStart = linePosition; } } else { lineRecalculateStart = linePosition; } } bool ignoreNL = false; if (chPrev == '\r' && chNext == '\n') { // Move back one plv->SetLineStart(lineRemove, position); lineRemove++; ignoreNL = true; // First \n is not real deletion } if (utf8LineEnds == LineEndType::Unicode && UTF8IsTrailByte(chNext)) { if (UTF8LineEndOverlaps(position)) { RemoveLine(lineRemove); } } unsigned char ch = chNext; for (Sci::Position i = 0; i < deleteLength; i++) { chNext = substance.ValueAt(position + i + 1); if (ch == '\r') { if (chNext != '\n') { RemoveLine(lineRemove); } } else if (ch == '\n') { if (ignoreNL) { ignoreNL = false; // Further \n are real deletions } else { RemoveLine(lineRemove); } } else if (utf8LineEnds == LineEndType::Unicode) { if (!UTF8IsAscii(ch)) { const unsigned char next3[3] = {ch, chNext, static_cast<unsigned char>(substance.ValueAt(position + i + 2))}; if (UTF8IsSeparator(next3) || UTF8IsNEL(next3)) { RemoveLine(lineRemove); } } } ch = chNext; } // May have to fix up end if last deletion causes cr to be next to lf // or removes one of a crlf pair const char chAfter = substance.ValueAt(position + deleteLength); if (chBefore == '\r' && chAfter == '\n') { // Using lineRemove-1 as cr ended line before start of deletion RemoveLine(lineRemove - 1); plv->SetLineStart(lineRemove - 1, position + 1); } } substance.DeleteRange(position, deleteLength); if (lineRecalculateStart >= 0) { RecalculateIndexLineStarts(lineRecalculateStart, lineRecalculateStart); } if (hasStyles) { style.DeleteRange(position, deleteLength); } } bool CellBuffer::SetUndoCollection(bool collectUndo) noexcept { collectingUndo = collectUndo; uh->DropUndoSequence(); return collectingUndo; } bool CellBuffer::IsCollectingUndo() const noexcept { return collectingUndo; } void CellBuffer::BeginUndoAction(bool mayCoalesce) noexcept { uh->BeginUndoAction(mayCoalesce); } void CellBuffer::EndUndoAction() noexcept { uh->EndUndoAction(); } int CellBuffer::UndoSequenceDepth() const noexcept { return uh->UndoSequenceDepth(); } void CellBuffer::AddUndoAction(Sci::Position token, bool mayCoalesce) { bool startSequence = false; uh->AppendAction(ActionType::container, token, nullptr, 0, startSequence, mayCoalesce); } void CellBuffer::DeleteUndoHistory() noexcept { uh->DeleteUndoHistory(); } bool CellBuffer::CanUndo() const noexcept { return uh->CanUndo(); } int CellBuffer::StartUndo() noexcept { return uh->StartUndo(); } Action CellBuffer::GetUndoStep() const noexcept { return uh->GetUndoStep(); } void CellBuffer::PerformUndoStep() { const Action previousStep = uh->GetUndoStep(); // PreviousBeforeSavePoint and AfterDetachPoint are called since acting on the previous action, // that is currentAction-1 if (changeHistory && uh->PreviousBeforeSavePoint()) { changeHistory->StartReversion(); } if (previousStep.at == ActionType::insert) { if (substance.Length() < previousStep.lenData) { throw std::runtime_error( "CellBuffer::PerformUndoStep: deletion must be less than document length."); } if (changeHistory) { changeHistory->DeleteRange(previousStep.position, previousStep.lenData, uh->PreviousBeforeSavePoint() && !uh->AfterDetachPoint()); } BasicDeleteChars(previousStep.position, previousStep.lenData); } else if (previousStep.at == ActionType::remove) { BasicInsertString(previousStep.position, previousStep.data, previousStep.lenData); if (changeHistory) { changeHistory->UndoDeleteStep(previousStep.position, previousStep.lenData, uh->AfterDetachPoint()); } } uh->CompletedUndoStep(); } bool CellBuffer::CanRedo() const noexcept { return uh->CanRedo(); } int CellBuffer::StartRedo() noexcept { return uh->StartRedo(); } Action CellBuffer::GetRedoStep() const noexcept { return uh->GetRedoStep(); } void CellBuffer::PerformRedoStep() { const Action actionStep = uh->GetRedoStep(); if (actionStep.at == ActionType::insert) { BasicInsertString(actionStep.position, actionStep.data, actionStep.lenData); if (changeHistory) { changeHistory->Insert(actionStep.position, actionStep.lenData, collectingUndo, uh->BeforeSavePoint() && !uh->AfterOrAtDetachPoint()); } } else if (actionStep.at == ActionType::remove) { if (changeHistory) { changeHistory->DeleteRangeSavingHistory(actionStep.position, actionStep.lenData, uh->BeforeReachableSavePoint(), uh->AfterOrAtDetachPoint()); } BasicDeleteChars(actionStep.position, actionStep.lenData); } if (changeHistory && uh->AfterSavePoint()) { changeHistory->EndReversion(); } uh->CompletedRedoStep(); } int CellBuffer::UndoActions() const noexcept { return uh->Actions(); } void CellBuffer::SetUndoSavePoint(int action) noexcept { uh->SetSavePoint(action); } int CellBuffer::UndoSavePoint() const noexcept { return uh->SavePoint(); } void CellBuffer::SetUndoDetach(int action) noexcept { uh->SetDetachPoint(action); } int CellBuffer::UndoDetach() const noexcept { return uh->DetachPoint(); } void CellBuffer::SetUndoTentative(int action) noexcept { uh->SetTentative(action); } int CellBuffer::UndoTentative() const noexcept { return uh->TentativePoint(); } namespace { void RestoreChangeHistory(const UndoHistory *uh, ChangeHistory *changeHistory) { // Replay all undo actions into changeHistory const int savePoint = uh->SavePoint(); const int detachPoint = uh->DetachPoint(); const int currentPoint = uh->Current(); for (int act = 0; act < uh->Actions(); act++) { const ActionType type = static_cast<ActionType>(uh->Type(act) & ~coalesceFlag); const Sci::Position position = uh->Position(act); const Sci::Position length = uh->Length(act); const bool beforeSave = act < savePoint || ((detachPoint >= 0) && (detachPoint > act)); const bool afterDetach = (detachPoint >= 0) && (detachPoint < act); switch (type) { case ActionType::insert: changeHistory->Insert(position, length, true, beforeSave); break; case ActionType::remove: changeHistory->DeleteRangeSavingHistory(position, length, beforeSave, afterDetach); break; default: // Only insertions and deletions go into change history break; } changeHistory->Check(); } // Undo back to currentPoint, updating change history for (int act = uh->Actions() - 1; act >= currentPoint; act--) { const ActionType type = static_cast<ActionType>(uh->Type(act) & ~coalesceFlag); const Sci::Position position = uh->Position(act); const Sci::Position length = uh->Length(act); const bool beforeSave = act < savePoint; const bool afterDetach = (detachPoint >= 0) && (detachPoint < act); if (beforeSave) { changeHistory->StartReversion(); } switch (type) { case ActionType::insert: changeHistory->DeleteRange(position, length, beforeSave && !afterDetach); break; case ActionType::remove: changeHistory->UndoDeleteStep(position, length, afterDetach); break; default: // Only insertions and deletions go into change history break; } changeHistory->Check(); } } } void CellBuffer::SetUndoCurrent(int action) { uh->SetCurrent(action, Length()); if (changeHistory) { if ((uh->DetachPoint() >= 0) && (uh->SavePoint() >= 0)) { // Can't have a valid save point and a valid detach point at same time uh->DeleteUndoHistory(); changeHistory.reset(); throw std::runtime_error("UndoHistory::SetCurrent: invalid undo history."); } const intptr_t sizeChange = uh->Delta(action); const intptr_t lengthOriginal = Length() - sizeChange; // Recreate empty change history changeHistory = std::make_unique<ChangeHistory>(lengthOriginal); RestoreChangeHistory(uh.get(), changeHistory.get()); if (Length() != changeHistory->Length()) { uh->DeleteUndoHistory(); changeHistory.reset(); throw std::runtime_error("UndoHistory::SetCurrent: invalid undo history."); } } } int CellBuffer::UndoCurrent() const noexcept { return uh->Current(); } int CellBuffer::UndoActionType(int action) const noexcept { return uh->Type(action); } Sci::Position CellBuffer::UndoActionPosition(int action) const noexcept { return uh->Position(action); } std::string_view CellBuffer::UndoActionText(int action) const noexcept { return uh->Text(action); } void CellBuffer::PushUndoActionType(int type, Sci::Position position) { uh->PushUndoActionType(type, position); } void CellBuffer::ChangeLastUndoActionText(size_t length, const char *text) { uh->ChangeLastUndoActionText(length, text); } void CellBuffer::ChangeHistorySet(bool set) { if (set) { if (!changeHistory && !uh->CanUndo()) { changeHistory = std::make_unique<ChangeHistory>(Length()); } } else { changeHistory.reset(); } } int CellBuffer::EditionAt(Sci::Position pos) const noexcept { if (changeHistory) { return changeHistory->EditionAt(pos); } return 0; } Sci::Position CellBuffer::EditionEndRun(Sci::Position pos) const noexcept { if (changeHistory) { return changeHistory->EditionEndRun(pos); } return Length(); } unsigned int CellBuffer::EditionDeletesAt(Sci::Position pos) const noexcept { if (changeHistory) { return changeHistory->EditionDeletesAt(pos); } return 0; } Sci::Position CellBuffer::EditionNextDelete(Sci::Position pos) const noexcept { if (changeHistory) { return changeHistory->EditionNextDelete(pos); } return Length() + 1; }
40,917
C++
.cxx
1,183
31.796281
133
0.736445
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,581
UndoHistory.cxx
dail8859_NotepadNext/src/scintilla/src/UndoHistory.cxx
// Scintilla source code edit control /** @file UndoHistory.cxx ** Manages undo for the document. **/ // Copyright 1998-2024 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cstddef> #include <cstdlib> #include <cstdint> #include <cassert> #include <cstring> #include <cstdio> #include <cstdarg> #include <climits> #include <stdexcept> #include <string> #include <string_view> #include <vector> #include <optional> #include <algorithm> #include <memory> #include "ScintillaTypes.h" #include "Debugging.h" #include "Position.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "SparseVector.h" #include "ChangeHistory.h" #include "CellBuffer.h" #include "UndoHistory.h" namespace Scintilla::Internal { template <typename T> void VectorTruncate(std::vector<T> &v, size_t length) noexcept { v.erase(v.begin() + length, v.end()); } constexpr size_t byteMask = UINT8_MAX; constexpr size_t byteBits = 8; size_t ReadValue(const uint8_t *bytes, size_t length) noexcept { size_t value = 0; for (size_t i = 0; i < length; i++) { value = (value << byteBits) + bytes[i]; } return value; } void WriteValue(uint8_t *bytes, size_t length, size_t value) noexcept { while (length != 0) { --length; bytes[length] = value & byteMask; value = value >> byteBits; } } size_t ScaledVector::Size() const noexcept { return bytes.size() / element.size; } size_t ScaledVector::ValueAt(size_t index) const noexcept { return ReadValue(bytes.data() + index * element.size, element.size); } intptr_t ScaledVector::SignedValueAt(size_t index) const noexcept { return ReadValue(bytes.data() + index * element.size, element.size); } constexpr SizeMax ElementForValue(size_t value) noexcept { size_t maxN = byteMask; size_t i = 1; while (value > byteMask) { i++; value >>= byteBits; maxN = (maxN << byteBits) + byteMask; } return { i, maxN }; } void ScaledVector::SetValueAt(size_t index, size_t value) { // Check if value fits, if not then expand if (value > element.maxValue) { const SizeMax elementForValue = ElementForValue(value); const size_t length = bytes.size() / element.size; std::vector<uint8_t> bytesNew(elementForValue.size * length); for (size_t i = 0; i < length; i++) { const uint8_t *source = bytes.data() + i * element.size; uint8_t *destination = bytesNew.data() + (i+1) * elementForValue.size - element.size; memcpy(destination, source, element.size); } std::swap(bytes, bytesNew); element = elementForValue; } WriteValue(bytes.data() + index * element.size, element.size, value); } void ScaledVector::ClearValueAt(size_t index) noexcept { // 0 fits in any size element so no expansion needed so no exceptions WriteValue(bytes.data() + index * element.size, element.size, 0); } void ScaledVector::Clear() noexcept { bytes.clear(); } void ScaledVector::Truncate(size_t length) noexcept { VectorTruncate(bytes, length * element.size); assert(bytes.size() == length * element.size); } void ScaledVector::ReSize(size_t length) { bytes.resize(length * element.size); } void ScaledVector::PushBack() { bytes.resize(bytes.size() + element.size); } size_t ScaledVector::SizeInBytes() const noexcept { return bytes.size(); } UndoActionType::UndoActionType() noexcept : at(ActionType::insert), mayCoalesce(false) { } UndoActions::UndoActions() noexcept = default; void UndoActions::Truncate(size_t length) noexcept { VectorTruncate(types, length); assert(types.size() == length); positions.Truncate(length); lengths.Truncate(length); } void UndoActions::PushBack() { types.emplace_back(); positions.PushBack(); lengths.PushBack(); } void UndoActions::Clear() noexcept { types.clear(); positions.Clear(); lengths.Clear(); } intptr_t UndoActions::SSize() const noexcept { return types.size(); } void UndoActions::Create(size_t index, ActionType at_, Sci::Position position_, Sci::Position lenData_, bool mayCoalesce_) { types[index].at = at_; types[index].mayCoalesce = mayCoalesce_; positions.SetValueAt(index, position_); lengths.SetValueAt(index, lenData_); } bool UndoActions::AtStart(size_t index) const noexcept { if (index == 0) { return true; } return !types[index-1].mayCoalesce; } size_t UndoActions::LengthTo(size_t index) const noexcept { size_t sum = 0; for (size_t act = 0; act < index; act++) { sum += lengths.ValueAt(act); } return sum; } Sci::Position UndoActions::Position(int action) const noexcept { return positions.SignedValueAt(action); } Sci::Position UndoActions::Length(int action) const noexcept { return lengths.SignedValueAt(action); } void ScrapStack::Clear() noexcept { stack.clear(); current = 0; } const char *ScrapStack::Push(const char *text, size_t length) { if (current < stack.length()) { stack.resize(current); } stack.append(text, length); current = stack.length(); return stack.data() + current - length; } void ScrapStack::SetCurrent(size_t position) noexcept { current = position; } void ScrapStack::MoveForward(size_t length) noexcept { if ((current + length) <= stack.length()) { current += length; } } void ScrapStack::MoveBack(size_t length) noexcept { if (current >= length) { current -= length; } } const char *ScrapStack::CurrentText() const noexcept { return stack.data() + current; } const char *ScrapStack::TextAt(size_t position) const noexcept { return stack.data() + position; } // The undo history stores a sequence of user operations that represent the user's view of the // commands executed on the text. // Each user operation contains a sequence of text insertion and text deletion actions. // All the user operations are stored in a list of individual actions. // A false 'mayCoalesce' flag acts as an end to a user operation. // Initially there are no actions in the history. // As each action is performed, it is recorded in the history. The action may either become // part of the current user operation or may start a new user operation. If it is to be part of the // current operation, then 'mayCoalesce' is true. If it is to be part of a new operation, the // 'mayCoalesce' flag of the previous action is set false. // The decision of whether to start a new user operation is based upon two factors. If a // compound operation has been explicitly started by calling BeginUndoAction and no matching // EndUndoAction (these calls nest) has been called, then the action is coalesced into the current // operation. If there is no outstanding BeginUndoAction call then a new operation is started // unless it looks as if the new action is caused by the user typing or deleting a stream of text. // Sequences that look like typing or deletion are coalesced into a single user operation. int UndoHistory::PreviousAction() const noexcept { return currentAction - 1; } UndoHistory::UndoHistory() { scraps = std::make_unique<ScrapStack>(); } UndoHistory::~UndoHistory() noexcept = default; const char *UndoHistory::AppendAction(ActionType at, Sci::Position position, const char *data, Sci::Position lengthData, bool &startSequence, bool mayCoalesce) { //Platform::DebugPrintf("%% %d action %d %d %d\n", at, position, lengthData, currentAction); //Platform::DebugPrintf("^ %d action %d %d\n", actions[currentAction - 1].at, // actions[currentAction - 1].position, actions[currentAction - 1].lenData); if (currentAction < savePoint) { savePoint = -1; if (!detach) { detach = currentAction; } } else if (detach && (*detach > currentAction)) { detach = currentAction; } if (undoSequenceDepth > 0) { // Actions not at top level are always coalesced unless this is after return to top level mayCoalesce = true; } bool coalesce = true; if (currentAction >= 1) { int targetAct = currentAction - 1; if (0 == undoSequenceDepth) { // Top level actions may not always be coalesced // Container actions may forward the coalesce state of Scintilla Actions. while ((targetAct > 0) && (actions.types[targetAct].at == ActionType::container) && actions.types[targetAct].mayCoalesce) { targetAct--; } // See if current action can be coalesced into previous action // Will work if both are inserts or deletes and position is same if ((currentAction == savePoint) || (currentAction == tentativePoint)) { coalesce = false; } else if (!mayCoalesce || !actions.types[targetAct].mayCoalesce) { coalesce = false; } else if (at == ActionType::container || actions.types[targetAct].at == ActionType::container) { ; // A coalescible containerAction } else if ((at != actions.types[targetAct].at)) { // } && (!actions.AtStart(targetAct))) { coalesce = false; } else if ((at == ActionType::insert) && (position != (actions.Position(targetAct) + actions.Length(targetAct)))) { // Insertions must be immediately after to coalesce coalesce = false; } else if (at == ActionType::remove) { if ((lengthData == 1) || (lengthData == 2)) { if ((position + lengthData) == actions.Position(targetAct)) { ; // Backspace -> OK } else if (position == actions.Position(targetAct)) { ; // Delete -> OK } else { // Removals must be at same position to coalesce coalesce = false; } } else { // Removals must be of one character to coalesce coalesce = false; } } else { // Action coalesced. } } else { // Actions not at top level are always coalesced unless this is after return to top level if (!actions.types[targetAct].mayCoalesce) coalesce = false; } } else { coalesce = false; } startSequence = !coalesce; // Maybe close previous action if ((currentAction > 0) && startSequence) { actions.types[PreviousAction()].mayCoalesce = false; } const char *dataNew = lengthData ? scraps->Push(data, lengthData) : nullptr; if (currentAction >= actions.SSize()) { actions.PushBack(); } else { actions.Truncate(currentAction+1); } actions.Create(currentAction, at, position, lengthData, mayCoalesce); currentAction++; return dataNew; } void UndoHistory::BeginUndoAction(bool mayCoalesce) noexcept { if (undoSequenceDepth == 0) { if (currentAction > 0) { actions.types[PreviousAction()].mayCoalesce = mayCoalesce; } } undoSequenceDepth++; } void UndoHistory::EndUndoAction() noexcept { PLATFORM_ASSERT(undoSequenceDepth > 0); undoSequenceDepth--; if (0 == undoSequenceDepth) { if (currentAction > 0) { actions.types[PreviousAction()].mayCoalesce = false; } } } int UndoHistory::UndoSequenceDepth() const noexcept { return undoSequenceDepth; } void UndoHistory::DropUndoSequence() noexcept { undoSequenceDepth = 0; } void UndoHistory::DeleteUndoHistory() noexcept { actions.Clear(); currentAction = 0; savePoint = 0; tentativePoint = -1; scraps->Clear(); memory = {}; } int UndoHistory::Actions() const noexcept { return static_cast<int>(actions.SSize()); } void UndoHistory::SetSavePoint(int action) noexcept { savePoint = action; } int UndoHistory::SavePoint() const noexcept { return savePoint; } void UndoHistory::SetSavePoint() noexcept { savePoint = currentAction; detach.reset(); } bool UndoHistory::IsSavePoint() const noexcept { return savePoint == currentAction; } bool UndoHistory::BeforeSavePoint() const noexcept { return (savePoint < 0) || (savePoint > currentAction); } bool UndoHistory::PreviousBeforeSavePoint() const noexcept { return (savePoint < 0) || (savePoint >= currentAction); } bool UndoHistory::BeforeReachableSavePoint() const noexcept { return (savePoint > 0) && (savePoint > currentAction); } bool UndoHistory::AfterSavePoint() const noexcept { return (savePoint >= 0) && (savePoint <= currentAction); } void UndoHistory::SetDetachPoint(int action) noexcept { if (action == -1) { detach = {}; } else { detach = action; } } int UndoHistory::DetachPoint() const noexcept { return detach.value_or(-1); } bool UndoHistory::AfterDetachPoint() const noexcept { return detach && (*detach < currentAction); } bool UndoHistory::AfterOrAtDetachPoint() const noexcept { return detach && (*detach <= currentAction); } intptr_t UndoHistory::Delta(int action) const noexcept { intptr_t sizeChange = 0; for (int act = 0; act < action; act++) { const intptr_t lengthChange = actions.Length(act); sizeChange += (actions.types[act].at == ActionType::insert) ? lengthChange : -lengthChange; } return sizeChange; } bool UndoHistory::Validate(intptr_t lengthDocument) const noexcept { // Check history for validity const intptr_t sizeChange = Delta(currentAction); if (sizeChange > lengthDocument) { // Current document size too small for changes made in undo history. return false; } const intptr_t lengthOriginal = lengthDocument - sizeChange; intptr_t lengthCurrent = lengthOriginal; for (int act = 0; act < actions.SSize(); act++) { const intptr_t lengthChange = actions.Length(act); if (actions.Position(act) > lengthCurrent) { // Change outside document. return false; } lengthCurrent += (actions.types[act].at == ActionType::insert) ? lengthChange : -lengthChange; if (lengthCurrent < 0) { return false; } } return true; } void UndoHistory::SetCurrent(int action, intptr_t lengthDocument) { // Find position in scraps for action memory = {}; const size_t lengthSum = actions.LengthTo(action); scraps->SetCurrent(lengthSum); currentAction = action; if (!Validate(lengthDocument)) { currentAction = 0; DeleteUndoHistory(); throw std::runtime_error("UndoHistory::SetCurrent: invalid undo history."); } } int UndoHistory::Current() const noexcept { return currentAction; } int UndoHistory::Type(int action) const noexcept { const int baseType = static_cast<int>(actions.types[action].at); const int open = actions.types[action].mayCoalesce ? coalesceFlag : 0; return baseType | open; } Sci::Position UndoHistory::Position(int action) const noexcept { return actions.Position(action); } Sci::Position UndoHistory::Length(int action) const noexcept { return actions.Length(action); } std::string_view UndoHistory::Text(int action) noexcept { // Assumes first call after any changes is for action 0. // TODO: may need to invalidate memory in other circumstances if (action == 0) { memory = {}; } int act = 0; size_t position = 0; if (memory && memory->act <= action) { act = memory->act; position = memory->position; } for (; act < action; act++) { position += actions.Length(act); } const size_t length = actions.Length(action); const char *scrap = scraps->TextAt(position); memory = {action, position}; return {scrap, length}; } void UndoHistory::PushUndoActionType(int type, Sci::Position position) { actions.PushBack(); actions.Create(actions.SSize()-1, static_cast<ActionType>(type & byteMask), position, 0, type & coalesceFlag); } void UndoHistory::ChangeLastUndoActionText(size_t length, const char *text) { assert(actions.lengths.ValueAt(actions.SSize()-1) == 0); actions.lengths.SetValueAt(actions.SSize()-1, length); scraps->Push(text, length); } void UndoHistory::SetTentative(int action) noexcept { tentativePoint = action; } int UndoHistory::TentativePoint() const noexcept { return tentativePoint; } void UndoHistory::TentativeStart() noexcept { tentativePoint = currentAction; } void UndoHistory::TentativeCommit() noexcept { tentativePoint = -1; // Truncate undo history actions.Truncate(currentAction); } bool UndoHistory::TentativeActive() const noexcept { return tentativePoint >= 0; } int UndoHistory::TentativeSteps() const noexcept { // Drop any trailing startAction if (tentativePoint >= 0) return currentAction - tentativePoint; return -1; } bool UndoHistory::CanUndo() const noexcept { return (currentAction > 0) && (actions.SSize() != 0); } int UndoHistory::StartUndo() const noexcept { assert(currentAction >= 0); // Count the steps in this action if (currentAction == 0) { return 0; } int act = currentAction - 1; while (act > 0 && !actions.AtStart(act)) { act--; } return currentAction - act; } Action UndoHistory::GetUndoStep() const noexcept { const int previousAction = PreviousAction(); Action acta { actions.types[previousAction].at, actions.types[previousAction].mayCoalesce, actions.Position(previousAction), nullptr, actions.Length(previousAction) }; if (acta.lenData) { acta.data = scraps->CurrentText() - acta.lenData; } return acta; } void UndoHistory::CompletedUndoStep() noexcept { scraps->MoveBack(actions.Length(PreviousAction())); currentAction--; } bool UndoHistory::CanRedo() const noexcept { return actions.SSize() > currentAction; } int UndoHistory::StartRedo() const noexcept { // Count the steps in this action if (currentAction >= actions.SSize()) { // Already at end so can't redo return 0; } // Slightly unusual logic handles case where last action still has mayCoalesce. // Could set mayCoalesce of last action to false in StartUndo but this state is // visible to applications so should not be changed. const int maxAction = Actions() - 1; int act = currentAction; while (act <= maxAction && actions.types[act].mayCoalesce) { act++; } act = std::min(act, maxAction); return act - currentAction + 1; } Action UndoHistory::GetRedoStep() const noexcept { Action acta{ actions.types[currentAction].at, actions.types[currentAction].mayCoalesce, actions.Position(currentAction), nullptr, actions.Length(currentAction) }; if (acta.lenData) { acta.data = scraps->CurrentText(); } return acta; } void UndoHistory::CompletedRedoStep() noexcept { scraps->MoveForward(actions.Length(currentAction)); currentAction++; } }
17,724
C++
.cxx
543
30.445672
126
0.73679
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,594
CatalogueModules.h
dail8859_NotepadNext/src/lexilla/lexlib/CatalogueModules.h
// Scintilla source code edit control /** @file CatalogueModules.h ** Lexer infrastructure. ** Contains a list of LexerModules which can be searched to find a module appropriate for a ** particular language. **/ // Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #ifndef CATALOGUEMODULES_H #define CATALOGUEMODULES_H namespace Lexilla { class CatalogueModules { std::vector<const LexerModule *> lexerCatalogue; public: const LexerModule *Find(int language) const noexcept { for (const LexerModule *lm : lexerCatalogue) { if (lm->GetLanguage() == language) { return lm; } } return nullptr; } const LexerModule *Find(const char *languageName) const noexcept { if (languageName) { for (const LexerModule *lm : lexerCatalogue) { if (lm->languageName && (0 == strcmp(lm->languageName, languageName))) { return lm; } } } return nullptr; } void AddLexerModule(const LexerModule *plm) { lexerCatalogue.push_back(plm); } void AddLexerModules(std::initializer_list<const LexerModule *> modules) { lexerCatalogue.insert(lexerCatalogue.end(), modules); } size_t Count() const noexcept { return lexerCatalogue.size(); } const char *Name(size_t index) const noexcept { if (index < lexerCatalogue.size()) { return lexerCatalogue[index]->languageName; } return ""; } LexerFactoryFunction Factory(size_t index) const noexcept { // Works for object lexers but not for function lexers return lexerCatalogue[index]->fnFactory; } Scintilla::ILexer5 *Create(size_t index) const { const LexerModule *plm = lexerCatalogue[index]; if (!plm) { return nullptr; } return plm->Create(); } }; } #endif
1,781
C++
.h
61
26.491803
94
0.741218
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,602
InList.h
dail8859_NotepadNext/src/lexilla/lexlib/InList.h
// Scintilla source code edit control /** @file InList.h ** Check if a string is in a list. **/ // Copyright 2024 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #ifndef INLIST_H #define INLIST_H namespace Lexilla { bool InList(std::string_view value, std::initializer_list<std::string_view> list) noexcept; bool InListCaseInsensitive(std::string_view value, std::initializer_list<std::string_view> list) noexcept; } #endif
516
C++
.h
13
38.153846
106
0.779116
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,603
SciLexer.h
dail8859_NotepadNext/src/lexilla/include/SciLexer.h
/* Scintilla source code edit control */ /** @file SciLexer.h ** Interface to the added lexer functions in the SciLexer version of the edit control. **/ /* Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org> * The License.txt file describes the conditions under which this software may be distributed. */ /* Most of this file is automatically generated from the Scintilla.iface interface definition * file which contains any comments about the definitions. HFacer.py does the generation. */ #ifndef SCILEXER_H #define SCILEXER_H /* SciLexer features - not in standard Scintilla */ /* ++Autogenerated -- start of section automatically generated from Scintilla.iface */ #define SCLEX_CONTAINER 0 #define SCLEX_NULL 1 #define SCLEX_PYTHON 2 #define SCLEX_CPP 3 #define SCLEX_HTML 4 #define SCLEX_XML 5 #define SCLEX_PERL 6 #define SCLEX_SQL 7 #define SCLEX_VB 8 #define SCLEX_PROPERTIES 9 #define SCLEX_ERRORLIST 10 #define SCLEX_MAKEFILE 11 #define SCLEX_BATCH 12 #define SCLEX_XCODE 13 #define SCLEX_LATEX 14 #define SCLEX_LUA 15 #define SCLEX_DIFF 16 #define SCLEX_CONF 17 #define SCLEX_PASCAL 18 #define SCLEX_AVE 19 #define SCLEX_ADA 20 #define SCLEX_LISP 21 #define SCLEX_RUBY 22 #define SCLEX_EIFFEL 23 #define SCLEX_EIFFELKW 24 #define SCLEX_TCL 25 #define SCLEX_NNCRONTAB 26 #define SCLEX_BULLANT 27 #define SCLEX_VBSCRIPT 28 #define SCLEX_BAAN 31 #define SCLEX_MATLAB 32 #define SCLEX_SCRIPTOL 33 #define SCLEX_ASM 34 #define SCLEX_CPPNOCASE 35 #define SCLEX_FORTRAN 36 #define SCLEX_F77 37 #define SCLEX_CSS 38 #define SCLEX_POV 39 #define SCLEX_LOUT 40 #define SCLEX_ESCRIPT 41 #define SCLEX_PS 42 #define SCLEX_NSIS 43 #define SCLEX_MMIXAL 44 #define SCLEX_CLW 45 #define SCLEX_CLWNOCASE 46 #define SCLEX_LOT 47 #define SCLEX_YAML 48 #define SCLEX_TEX 49 #define SCLEX_METAPOST 50 #define SCLEX_POWERBASIC 51 #define SCLEX_FORTH 52 #define SCLEX_ERLANG 53 #define SCLEX_OCTAVE 54 #define SCLEX_MSSQL 55 #define SCLEX_VERILOG 56 #define SCLEX_KIX 57 #define SCLEX_GUI4CLI 58 #define SCLEX_SPECMAN 59 #define SCLEX_AU3 60 #define SCLEX_APDL 61 #define SCLEX_BASH 62 #define SCLEX_ASN1 63 #define SCLEX_VHDL 64 #define SCLEX_CAML 65 #define SCLEX_BLITZBASIC 66 #define SCLEX_PUREBASIC 67 #define SCLEX_HASKELL 68 #define SCLEX_PHPSCRIPT 69 #define SCLEX_TADS3 70 #define SCLEX_REBOL 71 #define SCLEX_SMALLTALK 72 #define SCLEX_FLAGSHIP 73 #define SCLEX_CSOUND 74 #define SCLEX_FREEBASIC 75 #define SCLEX_INNOSETUP 76 #define SCLEX_OPAL 77 #define SCLEX_SPICE 78 #define SCLEX_D 79 #define SCLEX_CMAKE 80 #define SCLEX_GAP 81 #define SCLEX_PLM 82 #define SCLEX_PROGRESS 83 #define SCLEX_ABAQUS 84 #define SCLEX_ASYMPTOTE 85 #define SCLEX_R 86 #define SCLEX_MAGIK 87 #define SCLEX_POWERSHELL 88 #define SCLEX_MYSQL 89 #define SCLEX_PO 90 #define SCLEX_TAL 91 #define SCLEX_COBOL 92 #define SCLEX_TACL 93 #define SCLEX_SORCUS 94 #define SCLEX_POWERPRO 95 #define SCLEX_NIMROD 96 #define SCLEX_SML 97 #define SCLEX_MARKDOWN 98 #define SCLEX_TXT2TAGS 99 #define SCLEX_A68K 100 #define SCLEX_MODULA 101 #define SCLEX_COFFEESCRIPT 102 #define SCLEX_TCMD 103 #define SCLEX_AVS 104 #define SCLEX_ECL 105 #define SCLEX_OSCRIPT 106 #define SCLEX_VISUALPROLOG 107 #define SCLEX_LITERATEHASKELL 108 #define SCLEX_STTXT 109 #define SCLEX_KVIRC 110 #define SCLEX_RUST 111 #define SCLEX_DMAP 112 #define SCLEX_AS 113 #define SCLEX_DMIS 114 #define SCLEX_REGISTRY 115 #define SCLEX_BIBTEX 116 #define SCLEX_SREC 117 #define SCLEX_IHEX 118 #define SCLEX_TEHEX 119 #define SCLEX_JSON 120 #define SCLEX_EDIFACT 121 #define SCLEX_INDENT 122 #define SCLEX_MAXIMA 123 #define SCLEX_STATA 124 #define SCLEX_SAS 125 #define SCLEX_NIM 126 #define SCLEX_CIL 127 #define SCLEX_X12 128 #define SCLEX_DATAFLEX 129 #define SCLEX_HOLLYWOOD 130 #define SCLEX_RAKU 131 #define SCLEX_FSHARP 132 #define SCLEX_JULIA 133 #define SCLEX_ASCIIDOC 134 #define SCLEX_GDSCRIPT 135 #define SCLEX_TOML 136 #define SCLEX_TROFF 137 #define SCLEX_DART 138 #define SCLEX_ZIG 139 #define SCLEX_AUTOMATIC 1000 #define SCE_P_DEFAULT 0 #define SCE_P_COMMENTLINE 1 #define SCE_P_NUMBER 2 #define SCE_P_STRING 3 #define SCE_P_CHARACTER 4 #define SCE_P_WORD 5 #define SCE_P_TRIPLE 6 #define SCE_P_TRIPLEDOUBLE 7 #define SCE_P_CLASSNAME 8 #define SCE_P_DEFNAME 9 #define SCE_P_OPERATOR 10 #define SCE_P_IDENTIFIER 11 #define SCE_P_COMMENTBLOCK 12 #define SCE_P_STRINGEOL 13 #define SCE_P_WORD2 14 #define SCE_P_DECORATOR 15 #define SCE_P_FSTRING 16 #define SCE_P_FCHARACTER 17 #define SCE_P_FTRIPLE 18 #define SCE_P_FTRIPLEDOUBLE 19 #define SCE_P_ATTRIBUTE 20 #define SCE_C_DEFAULT 0 #define SCE_C_COMMENT 1 #define SCE_C_COMMENTLINE 2 #define SCE_C_COMMENTDOC 3 #define SCE_C_NUMBER 4 #define SCE_C_WORD 5 #define SCE_C_STRING 6 #define SCE_C_CHARACTER 7 #define SCE_C_UUID 8 #define SCE_C_PREPROCESSOR 9 #define SCE_C_OPERATOR 10 #define SCE_C_IDENTIFIER 11 #define SCE_C_STRINGEOL 12 #define SCE_C_VERBATIM 13 #define SCE_C_REGEX 14 #define SCE_C_COMMENTLINEDOC 15 #define SCE_C_WORD2 16 #define SCE_C_COMMENTDOCKEYWORD 17 #define SCE_C_COMMENTDOCKEYWORDERROR 18 #define SCE_C_GLOBALCLASS 19 #define SCE_C_STRINGRAW 20 #define SCE_C_TRIPLEVERBATIM 21 #define SCE_C_HASHQUOTEDSTRING 22 #define SCE_C_PREPROCESSORCOMMENT 23 #define SCE_C_PREPROCESSORCOMMENTDOC 24 #define SCE_C_USERLITERAL 25 #define SCE_C_TASKMARKER 26 #define SCE_C_ESCAPESEQUENCE 27 #define SCE_D_DEFAULT 0 #define SCE_D_COMMENT 1 #define SCE_D_COMMENTLINE 2 #define SCE_D_COMMENTDOC 3 #define SCE_D_COMMENTNESTED 4 #define SCE_D_NUMBER 5 #define SCE_D_WORD 6 #define SCE_D_WORD2 7 #define SCE_D_WORD3 8 #define SCE_D_TYPEDEF 9 #define SCE_D_STRING 10 #define SCE_D_STRINGEOL 11 #define SCE_D_CHARACTER 12 #define SCE_D_OPERATOR 13 #define SCE_D_IDENTIFIER 14 #define SCE_D_COMMENTLINEDOC 15 #define SCE_D_COMMENTDOCKEYWORD 16 #define SCE_D_COMMENTDOCKEYWORDERROR 17 #define SCE_D_STRINGB 18 #define SCE_D_STRINGR 19 #define SCE_D_WORD5 20 #define SCE_D_WORD6 21 #define SCE_D_WORD7 22 #define SCE_TCL_DEFAULT 0 #define SCE_TCL_COMMENT 1 #define SCE_TCL_COMMENTLINE 2 #define SCE_TCL_NUMBER 3 #define SCE_TCL_WORD_IN_QUOTE 4 #define SCE_TCL_IN_QUOTE 5 #define SCE_TCL_OPERATOR 6 #define SCE_TCL_IDENTIFIER 7 #define SCE_TCL_SUBSTITUTION 8 #define SCE_TCL_SUB_BRACE 9 #define SCE_TCL_MODIFIER 10 #define SCE_TCL_EXPAND 11 #define SCE_TCL_WORD 12 #define SCE_TCL_WORD2 13 #define SCE_TCL_WORD3 14 #define SCE_TCL_WORD4 15 #define SCE_TCL_WORD5 16 #define SCE_TCL_WORD6 17 #define SCE_TCL_WORD7 18 #define SCE_TCL_WORD8 19 #define SCE_TCL_COMMENT_BOX 20 #define SCE_TCL_BLOCK_COMMENT 21 #define SCE_H_DEFAULT 0 #define SCE_H_TAG 1 #define SCE_H_TAGUNKNOWN 2 #define SCE_H_ATTRIBUTE 3 #define SCE_H_ATTRIBUTEUNKNOWN 4 #define SCE_H_NUMBER 5 #define SCE_H_DOUBLESTRING 6 #define SCE_H_SINGLESTRING 7 #define SCE_H_OTHER 8 #define SCE_H_COMMENT 9 #define SCE_H_ENTITY 10 #define SCE_H_TAGEND 11 #define SCE_H_XMLSTART 12 #define SCE_H_XMLEND 13 #define SCE_H_SCRIPT 14 #define SCE_H_ASP 15 #define SCE_H_ASPAT 16 #define SCE_H_CDATA 17 #define SCE_H_QUESTION 18 #define SCE_H_VALUE 19 #define SCE_H_XCCOMMENT 20 #define SCE_H_SGML_DEFAULT 21 #define SCE_H_SGML_COMMAND 22 #define SCE_H_SGML_1ST_PARAM 23 #define SCE_H_SGML_DOUBLESTRING 24 #define SCE_H_SGML_SIMPLESTRING 25 #define SCE_H_SGML_ERROR 26 #define SCE_H_SGML_SPECIAL 27 #define SCE_H_SGML_ENTITY 28 #define SCE_H_SGML_COMMENT 29 #define SCE_H_SGML_1ST_PARAM_COMMENT 30 #define SCE_H_SGML_BLOCK_DEFAULT 31 #define SCE_HJ_START 40 #define SCE_HJ_DEFAULT 41 #define SCE_HJ_COMMENT 42 #define SCE_HJ_COMMENTLINE 43 #define SCE_HJ_COMMENTDOC 44 #define SCE_HJ_NUMBER 45 #define SCE_HJ_WORD 46 #define SCE_HJ_KEYWORD 47 #define SCE_HJ_DOUBLESTRING 48 #define SCE_HJ_SINGLESTRING 49 #define SCE_HJ_SYMBOLS 50 #define SCE_HJ_STRINGEOL 51 #define SCE_HJ_REGEX 52 #define SCE_HJ_TEMPLATELITERAL 53 #define SCE_HJA_START 55 #define SCE_HJA_DEFAULT 56 #define SCE_HJA_COMMENT 57 #define SCE_HJA_COMMENTLINE 58 #define SCE_HJA_COMMENTDOC 59 #define SCE_HJA_NUMBER 60 #define SCE_HJA_WORD 61 #define SCE_HJA_KEYWORD 62 #define SCE_HJA_DOUBLESTRING 63 #define SCE_HJA_SINGLESTRING 64 #define SCE_HJA_SYMBOLS 65 #define SCE_HJA_STRINGEOL 66 #define SCE_HJA_REGEX 67 #define SCE_HJA_TEMPLATELITERAL 68 #define SCE_HB_START 70 #define SCE_HB_DEFAULT 71 #define SCE_HB_COMMENTLINE 72 #define SCE_HB_NUMBER 73 #define SCE_HB_WORD 74 #define SCE_HB_STRING 75 #define SCE_HB_IDENTIFIER 76 #define SCE_HB_STRINGEOL 77 #define SCE_HBA_START 80 #define SCE_HBA_DEFAULT 81 #define SCE_HBA_COMMENTLINE 82 #define SCE_HBA_NUMBER 83 #define SCE_HBA_WORD 84 #define SCE_HBA_STRING 85 #define SCE_HBA_IDENTIFIER 86 #define SCE_HBA_STRINGEOL 87 #define SCE_HP_START 90 #define SCE_HP_DEFAULT 91 #define SCE_HP_COMMENTLINE 92 #define SCE_HP_NUMBER 93 #define SCE_HP_STRING 94 #define SCE_HP_CHARACTER 95 #define SCE_HP_WORD 96 #define SCE_HP_TRIPLE 97 #define SCE_HP_TRIPLEDOUBLE 98 #define SCE_HP_CLASSNAME 99 #define SCE_HP_DEFNAME 100 #define SCE_HP_OPERATOR 101 #define SCE_HP_IDENTIFIER 102 #define SCE_HPHP_COMPLEX_VARIABLE 104 #define SCE_HPA_START 105 #define SCE_HPA_DEFAULT 106 #define SCE_HPA_COMMENTLINE 107 #define SCE_HPA_NUMBER 108 #define SCE_HPA_STRING 109 #define SCE_HPA_CHARACTER 110 #define SCE_HPA_WORD 111 #define SCE_HPA_TRIPLE 112 #define SCE_HPA_TRIPLEDOUBLE 113 #define SCE_HPA_CLASSNAME 114 #define SCE_HPA_DEFNAME 115 #define SCE_HPA_OPERATOR 116 #define SCE_HPA_IDENTIFIER 117 #define SCE_HPHP_DEFAULT 118 #define SCE_HPHP_HSTRING 119 #define SCE_HPHP_SIMPLESTRING 120 #define SCE_HPHP_WORD 121 #define SCE_HPHP_NUMBER 122 #define SCE_HPHP_VARIABLE 123 #define SCE_HPHP_COMMENT 124 #define SCE_HPHP_COMMENTLINE 125 #define SCE_HPHP_HSTRING_VARIABLE 126 #define SCE_HPHP_OPERATOR 127 #define SCE_PL_DEFAULT 0 #define SCE_PL_ERROR 1 #define SCE_PL_COMMENTLINE 2 #define SCE_PL_POD 3 #define SCE_PL_NUMBER 4 #define SCE_PL_WORD 5 #define SCE_PL_STRING 6 #define SCE_PL_CHARACTER 7 #define SCE_PL_PUNCTUATION 8 #define SCE_PL_PREPROCESSOR 9 #define SCE_PL_OPERATOR 10 #define SCE_PL_IDENTIFIER 11 #define SCE_PL_SCALAR 12 #define SCE_PL_ARRAY 13 #define SCE_PL_HASH 14 #define SCE_PL_SYMBOLTABLE 15 #define SCE_PL_VARIABLE_INDEXER 16 #define SCE_PL_REGEX 17 #define SCE_PL_REGSUBST 18 #define SCE_PL_LONGQUOTE 19 #define SCE_PL_BACKTICKS 20 #define SCE_PL_DATASECTION 21 #define SCE_PL_HERE_DELIM 22 #define SCE_PL_HERE_Q 23 #define SCE_PL_HERE_QQ 24 #define SCE_PL_HERE_QX 25 #define SCE_PL_STRING_Q 26 #define SCE_PL_STRING_QQ 27 #define SCE_PL_STRING_QX 28 #define SCE_PL_STRING_QR 29 #define SCE_PL_STRING_QW 30 #define SCE_PL_POD_VERB 31 #define SCE_PL_SUB_PROTOTYPE 40 #define SCE_PL_FORMAT_IDENT 41 #define SCE_PL_FORMAT 42 #define SCE_PL_STRING_VAR 43 #define SCE_PL_XLAT 44 #define SCE_PL_REGEX_VAR 54 #define SCE_PL_REGSUBST_VAR 55 #define SCE_PL_BACKTICKS_VAR 57 #define SCE_PL_HERE_QQ_VAR 61 #define SCE_PL_HERE_QX_VAR 62 #define SCE_PL_STRING_QQ_VAR 64 #define SCE_PL_STRING_QX_VAR 65 #define SCE_PL_STRING_QR_VAR 66 #define SCE_RB_DEFAULT 0 #define SCE_RB_ERROR 1 #define SCE_RB_COMMENTLINE 2 #define SCE_RB_POD 3 #define SCE_RB_NUMBER 4 #define SCE_RB_WORD 5 #define SCE_RB_STRING 6 #define SCE_RB_CHARACTER 7 #define SCE_RB_CLASSNAME 8 #define SCE_RB_DEFNAME 9 #define SCE_RB_OPERATOR 10 #define SCE_RB_IDENTIFIER 11 #define SCE_RB_REGEX 12 #define SCE_RB_GLOBAL 13 #define SCE_RB_SYMBOL 14 #define SCE_RB_MODULE_NAME 15 #define SCE_RB_INSTANCE_VAR 16 #define SCE_RB_CLASS_VAR 17 #define SCE_RB_BACKTICKS 18 #define SCE_RB_DATASECTION 19 #define SCE_RB_HERE_DELIM 20 #define SCE_RB_HERE_Q 21 #define SCE_RB_HERE_QQ 22 #define SCE_RB_HERE_QX 23 #define SCE_RB_STRING_Q 24 #define SCE_RB_STRING_QQ 25 #define SCE_RB_STRING_QX 26 #define SCE_RB_STRING_QR 27 #define SCE_RB_STRING_QW 28 #define SCE_RB_WORD_DEMOTED 29 #define SCE_RB_STDIN 30 #define SCE_RB_STDOUT 31 #define SCE_RB_STDERR 40 #define SCE_RB_STRING_W 41 #define SCE_RB_STRING_I 42 #define SCE_RB_STRING_QI 43 #define SCE_RB_STRING_QS 44 #define SCE_RB_UPPER_BOUND 45 #define SCE_B_DEFAULT 0 #define SCE_B_COMMENT 1 #define SCE_B_NUMBER 2 #define SCE_B_KEYWORD 3 #define SCE_B_STRING 4 #define SCE_B_PREPROCESSOR 5 #define SCE_B_OPERATOR 6 #define SCE_B_IDENTIFIER 7 #define SCE_B_DATE 8 #define SCE_B_STRINGEOL 9 #define SCE_B_KEYWORD2 10 #define SCE_B_KEYWORD3 11 #define SCE_B_KEYWORD4 12 #define SCE_B_CONSTANT 13 #define SCE_B_ASM 14 #define SCE_B_LABEL 15 #define SCE_B_ERROR 16 #define SCE_B_HEXNUMBER 17 #define SCE_B_BINNUMBER 18 #define SCE_B_COMMENTBLOCK 19 #define SCE_B_DOCLINE 20 #define SCE_B_DOCBLOCK 21 #define SCE_B_DOCKEYWORD 22 #define SCE_PROPS_DEFAULT 0 #define SCE_PROPS_COMMENT 1 #define SCE_PROPS_SECTION 2 #define SCE_PROPS_ASSIGNMENT 3 #define SCE_PROPS_DEFVAL 4 #define SCE_PROPS_KEY 5 #define SCE_L_DEFAULT 0 #define SCE_L_COMMAND 1 #define SCE_L_TAG 2 #define SCE_L_MATH 3 #define SCE_L_COMMENT 4 #define SCE_L_TAG2 5 #define SCE_L_MATH2 6 #define SCE_L_COMMENT2 7 #define SCE_L_VERBATIM 8 #define SCE_L_SHORTCMD 9 #define SCE_L_SPECIAL 10 #define SCE_L_CMDOPT 11 #define SCE_L_ERROR 12 #define SCE_LUA_DEFAULT 0 #define SCE_LUA_COMMENT 1 #define SCE_LUA_COMMENTLINE 2 #define SCE_LUA_COMMENTDOC 3 #define SCE_LUA_NUMBER 4 #define SCE_LUA_WORD 5 #define SCE_LUA_STRING 6 #define SCE_LUA_CHARACTER 7 #define SCE_LUA_LITERALSTRING 8 #define SCE_LUA_PREPROCESSOR 9 #define SCE_LUA_OPERATOR 10 #define SCE_LUA_IDENTIFIER 11 #define SCE_LUA_STRINGEOL 12 #define SCE_LUA_WORD2 13 #define SCE_LUA_WORD3 14 #define SCE_LUA_WORD4 15 #define SCE_LUA_WORD5 16 #define SCE_LUA_WORD6 17 #define SCE_LUA_WORD7 18 #define SCE_LUA_WORD8 19 #define SCE_LUA_LABEL 20 #define SCE_ERR_DEFAULT 0 #define SCE_ERR_PYTHON 1 #define SCE_ERR_GCC 2 #define SCE_ERR_MS 3 #define SCE_ERR_CMD 4 #define SCE_ERR_BORLAND 5 #define SCE_ERR_PERL 6 #define SCE_ERR_NET 7 #define SCE_ERR_LUA 8 #define SCE_ERR_CTAG 9 #define SCE_ERR_DIFF_CHANGED 10 #define SCE_ERR_DIFF_ADDITION 11 #define SCE_ERR_DIFF_DELETION 12 #define SCE_ERR_DIFF_MESSAGE 13 #define SCE_ERR_PHP 14 #define SCE_ERR_ELF 15 #define SCE_ERR_IFC 16 #define SCE_ERR_IFORT 17 #define SCE_ERR_ABSF 18 #define SCE_ERR_TIDY 19 #define SCE_ERR_JAVA_STACK 20 #define SCE_ERR_VALUE 21 #define SCE_ERR_GCC_INCLUDED_FROM 22 #define SCE_ERR_ESCSEQ 23 #define SCE_ERR_ESCSEQ_UNKNOWN 24 #define SCE_ERR_GCC_EXCERPT 25 #define SCE_ERR_BASH 26 #define SCE_ERR_ES_BLACK 40 #define SCE_ERR_ES_RED 41 #define SCE_ERR_ES_GREEN 42 #define SCE_ERR_ES_BROWN 43 #define SCE_ERR_ES_BLUE 44 #define SCE_ERR_ES_MAGENTA 45 #define SCE_ERR_ES_CYAN 46 #define SCE_ERR_ES_GRAY 47 #define SCE_ERR_ES_DARK_GRAY 48 #define SCE_ERR_ES_BRIGHT_RED 49 #define SCE_ERR_ES_BRIGHT_GREEN 50 #define SCE_ERR_ES_YELLOW 51 #define SCE_ERR_ES_BRIGHT_BLUE 52 #define SCE_ERR_ES_BRIGHT_MAGENTA 53 #define SCE_ERR_ES_BRIGHT_CYAN 54 #define SCE_ERR_ES_WHITE 55 #define SCE_BAT_DEFAULT 0 #define SCE_BAT_COMMENT 1 #define SCE_BAT_WORD 2 #define SCE_BAT_LABEL 3 #define SCE_BAT_HIDE 4 #define SCE_BAT_COMMAND 5 #define SCE_BAT_IDENTIFIER 6 #define SCE_BAT_OPERATOR 7 #define SCE_BAT_AFTER_LABEL 8 #define SCE_TCMD_DEFAULT 0 #define SCE_TCMD_COMMENT 1 #define SCE_TCMD_WORD 2 #define SCE_TCMD_LABEL 3 #define SCE_TCMD_HIDE 4 #define SCE_TCMD_COMMAND 5 #define SCE_TCMD_IDENTIFIER 6 #define SCE_TCMD_OPERATOR 7 #define SCE_TCMD_ENVIRONMENT 8 #define SCE_TCMD_EXPANSION 9 #define SCE_TCMD_CLABEL 10 #define SCE_MAKE_DEFAULT 0 #define SCE_MAKE_COMMENT 1 #define SCE_MAKE_PREPROCESSOR 2 #define SCE_MAKE_IDENTIFIER 3 #define SCE_MAKE_OPERATOR 4 #define SCE_MAKE_TARGET 5 #define SCE_MAKE_IDEOL 9 #define SCE_DIFF_DEFAULT 0 #define SCE_DIFF_COMMENT 1 #define SCE_DIFF_COMMAND 2 #define SCE_DIFF_HEADER 3 #define SCE_DIFF_POSITION 4 #define SCE_DIFF_DELETED 5 #define SCE_DIFF_ADDED 6 #define SCE_DIFF_CHANGED 7 #define SCE_DIFF_PATCH_ADD 8 #define SCE_DIFF_PATCH_DELETE 9 #define SCE_DIFF_REMOVED_PATCH_ADD 10 #define SCE_DIFF_REMOVED_PATCH_DELETE 11 #define SCE_CONF_DEFAULT 0 #define SCE_CONF_COMMENT 1 #define SCE_CONF_NUMBER 2 #define SCE_CONF_IDENTIFIER 3 #define SCE_CONF_EXTENSION 4 #define SCE_CONF_PARAMETER 5 #define SCE_CONF_STRING 6 #define SCE_CONF_OPERATOR 7 #define SCE_CONF_IP 8 #define SCE_CONF_DIRECTIVE 9 #define SCE_AVE_DEFAULT 0 #define SCE_AVE_COMMENT 1 #define SCE_AVE_NUMBER 2 #define SCE_AVE_WORD 3 #define SCE_AVE_STRING 6 #define SCE_AVE_ENUM 7 #define SCE_AVE_STRINGEOL 8 #define SCE_AVE_IDENTIFIER 9 #define SCE_AVE_OPERATOR 10 #define SCE_AVE_WORD1 11 #define SCE_AVE_WORD2 12 #define SCE_AVE_WORD3 13 #define SCE_AVE_WORD4 14 #define SCE_AVE_WORD5 15 #define SCE_AVE_WORD6 16 #define SCE_ADA_DEFAULT 0 #define SCE_ADA_WORD 1 #define SCE_ADA_IDENTIFIER 2 #define SCE_ADA_NUMBER 3 #define SCE_ADA_DELIMITER 4 #define SCE_ADA_CHARACTER 5 #define SCE_ADA_CHARACTEREOL 6 #define SCE_ADA_STRING 7 #define SCE_ADA_STRINGEOL 8 #define SCE_ADA_LABEL 9 #define SCE_ADA_COMMENTLINE 10 #define SCE_ADA_ILLEGAL 11 #define SCE_BAAN_DEFAULT 0 #define SCE_BAAN_COMMENT 1 #define SCE_BAAN_COMMENTDOC 2 #define SCE_BAAN_NUMBER 3 #define SCE_BAAN_WORD 4 #define SCE_BAAN_STRING 5 #define SCE_BAAN_PREPROCESSOR 6 #define SCE_BAAN_OPERATOR 7 #define SCE_BAAN_IDENTIFIER 8 #define SCE_BAAN_STRINGEOL 9 #define SCE_BAAN_WORD2 10 #define SCE_BAAN_WORD3 11 #define SCE_BAAN_WORD4 12 #define SCE_BAAN_WORD5 13 #define SCE_BAAN_WORD6 14 #define SCE_BAAN_WORD7 15 #define SCE_BAAN_WORD8 16 #define SCE_BAAN_WORD9 17 #define SCE_BAAN_TABLEDEF 18 #define SCE_BAAN_TABLESQL 19 #define SCE_BAAN_FUNCTION 20 #define SCE_BAAN_DOMDEF 21 #define SCE_BAAN_FUNCDEF 22 #define SCE_BAAN_OBJECTDEF 23 #define SCE_BAAN_DEFINEDEF 24 #define SCE_LISP_DEFAULT 0 #define SCE_LISP_COMMENT 1 #define SCE_LISP_NUMBER 2 #define SCE_LISP_KEYWORD 3 #define SCE_LISP_KEYWORD_KW 4 #define SCE_LISP_SYMBOL 5 #define SCE_LISP_STRING 6 #define SCE_LISP_STRINGEOL 8 #define SCE_LISP_IDENTIFIER 9 #define SCE_LISP_OPERATOR 10 #define SCE_LISP_SPECIAL 11 #define SCE_LISP_MULTI_COMMENT 12 #define SCE_EIFFEL_DEFAULT 0 #define SCE_EIFFEL_COMMENTLINE 1 #define SCE_EIFFEL_NUMBER 2 #define SCE_EIFFEL_WORD 3 #define SCE_EIFFEL_STRING 4 #define SCE_EIFFEL_CHARACTER 5 #define SCE_EIFFEL_OPERATOR 6 #define SCE_EIFFEL_IDENTIFIER 7 #define SCE_EIFFEL_STRINGEOL 8 #define SCE_NNCRONTAB_DEFAULT 0 #define SCE_NNCRONTAB_COMMENT 1 #define SCE_NNCRONTAB_TASK 2 #define SCE_NNCRONTAB_SECTION 3 #define SCE_NNCRONTAB_KEYWORD 4 #define SCE_NNCRONTAB_MODIFIER 5 #define SCE_NNCRONTAB_ASTERISK 6 #define SCE_NNCRONTAB_NUMBER 7 #define SCE_NNCRONTAB_STRING 8 #define SCE_NNCRONTAB_ENVIRONMENT 9 #define SCE_NNCRONTAB_IDENTIFIER 10 #define SCE_FORTH_DEFAULT 0 #define SCE_FORTH_COMMENT 1 #define SCE_FORTH_COMMENT_ML 2 #define SCE_FORTH_IDENTIFIER 3 #define SCE_FORTH_CONTROL 4 #define SCE_FORTH_KEYWORD 5 #define SCE_FORTH_DEFWORD 6 #define SCE_FORTH_PREWORD1 7 #define SCE_FORTH_PREWORD2 8 #define SCE_FORTH_NUMBER 9 #define SCE_FORTH_STRING 10 #define SCE_FORTH_LOCALE 11 #define SCE_MATLAB_DEFAULT 0 #define SCE_MATLAB_COMMENT 1 #define SCE_MATLAB_COMMAND 2 #define SCE_MATLAB_NUMBER 3 #define SCE_MATLAB_KEYWORD 4 #define SCE_MATLAB_STRING 5 #define SCE_MATLAB_OPERATOR 6 #define SCE_MATLAB_IDENTIFIER 7 #define SCE_MATLAB_DOUBLEQUOTESTRING 8 #define SCE_MAXIMA_OPERATOR 0 #define SCE_MAXIMA_COMMANDENDING 1 #define SCE_MAXIMA_COMMENT 2 #define SCE_MAXIMA_NUMBER 3 #define SCE_MAXIMA_STRING 4 #define SCE_MAXIMA_COMMAND 5 #define SCE_MAXIMA_VARIABLE 6 #define SCE_MAXIMA_UNKNOWN 7 #define SCE_SCRIPTOL_DEFAULT 0 #define SCE_SCRIPTOL_WHITE 1 #define SCE_SCRIPTOL_COMMENTLINE 2 #define SCE_SCRIPTOL_PERSISTENT 3 #define SCE_SCRIPTOL_CSTYLE 4 #define SCE_SCRIPTOL_COMMENTBLOCK 5 #define SCE_SCRIPTOL_NUMBER 6 #define SCE_SCRIPTOL_STRING 7 #define SCE_SCRIPTOL_CHARACTER 8 #define SCE_SCRIPTOL_STRINGEOL 9 #define SCE_SCRIPTOL_KEYWORD 10 #define SCE_SCRIPTOL_OPERATOR 11 #define SCE_SCRIPTOL_IDENTIFIER 12 #define SCE_SCRIPTOL_TRIPLE 13 #define SCE_SCRIPTOL_CLASSNAME 14 #define SCE_SCRIPTOL_PREPROCESSOR 15 #define SCE_ASM_DEFAULT 0 #define SCE_ASM_COMMENT 1 #define SCE_ASM_NUMBER 2 #define SCE_ASM_STRING 3 #define SCE_ASM_OPERATOR 4 #define SCE_ASM_IDENTIFIER 5 #define SCE_ASM_CPUINSTRUCTION 6 #define SCE_ASM_MATHINSTRUCTION 7 #define SCE_ASM_REGISTER 8 #define SCE_ASM_DIRECTIVE 9 #define SCE_ASM_DIRECTIVEOPERAND 10 #define SCE_ASM_COMMENTBLOCK 11 #define SCE_ASM_CHARACTER 12 #define SCE_ASM_STRINGEOL 13 #define SCE_ASM_EXTINSTRUCTION 14 #define SCE_ASM_COMMENTDIRECTIVE 15 #define SCE_F_DEFAULT 0 #define SCE_F_COMMENT 1 #define SCE_F_NUMBER 2 #define SCE_F_STRING1 3 #define SCE_F_STRING2 4 #define SCE_F_STRINGEOL 5 #define SCE_F_OPERATOR 6 #define SCE_F_IDENTIFIER 7 #define SCE_F_WORD 8 #define SCE_F_WORD2 9 #define SCE_F_WORD3 10 #define SCE_F_PREPROCESSOR 11 #define SCE_F_OPERATOR2 12 #define SCE_F_LABEL 13 #define SCE_F_CONTINUATION 14 #define SCE_CSS_DEFAULT 0 #define SCE_CSS_TAG 1 #define SCE_CSS_CLASS 2 #define SCE_CSS_PSEUDOCLASS 3 #define SCE_CSS_UNKNOWN_PSEUDOCLASS 4 #define SCE_CSS_OPERATOR 5 #define SCE_CSS_IDENTIFIER 6 #define SCE_CSS_UNKNOWN_IDENTIFIER 7 #define SCE_CSS_VALUE 8 #define SCE_CSS_COMMENT 9 #define SCE_CSS_ID 10 #define SCE_CSS_IMPORTANT 11 #define SCE_CSS_DIRECTIVE 12 #define SCE_CSS_DOUBLESTRING 13 #define SCE_CSS_SINGLESTRING 14 #define SCE_CSS_IDENTIFIER2 15 #define SCE_CSS_ATTRIBUTE 16 #define SCE_CSS_IDENTIFIER3 17 #define SCE_CSS_PSEUDOELEMENT 18 #define SCE_CSS_EXTENDED_IDENTIFIER 19 #define SCE_CSS_EXTENDED_PSEUDOCLASS 20 #define SCE_CSS_EXTENDED_PSEUDOELEMENT 21 #define SCE_CSS_GROUP_RULE 22 #define SCE_CSS_VARIABLE 23 #define SCE_POV_DEFAULT 0 #define SCE_POV_COMMENT 1 #define SCE_POV_COMMENTLINE 2 #define SCE_POV_NUMBER 3 #define SCE_POV_OPERATOR 4 #define SCE_POV_IDENTIFIER 5 #define SCE_POV_STRING 6 #define SCE_POV_STRINGEOL 7 #define SCE_POV_DIRECTIVE 8 #define SCE_POV_BADDIRECTIVE 9 #define SCE_POV_WORD2 10 #define SCE_POV_WORD3 11 #define SCE_POV_WORD4 12 #define SCE_POV_WORD5 13 #define SCE_POV_WORD6 14 #define SCE_POV_WORD7 15 #define SCE_POV_WORD8 16 #define SCE_LOUT_DEFAULT 0 #define SCE_LOUT_COMMENT 1 #define SCE_LOUT_NUMBER 2 #define SCE_LOUT_WORD 3 #define SCE_LOUT_WORD2 4 #define SCE_LOUT_WORD3 5 #define SCE_LOUT_WORD4 6 #define SCE_LOUT_STRING 7 #define SCE_LOUT_OPERATOR 8 #define SCE_LOUT_IDENTIFIER 9 #define SCE_LOUT_STRINGEOL 10 #define SCE_ESCRIPT_DEFAULT 0 #define SCE_ESCRIPT_COMMENT 1 #define SCE_ESCRIPT_COMMENTLINE 2 #define SCE_ESCRIPT_COMMENTDOC 3 #define SCE_ESCRIPT_NUMBER 4 #define SCE_ESCRIPT_WORD 5 #define SCE_ESCRIPT_STRING 6 #define SCE_ESCRIPT_OPERATOR 7 #define SCE_ESCRIPT_IDENTIFIER 8 #define SCE_ESCRIPT_BRACE 9 #define SCE_ESCRIPT_WORD2 10 #define SCE_ESCRIPT_WORD3 11 #define SCE_PS_DEFAULT 0 #define SCE_PS_COMMENT 1 #define SCE_PS_DSC_COMMENT 2 #define SCE_PS_DSC_VALUE 3 #define SCE_PS_NUMBER 4 #define SCE_PS_NAME 5 #define SCE_PS_KEYWORD 6 #define SCE_PS_LITERAL 7 #define SCE_PS_IMMEVAL 8 #define SCE_PS_PAREN_ARRAY 9 #define SCE_PS_PAREN_DICT 10 #define SCE_PS_PAREN_PROC 11 #define SCE_PS_TEXT 12 #define SCE_PS_HEXSTRING 13 #define SCE_PS_BASE85STRING 14 #define SCE_PS_BADSTRINGCHAR 15 #define SCE_NSIS_DEFAULT 0 #define SCE_NSIS_COMMENT 1 #define SCE_NSIS_STRINGDQ 2 #define SCE_NSIS_STRINGLQ 3 #define SCE_NSIS_STRINGRQ 4 #define SCE_NSIS_FUNCTION 5 #define SCE_NSIS_VARIABLE 6 #define SCE_NSIS_LABEL 7 #define SCE_NSIS_USERDEFINED 8 #define SCE_NSIS_SECTIONDEF 9 #define SCE_NSIS_SUBSECTIONDEF 10 #define SCE_NSIS_IFDEFINEDEF 11 #define SCE_NSIS_MACRODEF 12 #define SCE_NSIS_STRINGVAR 13 #define SCE_NSIS_NUMBER 14 #define SCE_NSIS_SECTIONGROUP 15 #define SCE_NSIS_PAGEEX 16 #define SCE_NSIS_FUNCTIONDEF 17 #define SCE_NSIS_COMMENTBOX 18 #define SCE_MMIXAL_LEADWS 0 #define SCE_MMIXAL_COMMENT 1 #define SCE_MMIXAL_LABEL 2 #define SCE_MMIXAL_OPCODE 3 #define SCE_MMIXAL_OPCODE_PRE 4 #define SCE_MMIXAL_OPCODE_VALID 5 #define SCE_MMIXAL_OPCODE_UNKNOWN 6 #define SCE_MMIXAL_OPCODE_POST 7 #define SCE_MMIXAL_OPERANDS 8 #define SCE_MMIXAL_NUMBER 9 #define SCE_MMIXAL_REF 10 #define SCE_MMIXAL_CHAR 11 #define SCE_MMIXAL_STRING 12 #define SCE_MMIXAL_REGISTER 13 #define SCE_MMIXAL_HEX 14 #define SCE_MMIXAL_OPERATOR 15 #define SCE_MMIXAL_SYMBOL 16 #define SCE_MMIXAL_INCLUDE 17 #define SCE_CLW_DEFAULT 0 #define SCE_CLW_LABEL 1 #define SCE_CLW_COMMENT 2 #define SCE_CLW_STRING 3 #define SCE_CLW_USER_IDENTIFIER 4 #define SCE_CLW_INTEGER_CONSTANT 5 #define SCE_CLW_REAL_CONSTANT 6 #define SCE_CLW_PICTURE_STRING 7 #define SCE_CLW_KEYWORD 8 #define SCE_CLW_COMPILER_DIRECTIVE 9 #define SCE_CLW_RUNTIME_EXPRESSIONS 10 #define SCE_CLW_BUILTIN_PROCEDURES_FUNCTION 11 #define SCE_CLW_STRUCTURE_DATA_TYPE 12 #define SCE_CLW_ATTRIBUTE 13 #define SCE_CLW_STANDARD_EQUATE 14 #define SCE_CLW_ERROR 15 #define SCE_CLW_DEPRECATED 16 #define SCE_LOT_DEFAULT 0 #define SCE_LOT_HEADER 1 #define SCE_LOT_BREAK 2 #define SCE_LOT_SET 3 #define SCE_LOT_PASS 4 #define SCE_LOT_FAIL 5 #define SCE_LOT_ABORT 6 #define SCE_YAML_DEFAULT 0 #define SCE_YAML_COMMENT 1 #define SCE_YAML_IDENTIFIER 2 #define SCE_YAML_KEYWORD 3 #define SCE_YAML_NUMBER 4 #define SCE_YAML_REFERENCE 5 #define SCE_YAML_DOCUMENT 6 #define SCE_YAML_TEXT 7 #define SCE_YAML_ERROR 8 #define SCE_YAML_OPERATOR 9 #define SCE_TEX_DEFAULT 0 #define SCE_TEX_SPECIAL 1 #define SCE_TEX_GROUP 2 #define SCE_TEX_SYMBOL 3 #define SCE_TEX_COMMAND 4 #define SCE_TEX_TEXT 5 #define SCE_METAPOST_DEFAULT 0 #define SCE_METAPOST_SPECIAL 1 #define SCE_METAPOST_GROUP 2 #define SCE_METAPOST_SYMBOL 3 #define SCE_METAPOST_COMMAND 4 #define SCE_METAPOST_TEXT 5 #define SCE_METAPOST_EXTRA 6 #define SCE_ERLANG_DEFAULT 0 #define SCE_ERLANG_COMMENT 1 #define SCE_ERLANG_VARIABLE 2 #define SCE_ERLANG_NUMBER 3 #define SCE_ERLANG_KEYWORD 4 #define SCE_ERLANG_STRING 5 #define SCE_ERLANG_OPERATOR 6 #define SCE_ERLANG_ATOM 7 #define SCE_ERLANG_FUNCTION_NAME 8 #define SCE_ERLANG_CHARACTER 9 #define SCE_ERLANG_MACRO 10 #define SCE_ERLANG_RECORD 11 #define SCE_ERLANG_PREPROC 12 #define SCE_ERLANG_NODE_NAME 13 #define SCE_ERLANG_COMMENT_FUNCTION 14 #define SCE_ERLANG_COMMENT_MODULE 15 #define SCE_ERLANG_COMMENT_DOC 16 #define SCE_ERLANG_COMMENT_DOC_MACRO 17 #define SCE_ERLANG_ATOM_QUOTED 18 #define SCE_ERLANG_MACRO_QUOTED 19 #define SCE_ERLANG_RECORD_QUOTED 20 #define SCE_ERLANG_NODE_NAME_QUOTED 21 #define SCE_ERLANG_BIFS 22 #define SCE_ERLANG_MODULES 23 #define SCE_ERLANG_MODULES_ATT 24 #define SCE_ERLANG_UNKNOWN 31 #define SCE_JULIA_DEFAULT 0 #define SCE_JULIA_COMMENT 1 #define SCE_JULIA_NUMBER 2 #define SCE_JULIA_KEYWORD1 3 #define SCE_JULIA_KEYWORD2 4 #define SCE_JULIA_KEYWORD3 5 #define SCE_JULIA_CHAR 6 #define SCE_JULIA_OPERATOR 7 #define SCE_JULIA_BRACKET 8 #define SCE_JULIA_IDENTIFIER 9 #define SCE_JULIA_STRING 10 #define SCE_JULIA_SYMBOL 11 #define SCE_JULIA_MACRO 12 #define SCE_JULIA_STRINGINTERP 13 #define SCE_JULIA_DOCSTRING 14 #define SCE_JULIA_STRINGLITERAL 15 #define SCE_JULIA_COMMAND 16 #define SCE_JULIA_COMMANDLITERAL 17 #define SCE_JULIA_TYPEANNOT 18 #define SCE_JULIA_LEXERROR 19 #define SCE_JULIA_KEYWORD4 20 #define SCE_JULIA_TYPEOPERATOR 21 #define SCE_MSSQL_DEFAULT 0 #define SCE_MSSQL_COMMENT 1 #define SCE_MSSQL_LINE_COMMENT 2 #define SCE_MSSQL_NUMBER 3 #define SCE_MSSQL_STRING 4 #define SCE_MSSQL_OPERATOR 5 #define SCE_MSSQL_IDENTIFIER 6 #define SCE_MSSQL_VARIABLE 7 #define SCE_MSSQL_COLUMN_NAME 8 #define SCE_MSSQL_STATEMENT 9 #define SCE_MSSQL_DATATYPE 10 #define SCE_MSSQL_SYSTABLE 11 #define SCE_MSSQL_GLOBAL_VARIABLE 12 #define SCE_MSSQL_FUNCTION 13 #define SCE_MSSQL_STORED_PROCEDURE 14 #define SCE_MSSQL_DEFAULT_PREF_DATATYPE 15 #define SCE_MSSQL_COLUMN_NAME_2 16 #define SCE_V_DEFAULT 0 #define SCE_V_COMMENT 1 #define SCE_V_COMMENTLINE 2 #define SCE_V_COMMENTLINEBANG 3 #define SCE_V_NUMBER 4 #define SCE_V_WORD 5 #define SCE_V_STRING 6 #define SCE_V_WORD2 7 #define SCE_V_WORD3 8 #define SCE_V_PREPROCESSOR 9 #define SCE_V_OPERATOR 10 #define SCE_V_IDENTIFIER 11 #define SCE_V_STRINGEOL 12 #define SCE_V_USER 19 #define SCE_V_COMMENT_WORD 20 #define SCE_V_INPUT 21 #define SCE_V_OUTPUT 22 #define SCE_V_INOUT 23 #define SCE_V_PORT_CONNECT 24 #define SCE_KIX_DEFAULT 0 #define SCE_KIX_COMMENT 1 #define SCE_KIX_STRING1 2 #define SCE_KIX_STRING2 3 #define SCE_KIX_NUMBER 4 #define SCE_KIX_VAR 5 #define SCE_KIX_MACRO 6 #define SCE_KIX_KEYWORD 7 #define SCE_KIX_FUNCTIONS 8 #define SCE_KIX_OPERATOR 9 #define SCE_KIX_COMMENTSTREAM 10 #define SCE_KIX_IDENTIFIER 31 #define SCE_GC_DEFAULT 0 #define SCE_GC_COMMENTLINE 1 #define SCE_GC_COMMENTBLOCK 2 #define SCE_GC_GLOBAL 3 #define SCE_GC_EVENT 4 #define SCE_GC_ATTRIBUTE 5 #define SCE_GC_CONTROL 6 #define SCE_GC_COMMAND 7 #define SCE_GC_STRING 8 #define SCE_GC_OPERATOR 9 #define SCE_SN_DEFAULT 0 #define SCE_SN_CODE 1 #define SCE_SN_COMMENTLINE 2 #define SCE_SN_COMMENTLINEBANG 3 #define SCE_SN_NUMBER 4 #define SCE_SN_WORD 5 #define SCE_SN_STRING 6 #define SCE_SN_WORD2 7 #define SCE_SN_WORD3 8 #define SCE_SN_PREPROCESSOR 9 #define SCE_SN_OPERATOR 10 #define SCE_SN_IDENTIFIER 11 #define SCE_SN_STRINGEOL 12 #define SCE_SN_REGEXTAG 13 #define SCE_SN_SIGNAL 14 #define SCE_SN_USER 19 #define SCE_AU3_DEFAULT 0 #define SCE_AU3_COMMENT 1 #define SCE_AU3_COMMENTBLOCK 2 #define SCE_AU3_NUMBER 3 #define SCE_AU3_FUNCTION 4 #define SCE_AU3_KEYWORD 5 #define SCE_AU3_MACRO 6 #define SCE_AU3_STRING 7 #define SCE_AU3_OPERATOR 8 #define SCE_AU3_VARIABLE 9 #define SCE_AU3_SENT 10 #define SCE_AU3_PREPROCESSOR 11 #define SCE_AU3_SPECIAL 12 #define SCE_AU3_EXPAND 13 #define SCE_AU3_COMOBJ 14 #define SCE_AU3_UDF 15 #define SCE_APDL_DEFAULT 0 #define SCE_APDL_COMMENT 1 #define SCE_APDL_COMMENTBLOCK 2 #define SCE_APDL_NUMBER 3 #define SCE_APDL_STRING 4 #define SCE_APDL_OPERATOR 5 #define SCE_APDL_WORD 6 #define SCE_APDL_PROCESSOR 7 #define SCE_APDL_COMMAND 8 #define SCE_APDL_SLASHCOMMAND 9 #define SCE_APDL_STARCOMMAND 10 #define SCE_APDL_ARGUMENT 11 #define SCE_APDL_FUNCTION 12 #define SCE_SH_DEFAULT 0 #define SCE_SH_ERROR 1 #define SCE_SH_COMMENTLINE 2 #define SCE_SH_NUMBER 3 #define SCE_SH_WORD 4 #define SCE_SH_STRING 5 #define SCE_SH_CHARACTER 6 #define SCE_SH_OPERATOR 7 #define SCE_SH_IDENTIFIER 8 #define SCE_SH_SCALAR 9 #define SCE_SH_PARAM 10 #define SCE_SH_BACKTICKS 11 #define SCE_SH_HERE_DELIM 12 #define SCE_SH_HERE_Q 13 #define SCE_ASN1_DEFAULT 0 #define SCE_ASN1_COMMENT 1 #define SCE_ASN1_IDENTIFIER 2 #define SCE_ASN1_STRING 3 #define SCE_ASN1_OID 4 #define SCE_ASN1_SCALAR 5 #define SCE_ASN1_KEYWORD 6 #define SCE_ASN1_ATTRIBUTE 7 #define SCE_ASN1_DESCRIPTOR 8 #define SCE_ASN1_TYPE 9 #define SCE_ASN1_OPERATOR 10 #define SCE_VHDL_DEFAULT 0 #define SCE_VHDL_COMMENT 1 #define SCE_VHDL_COMMENTLINEBANG 2 #define SCE_VHDL_NUMBER 3 #define SCE_VHDL_STRING 4 #define SCE_VHDL_OPERATOR 5 #define SCE_VHDL_IDENTIFIER 6 #define SCE_VHDL_STRINGEOL 7 #define SCE_VHDL_KEYWORD 8 #define SCE_VHDL_STDOPERATOR 9 #define SCE_VHDL_ATTRIBUTE 10 #define SCE_VHDL_STDFUNCTION 11 #define SCE_VHDL_STDPACKAGE 12 #define SCE_VHDL_STDTYPE 13 #define SCE_VHDL_USERWORD 14 #define SCE_VHDL_BLOCK_COMMENT 15 #define SCE_CAML_DEFAULT 0 #define SCE_CAML_IDENTIFIER 1 #define SCE_CAML_TAGNAME 2 #define SCE_CAML_KEYWORD 3 #define SCE_CAML_KEYWORD2 4 #define SCE_CAML_KEYWORD3 5 #define SCE_CAML_LINENUM 6 #define SCE_CAML_OPERATOR 7 #define SCE_CAML_NUMBER 8 #define SCE_CAML_CHAR 9 #define SCE_CAML_WHITE 10 #define SCE_CAML_STRING 11 #define SCE_CAML_COMMENT 12 #define SCE_CAML_COMMENT1 13 #define SCE_CAML_COMMENT2 14 #define SCE_CAML_COMMENT3 15 #define SCE_HA_DEFAULT 0 #define SCE_HA_IDENTIFIER 1 #define SCE_HA_KEYWORD 2 #define SCE_HA_NUMBER 3 #define SCE_HA_STRING 4 #define SCE_HA_CHARACTER 5 #define SCE_HA_CLASS 6 #define SCE_HA_MODULE 7 #define SCE_HA_CAPITAL 8 #define SCE_HA_DATA 9 #define SCE_HA_IMPORT 10 #define SCE_HA_OPERATOR 11 #define SCE_HA_INSTANCE 12 #define SCE_HA_COMMENTLINE 13 #define SCE_HA_COMMENTBLOCK 14 #define SCE_HA_COMMENTBLOCK2 15 #define SCE_HA_COMMENTBLOCK3 16 #define SCE_HA_PRAGMA 17 #define SCE_HA_PREPROCESSOR 18 #define SCE_HA_STRINGEOL 19 #define SCE_HA_RESERVED_OPERATOR 20 #define SCE_HA_LITERATE_COMMENT 21 #define SCE_HA_LITERATE_CODEDELIM 22 #define SCE_T3_DEFAULT 0 #define SCE_T3_X_DEFAULT 1 #define SCE_T3_PREPROCESSOR 2 #define SCE_T3_BLOCK_COMMENT 3 #define SCE_T3_LINE_COMMENT 4 #define SCE_T3_OPERATOR 5 #define SCE_T3_KEYWORD 6 #define SCE_T3_NUMBER 7 #define SCE_T3_IDENTIFIER 8 #define SCE_T3_S_STRING 9 #define SCE_T3_D_STRING 10 #define SCE_T3_X_STRING 11 #define SCE_T3_LIB_DIRECTIVE 12 #define SCE_T3_MSG_PARAM 13 #define SCE_T3_HTML_TAG 14 #define SCE_T3_HTML_DEFAULT 15 #define SCE_T3_HTML_STRING 16 #define SCE_T3_USER1 17 #define SCE_T3_USER2 18 #define SCE_T3_USER3 19 #define SCE_T3_BRACE 20 #define SCE_REBOL_DEFAULT 0 #define SCE_REBOL_COMMENTLINE 1 #define SCE_REBOL_COMMENTBLOCK 2 #define SCE_REBOL_PREFACE 3 #define SCE_REBOL_OPERATOR 4 #define SCE_REBOL_CHARACTER 5 #define SCE_REBOL_QUOTEDSTRING 6 #define SCE_REBOL_BRACEDSTRING 7 #define SCE_REBOL_NUMBER 8 #define SCE_REBOL_PAIR 9 #define SCE_REBOL_TUPLE 10 #define SCE_REBOL_BINARY 11 #define SCE_REBOL_MONEY 12 #define SCE_REBOL_ISSUE 13 #define SCE_REBOL_TAG 14 #define SCE_REBOL_FILE 15 #define SCE_REBOL_EMAIL 16 #define SCE_REBOL_URL 17 #define SCE_REBOL_DATE 18 #define SCE_REBOL_TIME 19 #define SCE_REBOL_IDENTIFIER 20 #define SCE_REBOL_WORD 21 #define SCE_REBOL_WORD2 22 #define SCE_REBOL_WORD3 23 #define SCE_REBOL_WORD4 24 #define SCE_REBOL_WORD5 25 #define SCE_REBOL_WORD6 26 #define SCE_REBOL_WORD7 27 #define SCE_REBOL_WORD8 28 #define SCE_SQL_DEFAULT 0 #define SCE_SQL_COMMENT 1 #define SCE_SQL_COMMENTLINE 2 #define SCE_SQL_COMMENTDOC 3 #define SCE_SQL_NUMBER 4 #define SCE_SQL_WORD 5 #define SCE_SQL_STRING 6 #define SCE_SQL_CHARACTER 7 #define SCE_SQL_SQLPLUS 8 #define SCE_SQL_SQLPLUS_PROMPT 9 #define SCE_SQL_OPERATOR 10 #define SCE_SQL_IDENTIFIER 11 #define SCE_SQL_SQLPLUS_COMMENT 13 #define SCE_SQL_COMMENTLINEDOC 15 #define SCE_SQL_WORD2 16 #define SCE_SQL_COMMENTDOCKEYWORD 17 #define SCE_SQL_COMMENTDOCKEYWORDERROR 18 #define SCE_SQL_USER1 19 #define SCE_SQL_USER2 20 #define SCE_SQL_USER3 21 #define SCE_SQL_USER4 22 #define SCE_SQL_QUOTEDIDENTIFIER 23 #define SCE_SQL_QOPERATOR 24 #define SCE_ST_DEFAULT 0 #define SCE_ST_STRING 1 #define SCE_ST_NUMBER 2 #define SCE_ST_COMMENT 3 #define SCE_ST_SYMBOL 4 #define SCE_ST_BINARY 5 #define SCE_ST_BOOL 6 #define SCE_ST_SELF 7 #define SCE_ST_SUPER 8 #define SCE_ST_NIL 9 #define SCE_ST_GLOBAL 10 #define SCE_ST_RETURN 11 #define SCE_ST_SPECIAL 12 #define SCE_ST_KWSEND 13 #define SCE_ST_ASSIGN 14 #define SCE_ST_CHARACTER 15 #define SCE_ST_SPEC_SEL 16 #define SCE_FS_DEFAULT 0 #define SCE_FS_COMMENT 1 #define SCE_FS_COMMENTLINE 2 #define SCE_FS_COMMENTDOC 3 #define SCE_FS_COMMENTLINEDOC 4 #define SCE_FS_COMMENTDOCKEYWORD 5 #define SCE_FS_COMMENTDOCKEYWORDERROR 6 #define SCE_FS_KEYWORD 7 #define SCE_FS_KEYWORD2 8 #define SCE_FS_KEYWORD3 9 #define SCE_FS_KEYWORD4 10 #define SCE_FS_NUMBER 11 #define SCE_FS_STRING 12 #define SCE_FS_PREPROCESSOR 13 #define SCE_FS_OPERATOR 14 #define SCE_FS_IDENTIFIER 15 #define SCE_FS_DATE 16 #define SCE_FS_STRINGEOL 17 #define SCE_FS_CONSTANT 18 #define SCE_FS_WORDOPERATOR 19 #define SCE_FS_DISABLEDCODE 20 #define SCE_FS_DEFAULT_C 21 #define SCE_FS_COMMENTDOC_C 22 #define SCE_FS_COMMENTLINEDOC_C 23 #define SCE_FS_KEYWORD_C 24 #define SCE_FS_KEYWORD2_C 25 #define SCE_FS_NUMBER_C 26 #define SCE_FS_STRING_C 27 #define SCE_FS_PREPROCESSOR_C 28 #define SCE_FS_OPERATOR_C 29 #define SCE_FS_IDENTIFIER_C 30 #define SCE_FS_STRINGEOL_C 31 #define SCE_CSOUND_DEFAULT 0 #define SCE_CSOUND_COMMENT 1 #define SCE_CSOUND_NUMBER 2 #define SCE_CSOUND_OPERATOR 3 #define SCE_CSOUND_INSTR 4 #define SCE_CSOUND_IDENTIFIER 5 #define SCE_CSOUND_OPCODE 6 #define SCE_CSOUND_HEADERSTMT 7 #define SCE_CSOUND_USERKEYWORD 8 #define SCE_CSOUND_COMMENTBLOCK 9 #define SCE_CSOUND_PARAM 10 #define SCE_CSOUND_ARATE_VAR 11 #define SCE_CSOUND_KRATE_VAR 12 #define SCE_CSOUND_IRATE_VAR 13 #define SCE_CSOUND_GLOBAL_VAR 14 #define SCE_CSOUND_STRINGEOL 15 #define SCE_INNO_DEFAULT 0 #define SCE_INNO_COMMENT 1 #define SCE_INNO_KEYWORD 2 #define SCE_INNO_PARAMETER 3 #define SCE_INNO_SECTION 4 #define SCE_INNO_PREPROC 5 #define SCE_INNO_INLINE_EXPANSION 6 #define SCE_INNO_COMMENT_PASCAL 7 #define SCE_INNO_KEYWORD_PASCAL 8 #define SCE_INNO_KEYWORD_USER 9 #define SCE_INNO_STRING_DOUBLE 10 #define SCE_INNO_STRING_SINGLE 11 #define SCE_INNO_IDENTIFIER 12 #define SCE_OPAL_SPACE 0 #define SCE_OPAL_COMMENT_BLOCK 1 #define SCE_OPAL_COMMENT_LINE 2 #define SCE_OPAL_INTEGER 3 #define SCE_OPAL_KEYWORD 4 #define SCE_OPAL_SORT 5 #define SCE_OPAL_STRING 6 #define SCE_OPAL_PAR 7 #define SCE_OPAL_BOOL_CONST 8 #define SCE_OPAL_DEFAULT 32 #define SCE_SPICE_DEFAULT 0 #define SCE_SPICE_IDENTIFIER 1 #define SCE_SPICE_KEYWORD 2 #define SCE_SPICE_KEYWORD2 3 #define SCE_SPICE_KEYWORD3 4 #define SCE_SPICE_NUMBER 5 #define SCE_SPICE_DELIMITER 6 #define SCE_SPICE_VALUE 7 #define SCE_SPICE_COMMENTLINE 8 #define SCE_CMAKE_DEFAULT 0 #define SCE_CMAKE_COMMENT 1 #define SCE_CMAKE_STRINGDQ 2 #define SCE_CMAKE_STRINGLQ 3 #define SCE_CMAKE_STRINGRQ 4 #define SCE_CMAKE_COMMANDS 5 #define SCE_CMAKE_PARAMETERS 6 #define SCE_CMAKE_VARIABLE 7 #define SCE_CMAKE_USERDEFINED 8 #define SCE_CMAKE_WHILEDEF 9 #define SCE_CMAKE_FOREACHDEF 10 #define SCE_CMAKE_IFDEFINEDEF 11 #define SCE_CMAKE_MACRODEF 12 #define SCE_CMAKE_STRINGVAR 13 #define SCE_CMAKE_NUMBER 14 #define SCE_GAP_DEFAULT 0 #define SCE_GAP_IDENTIFIER 1 #define SCE_GAP_KEYWORD 2 #define SCE_GAP_KEYWORD2 3 #define SCE_GAP_KEYWORD3 4 #define SCE_GAP_KEYWORD4 5 #define SCE_GAP_STRING 6 #define SCE_GAP_CHAR 7 #define SCE_GAP_OPERATOR 8 #define SCE_GAP_COMMENT 9 #define SCE_GAP_NUMBER 10 #define SCE_GAP_STRINGEOL 11 #define SCE_PLM_DEFAULT 0 #define SCE_PLM_COMMENT 1 #define SCE_PLM_STRING 2 #define SCE_PLM_NUMBER 3 #define SCE_PLM_IDENTIFIER 4 #define SCE_PLM_OPERATOR 5 #define SCE_PLM_CONTROL 6 #define SCE_PLM_KEYWORD 7 #define SCE_ABL_DEFAULT 0 #define SCE_ABL_NUMBER 1 #define SCE_ABL_WORD 2 #define SCE_ABL_STRING 3 #define SCE_ABL_CHARACTER 4 #define SCE_ABL_PREPROCESSOR 5 #define SCE_ABL_OPERATOR 6 #define SCE_ABL_IDENTIFIER 7 #define SCE_ABL_BLOCK 8 #define SCE_ABL_END 9 #define SCE_ABL_COMMENT 10 #define SCE_ABL_TASKMARKER 11 #define SCE_ABL_LINECOMMENT 12 #define SCE_ABAQUS_DEFAULT 0 #define SCE_ABAQUS_COMMENT 1 #define SCE_ABAQUS_COMMENTBLOCK 2 #define SCE_ABAQUS_NUMBER 3 #define SCE_ABAQUS_STRING 4 #define SCE_ABAQUS_OPERATOR 5 #define SCE_ABAQUS_WORD 6 #define SCE_ABAQUS_PROCESSOR 7 #define SCE_ABAQUS_COMMAND 8 #define SCE_ABAQUS_SLASHCOMMAND 9 #define SCE_ABAQUS_STARCOMMAND 10 #define SCE_ABAQUS_ARGUMENT 11 #define SCE_ABAQUS_FUNCTION 12 #define SCE_ASY_DEFAULT 0 #define SCE_ASY_COMMENT 1 #define SCE_ASY_COMMENTLINE 2 #define SCE_ASY_NUMBER 3 #define SCE_ASY_WORD 4 #define SCE_ASY_STRING 5 #define SCE_ASY_CHARACTER 6 #define SCE_ASY_OPERATOR 7 #define SCE_ASY_IDENTIFIER 8 #define SCE_ASY_STRINGEOL 9 #define SCE_ASY_COMMENTLINEDOC 10 #define SCE_ASY_WORD2 11 #define SCE_R_DEFAULT 0 #define SCE_R_COMMENT 1 #define SCE_R_KWORD 2 #define SCE_R_BASEKWORD 3 #define SCE_R_OTHERKWORD 4 #define SCE_R_NUMBER 5 #define SCE_R_STRING 6 #define SCE_R_STRING2 7 #define SCE_R_OPERATOR 8 #define SCE_R_IDENTIFIER 9 #define SCE_R_INFIX 10 #define SCE_R_INFIXEOL 11 #define SCE_R_BACKTICKS 12 #define SCE_R_RAWSTRING 13 #define SCE_R_RAWSTRING2 14 #define SCE_R_ESCAPESEQUENCE 15 #define SCE_MAGIK_DEFAULT 0 #define SCE_MAGIK_COMMENT 1 #define SCE_MAGIK_HYPER_COMMENT 16 #define SCE_MAGIK_STRING 2 #define SCE_MAGIK_CHARACTER 3 #define SCE_MAGIK_NUMBER 4 #define SCE_MAGIK_IDENTIFIER 5 #define SCE_MAGIK_OPERATOR 6 #define SCE_MAGIK_FLOW 7 #define SCE_MAGIK_CONTAINER 8 #define SCE_MAGIK_BRACKET_BLOCK 9 #define SCE_MAGIK_BRACE_BLOCK 10 #define SCE_MAGIK_SQBRACKET_BLOCK 11 #define SCE_MAGIK_UNKNOWN_KEYWORD 12 #define SCE_MAGIK_KEYWORD 13 #define SCE_MAGIK_PRAGMA 14 #define SCE_MAGIK_SYMBOL 15 #define SCE_POWERSHELL_DEFAULT 0 #define SCE_POWERSHELL_COMMENT 1 #define SCE_POWERSHELL_STRING 2 #define SCE_POWERSHELL_CHARACTER 3 #define SCE_POWERSHELL_NUMBER 4 #define SCE_POWERSHELL_VARIABLE 5 #define SCE_POWERSHELL_OPERATOR 6 #define SCE_POWERSHELL_IDENTIFIER 7 #define SCE_POWERSHELL_KEYWORD 8 #define SCE_POWERSHELL_CMDLET 9 #define SCE_POWERSHELL_ALIAS 10 #define SCE_POWERSHELL_FUNCTION 11 #define SCE_POWERSHELL_USER1 12 #define SCE_POWERSHELL_COMMENTSTREAM 13 #define SCE_POWERSHELL_HERE_STRING 14 #define SCE_POWERSHELL_HERE_CHARACTER 15 #define SCE_POWERSHELL_COMMENTDOCKEYWORD 16 #define SCE_MYSQL_DEFAULT 0 #define SCE_MYSQL_COMMENT 1 #define SCE_MYSQL_COMMENTLINE 2 #define SCE_MYSQL_VARIABLE 3 #define SCE_MYSQL_SYSTEMVARIABLE 4 #define SCE_MYSQL_KNOWNSYSTEMVARIABLE 5 #define SCE_MYSQL_NUMBER 6 #define SCE_MYSQL_MAJORKEYWORD 7 #define SCE_MYSQL_KEYWORD 8 #define SCE_MYSQL_DATABASEOBJECT 9 #define SCE_MYSQL_PROCEDUREKEYWORD 10 #define SCE_MYSQL_STRING 11 #define SCE_MYSQL_SQSTRING 12 #define SCE_MYSQL_DQSTRING 13 #define SCE_MYSQL_OPERATOR 14 #define SCE_MYSQL_FUNCTION 15 #define SCE_MYSQL_IDENTIFIER 16 #define SCE_MYSQL_QUOTEDIDENTIFIER 17 #define SCE_MYSQL_USER1 18 #define SCE_MYSQL_USER2 19 #define SCE_MYSQL_USER3 20 #define SCE_MYSQL_HIDDENCOMMAND 21 #define SCE_MYSQL_PLACEHOLDER 22 #define SCE_PO_DEFAULT 0 #define SCE_PO_COMMENT 1 #define SCE_PO_MSGID 2 #define SCE_PO_MSGID_TEXT 3 #define SCE_PO_MSGSTR 4 #define SCE_PO_MSGSTR_TEXT 5 #define SCE_PO_MSGCTXT 6 #define SCE_PO_MSGCTXT_TEXT 7 #define SCE_PO_FUZZY 8 #define SCE_PO_PROGRAMMER_COMMENT 9 #define SCE_PO_REFERENCE 10 #define SCE_PO_FLAGS 11 #define SCE_PO_MSGID_TEXT_EOL 12 #define SCE_PO_MSGSTR_TEXT_EOL 13 #define SCE_PO_MSGCTXT_TEXT_EOL 14 #define SCE_PO_ERROR 15 #define SCE_PAS_DEFAULT 0 #define SCE_PAS_IDENTIFIER 1 #define SCE_PAS_COMMENT 2 #define SCE_PAS_COMMENT2 3 #define SCE_PAS_COMMENTLINE 4 #define SCE_PAS_PREPROCESSOR 5 #define SCE_PAS_PREPROCESSOR2 6 #define SCE_PAS_NUMBER 7 #define SCE_PAS_HEXNUMBER 8 #define SCE_PAS_WORD 9 #define SCE_PAS_STRING 10 #define SCE_PAS_STRINGEOL 11 #define SCE_PAS_CHARACTER 12 #define SCE_PAS_OPERATOR 13 #define SCE_PAS_ASM 14 #define SCE_SORCUS_DEFAULT 0 #define SCE_SORCUS_COMMAND 1 #define SCE_SORCUS_PARAMETER 2 #define SCE_SORCUS_COMMENTLINE 3 #define SCE_SORCUS_STRING 4 #define SCE_SORCUS_STRINGEOL 5 #define SCE_SORCUS_IDENTIFIER 6 #define SCE_SORCUS_OPERATOR 7 #define SCE_SORCUS_NUMBER 8 #define SCE_SORCUS_CONSTANT 9 #define SCE_POWERPRO_DEFAULT 0 #define SCE_POWERPRO_COMMENTBLOCK 1 #define SCE_POWERPRO_COMMENTLINE 2 #define SCE_POWERPRO_NUMBER 3 #define SCE_POWERPRO_WORD 4 #define SCE_POWERPRO_WORD2 5 #define SCE_POWERPRO_WORD3 6 #define SCE_POWERPRO_WORD4 7 #define SCE_POWERPRO_DOUBLEQUOTEDSTRING 8 #define SCE_POWERPRO_SINGLEQUOTEDSTRING 9 #define SCE_POWERPRO_LINECONTINUE 10 #define SCE_POWERPRO_OPERATOR 11 #define SCE_POWERPRO_IDENTIFIER 12 #define SCE_POWERPRO_STRINGEOL 13 #define SCE_POWERPRO_VERBATIM 14 #define SCE_POWERPRO_ALTQUOTE 15 #define SCE_POWERPRO_FUNCTION 16 #define SCE_SML_DEFAULT 0 #define SCE_SML_IDENTIFIER 1 #define SCE_SML_TAGNAME 2 #define SCE_SML_KEYWORD 3 #define SCE_SML_KEYWORD2 4 #define SCE_SML_KEYWORD3 5 #define SCE_SML_LINENUM 6 #define SCE_SML_OPERATOR 7 #define SCE_SML_NUMBER 8 #define SCE_SML_CHAR 9 #define SCE_SML_STRING 11 #define SCE_SML_COMMENT 12 #define SCE_SML_COMMENT1 13 #define SCE_SML_COMMENT2 14 #define SCE_SML_COMMENT3 15 #define SCE_MARKDOWN_DEFAULT 0 #define SCE_MARKDOWN_LINE_BEGIN 1 #define SCE_MARKDOWN_STRONG1 2 #define SCE_MARKDOWN_STRONG2 3 #define SCE_MARKDOWN_EM1 4 #define SCE_MARKDOWN_EM2 5 #define SCE_MARKDOWN_HEADER1 6 #define SCE_MARKDOWN_HEADER2 7 #define SCE_MARKDOWN_HEADER3 8 #define SCE_MARKDOWN_HEADER4 9 #define SCE_MARKDOWN_HEADER5 10 #define SCE_MARKDOWN_HEADER6 11 #define SCE_MARKDOWN_PRECHAR 12 #define SCE_MARKDOWN_ULIST_ITEM 13 #define SCE_MARKDOWN_OLIST_ITEM 14 #define SCE_MARKDOWN_BLOCKQUOTE 15 #define SCE_MARKDOWN_STRIKEOUT 16 #define SCE_MARKDOWN_HRULE 17 #define SCE_MARKDOWN_LINK 18 #define SCE_MARKDOWN_CODE 19 #define SCE_MARKDOWN_CODE2 20 #define SCE_MARKDOWN_CODEBK 21 #define SCE_TXT2TAGS_DEFAULT 0 #define SCE_TXT2TAGS_LINE_BEGIN 1 #define SCE_TXT2TAGS_STRONG1 2 #define SCE_TXT2TAGS_STRONG2 3 #define SCE_TXT2TAGS_EM1 4 #define SCE_TXT2TAGS_EM2 5 #define SCE_TXT2TAGS_HEADER1 6 #define SCE_TXT2TAGS_HEADER2 7 #define SCE_TXT2TAGS_HEADER3 8 #define SCE_TXT2TAGS_HEADER4 9 #define SCE_TXT2TAGS_HEADER5 10 #define SCE_TXT2TAGS_HEADER6 11 #define SCE_TXT2TAGS_PRECHAR 12 #define SCE_TXT2TAGS_ULIST_ITEM 13 #define SCE_TXT2TAGS_OLIST_ITEM 14 #define SCE_TXT2TAGS_BLOCKQUOTE 15 #define SCE_TXT2TAGS_STRIKEOUT 16 #define SCE_TXT2TAGS_HRULE 17 #define SCE_TXT2TAGS_LINK 18 #define SCE_TXT2TAGS_CODE 19 #define SCE_TXT2TAGS_CODE2 20 #define SCE_TXT2TAGS_CODEBK 21 #define SCE_TXT2TAGS_COMMENT 22 #define SCE_TXT2TAGS_OPTION 23 #define SCE_TXT2TAGS_PREPROC 24 #define SCE_TXT2TAGS_POSTPROC 25 #define SCE_A68K_DEFAULT 0 #define SCE_A68K_COMMENT 1 #define SCE_A68K_NUMBER_DEC 2 #define SCE_A68K_NUMBER_BIN 3 #define SCE_A68K_NUMBER_HEX 4 #define SCE_A68K_STRING1 5 #define SCE_A68K_OPERATOR 6 #define SCE_A68K_CPUINSTRUCTION 7 #define SCE_A68K_EXTINSTRUCTION 8 #define SCE_A68K_REGISTER 9 #define SCE_A68K_DIRECTIVE 10 #define SCE_A68K_MACRO_ARG 11 #define SCE_A68K_LABEL 12 #define SCE_A68K_STRING2 13 #define SCE_A68K_IDENTIFIER 14 #define SCE_A68K_MACRO_DECLARATION 15 #define SCE_A68K_COMMENT_WORD 16 #define SCE_A68K_COMMENT_SPECIAL 17 #define SCE_A68K_COMMENT_DOXYGEN 18 #define SCE_MODULA_DEFAULT 0 #define SCE_MODULA_COMMENT 1 #define SCE_MODULA_DOXYCOMM 2 #define SCE_MODULA_DOXYKEY 3 #define SCE_MODULA_KEYWORD 4 #define SCE_MODULA_RESERVED 5 #define SCE_MODULA_NUMBER 6 #define SCE_MODULA_BASENUM 7 #define SCE_MODULA_FLOAT 8 #define SCE_MODULA_STRING 9 #define SCE_MODULA_STRSPEC 10 #define SCE_MODULA_CHAR 11 #define SCE_MODULA_CHARSPEC 12 #define SCE_MODULA_PROC 13 #define SCE_MODULA_PRAGMA 14 #define SCE_MODULA_PRGKEY 15 #define SCE_MODULA_OPERATOR 16 #define SCE_MODULA_BADSTR 17 #define SCE_COFFEESCRIPT_DEFAULT 0 #define SCE_COFFEESCRIPT_COMMENT 1 #define SCE_COFFEESCRIPT_COMMENTLINE 2 #define SCE_COFFEESCRIPT_COMMENTDOC 3 #define SCE_COFFEESCRIPT_NUMBER 4 #define SCE_COFFEESCRIPT_WORD 5 #define SCE_COFFEESCRIPT_STRING 6 #define SCE_COFFEESCRIPT_CHARACTER 7 #define SCE_COFFEESCRIPT_UUID 8 #define SCE_COFFEESCRIPT_PREPROCESSOR 9 #define SCE_COFFEESCRIPT_OPERATOR 10 #define SCE_COFFEESCRIPT_IDENTIFIER 11 #define SCE_COFFEESCRIPT_STRINGEOL 12 #define SCE_COFFEESCRIPT_VERBATIM 13 #define SCE_COFFEESCRIPT_REGEX 14 #define SCE_COFFEESCRIPT_COMMENTLINEDOC 15 #define SCE_COFFEESCRIPT_WORD2 16 #define SCE_COFFEESCRIPT_COMMENTDOCKEYWORD 17 #define SCE_COFFEESCRIPT_COMMENTDOCKEYWORDERROR 18 #define SCE_COFFEESCRIPT_GLOBALCLASS 19 #define SCE_COFFEESCRIPT_STRINGRAW 20 #define SCE_COFFEESCRIPT_TRIPLEVERBATIM 21 #define SCE_COFFEESCRIPT_COMMENTBLOCK 22 #define SCE_COFFEESCRIPT_VERBOSE_REGEX 23 #define SCE_COFFEESCRIPT_VERBOSE_REGEX_COMMENT 24 #define SCE_COFFEESCRIPT_INSTANCEPROPERTY 25 #define SCE_AVS_DEFAULT 0 #define SCE_AVS_COMMENTBLOCK 1 #define SCE_AVS_COMMENTBLOCKN 2 #define SCE_AVS_COMMENTLINE 3 #define SCE_AVS_NUMBER 4 #define SCE_AVS_OPERATOR 5 #define SCE_AVS_IDENTIFIER 6 #define SCE_AVS_STRING 7 #define SCE_AVS_TRIPLESTRING 8 #define SCE_AVS_KEYWORD 9 #define SCE_AVS_FILTER 10 #define SCE_AVS_PLUGIN 11 #define SCE_AVS_FUNCTION 12 #define SCE_AVS_CLIPPROP 13 #define SCE_AVS_USERDFN 14 #define SCE_ECL_DEFAULT 0 #define SCE_ECL_COMMENT 1 #define SCE_ECL_COMMENTLINE 2 #define SCE_ECL_NUMBER 3 #define SCE_ECL_STRING 4 #define SCE_ECL_WORD0 5 #define SCE_ECL_OPERATOR 6 #define SCE_ECL_CHARACTER 7 #define SCE_ECL_UUID 8 #define SCE_ECL_PREPROCESSOR 9 #define SCE_ECL_UNKNOWN 10 #define SCE_ECL_IDENTIFIER 11 #define SCE_ECL_STRINGEOL 12 #define SCE_ECL_VERBATIM 13 #define SCE_ECL_REGEX 14 #define SCE_ECL_COMMENTLINEDOC 15 #define SCE_ECL_WORD1 16 #define SCE_ECL_COMMENTDOCKEYWORD 17 #define SCE_ECL_COMMENTDOCKEYWORDERROR 18 #define SCE_ECL_WORD2 19 #define SCE_ECL_WORD3 20 #define SCE_ECL_WORD4 21 #define SCE_ECL_WORD5 22 #define SCE_ECL_COMMENTDOC 23 #define SCE_ECL_ADDED 24 #define SCE_ECL_DELETED 25 #define SCE_ECL_CHANGED 26 #define SCE_ECL_MOVED 27 #define SCE_OSCRIPT_DEFAULT 0 #define SCE_OSCRIPT_LINE_COMMENT 1 #define SCE_OSCRIPT_BLOCK_COMMENT 2 #define SCE_OSCRIPT_DOC_COMMENT 3 #define SCE_OSCRIPT_PREPROCESSOR 4 #define SCE_OSCRIPT_NUMBER 5 #define SCE_OSCRIPT_SINGLEQUOTE_STRING 6 #define SCE_OSCRIPT_DOUBLEQUOTE_STRING 7 #define SCE_OSCRIPT_CONSTANT 8 #define SCE_OSCRIPT_IDENTIFIER 9 #define SCE_OSCRIPT_GLOBAL 10 #define SCE_OSCRIPT_KEYWORD 11 #define SCE_OSCRIPT_OPERATOR 12 #define SCE_OSCRIPT_LABEL 13 #define SCE_OSCRIPT_TYPE 14 #define SCE_OSCRIPT_FUNCTION 15 #define SCE_OSCRIPT_OBJECT 16 #define SCE_OSCRIPT_PROPERTY 17 #define SCE_OSCRIPT_METHOD 18 #define SCE_VISUALPROLOG_DEFAULT 0 #define SCE_VISUALPROLOG_KEY_MAJOR 1 #define SCE_VISUALPROLOG_KEY_MINOR 2 #define SCE_VISUALPROLOG_KEY_DIRECTIVE 3 #define SCE_VISUALPROLOG_COMMENT_BLOCK 4 #define SCE_VISUALPROLOG_COMMENT_LINE 5 #define SCE_VISUALPROLOG_COMMENT_KEY 6 #define SCE_VISUALPROLOG_COMMENT_KEY_ERROR 7 #define SCE_VISUALPROLOG_IDENTIFIER 8 #define SCE_VISUALPROLOG_VARIABLE 9 #define SCE_VISUALPROLOG_ANONYMOUS 10 #define SCE_VISUALPROLOG_NUMBER 11 #define SCE_VISUALPROLOG_OPERATOR 12 #define SCE_VISUALPROLOG_UNUSED1 13 #define SCE_VISUALPROLOG_UNUSED2 14 #define SCE_VISUALPROLOG_UNUSED3 15 #define SCE_VISUALPROLOG_STRING_QUOTE 16 #define SCE_VISUALPROLOG_STRING_ESCAPE 17 #define SCE_VISUALPROLOG_STRING_ESCAPE_ERROR 18 #define SCE_VISUALPROLOG_UNUSED4 19 #define SCE_VISUALPROLOG_STRING 20 #define SCE_VISUALPROLOG_UNUSED5 21 #define SCE_VISUALPROLOG_STRING_EOL 22 #define SCE_VISUALPROLOG_EMBEDDED 23 #define SCE_VISUALPROLOG_PLACEHOLDER 24 #define SCE_STTXT_DEFAULT 0 #define SCE_STTXT_COMMENT 1 #define SCE_STTXT_COMMENTLINE 2 #define SCE_STTXT_KEYWORD 3 #define SCE_STTXT_TYPE 4 #define SCE_STTXT_FUNCTION 5 #define SCE_STTXT_FB 6 #define SCE_STTXT_NUMBER 7 #define SCE_STTXT_HEXNUMBER 8 #define SCE_STTXT_PRAGMA 9 #define SCE_STTXT_OPERATOR 10 #define SCE_STTXT_CHARACTER 11 #define SCE_STTXT_STRING1 12 #define SCE_STTXT_STRING2 13 #define SCE_STTXT_STRINGEOL 14 #define SCE_STTXT_IDENTIFIER 15 #define SCE_STTXT_DATETIME 16 #define SCE_STTXT_VARS 17 #define SCE_STTXT_PRAGMAS 18 #define SCE_KVIRC_DEFAULT 0 #define SCE_KVIRC_COMMENT 1 #define SCE_KVIRC_COMMENTBLOCK 2 #define SCE_KVIRC_STRING 3 #define SCE_KVIRC_WORD 4 #define SCE_KVIRC_KEYWORD 5 #define SCE_KVIRC_FUNCTION_KEYWORD 6 #define SCE_KVIRC_FUNCTION 7 #define SCE_KVIRC_VARIABLE 8 #define SCE_KVIRC_NUMBER 9 #define SCE_KVIRC_OPERATOR 10 #define SCE_KVIRC_STRING_FUNCTION 11 #define SCE_KVIRC_STRING_VARIABLE 12 #define SCE_RUST_DEFAULT 0 #define SCE_RUST_COMMENTBLOCK 1 #define SCE_RUST_COMMENTLINE 2 #define SCE_RUST_COMMENTBLOCKDOC 3 #define SCE_RUST_COMMENTLINEDOC 4 #define SCE_RUST_NUMBER 5 #define SCE_RUST_WORD 6 #define SCE_RUST_WORD2 7 #define SCE_RUST_WORD3 8 #define SCE_RUST_WORD4 9 #define SCE_RUST_WORD5 10 #define SCE_RUST_WORD6 11 #define SCE_RUST_WORD7 12 #define SCE_RUST_STRING 13 #define SCE_RUST_STRINGR 14 #define SCE_RUST_CHARACTER 15 #define SCE_RUST_OPERATOR 16 #define SCE_RUST_IDENTIFIER 17 #define SCE_RUST_LIFETIME 18 #define SCE_RUST_MACRO 19 #define SCE_RUST_LEXERROR 20 #define SCE_RUST_BYTESTRING 21 #define SCE_RUST_BYTESTRINGR 22 #define SCE_RUST_BYTECHARACTER 23 #define SCE_DMAP_DEFAULT 0 #define SCE_DMAP_COMMENT 1 #define SCE_DMAP_NUMBER 2 #define SCE_DMAP_STRING1 3 #define SCE_DMAP_STRING2 4 #define SCE_DMAP_STRINGEOL 5 #define SCE_DMAP_OPERATOR 6 #define SCE_DMAP_IDENTIFIER 7 #define SCE_DMAP_WORD 8 #define SCE_DMAP_WORD2 9 #define SCE_DMAP_WORD3 10 #define SCE_DMIS_DEFAULT 0 #define SCE_DMIS_COMMENT 1 #define SCE_DMIS_STRING 2 #define SCE_DMIS_NUMBER 3 #define SCE_DMIS_KEYWORD 4 #define SCE_DMIS_MAJORWORD 5 #define SCE_DMIS_MINORWORD 6 #define SCE_DMIS_UNSUPPORTED_MAJOR 7 #define SCE_DMIS_UNSUPPORTED_MINOR 8 #define SCE_DMIS_LABEL 9 #define SCE_REG_DEFAULT 0 #define SCE_REG_COMMENT 1 #define SCE_REG_VALUENAME 2 #define SCE_REG_STRING 3 #define SCE_REG_HEXDIGIT 4 #define SCE_REG_VALUETYPE 5 #define SCE_REG_ADDEDKEY 6 #define SCE_REG_DELETEDKEY 7 #define SCE_REG_ESCAPED 8 #define SCE_REG_KEYPATH_GUID 9 #define SCE_REG_STRING_GUID 10 #define SCE_REG_PARAMETER 11 #define SCE_REG_OPERATOR 12 #define SCE_BIBTEX_DEFAULT 0 #define SCE_BIBTEX_ENTRY 1 #define SCE_BIBTEX_UNKNOWN_ENTRY 2 #define SCE_BIBTEX_KEY 3 #define SCE_BIBTEX_PARAMETER 4 #define SCE_BIBTEX_VALUE 5 #define SCE_BIBTEX_COMMENT 6 #define SCE_HEX_DEFAULT 0 #define SCE_HEX_RECSTART 1 #define SCE_HEX_RECTYPE 2 #define SCE_HEX_RECTYPE_UNKNOWN 3 #define SCE_HEX_BYTECOUNT 4 #define SCE_HEX_BYTECOUNT_WRONG 5 #define SCE_HEX_NOADDRESS 6 #define SCE_HEX_DATAADDRESS 7 #define SCE_HEX_RECCOUNT 8 #define SCE_HEX_STARTADDRESS 9 #define SCE_HEX_ADDRESSFIELD_UNKNOWN 10 #define SCE_HEX_EXTENDEDADDRESS 11 #define SCE_HEX_DATA_ODD 12 #define SCE_HEX_DATA_EVEN 13 #define SCE_HEX_DATA_UNKNOWN 14 #define SCE_HEX_DATA_EMPTY 15 #define SCE_HEX_CHECKSUM 16 #define SCE_HEX_CHECKSUM_WRONG 17 #define SCE_HEX_GARBAGE 18 #define SCE_JSON_DEFAULT 0 #define SCE_JSON_NUMBER 1 #define SCE_JSON_STRING 2 #define SCE_JSON_STRINGEOL 3 #define SCE_JSON_PROPERTYNAME 4 #define SCE_JSON_ESCAPESEQUENCE 5 #define SCE_JSON_LINECOMMENT 6 #define SCE_JSON_BLOCKCOMMENT 7 #define SCE_JSON_OPERATOR 8 #define SCE_JSON_URI 9 #define SCE_JSON_COMPACTIRI 10 #define SCE_JSON_KEYWORD 11 #define SCE_JSON_LDKEYWORD 12 #define SCE_JSON_ERROR 13 #define SCE_EDI_DEFAULT 0 #define SCE_EDI_SEGMENTSTART 1 #define SCE_EDI_SEGMENTEND 2 #define SCE_EDI_SEP_ELEMENT 3 #define SCE_EDI_SEP_COMPOSITE 4 #define SCE_EDI_SEP_RELEASE 5 #define SCE_EDI_UNA 6 #define SCE_EDI_UNH 7 #define SCE_EDI_BADSEGMENT 8 #define SCE_STATA_DEFAULT 0 #define SCE_STATA_COMMENT 1 #define SCE_STATA_COMMENTLINE 2 #define SCE_STATA_COMMENTBLOCK 3 #define SCE_STATA_NUMBER 4 #define SCE_STATA_OPERATOR 5 #define SCE_STATA_IDENTIFIER 6 #define SCE_STATA_STRING 7 #define SCE_STATA_TYPE 8 #define SCE_STATA_WORD 9 #define SCE_STATA_GLOBAL_MACRO 10 #define SCE_STATA_MACRO 11 #define SCE_SAS_DEFAULT 0 #define SCE_SAS_COMMENT 1 #define SCE_SAS_COMMENTLINE 2 #define SCE_SAS_COMMENTBLOCK 3 #define SCE_SAS_NUMBER 4 #define SCE_SAS_OPERATOR 5 #define SCE_SAS_IDENTIFIER 6 #define SCE_SAS_STRING 7 #define SCE_SAS_TYPE 8 #define SCE_SAS_WORD 9 #define SCE_SAS_GLOBAL_MACRO 10 #define SCE_SAS_MACRO 11 #define SCE_SAS_MACRO_KEYWORD 12 #define SCE_SAS_BLOCK_KEYWORD 13 #define SCE_SAS_MACRO_FUNCTION 14 #define SCE_SAS_STATEMENT 15 #define SCE_NIM_DEFAULT 0 #define SCE_NIM_COMMENT 1 #define SCE_NIM_COMMENTDOC 2 #define SCE_NIM_COMMENTLINE 3 #define SCE_NIM_COMMENTLINEDOC 4 #define SCE_NIM_NUMBER 5 #define SCE_NIM_STRING 6 #define SCE_NIM_CHARACTER 7 #define SCE_NIM_WORD 8 #define SCE_NIM_TRIPLE 9 #define SCE_NIM_TRIPLEDOUBLE 10 #define SCE_NIM_BACKTICKS 11 #define SCE_NIM_FUNCNAME 12 #define SCE_NIM_STRINGEOL 13 #define SCE_NIM_NUMERROR 14 #define SCE_NIM_OPERATOR 15 #define SCE_NIM_IDENTIFIER 16 #define SCE_CIL_DEFAULT 0 #define SCE_CIL_COMMENT 1 #define SCE_CIL_COMMENTLINE 2 #define SCE_CIL_WORD 3 #define SCE_CIL_WORD2 4 #define SCE_CIL_WORD3 5 #define SCE_CIL_STRING 6 #define SCE_CIL_LABEL 7 #define SCE_CIL_OPERATOR 8 #define SCE_CIL_IDENTIFIER 9 #define SCE_CIL_STRINGEOL 10 #define SCE_X12_DEFAULT 0 #define SCE_X12_BAD 1 #define SCE_X12_ENVELOPE 2 #define SCE_X12_FUNCTIONGROUP 3 #define SCE_X12_TRANSACTIONSET 4 #define SCE_X12_SEGMENTHEADER 5 #define SCE_X12_SEGMENTEND 6 #define SCE_X12_SEP_ELEMENT 7 #define SCE_X12_SEP_SUBELEMENT 8 #define SCE_DF_DEFAULT 0 #define SCE_DF_IDENTIFIER 1 #define SCE_DF_METATAG 2 #define SCE_DF_IMAGE 3 #define SCE_DF_COMMENTLINE 4 #define SCE_DF_PREPROCESSOR 5 #define SCE_DF_PREPROCESSOR2 6 #define SCE_DF_NUMBER 7 #define SCE_DF_HEXNUMBER 8 #define SCE_DF_WORD 9 #define SCE_DF_STRING 10 #define SCE_DF_STRINGEOL 11 #define SCE_DF_SCOPEWORD 12 #define SCE_DF_OPERATOR 13 #define SCE_DF_ICODE 14 #define SCE_HOLLYWOOD_DEFAULT 0 #define SCE_HOLLYWOOD_COMMENT 1 #define SCE_HOLLYWOOD_COMMENTBLOCK 2 #define SCE_HOLLYWOOD_NUMBER 3 #define SCE_HOLLYWOOD_KEYWORD 4 #define SCE_HOLLYWOOD_STDAPI 5 #define SCE_HOLLYWOOD_PLUGINAPI 6 #define SCE_HOLLYWOOD_PLUGINMETHOD 7 #define SCE_HOLLYWOOD_STRING 8 #define SCE_HOLLYWOOD_STRINGBLOCK 9 #define SCE_HOLLYWOOD_PREPROCESSOR 10 #define SCE_HOLLYWOOD_OPERATOR 11 #define SCE_HOLLYWOOD_IDENTIFIER 12 #define SCE_HOLLYWOOD_CONSTANT 13 #define SCE_HOLLYWOOD_HEXNUMBER 14 #define SCE_RAKU_DEFAULT 0 #define SCE_RAKU_ERROR 1 #define SCE_RAKU_COMMENTLINE 2 #define SCE_RAKU_COMMENTEMBED 3 #define SCE_RAKU_POD 4 #define SCE_RAKU_CHARACTER 5 #define SCE_RAKU_HEREDOC_Q 6 #define SCE_RAKU_HEREDOC_QQ 7 #define SCE_RAKU_STRING 8 #define SCE_RAKU_STRING_Q 9 #define SCE_RAKU_STRING_QQ 10 #define SCE_RAKU_STRING_Q_LANG 11 #define SCE_RAKU_STRING_VAR 12 #define SCE_RAKU_REGEX 13 #define SCE_RAKU_REGEX_VAR 14 #define SCE_RAKU_ADVERB 15 #define SCE_RAKU_NUMBER 16 #define SCE_RAKU_PREPROCESSOR 17 #define SCE_RAKU_OPERATOR 18 #define SCE_RAKU_WORD 19 #define SCE_RAKU_FUNCTION 20 #define SCE_RAKU_IDENTIFIER 21 #define SCE_RAKU_TYPEDEF 22 #define SCE_RAKU_MU 23 #define SCE_RAKU_POSITIONAL 24 #define SCE_RAKU_ASSOCIATIVE 25 #define SCE_RAKU_CALLABLE 26 #define SCE_RAKU_GRAMMAR 27 #define SCE_RAKU_CLASS 28 #define SCE_FSHARP_DEFAULT 0 #define SCE_FSHARP_KEYWORD 1 #define SCE_FSHARP_KEYWORD2 2 #define SCE_FSHARP_KEYWORD3 3 #define SCE_FSHARP_KEYWORD4 4 #define SCE_FSHARP_KEYWORD5 5 #define SCE_FSHARP_IDENTIFIER 6 #define SCE_FSHARP_QUOT_IDENTIFIER 7 #define SCE_FSHARP_COMMENT 8 #define SCE_FSHARP_COMMENTLINE 9 #define SCE_FSHARP_PREPROCESSOR 10 #define SCE_FSHARP_LINENUM 11 #define SCE_FSHARP_OPERATOR 12 #define SCE_FSHARP_NUMBER 13 #define SCE_FSHARP_CHARACTER 14 #define SCE_FSHARP_STRING 15 #define SCE_FSHARP_VERBATIM 16 #define SCE_FSHARP_QUOTATION 17 #define SCE_FSHARP_ATTRIBUTE 18 #define SCE_FSHARP_FORMAT_SPEC 19 #define SCE_ASCIIDOC_DEFAULT 0 #define SCE_ASCIIDOC_STRONG1 1 #define SCE_ASCIIDOC_STRONG2 2 #define SCE_ASCIIDOC_EM1 3 #define SCE_ASCIIDOC_EM2 4 #define SCE_ASCIIDOC_HEADER1 5 #define SCE_ASCIIDOC_HEADER2 6 #define SCE_ASCIIDOC_HEADER3 7 #define SCE_ASCIIDOC_HEADER4 8 #define SCE_ASCIIDOC_HEADER5 9 #define SCE_ASCIIDOC_HEADER6 10 #define SCE_ASCIIDOC_ULIST_ITEM 11 #define SCE_ASCIIDOC_OLIST_ITEM 12 #define SCE_ASCIIDOC_BLOCKQUOTE 13 #define SCE_ASCIIDOC_LINK 14 #define SCE_ASCIIDOC_CODEBK 15 #define SCE_ASCIIDOC_PASSBK 16 #define SCE_ASCIIDOC_COMMENT 17 #define SCE_ASCIIDOC_COMMENTBK 18 #define SCE_ASCIIDOC_LITERAL 19 #define SCE_ASCIIDOC_LITERALBK 20 #define SCE_ASCIIDOC_ATTRIB 21 #define SCE_ASCIIDOC_ATTRIBVAL 22 #define SCE_ASCIIDOC_MACRO 23 #define SCE_GD_DEFAULT 0 #define SCE_GD_COMMENTLINE 1 #define SCE_GD_NUMBER 2 #define SCE_GD_STRING 3 #define SCE_GD_CHARACTER 4 #define SCE_GD_WORD 5 #define SCE_GD_TRIPLE 6 #define SCE_GD_TRIPLEDOUBLE 7 #define SCE_GD_CLASSNAME 8 #define SCE_GD_FUNCNAME 9 #define SCE_GD_OPERATOR 10 #define SCE_GD_IDENTIFIER 11 #define SCE_GD_COMMENTBLOCK 12 #define SCE_GD_STRINGEOL 13 #define SCE_GD_WORD2 14 #define SCE_GD_ANNOTATION 15 #define SCE_GD_NODEPATH 16 #define SCE_TOML_DEFAULT 0 #define SCE_TOML_COMMENT 1 #define SCE_TOML_IDENTIFIER 2 #define SCE_TOML_KEYWORD 3 #define SCE_TOML_NUMBER 4 #define SCE_TOML_TABLE 5 #define SCE_TOML_KEY 6 #define SCE_TOML_ERROR 7 #define SCE_TOML_OPERATOR 8 #define SCE_TOML_STRING_SQ 9 #define SCE_TOML_STRING_DQ 10 #define SCE_TOML_TRIPLE_STRING_SQ 11 #define SCE_TOML_TRIPLE_STRING_DQ 12 #define SCE_TOML_ESCAPECHAR 13 #define SCE_TOML_DATETIME 14 #define SCE_TROFF_DEFAULT 0 #define SCE_TROFF_REQUEST 1 #define SCE_TROFF_COMMAND 2 #define SCE_TROFF_NUMBER 3 #define SCE_TROFF_OPERATOR 4 #define SCE_TROFF_STRING 5 #define SCE_TROFF_COMMENT 6 #define SCE_TROFF_IGNORE 7 #define SCE_TROFF_ESCAPE_STRING 8 #define SCE_TROFF_ESCAPE_MACRO 9 #define SCE_TROFF_ESCAPE_FONT 10 #define SCE_TROFF_ESCAPE_NUMBER 11 #define SCE_TROFF_ESCAPE_COLOUR 12 #define SCE_TROFF_ESCAPE_GLYPH 13 #define SCE_TROFF_ESCAPE_ENV 14 #define SCE_TROFF_ESCAPE_SUPPRESSION 15 #define SCE_TROFF_ESCAPE_SIZE 16 #define SCE_TROFF_ESCAPE_TRANSPARENT 17 #define SCE_TROFF_ESCAPE_ISVALID 18 #define SCE_TROFF_ESCAPE_DRAW 19 #define SCE_TROFF_ESCAPE_MOVE 20 #define SCE_TROFF_ESCAPE_HEIGHT 21 #define SCE_TROFF_ESCAPE_OVERSTRIKE 22 #define SCE_TROFF_ESCAPE_SLANT 23 #define SCE_TROFF_ESCAPE_WIDTH 24 #define SCE_TROFF_ESCAPE_VSPACING 25 #define SCE_TROFF_ESCAPE_DEVICE 26 #define SCE_TROFF_ESCAPE_NOMOVE 27 #define SCE_DART_DEFAULT 0 #define SCE_DART_COMMENTLINE 1 #define SCE_DART_COMMENTLINEDOC 2 #define SCE_DART_COMMENTBLOCK 3 #define SCE_DART_COMMENTBLOCKDOC 4 #define SCE_DART_STRING_SQ 5 #define SCE_DART_STRING_DQ 6 #define SCE_DART_TRIPLE_STRING_SQ 7 #define SCE_DART_TRIPLE_STRING_DQ 8 #define SCE_DART_RAWSTRING_SQ 9 #define SCE_DART_RAWSTRING_DQ 10 #define SCE_DART_TRIPLE_RAWSTRING_SQ 11 #define SCE_DART_TRIPLE_RAWSTRING_DQ 12 #define SCE_DART_ESCAPECHAR 13 #define SCE_DART_IDENTIFIER 14 #define SCE_DART_IDENTIFIER_STRING 15 #define SCE_DART_OPERATOR 16 #define SCE_DART_OPERATOR_STRING 17 #define SCE_DART_SYMBOL_IDENTIFIER 18 #define SCE_DART_SYMBOL_OPERATOR 19 #define SCE_DART_NUMBER 20 #define SCE_DART_KEY 21 #define SCE_DART_METADATA 22 #define SCE_DART_KW_PRIMARY 23 #define SCE_DART_KW_SECONDARY 24 #define SCE_DART_KW_TERTIARY 25 #define SCE_DART_KW_TYPE 26 #define SCE_ZIG_DEFAULT 0 #define SCE_ZIG_COMMENTLINE 1 #define SCE_ZIG_COMMENTLINEDOC 2 #define SCE_ZIG_COMMENTLINETOP 3 #define SCE_ZIG_NUMBER 4 #define SCE_ZIG_OPERATOR 5 #define SCE_ZIG_CHARACTER 6 #define SCE_ZIG_STRING 7 #define SCE_ZIG_MULTISTRING 8 #define SCE_ZIG_ESCAPECHAR 9 #define SCE_ZIG_IDENTIFIER 10 #define SCE_ZIG_FUNCTION 11 #define SCE_ZIG_BUILTIN_FUNCTION 12 #define SCE_ZIG_KW_PRIMARY 13 #define SCE_ZIG_KW_SECONDARY 14 #define SCE_ZIG_KW_TERTIARY 15 #define SCE_ZIG_KW_TYPE 16 /* --Autogenerated -- end of section automatically generated from Scintilla.iface */ #endif
61,694
C++
.h
2,151
27.677359
97
0.814337
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
16,605
LexillaAccess.h
dail8859_NotepadNext/src/lexilla/access/LexillaAccess.h
// SciTE - Scintilla based Text Editor /** @file LexillaAccess.h ** Interface to loadable lexers. ** This does not depend on SciTE code so can be copied out into other projects. **/ // Copyright 2019 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #ifndef LEXILLAACCESS_H #define LEXILLAACCESS_H namespace Lexilla { // Directory to load default Lexilla from, commonly the directory of the application. void SetDefaultDirectory(std::string_view directory); // Specify CreateLexer when statically linked so no hard dependency in LexillaAccess // so it doesn't have to be built in two forms - static and dynamic. void SetDefault(CreateLexerFn pCreate) noexcept; // sharedLibraryPaths is a ';' separated list of shared libraries to load. // On Win32 it is treated as UTF-8 and on Unix it is passed to dlopen directly. // Return true if any shared libraries are loaded. bool Load(std::string_view sharedLibraryPaths); Scintilla::ILexer5 *MakeLexer(std::string_view languageName); std::vector<std::string> Lexers(); [[deprecated]] std::string NameFromID(int identifier); std::vector<std::string> LibraryProperties(); void SetProperty(const char *key, const char *value); } #endif
1,271
C++
.h
26
47.423077
94
0.789644
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,622
Config.h
dail8859_NotepadNext/src/LuaBridge/detail/Config.h
// https://github.com/vinniefalco/LuaBridge // // Copyright 2019, Dmitry Tarakanov // SPDX-License-Identifier: MIT #pragma once #if !defined (LUABRIDGE_NO_CXX11) && (__cplusplus >= 201103L || (defined (_MSC_VER) && _MSC_VER >= 1900)) #define LUABRIDGE_CXX11 #endif
267
C++
.h
8
32.125
105
0.719844
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,629
DockedEditorTitleBar.h
dail8859_NotepadNext/src/NotepadNext/DockedEditorTitleBar.h
/* * This file is part of Notepad Next. * Copyright 2019 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #ifndef DOCKEDEDITORTITLEBAR_H #define DOCKEDEDITORTITLEBAR_H #include <DockAreaTitleBar.h> class DockedEditorTitleBar : public ads::CDockAreaTitleBar { Q_OBJECT public: explicit DockedEditorTitleBar(ads::CDockAreaWidget* parent) : ads::CDockAreaTitleBar(parent) {} signals: void doubleClicked(); protected: void mouseDoubleClickEvent(QMouseEvent *event) { ads::CDockAreaTitleBar::mouseDoubleClickEvent(event); if (event->button() == Qt::LeftButton) { emit doubleClicked(); } } }; #endif // DOCKEDEDITORTITLEBAR_H
1,307
C++
.h
36
33.027778
99
0.750991
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,631
FadingIndicator.h
dail8859_NotepadNext/src/NotepadNext/FadingIndicator.h
/* * This file is part of Notepad Next. * Copyright (C) 2016 The Qt Company Ltd. * Copyright 2024 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <QWidget> namespace FadingIndicator { enum TextSize { SmallText, LargeText }; void showText(QWidget *parent, const QString &text, TextSize size = LargeText); void showPixmap(QWidget *parent, const QString &pixmap); }
1,022
C++
.h
28
34.392857
79
0.762146
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,632
ScintillaCommenter.h
dail8859_NotepadNext/src/NotepadNext/ScintillaCommenter.h
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #ifndef SCINTILLACOMMENTER_H #define SCINTILLACOMMENTER_H #include "ScintillaNext.h" #include "SelectionTracker.h" #include "UndoAction.h" class ScintillaCommenter { public: explicit ScintillaCommenter(ScintillaNext *editor); void toggleSelection(); void commentSelection(); void uncommentSelection(); private: void toggleLine(int line); void commentLine(int line); void uncommentLine(int line); ScintillaNext *editor; SelectionTracker st; UndoAction ua; }; #endif // SCINTILLACOMMENTER_H
1,264
C++
.h
38
30.578947
73
0.766831
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,633
ZoomEventWatcher.h
dail8859_NotepadNext/src/NotepadNext/ZoomEventWatcher.h
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #ifndef ZOOMEVENTWATCHER_H #define ZOOMEVENTWATCHER_H #include <QObject> class ZoomEventWatcher : public QObject { Q_OBJECT public: explicit ZoomEventWatcher(QObject *parent = nullptr); signals: void zoomIn(); void zoomOut(); protected: bool eventFilter(QObject *obj, QEvent *event) override; }; #endif // ZOOMEVENTWATCHER_H
1,080
C++
.h
32
31.375
73
0.7625
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,634
Converter.h
dail8859_NotepadNext/src/NotepadNext/Converter.h
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <QTextStream> #include "ScintillaNext.h" class Converter { public: Converter(ScintillaNext *editor); void convert(QTextStream &stream); virtual void convertRange(QTextStream &stream, int start, int end) = 0; protected: void ensureDocumentStyled(int start, int end); ScintillaNext *editor; };
1,070
C++
.h
30
33.166667
75
0.761397
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,635
RecentFilesListMenuBuilder.h
dail8859_NotepadNext/src/NotepadNext/RecentFilesListMenuBuilder.h
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #ifndef RECENTFILESLISTMENUBUILDER_H #define RECENTFILESLISTMENUBUILDER_H #include "RecentFilesListManager.h" #include <QObject> class QMenu; class RecentFilesListMenuBuilder : public QObject { Q_OBJECT public: explicit RecentFilesListMenuBuilder(RecentFilesListManager *manager); void populateMenu(QMenu *menu); signals: void fileOpenRequest(const QString &filePath); private slots: void recentFileActionTriggered(); private: RecentFilesListManager *manager; }; #endif // RECENTFILESLISTMENUBUILDER_H
1,263
C++
.h
36
32.694444
73
0.788003
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,636
ISearchResultsHandler.h
dail8859_NotepadNext/src/NotepadNext/ISearchResultsHandler.h
/* * This file is part of Notepad Next. * Copyright 2023 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "ScintillaNext.h" #include <QString> class ISearchResultsHandler { public: virtual void newSearch(const QString searchTerm) = 0; virtual void newFileEntry(ScintillaNext *editor) = 0; virtual void newResultsEntry(const QString line, int lineNumber, int startPositionFromBeginning, int endPositionFromBeginning, int hitCount=1) = 0; virtual void completeSearch() = 0; };
1,139
C++
.h
27
39.814815
151
0.769648
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
16,637
ScintillaEnums.h
dail8859_NotepadNext/src/NotepadNext/ScintillaEnums.h
/* * This file is part of Notepad Next. * Copyright 2022 Justin Dailey * * Notepad Next is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Notepad Next 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Notepad Next. If not, see <https://www.gnu.org/licenses/>. */ /* ++Autogenerated -- start of section automatically generated from Scintilla.iface */ enum class Message { AddText = 2001, AddStyledText = 2002, InsertText = 2003, ChangeInsertion = 2672, ClearAll = 2004, DeleteRange = 2645, ClearDocumentStyle = 2005, GetLength = 2006, GetCharAt = 2007, GetCurrentPos = 2008, GetAnchor = 2009, GetStyleAt = 2010, GetStyleIndexAt = 2038, Redo = 2011, SetUndoCollection = 2012, SelectAll = 2013, SetSavePoint = 2014, GetStyledText = 2015, CanRedo = 2016, MarkerLineFromHandle = 2017, MarkerDeleteHandle = 2018, MarkerHandleFromLine = 2732, MarkerNumberFromLine = 2733, GetUndoCollection = 2019, GetViewWS = 2020, SetViewWS = 2021, GetTabDrawMode = 2698, SetTabDrawMode = 2699, PositionFromPoint = 2022, PositionFromPointClose = 2023, GotoLine = 2024, GotoPos = 2025, SetAnchor = 2026, GetCurLine = 2027, GetEndStyled = 2028, ConvertEOLs = 2029, GetEOLMode = 2030, SetEOLMode = 2031, StartStyling = 2032, SetStyling = 2033, GetBufferedDraw = 2034, SetBufferedDraw = 2035, SetTabWidth = 2036, GetTabWidth = 2121, SetTabMinimumWidth = 2724, GetTabMinimumWidth = 2725, ClearTabStops = 2675, AddTabStop = 2676, GetNextTabStop = 2677, SetCodePage = 2037, SetFontLocale = 2760, GetFontLocale = 2761, GetIMEInteraction = 2678, SetIMEInteraction = 2679, MarkerDefine = 2040, MarkerSetFore = 2041, MarkerSetBack = 2042, MarkerSetBackSelected = 2292, MarkerSetForeTranslucent = 2294, MarkerSetBackTranslucent = 2295, MarkerSetBackSelectedTranslucent = 2296, MarkerSetStrokeWidth = 2297, MarkerEnableHighlight = 2293, MarkerAdd = 2043, MarkerDelete = 2044, MarkerDeleteAll = 2045, MarkerGet = 2046, MarkerNext = 2047, MarkerPrevious = 2048, MarkerDefinePixmap = 2049, MarkerAddSet = 2466, MarkerSetAlpha = 2476, MarkerGetLayer = 2734, MarkerSetLayer = 2735, SetMarginTypeN = 2240, GetMarginTypeN = 2241, SetMarginWidthN = 2242, GetMarginWidthN = 2243, SetMarginMaskN = 2244, GetMarginMaskN = 2245, SetMarginSensitiveN = 2246, GetMarginSensitiveN = 2247, SetMarginCursorN = 2248, GetMarginCursorN = 2249, SetMarginBackN = 2250, GetMarginBackN = 2251, SetMargins = 2252, GetMargins = 2253, StyleClearAll = 2050, StyleSetFore = 2051, StyleSetBack = 2052, StyleSetBold = 2053, StyleSetItalic = 2054, StyleSetSize = 2055, StyleSetFont = 2056, StyleSetEOLFilled = 2057, StyleResetDefault = 2058, StyleSetUnderline = 2059, StyleGetFore = 2481, StyleGetBack = 2482, StyleGetBold = 2483, StyleGetItalic = 2484, StyleGetSize = 2485, StyleGetFont = 2486, StyleGetEOLFilled = 2487, StyleGetUnderline = 2488, StyleGetCase = 2489, StyleGetCharacterSet = 2490, StyleGetVisible = 2491, StyleGetChangeable = 2492, StyleGetHotSpot = 2493, StyleSetCase = 2060, StyleSetSizeFractional = 2061, StyleGetSizeFractional = 2062, StyleSetWeight = 2063, StyleGetWeight = 2064, StyleSetCharacterSet = 2066, StyleSetHotSpot = 2409, StyleSetCheckMonospaced = 2254, StyleGetCheckMonospaced = 2255, SetElementColour = 2753, GetElementColour = 2754, ResetElementColour = 2755, GetElementIsSet = 2756, GetElementAllowsTranslucent = 2757, GetElementBaseColour = 2758, SetSelFore = 2067, SetSelBack = 2068, GetSelAlpha = 2477, SetSelAlpha = 2478, GetSelEOLFilled = 2479, SetSelEOLFilled = 2480, GetSelectionLayer = 2762, SetSelectionLayer = 2763, GetCaretLineLayer = 2764, SetCaretLineLayer = 2765, GetCaretLineHighlightSubLine = 2773, SetCaretLineHighlightSubLine = 2774, SetCaretFore = 2069, AssignCmdKey = 2070, ClearCmdKey = 2071, ClearAllCmdKeys = 2072, SetStylingEx = 2073, StyleSetVisible = 2074, GetCaretPeriod = 2075, SetCaretPeriod = 2076, SetWordChars = 2077, GetWordChars = 2646, SetCharacterCategoryOptimization = 2720, GetCharacterCategoryOptimization = 2721, BeginUndoAction = 2078, EndUndoAction = 2079, IndicSetStyle = 2080, IndicGetStyle = 2081, IndicSetFore = 2082, IndicGetFore = 2083, IndicSetUnder = 2510, IndicGetUnder = 2511, IndicSetHoverStyle = 2680, IndicGetHoverStyle = 2681, IndicSetHoverFore = 2682, IndicGetHoverFore = 2683, IndicSetFlags = 2684, IndicGetFlags = 2685, IndicSetStrokeWidth = 2751, IndicGetStrokeWidth = 2752, SetWhitespaceFore = 2084, SetWhitespaceBack = 2085, SetWhitespaceSize = 2086, GetWhitespaceSize = 2087, SetLineState = 2092, GetLineState = 2093, GetMaxLineState = 2094, GetCaretLineVisible = 2095, SetCaretLineVisible = 2096, GetCaretLineBack = 2097, SetCaretLineBack = 2098, GetCaretLineFrame = 2704, SetCaretLineFrame = 2705, StyleSetChangeable = 2099, AutoCShow = 2100, AutoCCancel = 2101, AutoCActive = 2102, AutoCPosStart = 2103, AutoCComplete = 2104, AutoCStops = 2105, AutoCSetSeparator = 2106, AutoCGetSeparator = 2107, AutoCSelect = 2108, AutoCSetCancelAtStart = 2110, AutoCGetCancelAtStart = 2111, AutoCSetFillUps = 2112, AutoCSetChooseSingle = 2113, AutoCGetChooseSingle = 2114, AutoCSetIgnoreCase = 2115, AutoCGetIgnoreCase = 2116, UserListShow = 2117, AutoCSetAutoHide = 2118, AutoCGetAutoHide = 2119, AutoCSetOptions = 2638, AutoCGetOptions = 2639, AutoCSetDropRestOfWord = 2270, AutoCGetDropRestOfWord = 2271, RegisterImage = 2405, ClearRegisteredImages = 2408, AutoCGetTypeSeparator = 2285, AutoCSetTypeSeparator = 2286, AutoCSetMaxWidth = 2208, AutoCGetMaxWidth = 2209, AutoCSetMaxHeight = 2210, AutoCGetMaxHeight = 2211, SetIndent = 2122, GetIndent = 2123, SetUseTabs = 2124, GetUseTabs = 2125, SetLineIndentation = 2126, GetLineIndentation = 2127, GetLineIndentPosition = 2128, GetColumn = 2129, CountCharacters = 2633, CountCodeUnits = 2715, SetHScrollBar = 2130, GetHScrollBar = 2131, SetIndentationGuides = 2132, GetIndentationGuides = 2133, SetHighlightGuide = 2134, GetHighlightGuide = 2135, GetLineEndPosition = 2136, GetCodePage = 2137, GetCaretFore = 2138, GetReadOnly = 2140, SetCurrentPos = 2141, SetSelectionStart = 2142, GetSelectionStart = 2143, SetSelectionEnd = 2144, GetSelectionEnd = 2145, SetEmptySelection = 2556, SetPrintMagnification = 2146, GetPrintMagnification = 2147, SetPrintColourMode = 2148, GetPrintColourMode = 2149, FindText = 2150, FindTextFull = 2196, FormatRange = 2151, FormatRangeFull = 2777, GetFirstVisibleLine = 2152, GetLine = 2153, GetLineCount = 2154, AllocateLines = 2089, SetMarginLeft = 2155, GetMarginLeft = 2156, SetMarginRight = 2157, GetMarginRight = 2158, GetModify = 2159, SetSel = 2160, GetSelText = 2161, GetTextRange = 2162, GetTextRangeFull = 2039, HideSelection = 2163, PointXFromPosition = 2164, PointYFromPosition = 2165, LineFromPosition = 2166, PositionFromLine = 2167, LineScroll = 2168, ScrollCaret = 2169, ScrollRange = 2569, ReplaceSel = 2170, SetReadOnly = 2171, Null = 2172, CanPaste = 2173, CanUndo = 2174, EmptyUndoBuffer = 2175, Undo = 2176, Cut = 2177, Copy = 2178, Paste = 2179, Clear = 2180, SetText = 2181, GetText = 2182, GetTextLength = 2183, GetDirectFunction = 2184, GetDirectStatusFunction = 2772, GetDirectPointer = 2185, SetOvertype = 2186, GetOvertype = 2187, SetCaretWidth = 2188, GetCaretWidth = 2189, SetTargetStart = 2190, GetTargetStart = 2191, SetTargetStartVirtualSpace = 2728, GetTargetStartVirtualSpace = 2729, SetTargetEnd = 2192, GetTargetEnd = 2193, SetTargetEndVirtualSpace = 2730, GetTargetEndVirtualSpace = 2731, SetTargetRange = 2686, GetTargetText = 2687, TargetFromSelection = 2287, TargetWholeDocument = 2690, ReplaceTarget = 2194, ReplaceTargetRE = 2195, SearchInTarget = 2197, SetSearchFlags = 2198, GetSearchFlags = 2199, CallTipShow = 2200, CallTipCancel = 2201, CallTipActive = 2202, CallTipPosStart = 2203, CallTipSetPosStart = 2214, CallTipSetHlt = 2204, CallTipSetBack = 2205, CallTipSetFore = 2206, CallTipSetForeHlt = 2207, CallTipUseStyle = 2212, CallTipSetPosition = 2213, VisibleFromDocLine = 2220, DocLineFromVisible = 2221, WrapCount = 2235, SetFoldLevel = 2222, GetFoldLevel = 2223, GetLastChild = 2224, GetFoldParent = 2225, ShowLines = 2226, HideLines = 2227, GetLineVisible = 2228, GetAllLinesVisible = 2236, SetFoldExpanded = 2229, GetFoldExpanded = 2230, ToggleFold = 2231, ToggleFoldShowText = 2700, FoldDisplayTextSetStyle = 2701, FoldDisplayTextGetStyle = 2707, SetDefaultFoldDisplayText = 2722, GetDefaultFoldDisplayText = 2723, FoldLine = 2237, FoldChildren = 2238, ExpandChildren = 2239, FoldAll = 2662, EnsureVisible = 2232, SetAutomaticFold = 2663, GetAutomaticFold = 2664, SetFoldFlags = 2233, EnsureVisibleEnforcePolicy = 2234, SetTabIndents = 2260, GetTabIndents = 2261, SetBackSpaceUnIndents = 2262, GetBackSpaceUnIndents = 2263, SetMouseDwellTime = 2264, GetMouseDwellTime = 2265, WordStartPosition = 2266, WordEndPosition = 2267, IsRangeWord = 2691, SetIdleStyling = 2692, GetIdleStyling = 2693, SetWrapMode = 2268, GetWrapMode = 2269, SetWrapVisualFlags = 2460, GetWrapVisualFlags = 2461, SetWrapVisualFlagsLocation = 2462, GetWrapVisualFlagsLocation = 2463, SetWrapStartIndent = 2464, GetWrapStartIndent = 2465, SetWrapIndentMode = 2472, GetWrapIndentMode = 2473, SetLayoutCache = 2272, GetLayoutCache = 2273, SetScrollWidth = 2274, GetScrollWidth = 2275, SetScrollWidthTracking = 2516, GetScrollWidthTracking = 2517, TextWidth = 2276, SetEndAtLastLine = 2277, GetEndAtLastLine = 2278, TextHeight = 2279, SetVScrollBar = 2280, GetVScrollBar = 2281, AppendText = 2282, GetPhasesDraw = 2673, SetPhasesDraw = 2674, SetFontQuality = 2611, GetFontQuality = 2612, SetFirstVisibleLine = 2613, SetMultiPaste = 2614, GetMultiPaste = 2615, GetTag = 2616, LinesJoin = 2288, LinesSplit = 2289, SetFoldMarginColour = 2290, SetFoldMarginHiColour = 2291, SetAccessibility = 2702, GetAccessibility = 2703, LineDown = 2300, LineDownExtend = 2301, LineUp = 2302, LineUpExtend = 2303, CharLeft = 2304, CharLeftExtend = 2305, CharRight = 2306, CharRightExtend = 2307, WordLeft = 2308, WordLeftExtend = 2309, WordRight = 2310, WordRightExtend = 2311, Home = 2312, HomeExtend = 2313, LineEnd = 2314, LineEndExtend = 2315, DocumentStart = 2316, DocumentStartExtend = 2317, DocumentEnd = 2318, DocumentEndExtend = 2319, PageUp = 2320, PageUpExtend = 2321, PageDown = 2322, PageDownExtend = 2323, EditToggleOvertype = 2324, Cancel = 2325, DeleteBack = 2326, Tab = 2327, BackTab = 2328, NewLine = 2329, FormFeed = 2330, VCHome = 2331, VCHomeExtend = 2332, ZoomIn = 2333, ZoomOut = 2334, DelWordLeft = 2335, DelWordRight = 2336, DelWordRightEnd = 2518, LineCut = 2337, LineDelete = 2338, LineTranspose = 2339, LineReverse = 2354, LineDuplicate = 2404, LowerCase = 2340, UpperCase = 2341, LineScrollDown = 2342, LineScrollUp = 2343, DeleteBackNotLine = 2344, HomeDisplay = 2345, HomeDisplayExtend = 2346, LineEndDisplay = 2347, LineEndDisplayExtend = 2348, HomeWrap = 2349, HomeWrapExtend = 2450, LineEndWrap = 2451, LineEndWrapExtend = 2452, VCHomeWrap = 2453, VCHomeWrapExtend = 2454, LineCopy = 2455, MoveCaretInsideView = 2401, LineLength = 2350, BraceHighlight = 2351, BraceHighlightIndicator = 2498, BraceBadLight = 2352, BraceBadLightIndicator = 2499, BraceMatch = 2353, BraceMatchNext = 2369, GetViewEOL = 2355, SetViewEOL = 2356, GetDocPointer = 2357, SetDocPointer = 2358, SetModEventMask = 2359, GetEdgeColumn = 2360, SetEdgeColumn = 2361, GetEdgeMode = 2362, SetEdgeMode = 2363, GetEdgeColour = 2364, SetEdgeColour = 2365, MultiEdgeAddLine = 2694, MultiEdgeClearAll = 2695, GetMultiEdgeColumn = 2749, SearchAnchor = 2366, SearchNext = 2367, SearchPrev = 2368, LinesOnScreen = 2370, UsePopUp = 2371, SelectionIsRectangle = 2372, SetZoom = 2373, GetZoom = 2374, CreateDocument = 2375, AddRefDocument = 2376, ReleaseDocument = 2377, GetDocumentOptions = 2379, GetModEventMask = 2378, SetCommandEvents = 2717, GetCommandEvents = 2718, SetFocus = 2380, GetFocus = 2381, SetStatus = 2382, GetStatus = 2383, SetMouseDownCaptures = 2384, GetMouseDownCaptures = 2385, SetMouseWheelCaptures = 2696, GetMouseWheelCaptures = 2697, SetCursor = 2386, GetCursor = 2387, SetControlCharSymbol = 2388, GetControlCharSymbol = 2389, WordPartLeft = 2390, WordPartLeftExtend = 2391, WordPartRight = 2392, WordPartRightExtend = 2393, SetVisiblePolicy = 2394, DelLineLeft = 2395, DelLineRight = 2396, SetXOffset = 2397, GetXOffset = 2398, ChooseCaretX = 2399, GrabFocus = 2400, SetXCaretPolicy = 2402, SetYCaretPolicy = 2403, SetPrintWrapMode = 2406, GetPrintWrapMode = 2407, SetHotspotActiveFore = 2410, GetHotspotActiveFore = 2494, SetHotspotActiveBack = 2411, GetHotspotActiveBack = 2495, SetHotspotActiveUnderline = 2412, GetHotspotActiveUnderline = 2496, SetHotspotSingleLine = 2421, GetHotspotSingleLine = 2497, ParaDown = 2413, ParaDownExtend = 2414, ParaUp = 2415, ParaUpExtend = 2416, PositionBefore = 2417, PositionAfter = 2418, PositionRelative = 2670, PositionRelativeCodeUnits = 2716, CopyRange = 2419, CopyText = 2420, SetSelectionMode = 2422, GetSelectionMode = 2423, GetMoveExtendsSelection = 2706, GetLineSelStartPosition = 2424, GetLineSelEndPosition = 2425, LineDownRectExtend = 2426, LineUpRectExtend = 2427, CharLeftRectExtend = 2428, CharRightRectExtend = 2429, HomeRectExtend = 2430, VCHomeRectExtend = 2431, LineEndRectExtend = 2432, PageUpRectExtend = 2433, PageDownRectExtend = 2434, StutteredPageUp = 2435, StutteredPageUpExtend = 2436, StutteredPageDown = 2437, StutteredPageDownExtend = 2438, WordLeftEnd = 2439, WordLeftEndExtend = 2440, WordRightEnd = 2441, WordRightEndExtend = 2442, SetWhitespaceChars = 2443, GetWhitespaceChars = 2647, SetPunctuationChars = 2648, GetPunctuationChars = 2649, SetCharsDefault = 2444, AutoCGetCurrent = 2445, AutoCGetCurrentText = 2610, AutoCSetCaseInsensitiveBehaviour = 2634, AutoCGetCaseInsensitiveBehaviour = 2635, AutoCSetMulti = 2636, AutoCGetMulti = 2637, AutoCSetOrder = 2660, AutoCGetOrder = 2661, Allocate = 2446, TargetAsUTF8 = 2447, SetLengthForEncode = 2448, EncodedFromUTF8 = 2449, FindColumn = 2456, GetCaretSticky = 2457, SetCaretSticky = 2458, ToggleCaretSticky = 2459, SetPasteConvertEndings = 2467, GetPasteConvertEndings = 2468, ReplaceRectangular = 2771, SelectionDuplicate = 2469, SetCaretLineBackAlpha = 2470, GetCaretLineBackAlpha = 2471, SetCaretStyle = 2512, GetCaretStyle = 2513, SetIndicatorCurrent = 2500, GetIndicatorCurrent = 2501, SetIndicatorValue = 2502, GetIndicatorValue = 2503, IndicatorFillRange = 2504, IndicatorClearRange = 2505, IndicatorAllOnFor = 2506, IndicatorValueAt = 2507, IndicatorStart = 2508, IndicatorEnd = 2509, SetPositionCache = 2514, GetPositionCache = 2515, SetLayoutThreads = 2775, GetLayoutThreads = 2776, CopyAllowLine = 2519, GetCharacterPointer = 2520, GetRangePointer = 2643, GetGapPosition = 2644, IndicSetAlpha = 2523, IndicGetAlpha = 2524, IndicSetOutlineAlpha = 2558, IndicGetOutlineAlpha = 2559, SetExtraAscent = 2525, GetExtraAscent = 2526, SetExtraDescent = 2527, GetExtraDescent = 2528, MarkerSymbolDefined = 2529, MarginSetText = 2530, MarginGetText = 2531, MarginSetStyle = 2532, MarginGetStyle = 2533, MarginSetStyles = 2534, MarginGetStyles = 2535, MarginTextClearAll = 2536, MarginSetStyleOffset = 2537, MarginGetStyleOffset = 2538, SetMarginOptions = 2539, GetMarginOptions = 2557, AnnotationSetText = 2540, AnnotationGetText = 2541, AnnotationSetStyle = 2542, AnnotationGetStyle = 2543, AnnotationSetStyles = 2544, AnnotationGetStyles = 2545, AnnotationGetLines = 2546, AnnotationClearAll = 2547, AnnotationSetVisible = 2548, AnnotationGetVisible = 2549, AnnotationSetStyleOffset = 2550, AnnotationGetStyleOffset = 2551, ReleaseAllExtendedStyles = 2552, AllocateExtendedStyles = 2553, AddUndoAction = 2560, CharPositionFromPoint = 2561, CharPositionFromPointClose = 2562, SetMouseSelectionRectangularSwitch = 2668, GetMouseSelectionRectangularSwitch = 2669, SetMultipleSelection = 2563, GetMultipleSelection = 2564, SetAdditionalSelectionTyping = 2565, GetAdditionalSelectionTyping = 2566, SetAdditionalCaretsBlink = 2567, GetAdditionalCaretsBlink = 2568, SetAdditionalCaretsVisible = 2608, GetAdditionalCaretsVisible = 2609, GetSelections = 2570, GetSelectionEmpty = 2650, ClearSelections = 2571, SetSelection = 2572, AddSelection = 2573, DropSelectionN = 2671, SetMainSelection = 2574, GetMainSelection = 2575, SetSelectionNCaret = 2576, GetSelectionNCaret = 2577, SetSelectionNAnchor = 2578, GetSelectionNAnchor = 2579, SetSelectionNCaretVirtualSpace = 2580, GetSelectionNCaretVirtualSpace = 2581, SetSelectionNAnchorVirtualSpace = 2582, GetSelectionNAnchorVirtualSpace = 2583, SetSelectionNStart = 2584, GetSelectionNStart = 2585, GetSelectionNStartVirtualSpace = 2726, SetSelectionNEnd = 2586, GetSelectionNEndVirtualSpace = 2727, GetSelectionNEnd = 2587, SetRectangularSelectionCaret = 2588, GetRectangularSelectionCaret = 2589, SetRectangularSelectionAnchor = 2590, GetRectangularSelectionAnchor = 2591, SetRectangularSelectionCaretVirtualSpace = 2592, GetRectangularSelectionCaretVirtualSpace = 2593, SetRectangularSelectionAnchorVirtualSpace = 2594, GetRectangularSelectionAnchorVirtualSpace = 2595, SetVirtualSpaceOptions = 2596, GetVirtualSpaceOptions = 2597, SetRectangularSelectionModifier = 2598, GetRectangularSelectionModifier = 2599, SetAdditionalSelFore = 2600, SetAdditionalSelBack = 2601, SetAdditionalSelAlpha = 2602, GetAdditionalSelAlpha = 2603, SetAdditionalCaretFore = 2604, GetAdditionalCaretFore = 2605, RotateSelection = 2606, SwapMainAnchorCaret = 2607, MultipleSelectAddNext = 2688, MultipleSelectAddEach = 2689, ChangeLexerState = 2617, ContractedFoldNext = 2618, VerticalCentreCaret = 2619, MoveSelectedLinesUp = 2620, MoveSelectedLinesDown = 2621, SetIdentifier = 2622, GetIdentifier = 2623, RGBAImageSetWidth = 2624, RGBAImageSetHeight = 2625, RGBAImageSetScale = 2651, MarkerDefineRGBAImage = 2626, RegisterRGBAImage = 2627, ScrollToStart = 2628, ScrollToEnd = 2629, SetTechnology = 2630, GetTechnology = 2631, CreateLoader = 2632, FindIndicatorShow = 2640, FindIndicatorFlash = 2641, FindIndicatorHide = 2642, VCHomeDisplay = 2652, VCHomeDisplayExtend = 2653, GetCaretLineVisibleAlways = 2654, SetCaretLineVisibleAlways = 2655, SetLineEndTypesAllowed = 2656, GetLineEndTypesAllowed = 2657, GetLineEndTypesActive = 2658, SetRepresentation = 2665, GetRepresentation = 2666, ClearRepresentation = 2667, ClearAllRepresentations = 2770, SetRepresentationAppearance = 2766, GetRepresentationAppearance = 2767, SetRepresentationColour = 2768, GetRepresentationColour = 2769, EOLAnnotationSetText = 2740, EOLAnnotationGetText = 2741, EOLAnnotationSetStyle = 2742, EOLAnnotationGetStyle = 2743, EOLAnnotationClearAll = 2744, EOLAnnotationSetVisible = 2745, EOLAnnotationGetVisible = 2746, EOLAnnotationSetStyleOffset = 2747, EOLAnnotationGetStyleOffset = 2748, SupportsFeature = 2750, GetLineCharacterIndex = 2710, AllocateLineCharacterIndex = 2711, ReleaseLineCharacterIndex = 2712, LineFromIndexPosition = 2713, IndexPositionFromLine = 2714, StartRecord = 3001, StopRecord = 3002, GetLexer = 4002, Colourise = 4003, SetProperty = 4004, SetKeyWords = 4005, GetProperty = 4008, GetPropertyExpanded = 4009, GetPropertyInt = 4010, GetLexerLanguage = 4012, PrivateLexerCall = 4013, PropertyNames = 4014, PropertyType = 4015, DescribeProperty = 4016, DescribeKeyWordSets = 4017, GetLineEndTypesSupported = 4018, AllocateSubStyles = 4020, GetSubStylesStart = 4021, GetSubStylesLength = 4022, GetStyleFromSubStyle = 4027, GetPrimaryStyleFromStyle = 4028, FreeSubStyles = 4023, SetIdentifiers = 4024, DistanceToSecondaryStyles = 4025, GetSubStyleBases = 4026, GetNamedStyles = 4029, NameOfStyle = 4030, TagsOfStyle = 4031, DescriptionOfStyle = 4032, SetILexer = 4033, GetBidirectional = 2708, SetBidirectional = 2709, }; Q_ENUM(Message); enum class WhiteSpace { Invisible = 0, VisibleAlways = 1, VisibleAfterIndent = 2, VisibleOnlyInIndent = 3, }; Q_ENUM(WhiteSpace); enum class TabDrawMode { LongArrow = 0, StrikeOut = 1, }; Q_ENUM(TabDrawMode); enum class EndOfLine { CrLf = 0, Cr = 1, Lf = 2, }; Q_ENUM(EndOfLine); enum class IMEInteraction { Windowed = 0, Inline = 1, }; Q_ENUM(IMEInteraction); enum class Alpha { Transparent = 0, Opaque = 255, NoAlpha = 256, }; Q_ENUM(Alpha); enum class CursorShape { Normal = -1, Arrow = 2, Wait = 4, ReverseArrow = 7, }; Q_ENUM(CursorShape); enum class MarkerSymbol { Circle = 0, RoundRect = 1, Arrow = 2, SmallRect = 3, ShortArrow = 4, Empty = 5, ArrowDown = 6, Minus = 7, Plus = 8, VLine = 9, LCorner = 10, TCorner = 11, BoxPlus = 12, BoxPlusConnected = 13, BoxMinus = 14, BoxMinusConnected = 15, LCornerCurve = 16, TCornerCurve = 17, CirclePlus = 18, CirclePlusConnected = 19, CircleMinus = 20, CircleMinusConnected = 21, Background = 22, DotDotDot = 23, Arrows = 24, Pixmap = 25, FullRect = 26, LeftRect = 27, Available = 28, Underline = 29, RgbaImage = 30, Bookmark = 31, VerticalBookmark = 32, Character = 10000, }; Q_ENUM(MarkerSymbol); enum class MarkerOutline { FolderEnd = 25, FolderOpenMid = 26, FolderMidTail = 27, FolderTail = 28, FolderSub = 29, Folder = 30, FolderOpen = 31, }; Q_ENUM(MarkerOutline); enum class MarginType { Symbol = 0, Number = 1, Back = 2, Fore = 3, Text = 4, RText = 5, Colour = 6, }; Q_ENUM(MarginType); enum class StylesCommon { Default = 32, LineNumber = 33, BraceLight = 34, BraceBad = 35, ControlChar = 36, IndentGuide = 37, CallTip = 38, FoldDisplayText = 39, LastPredefined = 39, Max = 255, }; Q_ENUM(StylesCommon); enum class CharacterSet { Ansi = 0, Default = 1, Baltic = 186, ChineseBig5 = 136, EastEurope = 238, GB2312 = 134, Greek = 161, Hangul = 129, Mac = 77, Oem = 255, Russian = 204, Oem866 = 866, Cyrillic = 1251, ShiftJis = 128, Symbol = 2, Turkish = 162, Johab = 130, Hebrew = 177, Arabic = 178, Vietnamese = 163, Thai = 222, Iso8859_15 = 1000, }; Q_ENUM(CharacterSet); enum class CaseVisible { Mixed = 0, Upper = 1, Lower = 2, Camel = 3, }; Q_ENUM(CaseVisible); enum class FontWeight { Normal = 400, SemiBold = 600, Bold = 700, }; Q_ENUM(FontWeight); enum class Element { List = 0, ListBack = 1, ListSelected = 2, ListSelectedBack = 3, SelectionText = 10, SelectionBack = 11, SelectionAdditionalText = 12, SelectionAdditionalBack = 13, SelectionSecondaryText = 14, SelectionSecondaryBack = 15, SelectionInactiveText = 16, SelectionInactiveBack = 17, Caret = 40, CaretAdditional = 41, CaretLineBack = 50, WhiteSpace = 60, WhiteSpaceBack = 61, HotSpotActive = 70, HotSpotActiveBack = 71, FoldLine = 80, HiddenLine = 81, }; Q_ENUM(Element); enum class Layer { Base = 0, UnderText = 1, OverText = 2, }; Q_ENUM(Layer); enum class IndicatorStyle { Plain = 0, Squiggle = 1, TT = 2, Diagonal = 3, Strike = 4, Hidden = 5, Box = 6, RoundBox = 7, StraightBox = 8, Dash = 9, Dots = 10, SquiggleLow = 11, DotBox = 12, SquigglePixmap = 13, CompositionThick = 14, CompositionThin = 15, FullBox = 16, TextFore = 17, Point = 18, PointCharacter = 19, Gradient = 20, GradientCentre = 21, }; Q_ENUM(IndicatorStyle); enum class IndicatorNumbers { Container = 8, Ime = 32, ImeMax = 35, Max = 35, }; Q_ENUM(IndicatorNumbers); enum class IndicValue { Bit = 0x1000000, Mask = 0xFFFFFF, }; Q_ENUM(IndicValue); enum class IndicFlag { None = 0, ValueFore = 1, }; Q_ENUM(IndicFlag); enum class AutoCompleteOption { Normal = 0, FixedSize = 1, }; Q_ENUM(AutoCompleteOption); enum class IndentView { None = 0, Real = 1, LookForward = 2, LookBoth = 3, }; Q_ENUM(IndentView); enum class PrintOption { Normal = 0, InvertLight = 1, BlackOnWhite = 2, ColourOnWhite = 3, ColourOnWhiteDefaultBG = 4, ScreenColours = 5, }; Q_ENUM(PrintOption); enum class FindOption { None = 0x0, WholeWord = 0x2, MatchCase = 0x4, WordStart = 0x00100000, RegExp = 0x00200000, Posix = 0x00400000, Cxx11RegEx = 0x00800000, }; Q_ENUM(FindOption); enum class FoldLevel { None = 0x0, Base = 0x400, WhiteFlag = 0x1000, HeaderFlag = 0x2000, NumberMask = 0x0FFF, }; Q_ENUM(FoldLevel); enum class FoldDisplayTextStyle { Hidden = 0, Standard = 1, Boxed = 2, }; Q_ENUM(FoldDisplayTextStyle); enum class FoldAction { Contract = 0, Expand = 1, Toggle = 2, }; Q_ENUM(FoldAction); enum class AutomaticFold { None = 0x0000, Show = 0x0001, Click = 0x0002, Change = 0x0004, }; Q_ENUM(AutomaticFold); enum class FoldFlag { None = 0x0000, LineBeforeExpanded = 0x0002, LineBeforeContracted = 0x0004, LineAfterExpanded = 0x0008, LineAfterContracted = 0x0010, LevelNumbers = 0x0040, LineState = 0x0080, }; Q_ENUM(FoldFlag); enum class IdleStyling { None = 0, ToVisible = 1, AfterVisible = 2, All = 3, }; Q_ENUM(IdleStyling); enum class Wrap { None = 0, Word = 1, Char = 2, WhiteSpace = 3, }; Q_ENUM(Wrap); enum class WrapVisualFlag { None = 0x0000, End = 0x0001, Start = 0x0002, Margin = 0x0004, }; Q_ENUM(WrapVisualFlag); enum class WrapVisualLocation { Default = 0x0000, EndByText = 0x0001, StartByText = 0x0002, }; Q_ENUM(WrapVisualLocation); enum class WrapIndentMode { Fixed = 0, Same = 1, Indent = 2, DeepIndent = 3, }; Q_ENUM(WrapIndentMode); enum class LineCache { None = 0, Caret = 1, Page = 2, Document = 3, }; Q_ENUM(LineCache); enum class PhasesDraw { One = 0, Two = 1, Multiple = 2, }; Q_ENUM(PhasesDraw); enum class FontQuality { QualityMask = 0xF, QualityDefault = 0, QualityNonAntialiased = 1, QualityAntialiased = 2, QualityLcdOptimized = 3, }; Q_ENUM(FontQuality); enum class MultiPaste { Once = 0, Each = 1, }; Q_ENUM(MultiPaste); enum class Accessibility { Disabled = 0, Enabled = 1, }; Q_ENUM(Accessibility); enum class EdgeVisualStyle { None = 0, Line = 1, Background = 2, MultiLine = 3, }; Q_ENUM(EdgeVisualStyle); enum class PopUp { Never = 0, All = 1, Text = 2, }; Q_ENUM(PopUp); enum class DocumentOption { Default = 0, StylesNone = 0x1, TextLarge = 0x100, }; Q_ENUM(DocumentOption); enum class Status { Ok = 0, Failure = 1, BadAlloc = 2, WarnStart = 1000, RegEx = 1001, }; Q_ENUM(Status); enum class VisiblePolicy { Slop = 0x01, Strict = 0x04, }; Q_ENUM(VisiblePolicy); enum class CaretPolicy { Slop = 0x01, Strict = 0x04, Jumps = 0x10, Even = 0x08, }; Q_ENUM(CaretPolicy); enum class SelectionMode { Stream = 0, Rectangle = 1, Lines = 2, Thin = 3, }; Q_ENUM(SelectionMode); enum class CaseInsensitiveBehaviour { RespectCase = 0, IgnoreCase = 1, }; Q_ENUM(CaseInsensitiveBehaviour); enum class MultiAutoComplete { Once = 0, Each = 1, }; Q_ENUM(MultiAutoComplete); enum class Ordering { PreSorted = 0, PerformSort = 1, Custom = 2, }; Q_ENUM(Ordering); enum class CaretSticky { Off = 0, On = 1, WhiteSpace = 2, }; Q_ENUM(CaretSticky); enum class CaretStyle { Invisible = 0, Line = 1, Block = 2, OverstrikeBar = 0, OverstrikeBlock = 0x10, Curses = 0x20, InsMask = 0xF, BlockAfter = 0x100, }; Q_ENUM(CaretStyle); enum class MarginOption { None = 0, SubLineSelect = 1, }; Q_ENUM(MarginOption); enum class AnnotationVisible { Hidden = 0, Standard = 1, Boxed = 2, Indented = 3, }; Q_ENUM(AnnotationVisible); enum class UndoFlags { None = 0, MayCoalesce = 1, }; Q_ENUM(UndoFlags); enum class VirtualSpace { None = 0, RectangularSelection = 1, UserAccessible = 2, NoWrapLineStart = 4, }; Q_ENUM(VirtualSpace); enum class Technology { Default = 0, DirectWrite = 1, DirectWriteRetain = 2, DirectWriteDC = 3, }; Q_ENUM(Technology); enum class LineEndType { Default = 0, Unicode = 1, }; Q_ENUM(LineEndType); enum class RepresentationAppearance { Plain = 0, Blob = 1, Colour = 0x10, }; Q_ENUM(RepresentationAppearance); enum class EOLAnnotationVisible { Hidden = 0x0, Standard = 0x1, Boxed = 0x2, Stadium = 0x100, FlatCircle = 0x101, AngleCircle = 0x102, CircleFlat = 0x110, Flats = 0x111, AngleFlat = 0x112, CircleAngle = 0x120, FlatAngle = 0x121, Angles = 0x122, }; Q_ENUM(EOLAnnotationVisible); enum class Supports { LineDrawsFinal = 0, PixelDivisions = 1, FractionalStrokeWidth = 2, TranslucentStroke = 3, PixelModification = 4, ThreadSafeMeasureWidths = 5, }; Q_ENUM(Supports); enum class LineCharacterIndexType { None = 0, Utf32 = 1, Utf16 = 2, }; Q_ENUM(LineCharacterIndexType); enum class TypeProperty { Boolean = 0, Integer = 1, String = 2, }; Q_ENUM(TypeProperty); enum class ModificationFlags { None = 0x0, InsertText = 0x1, DeleteText = 0x2, ChangeStyle = 0x4, ChangeFold = 0x8, User = 0x10, Undo = 0x20, Redo = 0x40, MultiStepUndoRedo = 0x80, LastStepInUndoRedo = 0x100, ChangeMarker = 0x200, BeforeInsert = 0x400, BeforeDelete = 0x800, MultilineUndoRedo = 0x1000, StartAction = 0x2000, ChangeIndicator = 0x4000, ChangeLineState = 0x8000, ChangeMargin = 0x10000, ChangeAnnotation = 0x20000, Container = 0x40000, LexerState = 0x80000, InsertCheck = 0x100000, ChangeTabStops = 0x200000, ChangeEOLAnnotation = 0x400000, EventMaskAll = 0x7FFFFF, }; Q_ENUM(ModificationFlags); enum class Update { None = 0x0, Content = 0x1, Selection = 0x2, VScroll = 0x4, HScroll = 0x8, }; Q_ENUM(Update); enum class FocusChange { Change = 768, Setfocus = 512, Killfocus = 256, }; Q_ENUM(FocusChange); enum class Keys { Down = 300, Up = 301, Left = 302, Right = 303, Home = 304, End = 305, Prior = 306, Next = 307, Delete = 308, Insert = 309, Escape = 7, Back = 8, Tab = 9, Return = 13, Add = 310, Subtract = 311, Divide = 312, Win = 313, RWin = 314, Menu = 315, }; Q_ENUM(Keys); enum class KeyMod { Norm = 0, Shift = 1, Ctrl = 2, Alt = 4, Super = 8, Meta = 16, }; Q_ENUM(KeyMod); enum class CompletionMethods { FillUp = 1, DoubleClick = 2, Tab = 3, Newline = 4, Command = 5, }; Q_ENUM(CompletionMethods); enum class CharacterSource { DirectInput = 0, TentativeInput = 1, ImeResult = 2, }; Q_ENUM(CharacterSource); enum class Bidirectional { Disabled = 0, L2R = 1, R2L = 2, }; Q_ENUM(Bidirectional); enum class Notification { StyleNeeded = 2000, CharAdded = 2001, SavePointReached = 2002, SavePointLeft = 2003, ModifyAttemptRO = 2004, Key = 2005, DoubleClick = 2006, UpdateUI = 2007, Modified = 2008, MacroRecord = 2009, MarginClick = 2010, NeedShown = 2011, Painted = 2013, UserListSelection = 2014, URIDropped = 2015, DwellStart = 2016, DwellEnd = 2017, Zoom = 2018, HotSpotClick = 2019, HotSpotDoubleClick = 2020, CallTipClick = 2021, AutoCSelection = 2022, IndicatorClick = 2023, IndicatorRelease = 2024, AutoCCancelled = 2025, AutoCCharDeleted = 2026, HotSpotReleaseClick = 2027, FocusIn = 2028, FocusOut = 2029, AutoCCompleted = 2030, MarginRightClick = 2031, AutoCSelectionChange = 2032, }; Q_ENUM(Notification); /* --Autogenerated -- end of section automatically generated from Scintilla.iface */
35,341
C++
.h
1,431
20.283718
86
0.689314
dail8859/NotepadNext
9,006
547
57
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false