diff --git a/doc/ale.txt b/doc/ale.txt index 95ecb33e..4831da79 100644 --- a/doc/ale.txt +++ b/doc/ale.txt @@ -4498,7 +4498,8 @@ ale#Has(feature) *ale#Has()* `ale#Has('ale-x.y.z')`, such as `ale#Has('ale-2.4.0')`. -ale#Pad(string) *ale#Pad()* +ale.pad(str) *ale.pad()* +ale#Pad(str) *ale#Pad()* Given a string or any |empty()| value, return either the string prefixed with a single space, or an empty string. This function can be used to build diff --git a/lua/ale/init.lua b/lua/ale/init.lua index 0723997f..e8631186 100644 --- a/lua/ale/init.lua +++ b/lua/ale/init.lua @@ -64,6 +64,21 @@ ale.has = function(feature) return vim.fn["ale#Has"](feature) == 1 end +---Prefix a string with a single space if it is not empty. +---nil will be treated the same as an empty string. +--- +---This function is a convenience for chaining options for commands together +---without adding redundant whitespace. +---@param str string|nil A value to pad with whitespace. +---@return string padded A value padded with whitespace. +ale.pad = function(str) + if str == nil or str == "" then + return "" + end + + return " " .. str +end + ---Get an ALE variable for a buffer (first) or globally (second) ---@param buffer number The buffer number to retreive the variable for. ---@param variable_name string The variable to retrieve. diff --git a/test/lua/ale_pad_spec.lua b/test/lua/ale_pad_spec.lua new file mode 100644 index 00000000..28f52469 --- /dev/null +++ b/test/lua/ale_pad_spec.lua @@ -0,0 +1,13 @@ +local eq = assert.are.same +local ale = require("ale") + +describe("ale.pad", function() + it("should pad non-empty strings", function() + eq(" foo", ale.pad("foo")) + end) + + it("should return empty strings for nil or empty strings", function() + eq("", ale.pad(nil)) + eq("", ale.pad("")) + end) +end)