private void WriteElementClosingTag(string name, TextFormatMode formatMode, int level) { if (formatMode == TextFormatMode.Structured) { output.AppendLine(); WriteLineIndent(level); } output.AppendFormat("</{0}>", name); }
private void WriteComment(string content, TextFormatMode formatMode, int level) { if (formatMode == TextFormatMode.Structured) { output.AppendLine(); WriteLineIndent(level); } output.Append("<!--"); output.Append(content); output.Append("-->"); }
private void WriteText(string text, TextFormatMode formatMode, ref bool allowWhitespace, ref bool wordBegin) { switch (formatMode) { case TextFormatMode.Structured: throw new Exception("Unexpected text in the current context."); case TextFormatMode.Inline: WriteInlineText(text, ref allowWhitespace, ref wordBegin); break; case TextFormatMode.Preformatted: WriteXmlString(text, false); allowWhitespace = true; wordBegin = true; break; } }
/// <summary> /// 文本格式转换 /// </summary> /// <param name="input">输入文本</param> /// <param name="mode">模式</param> /// <returns></returns> public static string TextFormat(string input, TextFormatMode mode) { if (mode == TextFormatMode.Tranditional) { return(Strings.StrConv(input, VbStrConv.TraditionalChinese, 0)); } else if (mode == TextFormatMode.Simplified) { return(Strings.StrConv(input, VbStrConv.SimplifiedChinese, 0)); } else if (mode == TextFormatMode.Upper) { return(Strings.StrConv(input, VbStrConv.Uppercase, 0)); } else if (mode == TextFormatMode.Lower) { return(Strings.StrConv(input, VbStrConv.Lowercase, 0)); } else if (mode == TextFormatMode.InitialUpper) { return(Strings.StrConv(input, VbStrConv.ProperCase, 0)); } else if (mode == TextFormatMode.Pinyin) { StringBuilder sb = new StringBuilder(); foreach (char c in input) { if (Regex.IsMatch(c.ToString(), @"[\u4e00-\u9fbb]")) { ChineseChar ch = new ChineseChar(c); // 虽然有多音字的情况,但是并没有判断的能力,故默认选取第一个 string s = ch.Pinyins[0]; sb.Append(s.ToLower().Substring(0, s.Length - 1)); sb.Append(' '); } else { sb.Append(c); } } return(sb.ToString()); } return(input); }
public BookNodeInfo(string name, TextFormatMode formatMode) { Name = name; FormatMode = formatMode; Empty = true; }
private void ProcessSourceBook() { BookNodeStack nodeStack = new BookNodeStack(TextFormatMode.Structured); bool allowWhitespace = false; bool wordBegin = true; bool binaryElement = false; // Read the source book and write formatted content into a buffer. using (XmlTextReader reader = new XmlTextReader(sourceFileName)) { try { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.XmlDeclaration: sourceEncodingName = reader["encoding"]; targetEncoding = new EncodingData(Encoding.GetEncoding(sourceEncodingName)); break; case XmlNodeType.Element: string elementName = reader.Name; bool elementEmpty = reader.IsEmptyElement; WriteElementOpeningTag(elementName, nodeStack.FormatMode, nodeStack.Count); while (reader.MoveToNextAttribute()) { WriteElementAttribute(reader.Name, reader.Value); if (!elementEmpty && references != null && elementName == "a" && reader.Name == "l:href") { currentReference = FindReference(reader.Value); } } if (elementEmpty) { WriteEmptyElementCloser(); } else { WriteElementCloser(); } if (currentReference != null) { currentReferenceTextStart = output.Length; } allowWhitespace = allowWhitespace && nodeStack.FormatMode != TextFormatMode.Structured; wordBegin = wordBegin || nodeStack.FormatMode != TextFormatMode.Inline; if (!elementEmpty) { nodeStack.AddNode(elementName); } binaryElement = (elementName == "binary" && !elementEmpty); break; case XmlNodeType.EndElement: TextFormatMode insideFormatMode = nodeStack.FormatMode; nodeStack.DeleteNode(reader.Name); TextFormatMode outsideFormatMode = nodeStack.FormatMode; if (insideFormatMode == TextFormatMode.Inline && outsideFormatMode == TextFormatMode.Structured) { DeleteTrailingWhitespace(); } if (reader.Name == "a" && currentReference != null) { SetReferenceName(currentReference, output.ToString(currentReferenceTextStart, output.Length - currentReferenceTextStart)); currentReference = null; } WriteElementClosingTag(reader.Name, insideFormatMode, nodeStack.Count); allowWhitespace = allowWhitespace && nodeStack.FormatMode != TextFormatMode.Structured; wordBegin = wordBegin || nodeStack.FormatMode != TextFormatMode.Inline; binaryElement = false; break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (nodeStack.FormatMode != TextFormatMode.Structured) { WriteText(reader.Value, nodeStack.FormatMode, ref allowWhitespace, ref wordBegin); } break; case XmlNodeType.Text: if (binaryElement) { WriteBinary(reader.Value, nodeStack.Count); } else { WriteText(reader.Value, nodeStack.FormatMode, ref allowWhitespace, ref wordBegin); } break; case XmlNodeType.Comment: WriteComment(reader.Value, nodeStack.FormatMode, nodeStack.Count); allowWhitespace = true; wordBegin = true; break; } } } catch (Exception ex) { string message = string.Format(errXmlParseError, sourceFileName, reader.LineNumber, reader.LinePosition, ex.Message); throw new Exception(message, ex); } } }
public BookNodeStack(TextFormatMode defaultFormatMode) { this.defaultFormatMode = defaultFormatMode; items = new Stack <BookNodeInfo>(); }
private void ApplyButton_Click(object sender, RoutedEventArgs e) { DateTime startTime = DateTime.Now; string TT1 = T1; // T1 Temp string TT2 = T2; // T2 Temp // 内容查找与替换 if (ReplaceText.IsChecked.Value) { TT1 = F.Replace(TT1, rtFindText.Text, rtReplacement.Text, !rtIgnoreCase.IsChecked.Value); } // 删除括号内容 else if (Bracket.IsChecked.Value) { TT1 = F.Bracket(TT1, ref TT2, brLeft.Text, brRight.Text, brKeepBracket.IsChecked.Value, brNestBracket.IsChecked.Value); if (!brShowBracketContent.IsChecked.Value) { TT2 = F.EM; } } // 删除空白 else if (DeleteBlank.IsChecked.Value) { int mode = 0; if (dbRemoveAll.IsChecked.Value) { mode = 1; } else if (dbRemoveFront.IsChecked.Value) { mode = 2; } else if (dbRemoveEnd.IsChecked.Value) { mode = 3; } else if (dbRemoveFrontAndEnd.IsChecked.Value) { mode = 4; } TT1 = F.Blank(TT1, mode); } // 换行符相关 else if (NewlineSymbol.IsChecked.Value) { int mode = 0; if (nsRemoveAll.IsChecked.Value) { mode = 1; } else if (nsRemoveUseless.IsChecked.Value) { mode = 2; } else if (nsAddNewlines.IsChecked.Value) { mode = 3; } TT1 = F.Return(TT1, mode); } // 文本顺序调换 else if (TextOrder.IsChecked.Value) { int mode = 0; if (toByLine.IsChecked.Value) { mode = 1; } else if (toByWord.IsChecked.Value) { mode = 2; } else if (toByWordInLine.IsChecked.Value) { mode = 3; } TT1 = F.Reorder(TT1, mode); } // 批量重复文本 else if (RepeatText.IsChecked.Value) { TT1 = F.Repeat(TT1, rptTime.Text, rptAutoNewLine.IsChecked.Value); } // 逐行插入相同内容 else if (AddByLine.IsChecked.Value) { TT1 = F.AddTextByLine(TT1, ablInsertContent.Text, ablPosition.Text, ablIgnoreEmpty.IsChecked.Value, ablIgnoreBlank.IsChecked.Value); } // 逐行插入不同内容 else if (SpecialInsert.IsChecked.Value) { TT1 = F.AddTextsByLine(TT1, TT2, siPosition.Text, siIngoreEmpty.IsChecked.Value); } // 隔行删除 else if (DeleteByLine.IsChecked.Value) { TT1 = F.DeleteByLine(TT1, ref TT2, dblReserve.Text, dblRemove.Text); } // 隔行插入 else if (InsertByLine.IsChecked.Value) { TT1 = F.InsertByLine(TT1, TT2, iblReserve.Text, iblInsert.Text); } // 逐行添加序号 else if (AddIndexByLine.IsChecked.Value) { IndexFormat mode = IndexFormat.Normal; if (aiblNormal.IsChecked.Value) { mode = IndexFormat.Normal; } else if (aiblChinese.IsChecked.Value) { mode = IndexFormat.Chinese; } else if (aiblRoman.IsChecked.Value) { mode = IndexFormat.Roman; } else if (aiblCircle.IsChecked.Value) { mode = IndexFormat.Circle; } else if (aiblBracket.IsChecked.Value) { mode = IndexFormat.Bracket; } int start = 1; int digits = 0; if (int.TryParse(aiblStartValue.Text, out start) && int.TryParse(aiblDigits.Text, out digits)) { TT1 = F.InsertIndexAt(TT1, aiblLeft.Text, aiblRight.Text, start, digits, aiblPosition.Text, mode, aiblIgnoreEmpty.IsChecked.Value, aiblAlignNumber.IsChecked.Value); } } // 文本格式转换 else if (FormatText.IsChecked.Value) { TextFormatMode mode = TextFormatMode.Tranditional; if (ftST.IsChecked.Value) { mode = TextFormatMode.Tranditional; } else if (ftTS.IsChecked.Value) { mode = TextFormatMode.Simplified; } else if (ftLU.IsChecked.Value) { mode = TextFormatMode.Upper; } else if (ftUL.IsChecked.Value) { mode = TextFormatMode.Lower; } else if (ftFU.IsChecked.Value) { mode = TextFormatMode.InitialUpper; } else if (ftCP.IsChecked.Value) { mode = TextFormatMode.Pinyin; } TT1 = F.TextFormat(TT1, mode); } // 正则表达式 else if (RegularExpression.IsChecked.Value) { RegexOptions option = F.GetRexOptions(reIgnoreCase.IsChecked.Value, reMultiline.IsChecked.Value, reSingleline.IsChecked.Value, reIgnorePatternWhitespace.IsChecked.Value, reExplicitCapture.IsChecked.Value); RegexMode mode = RegexMode.Match; if (reReplaceOnly.IsChecked.Value) { mode = RegexMode.Replace; } else if (reReplaceAndShow.IsChecked.Value) { mode = RegexMode.ReplaceAndMatch; } else if (reShowOnly.IsChecked.Value) { mode = RegexMode.Match; } TT1 = F.UseRegex(TT1, ref TT2, reFind.Text, reReplace.Text, mode, option); } // 自定义转换列表 else if (TransformList.IsChecked.Value) { PairListManager manager; if (TransformListFiles.Text == PairListPanel.CurrentListName.Text) { manager = PairListPanel.Manager; } else { manager = new PairListManager(pairFolder + @"\" + TransformListFiles.Text + ".txt"); } TT1 = F.TransformList(TT1, manager, tlR.IsChecked.Value); } // 文件批量重命名 else if (RenameFiles.IsChecked.Value) { ApplyRename(); return; } // 剪贴板辅助工具 else if (ClipboardHelper.IsChecked.Value) { if (isUsingPasteHelper) { return; } PasteLines = F.SplitByString(TT1, F.NL, !chIgnoreBlank.IsChecked.Value); if (PasteLines.Count == 0) { MessageBox.Show("当前无可复制文本,剪贴板辅助工具开启失败。"); return; } MessageBox.Show("剪贴板辅助工具已启用,\n共采集到文本信息 " + PasteLines.Count.ToString() + " 行。"); isUsingPasteHelper = true; PasteLineIndex = 0; Clipboard.SetText(PasteLines[0]); // 改变相关控件的IsEnabled,防止用户在使用期间更改相关参数,导致程序出错 chStopButton.Visibility = Visibility.Visible; chIgnoreBlank.IsEnabled = false; chCycle.IsEnabled = false; chAutoPaste.IsEnabled = false; chAutoKeyDown.IsEnabled = false; chDelay.IsEnabled = false; if (chAutoPaste.IsChecked.Value) { hotkey = new HotKey(this, HotKey.KeyFlags.MOD_CONTROL, Form.Keys.V); hotkey.OnHotKey += HotKeyEvent; } else { kh = new KeyboardHook(); kh.SetHook(); kh.OnKeyDownEvent += HookOnKeyDownEvent; } } // 最终执行效果 T1 = TT1; if (EditorPanel.IsShowingBox2 || EditorPanel.AlwaysShowingBox2) // 当Box2不显示时,使其缓存的文本内容不改变 { T2 = TT2; } DateTime stopTime = DateTime.Now; if (showRunTime) { TimeSpan span = stopTime - startTime; MessageBox.Show("执行耗时" + span.TotalMilliseconds.ToString() + "毫秒"); } }
///////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC PROCEDURES ///////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Applies text formatting to part or all of a snapshot. /// </summary> /// <param name="snapshot">The target <see cref="ITextSnapshot"/>.</param> /// <param name="selectionPositionRanges"> /// The <see cref="ITextPositionRangeCollection"/> indicating the selection position ranges. /// These are used to translate the current selection to the new snapshot that is created, even when formatting the entire snapshot. /// </param> /// <param name="mode">A <see cref="TextFormatMode"/> indicating whether to format part or all of the snapshot. The default value is <c>Ranges</c>.</param> /// <remarks> /// The containing <see cref="ITextDocument"/> is accessible via the <see cref="ITextSnapshot"/>. /// </remarks> public void Format(ITextSnapshot snapshot, ITextPositionRangeCollection selectionPositionRanges, TextFormatMode mode = TextFormatMode.Ranges) { if (snapshot == null) { throw new ArgumentNullException("snapshot"); } if ((selectionPositionRanges == null) || (selectionPositionRanges.Count == 0)) { throw new ArgumentNullException("selectionPositionRanges"); } // Changes must occur sequentially so that we can use unmodified offsets while looping over the document var options = new TextChangeOptions(); options.OffsetDelta = TextChangeOffsetDelta.SequentialOnly; options.RetainSelection = true; var change = snapshot.Document.CreateTextChange(TextChangeTypes.AutoFormat, options); // Get the snapshot ranges to format var snapshotRanges = (mode == TextFormatMode.All ? new TextSnapshotRange[] { snapshot.SnapshotRange } : selectionPositionRanges.Select(pr => new TextSnapshotRange(snapshot, snapshot.PositionRangeToTextRange(pr))).ToArray() ); // Loop through the snapshot ranges foreach (var snapshotRange in snapshotRanges) { this.FormatCore(change, snapshotRange); } // Apply the changes if (change.Operations.Count > 0) { change.Apply(); } }