local D={string={}}function D.string.trim(D)return string.match(D,"\094\037\115\042\040\046-\041\037\115\042\036")end function D.string.startswith(D,o,m)local c=1 return string.find(D,o,c,m)==c end function D.string.endswith(D,o,m)local c=(#D-#o)+1 return string.find(D,o,c,m)==c end function D.addTagsAroundSelection(o,m,c,f)if m==-1 or c==-1 then return o.Text end local R,K=string.format("\060\037\115\062",f),string.format("\060\047\037\115\062",f)local C=string.sub(o.Text,math.min(m,c),math.max(m,c)-1)local B=D.string.trim(C)if D.string.startswith(B,R)and D.string.endswith(B,K)then C=(C:gsub(R,"")):gsub(K,"")else C=R..(C..K)end local t=string.sub(o.Text,0,math.min(m,c)-1)local n=t:len()+1 t..=C local k=t:len()+1 t..=string.sub(o.Text,math.max(m,c))return t,n,k end return D
local Utilities = {
  string = {}
}

function Utilities.string.trim(str)
  return string.match(str, '^%s*(.-)%s*$')
end

function Utilities.string.startswith(str, pattern, plain)
	local start = 1
	return string.find(str, pattern, start, plain) == start
end

function Utilities.string.endswith(str, pattern, plain)
	local start = #str - #pattern + 1
	return string.find(str, pattern, start, plain) == start
end

function Utilities.addTagsAroundSelection(guiItem, cursorPosition, selectionStart, tag)
  if cursorPosition == -1 or selectionStart == -1 then return guiItem.Text end

  local startTag, endTag = string.format('<%s>', tag), string.format('</%s>', tag)

  local selectedText = string.sub(guiItem.Text, math.min(cursorPosition, selectionStart), math.max(cursorPosition, selectionStart) - 1)
  local trimmedSelectedText = Utilities.string.trim(selectedText)

  if Utilities.string.startswith(trimmedSelectedText, startTag) and Utilities.string.endswith(trimmedSelectedText, endTag) then
    selectedText = selectedText:gsub(startTag, ""):gsub(endTag, "")
  else
    selectedText = startTag .. selectedText .. endTag
  end

  local text = string.sub(guiItem.Text, 0, math.min(cursorPosition, selectionStart) - 1)
  local startPosition = text:len() + 1
  text ..= selectedText
  local endPosition = text:len() + 1
  text ..= string.sub(guiItem.Text, math.max(cursorPosition, selectionStart))

  return text, startPosition, endPosition
end

return Utilities