unifieddiff()
| Function group | Execute on client | Platform(s) |
|---|---|---|
| String | NO | All |
Syntax
unifieddiff(oldtext,newtext[,context=3,linesep,flags=0])
Description
Returns a unified diff of oldtext and newtext, with context unchanged lines either side of each change. Lines are rejoined with linesep. Flags can be kDiffKeepTrailingEmptyLine.
The returned text is a unified diff, the format produced by "diff -u" and "git diff". Each run of changes is headed by an @@ line saying where it sits in each version of the text, followed by the lines themselves: a leading space for an unchanged line, "-" for a line only in oldtext, and "+" for a line only in newtext. A line which was edited appears as the old line followed by the new one.
The function returns an empty string when the two texts are the same, so you can test the result to find out whether anything changed.
context is the number of unchanged lines reported either side of each change, to show where it belongs. It defaults to 3. Pass zero to report only the lines which differ.
Both texts are split into lines at a carriage return, a line feed, or a carriage return and line feed together, whichever each line happens to end with, so text which has picked up mixed line endings is still read one line per line. A single line ending at the very end of a text is treated as ending the last line rather than starting an empty one, so a text with a trailing line ending and one without are otherwise the same. Pass kDiffKeepTrailingEmptyLine in flags to treat that final line ending as starting an empty last line instead, so that adding or removing a blank line at the end of a text is reported as a change. Use it where a line ending at the end of the text is part of the data rather than a terminator. Give the same constant to applydiff(), since a diff made under one reading and applied under the other describes lines the other does not have.
The lines of the returned diff are joined with linesep. If you omit it the function uses whichever line ending it finds in oldtext, or in newtext when oldtext is empty, so the diff is punctuated like the text it describes. Text with no line ending at all gives a diff joined with line feeds.
A removed line and an added line are only reported as a single edited line where the two actually resemble one another, comparing what they share at the start and the end. Lines with little in common are reported separately, so a diff never claims one line became another it has nothing to do with.
To apply the returned diff to text, and so reproduce newtext from oldtext, use the function applydiff(). It will also undo one, turning newtext back into oldtext.