Skip to content

Instantly share code, notes, and snippets.

@AndrewRadev
Last active October 19, 2023 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewRadev/ded2eb17d8be34eba428a421c5dbd728 to your computer and use it in GitHub Desktop.
Save AndrewRadev/ded2eb17d8be34eba428a421c5dbd728 to your computer and use it in GitHub Desktop.
Timestamp formatting
" Place under ~/.vim/plugin/
"
" Calling :Timestamp will try to convert the word under the cursor. Selecting
" an area in visual mode will pass it to `date` and replace the entire area.
"
command! -range=0 Timestamp call s:Timestamp(<count>)
function! s:Timestamp(count) abort
let is_visual = a:count > 0
if !executable('date')
echohl Error | echomsg "Couldn't find `date` executable" | echohl NONE
return
endif
if is_visual
let description = s:GetLastSelectedText()
else
let description = expand('<cword>')
endif
let output = trim(system('date --date=' .. shellescape(description)))
if v:shell_error
echohl Error | echomsg "Got error: " .. output | echohl NONE
return
endif
if is_visual
call s:ReplaceArea('gv', output)
else
call s:ReplaceArea('viw', output)
endif
endfunction
function! s:GetLastSelectedText() abort
let saved_view = winsaveview()
let original_reg = getreg('z')
let original_reg_type = getregtype('z')
normal! gv"zy
let text = @z
call setreg('z', original_reg, original_reg_type)
call winrestview(saved_view)
return text
endfunction
function! s:ReplaceArea(motion, text) abort
let saved_view = winsaveview()
let original_reg = getreg('z')
let original_reg_type = getregtype('z')
let @z = a:text
exe 'normal! ' .. a:motion .. '"zp'
call setreg('z', original_reg, original_reg_type)
call winrestview(saved_view)
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment