From 7b5a87df3868ac107bb9e27e458b3a4dd10992fb Mon Sep 17 00:00:00 2001 From: Jean-Francois Dockes Date: Wed, 7 Sep 2022 10:30:17 +0200 Subject: [PATCH] grep before stdin --- src/index/rclgrep.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/index/rclgrep.cpp b/src/index/rclgrep.cpp index 5004e573..df4611f1 100644 --- a/src/index/rclgrep.cpp +++ b/src/index/rclgrep.cpp @@ -119,14 +119,22 @@ void grepit(const Rcl::Doc& doc) ppath += doc.ipath + "::"; } int lnum = 0; + int idx; std::string ln; bool inmatch{false}; for (const auto& line: lines) { + idx = lnum; ++lnum; //std::cout << "LINE:[" << line << "]\n"; for (const auto e_p : g_expressions) { auto match = e_p->simpleMatch(line); - if (((op_flags & OPT_v) && match) || (!(op_flags&OPT_v) && !match)) { + if (((op_flags & OPT_v) && match) || (!(op_flags & OPT_v) && !match)) { + if (inmatch && aftercontext && !(op_flags&OPT_c) && idx < int(lines.size())) { + for (int i = idx; i < std::min(int(lines.size()), idx + aftercontext); i++) { + std::cout << ppath << ln << lines[i] << "\n"; + } + std::cout << "--\n"; + } inmatch = false; goto nextline; } @@ -137,19 +145,13 @@ void grepit(const Rcl::Doc& doc) if (op_flags & OPT_n) { ln = ulltodecstr(lnum) + ":"; } - int idx = lnum -1; - if (beforecontext) { + if (!inmatch && !(op_flags&OPT_c) && beforecontext) { for (int i = std::max(0, idx - beforecontext); i < idx; i++) { std::cout << ppath << ln << lines[i] << "\n"; } } + inmatch=true; std::cout << ppath << ln << line << "\n"; - if (aftercontext && idx < int(lines.size() - 1)) { - for (int i = idx + 1; i < std::min(int(lines.size()), idx + aftercontext + 1); i++) { - std::cout << ppath << ln << lines[i] << "\n"; - } - std::cout << "--\n"; - } } nextline: continue;