我如何让Vim检测文件类型,并在粘贴到第一个缓冲区后立即为新文件进行语法高亮显示

sczxawaw  于 2024-01-08  发布在  其他
关注(0)|答案(1)|浏览(252)

我经常从一个文件中复制文本,或者从一个格式化为html、json或python的网页中复制文本。为了使用它,我打开一个空的Vim缓冲区并将其粘贴进去(用ctrl-v)。在这一点上,我可以手动设置语法或用途:filetype detect,但我希望它自动发生,就像打开一个文件一样。
我尝试了一些autocmds,但我不知道如果语法关闭,但他们没有工作。我试过

  1. au TextChangedI * :filetype detect

字符串
但没有效果

lfapxunr

lfapxunr1#

您可以创建一个单一的Map来完成所有事情:

  1. " the function where everything happens
  2. function! MagicPaste()
  3. " create a new buffer, see :help :enew
  4. enew
  5. " grab the content of register "+
  6. let reg = getreg("+", 1, 1)
  7. " figure out how many empty lines there are at the top
  8. " and remove them, if any
  9. let i = 0
  10. while reg[i] == ""
  11. let i += 1
  12. endwhile
  13. if i > 0
  14. call remove(reg, 0, i - 1)
  15. endif
  16. " insert the the remaining lines in the buffer,
  17. " see :help setline() and :help getreg()
  18. call setline(1, reg)
  19. " perform filetype detection
  20. filetype detect
  21. endfunction
  22. " the custom mapping
  23. nnoremap <key> <Cmd>call MagicPaste()<CR>

字符串
请注意,此代码片段假设您有一个适当的Vim,构建时支持剪贴板。

展开查看全部

相关问题