Skip to content

Decoration sample update for Lezer complex node structure #210

@Randy-Chuang

Description

@Randy-Chuang

https://docs.obsidian.md/Plugins/Editor/Decorations

After testing, I found that one line of Markdown note will be converted into multiple nodes (things like list-1, list-1_trailing_space, and list-1_string_url). Even a single list-x node may appear multiple times. Hence, I suggest updating the sample code to conform to the complex rendering behavior in practice.

Original code snippet:

        enter(node) {
          if (node.type.name.startsWith('list')) {
            // Position of the '-' or the '*'.
            const listCharFrom = node.from - 2;

            builder.add(
              listCharFrom,
              listCharFrom + 1,
              Decoration.replace({
                widget: new EmojiWidget(),
              })
            );
          }
        },
Image

Modified code snippet:

		const handledLines = new Set<number>();

		for (let { from, to } of view.visibleRanges) {
			syntaxTree(view.state).iterate({
				from,
				to,
				enter(node) {
					try {
						if (node.type.name.match('^list-[1-9]$')) {
							const line = view.state.doc.lineAt(node.from); 
							if(!line.text.trim().startsWith('- ') && !line.text.trim().startsWith('* ')){
								return;
							}

							if(handledLines.has(line.number)){
								return;
							}
							handledLines.add(line.number);

							// Calculate leading spaces for Markdown list indentation.
							let leadingSpace = line.text.length - line.text.trimStart().length;
							const markerPos = line.from + leadingSpace;

							builder.add(
								markerPos,
								markerPos + 1,
								Decoration.widget({ widget: new EmojiWidget() })
							);
						}
					} catch (e) {
					}
				},
			});
		}
Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions