Javaв„ў EE 5 Tutorial, The (3rd Edition)

using System; using System.Collections; using System.Text; using System.Text.RegularExpressions; namespace Notepad { class TextModel { private ArrayList lines; private int selectionStart; public TextModel() { lines = new ArrayList(); } 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; } 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 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; } public void Enter() { InsertParagraphTag(); } public void InsertParagraphTag() { int cursorLine = LineContainingCursor(); lines.InsertRange(cursorLine+1, NewParagraph()); selectionStart = NewSelectionStart(cursorLine + 1, "<P>"); } public ArrayList NewParagraph() { ArrayList temp = new ArrayList(); temp.Add("<P></P>"); return temp; } public void AltS() { InsertSectionTags(); } public void InsertSectionTags() { int cursorLine = LineContainingCursor(); lines.InsertRange(cursorLine+1, NewSection()); selectionStart = NewSelectionStart(cursorLine + 1, "<sect1><title>"); } public ArrayList NewSection() { ArrayList temp = new ArrayList(); temp.Add("<sect1><title></title>"); temp.Add("</sect1>"); return temp; } 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; } } }

Категории