Skip to content
This repository was archived by the owner on Dec 15, 2022. It is now read-only.

Add Display Layers to transform text for display on screen - #149

Merged
as-cii merged 265 commits into
masterfrom
display-layers
May 4, 2016
Merged

as-cii merged 265 commits into
masterfrom
display-layers

Conversation

@nathansobo

Copy link
Copy Markdown
Contributor

This PR introduces a major new feature to this library called "display layers".

Until now, text-buffer has handled all logic related to the contents of text files as they are represented on disk. Line breaks were interpreted to present a row/column coordinate space in various APIs, but the task of performing additional transformations required to present a buffer's contents on screen in a text editor were left to users of the library.

A viable text editor can't simply render the raw contents of each line as it appears in the buffer. To start with, hard tabs are represented as individual control characters in the buffer, but need to be expanded to multiple spaces when presented on screen based on their location in the line relative to the next tab stop. Soft wraps introduce line breaks and leading whitespace on screen that don't exist in the file, and folds do the opposite, removing fragments of text from what we ultimately present on screen. Then there are other details such as atomic soft tabs, invisible character glyphs, and indent guides, all of which are computed based on the content of the underlying buffer.

These transformations interleave with a couple of different concerns. First, there is spatial handling. In order to mutate the file in the correct location based on the current selection, we need to efficiently translate between a row/column in the displayed content and the corresponding row/column in the underlying buffer. We also need to clip positions. It's illegal to place your cursor in the middle of a hard tab or within the synthetic indent of a soft-wrapped line, so we need to efficiently recognize such placements as invalid and clip to the nearest valid positions.

The second major intertwined concern is syntax highlighting and text decoration in general. Parsers operate on the raw, untransformed character stream, yet syntax highlighting demands that we efficiently combine syntactic scopes denoted in untransformed coordinates with the transformed content that actually appears on screen.

Basic API

The new display layer abstraction is designed to address all of these concerns efficiently and bundle them into a convenient package. Here's a demo of usage:

let layer = buffer.addDisplayLayer({
  tabLength: 1,
  invisibles: {space: '•', cr: '¤', eol: '¬'},
  softWrapColumn: 80,
  foldCharacter: '⋯'
})

// Fold arbitrary ranges
layer.foldBufferRange([[1, 2], [3, 4]])

// Translate and clip points
layer.translateScreenPosition([3, 4])
layer.clipScreenPosition([3, 4])
layer.translateBufferPosition([1, 2])

// Get transformed text
layer.getText()

// Get line objects for a row range to render on screen.
// These are represented in an "interesting" format for storage efficiency.
layer.getScreenLines(0, 5)

Text Decoration Layers

There's also a mechanism to plug in a text decoration layer that can weave start and end "tags" into the content of the display layer. These tags are included in the data returned by getScreenLines and can be used to create the appropriate nested span tags to render a syntax-highlighted line.

Text decoration layers are just objects that support the following interface:

  • getIterator This returns an iterator that walks over tag boundaries. Every time a syntactic scope opens or closes, this iterator yields a value. Its interface looks like this:
    • seek(position) Jump to the iterator to the first boundary greater than or equal to the given position. Return an array of all tags containing the given position.
    • moveToSuccessor Jumps to the next boundary.
    • getPosition Get the position of the current boundary.
    • getCloseTags Get the tags closing at the current boundary.
    • getOpenTags Get the tags opening at the current boundary.
  • getInvalidatedRanges This is called by the display layer whenever it is processing a buffer change. Eventually it will pass a set of changes to the text decoration layer so it can maintain its state without subscribing to buffer changes. For now it is called with no arguments.
  • onDidInvalidateRange This is optional, and can be used to inform the display layer of asynchronous changes to the text decorations. We use this to notify the display layer of a chunk of work being completed when we break tokenization up over multiple requestIdleCallbacks.

We currently only support a single text decoration layer via DisplayLayer.prototype.setTextDecorationLayer. This will be used in Atom to perform syntax highlighting. However, in the future it should be straightforward to allow multiple text decoration layers, which could simplify the implementation of packages that need to style runs of text in specific ways instead of just highlighting them with absolutely positioned divs. An example of such a package is pigments by @abe33.

Screen Lines

The interface of the position translation methods is obvious. Less obvious is our representation of screen lines. For now, this API is entirely internal to Atom, so we left it fairly raw. When you request a row range via getScreenLines, you're returned an array of screen line objects. Each object has the following fields:

  • id This uniquely identifies the line by text and decoration content. If either changes, you'll get a new line with a new id. This is vital for DOM diffing.
  • lineText This is the transformed text of the line as it appears on screen.
  • tagCodes Here's the weird one. This is an array of integers in a specific format that describes the location of open tags and close tags in the line. We interpret this array in Atom to build up the DOM tree representing the line.

Tag Codes

Screen lines are cached internally, so it's important that they have a compact representation. Since this API will only be exposed internally, we didn't take too many pains to abstract this representations. Just some basic helper methods on the display layer. Integers in the array of tagCodes are interpreted as follows:

  • negative, odd: An open tag. Begins a new scope. Perform a lookup via DisplayLayer.prototype.tagForCode to translate to the string name of a tag. You can use DisplayLayer.protottype.isCloseTagCode to determine if an integer represents a close tag without mucking with %.
  • negative, even: Close tag. Ends a scope. Again, use tagForCode if you want to know the name of the closed scope. You can use DisplayLayer.protottype.isOpenTagCode to determine if an integer represents an open tag.
  • non-negative: A run of zero or more characters.

So if we assigned integers to tag names in the following way, we would represent a string as follows:

| code | scope name |
|------|------------|
| -1   | js         |
| -3   | keyword    |
| -5   | variable    |
| -7   | assignment |

"var hello = 1"
[-1, -3, 3, -4, 1, -5, 5, -6, 1, -7, 1, -8, 2, -2]

Note that even integers are omitted from the table as they simply close the tag associated with their odd predecessor (-2 closes -1, etc). In the representation above, you can see how open and close tags wrap positive integers representing discrete runs of text. We build a DOM node representing this line by slicing the string at each positive integer and appending children or traversing to parents on the even integers.

Next Steps

There's plenty more to do to make display layers everything they could be. This is a starting point and gives us better folds and more efficient point translation in the presence of folds and soft wraps, but there's still optimization to do.

  • We need to update the display index in a batched way rather than per-keystroke.
  • We need to add the ability to compute display metadata in the background and only synchronously build as much as we need to answer current queries, which are typically constrained to the visible screen range. Synchronous APIs demand that we block if we request information that's not yet computed, so this should get interesting.

I plan on writing a blog post going into more detail on the implementation, but I want to merge this PR before it's done so this was a quick explanation.

Nathan Sobo added 30 commits January 13, 2016 12:19
They don’t require Point instances as arguments, but always return them.
It’s not optimally efficient, because we perform a log(n) containment
query for every marker in the result set. If this proves to be an issue
with large numbers of folds we can revisit building a more direct query
into the index.
Changes that invalidate folds still need to be dealt with.
This replaces an n*log(n) algorithm for eliminated nested folds with a
linear algorithm and avoids repeated querying of the same row range.
This combines the spliceInput that was changing the shape of the patch
with the spliceInput that was clearing away regions on recomputed lines.
Also, make some aesthetic changes to the specs.
@as-cii
as-cii merged commit 47ff74e into master May 4, 2016
@as-cii
as-cii deleted the display-layers branch May 4, 2016 16:53
@colelawrence

Copy link
Copy Markdown

Great work! I'm very excited for these features to bleed into prod.

@lierdakil

Copy link
Copy Markdown

Hmm. Any reason in particular for 9e86db5? I've been using custom marker properties for bulk operations on markers for a while now, so I'm a bit unclear as to how I should transition away from that in a backwards-compatible manner.

@lierdakil

Copy link
Copy Markdown

What I'm trying to say is, TextEditor.findMarkers seems pretty useless without custom properties.

@nathansobo

Copy link
Copy Markdown
Contributor Author

@lierdakil We didn't like the fact that this parameter was a mixed bag of options to the marker such as reversed and arbitrary properties. I'm trying to remember why we thought it was okay to change this, perhaps based on a search of existing usages. Sounds like we missed your package. Despite the commit message and parameter name change, I'm pretty sure this should still work. Since there are usages we missed, perhaps we should consider documenting it and keeping it forever, despite my distaste for this bad decision of mine to mix things together.

@as-cii Can you remember any more context that I missed? Seems like we should just restore this even though I don't think it's actually broken. Just add it back to the docs and maybe test that it works.

@nathansobo

Copy link
Copy Markdown
Contributor Author

@lierdakil I'd recommend using a custom marker layer for bulk operations on markers rather than a distinguishing property such as class, if that's the kind of usage you're referring to.

@lierdakil

Copy link
Copy Markdown

@nathansobo, it's in fact actually broken, at least TextEditor.markBufferPosition is, since MarkerLayer.markPosition ignores any properties except invalidate atom-haskell/ide-haskell#167

I'm pretty much referring to that kind of usage, yes. Problem is, I actually have several distinguishing properties, which are, in some cases, orthogonal, in other cases, hierarchical. Something like class1, class2 and subclass if you will. Custom marker layers don't mix that well with this.

@lierdakil

Copy link
Copy Markdown

At the very least, fixing markPosition to work with a proper deprecation warning would be nice, so that I could make a nice slow transition to marker layers or something.

@nathansobo

nathansobo commented Jul 29, 2016 •

Copy link
Copy Markdown
Contributor Author

@lierdakil I'm very sorry about this. Seems like a bad move on our part and I'll try to be more careful going forward. I'll investigate this and restore the pre-existing behavior.

@lierdakil

Copy link
Copy Markdown

@nathansobo, thank you.

@lierdakil

Copy link
Copy Markdown

@nathansobo, after thinking about this for a bit, I believe Makrer.setProperties is not deprecated, is it? Although this system (Marker.setProperties+MarkerLayer.findMarkers/Marker.matchesParams) seems to suffer from that same problem of mixing reserved and arbitrary identifiers.

@nathansobo

Copy link
Copy Markdown
Contributor Author

@lierdakil Yes, setProperties is still there. The main reason I'm restoring the other approach is that if we decide to change this (and it's not a huge priority honestly) then we should deprecate all of these mixed usages across the API. Planning on releasing today.

@toasty-sunbeam

Copy link
Copy Markdown

The blog post says this patch includes an improved soft-wrapping algorithm. What is the best place to report a bug with the soft-wrapping algorithm? I filed one on Atom but I haven't gotten it looked at yet. I understand if it's not a high priority, but since people have been working on soft-wrap anyway, I was hoping it would be possible to sneak in a quick fix.

@nathansobo

Copy link
Copy Markdown
Contributor Author

@DawnPaladin the improvements had more to do with how we track the location of soft wraps for purposes of translating positions in the buffer to positions on screen. That bug has more to do with how we select the location of a wrap, and is a separate issue. Not saying it isn't worth doing, but it is somewhat unrelated to these changes.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants