Classes: Text, Mark, Range, Pattern, PatternCount, Box; Delegates, Enums

Examples


Class Text: Text Constructors, Text Methods, Text Operators, Text Properties, Text Events

Defines a buffer of text which can be manipulated programmatically.

Text Constructors

Text()

Creates an empty Text.

Text(string text)

Creates a Text from a string. Carriage return characters are removed.
text: string value to add to the Text.

Text(string text, bool removeCR)

Creates a Text from a string.
text: string value to add to the Text.
removeCR: bool value to indicate whether carriage return characters should be removed.

Text(string filename, Encoding encoding)

Creates a Text from a text file. Carriage return characters are removed, and the whole file is read before returning.
filename: string value containing the text file path.
encoding: Encoding value or null for default ASCII.

Text(string filename, Encoding encoding, bool removeCR)

Creates a Text from a text file. The whole file is read before returning.
filename: string value containing the text file path.
encoding: Encoding value or null for default ASCII.
removeCR: bool value to indicate whether carriage return characters should be removed.

Text(string filename, Encoding encoding, DataLoad dataLoad)

Creates a Text from a text file. Carriage returns are removed.
filename: string value containing the text file path.
encoding: Encoding value or null for default ASCII.
dataLoad: DataLoad value to indicate timing of loading of data from the file.

Text(string filename, Encoding encoding, bool removeCR, DataLoad dataLoad)

Creates a Text from a text file.
filename: string value containing the text file path.
encoding: Encoding value or null for default ASCII.
removeCR: bool value to indicate whether carriage return characters should be removed.
dataLoad: DataLoad value to indicate timing of loading of data from the file.

Text(StreamReader stream)

Creates a Text from a StreamReader. Carriage return characters are removed, and the whole stream is read before returning.
stream: StreamReader to read text from.

Text(StreamReader stream, bool removeCR)

Creates a Text from a StreamReader. The whole stream is read before returning.
stream: StreamReader to read text from.
removeCR: bool value to indicate whether carriage return characters should be removed.

Text Method AddMark

Mark AddMark(Mark mark)

Creates a new Mark in the Text using the passed Mark value.
mark: Mark value representing the initial position of the new Mark.

Mark AddMark()

Creates a new Mark in the Text at the current cursor position.

Text Method AddRange

Range AddRange(Mark mark1, Mark mark2)

Creates a new Range in the Text using start and end Mark values.
mark1: Mark value representing the start of the new Range.
mark2: Mark value representing the end of the new Range.

Range AddRange(Range range)

Creates a new Range in the Text using the passed Range value.
range: Range value representing the initial span of the new Range.

Range AddRange(long offset)

Creates a new Range in the Text using an offset from the current cursor position.
offset: Offset (positive or negative) from the current cursor position.
The Range stretches between the current cursor position and the offset position.

Range AddRange()

Creates an empty new Range at the start of the Text.

Text Method Cut

string Cut(int chars)

Deletes text forwards or backwards from the current cursor position, returning the deleted text as a string.
chars: Number of characters to delete, negative for deletion backwards, and positive for deletion forwards.

Text Method Delete

Text Delete(long chars)

Deletes text forwards or backwards from the current cursor position. The Text is returned to allow chaining of calls.
chars: Number of characters to delete, negative for deletion backwards, and positive for deletion forwards.

Text Method Dispose

void Dispose()

Releases resources used by the Text.

Text Method GetHashCode

int GetHashCode()

Override for default GetHashCode() - returns a unique index.

Text Method Insert

Text Insert(string text)

Inserts text at the current cursor position in the Text. The cursor position is moved to the end of the inserted text, and the Text is returned to allow chaining of calls. Other Marks originally at the cursor position are not moved.
text: string value containing the text for insertion.

Text Insert(object source)

Inserts text at the current cursor position in the Text. The cursor position is moved to the end of the inserted text, and the Text is returned to allow chaining of calls. Other Marks originally at the cursor position are not moved.
source: object whose ToString method will define the text for insertion.

Text Method Line

Range Line()

Returns a Range containing the line (excluding line feeds) which the current cursor is in. Do not assign this value to a Range variable - it will become invalidated if the text changes. Use Text.AddRange() or Range.MoveTo() instead.

Text Method LineEnd

Mark LineEnd()

Returns a Mark at the end of the current line in the Text. Do not assign this value to a Mark variable - it will become invalidated if the text changes. Use Text.AddMark() or Mark.MoveTo() instead.

Text Method LineStart

Mark LineStart()

Returns a Mark at the start of the current line in the Text. Do not assign this value to a Mark variable - it will become invalidated if the text changes. Use Text.AddMark() or Mark.MoveTo() instead.

Text Method MoveTo

Text MoveTo(long offset)

Moves the current cursor position forwards or backwards. No exception is raised if the start or end of the text is reached. The Text is returned to allow chaining of calls.
offset: Number of characters to move, positive or negative.

Text MoveTo(Mark mark)

Moves the current cursor position to a passed Mark position. The Text is returned to allow chaining of calls.
mark: Mark position to move to.

Text Method NextLine

bool NextLine()

Moves the current cursor position to the beginning of the next line if there is one, and returns true, or leaves the cursor unmoved and returns false.

Text Method PreviousLine

bool PreviousLine()

Moves the current cursor position to the beginning of the previous line if there is one, and returns true, or leaves the cursor unmoved and returns false.

Text Method Remove

Text Remove(Mark mark)

Removes a Mark from the list of Marks registered with the Text. The Mark is invalidated. The Text is returned to allow chaining of calls.
mark: Mark to be removed from the Text.

Text Remove(Range range)

Removes a Range from the list of Ranges registered with the Text. The Range is invalidated. The Text is returned to allow chaining of calls.
range: Range to be removed from the Text.

Text Method Search

bool Search(Pattern pattern, SearchType searchType)

Searches from the current cursor to find a match for the Pattern, and moves the current cursor as necessary if a match is found.
pattern: A Pattern to match.
searchType: A SearchType specifying whether the search is forwards from the current cursor, backwards from the cursor, or anchored at the cursor.

bool Search(Pattern pattern)

Searches forwards from the current cursor to find a match for the Pattern, and moves the current cursor if a match is found.
pattern: A Pattern to match.

Text Method ToString

string ToString()

Converts the Text contents to a string with newline characters at line ends.

Text Method Write

void Write()

Writes the Text to a text file using the stored filename and encoding, calling WriteLine at newline characters by default. If carriage returns were not removed from input data, no end-of-line processing is done, and CR/LF sequences are expected within the Text.

void Write(string filename)

Writes the Text to a text file using the passed filename and ASCII encoding, calling WriteLine at newline characters by default. If carriage returns were not removed from input data, no end-of-line processing is done, and CR/LF sequences are expected within the Text.
filename: string value containing the text file path.

void Write(string filename, Encoding encoding)

Writes the Text to a text file using the passed filename and encoding, calling WriteLine at newline characters by default. If carriage returns were not removed from input data, no end-of-line processing is done, and CR/LF sequences are expected within the Text.
filename: string value containing the text file path.
encoding: Encoding value or null for default ASCII.

void Write(StreamWriter stream)

Writes the Text using a StreamWriter, calling WriteLine at newline characters by default. If carriage returns were not removed from input data, no end-of-line processing is done, and CR/LF sequences are expected within the Text.
stream: StreamWriter to be written to.

Text Property All

Range All

Range containing the whole contents of the Text. Do not assign this value to a Range variable - it will become invalidated if the text changes. Use Text.AddRange() or Range.MoveTo() instead.

Text Property Cursor

Mark Cursor

Current cursor position in the Text. Do not assign this value to a Mark variable - it will become invalidated if the text changes. Use Text.AddMark() or Mark.MoveTo() instead.

Text Property End

Mark End

Position at the end of the Text. Do not assign this value to a Mark variable - it will become invalidated if the text changes. Use Text.AddMark() or Mark.MoveTo() instead.

Text Property Length

long Length

Length of the text in the Text including newline characters. If data is loaded from a file in the background or on demand with carriage returns removed, the whole file will be read before a value is returned.

Text Property Start

Mark Start

Position at the start of the Text. Do not assign this value to a Mark variable - it will become invalidated if the text changes. Use Text.AddMark() or Mark.MoveTo() instead.

Text Property this[long index]

char this[long index]

Char at the given index in the Text.
index: Offset from the start of the Text.

Class Mark: Mark Constructors, Mark Methods, Mark Operators, Mark Properties, Mark Events

Defines a bookmark in a Text which moves with the text.

Mark Method Cut

string Cut(int chars)

Deletes text forwards or backwards from the Mark position, returning the deleted text as a string.
chars: Number of characters to delete, negative for deletion backwards, and positive for deletion forwards.

Mark Method Delete

Mark Delete(long chars)

Deletes text forwards or backwards from the Mark position. The Mark is returned to allow chaining of calls.
chars: Number of characters to delete, negative for deletion backwards, and positive for deletion forwards.

Mark Method GetHashCode

int GetHashCode()

Override for default GetHashCode() - returns an index which is unique for Marks created with Text.AddMark(). An unregistered Mark returns a value of zero or -1 if it has been invalidated by a change to the text.

Mark Method Insert

Mark Insert(string insert)

Inserts text at the Mark position. The Mark is moved to the end of the inserted text, and the Mark is returned to allow chaining of calls. Other Marks originally at the same position are not moved.
insert: string value containing the text for insertion.

Mark Insert(object source)

Inserts text at the Mark position. The Mark is moved to the end of the inserted text, and the Mark is returned to allow chaining of calls. Other Marks originally at the same position are not moved.
source: object whose ToString method will define the text for insertion.

Mark Method Line

Range Line()

Returns an unregistered Range containing the line (excluding newline characters) which the Mark is in. Do not assign this value to a Range variable - it will become invalidated if the text changes. Use Text.AddRange() or Range.MoveTo() instead.

Mark Method LineEnd

Mark LineEnd()

Returns an unregistered Mark located at the end of the line which the Mark is in. Do not assign this value to a Mark variable - it will become invalidated if the text changes. Use Text.AddMark() or Mark.MoveTo() instead.

Mark Method LineStart

Mark LineStart()

Returns an unregistered Mark located at the start of the line which the Mark is in. Do not assign this value to a Mark variable - it will become invalidated if the text changes. Use Text.AddMark() or Mark.MoveTo() instead.

Mark Method MoveTo

Mark MoveTo(long offset)

Moves the Mark forwards or backwards in the Text. The Mark is returned to allow chaining of calls.
offset: Number of characters, positive or negative, to move.

Mark MoveTo(Mark mark)

Moves the Mark to the position of a given mark value. The Mark is returned to allow chaining of calls.
mark: Mark value defining the new position.

Mark MoveTo()

Moves the Mark to the current cursor position in its Text. The Mark is returned to allow chaining of calls.

Mark Method Offset

long Offset(Mark mark)

Returns the offset of this Mark from the passed Mark (positive if this Mark is after the passed Mark).
mark: Mark value to compare this Mark to.

long Offset()

Returns the offset of this Mark from the start of its Text.

Mark Method Remove

void Remove()

Removes the Mark from the list of Marks registered with its Text. The Mark will be invalidated by subsequent changes to the text.

Mark Method SameAs

bool SameAs(Mark mark)

Returns true if the passed Mark is at the same location as this Mark.
mark: Mark to compare against.

Mark Method Search

bool Search(Pattern pattern)

Determines whether the text immediately following the Mark is a match for the Pattern.
pattern: A Pattern to match.

Mark Method SearchAgain

bool SearchAgain()

After a successful call to Search, determines whether there is another way of matching the same Pattern at the same place.

Mark Method ToString

string ToString()

Returns a string showing up to four characters either side of the Mark.

string ToString(int chars)

Returns a string showing characters either side of the Mark.
chars: Number of characters to show on either side.

Mark Method Within

bool Within(Range range)

Returns true if this Mark is at the start of, or within, but not at the end of the passed Range.
range: Range which Mark may lie within.

Mark Operator -

static long operator -(Mark mark1, Mark mark2)

Returns the offset of the first Mark from the second Mark.
mark1: Mark value whose offset is returned.
mark2: Mark value used as the base for the offset.

static Mark operator -(Mark mark, long offset)

Returns an unregistered Mark whose position is an offset from the Mark. Do not assign this value to a Mark variable - it will become invalidated if the text changes. Use Text.AddMark() or Mark.MoveTo() instead.
mark: Mark to start from.
offset: Number of characters, positive or negative, of offset.

Mark Operator +

static Mark operator +(Mark mark, long offset)

Returns an unregistered Mark whose position is an offset from the Mark. Do not assign this value to a Mark variable - it will become invalidated if the text changes. Use Text.AddMark() or Mark.MoveTo() instead.
mark: Mark to start from.
offset: Number of characters, positive or negative, of offset.

static Range operator +(Mark mark1, Mark mark2)

Returns an unregistered Range between the two Marks. Do not assign this value to a Range variable - it will become invalidated if the text changes. Use Text.AddRange() or Range.MoveTo() instead.
mark1: Mark at the start of the Range.
mark2: Mark at the end of the Range.

Mark Property Text

Text Text

Text which the Mark is in.

Class Range: Range Constructors, Range Methods, Range Operators, Range Properties, Range Events

Defines a span between two Marks in a Text which move with the text.

Range Method Contains

bool Contains(Mark mark)

Returns true if this Range contains the passed Mark at the start or in the middle but not at the end position.
mark: Mark which may lie within the Range.

Range Method Cut

string Cut()

Deletes the text in the Range, returning the original contents. All registered Marks in the Range move to the start (and end) of the Range.

Range Method Delete

Range Delete()

Deletes the text in the Range. All registered Marks in the Range move to the start (and end) of the Range. The Range is returned to allow chaining of calls.

Range Method GetHashCode

int GetHashCode()

Override for default GetHashCode() - returns an index which is unique for Ranges created with Text.AddRange(). An unregistered Range returns a value of zero, or -1 if the Range has been invalidated by a change to the text.

Range Method Length

long Length()

Returns the length of the Range, including newline characters.

Range Method MoveTo

Range MoveTo(Range range)

Moves the Range to the span of a given Range value. The Range is returned to allow chaining of calls.
range: Range value defining the new span.

Range MoveTo(Mark mark1, Mark mark2)

Moves the Range to lie between the given Marks. The Range is returned to allow chaining of calls.
mark1: Mark value defining the start of the new span.
mark2: Mark value defining the end of the new span.

Range Method Remove

void Remove()

Removes the Range from the list of Ranges registered with its Text. The Range will be invalidated by subsequent changes to the text.

Range Method Replace

Range Replace(string text)

Replaces the text in the Range with a given string. All registered Marks initially in the Range end up at the start of the Range. The Range is returned to allow chaining of calls.
text: string value containing the text for insertion.

Range Replace(object source)

Replaces the text in the Range. All registered Marks initially in the Range end up at the start of the Range. The Range is returned to allow chaining of calls.
source: object whose ToString method will define the text for insertion.

Range Method SameAs

bool SameAs(Range range)

Returns true if the passed Range has the same extent as this Range.
range: Range to compare against.

Range Method Search

bool Search(Pattern pattern, SearchType searchType)

Searches from one end of the Range to find a match for the Pattern, and moves the current cursor if a match is found.
pattern: A Pattern to match.
searchType: A SearchType specifying whether the search is forwards from the start of the Range, backwards from the end of the Range, or anchored at the start.

bool Search(Pattern pattern)

Searches forwards from the start of the Range to find a match for the Pattern, and moves the current cursor if a match is found.
pattern: A Pattern to match.

Range Method ToString

string ToString()

Converts the Range contents to a string with newline characters at line ends.

Range Property End

Mark End

Position at the end of the Range. Do not assign this value to a Mark variable - it will become invalidated if the text changes. Use Text.AddMark() or Mark.MoveTo() instead.

Range Property Start

Mark Start

Position at the start of the Range. Do not assign this value to a Mark variable - it will become invalidated if the text changes. Use Text.AddMark() or Mark.MoveTo() instead.

Range Property Text

Text Text

Text which the Range is in.

Range Property this[long index]

char this[long index]

Char at the given index in the Range.
index: int offset from the start of the Range.

Class Pattern: Pattern Constructors, Pattern Methods, Pattern Operators, Pattern Properties, Pattern Events

Defines a hierarchical structure for complex recursive pattern-matching.

Pattern Method And

static Pattern And(params Pattern[] patterns)

Creates a Pattern which matches a series of Patterns one after the other. The sequence of Patterns may be recursed over, so that if there is more than one way to match the first Pattern, then the subsequent Patterns may be visited more than once.
patterns: Two or more Patterns to be combined.

Pattern Method Any

static Pattern Any()

Creates a Pattern which matches any character including newline characters.

Pattern Method AnyBut

static Pattern AnyBut(string text, bool exact)

Creates a Pattern which matches any character not in the given text.
text: string to not match any character from.
exact: bool indicating whether case and diacritical marks should be respected.

static Pattern AnyBut(string text)

Creates a Pattern which matches any character not in the given text. Case and diacritical marks will be respected if the static Pattern property Exact is set to true.
text: string to not match any character from.

Pattern Method AnyOf

static Pattern AnyOf(string text, bool exact, PatternCount count)

Creates a Pattern which matches any character in the given text.
text: string to match a character from.
exact: bool indicating whether case and diacritical marks should be respected.
count: PatternCount to be set to the index of the matched character when the Pattern is last encountered.

static Pattern AnyOf(string text, bool exact)

Creates a Pattern which matches any character in the given text.
text: string to match a character from.
exact: bool indicating whether case and diacritical marks should be respected.

static Pattern AnyOf(string text, PatternCount count)

Creates a Pattern which matches any character in the given text. Case and diacritical marks will be respected if the static Pattern property Exact is set to true.
text: string to match a character from.
count: PatternCount to be set to the index of the matched character when the Pattern is last encountered.

static Pattern AnyOf(string text)

Creates a Pattern which matches any character in the given text. Case and diacritical marks will be respected if the static Pattern property Exact is set to true.
text: string to match a character from.

Pattern Method BeginLine

static Pattern BeginLine()

Creates a Pattern which matches the beginning of a line (at the start of the Text or following a newline character).

Pattern Method BeginWord

static Pattern BeginWord()

Creates a Pattern which matches the beginning of a word (between a non-word character and a word character, where a word character is a letter, digit or underscore).

Pattern Method BeginWord7

static Pattern BeginWord7()

Creates a Pattern which matches the beginning of a 7-bit (Basic Latin) word (between a non-word character and a word character, where a word character is a Basic Latin letter, digit or underscore).

Pattern Method Black

static Pattern Black()

Creates a Pattern which matches any printing character as determined by Char.IsWhiteSpace() and Char.IsControl().

Pattern Method Black7

static Pattern Black7()

Creates a Pattern which matches a 7-bit (Basic Latin) printing character.

Pattern Method Control

static Pattern Control()

Creates a Pattern which matches any control character as determined by Char.IsControl().

Pattern Method Control7

static Pattern Control7()

Creates a Pattern which matches a 7-bit (Basic Latin) control character.

Pattern Method Delegate

static Pattern Delegate(PatternDelegate del)

Creates a Pattern which matches according to the return from a PatternDelegate. The PatternDelegate function is passed a Mark containing the current search cursor position and must return a bool value indicating a match. If the return value is true, the second Mark argument must be set to the end of the matched span.
del: PatternDelegate to be called when the Pattern is reached.

static Pattern Delegate(PatternDelegate del, PatternCount count)

Creates a Pattern which matches according to the return from a PatternDelegate. The PatternDelegate function is passed a Mark containing the current search cursor position and must return a bool value indicating a match. If the return value is true, the second Mark argument must be set to the end of the matched span. The delegate may also set an integer value.
del: PatternDelegate to be called when the Pattern is reached.
count: PatternCount to be set to the returned integer value if a match was found.

Pattern Method DelimitedString

static Pattern DelimitedString(Pattern start, Pattern end)

Creates a Pattern which matches a delimited string, starting when one delimiter pattern starts, and ending at the end of another delimiter.
start: Pattern which matches the start of the delimited string.
end: Pattern which matches the end of the delimited string.

static Pattern DelimitedString(Pattern start, Pattern end, Pattern escape)

Creates a Pattern which matches a delimited string, starting when one delimiter pattern starts, and ending at the end of another delimiter, but ignoring end delimiters which are escaped.
start: Pattern which matches the start of the delimited string.
end: Pattern which matches the end of the delimited string.
escape: Pattern which can be consumed without terminating the string.

Pattern Method Digit

static Pattern Digit()

Creates a Pattern which matches any digit as determined by Char.IsDigit().

Pattern Method Digit7

static Pattern Digit7()

Creates a Pattern which matches a 7-bit (Basic Latin) digit.

Pattern Method EndLine

static Pattern EndLine()

Creates a Pattern which matches the end of a line (preceding a newline character or at the end of the Text).

Pattern Method EndWord

static Pattern EndWord()

Creates a Pattern which matches the end of a word (between a word character and a non-word character, where a word character is a letter, digit or underscore).

Pattern Method EndWord7

static Pattern EndWord7()

Creates a Pattern which matches the end of a 7-bit (Basic Latin) word (between a word character and a non-word character, where a word character is a Basic Latin letter, digit or underscore).

Pattern Method Equals

static Pattern Equals(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern Equals(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

Pattern Method False

static Pattern False()

Creates a Pattern which always fails to match, used for example to terminate an unlimited Repeat.

Pattern Method Float

static Pattern Float()

Creates a Pattern which matches a float value: {+|-}(9...{.{9...}}|.9...){(e|E){+|-}9...}

Pattern Method Gap

static Pattern Gap()

Creates a Pattern which greedily matches a non-empty sequence of whitespace characters as defined by Char.IsWhiteSpace(), but not including newline.

Pattern Method Gap7

static Pattern Gap7()

Creates a Pattern which greedily matches a non-empty sequence of 7-bit (Basic Latin) whitespace characters, but not including newline.

Pattern Method GetHashCode

int GetHashCode()

Returns a unique ID for the Pattern.

Pattern Method Greater

static Pattern Greater(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern Greater(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

Pattern Method GreaterEqual

static Pattern GreaterEqual(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern GreaterEqual(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

Pattern Method Int

static Pattern Int()

Creates a Pattern which matches an integer value: {+|-}9... .

static Pattern Int(PatternCount count)

Creates a Pattern which matches an integer value: {+|-}9... and returns the value in a PatternCount.
count: PatternCount which will be set to the value of the integer if the match is successful.

Pattern Method Lacuna

static Pattern Lacuna()

Creates a Pattern which greedily matches a non-empty sequence of whitespace characters as defined by Char.IsWhiteSpace().

Pattern Method Lacuna7

static Pattern Lacuna7()

Creates a Pattern which greedily matches a non-empty sequence of 7-bit (Basic Latin) whitespace characters.

Pattern Method Less

static Pattern Less(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern Less(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

Pattern Method LessEqual

static Pattern LessEqual(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern LessEqual(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

Pattern Method Letter

static Pattern Letter()

Creates a Pattern which matches any letter as determined by Char.IsLetter().

Pattern Method Letter7

static Pattern Letter7()

Creates a Pattern which matches a 7-bit (Basic Latin) letter.

Pattern Method Lower

static Pattern Lower()

Creates a Pattern which matches any lower-case letter as determined by Char.IsLower().

Pattern Method Lower7

static Pattern Lower7()

Creates a Pattern which matches a 7-bit (Basic Latin) lower case letter.

Pattern Method Minus

static Pattern Minus(PatternCount count, int value)

Creates a Pattern which always matches, and decrements the value of a PatternCount. Note that the decrement occurs even if the current recursive branch of the search, or the whole search, fails.
count: PatternCount whose value is decremented when the Pattern is reached.
value: int value to decrement the PatternCount by.

static Pattern Minus(PatternCount count)

Creates a Pattern which always matches, and decrements the value of a PatternCount. Note that the decrement occurs even if the current recursive branch of the search, or the whole search, fails.
count: PatternCount whose value is decremented by 1 when the Pattern is reached.

static Pattern Minus(PatternCount count1, PatternCount count2)

Creates a Pattern which always matches, and decrements the value of a PatternCount. Note that the decrement occurs even if the current recursive branch of the search, or the whole search, fails.
count1: PatternCount whose value is decremented when the Pattern is reached.
count2: PatternCount whose current value is used.

Pattern Method Name

static Pattern Name()

Creates a Pattern which matches a name - letters, digits and underscores surrounded by non-word characters, starting with a letter or underscore.

Pattern Method Name7

static Pattern Name7()

Creates a Pattern which matches a 7-bit (Basic Latin) name - letters, digits and underscores surrounded by non-word characters, starting with a letter or underscore.

Pattern Method Not

static Pattern Not(Pattern pattern)

Creates a Pattern which finds a match only if the given Pattern does not match. The search cursor is not moved.
pattern: Pattern to not match.

Pattern Method NotEquals

static Pattern NotEquals(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern NotEquals(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

Pattern Method Or

static Pattern Or(params Pattern[] patterns)

Creates a Pattern which finds a match among a set of alternative Patterns at the current search cursor. The first Pattern is tested first, then the second is tested only if the first does not match. If the first Pattern is matched but a following Pattern fails to match, the search will recurse, and the second Pattern will be tested.
patterns: Two or more alternative Patterns to be tested.

static Pattern Or(PatternCount count, params Pattern[] patterns)

Creates a Pattern which finds a match among a set of alternative Patterns at the current search cursor. The first Pattern is tested first, then the second is tested only if the first does not match. If the first Pattern is matched but a following Pattern fails to match, the search will recurse, and the second Pattern will be tested.
count: PatternCount to be set to the index of the Pattern which was matched.
patterns: Two or more alternative Patterns to be tested.

Pattern Method Plus

static Pattern Plus(PatternCount count, int value)

Creates a Pattern which always matches, and increments the value of a PatternCount. Note that the increment occurs even if the current recursive branch of the search, or the whole search, fails.
count: PatternCount whose value is incremented when the Pattern is reached.
value: int value to increment the PatternCount by.

static Pattern Plus(PatternCount count)

Creates a Pattern which always matches, and increments the value of a PatternCount. Note that the increment occurs even if the current recursive branch of the search, or the whole search, fails.
count: PatternCount whose value is incremented by 1 when the Pattern is reached.

static Pattern Plus(PatternCount count1, PatternCount count2)

Creates a Pattern which always matches, and increments the value of a PatternCount. Note that the increment occurs even if the current recursive branch of the search, or the whole search, fails.
count1: PatternCount whose value is incremented when the Pattern is reached.
count2: PatternCount whose current value is used.

Pattern Method Punctuation

static Pattern Punctuation()

Creates a Pattern which matches any punctuation character as determined by Char.IsPunctuation().

Pattern Method Punctuation7

static Pattern Punctuation7()

Creates a Pattern which matches a 7-bit (Basic Latin) punctuation character.

Pattern Method Repeat

static Pattern Repeat(Pattern pattern, int minimum, int maximum)

Creates a Pattern which matches multiple occurrences of a Pattern. If the minimum count is less than the maximum, the search will recurse over number of matches. The recursion moves forwards only, so earlier matches of the pattern are not recursed over.
pattern: Pattern to be matched repeatedly.
minimum: Minimum number of times to match.
maximum: Maximum number of times to match or less than minimum to match as many times as possible.

static Pattern Repeat(Pattern pattern, int minimum, int maximum, PatternCount count)

Creates a Pattern which matches multiple occurrences of a Pattern and returns the actual number of matches. If the minimum count is less than the maximum, the search will recurse over number of matches. The recursion moves forwards only, so earlier matches of the pattern are not recursed over.
pattern: Pattern to be matched repeatedly.
minimum: Minimum number of times to match.
maximum: Maximum number of times to match or less than minimum to match as many times as possible.
count: PatternCount to be set to the actual number of times the pattern was matched when it was last encountered.

Pattern Method Same

static Pattern Same(Range range, bool exact)

Creates a Pattern which matches against the text in a given Range, for example set by the Save Pattern.
range: Range to compare against.
exact: bool indicating whether case and diacritical marks should be respected.

static Pattern Same(Range range)

Creates a Pattern which matches against the text in a given Range, for example set by the Save Pattern. Case and diacritical marks will be respected if the static Pattern property Exact is set to true.
range: Range to compare against.

Pattern Method Save

static Pattern Save(Pattern pattern, Range range)

Creates a Pattern which saves the result of a successful match into a Range.
pattern: Pattern which must match.
range: Range to hold the span of the match.

Pattern Method Set

static Pattern Set(PatternCount count, int value)

Creates a Pattern which always matches, and sets the value of a PatternCount.
count: PatternCount whose value is set when the Pattern is reached.
value: int value to set the PatternCount to.

static Pattern Set(PatternCount count1, PatternCount count2)

Creates a Pattern which always matches, and sets the value of a PatternCount.
count1: PatternCount whose value is set when the Pattern is reached.
count2: PatternCount whose current value is used.

Pattern Method Span

static Pattern Span(char lower, char upper)

Creates a Pattern which matches any character lying between (and including) the two given chars in Unicode sort order.
lower: char defining the lower end of the span.
upper: char defining the upper end of the span.

Pattern Method Symbol

static Pattern Symbol()

Creates a Pattern which matches any symbol character as determined by Char.IsSymbol().

Pattern Method Symbol7

static Pattern Symbol7()

Creates a Pattern which matches a 7-bit (Basic Latin) symbol character.

Pattern Method Text

static Pattern Text(string text, bool exact)

Creates a Pattern which matches given text.
text: string to match.
exact: bool indicating whether case and diacritical marks should be respected.

static Pattern Text(string text)

Creates a Pattern which matches given text. Case and diacritical marks will be respected if the static Pattern property Exact is set to true.
text: string to match.

static Pattern Text(char text)

Creates a Pattern which matches a given character.
text: char to match. The match is exact

Pattern Method ToString

string ToString()

Returns a string describing the Pattern.

Pattern Method True

static Pattern True()

Creates a Pattern which always matches, for example for use with Or to match an optional element.

Pattern Method Upper

static Pattern Upper()

Creates a Pattern which matches any upper-case letter as determined by Char.IsUpper().

Pattern Method Upper7

static Pattern Upper7()

Creates a Pattern which matches a 7-bit (Basic Latin) upper case letter.

Pattern Method White

static Pattern White()

Creates a Pattern which matches any whitespace character as determined by Char.IsWhiteSpace().

Pattern Method White7

static Pattern White7()

Creates a Pattern which matches a 7-bit (Basic Latin) whitespace character.

Pattern Method Word

static Pattern Word()

Creates a Pattern which matches a word - letters, digits and underscores surrounded by non-word characters.

Pattern Method Word7

static Pattern Word7()

Creates a Pattern which matches a 7-bit (Basic Latin) word - letters, digits and underscores surrounded by non-word characters.

Pattern Operator %

static Pattern operator %(Pattern pattern, Range range)

Creates a Pattern which saves the result of a successful match into a Range.
pattern: Pattern which must match.
range: Range to hold the span of the match.

Pattern Operator &

static Pattern operator &(Pattern pattern1, Pattern pattern2)

Creates a Pattern which matches one Pattern followed by another. The sequence of Patterns may be recursed over, so that if there is more than one way to match the first Pattern, then the subsequent Patterns may be visited more than once.
pattern1: First Pattern to be matched.
pattern2: Subsequent Pattern to be matched.

Pattern Operator *

static Pattern operator *(Pattern pattern, int repeat)

Creates a Pattern which matches multiple occurrences of a Pattern.
pattern: Pattern to repeat.
repeat: Exact number of times to match, or negative to match as many times as possible (in which case the search always returns true).

Pattern Operator |

static Pattern operator |(Pattern pattern1, Pattern pattern2)

Creates a Pattern which finds a match for either of two Patterns at the current search cursor. The first Pattern is tested first, then the second is tested only if the first does not match. If the first Pattern is matched but a following Pattern fails to match, the search will recurse, and the second Pattern will be tested.
pattern1: First Pattern to be tested.
pattern2: Second Pattern to be tested if the first Pattern fails to match.

Pattern Operator ~

static Pattern operator ~(Pattern pattern)

Creates a Pattern which finds a match only if the given Pattern does not match. The search cursor is not moved.
pattern: Pattern to not match.

Pattern Operator Pattern

static implicit operator Pattern(bool flag)

Creates a Pattern which always matches or fails to match according to the current value of the argument.
flag: bool value indicating whether to match or not to match.

static implicit operator Pattern(string text)

Creates a Pattern which matches given text. Case and diacritical marks will be respected if the static Pattern property Exact is set to true.
text: string to match.

static implicit operator Pattern(char text)

Creates a Pattern which matches a given character.
text: char to match. The match is exact

Pattern Property Exact

static bool Exact

Specifies a default value for exact matching applying to any new Pattern when the exact argument is not specified in the constructor.

Pattern Property this[int minimum, int maximum]

Pattern this[int minimum, int maximum]

Creates a Pattern which matches multiple occurrences of a Pattern. If the minimum count is less than the maximum, the search will recurse over number of matches. The recursion moves forwards only, so earlier matches of the pattern are not recursed over.
minimum: Minimum number of times to match.
maximum: Maximum number of times to match or less than minimum to match as many times as possible.

Class PatternCount: PatternCount Constructors, PatternCount Methods, PatternCount Operators, PatternCount Properties, PatternCount Events

Lightweight class used to pass and return integer count and flag values for complex searches.

PatternCount Constructors

PatternCount(int value)

Creates a PatternCount with an initial value.
value: Initial value for the PatternCount.

PatternCount()

Creates a PatternCount with an initial value of zero.

PatternCount Method GetHashCode

int GetHashCode()

Returns a unique ID for the PatternCount.

PatternCount Method ToString

string ToString()

Returns the current value of the PatternCount as a string.

PatternCount Operator !=

static Pattern operator !=(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern operator !=(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

PatternCount Operator -

static Pattern operator -(PatternCount count, int value)

Creates a Pattern which always matches, and decrements the value of a PatternCount.
count: PatternCount whose value is decremented when the Pattern is reached.
value: int value to decrement the PatternCount by.

static Pattern operator -(PatternCount count1, PatternCount count2)

Creates a Pattern which always matches, and decrements the value of one PatternCount by another.
count1: PatternCount whose value is decremented when the Pattern is reached.
count2: PatternCount whose value is used.

PatternCount Operator ^

static Pattern operator ^(PatternCount count, int value)

Creates a Pattern which always matches, and sets the value of a PatternCount.
count: PatternCount whose value is set when the Pattern is reached.
value: int value to set the PatternCount to.

static Pattern operator ^(PatternCount count1, PatternCount count2)

Creates a Pattern which always matches, and sets the value of a PatternCount.
count1: PatternCount whose value is set when the Pattern is reached.
count2: PatternCount whose value is used.

PatternCount Operator +

static Pattern operator +(PatternCount count, int value)

Creates a Pattern which always matches, and increments the value of a PatternCount.
count: PatternCount whose value is incremented when the Pattern is reached.
value: int value to increment the PatternCount by.

static Pattern operator +(PatternCount count1, PatternCount count2)

Creates a Pattern which always matches, and increments the value of one PatternCount by the value of another.
count1: PatternCount whose value is incremented when the Pattern is reached.
count2: PatternCount whose value is used.

PatternCount Operator <

static Pattern operator <(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern operator <(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

PatternCount Operator <=

static Pattern operator <=(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern operator <=(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

PatternCount Operator ==

static Pattern operator ==(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern operator ==(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

PatternCount Operator >

static Pattern operator >(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern operator >(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

PatternCount Operator >=

static Pattern operator >=(PatternCount count, int value)

Creates a Pattern which matches according to the value of a PatternCount.
count: PatternCount whose value is tested when the Pattern is reached.
value: int value to compare the PatternCount to.

static Pattern operator >=(PatternCount count1, PatternCount count2)

Creates a Pattern which matches according to the comparitive values of two PatternCounts.
count1: PatternCount whose value is tested when the Pattern is reached.
count2: PatternCount whose value is compared.

PatternCount Property Value

int Value

Current value held by the PatternCount.

Class Box: Box Constructors, Box Methods, Box Operators, Box Properties, Box Events

Defines a rich text box for use with a Text, inheriting from System.Windows.Forms.RichTextBox. Box and Text can change independently via code or user interaction; events are raised when either happens. When the two are synchronised, the user selection in the Box can be mapped into a Range, and a Range can be used to make a selection in the Box. The Box is ReadOnly by default and uses default font Consolas 9pt.

Box Constructors

Box()

Creates a rich text box to be associated with a Range.

Box Method LoadRange

void LoadRange(Range range)

Replaces the contents of the rich text box with the contents of the Range.
range: Range from which to fill the text box.

void LoadRange()

Refreshes the contents of the rich text box with the contents of its Range. All formatting is lost.

Box Method Save

void Save()

Saves the contents of the rich text box into its source Range.

Box Method SelectedRange

Range SelectedRange()

Maps the text selected by the user into an unregistered Range in the source Text. Do not assign this value to a Range variable - it will become invalidated if the text changes. Use Text.AddRange() or Range.MoveTo() instead.

Box Method SelectRange

void SelectRange(Range range)

Selects the text which is shared by the rich text box and the passed Range.
range: Range defining the new selection.

Box Property Dirty

bool Dirty

True if the contents of the Box may no longer match the contents of the Range.

Box Property DirtyBox

bool DirtyBox

True if the contents of the Box have changed since the last Save or LoadRange.

Box Property DirtyRange

bool DirtyRange

True if the contents of the Range have changed since the last Save or LoadRange.

Box Property Range

Range Range

Gets an unregistered Range matching the source Range for the Box or null.

Box Event BoxDirty

event EventHandler BoxDirty

Occurs when the plain text in the Box is first changed by the user or calling code.

Box Event RangeDirty

event EventHandler RangeDirty

Occurs when the source Range for the Box is first changed in code.

Delegates

Delegate PatternDelegate

delegate bool PatternDelegate(Mark start, Mark end, ref int count)

Type of delegate to be called during a search.
start: Mark passed in with the current search cursor position.
end: Mark that must be moved to the end of the matched text if the delegate returns True.
count: int that may be returned and used to set a PatternCount on a successful match, if one was defined when the Pattern was created.

Enums

DataLoad Enum DataLoad

enum DataLoad

Specifies the timing of data loading from a file when the Text is created.
Immediate: Loads all data before returning from the Text constructor (default).
Background: Returns immediately then loads all data in a background thread.
OnDemand: Returns immediately then loads data block-by-block as it is required. Requires the input stream to be seekable, with fixed-length encoding (UTF-16 is considered fixed length).

SearchType Enum SearchType

enum SearchType

Specifies the type and direction of a search.
Forwards: Search will move forwards through the Text until a match is found.
Backwards: Search will move backwards through the Text until a match is found.
Anchored: Search will test for a match only at one position in the Text.

Examples

Hello World

...
using TextEditorLibrary;
...
Text tHello = new Text();                       // Empty text buffer
tHello.Insert("worlf").Insert("!");             // Add some text (oops)
tHello.MoveTo(tHello.Start);                    // Cursor to the beginning
tHello.Insert("Hello ");                        // Add some more text
((tHello.End-2)+(tHello.End-1)).Replace("d");   // Define a Range from two offset Marks
                                                // and fix the typo
tHello.Start.Insert("\n");                      // Newlines at Marks
tHello.End.Insert("\n");
Console.Write(tHello);                          // What have we got?

Using Marks to Reverse the Lines in a File

Text tReverse = new Text("backwards.txt",null); // Text buffer filled from ASCII file,  
                                                // carriage returns stripped out
Mark mCopy = tReverse.AddMark(tReverse.End);    // Attach a Mark at the end
Mark mPaste = tReverse.AddMark();               // And one at the start
	
while (!mCopy.SameAs(mPaste))                   // Loop until the Marks collide
{
    mPaste.Insert(mCopy.Line()).Insert("\n");   // Note implicit ToString() on the Range 
                                                // mCopy.Line()
    mCopy.Line().Delete();                      // Clear the copied line
    mCopy.Delete(-1);                           // And remove the trailing newline
}

tReverse.Write();                               // Overwrite the original file, CR/LFs 
                                                // restored (uses WriteLine on newline)

Quickly Print the Last Three Lines from a Huge Unicode File

Note that on-demand load only reads where data is requested, so this code will probably only read 8192 bytes from the file. Leaving carriage returns in the file makes no difference in this case, but would improve performance if it was necessary to move in the file by a large fixed offset, or find the length of the Text.

using (Text tBig = new Text("huge.log", Encoding.Unicode, false, DataLoad.OnDemand))
                                                // Leave carriage returns, load on
                                                // demand, dispose when done
{
    tBig.MoveTo(tBig.End);
    tBig.PreviousLine();
    tBig.PreviousLine();
    Console.WriteLine(tBig.Cursor+tBig.End);    // And we're done
}

Remove Indents from Whole-line Comments Using Patterns

Text tCode = new Text("Pattern.cs", null);
Range rWhite = tCode.AddRange();                // Range for Pattern to report back to
Pattern pComment =
    Pattern.And(                                // Pattern to match a series of things:
        Pattern.BeginLine(),                    // Beginning of a line
        Pattern.Save(                           // Save the enclosed - like a regex group
                                                // but you also find out where it matches
            Pattern.Repeat(                     // Repeat the enclosed
                Pattern.White(),                // Match a whitespace character
                1, -1                           // At least once, and as many times as
                                                // possible (greedy match)
            ),
            rWhite                              // Range to save whitespace section into
        ),
        Pattern.Text("//")                      // Whole-line comment indicator
    );
	
// This does the same job, more compactly, using operators and implicit conversion:
// Pattern pComment = Pattern.BeginLine() & Pattern.White()[1,-1]%rWhite & "//";

// And as of release 1.2, this is another way to do it - and it matches only one line:
// Pattern pComment = Pattern.BeginLine() & Pattern.Gap()%rWhite & "//";

while (tCode.Search(pComment))                  // Loop until we can't find any matches
{
    // If we delete all the whitespace we lose preceding empty lines, so take care
    tCode.MoveTo(rWhite.End.LineStart());
    (tCode.Cursor+rWhite.End).Delete();
}

tCode.Write("Pattern2.cs");                     // Write it out again

Console.WriteLine(pComment);                    // Full structure of pattern for debug
Console.ReadLine();

Find Words with More Vowels than Consonants with PatternCounts

Note that to match a letter which is not a vowel, we must match "not a vowel" then "letter". The Not Pattern does not move the search cursor. Note also that if we matched "vowel" | "letter", we would have to worry about the search recursing and recognising a vowel as a letter. (Although in this case the greedy repeat prevents that.)

Text tCode = new Text("Pattern.cs", null);
PatternCount cVowel = new PatternCount();       // Count for vowels
PatternCount cConst = new PatternCount();       // Count for consonants
Pattern pVowel = Pattern.AnyOf("aeiouyAEIOUY"); // Any vowel
Pattern pConst = ~pVowel & Pattern.Letter7();   // Any consonant - Pattern.Not()
Pattern pOther = ~Pattern.Letter7() & Pattern.Word7();  // Avoid invalid recursion

Pattern pCount =
    Pattern.BeginWord7() &                      // Beginning of word (7-bit)
    (cVowel^0) & (cConst^0) &                   // Reset the counts
    Pattern.Repeat(
        (pVowel & cVowel+1) |                   // Count vowels
        (pConst & cConst+1) |                   // Count consonants
        pOther,                                 // Pass others
        1, -1) &                                // As many times as possible
    cVowel>cConst;                              // And then compare the scores

Range rWord = tCode.AddRange();                 // Range to capture the whole word
while (tCode.Search(pCount%rWord))              // Loop until we can't find any matches
{
    Console.WriteLine(rWord);
    tCode.MoveTo(rWord.End);                    // Or we will keep finding the same word
}
Console.ReadLine();

Find Palindromic Words with a Delegate Pattern

Note that we can safely perform a Search within a Search. (If you change the Text while searching, the results are likely to be confusing.) Note also the use of closure to allow communication from the calling code to the delegate (Pattern pWord) and vice versa (Range rWord).

Text tCode = new Text("dictionary.txt", null);
Range rWord = tCode.AddRange();
Pattern pWord = Pattern.Word()%rWord;           // We will do a Search in the delegate,
                                                // so define the Pattern just once
PatternDelegate del = delegate(Mark start, Mark end, ref int value)
{
    if (start.Search(pWord) && rWord.Length()>1)// See if we have a word - Search method
                                                // of a Mark is anchored
    {
        char[] reverse = rWord.ToString().ToCharArray();  // A bit inefficient?
        Array.Reverse(reverse);
        if (rWord.ToString() == new String(reverse))
        {
            end.MoveTo(rWord.End);              // On success, we must move the end Mark
            return true;
        }
    }
    return false;                               // On failure, the end Mark is ignored
};
Pattern pDel = Pattern.Delegate(del);           // Create the delegate Pattern

while (tCode.Search(pDel))                      // The Search will move to the word start
{
    Console.WriteLine(rWord.ToString());
    tCode.MoveTo(rWord.End);                    // So move to the end to avoid repeating
}
Console.ReadLine();

Find Paired Braces In C# Source Using DelimitedString

We have to step over strings and comments, and we have to count the number of open and close braces.

PatternCount count = new PatternCount();        // Count internal braces
Range range = text.AddRange();                  // From { to }

// Match a verbatim string consuming doubled quote
Pattern stringPatt1 = Pattern.DelimitedString(@"@""", @"""", @"""""");

// Match a regular string consuming escaped quote
Pattern stringPatt2 = Pattern.DelimitedString("\"", "\"", "\\\"");

// Match a delimited comment - no escapes
Pattern commentPatt1 = Pattern.DelimitedString("/*", "*/");

// Match a single-line comment - no escapes
Pattern commentPatt2 = Pattern.DelimitedString("//", "\n");

// Match any of those - NB the order is important because /* can appear in a string
Pattern skipPatt = Pattern.Or(
                        stringPatt1,
                        stringPatt2,
                        commentPatt1,
                        commentPatt2
                    );

// Consume strings, comments and anything except open brace to find the start
Pattern startPatt = Pattern.Repeat(skipPatt | Pattern.AnyBut("{"), 0, -1);

// Within the paired braces we also have to consume strings and comments, and also a
// close brace that is not at depth zero; meanwhile keep count of the depth
Pattern escapePatt = Pattern.Or(
                        skipPatt,
                        Pattern.And("}", count>0, count-1),
                        Pattern.And("{", count+1)
                     );

// Find the start, set the count, scan from open to close brace, consuming the escape
Pattern bracePatt = startPatt &
                    (count^0) &
                    Pattern.DelimitedString("{", "}", escapePatt) % range;

// Anchored search because otherwise we might try to start inside a comment etc.
text.Search(bracePatt,SearchType.Anchored);

Search and Display Found Text in a Box

This example assumes that a form Form1 has been created, and contains a Box box1 and button nextButton.

The user may be given multiple options, for example replacement of the found text with calculated alternatives.

Text text;
Range typeRange;
Range nameRange;
Pattern constPatt;

void Form1_Load(object sender, EventArgs e)
{
    text = new Text("Example.txt", null);
    typeRange = text.AddRange();
    nameRange = text.AddRange();
    constPatt = "const" & 
                Pattern.Gap7() &
                (Pattern.Word7() % typeRange) &
                Pattern.Gap7() &
                (Pattern.Word7() % nameRange);
    getNext();
}

void nextButton_Click(object sender, EventArgs e)
{
    getNext();
}

void getNext()
{
    if (text.Search(constPatt))
    {
        box1.LoadRange(text.Line());
        box1.SelectRange(typeRange);
        box1.SelectionBackColor = Color.LightGreen;
        box1.SelectRange(nameRange);
        box1.SelectionBackColor = Color.LightBlue;

        text.MoveTo(nameRange.End);
        box1.SelectRange(text.Cursor + text.Cursor);
    }
    else
    {
        box1.Clear();
        nextButton.Enabled = false;
        MessageBox.Show("No more matches found");
    }
}

Last edited Aug 12, 2014 at 11:16 PM by Bodgel, version 17