Skip to content

Commit 90b70b3

Browse files
authored
Auto detect EOL mode (#693)
Closes #607
1 parent 0bad562 commit 90b70b3

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/NotepadNext/EditorManager.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,9 @@ void EditorManager::setupEditor(ScintillaNext *editor)
266266
editor->setIndentationGuides(settings->showIndentGuide() ? SC_IV_LOOKBOTH : SC_IV_NONE);
267267
editor->setWrapMode(settings->wordWrap() ? SC_WRAP_WORD : SC_WRAP_NONE);
268268

269+
// TODO: make this optional
270+
editor->setEOLMode(detectEOLMode(editor));
271+
269272
// Decorators
270273
SmartHighlighter *s = new SmartHighlighter(editor);
271274
s->setEnabled(true);
@@ -316,3 +319,53 @@ QList<QPointer<ScintillaNext> > EditorManager::getEditors()
316319
purgeOldEditorPointers();
317320
return editors;
318321
}
322+
323+
int EditorManager::detectEOLMode(ScintillaNext *editor) const
324+
{
325+
qInfo(Q_FUNC_INFO);
326+
327+
const int MIN_LINE_THRESHOLD = 3;
328+
const int MAX_BYTES_TO_CHECK = 10*1024;
329+
330+
int index = 0;
331+
int lf = 0;
332+
int cr = 0;
333+
int crlf = 0;
334+
int chPrev = ' ';
335+
int chNext = editor->charAt(index);
336+
337+
for (int i = 0; i < qMin(MAX_BYTES_TO_CHECK, (int) editor->length()); ++i) {
338+
int ch = chNext;
339+
chNext = editor->charAt(i + 1);
340+
341+
if (ch == '\r') {
342+
if (chNext == '\n') crlf++;
343+
else cr++;
344+
}
345+
else if (ch == '\n') {
346+
if (chPrev != '\r') lf++;
347+
}
348+
349+
chPrev = ch;
350+
351+
// If any meet some minimum threshold then just declare victory
352+
if (crlf == MIN_LINE_THRESHOLD) return SC_EOL_CRLF;
353+
else if (cr == MIN_LINE_THRESHOLD) return SC_EOL_CR;
354+
else if (lf == MIN_LINE_THRESHOLD) return SC_EOL_LF;
355+
}
356+
357+
// There are either no lines or only a few, so make a best effort determination
358+
359+
if (crlf > cr && crlf > lf) {
360+
return SC_EOL_CRLF;
361+
}
362+
else if (cr > lf) {
363+
return SC_EOL_CR;
364+
}
365+
else if (lf > cr) {
366+
return SC_EOL_LF;
367+
}
368+
else {
369+
return editor->eOLMode();
370+
}
371+
}

src/NotepadNext/EditorManager.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ class EditorManager : public QObject
4949
void setupEditor(ScintillaNext *editor);
5050
void purgeOldEditorPointers();
5151
QList<QPointer<ScintillaNext>> getEditors();
52+
int detectEOLMode(ScintillaNext *editor) const;
5253

5354
QList<QPointer<ScintillaNext>> editors;
5455
ApplicationSettings *settings;

0 commit comments

Comments
 (0)