Automatically convert indentation from 2 to 4 spaces in Sublime Text 3

别说谁变了你拦得住时间么 提交于 2021-02-10 18:23:01

问题


There are a few topics about auto-conversion of the indentation in Sublime Text, but I didn't find the way to do it automatically.

Many files I download have indentation of 2, which I hate, so I want to convert them to 4. What I do is:

  1. Select Tab size: 2
  2. Convert indentation to Tabs
  3. Select Tab size: 4
  4. Convert indentation to Spaces

I don't think I need to mention that it's too much work for every single file. Some people suggest Reindent option, but for my experience, it almost never works correctly.

Is there some build-it way, or perhaps a package to convert indentation in one step?


回答1:


Converting indentation to a personal preference can be a tedious task in Sublime Text which, as you observe, gets mentioned on StackOverflow quite regularly. In fact 4 years ago I answered a question which lists almost exactly the steps you've listed in your question.

I too have found the 3 Command Pallette reindent commands to be a little temperamental, sometimes working as I think they ought to and sometimes doing (what appears to be) nothing at all. But no matter...

There is of course a way to perform the actions you've listed in one step; use a macro.

Copy and paste the macro code below and save it in your User folder as IndentationTo4Spaces.sublime-macro.

[
    { "command": "set_setting", "args": {"setting": "tab_size", "value": 2} },
    { "command": "unexpand_tabs", "args": {"set_translate_tabs": true} },
    { "command": "set_setting", "args": {"setting": "tab_size", "value": 4} },
    { "command": "expand_tabs", "args": {"set_translate_tabs": true} }
]

You could run the macro from the menu Tools --> Macros --> User --> IndentationTo4Spaces, set up a key binding, or add an entry to the Command Pallette.

// Add keys to: Packages/User/Default (Linux/OSX/Windows).sublime-keymap
{ "keys": ["ctrl+shift+y"], "command": "run_macro_file",
  "args": {"file": "res://Packages/User/IndentationTo4Spaces.sublime-macro"} },

// Add command to: Packages/User/Default.sublime-commands
{ "caption": "Convert Indentation To 4 Spaces", "command": "run_macro_file",
  "args": {"file": "res://Packages/User/IndentationTo4Spaces.sublime-macro"} },


来源:https://stackoverflow.com/questions/64737302/automatically-convert-indentation-from-2-to-4-spaces-in-sublime-text-3

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