Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,13 @@
}
},
"configurationDefaults": {
"[html]": {
"codeBlocks.queries": [
"(element (start_tag)) @item",
"(text) @item",
"(element (end_tag)) @item"
]
},
"[github-actions-workflow]": {
"codeBlocks.npmPackageName": "@tree-sitter-grammars/tree-sitter-yaml",
"codeBlocks.parserName": "tree-sitter-yaml"
Expand Down
1 change: 0 additions & 1 deletion src/FileTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,6 @@ export class FileTree implements vscode.Disposable {
break;
}
case "swap-next": {
// TODO: if block mode, resolve previous block
const nextSelection = selection.getNext(blocks);
if (!nextSelection) {
return err(`Can't move to ${direction}, next node of selection is null`);
Expand Down
64 changes: 39 additions & 25 deletions src/Selection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,56 +62,70 @@
const parent = this.firstNode().parent;
const range = this.getRange();

let smallestBlockIndex: number | undefined = undefined;
let smallestBlock: Block | undefined = undefined;
let smallestBlockLength: number | undefined = undefined;
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];

const blockRange = {
startIndex: block[0].startIndex,
endIndex: block[block.length - 1].endIndex,
};
for (const block of blocks) {
const startIndex = block[0].startIndex;
const endIndex = block[block.length - 1].endIndex;

// check if block contains selection
if (blockRange.startIndex <= range.startIndex && range.endIndex <= blockRange.endIndex) {
const contains = startIndex <= range.startIndex && range.endIndex <= endIndex;
if (contains) {
// check if block is at the same hierarchy level as the selection
if (
const isSibling =
(parent === null && block[0].parent === null) ||
(block[0].parent !== null && parent === block[0].parent)
) {
const length = blockRange.endIndex - blockRange.startIndex;
(block[0].parent !== null &&
parent?.startIndex === block[0].parent.startIndex &&
parent?.endIndex === block[0].parent.endIndex);

Check warning on line 79 in src/Selection.ts

View workflow job for this annotation

GitHub Actions / test (macos-latest)

Unnecessary optional chain on a non-nullish value

Check warning on line 79 in src/Selection.ts

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Unnecessary optional chain on a non-nullish value

Check warning on line 79 in src/Selection.ts

View workflow job for this annotation

GitHub Actions / test (windows-latest)

Unnecessary optional chain on a non-nullish value

Check warning on line 79 in src/Selection.ts

View workflow job for this annotation

GitHub Actions / test (macos-latest)

Unnecessary optional chain on a non-nullish value

Check warning on line 79 in src/Selection.ts

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest)

Unnecessary optional chain on a non-nullish value

Check warning on line 79 in src/Selection.ts

View workflow job for this annotation

GitHub Actions / test (windows-latest)

Unnecessary optional chain on a non-nullish value

if (isSibling) {
const length = endIndex - startIndex;
if (length <= (smallestBlockLength ?? length)) {
smallestBlockIndex = i;
smallestBlock = block;
smallestBlockLength = length;
}
}
}
}

if (smallestBlockIndex !== undefined) {
const smallestBlock = blocks[smallestBlockIndex];
this.selectedSiblings = smallestBlock;
if (smallestBlock === undefined) {
return this;
}

this.selectedSiblings = smallestBlock;
return this;
}

public getPrevious(blocks: Block[] | undefined): Selection | undefined {
const previousNode = this.selectedSiblings[0].previousNamedSibling;
if (previousNode) {
return new Selection([previousNode], this.version).expandToBlock(blocks);
} else {
if (!previousNode) {
return undefined;
}

const previous = Selection.fromNode(previousNode, this.version).expandToBlock(blocks);
const parent = this.getParent(blocks)?.toVscodeSelection();

if (parent !== undefined && previous.toVscodeSelection().isEqual(parent)) {
return undefined;
}

return previous;
}

public getNext(blocks: Block[] | undefined): Selection | undefined {
const nextNode = this.selectedSiblings.at(-1)?.nextNamedSibling;
if (nextNode) {
return new Selection([nextNode], this.version).expandToBlock(blocks);
} else {
if (!nextNode) {
return undefined;
}

const next = Selection.fromNode(nextNode, this.version).expandToBlock(blocks);
const parent = this.getParent(blocks)?.toVscodeSelection();

if (parent !== undefined && next.toVscodeSelection().isEqual(parent)) {
return undefined;
}

return next;
}

public getParent(blocks: Block[] | undefined): Selection | undefined {
Expand All @@ -128,7 +142,7 @@
}

if (parent) {
return new Selection([parent], this.version).expandToBlock(blocks);
return Selection.fromNode(parent, this.version).expandToBlock(blocks);
} else {
return undefined;
}
Expand All @@ -148,7 +162,7 @@
}

if (child) {
return new Selection([child], this.version).expandToBlock(blocks);
return Selection.fromNode(child, this.version).expandToBlock(blocks);
} else {
return undefined;
}
Expand Down
24 changes: 24 additions & 0 deletions src/test/suite/BlockTrees.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,30 @@ suite("BlockTrees", function () {
return void vscode.window.showInformationMessage("Start blockTrees.getBlockTrees tests");
});

test("resolves html blocks", async function () {
const text = "<parent>\n <child1></child1>\n <child2></child2>\n</parent>";
const { fileTree } = await openDocument(text, "html");
const lang = fileTree.parser.getLanguage() as Language;
const queries = [new Query(lang, "(element) @item")];
const blocksTrees = getBlockTrees(fileTree.tree, queries);

expect("\n" + blockTreesToString(text, blocksTrees)).to.equal(`
+------------------------+
| <parent> |
| |
| +-------------------+ |
| | <child1></child1> | |
| | | |
| +-------------------+ |
| +-------------------+ |
| | <child2></child2> | |
| +-------------------+ |
| |
| </parent> |
+------------------------+
`);
});

test("resolves sequential blocks", async function () {
const text = "fn foo() {}\nfn bar() {}";
const { fileTree } = await openDocument(text, "rust");
Expand Down
33 changes: 25 additions & 8 deletions src/test/suite/Selection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,42 @@ suite("Selection", function () {
}

for (const update of updates) {
selection.update(update, []);
selection.update(update, fileTree.blocks);
}

const selectionText = selection.getText(content);

return selectionText;
}

suite(".getPrevious", function () {
test("Ignores previous nodes that start with parent", async () => {
const text = "<parent><child>@1</child><child>2</child></parent>";

expect(await selectionAt("html", text)).to.equal("1");
expect(await selectionAt("html", text, ["parent"])).to.equal("<child>1</child>");
expect(await selectionAt("html", text, ["parent", "add-previous"])).to.equal("<child>1</child>");
});
});

suite(".getNext", function () {
test("Ignores next nodes that start with parent", async () => {
const text = "<parent><child>1</child><child>@2</child></parent>";

expect(await selectionAt("html", text)).to.equal("2");
expect(await selectionAt("html", text, ["parent"])).to.equal("<child>2</child>");
expect(await selectionAt("html", text, ["parent", "add-next"])).to.equal("<child>2</child>");
});
});

suite(".update", function () {
test("Select source_file node is undefined", async () => {
expect(await selectionAt("rust", "fn main() { }@")).to.be.undefined;
});

test("Update selection parent/child", async () => {
expect(await selectionAt("rust", "fn main() { @ }")).to.equal("{ }");
expect(await selectionAt("rust", "fn main() { @ }", ["parent"])).to.equal("fn main() { }");
expect(await selectionAt("rust", "fn main() { @ }", ["parent", "child"])).to.equal("main");
test.only("Update selection parent/child", async () => {
expect(await selectionAt("rust", "fn foo() { fn nested() { @ } }")).to.equal("fn nested() { }");
expect(await selectionAt("rust", "fn main() { @ }")).to.equal("fn main() { }");
expect(await selectionAt("rust", "if true { @ }", ["parent"])).to.equal("if true { }");
expect(await selectionAt("rust", "if true { @ }", ["parent", "child"])).to.equal("true");
expect(
Expand All @@ -64,9 +83,7 @@ suite("Selection", function () {

test("Update selection parent/child", async () => {
const text = "function main() { @ }";
expect(await selectionAt("typescriptreact", text)).to.equal("{ }");
expect(await selectionAt("typescriptreact", text, ["parent"])).to.equal("function main() { }");
expect(await selectionAt("typescriptreact", text, ["parent", "child"])).to.equal("main");
expect(await selectionAt("typescriptreact", text)).to.equal("function main() { }");
});

test("Update selection previous/next", async () => {
Expand Down
8 changes: 4 additions & 4 deletions src/test/suite/extension.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,17 +214,17 @@ source_file [0:0 - 0:12]
await testSelectionCommands({
content: "<> <p>@a</p> </>",
selectionCommands: ["codeBlocks.selectPrevious"],
expectedSelectionContent: "<p>a",
expectedSelectionContent: "a",
language: "typescriptreact",
});
});
});

suite(".selectChild", function () {
test("contracts to first named child", async () => {
test.only("contracts to first named child", async () => {
await testSelectionCommands({
content: "pub fn foo() { @ }",
selectionCommands: ["codeBlocks.selectParent", "codeBlocks.selectChild"],
content: "pub fn foo() { fn nested() { @ } }",
selectionCommands: ["codeBlocks.selectBlock"],
expectedSelectionContent: "pub",
});
await testSelectionCommands({
Expand Down
21 changes: 21 additions & 0 deletions test-parsers/tree-sitter-html/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2014 Max Brunsfeld

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
21 changes: 21 additions & 0 deletions test-parsers/tree-sitter-html/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# tree-sitter-html

[![CI][ci]](https://github.com/tree-sitter/tree-sitter-html/actions/workflows/ci.yml)
[![discord][discord]](https://discord.gg/w7nTvsVJhm)
[![matrix][matrix]](https://matrix.to/#/#tree-sitter-chat:matrix.org)
[![crates][crates]](https://crates.io/crates/tree-sitter-html)
[![npm][npm]](https://www.npmjs.com/package/tree-sitter-html)
[![pypi][pypi]](https://pypi.org/project/tree-sitter-html)

HTML grammar for [tree-sitter](https://github.com/tree-sitter/tree-sitter).

References

- [The HTML5 Spec](https://www.w3.org/TR/html5/syntax.html)

[ci]: https://img.shields.io/github/actions/workflow/status/tree-sitter/tree-sitter-html/ci.yml?logo=github&label=CI
[discord]: https://img.shields.io/discord/1063097320771698699?logo=discord&label=discord
[matrix]: https://img.shields.io/matrix/tree-sitter-chat%3Amatrix.org?logo=matrix&label=matrix
[npm]: https://img.shields.io/npm/v/tree-sitter-html?logo=npm
[crates]: https://img.shields.io/crates/v/tree-sitter-html?logo=rust
[pypi]: https://img.shields.io/pypi/v/tree-sitter-html?logo=pypi&logoColor=ffd242
30 changes: 30 additions & 0 deletions test-parsers/tree-sitter-html/binding.gyp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"targets": [
{
"target_name": "tree_sitter_html_binding",
"dependencies": [
"<!(node -p \"require('node-addon-api').targets\"):node_addon_api_except",
],
"include_dirs": [
"src",
],
"sources": [
"bindings/node/binding.cc",
"src/parser.c",
"src/scanner.c",
],
"conditions": [
["OS!='win'", {
"cflags_c": [
"-std=c11",
],
}, { # OS == "win"
"cflags_c": [
"/std:c11",
"/utf-8",
],
}],
],
}
]
}
20 changes: 20 additions & 0 deletions test-parsers/tree-sitter-html/bindings/node/binding.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <napi.h>

typedef struct TSLanguage TSLanguage;

extern "C" TSLanguage *tree_sitter_html();

// "tree-sitter", "language" hashed with BLAKE2
const napi_type_tag LANGUAGE_TYPE_TAG = {
0x8AF2E5212AD58ABF, 0xD5006CAD83ABBA16
};

Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports["name"] = Napi::String::New(env, "html");
auto language = Napi::External<TSLanguage>::New(env, tree_sitter_html());
language.TypeTag(&LANGUAGE_TYPE_TAG);
exports["language"] = language;
return exports;
}

NODE_API_MODULE(tree_sitter_html_binding, Init)
9 changes: 9 additions & 0 deletions test-parsers/tree-sitter-html/bindings/node/binding_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/// <reference types="node" />

const assert = require("node:assert");
const { test } = require("node:test");

test("can load grammar", () => {
const parser = new (require("tree-sitter"))();
assert.doesNotThrow(() => parser.setLanguage(require(".")));
});
28 changes: 28 additions & 0 deletions test-parsers/tree-sitter-html/bindings/node/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
type BaseNode = {
type: string;
named: boolean;
};

type ChildNode = {
multiple: boolean;
required: boolean;
types: BaseNode[];
};

type NodeInfo =
| (BaseNode & {
subtypes: BaseNode[];
})
| (BaseNode & {
fields: { [name: string]: ChildNode };
children: ChildNode[];
});

type Language = {
name: string;
language: unknown;
nodeTypeInfo: NodeInfo[];
};

declare const language: Language;
export = language;
7 changes: 7 additions & 0 deletions test-parsers/tree-sitter-html/bindings/node/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const root = require("path").join(__dirname, "..", "..");

module.exports = require("node-gyp-build")(root);

try {
module.exports.nodeTypeInfo = require("../../src/node-types.json");
} catch (_) {}
Loading
Loading