Skip to content

Commit 1b186af

Browse files
authored
Merge pull request #6 from lifenjoiner/LineEncoding
fix CTextFile line recognition
2 parents e4a5c2f + 89d4a79 commit 1b186af

File tree

1 file changed

+21
-28
lines changed

1 file changed

+21
-28
lines changed

TextFile.cpp

+21-28
Original file line numberDiff line numberDiff line change
@@ -531,37 +531,36 @@ bool CTextFile::CalculateLines(std::atomic_bool &bCancelled)
531531
return true;
532532
linePositions.clear();
533533
linePositions.reserve(textContent.size() / 10);
534-
size_t pos = 0;
534+
size_t pos = 0;
535+
bool bGot = false;
535536
for (auto it = textContent.begin(); it != textContent.end() && !bCancelled; ++it)
536537
{
538+
bGot = false;
537539
if (*it == '\r')
538540
{
539-
++it;
540-
++pos;
541-
if (it != textContent.end())
541+
// cr lineending
542+
bGot = true;
543+
if (it + 1 < textContent.end())
542544
{
543-
if (*it == '\n')
545+
if (it[1] == '\n')
544546
{
545547
// crlf lineending
546-
linePositions.push_back(pos);
547-
}
548-
else
549-
{
550-
// cr lineending
551-
linePositions.push_back(pos - 1);
548+
++it;
549+
++pos;
552550
}
553551
}
554-
else
555-
break;
556552
}
557553
else if (*it == '\n')
558554
{
559555
// lf lineending
560-
linePositions.push_back(pos);
556+
bGot = true;
561557
}
558+
if (bGot)
559+
linePositions.push_back(pos);
562560
++pos;
563561
}
564-
linePositions.push_back(pos);
562+
if (!bGot)
563+
linePositions.push_back(pos);
565564
return true;
566565
}
567566

@@ -574,23 +573,17 @@ long CTextFile::LineFromPosition(long pos) const
574573

575574
std::wstring CTextFile::GetLineString(long lineNumber) const
576575
{
577-
if ((lineNumber - 2) >= static_cast<long>(linePositions.size()))
578-
return std::wstring();
579-
if (lineNumber <= 0)
576+
if ((lineNumber <= 0) || (lineNumber > static_cast<long>(linePositions.size())))
580577
return std::wstring();
581578

582-
long startPos = 0;
579+
size_t startPos = 0;
580+
size_t endPos = linePositions[lineNumber - 1];
583581
if (lineNumber > 1)
584-
startPos = static_cast<long>(linePositions[lineNumber - 2]) + 1;
585-
std::wstring endChars(L"\n\0", 2);
586-
size_t endPos = textContent.find_first_of(endChars, startPos);
587-
std::wstring line;
588-
if (endPos != std::wstring::npos)
589-
line = std::wstring(textContent.begin() + startPos, textContent.begin() + endPos);
590-
else
591-
line = std::wstring(textContent.begin() + startPos, textContent.end());
582+
startPos = linePositions[lineNumber - 2] + 1;
583+
if (lineNumber < static_cast<long>(linePositions.size()))
584+
endPos++;
592585

593-
return line;
586+
return std::wstring(textContent.begin() + startPos, textContent.begin() + endPos);
594587
}
595588

596589
std::wstring CTextFile::GetEncodingString(UnicodeType type)

0 commit comments

Comments
 (0)