vim - 如何在 vim 中基于大括号定义缩进?

标签 vim indentation sass auto-indent

我在 vim 上使用 https://github.com/cakebaker/scss-syntax.vim 来语法突出显示 SCSS(或 SASS)文件,这对于语法突出显示非常有效。但是,该插件没有附带缩进文件,并且在编写缩进文件时遇到了麻烦。

我想将缩进设置为如下所示:

enter image description here

但是,如果我这样做gg=G,我会得到:

enter image description here

我怀疑它不理解基于大括号的嵌套缩进。我尝试了所有不同的组合

设置cindent

设置nocindent

设置自动缩进

设置智能缩进

并尝试使用 Tab key == 4 spaces and auto-indent after curly braces in Vim 中的代码,包括

设置 tabstop=2

设置shiftwidth=2

设置展开选项卡

...但是嵌套大括号缩进似乎永远不起作用。

我相信我可能想要编写一个自定义缩进文件,而我所需要的只是基于具有嵌套级别的大括号​​的缩进。我该怎么办?如果有人有一个具有类似语法的文件类型的缩进文件,那就太好了。

最佳答案

这是一个基于内置 perl 缩进代码(在 indent/perl.vim 中)的快速破解。希望你能用它来实现你想做的事。有关详细信息,请参阅 perl 缩进代码或缩进​​目录中的另一个文件中的更详细注释。

setlocal indentexpr=GetMyIndent()
function! GetMyIndent()
    let cline = getline(v:lnum)

    " Find a non-blank line above the current line.
    let lnum = prevnonblank(v:lnum - 1)
    " Hit the start of the file, use zero indent.
    if lnum == 0
        return 0
    endif
    let line = getline(lnum)
    let ind = indent(lnum)

    " Indent blocks enclosed by {}, (), or []
    " Find a real opening brace
    let bracepos = match(line, '[(){}\[\]]', matchend(line, '^\s*[)}\]]'))
    while bracepos != -1
        let brace = strpart(line, bracepos, 1)
        if brace == '(' || brace == '{' || brace == '['
            let ind = ind + &sw
        else
            let ind = ind - &sw
        endif
        let bracepos = match(line, '[(){}\[\]]', bracepos + 1)
    endwhile
    let bracepos = matchend(cline, '^\s*[)}\]]')
    if bracepos != -1
        let ind = ind - &sw
    endif

    return ind
endfunction

将该文件另存为 ~/.vim/indent/something.vim 其中 something 是您的文件类型(替换 ~/.vim如果您使用的是 Windows,请使用 vimfiles 的路径。

您可能还想将其粘贴在文件的开头(但前提是没有可能首先加载的其他缩进声明):

" Only load this indent file when no other was loaded.
if exists("b:did_indent")
    finish
endif
let b:did_indent = 1

关于vim - 如何在 vim 中基于大括号定义缩进?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4829244/

相关文章:

css - SASS 错误 : can't import Compass

angular - 无法在 Ionic/Angular 应用程序中导入 Swiper Scss

vim - 如何使用 vim 更改文件的编码?

vim - 设置 IdeaVIM 缩进的字符数(<< 和 >>)

eclipse - Eclipse 中的多行字符串对齐/缩进

vim - 使用文件夹中的所有文件在 VIM 中缩进

SASS - 从@mixin 中将 $variable 传递给@content

c++ - 如何在 vim 中将 C 风格的 printf 转换为 C++ 风格的 cout

Vim:对于多个文件:复制所有文本,替换并粘贴

Eclipse 连续缩进