From 43cc07cde43e8a4caf6a9c7471f6e3e69e67c242 Mon Sep 17 00:00:00 2001 From: Chen Asraf Date: Thu, 18 May 2023 02:41:33 +0300 Subject: [PATCH] fix: words split --- lua/text-transform/main.lua | 19 +++++++------------ tests/test_into_words.lua | 8 ++++++++ 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/lua/text-transform/main.lua b/lua/text-transform/main.lua index 48e05c7..f9c03b9 100644 --- a/lua/text-transform/main.lua +++ b/lua/text-transform/main.lua @@ -46,15 +46,10 @@ function TextTransform.disable() return S end -local function trim(s) - return s:match("^%s*(.-)%s*$") -end - --- Splits a string into words. function TextTransform.into_words(str) local words = {} local word = "" - str = trim(str) local previous_is_split_token = false for i = 1, #str do @@ -66,15 +61,15 @@ function TextTransform.into_words(str) -- split on uppercase letters or numbers if is_split_token and not previous_is_split_token then if word ~= "" then - table.insert(words, trim(str):lower()) + table.insert(words, word:lower()) end - previous_is_split_token = is_split_token + previous_is_split_token = true word = char -- split on underscores, hyphens, and spaces elseif is_separator then if word ~= "" then - table.insert(words, trim(str):lower()) - previous_is_split_token = is_split_token + table.insert(words, word:lower()) + previous_is_split_token = false end word = "" else @@ -83,7 +78,7 @@ function TextTransform.into_words(str) end end if word ~= "" then - table.insert(words, trim(str):lower()) + table.insert(words, word:lower()) previous_is_split_token = false end return words @@ -231,9 +226,9 @@ function TextTransform.replace_columns(transform) -- get the line of this cursor local line = vim.fn.getline(line_num) -- match the surrounding word using start_col - local word = line:match("[%w%_%-%s%.]+", start_col) + local word = line:match("[%w%_%-%.]+", start_col) -- replace the word with the transformed word - TextTransform.replace_cursor_range(line_num, start_col, start_col + #word - 1, transform) + TextTransform.replace_cursor_range(line_num, start_col, start_col + #word, transform) end end diff --git a/tests/test_into_words.lua b/tests/test_into_words.lua index 9917a07..4d8ccc0 100644 --- a/tests/test_into_words.lua +++ b/tests/test_into_words.lua @@ -57,4 +57,12 @@ T["into_words()"]["should split two words with a number inside"] = function() eq_global(child, "result[3]", "123") end +T["into_words()"]["should split two words and ignore trailing/leading spaces"] = function() + child.lua([[require('text-transform').setup()]]) + child.lua([[result = require('text-transform').into_words(" hello world ")]]) + eq_type_global(child, "result", "table") + eq_global(child, "result[1]", "hello") + eq_global(child, "result[2]", "world") +end + return T