Javaв„ў EE 5 Tutorial, The (3rd Edition)
The class, with things rearranged a bit, looks like this now:
using System; using System.Collections; using System.Text; using System.Text.RegularExpressions; namespace Notepad { class TextModel { private static string[] newParagraph = { "<P></P>" }; private static string paragraphSkip = "<P>"; private static string[] newSection = {"<sect1><title></title>","</sect1>" }; private static string sectionSkip = "<sect1><title>"; private ArrayList lines; private int selectionStart; public TextModel() { lines = new ArrayList(); } public ArrayList Lines { get { return lines; } set { lines = value; } } public void SetLines(String[] lines) { this.Lines = new ArrayList(lines); } public String[] LinesArray() { String[] result = new String[lines.Count]; lines.CopyTo(result); return result; } public String TestText { get { StringBuilder b = new StringBuilder(); foreach(String s in lines) { b.Append(s); b.Append(System.Environment.NewLine); } b.Insert(SelectionStart,""); return b.ToString(); } } public int SelectionStart { get { return selectionStart; } set { selectionStart = value; } } public void Enter() { InsertParagraphTag(); } public void InsertParagraphTag() { InsertTags(newParagraph, paragraphSkip); } public void AltS() { InsertSectionTags(); } public void InsertSectionTags() { InsertTags(newSection, sectionSkip); } private void InsertTags(string[] tagsToInsert, string tagsPrecedingCursor) { int cursorLine = LineContainingCursor(); lines.InsertRange(cursorLine+1, tagsToInsert); selectionStart = NewSelectionStart(cursorLine + 1, tagsPrecedingCursor); } private int NewSelectionStart(int cursorLine, string tags) { return SumLineLengths(cursorLine) + tags.Length; } private int SumLineLengths(int cursorLine) { int length = 0; for (int i = 0; i < cursorLine; i++) length += ((String)lines[i]).Length + Environment.NewLine.Length; return length; } public void ChangeToH2() { ArrayList linesList = Lines; String oldLine = (String) linesList[LineContainingCursor()]; Regex r = new Regex("<(?<prefix>.*)>(?<body>.*)</(?<suffix>.*)>"); Match m = r.Match(oldLine); String newLine = "<H2>" + m.Groups["body"] + "</H2>"; linesList[LineContainingCursor()] = newLine; Lines = linesList; } private int LineContainingCursor() { if (lines.Count == 0) return -1; int length = 0; int lineNr = 0; int cr = Environment.NewLine.Length; foreach ( String s in lines) { if (length <= selectionStart && selectionStart < length+s.Length + cr ) break; length += s.Length + cr; lineNr++; } return lineNr; } } }
By the way, you may have noticed that ChangeToH2 and LineContainingCursor. They re part of an experiment that I haven t written up, in how to change a <P> tag to an <H2>. If I were entirely brave, I d delete the code and the test that uses it until I need it. But I m only human...
Категории