/// <summary> /// Replaces all the search option holders in the given text. /// </summary> /// <param name="text">Text containing holders</param> /// <param name="grep">Grep object containing settings</param> /// <param name="totalHits">Number of total hits</param> /// <param name="showLineNumbers">Determines whether to show line numbers</param> /// <param name="removeLeadingWhiteSpace">Determines whether to remove leading white space</param> /// <returns>Text with holders replaced</returns> /// <history> /// [Curtis_Beard] 09/05/2006 Created /// [Curtis_Beard] 01/31/2012 ADD: display for additional options (skip hidden/system options, search paths, modified dates, file sizes) /// [Curtis_Beard] 10/30/2012 CHG: use year replacement for copyright /// [Curtis_Beard] 10/30/2012 ADD: file hit count, CHG: recurse to Subfolders /// [Curtis_Beard] 02/12/2014 CHG: handle file search only better, add totalHits as parameter /// [Curtis_Beard] 11/11/2014 ADD: export all filteritems /// </history> public static string ReplaceSearchOptions(string text, Grep grep, int totalHits, bool showLineNumbers, bool removeLeadingWhiteSpace) { var spec = grep.SearchSpec; text = text.Replace("%%totalhits%%", totalHits.ToString()); text = text.Replace("%%year%%", DateTime.Now.Year.ToString()); text = text.Replace("%%searchpaths%%", "Search Path(s): " + string.Join(", ", spec.StartDirectories)); text = text.Replace("%%filetypes%%", "File Types: " + grep.FileFilterSpec.FileFilter); text = text.Replace("%%regex%%", "Regular Expressions: " + spec.UseRegularExpressions); text = text.Replace("%%casesen%%", "Case Sensitive: " + spec.UseCaseSensitivity); text = text.Replace("%%wholeword%%", "Whole Word: " + spec.UseWholeWordMatching); text = text.Replace("%%recurse%%", "Subfolders: " + spec.SearchInSubfolders); text = text.Replace("%%filenameonly%%", "Show File Names Only: " + spec.ReturnOnlyFileNames); text = text.Replace("%%negation%%", "Negation: " + spec.UseNegation); text = text.Replace("%%linenumbers%%", "Line Numbers: " + showLineNumbers); text = text.Replace("%%removeleadingwhitespace%%", "Remove Leading White Space: " + removeLeadingWhiteSpace); text = text.Replace("%%contextlines%%", "Context Lines: " + spec.ContextLines); // filter items StringBuilder filterBuilder = new StringBuilder(); if (grep.FileFilterSpec.FilterItems != null) { filterBuilder.Append("Exclusions:<br/>"); foreach (FilterItem item in grep.FileFilterSpec.FilterItems) { string option = item.ValueOption.ToString(); if (item.ValueOption == FilterType.ValueOptions.None) { option = string.Empty; } filterBuilder.AppendFormat("<span class=\"indent\">{0} -> {1}: {2} {3} {4}</span><br/>", item.FilterType.Category, item.FilterType.SubCategory, item.Value, option, !string.IsNullOrEmpty(option) && item.ValueIgnoreCase ? " (ignore case)" : string.Empty ); } } text = text.Replace("%%exclusions%%", filterBuilder.ToString()); // %%searchmessage%% string searchMessage = string.Empty; if (!string.IsNullOrEmpty(grep.SearchSpec.SearchText)) { if (grep.SearchSpec.ReturnOnlyFileNames) { searchMessage = string.Format("{0} was {1}found in {2} file{3}", spec.SearchText, spec.UseNegation ? "not " : "", grep.MatchResults.Count, grep.MatchResults.Count > 1 ? "s" : ""); } else { searchMessage = string.Format("{0} was found {1} time{2} in {3} file{4}", spec.SearchText, totalHits, totalHits > 1 ? "s" : "", grep.MatchResults.Count, grep.MatchResults.Count > 1 ? "s" : ""); } } text = text.Replace("%%searchmessage%%", searchMessage); return(text); }
/// <summary> /// Replaces all the search option holders in the given text. /// </summary> /// <param name="text">Text containing holders</param> /// <param name="grep">Grep Object containing options</param> /// <returns>Text with holders replaced</returns> /// <history> /// [Curtis_Beard] 09/05/2006 Created /// </history> public static string ReplaceSearchOptions(string text, Grep grep) { text = text.Replace("%%filetypes%%", "File Types: " + grep.FileFilter); text = text.Replace("%%regex%%", "Regular Expressions: " + grep.UseRegularExpressions.ToString()); text = text.Replace("%%casesen%%", "Case Sensitive: " + grep.UseCaseSensitivity.ToString()); text = text.Replace("%%wholeword%%", "Whole Word: " + grep.UseWholeWordMatching.ToString()); text = text.Replace("%%recurse%%", "Recurse: " + grep.UseRecursion.ToString()); text = text.Replace("%%filenameonly%%", "Show File Names Only: " + grep.ReturnOnlyFileNames.ToString()); text = text.Replace("%%negation%%", "Negation: " + grep.UseNegation.ToString()); text = text.Replace("%%linenumbers%%", "Line Numbers: " + grep.IncludeLineNumbers.ToString()); text = text.Replace("%%contextlines%%", "Context Lines: " + grep.ContextLines.ToString()); text = text.Replace("%%totalfiles%%", grep.Greps.Count.ToString()); text = text.Replace("%%searchterm%%", grep.SearchText); if (grep.UseNegation) { text = text.Replace("%%usenegation%%", "not "); } else { text = text.Replace("%%usenegation%%", string.Empty); } return(text); }
public void ShouldCountTokenOccurancesInSingleLine() { //Assign var mock = new Mock <ILogger>(); var grep = new Grep(new[] { "marxk", "szymoxkn", "szyxmon", "sxkzyxmon", "sxkzyxmo nx xk xk", "", " ", "\\n", }, mock.Object); const string token = "xk"; //Act int result = grep.CountTokenOccurancesInAllLines(token); //Assert Assert.AreEqual(6, result); }
// pnyx -e=documentation pncs.cmd.examples.documentation.library.ExampleProcessorChain processorChain public static void processorChain() { StreamInformation streamInformation = new StreamInformation(new Settings()); // Writes to STDOUT ILineProcessor dest = new LineProcessorToStream(streamInformation, Console.OpenStandardOutput()); // Grep filter / processor pair ILineFilter grepFilter = new Grep { textToFind = "world", caseSensitive = false }; ILineProcessor grepProcessor = new LineFilterProcessor { filter = grepFilter, processor = dest }; // Sed transformer / processor pair ILineTransformer sedTransformer = new SedReplace("World", "World, with love from Pnyx..", null); ILineProcessor sedProcessor = new LineTransformerProcessor { transform = sedTransformer, processor = grepProcessor }; // Reads from source using (StringStreamFactory streamFactory = new StringStreamFactory("Hello World.")) { using (StreamToLineProcessor source = new StreamToLineProcessor(streamInformation, streamFactory)) { source.setNextLineProcessor(sedProcessor); // Runs source.process(); // All I/O occurs on this step } } // outputs: Hello World, with love from Pnyx... }
public void Multiple_files_several_matches_inverted_and_match_entire_lines_flags() { var pattern = "Illustrious into Ades premature,"; var flags = "-x -v"; var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "iliad.txt:Achilles sing, O Goddess! Peleus' son;\n" + "iliad.txt:His wrath pernicious, who ten thousand woes\n" + "iliad.txt:Caused to Achaia's host, sent many a soul\n" + "iliad.txt:And Heroes gave (so stood the will of Jove)\n" + "iliad.txt:To dogs and to all ravening fowls a prey,\n" + "iliad.txt:When fierce dispute had separated once\n" + "iliad.txt:The noble Chief Achilles from the son\n" + "iliad.txt:Of Atreus, Agamemnon, King of men.\n" + "midsummer-night.txt:I do entreat your grace to pardon me.\n" + "midsummer-night.txt:I know not by what power I am made bold,\n" + "midsummer-night.txt:Nor how it may concern my modesty,\n" + "midsummer-night.txt:In such a presence here to plead my thoughts;\n" + "midsummer-night.txt:But I beseech your grace that I may know\n" + "midsummer-night.txt:The worst that may befall me in this case,\n" + "midsummer-night.txt:If I refuse to wed Demetrius.\n" + "paradise-lost.txt:Of Mans First Disobedience, and the Fruit\n" + "paradise-lost.txt:Of that Forbidden Tree, whose mortal tast\n" + "paradise-lost.txt:Brought Death into the World, and all our woe,\n" + "paradise-lost.txt:With loss of Eden, till one greater Man\n" + "paradise-lost.txt:Restore us, and regain the blissful Seat,\n" + "paradise-lost.txt:Sing Heav'nly Muse, that on the secret top\n" + "paradise-lost.txt:Of Oreb, or of Sinai, didst inspire\n" + "paradise-lost.txt:That Shepherd, who first taught the chosen Seed"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void One_file_no_matches_various_flags(string flags) { const string pattern = "Gandalf"; var files = new[] { IliadFileName }; const string expected = ""; Assert.That(Grep.Find(pattern, flags, files), Is.EqualTo(expected)); }
public void One_file_one_match_no_flags() { var pattern = "Agamemnon"; var flags = ""; var files = new[] { "iliad.txt" }; var expected = "Of Atreus, Agamemnon, King of men."; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void One_file_one_match_multiple_flags() { var pattern = "OF ATREUS, Agamemnon, KIng of MEN."; var flags = "-n -i -x"; var files = new[] { "iliad.txt" }; var expected = "9:Of Atreus, Agamemnon, King of men."; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
private void BtnSearch_Click(object sender, EventArgs e) { var searchSpec = GetSearchSpecFromUI(); grep = new Grep(searchSpec); grep.FileHit += ReceiveFileHit; grep.Execute(); }
public void One_file_one_match_case_insensitive_flag() { var pattern = "FORBIDDEN"; var flags = "-i"; var files = new[] { "paradise-lost.txt" }; var expected = "Of that Forbidden Tree, whose mortal tast"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void Multiple_files_no_matches_various_flags() { var pattern = "Frodo"; var flags = "-n -l -x -i"; var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = ""; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void Multiple_files_one_match_multiple_flags() { var pattern = "WITH LOSS OF EDEN, TILL ONE GREATER MAN"; var flags = "-n -i -x"; var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "paradise-lost.txt:4:With loss of Eden, till one greater Man"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void Multiple_files_one_match_match_entire_lines_flag() { var pattern = "But I beseech your grace that I may know"; var flags = "-x"; var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "midsummer-night.txt:But I beseech your grace that I may know"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void One_file_one_match_print_line_numbers_flag() { var pattern = "Forbidden"; var flags = "-n"; var files = new[] { "paradise-lost.txt" }; var expected = "2:Of that Forbidden Tree, whose mortal tast"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void Multiple_files_one_match_no_flags() { var pattern = "Agamemnon"; var flags = ""; var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "iliad.txt:Of Atreus, Agamemnon, King of men."; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void One_file_one_match_file_flag_takes_precedence_over_line_flag() { var pattern = "ten"; var flags = "-n -l"; var files = new[] { "iliad.txt" }; var expected = "iliad.txt"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void One_file_no_matches_various_flags() { var pattern = "Gandalf"; var flags = "-n -l -x -i"; var files = new[] { "iliad.txt" }; var expected = ""; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void One_file_several_matches_match_entire_lines_flag() { var pattern = "may"; var flags = "-x"; var files = new[] { "midsummer-night.txt" }; var expected = ""; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void One_file_one_match_match_entire_lines_flag() { var pattern = "With loss of Eden, till one greater Man"; var flags = "-x"; var files = new[] { "paradise-lost.txt" }; var expected = "With loss of Eden, till one greater Man"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void One_file_one_match_print_file_names_flag() { var pattern = "Forbidden"; var flags = "-l"; var files = new[] { "paradise-lost.txt" }; var expected = "paradise-lost.txt"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); }
public void grep(String source, String textToFind, bool caseSensitive, bool expected) { Grep grep = new Grep(); grep.textToFind = textToFind; grep.caseSensitive = caseSensitive; Assert.Equal(expected, grep.shouldKeepLine(source)); }
public void Multiple_files_no_matches_various_flags(string flags) { const string pattern = "Frodo"; var files = new[] { IliadFileName, MidsummerNightFileName, ParadiseLostFileName }; const string expected = ""; Assert.That(Grep.Find(pattern, flags, files), Is.EqualTo(expected)); }
/// <summary> /// Returns the given line with the search text highlighted. /// </summary> /// <param name="line">Line to check</param> /// <param name="grep">Grep Object containing options</param> /// <returns>Line with search text highlighted</returns> /// <history> /// [Curtis_Beard] 09/05/2006 Created /// [Curtis_Beard] 05/18/2006 FIX: 1723815, use correct whole word matching regex /// [Curtis_Beard] 11/11/2014 CHG: escape any html characters /// [Curtis_Beard] 04/13/2015 CHG: code cleanup /// </history> private static string HighlightRegEx(string line, Grep grep) { string tempString = string.Empty; int lastPos = 0; Regex regEx; MatchCollection matchCollection; Match match; StringBuilder newLine = new StringBuilder(); // find all reg ex matches in line string pattern = string.Format("{0}{1}{0}", grep.SearchSpec.UseWholeWordMatching ? "\\b" : string.Empty, grep.SearchSpec.SearchText); RegexOptions options = grep.SearchSpec.UseCaseSensitivity ? RegexOptions.None : RegexOptions.IgnoreCase; regEx = new Regex(pattern, options); matchCollection = regEx.Matches(line); // loop through the matches for (int i = 0; i < matchCollection.Count; i++) { match = matchCollection[i]; // check for empty string to prevent assigning nothing to selection text preventing // a system beep tempString = line.Substring(lastPos, match.Index - lastPos); if (!tempString.Equals(string.Empty)) { newLine.Append(WebUtility.HtmlEncode(tempString)); } // set the hit text newLine.AppendFormat("<span class=\"searchtext\">{0}</span>", WebUtility.HtmlEncode(line.Substring(match.Index, match.Length))); // set the end text if (i + 1 >= matchCollection.Count) { // no more hits so just set the rest newLine.Append(WebUtility.HtmlEncode(line.Substring(match.Index + match.Length))); lastPos = match.Index + match.Length; } else { // another hit so just set inbetween newLine.Append(WebUtility.HtmlEncode(line.Substring(match.Index + match.Length, matchCollection[i + 1].Index - (match.Index + match.Length)))); lastPos = matchCollection[i + 1].Index; } } if (matchCollection.Count == 0) { // no match, just a context line newLine.Append(WebUtility.HtmlEncode(line)); } return(newLine.ToString()); }
public void Multiple_files_one_match_multiple_flags() { const string pattern = "WITH LOSS OF EDEN, TILL ONE GREATER MAN"; var files = new[] { IliadFileName, MidsummerNightFileName, ParadiseLostFileName }; const string flags = "-n -i -x"; var expected = $"{ParadiseLostFileName}:4:With loss of Eden, till one greater Man\n"; Assert.That(Grep.Find(pattern, flags, files), Is.EqualTo(expected)); }
public void One_file_one_match_multiple_flags() { const string pattern = "OF ATREUS, Agamemnon, KIng of MEN."; var files = new[] { IliadFileName }; const string flags = "-n -i -x"; const string expected = "9:Of Atreus, Agamemnon, King of men.\n"; Assert.That(Grep.Find(pattern, flags, files), Is.EqualTo(expected)); }
public void One_file_several_matches_match_entire_lines_flag() { const string pattern = "may"; const string flags = "-x"; var files = new[] { MidsummerNightFileName }; const string expected = ""; Assert.That(Grep.Find(pattern, flags, files), Is.EqualTo(expected)); }
/// <summary> /// Returns the given line with the search text highlighted. /// </summary> /// <param name="line">Line to check</param> /// <param name="grep">Grep Object containing options</param> /// <returns>Line with search text highlighted</returns> /// <history> /// [Curtis_Beard] 09/05/2006 Created /// [Curtis_Beard] 11/11/2014 CHG: escape any html characters /// [Curtis_Beard] 04/13/2015 CHG: code cleanup /// </history> private static string HighlightNormal(string line, Grep grep) { StringBuilder newLine = new StringBuilder(); string searchText = grep.SearchSpec.SearchText; string tempLine = line; // attempt to locate the text in the line int pos = tempLine.IndexOf(searchText, grep.SearchSpec.UseCaseSensitivity ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); if (pos > -1) { while (pos > -1) { //retrieve parts of text var begin = tempLine.Substring(0, pos); var text = tempLine.Substring(pos, searchText.Length); var end = tempLine.Substring(pos + searchText.Length); newLine.Append(WebUtility.HtmlEncode(begin)); // do a check to see if begin and end are valid for wholeword searches bool highlight = true; if (grep.SearchSpec.UseWholeWordMatching) { highlight = Grep.WholeWordOnly(begin, end); } // set highlight color for searched text if (highlight) { newLine.AppendFormat("<span class=\"searchtext\">{0}</span>", WebUtility.HtmlEncode(text)); } else { newLine.Append(WebUtility.HtmlEncode(text)); } // Check remaining string for other hits in same line pos = end.IndexOf(searchText, grep.SearchSpec.UseCaseSensitivity ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); // set default color for end, if no more hits in line tempLine = end; if (pos < 0) { newLine.Append(WebUtility.HtmlEncode(end)); } } } else { newLine.Append(WebUtility.HtmlEncode(tempLine)); } return(newLine.ToString()); }
public void One_file_one_match_print_file_names_flag() { const string pattern = "Forbidden"; const string flags = "-l"; var files = new[] { ParadiseLostFileName }; var expected = $"{ParadiseLostFileName}\n"; Assert.That(Grep.Find(pattern, flags, files), Is.EqualTo(expected)); }
public void One_file_one_match_case_insensitive_flag() { const string pattern = "Forbidden"; const string flags = "-i"; var files = new[] { ParadiseLostFileName }; const string expected = "Of that Forbidden Tree, whose mortal tast\n"; Assert.That(Grep.Find(pattern, flags, files), Is.EqualTo(expected)); }
public void One_file_one_match_no_flags() { const string pattern = "Agamemnon"; const string flags = ""; var files = new[] { IliadFileName }; const string expected = "Of Atreus, Agamemnon, King of men.\n"; Assert.That(Grep.Find(pattern, flags, files), Is.EqualTo(expected)); }