mirror of
https://github.com/RGBCube/serenity
synced 2025-07-24 15:17:45 +00:00
LibGUI: Make TextEditor write a trailing newline to non-empty files
Fixes #4801.
This commit is contained in:
parent
a048f46be5
commit
7f616449ec
2 changed files with 23 additions and 14 deletions
|
@ -79,6 +79,11 @@ void TextDocument::set_text(const StringView& text)
|
||||||
add_line(i);
|
add_line(i);
|
||||||
}
|
}
|
||||||
add_line(i);
|
add_line(i);
|
||||||
|
|
||||||
|
// Don't show the file's trailing newline as an actual new line.
|
||||||
|
if (line_count() > 1 && line(line_count() - 1).is_empty())
|
||||||
|
m_lines.take_last();
|
||||||
|
|
||||||
m_client_notifications_enabled = true;
|
m_client_notifications_enabled = true;
|
||||||
|
|
||||||
for (auto* client : m_clients)
|
for (auto* client : m_clients)
|
||||||
|
|
|
@ -1060,19 +1060,25 @@ bool TextEditor::write_to_file(const String& path)
|
||||||
|
|
||||||
ScopeGuard fd_guard = [fd] { close(fd); };
|
ScopeGuard fd_guard = [fd] { close(fd); };
|
||||||
|
|
||||||
// Compute the final file size and ftruncate() to make writing fast.
|
|
||||||
// FIXME: Remove this once the kernel is smart enough to do this instead.
|
|
||||||
off_t file_size = 0;
|
off_t file_size = 0;
|
||||||
for (size_t i = 0; i < line_count(); ++i)
|
if (line_count() == 1 && line(0).is_empty()) {
|
||||||
file_size += line(i).length();
|
// Truncate to zero.
|
||||||
file_size += line_count() - 1;
|
} else {
|
||||||
|
// Compute the final file size and ftruncate() to make writing fast.
|
||||||
|
// FIXME: Remove this once the kernel is smart enough to do this instead.
|
||||||
|
for (size_t i = 0; i < line_count(); ++i)
|
||||||
|
file_size += line(i).length();
|
||||||
|
file_size += line_count();
|
||||||
|
}
|
||||||
|
|
||||||
int rc = ftruncate(fd, file_size);
|
if (ftruncate(fd, file_size) < 0) {
|
||||||
if (rc < 0) {
|
|
||||||
perror("ftruncate");
|
perror("ftruncate");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (file_size == 0)
|
||||||
|
return true;
|
||||||
|
|
||||||
for (size_t i = 0; i < line_count(); ++i) {
|
for (size_t i = 0; i < line_count(); ++i) {
|
||||||
auto& line = this->line(i);
|
auto& line = this->line(i);
|
||||||
if (line.length()) {
|
if (line.length()) {
|
||||||
|
@ -1083,13 +1089,11 @@ bool TextEditor::write_to_file(const String& path)
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (i != line_count() - 1) {
|
char ch = '\n';
|
||||||
char ch = '\n';
|
ssize_t nwritten = write(fd, &ch, 1);
|
||||||
ssize_t nwritten = write(fd, &ch, 1);
|
if (nwritten != 1) {
|
||||||
if (nwritten != 1) {
|
perror("write");
|
||||||
perror("write");
|
return false;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue