How to use the diff-match-patch.diff_match_patch function in diff-match-patch

To help you get started, we’ve selected a few diff-match-patch examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DefinitelyTyped / DefinitelyTyped / types / diff-match-patch / diff-match-patch-tests.ts View on Github external
case DiffMatchPatch.DIFF_DELETE:
                pattern += "D";
                break;
            case DiffMatchPatch.DIFF_EQUAL:
                pattern += "E";
                break;
        }

        changes += text;
    });
}

const DIFF_DELETE: number = DiffMatchPatch.DIFF_DELETE;
const DIFF_INSERT: number = DiffMatchPatch.DIFF_INSERT;
const DIFF_EQUAL: number = DiffMatchPatch.DIFF_EQUAL;
const dmp = new DiffMatchPatch.diff_match_patch();

// DIFF TEST FUNCTIONS

function testDiffCommonPrefix() {
    assertEquals(0, dmp.diff_commonPrefix('abc', 'xyz'));
}

function testDiffCommonSuffix() {
    assertEquals(0, dmp.diff_commonSuffix('abc', 'xyz'));
}

function testDiffCommonOverlap() {
    assertEquals(0, dmp.diff_commonOverlap_('', 'abcd'));
}

function testDiffHalfMatch() {
github DefinitelyTyped / DefinitelyTyped / types / diff-match-patch / diff-match-patch-tests.ts View on Github external
function testDiffMainEach() {
    const oldValue = "hello world, how are you?";
    const newValue = "hello again world. how have you been?";

    const diffEngine = new DiffMatchPatch.diff_match_patch();
    const diffs = diffEngine.diff_main(oldValue, newValue);
    diffEngine.diff_cleanupSemantic(diffs);

    let changes = "";
    let pattern = "";

    diffs.forEach((diff) => {
        const operation = diff[0]; // Operation (insert, delete, equal)
        const text = diff[1]; // Text of change

        switch (operation) {
            case DiffMatchPatch.DIFF_INSERT:
                pattern += "I";
                break;
            case DiffMatchPatch.DIFF_DELETE:
                pattern += "D";
github inkandswitch / capstone / src / components / TextEditor.tsx View on Github external
updateCodeMirrorContent = (newContent: string) => {
    if (!this.codeMirror) return

    const codeMirrorDoc: CodeMirror.Doc = this.codeMirror.getDoc()

    // Short circuit if we don't need to apply any changes to the editor. This
    // happens when we get a text update based on our own local edits.
    const oldContent = codeMirrorDoc.getValue()
    if (oldContent === newContent) {
      return
    }

    // Otherwise find the diff between the current and desired contents, and
    // apply corresponding editor ops to close them.
    const dmp = new DiffMatchPatch.diff_match_patch()
    const diff = dmp.diff_main(oldContent, newContent)
    // The diff lib doesn't give indicies so we need to compute them ourself as
    // we go along.
    let at = 0
    for (let i = 0; i < diff.length; i += 1) {
      const [type, str] = diff[i]
      switch (type) {
        case DiffMatchPatch.DIFF_EQUAL: {
          at += str.length
          break
        }
        case DiffMatchPatch.DIFF_INSERT: {
          const fromPos = codeMirrorDoc.posFromIndex(at)
          codeMirrorDoc.replaceRange(str, fromPos, undefined, "automerge")
          at += str.length
          break
github facebookarchive / atom-ide-ui / modules / atom-ide-debugger-python / VendorLib / vs-py-debugger / out / client / common / editor.js View on Github external
if (patch.length === 0) {
            return;
        }
        // We can't find the find name
        if (fileNameLines.length === 0) {
            return;
        }
        let fileName = fileNameLines[0].substring(fileNameLines[0].indexOf(' a') + 3).trim();
        fileName = workspaceRoot && !path.isAbsolute(fileName) ? path.resolve(workspaceRoot, fileName) : fileName;
        if (!fs.existsSync(fileName)) {
            return;
        }
        // Remove the text added by unified_diff
        // # Work around missing newline (http://bugs.python.org/issue2142).
        patch = patch.replace(/\\ No newline at end of file[\r\n]/, '');
        const d = new dmp.diff_match_patch();
        const patches = patch_fromText.call(d, patch);
        if (!Array.isArray(patches) || patches.length === 0) {
            throw new Error('Unable to parse Patch string');
        }
        const fileSource = fs.readFileSync(fileName).toString('utf8');
        const fileUri = vscode.Uri.file(fileName);
        // Add line feeds and build the text edits
        patches.forEach(p => {
            p.diffs.forEach(diff => {
                diff[1] += os_1.EOL;
            });
            getTextEditsInternal(fileSource, p.diffs, p.start1).forEach(edit => {
                switch (edit.action) {
                    case EditAction.Delete:
                        workspaceEdit.delete(fileUri, new vscode_1.Range(edit.start, edit.end));
                        break;
github microsoft / just / packages / just-scripts / src / stack / getStackDiffs.ts View on Github external
export async function getSingleStackDiffs(stack: string, fromVersion: string, toVersion: string): Promise {
  const packagePaths = await Promise.all([downloadPackage(stack, fromVersion), downloadPackage(stack, toVersion)]);

  // Concentrates on new and modified files only
  const diffInfo: DiffInfo = {
    patches: {},
    fromVersion,
    toVersion
  };

  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  const fromPath = packagePaths[0]!;
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  const toPath = packagePaths[1]!;
  const globbedFiles = glob.sync('**/*', { cwd: toPath, nodir: true, dot: true });
  const dmp = new DiffMatchPatch();

  globbedFiles.forEach(file => {
    const toFile = path.join(toPath, file);
    const toContent = fs.readFileSync(toFile).toString();

    const fromFile = path.join(fromPath, file);

    let diffs: Diff[];
    let patches: Patch[];

    if (fs.existsSync(fromFile)) {
      const fromContent = fs.readFileSync(fromFile).toString();
      diffs = dmp.diff_main(fromContent, toContent);
      patches = dmp.patch_make(fromContent, toContent, diffs);
    } else {
      diffs = dmp.diff_main('', toContent);
github kythe / kythe / kythe / typescript / languageserver / languageserver / src / document.ts View on Github external
private generateDirtyRefs() {
    const differ = new diff.diff_match_patch();
    const diffs = differ.diff_main(this.sourceText, this.dirtyText);
    differ.diff_cleanupSemantic(diffs);
    const oldPosition: Position = {line: 0, character: 0};

    const newPosition: Position = {line: 0, character: 0};

    let refIndex = 0;

    for (const d of diffs) {
      // If we're past the ref with respect to the old file, shift refIndex
      while (refIndex < this.refs.length &&
             (this.refs[refIndex].range.start.line < oldPosition.line ||
              (this.refs[refIndex].range.start.line === oldPosition.line &&
               this.refs[refIndex].range.start.character <
                   oldPosition.character))) {
        refIndex++;
github akof1314 / CoolFormat / Plugins / VSCode / CoolFormatVSCodePlugin / extension.js View on Github external
generateTextEditors(document, formattedText) {
        let dmp = new diffMatchPatch.diff_match_patch();
        let diffs = dmp.diff_main(document.getText(), formattedText.replace(/\r\n|\r|\n/g, document.eol == 2 ? '\r\n' : '\n'));
        let editors = [];
        let line = 0, character = 0;

        diffs.forEach((diff) => {
            let op = diff[0];
            let text = diff[1];
            let start = new vscode.Position(line, character);
            let lines = text.split(/\r\n|\r|\n/g);

            line += lines.length - 1;

            if (lines.length > 1) {
                character = lines[lines.length - 1].length;
            } else if (lines.length == 1) {
                character += lines[0].length;
github microsoft / just / packages / just-scripts / src / stack / applyStackDiffs.ts View on Github external
export function applyStackDiffs(projectPath: string, diffInfo: DiffInfo) {
  const dmp = new DiffMatchPatch();

  const globbedFiles = glob.sync('**/*', {
    cwd: projectPath,
    ignore: 'node_modules/**/*',
    nodir: true,
    dot: true
  });

  globbedFiles.forEach(file => {
    const filePath = path.join(projectPath, file);

    if (diffInfo.patches[file]) {
      logger.info(`Patching ${file}`);
      const content = fs.readFileSync(filePath).toString();
      const [newContent] = dmp.patch_apply(diffInfo.patches[file], content);
      fs.writeFileSync(filePath, newContent);
github sanity-io / sanity / packages / @sanity / mutator / src / patch / DiffMatchPatch.ts View on Github external
import * as DMP from 'diff-match-patch'

const dmp = new DMP.diff_match_patch()

export default class DiffMatchPatch {
  path: string
  dmpPatch: DMP.patch_obj[]
  id: string
  constructor(id: string, path: string, dmpPatchSrc: string) {
    this.id = id
    this.path = path
    this.dmpPatch = dmp.patch_fromText(dmpPatchSrc)
  }
  apply(targets, accessor) {
    let result = accessor
    targets.forEach(target => {
      if (target.isIndexReference()) {
        target.toIndicies(accessor).forEach(i => {
          const oldValue = result.getIndex(i).get()
github esteemapp / esteem-surfer / app / utils / posting-helpers.js View on Github external
export const createPatch = (text1, text2) => {
  const dmp = new diff_match_patch();
  if (!text1 && text1 === '') return undefined;
  const patches = dmp.patch_make(text1, text2);
  const patch = dmp.patch_toText(patches);
  return patch;
};

diff-match-patch

npm package for https://github.com/google/diff-match-patch

Apache-2.0
Latest version published 4 years ago

Package Health Score

71 / 100
Full package analysis