Skip to content

Commit db177ec

Browse files
committed
添加STRING.trimIndent方法,解决inline多行字符串的前置空格问题
1 parent 7e6405e commit db177ec

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

stringExtend.lua

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,35 @@ function STRING.trim(str)
193193
return match(str,"^%s*(.-)%s*$") or ""
194194
end
195195

196+
---Trim spaces and tabs at the beginning of all lines, useful for inline multi-line strings
197+
---## Example
198+
---```lua
199+
---do
200+
--- local s=STRING.trimIndent[=[
201+
--- Hello
202+
--- World
203+
--- ]=] --> "Hello\nWorld\n", not " Hello\n World\n "
204+
---end
205+
---```
206+
---@param str string
207+
---@param keep? boolean|number `true`: keep some indent based on 1st line; [number] trim specific number of spaces
208+
---@return string
209+
function STRING.trimIndent(str,keep)
210+
if keep then
211+
local list=STRING.split(str,'\n')
212+
local s=type(keep)=='number' and keep+1 or #list[1]:match('^%s*')+1
213+
if s==1 then return str end
214+
215+
for i=1,#list do
216+
print(i,min(s,find(list[i],'%S') or #list[i]+1))
217+
list[i]=sub(list[i],min(s,find(list[i],'%S') or #list[i]+1))
218+
end
219+
return table.concat(list,'\n')
220+
else
221+
return (gsub('\n'..str,'\n[ \t]+','\n'):sub(2))
222+
end
223+
end
224+
196225
---Get string before pattern
197226
---@param str string
198227
---@param sep string

0 commit comments

Comments
 (0)