LoginSignup
4
5

More than 5 years have passed since last update.

( Vim )全角スペースを表示、全角スペースを半角スペースに変換、文末の全角スペースを削除する

Last updated at Posted at 2019-04-03

Screen Shot 2019-04-03 at 13.34.03.png

Summary

Vim

  1. 全角スペースを表示

  2. 全角スペースを半角スペースに変換

  3. 文末の全角スペースを削除

全角スペースを表示する

autocmd MyAutoCmd ColorScheme * highlight UnicodeSpaces  ctermbg=131  guibg=#af5f5f
autocmd MyAutoCmd BufRead,BufNewFile * call matchadd(
      \ 'UnicodeSpaces', '\v' .
      \ '%u180E|%u2028|%u2029|%u00A0|%u2000|%u2001|' .
      \ '%u2002|%u2003|%u2004|%u2005|%u2006|%u2007|' .
      \ '%u2008|%u2009|%u200A|%u202F|%u205F|%u3000'
      \ )

全角スペースを半角スペースにする

command! Spaces call s:spaces()
function! s:spaces() abort

  " mark origin position
  :normal! ma

  let l:range = '%'

  let l:unicodeSpaces = '\v' .
    \ '%u180E|%u2028|%u2029|%u00A0|%u2000|%u2001|' .
    \ '%u2002|%u2003|%u2004|%u2005|%u2006|%u2007|' .
    \ '%u2008|%u2009|%u200A|%u202F|%u205F|%u3000'

  let l:space = ' '

  " Replace unicode spaces to normal space
  :execute l:range 'substitute' '/\v(' . l:unicodeSpaces . ')/' . l:space . '/ge'

  " back to origin position
  :normal! `a

endfunction

文末の半角・全角スペースのみ削除する

  command! TrimEnd call s:trimEnd()
  function! s:trimEnd() abort

    " mark origin position
    :normal! ma

    let l:range = '%'

    let l:unicodeSpaces = '\v' .
      \ '%u180E|%u2028|%u2029|%u00A0|%u2000|%u2001|' .
      \ '%u2002|%u2003|%u2004|%u2005|%u2006|%u2007|' .
      \ '%u2008|%u2009|%u200A|%u202F|%u205F|%u3000'

    let l:space = '\v\s'

    " Trim end spaces
    :execute l:range 'substitute' '/\v(' . l:unicodeSpaces . '|' . l:space . ')+$//ge'

    " back to origin position
    :normal! `a

  endfunction

Thanks

@mattn
@koron
@thinca
@yaegassy
@m_nish

See also

Vimで全角空白以外のユニコードの空白文字もハイライト&取り除く

Table Unicode space characters( 下記のホームページを参考に作成)

page11 Table 6-2.Unicode Space Characters

fileformat.info

Code  Char    Regex   Name
--------------------------------------------------------
[Cf]  U+180E  %u180E  MONGOLIAN VOWEL SEPARATOR
[ZI]  U+2028  %u2028  LINE SEPARATOR
[Zp]  U+2029  %u2029  PARAGRAPH SEPARATOR
[Zs]  U+00A0  %u00A0  NO-BREAK SPACE
[Zs]  U+2000  %u2000  EN QUAD
[Zs]  U+2001  %u2001  EM QUAD
[Zs]  U+2002  %u2002  EN SPACE (nut)
[Zs]  U+2003  %u2003  EM SPACE (mutton)
[Zs]  U+2004  %u2004  THREE-PER-EM SPACEk space)
[Zs]  U+2005  %u2005  FOUR-PER-EM SPACE (space)
[Zs]  U+2006  %u2006  SIX-PER-EM SPACE
[Zs]  U+2007  %u2007  FIGURE SPACE
[Zs]  U+2008  %u2008  PUNCTUATION SPACE
[Zs]  U+2009  %u2009  THIN SPACE
[Zs]  U+200A  %u200A  HAIR SPACE
[Zs]  U+202F  %u202F  NARROW NO-BREAK SPACE
[Zs]  U+205F  %u205F  MEDIUM MATHEMATICAL SPACE
[Zs]  U+3000  %u3000  IDEOGRAPHIC SPACE
4
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5