From fbb734689b8989bb8bc5df8217b1469e084ca64b Mon Sep 17 00:00:00 2001 From: John Wiegley Date: Thu, 26 Feb 2009 04:41:38 -0400 Subject: Added a new source_context function --- src/error.cc | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'src/error.cc') diff --git a/src/error.cc b/src/error.cc index ffcd2941..5a45318f 100644 --- a/src/error.cc +++ b/src/error.cc @@ -77,4 +77,40 @@ string line_context(const string& line, return buf.str(); } +string source_context(const path& file, + std::size_t pos, + std::size_t end_pos, + const string& prefix) +{ + std::size_t len = end_pos - pos; + if (! len) + return _(""); + + assert(len > 0); + assert(len < 2048); + + std::ostringstream out; + + ifstream in(file); + in.seekg(pos, std::ios::beg); + + scoped_array buf(new char[len + 1]); + in.read(buf.get(), len); + assert(static_cast(in.gcount()) == len); + buf[len] = '\0'; + + bool first = true; + for (char * p = std::strtok(buf.get(), "\n"); + p; + p = std::strtok(NULL, "\n")) { + if (first) + first = false; + else + out << '\n'; + out << prefix << p; + } + + return out.str(); +} + } // namespace ledger -- cgit v1.2.3