AvalonEdit: Copy takes forever for large highlight

2019-07-04 02:39发布

问题:

Actually this was asked on http://community.sharpdevelop.net/forums/p/21949/56153.aspx#56153 but with no answer yet - so I try it here.

I'm using Avalon Edit (ICSharpCode.AvalonEdit.dll 4.4.2) in a WPF 4.0 application. I have loaded a text file (~7 MBytes) into the editor. When I apply syntax highlighting and then coping (Control-A and Control-C) the whole text it takes forever (without highlighting it's done in a second)

When I break into debugger I get the following callstack (shortened):

System.Text.RegularExpressions.RegexInterpreter.Go() 
System.Text.RegularExpressions.RegexRunner.Scan(regex, text, textbeg, textend, textstart, prevlen, quick, timeout) 
System.Text.RegularExpressions.Regex.Run(quick, prevlen, input, beginning, length, startat) 
System.Text.RegularExpressions.Regex.Match(input, beginning, length) 
ICSharpCode.AvalonEdit.Highlighting.DocumentHighlighter.HighlightNonSpans(until) 
ICSharpCode.AvalonEdit.Highlighting.DocumentHighlighter.HighlightLineInternal(line) 
ICSharpCode.AvalonEdit.Highlighting.DocumentHighlighter.HighlightLineAndUpdateTreeList(line, lineNumber) 
ICSharpCode.AvalonEdit.Highlighting.DocumentHighlighter.HighlightLine(lineNumber) 
ICSharpCode.AvalonEdit.Highlighting.HtmlClipboard.CreateHtmlFragment(document, highlighter, segment, options) 
ICSharpCode.AvalonEdit.Editing.Selection.CreateHtmlFragment(options) 
ICSharpCode.AvalonEdit.Editing.Selection.CreateDataObject(textArea) 
ICSharpCode.AvalonEdit.Editing.EditingCommandHandler.CopySelectedText(textArea) 
ICSharpCode.AvalonEdit.Editing.EditingCommandHandler.OnCopy(target, args) 

It seems the editor creates html-based content for the clipboard and uses RegularExpressions which takes forever (~30 seconds).

Question: Does anyone know a possibility to disable the syntax highlighting for the copy action so that only pure text is copied to the clipboard.

回答1:

I got the answer from DanielGrunwald on SharpDevelop that I want to share: In avalonedit 4.X it's not possible to disable html copy to clipboard. But in 5.X you can do that.

With:

AvalonEdit.TextEditor TextView

write the following to register the callback for the before-copy event:

DataObject.AddSettingDataHandler(TextView, onTextViewSettingDataHandler);

to register a user handler that is called before cliboard copying is processed. In that handler cancel the html format (e.g. depending on the document size). Example:

static public void onTextViewSettingDataHandler(object sender, DataObjectSettingDataEventArgs e)
{
  var textView = sender as TextEditor;
  if (textView != null && e.Format == DataFormats.Html && textView.Text.Count() > MaxDocByteSizeForHtmlCopy)
  {        
    e.CancelCommand();
  }
}

With that code you can prevent that hanger, but of course formatting is not preserved when the content is pasted (e.g. into Word).