diff --git a/src/NotepadNext/EditorManager.cpp b/src/NotepadNext/EditorManager.cpp index 53eaa752f..1e155af13 100644 --- a/src/NotepadNext/EditorManager.cpp +++ b/src/NotepadNext/EditorManager.cpp @@ -266,6 +266,9 @@ void EditorManager::setupEditor(ScintillaNext *editor) editor->setIndentationGuides(settings->showIndentGuide() ? SC_IV_LOOKBOTH : SC_IV_NONE); editor->setWrapMode(settings->wordWrap() ? SC_WRAP_WORD : SC_WRAP_NONE); + // TODO: make this optional + editor->setEOLMode(detectEOLMode(editor)); + // Decorators SmartHighlighter *s = new SmartHighlighter(editor); s->setEnabled(true); @@ -316,3 +319,53 @@ QList > EditorManager::getEditors() purgeOldEditorPointers(); return editors; } + +int EditorManager::detectEOLMode(ScintillaNext *editor) const +{ + qInfo(Q_FUNC_INFO); + + const int MIN_LINE_THRESHOLD = 3; + const int MAX_BYTES_TO_CHECK = 10*1024; + + int index = 0; + int lf = 0; + int cr = 0; + int crlf = 0; + int chPrev = ' '; + int chNext = editor->charAt(index); + + for (int i = 0; i < qMin(MAX_BYTES_TO_CHECK, (int) editor->length()); ++i) { + int ch = chNext; + chNext = editor->charAt(i + 1); + + if (ch == '\r') { + if (chNext == '\n') crlf++; + else cr++; + } + else if (ch == '\n') { + if (chPrev != '\r') lf++; + } + + chPrev = ch; + + // If any meet some minimum threshold then just declare victory + if (crlf == MIN_LINE_THRESHOLD) return SC_EOL_CRLF; + else if (cr == MIN_LINE_THRESHOLD) return SC_EOL_CR; + else if (lf == MIN_LINE_THRESHOLD) return SC_EOL_LF; + } + + // There are either no lines or only a few, so make a best effort determination + + if (crlf > cr && crlf > lf) { + return SC_EOL_CRLF; + } + else if (cr > lf) { + return SC_EOL_CR; + } + else if (lf > cr) { + return SC_EOL_LF; + } + else { + return editor->eOLMode(); + } +} diff --git a/src/NotepadNext/EditorManager.h b/src/NotepadNext/EditorManager.h index 68fc960b6..0aebb1ebb 100644 --- a/src/NotepadNext/EditorManager.h +++ b/src/NotepadNext/EditorManager.h @@ -49,6 +49,7 @@ class EditorManager : public QObject void setupEditor(ScintillaNext *editor); void purgeOldEditorPointers(); QList> getEditors(); + int detectEOLMode(ScintillaNext *editor) const; QList> editors; ApplicationSettings *settings;