# Easily track & remove content with decorations

**URL:** <https://discuss.codemirror.net/t/easily-track-remove-content-with-decorations/4606>\
**Category:** v6\
**Created:** [June 23, 2022, 1:42pm UTC](https://discuss.codemirror.net/t/easily-track-remove-content-with-decorations/4606 "2022-06-23T13:42:40Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![shshaw](https://discuss.codemirror.net/user_avatar/discuss.codemirror.net/shshaw/32/2184_2.png) [@shshaw](https://discuss.codemirror.net/u/shshaw)\
**Post date:** [June 23, 2022, 1:42pm UTC](https://discuss.codemirror.net/t/easily-track-remove-content-with-decorations/4606/1 "2022-06-23T13:42:40Z")

</div>

Say I have a setup like the Chrome DevTools Console, where individual entries are added and can be removed via limits (only render last 50 logs) or something like `console.clear()`.

**What’s the proper way to add an entry and track its position so it can be removed?**

Adding an entry should:

- Insert a value at the end of the document
- Optionally apply decorations (a mark and/or line decorations covering multiple lines)

Removing an entry should:

- Remove that value
- Remove any decorations
- Update ranges of other entries??

Previously in CodeMirror 5, I used Bookmarks to help track the positions for later removal, and the line classes / line widgets were easy to manage.

The basics of CodeMirror 6 are really tough to get into. It’s really hard to figure out the right types and methods to use in the API.

I’ve referenced docs on `RangeSets`/`StateFields`, the examples for decorations, and various topics in the forum, but there are so many new concepts in CM6 that I’m at a loss for the “proper” way to insert and track all this data.

- [CodeMirror Decoration Example](https://codemirror.net/examples/decoration/#underlining-command)
- [CodeMirror Zebra Stipes Example](https://codemirror.net/examples/zebra/)
- [How to add `Decoration.line()` for multiple lines at once? - #3 by Danon](https://discuss.codemirror.net/t/how-to-add-decoration-line-for-multiple-lines-at-once/4156/3)

Here’s a variant of the approach I’ve been trying based on what I’ve found.

```auto
const addConsoleEntry = StateEffect.define();
// Should I use a `StateField` or a `RangeSet` for these entries?
const consoleEntriesField = StateField.define({
  // Do I need a `create` or `provide` functions? What value should they return?
  update(consoleEntries, tr) {
    consoleEntries = consoleEntries.map(tr.changes);
    for (let e of tr.effects) {
      if (e.is(addConsoleEntry)) {
        let log = e.value;
        let from = tr.state.doc.length;
        // Can I inject a value into the doc from here, or is that not allowed in `StateEffects` since this transaction may already have `changes`?
        // Once I've injected the value, do I add a `Range` to `consoleEntries` to track this value?
        consoleEntries = consoleEntries.update({
          add: [Range({ from, to, value })],
        });

          // Loop through lines and add decorations
          for (let pos = from; pos <= end; ) {
            let line = tr.state.doc.lineAt(pos);
            consoleEntries = consoleEntries.update({
              add: [consoleLineDecoration.range(line.from)],
            });
            // Next line
            pos = line.to + 1;
          }
      }
    }
    return consoleEntries;
  },
});

function addConsoleLog(view, log) {
  let effects = [addConsoleEntry.of(log)];

  // Ensure that the necessary extensions are added.
  if (!view.state.field(consoleEntriesField, false)) {
    effects.push(
      StateEffect.appendConfig.of([consoleEntriesField, consoleEntriesTheme])
    );
  }

  view.dispatch({
    // Do I have to make the `changes` of inserting the value here, and not in the effect?
    effects,
  });

  // How can I reference this exact entry to remove it?
}

```

---

<div class="post-metadata">

**Author:** ![marijn](https://discuss.codemirror.net/user_avatar/discuss.codemirror.net/marijn/32/136_2.png) [@marijn](https://discuss.codemirror.net/u/marijn)\
**Post date:** [June 23, 2022, 2:57pm UTC](https://discuss.codemirror.net/t/easily-track-remove-content-with-decorations/4606/2 "2022-06-23T14:57:23Z")

</div>

The way to do something like bookmarks would be to create a state field that tracks the positions you are interested in, and on any transaction where `!tr.changes.empty`, map all those positions to their new equivalent with `tr.changes.mapPos`. Using a range set might be an optimization for this (it is more clever about mapping large numbers of positions without looking at every single one of them).

---

<div class="post-metadata">

**Author:** ![shshaw](https://discuss.codemirror.net/user_avatar/discuss.codemirror.net/shshaw/32/2184_2.png) [@shshaw](https://discuss.codemirror.net/u/shshaw)\
**Post date:** [June 23, 2022, 5:01pm UTC](https://discuss.codemirror.net/t/easily-track-remove-content-with-decorations/4606/4 "2022-06-23T17:01:29Z")

</div>

Thanks for the response.

Storing data as a `RangeSet` makes (theoretical) sense. However, even after spending a week steeped in the CodeMirror 6 docs, I constantly find myself struggling with the practical implementation.

For example: You recommend using `RangeSet`.

1. There aren’t any direct [examples](https://codemirror.net/examples/) of `RangeSet` I can find, so…
2. I go to the [`RangeSet` Docs](https://codemirror.net/docs/ref/#state.RangeSet)
3. Dig through dozen or more methods to even see the ways to create a `RangeSet`.
4. It’s still unclear if I should use `new RangeSet()`, `RangeSet.of()`, `RangeSet.empty`, or if I need to use the completely separate `RangeSetBuilder`.

After all of that, I still have to figure out:

1. How to integrate that into `StateField`
2. How to properly store data in the `RangeSet` and `StateField`
3. How to loop through the `RangeSet` to update the position with `tr.changes.mapPos`
4. How to get that data back and use it to remove a range of the document.

I’m not complaining about having to learn new concepts, but there are so many disparate concepts/types and so few examples that really showcase how these concepts are supposed to work individually or together.

Some of that will come with time and community, but if there are parts of the documentation or codebase I might be missing that help with understanding how to implement or use them, do let me know.

Noting other discussions for reference:

> [@Where to start](https://discuss.codemirror.net/t/where-to-start/4527/15):
>
> This resonates with my experience learning CM6 too. I would describe it something like this: In addition to CM6, I’ve used a number of other libraries/frameworks for text editing, for UI, and etc. They often share similar ideas for how to structure code and expose levers for making your own editing experience. As a result, I’ve built up a number of code architectures/approaches to doing certain kinds of tasks with text editors that I can usually apply in some fashion, no matter the text editor …

> [@RangeSet with metadata and different decorations](https://discuss.codemirror.net/t/rangeset-with-metadata-and-different-decorations/3874):
>
> Hello. Please help to understand the best way to create a RangeSet with Ranges that contain metadata (e.g., variable or object) together with a state. This state would define behaviour and decoration logic. The flow is the following: The hotkey creates a new Range with some metadata (and a state from 3-5 predefined states). Based on user’s input the state would change (or delete it in some cases). Based on state the Range is decorated differently (applying Mark, collapsed, etc.). I understa…

> [@Keep track of ranges when changing content](https://discuss.codemirror.net/t/keep-track-of-ranges-when-changing-content/4462):
>
> Hello, Let’s say I have the following content: \<some-element\> \<some-child some-attr="foo" another-attr="bar" /\> \</some-element\> I am obviously able to parse this and get a data structure that represents this document in memory. I would like to attach some ranges to objects representing this document. For example, the value of some-attr starts at 42 and ends at 45, so I attach the range [42-45] to the object representing some-attr in memory. My question is: how to keep track of subsequent…

---

<div class="post-metadata">

**Author:** ![marijn](https://discuss.codemirror.net/user_avatar/discuss.codemirror.net/marijn/32/136_2.png) [@marijn](https://discuss.codemirror.net/u/marijn)\
**Post date:** [June 23, 2022, 5:34pm UTC](https://discuss.codemirror.net/t/easily-track-remove-content-with-decorations/4606/5 "2022-06-23T17:34:17Z")

</div>

> [@shshaw](#):
>
> It’s still unclear if I should use `new RangeSet()`, `RangeSet.of()`, `RangeSet.empty`, or if I need to use the completely separate `RangeSetBuilder`.

Since the constructor isn’t in the docs (and thus private), use `of` or `empty` depending on whether you want an empty set. As its documentation states, `RangeSetBuilder` is an optimization for building sets quickly.

I know there’s a lot going on in the library, but I don’t really think you can expect writing custom extensions to be some kind of no-brainer. You’re going to have to learn and combine concepts, and that’s okay.

> [@shshaw](#):
>
> How to integrate that into `StateField`

Put it in the state field. That’s what state fields do, they hold data.

> [@shshaw](#):
>
> How to properly store data in the `RangeSet` and `StateField`

Attach information about what you’re doing to a transaction (probably as a `StateEffect`) and update your rangeset with its `update` method when it sees a transaction like that.

> [@shshaw](#):
>
> How to loop through the `RangeSet` to update the position with `tr.changes.mapPos`

See [`RangeSet.map`](https://codemirror.net/docs/ref/#state.RangeSet.map).

> [@shshaw](#):
>
> How to get that data back and use it to remove a range of the document.

[`RangeSet.between`](https://codemirror.net/docs/ref/#state.RangeSet.between).

---

<div class="post-metadata">

**Author:** ![shshaw](https://discuss.codemirror.net/user_avatar/discuss.codemirror.net/shshaw/32/2184_2.png) [@shshaw](https://discuss.codemirror.net/u/shshaw)\
**Post date:** [June 23, 2022, 10:04pm UTC](https://discuss.codemirror.net/t/easily-track-remove-content-with-decorations/4606/6 "2022-06-23T22:04:48Z")

</div>

> [@marijn](#):
>
> I know there’s a lot going on in the library, but I don’t really think you can expect writing custom extensions to be some kind of no-brainer. You’re going to have to learn and combine concepts, and that’s okay.

Of course. I’m trying to invest the time to understand it. Just a bit tough to pull all these concepts together.

Thanks for the additional clarifications.
