From dcd712dceb07eeea0ae0bfb63e680c89bae50f2c Mon Sep 17 00:00:00 2001
From: Aadhavan Srinivasan <aadhavan@twomorecents.org>
Date: Mon, 18 Nov 2024 09:36:16 -0500
Subject: [PATCH] Added support for -o flag: only print matching content

---
 main.go | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)

diff --git a/main.go b/main.go
index daedf56..3ec739a 100644
--- a/main.go
+++ b/main.go
@@ -372,7 +372,10 @@ func thompson(re []postfixNode) *State {
 
 func main() {
 	invertFlag := flag.Bool("v", false, "Invert match.")
-	//onlyFlag := flag.Bool("o", false, "Print only colored content.")
+	// This flag has two 'modes':
+	// 1. Without '-v': Prints only matches. Prints a newline after every match.
+	// 2. With '-v': Substitutes all matches with empty string.
+	onlyFlag := flag.Bool("o", false, "Print only colored content.")
 	flag.Parse()
 
 	// Process:
@@ -419,8 +422,19 @@ func main() {
 		for i, c := range test_str {
 			if indicesToPrint.contains(i) {
 				color.New(color.FgRed).Fprintf(out, "%c", c)
+				// Newline after every match - only if -v is disabled.
+				if !(*invertFlag) {
+					for _, idx := range matchIndices {
+						if i+1 == idx.endIdx { // End index is one more than last index of match
+							fmt.Fprintf(out, "\n")
+							break
+						}
+					}
+				}
 			} else {
-				fmt.Fprintf(out, "%c", c)
+				if !(*onlyFlag) {
+					fmt.Fprintf(out, "%c", c)
+				}
 			}
 		}
 		err = out.Flush()