From be03db9a249e8124f2b9a77d3bdbb8d6b884a70e Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Fri, 5 Jun 2015 13:52:56 +0100 Subject: [PATCH] Support sourcing files that use crlf end of lines --- src/commands.cc | 2 +- src/file.cc | 27 +++++++++++++++++++++------ src/file.hh | 4 ++-- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/src/commands.cc b/src/commands.cc index e1aad46d..ce32f08e 100644 --- a/src/commands.cc +++ b/src/commands.cc @@ -947,7 +947,7 @@ const CommandDesc source_cmd = { filename_completer, [](const ParametersParser& parser, Context& context) { - String file_content = read_file(parse_filename(parser[0])); + String file_content = read_file(parse_filename(parser[0]), true); try { CommandManager::instance().execute(file_content, context); diff --git a/src/file.cc b/src/file.cc index adbb37cc..9f299a93 100644 --- a/src/file.cc +++ b/src/file.cc @@ -110,22 +110,37 @@ String compact_path(StringView filename) return filename.str(); } -String read_fd(int fd) +String read_fd(int fd, bool text) { String content; - char buf[256]; + constexpr size_t bufsize = 256; + char buf[bufsize]; while (true) { - ssize_t size = read(fd, buf, 256); + ssize_t size = read(fd, buf, bufsize); if (size == -1 or size == 0) break; - content += StringView(buf, buf + size); + if (text) + { + ssize_t beg = 0; + for (ssize_t pos = 0; pos < size; ++pos) + { + if (buf[pos] == '\r') + { + content += StringView{buf + beg, buf + pos}; + beg = pos + 1; + } + } + content += StringView{buf + beg, buf + size}; + } + else + content += StringView{buf, buf + size}; } return content; } -String read_file(StringView filename) +String read_file(StringView filename, bool text) { int fd = open(parse_filename(filename).c_str(), O_RDONLY); if (fd == -1) @@ -137,7 +152,7 @@ String read_file(StringView filename) } auto close_fd = on_scope_end([fd]{ close(fd); }); - return read_fd(fd); + return read_fd(fd, text); } Buffer* create_buffer_from_file(StringView filename) diff --git a/src/file.hh b/src/file.hh index 6f018e55..863c98fb 100644 --- a/src/file.hh +++ b/src/file.hh @@ -37,8 +37,8 @@ std::pair split_path(StringView path); String get_kak_binary_path(); -String read_fd(int fd); -String read_file(StringView filename); +String read_fd(int fd, bool text = false); +String read_file(StringView filename, bool text = false); Buffer* create_buffer_from_file(StringView filename);