From d9a9b44e6de4d8b5326317432c91c7f6508269f7 Mon Sep 17 00:00:00 2001 From: Santos Gallegos Date: Thu, 8 Jul 2021 23:35:53 -0500 Subject: [PATCH] Playground: check for nodes out of range (EOF) The playground will try to set the cursor to an invalid position (nvim_win_set_cursor) if the node starts at the EOF mark. ```ruby def run a = <<~EOF end ``` --- lua/nvim-treesitter-playground/internal.lua | 7 +++++++ lua/nvim-treesitter-playground/utils.lua | 9 +++++++++ 2 files changed, 16 insertions(+) diff --git a/lua/nvim-treesitter-playground/internal.lua b/lua/nvim-treesitter-playground/internal.lua index 0dc6e47..3142d6d 100644 --- a/lua/nvim-treesitter-playground/internal.lua +++ b/lua/nvim-treesitter-playground/internal.lua @@ -450,6 +450,13 @@ function M.highlight_node(bufnr) end local start_row, start_col, _ = node:start() + local last_row, last_col = utils.get_end_pos(bufnr) + -- Set the cursor to the last column + -- if the node starts at the EOF mark. + if start_row > last_row then + start_row = last_row + start_col = last_col + end M.highlight_nodes(bufnr, { node }) diff --git a/lua/nvim-treesitter-playground/utils.lua b/lua/nvim-treesitter-playground/utils.lua index b8ae13c..b69fbaf 100644 --- a/lua/nvim-treesitter-playground/utils.lua +++ b/lua/nvim-treesitter-playground/utils.lua @@ -60,4 +60,13 @@ function M.node_contains(node, range) return start_fits and end_fits end +--- Returns a tuple with the position of the last line and last column (0-indexed). +function M.get_end_pos(bufnr) + local bufnr = bufnr or api.nvim_get_current_buf() + local last_row = api.nvim_buf_line_count(bufnr) - 1 + local last_line = api.nvim_buf_get_lines(bufnr, last_row, last_row + 1, true)[1] + local last_col = #last_line + return last_row, last_col +end + return M