Nice programing

Vim이 모든 공백을 문자로 표시하도록합니다.

nicepro 2020. 9. 29. 18:43
반응형

Vim이 모든 공백을 문자로 표시하도록합니다.


Vim에서 모든 공백을 문자로 표시하는 방법을 찾을 수 없습니다. 내가 찾은 것은 탭, 후행 공백 등에 관한 것뿐입니다.


다른 사람들이 말했듯이

:set list

다음과 결합하여

:set listchars=...

보이지 않는 문자를 표시합니다.
이제 공백 표시 하는 데 사용할 수있는 명시적인 옵션이 없지만 listchars에서는 공백을 제외한 모든 항목에 대해 표시 할 문자를 설정할 수 있습니다. 예를 들어, 내 모습은 다음과 같습니다.

:set listchars=eol:$,tab:>-,trail:~,extends:>,precedes:<

자, 이제 사용 후

:set list

명시 적으로 다른 것으로 표시되지 않은 모든 것은 실제로 평범한 오래된 공백입니다.

평소처럼 listchars작동 방식 을 이해 하려면 도움말을 사용하십시오. 표시 할 수있는 문자 (예 : 후행 공백) 및 수행 방법에 대한 훌륭한 정보를 제공합니다.

:help listchars

편집 도중에 변경 사항을 쉽게 볼 수 있도록 토글을 추가하는 것이 도움이 될 수 있습니다 (출처 : VIM : set list! as a toggle in .vimrc ) :

noremap <F5> :set list!<CR>
inoremap <F5> <C-o>:set list!<CR>
cnoremap <F5> <C-c>:set list!<CR>

:set list 사용하려면.

:set nolist 비활성화합니다.


7.4.710 패치 부터 이제 listchars 를 사용하여 공백 대신에 표시 할 문자를 설정할 수 있습니다!

:set listchars+=space:␣

따라서 모든 공백 문자를 문자로 표시 하려면 다음을 수행 할 수 있습니다.

:set listchars=eol:¬,tab:>·,trail:~,extends:>,precedes:<,space:␣
:set list

메일 링리스트에 대한 토론 : https://groups.google.com/forum/?fromgroups#!topic/vim_dev/pjmW6wOZW_Q


여기에 다른 답변이 더 포괄적이라고 생각하지만 탭과 공백을 시각적으로 구분하는 데 일반적으로 사용하는 트릭을 공유 할 것이라고 생각했습니다.

:syntax on
:set syntax=whitespace

이는 공백 프로그래밍 언어에 대한 구문 강조 규칙입니다. 탭은 녹색으로 표시되고 공백은 빨간색으로 표시됩니다. :)

:set list탭은 녹색 강조 표시없이 ^ I로 표시되지만 공백은 빨간색으로 표시되지만 다른 많은 답변에서 언급 한대로 결합 할 수 있습니다 .


:set list모든 공백을 문자로 표시합니다. 공간을 제외한 모든 것은 정상적인 상태와 다르게 보일 것입니다. 즉, 여전히 평범한 오래된 공간이 보인다면 실제로는 평범한 오래된 공간입니다. :)


설정하는 경우 :

:highlight Search cterm=underline gui=underline ctermbg=none guibg=none ctermfg=none guifg=none

그런 다음 공백 검색을 수행하면 모든 공백 문자가 밑줄 문자로 표시됩니다.

공백의 "밑줄"을 전환하는 편리한 기능에서이 명령을 사용할 수 있습니다.

set hls
let g:HLSpace = 1
let g:HLColorScheme = g:colors_name
function ToggleSpaceUnderscoring()
    if g:HLSpace
        highlight Search cterm=underline gui=underline ctermbg=none guibg=none ctermfg=none guifg=none
        let @/ = " "
    else
        highlight clear
        silent colorscheme "".g:HLColorScheme
        let @/ = ""
    endif
    let g:HLSpace = !g:HLSpace
endfunction

다음을 사용하여 기능을 바로 가기 키에 매핑합니다.

nmap <silent> <F3> <Esc>:call ToggleSpaceUnderscoring()<CR>

주의 : colorscheme이 설정된 후 vimrc에서 함수를 정의하십시오.


현재 버퍼의 구문 규칙에 따라 다음과 같이 작동 할 수 있습니다.

:syn match WhiteSpace / / containedin=ALL conceal cchar=Æ
:setl conceallevel=2 concealcursor=nv

This needs a vim 7.3 with +conceal feature

Update 10/24/2014 To expand a little bit on that. It is of course possible to define some highlighting for the conealed characters.

  • You can configure, how the concealed chars look. For highlighting, you would have to at least once configure the 'Conceal' highlighting group (See the help at :h hl-Conceal This can be done in your colorscheme and then you do not need to reconfigure it again. But this affects all concealed chars (e.g. if your syntax script conceals some more items, they will be displayed as your white space chars). That could look like this:

    :hi Conceal ctermfg=7 ctermbg=NONE guifg=LightGrey guibg=NONE

  • There seems to be a particularity that Vim will not highlight spaces, if the syntax script uses the skipwhite keyword. There will be no way around (perhaps this will be fixed, I posted a patch)

  • There seems to be a patch floating around, that will allow to customize how spaces will look in list mode. The latest one at the time of writing seems to be this one. (This means, you need to built your own Vim to use this).
  • The conceallevel and concealcursor are window local options. That means they can be different in different windows (and will possibly be also set by filetype plugins or other plugin scripts).
  • The syntax highlighting groups need to be executed whenever a syntax definition file is reloaded. This could be done using a BufWinEnteror possibly also a Syntax or even FileType autocommand. (I have not tested which one actually works).

The last two items means, you would have to setup some autocommands that reset the syntax rules and the correesponding options. For the first one, one might want to setup the highlighting using a ColorScheme autocommand (so that the concealed chars always look the same, independent of what a color scheme actually sets up). For a complete solution, look into romainl answer, that should give you a start. If you setup a function, you can easily setup a toggle command to switch displaying special Highlighting on or off.

Update 10/26/2014 I made a plugin out of this question.

Update 04/22/2015 A patch has been included in Vim that makes this possible using the list option. Simply set set list listchars+=space:␣ This works as of Vim 7.4.711


I use this

/\s
:set hlsearch

to highlight white spaces. It searches for all white spaces, and then enables the highlight to make them pop out. However, it does not print a special character.


If by whitespaces you mean the ' ' character, my suggestion would just be a search/replace. As the others have hinted, set list changes non printing characters to a visible character that's configured in listchars.

To explicitly show spaces as some other character, something similar to the below should do the trick:

:%s/ /█/g

Then just undo the change to go back again.

(to get the █ I pressed this exact key sequence: :%s/ /CTRL-KFB/g)


To highlight spaces, just search for it:

/<space>

Notes:

  • <space> means just type the space character.
  • Enable highlighting of search results with :set hlsearch

    To highlight spaces & tabs:

    /[<space><tab>]

    A quick way to remove the highlights is to search for anything else: /asdf

    (just type any short list of random characters)


  • The code below is based on Christian Brabandt's answer and seems to do what the OP wants:

    function! Whitespace()
        if !exists('b:ws')
            highlight Conceal ctermbg=NONE ctermfg=240 cterm=NONE guibg=NONE guifg=#585858 gui=NONE
            highlight link Whitespace Conceal
            let b:ws = 1
        endif
    
        syntax clear Whitespace
        syntax match Whitespace / / containedin=ALL conceal cchar=·
        setlocal conceallevel=2 concealcursor=c
    endfunction
    
    augroup Whitespace
        autocmd!
        autocmd BufEnter,WinEnter * call Whitespace()
    augroup END
    

    Append those lines to your ~/.vimrc and start a new Vim session to see the still imperfect magic happen.

    Feel free to edit the default colors and conceal character.


    Caveat: something in the *FuncBody syntax group in several languages prevents the middle dot from showing. I don't know (yet?) how to make that solution more reliable.


    I was frustrated with all of the other answers to this question, because none of them highlight the space character in a useful way. Showing spaces as characters would particularly help for whitespace-formatted languages, where mixing tabs and spaces is harmful.

    My solution is to show tabs and underline multiple spaces. It borrows from mrucci's answer and this tutorial. Because it uses syntax highlighting, it's persistent:

    set list listchars=tab:\|\ 
    highlight Whitespace cterm=underline gui=underline ctermbg=NONE guibg=NONE ctermfg=yellow guifg=yellow
    autocmd ColorScheme * highlight Whitespace gui=underline ctermbg=NONE guibg=NONE ctermfg=yellow guifg=yellow
    match Whitespace /  \+/
    

    Using this, tabs are displayed as | and spaces as _, which makes it very easy to tell when I'm mixing code styles.

    The only downside I've found is that this snippet doesn't adjust background color to match the context (like in a comment).


    all of the answers above try to make spaces visible from within vim. If you really insist on having visible spaces as dots, there's another approach...

    If it cannot be done in vim, change your font entirely. I copied the Ubuntu One Mono font and edited it using FontForge. Remember to change the font's fullname, family, preferred family, compatible full (in FontFoge it's under TTF Names in the font info), in order to have it as a separate font. Simply edit the space character to have a dot in the middle and save the font to ~/.fonts Now you can use it for your gvim or the entire terminal... I copied the "!" character, removed the line and moved the dot to the middle. It took a little more than 5 minutes...

    Note: changing the space character (0x20) results in the inconvenience of having dots on the entire vim screen... (but it will separate the spaces from tabs...)


    I didn't find exactly what I wanted from the existing answers. The code below will highlight all trailing spaces bright red. Simply add the following to your .vimrc

    highlight ExtraWhitespace ctermbg=red guibg=red
    match ExtraWhitespace /\s\+$/
    autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
    autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
    autocmd InsertLeave * match ExtraWhitespace /\s\+$/
    autocmd BufWinLeave * call clearmatches()
    

    :match CursorLine /\s\+/
    

    avoids the "you have to search for spaces to get them to show up" bit but afaict can't be configured to do non-hilighting things to the spaces. CursorLine can be any hilighting group and in the default theme it's a plain underline.


    I like using special characters to show whitespace, is more clear. Even a map to toggle is a key feature, for a quick check.

    You can find this features in an old vim script not updated since 2004:

    vim-scripts/cream-showinvisibles@vim.org

    Thanks to project vim-scripts and vundle you can come back to life this plugin

    vim-scripts/cream-showinvisibles@github

    Even better, my two cents on this is to add a configurable shortcut (instead of predefined F4)

    so add this to ~/.vimrc

    Plugin 'albfan/cream-invisibles'
    
    let g:creamInvisibleShortCut = "<F5>" "for my F4 goto next error
    

    install plugin on vim

    :PluginInstall
    

    and there you go


    To cover Unicode whitespace characters:

    set list
    set listchars=tab:│\ ,nbsp:·
    highlight StrangeWhitespace guibg=Red ctermbg=Red
    " The list is from https://stackoverflow.com/a/37903645 (with `\t`, `\n`, ` `, `\xa0` removed):
    call matchadd('StrangeWhitespace', '[\x0b\x0c\r\x1c\x1d\x1e\x1f\x85\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]')
    

    The result:

    • only the ordinal space (U+0020) looks just like a space ("")
    • the tab (U+0009) looks like "│ " (two characters: a long pipe and then an ordinal space; they are gray in colorscheme murphy)
    • the normal non-breaking space (U+00A0) looks like "·" (one character; it's gray in colorscheme murphy)
    • any other whitespace character looks like red ""

    You could use

    :set list
    

    to really see the structure of a line. You will see tabs and newlines explicitly. When you see a blank, it's really a blank.


    highlight search

    :set hlsearch 
    

    in .vimrc that is

    and search for space tabs and carriage returns

    / \|\t\|\r
    

    or search for all whitespace characters

    /\s
    

    of search for all non white space characters (the whitespace characters are not shown, so you see the whitespace characters between words, but not the trailing whitespace characters)

    /\S
    

    to show all trailing white space characters - at the end of the line

    /\s$
    

    Keep those hacks in the .vimrc as comments, so in the shell, simply :

    echo '
      " how-to see the non-visible while spaces
      " :set listchars=eol:¬,tab:>·,trail:~,extends:>,precedes:<,space:␣
      " set listchars=eol:$,tab:>-,trail:~,extends:>,precedes:<
      " :set list
      " but hei how-to unset the visible tabs ?!
      " :set nolist
      ' >> ~/.vimrc
    

    :se list
    :se nolist
    

    :se is enough, :set isn't needed.


    you can also highlight the spaces (replacing the spaces with a block):

    :%s/ /█/g
    

    (before writing undo it)


    Adding this to my .vimrc works for me. Just make sure you don't have anything else conflicting..

    autocmd VimEnter * :syn match space /\s/
    autocmd VimEnter * :hi space ctermbg=lightgray ctermfg=black guibg=lightgray guifg=black
    

    참고URL : https://stackoverflow.com/questions/1675688/make-vim-show-all-white-spaces-as-a-character

    반응형