首页 > 其他分享 >文本比对工具 diffplex

文本比对工具 diffplex

时间:2024-03-02 10:44:50浏览次数:17  
标签:set string get text public diffplex 文本 工具 side

https://github.com/mmanela/diffplex

DiffPlex is C# library to generate textual diffs. It targets netstandard1.0+.

About the API

The DiffPlex library currently exposes two interfaces for generating diffs:

  • IDiffer (implemented by the Differ class) - This is the core diffing class. It exposes the low level functions to generate differences between texts.
  • ISidebySideDiffer (implemented by the SideBySideDiffer class) - This is a higher level interface. It consumes the IDiffer interface and generates a SideBySideDiffModel. This is a model which is suited for displaying the differences of two pieces of text in a side by side view.

Examples

For examples of how to use the API please see the the following projects contained in the DiffPlex solution.

For use of the IDiffer interface see:

  • SidebySideDiffer.cs contained in the DiffPlex Project.
  • UnidiffFormater.cs contained in the DiffPlex.ConsoleRunner project.

For use of the ISidebySideDiffer interface see:

  • DiffController.cs and associated MVC views in the WebDiffer project
  • TextBoxDiffRenderer.cs in the SilverlightDiffer project

Sample code

var diff = InlineDiffBuilder.Diff(before, after);

var savedColor = Console.ForegroundColor;
foreach (var line in diff.Lines)
{
    switch (line.Type)
    {
        case ChangeType.Inserted:
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write("+ ");
            break;
        case ChangeType.Deleted:
            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write("- ");
            break;
        default:
            Console.ForegroundColor = ConsoleColor.Gray; // compromise for dark or light background
            Console.Write("  ");
            break;
    }

    Console.WriteLine(line.Text);
}
Console.ForegroundColor = savedColor;
 

IDiffer Interface

/// <summary>
/// Provides methods for generate differences between texts
/// </summary>
public interface IDiffer
{
    /// <summary>
    /// Create a diff by comparing text line by line
    /// </summary>
    /// <param name="oldText">The old text.</param>
    /// <param name="newText">The new text.</param>
    /// <param name="ignoreWhiteSpace">if set to <c>true</c> will ignore white space when determining if lines are the same.</param>
    /// <returns>A DiffResult object which details the differences</returns>
    DiffResult CreateLineDiffs(string oldText, string newText, bool ignoreWhiteSpace);

    /// <summary>
    /// Create a diff by comparing text character by character
    /// </summary>
    /// <param name="oldText">The old text.</param>
    /// <param name="newText">The new text.</param>
    /// <param name="ignoreWhitespace">if set to <c>true</c> will treat all whitespace characters are empty strings.</param>
    /// <returns>A DiffResult object which details the differences</returns>
    DiffResult CreateCharacterDiffs(string oldText, string newText, bool ignoreWhitespace);

    /// <summary>
    /// Create a diff by comparing text word by word
    /// </summary>
    /// <param name="oldText">The old text.</param>
    /// <param name="newText">The new text.</param>
    /// <param name="ignoreWhitespace">if set to <c>true</c> will ignore white space when determining if words are the same.</param>
    /// <param name="separators">The list of characters which define word separators.</param>
    /// <returns>A DiffResult object which details the differences</returns>
    DiffResult CreateWordDiffs(string oldText, string newText, bool ignoreWhitespace, char[] separators);

    /// <summary>
    /// Create a diff by comparing text in chunks determined by the supplied chunker function.
    /// </summary>
    /// <param name="oldText">The old text.</param>
    /// <param name="newText">The new text.</param>
    /// <param name="ignoreWhiteSpace">if set to <c>true</c> will ignore white space when determining if chunks are the same.</param>
    /// <param name="chunker">A function that will break the text into chunks.</param>
    /// <returns>A DiffResult object which details the differences</returns>
    DiffResult CreateCustomDiffs(string oldText, string newText, bool ignoreWhiteSpace, Func<string, string[]> chunker);

            /// <summary>
        /// Create a diff by comparing text line by line
        /// </summary>
        /// <param name="oldText">The old text.</param>
        /// <param name="newText">The new text.</param>
        /// <param name="ignoreWhiteSpace">if set to <c>true</c> will ignore white space when determining if lines are the same.</param>
        /// <param name="ignoreCase">Determine if the text comparision is case sensitive or not</param>
        /// <param name="chunker">Component responsible for tokenizing the compared texts</param>
        /// <returns>A DiffResult object which details the differences</returns>
        DiffResult CreateDiffs(string oldText, string newText, bool ignoreWhiteSpace, bool ignoreCase, IChunker chunker);
}
 

IChunker Interface

public interface IChunker
{
    /// <summary>
    /// Dive text into sub-parts
    /// </summary>
    string[] Chunk(string text);
}
 

Currently provided implementations:

  • CharacterChunker
  • CustomFunctionChunker
  • DelimiterChunker
  • LineChunker
  • LineEndingsPreservingChunker
  • WordChunker

ISideBySideDifferBuilder Interface

/// <summary>
/// Provides methods that generate differences between texts for displaying in a side by side view.
/// </summary>
public interface ISideBySideDiffBuilder
{
    /// <summary>
    /// Builds a diff model for  displaying diffs in a side by side view
    /// </summary>
    /// <param name="oldText">The old text.</param>
    /// <param name="newText">The new text.</param>
    /// <returns>The side by side diff model</returns>
    SideBySideDiffModel BuildDiffModel(string oldText, string newText);
}
 

Sample Website

DiffPlex also contains a sample website that shows how to create a basic side by side diff in an ASP MVC website.

Web page sample

Windows app

There are 2 libraries for Windows app development. One is for Windows App SDK, another is for WPF and WinForms.

WinUI 3 Elements

NuGet

DiffPlex WinUI library DiffPlex.Windows is used to render textual diffs in your app which targets to Windows App SDK.

using DiffPlex.UI;
 

And insert following code into the root node of your xaml file, e.g. user control, page or window.

xmlns:diffplex="using:DiffPlex.UI"
 
  • DiffTextView Textual diffs view element.

For example.

<diffplex:DiffTextView x:Name="DiffView" />
 
DiffView.SetText(OldText, NewText);
 

WinUI sample

You can also customize the style. Following are some of the properties you can get or set.

// true if it is in split view; otherwise, false, in unified view.
public bool IsSplitView { get; set; }

// true if it is in unified view; otherwise, false, in split view.
public bool IsUnifiedView { get; set; }

// The selection mode of list view. Default is None.
public ListViewSelectionMode SelectionMode { get; set; }

// true if ignore white spaces; otherwise, false. Default is true.
public bool IgnoreWhiteSpace { get; set; }

// true if the text is case sensitive; otherwise, false. Default is false.
public bool IsCaseSensitive { get; set; }

// The default text color (foreground brush).
public Brush Foreground { get; set; }

// The background.
public Brush Background { get; set; }

// The width of the line number. Default is 50.
public GridLength LineNumberWidth { get; set; }

// The style of the line number.
public Style LineNumberStyle { get; set; }

// The width of the change type symbol. Default is 20.
public GridLength ChangeTypeWidth { get; set; }

// The style of the change type symbol.
public Style ChangeTypeStyle { get; set; }

// The style of the text.
public Style TextStyle { get; set; }

// true if the text is selection enabled; otherwise, false. Default is true.
public bool IsTextSelectionEnabled { get; set; }

// true if collapse unchanged sections; otherwise, false. Default is false.
public bool IsUnchangedSectionCollapsed { get; set; }

// The lines for context. Default is 2.
public int LineCountForContext { get; set; }

// true if the file selector menu button is enabled; otherwise, false. Default is true.
public bool IsFileMenuEnabled { get; set; }

// The height of command bar. Default is 50.
public GridLength CommandBarHeight { get; set; }

// The default label position of command bar. Default is Right.
public CommandBarDefaultLabelPosition CommandLabelPosition { get; set; }

// The collection of secondary command elements for the command bar.
public IObservableVector<ICommandBarElement> SecondaryCommands { get; }
 

WPF Controls

NuGet

DiffPlex WPF control library DiffPlex.Wpf is used to render textual diffs in your WPF application. It targets .NET 6.NET Framework 4.8 and .NET Framework 4.6.

using DiffPlex.Wpf.Controls;
 

To import the controls into your window/page/control, please insert following attribute into the root node (such as <Window />) of your xaml files.

xmlns:diffplex="clr-namespace:DiffPlex.Wpf.Controls;assembly=DiffPlex.Wpf"
 
  • DiffViewer Textual diffs viewer control with view mode switching by setting an old text and a new text to diff.
  • SideBySideDiffViewer Side-by-side (splitted) textual diffs viewer control by setting a diff model SideBySideDiffModel.
  • InlineDiffViewer Inline textual diffs viewer control by setting a diff model DiffPaneModel.

For example.

<diffplex:DiffViewer x:Name="DiffView" />
 
DiffView.OldText = oldText;
DiffView.NewText = newText;
 

WPF sample

You can also customize the style. Following are some of the properties you can get or set.

// The header of old text.
public string OldTextHeader { get; set; }

// The header of new text.
public string NewTextHeader { get; set; }

// true if it is in side-by-side (split) view;
// otherwise, false, in inline (unified) view.
public bool IsSideBySideViewMode { get; }

// true if collapse unchanged sections; otherwise, false.
public bool IgnoreUnchanged { get; set; }

// The font size.
public double FontSize { get; set; }

// The preferred font family.
public FontFamily FontFamily { get; set; }

// The font weight.
public FontWeight FontWeight { get; set; }

// The font style.
public FontStyle FontStyle { get; set; }

// The font-stretching characteristics.
public FontStretch FontStretch { get; set; }

// The default text color (foreground brush).
public Brush Foreground { get; set; }

// The background brush of the line inserted.
public Brush InsertedBackground { get; set; }

// The background brush of the line deleted.
public Brush DeletedBackground { get; set; }

// The text color (foreground brush) of the line number.
public Brush LineNumberForeground { get; set; }

// The width of the line number and change type symbol.
public int LineNumberWidth { get; set; }

// The background brush of the line imaginary.
public Brush ImaginaryBackground { get; set; }

// The text color (foreground brush) of the change type symbol.
public Brush ChangeTypeForeground { get; set; }

// The background brush of the header.
public Brush HeaderBackground { get; set; }

// The height of the header.
public double HeaderHeight { get; set; }

// The background brush of the grid splitter.
public Brush SplitterBackground { get; set; }

// The width of the grid splitter.
public Thickness SplitterWidth { get; set; }

// A value that represents the actual calculated width of the left side panel.
public double LeftSideActualWidth { get; }

// A value that represents the actual calculated width of the right side panel.
public double RightSideActualWidth { get; }
 

And you can listen following event handlers.

// Occurs when the grid splitter loses mouse capture.
public event DragCompletedEventHandler SplitterDragCompleted;

// Occurs one or more times as the mouse changes position when the grid splitter has logical focus and mouse capture.
public event DragDeltaEventHandler SplitterDragDelta;

// Occurs when the grid splitter receives logical focus and mouse capture.
public event DragStartedEventHandler SplitterDragStarted;

// Occurs when the view mode is changed.
public event EventHandler<ViewModeChangedEventArgs> ViewModeChanged;
 

WinForms Controls

NuGet

Windows Forms control of diff viewer is a WPF element host control. It is also included in DiffPlex.Wpf assembly. You can import it to use in your Windows Forms application. It targets .NET 6.NET Framework 4.8 and .NET Framework 4.6.

using DiffPlex.WindowsForms.Controls;
 

Then you can add the following control in window or user control.

  • DiffViewer Textual diffs viewer control with view mode switching by setting an old text and a new text to diff.

For example.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        var diffView = new DiffViewer
        {
            Margin = new Padding(0),
            Dock = DockStyle.Fill,
            OldText = oldText,
            NewText = newText
        };
        Controls.Add(diffView);
    }
}
 

Windows Forms sample

You can also customize the style. Following are some of the properties you can get or set.

// The header of old text.
public string OldTextHeader { get; set; }

// The header of new text.
public string NewTextHeader { get; set; }

// true if it is in side-by-side (split) view;
// otherwise, false, in inline (unified) view.
public bool IsSideBySideViewMode { get; }

// true if collapse unchanged sections; otherwise, false.
public bool IgnoreUnchanged { get; set; }

// The font size.
public double FontSize { get; set; }

// The preferred font family names in string.
public string FontFamilyNames { get; set; }

// The font weight.
public int FontWeight { get; set; }

// The font style.
public bool IsFontItalic { get; set; }

// The default text color (foreground brush).
public Color ForeColor { get; set; }

// The background brush of the line inserted.
public Color InsertedBackColor { get; set; }

// The background brush of the line deleted.
public Color DeletedBackColor { get; set; }

// The text color (foreground color) of the line number.
public Color LineNumberForeColor { get; set; }

// The width of the line number and change type symbol.
public int LineNumberWidth { get; set; }

// The background brush of the line imaginary.
public Color ImaginaryBackColor { get; set; }

// The text color (foreground color) of the change type symbol.
public Color ChangeTypeForeColor { get; set; }

// The background brush of the header.
public Color HeaderBackColor { get; set; }

// The height of the header.
public double HeaderHeight { get; set; }

// The background brush of the grid splitter.
public Color SplitterBackColor { get; set; }

// The width of the grid splitter.
public Padding SplitterWidth { get; set; }

// A value that represents the actual calculated width of the left side panel.
public double LeftSideActualWidth { get; }

// A value that represents the actual calculated width of the right side panel.
public double RightSideActualWidth { get; }

标签:set,string,get,text,public,diffplex,文本,工具,side
From: https://www.cnblogs.com/lhxsoft/p/18048373

相关文章

  • 懒人读论文和做笔记的trick——只保留文本粘贴&去除空行
    工具/快捷键可以节省时间,这样就有时间玩耍啦!偷懒是好事情,懒是第一生产力!找到自己的节奏,不要被别人所干扰~只保留文本粘贴选项-快速访问工具栏-选择“所有命令”-找到“粘贴并只保留文本”-添加-移到最上边,按alt+1就可以了。去除空行复制之后粘贴到浏览器地址栏,然后左键连......
  • FRP(Fast Reverse Proxy)网络映射工具部署
    FastReverseProxy(FRP)是一款由fatedier开发的高性能的反向代理工具,用于穿透防火墙、NAT等网络障碍,将内网服务映射到公网上github地址https://github.com/fatedier/frp 下载https://github.com/fatedier/frp/releases根据操作系统找到对应版本,客户端服务端共用一个包。 ......
  • 弱网罗测试工具clumsy
    clumsy能在Windows平台下人工造成不稳定的网络状况,方便你调试应用程序在极端网络状况下的表现。 简介利用封装WinodwsFilteringPlatform的WinDivert库,clumsy能实时的将系统接收和发出的网络数据包拦截下来,人工的造成延迟,掉包和篡改操作后再进行发送。无论你是要重......
  • 弱网模拟工具Clumsy
    Clumsy是基于C语言开发的一款开源网络模拟工具。它能在Windows平台下人工造成不稳定的网络状态,应用它可以方便调试应用程序在极端网络状态下的表现。一、下载安装软件下载地址:http://jagt.github.io/clumsy/cn/download首先请根据你系统的版本(32位或64位)下载clumsy最新版本......
  • 基于CNN卷积网络的MNIST手写数字识别matlab仿真,CNN编程实现不使用matlab工具箱
    1.算法运行效果图预览    2.算法运行软件版本matlab2022a  3.算法理论概述       MNIST是一个手写数字的大型数据库,包含60,000个训练样本和10,000个测试样本。每个样本都是28x28像素的灰度图像,代表0到9之间的一个数字。 3.1卷积神经网络(CNN)   ......
  • 使用ConfuserEx代码混淆工具保护你的.NET应用程序
    .NET反编译相关的文章4款免费且实用的.NET反编译工具.NET反编译神器ILSpy怎么用?ConfuserEx.NET混淆工具安装GitHub开源地址:https://github.com/mkaring/ConfuserEx下载地址:https://github.com/mkaring/ConfuserEx/releases ConfuserEx-GUI.zip包解压即可使用:使......
  • Debug工具
              ......
  • Windows Server 2019 不使用第三方工具,开启SFTP
    在WindowsServer2019上,你可以通过安装和配置OpenSSH服务器来启用SFTP(SSH文件传输协议)。以下是在WindowsServer2019上开启SFTP的步骤:#创建一个新的本地用户账户。运行以下命令来创建一个名为"sftp"的用户账户(你可以根据需要更改用户名)New-LocalUser-Name"sft......
  • 运用表单设计工具实现流程化办公!
    当前,不少企业希望能借助低代码技术平台的力量实现流程化办公。这也是当前一个比较有前景的发展趋势。表单设计工具是低代码技术平台里的一项重要功能,在推动企业做好数据管理工作、沟通部门领域发挥了重要的价值和作用。想要实现流程化办公,不妨一起了解表单设计工具、低代码技术平......
  • 编辑器脚本工具——批量修改场景中的静态网格体
    介绍这个功能可以让用户在场景中批量替换静态模型使用方式在场景中选择完想要更改的静态模型在弹出的窗口选择要替换的模型替换完成蓝图https://blueprintue.com/blueprint/p1p8imoa/......