Skip to main content

Beautiful Diff view widget for Textual applications

Project description

Textual Diff View

Textual Diff View is a Textual widget to display beautiful diffs in your terminal application. Originally built for Toad, this widget may be used standalone.

This is what it can look like...

Features

The DiffView widget displays two versions of a file with syntax and changes clearly highlighted. Deleted lines / characters are shown with a red highlight. Added lines / characters are shown with a green highlight.

There are two layout options; a unified view which shows the two files top-to-bottom with highlights, and a split view which shows the two files next to each other.

DiffView can also display annotations ("+" and "-" for added and deleted), to improve readability for color blind users.

Textual's theming system provides a variety of themes for the diff view, both light and dark.

Example

The following is a simple app to display a diff between two files from the command line.

from textual.app import App, ComposeResult
from textual import containers
from textual.reactive import var
from textual import widgets

from textual_diff_view import DiffView, LoadError


class DiffApp(App):
    """Simple app to display a diff between two files."""

    BINDINGS = [
        ("space", "toggle('split')", "Toggle split"),
        ("a", "toggle('annotations')", "Toggle annotations"),
    ]

    split = var(True)
    annotations = var(True)

    def __init__(self, original: str, modified: str) -> None:
        self.original = original
        self.modified = modified
        super().__init__()

    def compose(self) -> ComposeResult:
        yield containers.VerticalScroll(id="diff-container")
        yield widgets.Footer()

    async def on_mount(self) -> None:
        try:
            diff_view = await DiffView.load(self.original, self.modified)
        except LoadError as error:
            self.notify(str(error), title="Failed to load code", severity="error")
        else:
            diff_view.data_bind(DiffApp.split, DiffApp.annotations)
            await self.query_one("#diff-container").mount(diff_view)


if __name__ == "__main__":
    import sys

    if len(sys.argv) != 3:
        print("Usage python tdiff.py PATH1 PATH2\nTry: python tdiff.py example1.rs example2.rs")
    else:
        app = DiffApp(sys.argv[1], sys.argv[2])
        app.run()

You can find this file in the examples/ directory. Run it with the following:

uv run python tdiff.py example1.rs example2.rs

Use space to toggle unified / split, and a to toggle annotations.

Screenshots

A few screenshots taken from the example app:

Installing

Texual Diff View is on PyPI and may be installed with pip, or uv.

Here's how to install with uv:

uv add textual-diff-view

How to use

Import the widget with the following:

from textual_diff_view import DiffView

Then yield an instance of DiffView in your compose method.

The constructor accepts 4 positional arguments:

Argument type Purpose
path_original str A path to the original code
path_modified str A path to the modified code
code_original str The contents of the original code
code_modified str The contents of the modified code

Additionally, the constructor accepts the standard keyword arguments, name, id, and classes——which have the same meaning as Textual's built in widgets.

Here's a very simple example:

from textual.app import App, ComposeResult
from textual import containers

from textual_diff_view import DiffView

HELLO1 = """
def greet():
    print "Hello!"

greet()
"""

HELLO2 = """
def greet(name:str):
    print(f"Hello, {name}!")

greet('Will')
"""


class Hello(App):
    def compose(self) -> ComposeResult:
        with containers.VerticalScroll():
            yield DiffView("hello1.py", "hello2.py", HELLO1, HELLO2)


Hello().run()

Note that we put the DiffView within a VerticalScroll, so the user may scroll the container if the diff doesn't fit.

The above code will generate the following output:

Load constructor

DiffView provides an alternative constructor, DiffView.load, which also loads the code. If both your original code and modified code is on disk, this may be simpler than the standard constructor.

DiffView.load accepts the following positional arguments:

Argument Type Purpose
path_original str or Path A path to the original code
path_modified str or Path A path to the modified code

Since load is a coroutine, you would typically call it from a message handler in another widget, or App, then mount it somewhere in the DOM.

The code would look something like the following:

diff_view = await DiffView.load("original.py", "modified.py")
await self.query_one("VerticalScroll").mount(diff_view)

Reactives

The DiffView supports the following reactive attributes.

Name Type Explanation
split bool Enables split view when True, or unified view when False
auto_split bool Automatically enable split view if there is enough space to fit the longest lines from both file.
annotations bool Enable annotations ("+" or "-" symbols). It is reccomended that apps always offer this for color blind users.
wrap bool Wrap code lines rather than enable horizontal scrolling.

Roadmap

There are a few remaining features that I anticipate a need for:

  • Word wrapping The widget currently supports horizontal scrolling (via mouse-wheel, trackpad, or shift+mouse-wheel). This works rather well, but has the downside that it is not especially discoverable. An option to enable word wrapping would be useful.
  • ANSI theme A future version will add support for ANSI themes, which is limited to the user's choice of 16 colors. It will never look as good, but some people say they prefer it.
  • Expand control A clickable icon or link to expand the number of lines surrounding an edit.

There are also a few more high-effort features that I could be tempted to implement:

  • Swappable diff methods. There is no perfect diff algorithm. They all have their trade-offs. The DiffView widget uses Python's difflib but it could offer an interface to add other diff algorithms.
  • AST level diffs A diff view that works at the AST level can offer diffs that more closely reflect how a human might edit code.
  • Notes Add notes associated with specific lines, displayed in a panel or pop-up.

License

DiffView is licensed under the terms of the AGPL license. A commercial license is available if you aren't comfortable with the copyleft restriction. Contact Will McGugan for more information.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

textual_diff_view-0.1.5.tar.gz (38.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

textual_diff_view-0.1.5-py3-none-any.whl (25.5 kB view details)

Uploaded Python 3

File details

Details for the file textual_diff_view-0.1.5.tar.gz.

File metadata

  • Download URL: textual_diff_view-0.1.5.tar.gz
  • Upload date:
  • Size: 38.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.6 {"installer":{"name":"uv","version":"0.11.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for textual_diff_view-0.1.5.tar.gz
Algorithm Hash digest
SHA256 e28151c45d4207fb7b50b57fce2bc249e880c2a496b21bf7d8560a92e59caecb
MD5 9e90a57ef8a849a1ebe50c0748e01b2d
BLAKE2b-256 7655bb5d51487b195bee04c71d42bc5b3e6bca0ba9477cf9b6f12c7f498a0bd7

See more details on using hashes here.

File details

Details for the file textual_diff_view-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: textual_diff_view-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 25.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.6 {"installer":{"name":"uv","version":"0.11.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for textual_diff_view-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 2e9c7c7f37d195688d0df56f7056e9580e4f40c3583834b12366199b77798f35
MD5 57f2cfa551db059bea4a01ad9aab1c5d
BLAKE2b-256 2db3891eb302e7bb037b308cd2960ba0f762fa1e95f574c1ed810b23c86326a1

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page