logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

number-inc-dec.lua (1917B)


  1. -- increment/decrement number in dec/hex/oct format
  2. local lexer = vis.lexers
  3. local lpeg = vis.lpeg
  4. if not lexer.load or not lpeg then return end
  5. local Cp = lpeg.Cp()
  6. local dec_num = lpeg.S('+-')^-1 * lexer.dec_num
  7. local pattern = lpeg.P{ Cp * (lexer.hex_num + lexer.oct_num + dec_num) * Cp + 1 * lpeg.V(1) }
  8. local change = function(delta)
  9. local win = vis.win
  10. local file = win.file
  11. local count = vis.count
  12. if not count then count = 1 end
  13. vis.count = nil -- reset count, otherwise it affects next motion
  14. for selection in win:selections_iterator() do
  15. local pos = selection.pos
  16. if not pos then goto continue end
  17. local word = file:text_object_word(pos);
  18. if not word then goto continue end
  19. local data = file:content(word.start, 1024)
  20. if not data then goto continue end
  21. local s, e = pattern:match(data)
  22. if not s then goto continue end
  23. data = string.sub(data, s, e-1)
  24. if #data == 0 then goto continue end
  25. -- align start and end for fileindex
  26. s = word.start + s - 1
  27. e = word.start + e - 1
  28. local base, format, padding = 10, 'd', 0
  29. if lexer.oct_num:match(data) then
  30. base = 8
  31. format = 'o'
  32. padding = #data
  33. elseif lexer.hex_num:match(data) then
  34. base = 16
  35. format = 'x'
  36. padding = #data - #"0x"
  37. end
  38. local number = tonumber(data, base == 8 and 8 or nil)
  39. if not number then goto continue end
  40. number = number + delta * count
  41. -- string.format does not support negative hex/oct values
  42. if base ~= 10 and number < 0 then number = 0 end
  43. number = string.format((base == 16 and "0x" or "") .. "%0"..padding..format, number)
  44. if base == 8 and string.sub(number, 0, 1) ~= "0" then
  45. number = '0' .. number
  46. end
  47. file:delete(s, e - s)
  48. file:insert(s, number)
  49. selection.pos = s
  50. ::continue::
  51. end
  52. end
  53. vis:map(vis.modes.NORMAL, "<C-a>", function() change( 1) end, "Increment number")
  54. vis:map(vis.modes.NORMAL, "<C-x>", function() change(-1) end, "Decrement number")