(Re)formatting PHP code in Vim

萝らか妹 提交于 2019-12-08 06:42:36

问题


How do I format PHP code that looks like this

class SomeClass
{
    function insideclass()
    {


    }
} 

into this, using Vim without any external tool?

class SomeClass {
    function insideclass() {


    }
} 

I am not arguing that this is the best way to format the code, but this is what we are following in the team.

Edit: Removed reference to the snippet addon, which caused some confusion about the question.


回答1:


You have two unrelated problems and you won't find a unique solution to both.

  1. You don't like the default class snippet.

    No problem. If it's not already there, create ~/.vim/snippets/php.snippets and customize it to fit your team's rules by following the other answers. Snipmate is not smart enough to adapt itself to your coding style.

  2. Some of your existing code doesn't conform to your coding rules.

    Snipmate won't help at all since it only deals with insertion, not transformation. You are going to need either some external beautifier or a few macros.

    EDIT

    Here is a very simple command that does exactly what you want on your example. I offer no guarantee that it's going to work for everything everywhere. Take it as a naive starting point.

    :g/^\s*{\s*$/normal kJ
    
    • :g/pattern acts on all lines containing pattern, see :h :global.

    • ^\s*{\s*$ matches all single { whatever the amount of whitespace between them and the beginning of the line.

    • normal executes normal commands, see :h :normal.

    • kJ goes up one line and Joins this line with the matched line.

    • Done.

    ENDEDIT




回答2:


Why not modify the source code of that addon?

For example, change these:

snippet class
    /**
     * ${1}
     */
    class ${2:ClassName}
    {
        ${3}
        function ${4:__construct}(${5:argument})
        {
            ${6:// code...}
        }
    }

to

snippet class
    /**
     * ${1}
     */
    class ${2:ClassName}{
        ${3}
        function ${4:__construct}(${5:argument}){
            ${6:// code...}
        }
    }



回答3:


Al the snipmate snippets are stored in a directory. Go to that directory and edit the file you want.

The direcorty is stored in the vim directory and called snippets. In there you see a php.snippets file. Go to that file and on line 70 you can edit the snippet for the class.



来源:https://stackoverflow.com/questions/10118738/reformatting-php-code-in-vim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!