Как изменить табуляцию в visual studio code
How do I customize the tab-to-space conversion factor when using Visual Studio Code?
For instance, right now in HTML it appears to produce two spaces per press of TAB , but in TypeScript it produces 4.
21 Answers 21
By default, Visual Studio Code will try to guess your indentation options depending on the file you open.
You can turn off indentation guessing via "editor.detectIndentation": false .
You can customize this easily via these three settings for Windows in menu File → Preferences → User Settings and for Mac in menu Code → Preferences → Settings or ⌘, :
Hey Guss, would you be willing to point me to a file where the guessing is wrong? Also please share how you've configured these two settings (tabSize & insertSpaces) and what you would expect to get. Thanks! :)
Is there also an option to set the default for new, blank files? There's not much to guess in that scenario and I think VSCode will default to using spaces (which I don't prefer).
Fwiw, there's also a workplace settings option so that you can set a different behavior by project that overrides user settings. 2¢
Thanks ruffin. Is there a way to change tabSize per language? e.g. when editing multiple files with different languages in the same Workspace (e.g. Ruby, JavaScript, CSS, etc.) - Ruby would be 2 spaces, but CSS would be 4 . usually.
I'm running version 1.21, but I think this may apply to other versions as well.
Take a look at the bottom right-hand side of the screen. You should see something that says Spaces or Tab-Size .
Mine shows spaces, →
- Click on the Spaces (or Tab-Size)
- Choose Indent Using Spaces or Indent using Tabs
- Select the amount of spaces or tabs you like.
This only works per document, not project-wide. If you want to apply it project-wide, you need to also add "editor.detectIndentation": false to your user settings.
If you have a .editorconfig file, it overrides all tab size. Make sure you have indent_size = 4 in that file
Note
if you are talking about prettier for tabSize, go to the section 2 of this answer
Well, if you like the developer way, Visual Studio Code allows you to specify the different file types for the tabSize . Here is the example of my settings.json with default four spaces and JavaScript/JSON two spaces:
PS: Well, if you do not know how to open this file (specially in a new version of Visual Studio Code), you can:
- Left-bottom gear →
- Settings → top right Open Settings
Section2: If using prettier
If you are using prettier, things may be different again, prettier has 2 level of setting for this:
- User level, which you can click the extension and click setting find the keyword tabWidth
- Project level, which you can add/update from the root project level in file .prettierrc
@bck are you using pretter? that case may be different, you might need to change extension setting or the project file .prettierrc .
By default, Visual Studio Code auto-detects the indentation of the current open file. If you want to switch this feature off and make all indentation, for example, two spaces, you'd do the following in your User Settings or Workspace settings.
We can control tab size by file type with EditorConfig and its EditorConfig for VS Code extension. We then can make Alt + Shift + F specific to each file type.
Installation
Open the VS Code command palette with CTRL + P and paste this:
Example Configuration
.editorconfig
settings.json
EditorConfig overrides whatever settings.json configures for the editor. There is no need to change editor.detectIndentation .
What is this ext you speak of (please respond by editing your answer, not here in comments (as appropriate))? Some Node.js thingy? What platform?
@PeterMortensen You can do a CTRL+P and paste the ext install EditorConfig it's a shortcut installation command specific to Vscode.
If you use the prettier extension in Visual Studio Code, try adding this to the settings.json file:
Thank you!! "prettier.tabWidth": 4, "prettier.useTabs": true did it for me - i lost like 2 hours on this :)
In Visual Studio Code version 1.31.1 or later (I think): Like sed Alex Dima, you can customize this easily via these settings for
- Windows in menu File → Preferences → User Settings or use short keys Ctrl + Shift + P
- Mac in menu Code → Preferences → Settings or ⌘ ,
just copy and paste above code to your settings.json file and save. thanks
Yeah, this is the way to go if you want to set a different format for a specific language. I like using tabs with tabWidth=2, but autopep8 just hates that.
- CTRL + comma
- Search for indent using tabs
- Go and change Editor: Tab Size
In your bottom-right corner, you have Spaces: Spaces: 2
There you can change the indentation according to your needs: Indentation Options
many answers above you telling me how I can turn off the manual detection for all files - but yours was the first I spotted that actually told me how to change how many spaces it was detecting :) followed it up with "Format Document" - Shift-Alt-F to pretty print and adjust to the new Space-Tab-Indention depts
That is lonefy.vscode-js-css-html-formatter to blame. Disable it, and install HookyQR.beautify .
Now on save your tabs wouldn't be converted.
You want to make sure your editorconfig is not conflicting with your user or workspace settings configuration, as I just had a bit of annoyance thinking the settings files settings were not being applied when it was my editor configuration undoing those changes.
If the accepted answer on this post doesn't work, give this a try:
I had EditorConfig for Visual Studio Code installed in my editor, and it kept overriding my user settings which were set to indent files using spaces. Every time I switched between editor tabs, my file would automatically get indented with tabs even if I had converted indentation to spaces.
Right after I uninstalled this extension, indentation no longer changes between switching editor tabs, and I can work more comfortably rather than having to manually convert tabs to spaces every time I switch files - that is painful.
Oh my god.. I just struggled for some time trying to work out why my tabs would go back to using 4 spaces instead of 2. Once EditorConfig was uninstalled, it worked. Thanks!
When using TypeScript, the default tab width is always two regardless of what it says in the toolbar. You have to set "prettier.tabWidth" in your user settings to change it.
Ctrl + P , Type → user settings, add:
Menu File → Preferences → Settings
Add to user settings:
then right click your document if you have one opened already and click Format Document to have your existing document follow these new settings.
@alex-dima's solution from 2015 will change tab sizes and spaces for all files and @Tricky's solution from 2016 appears to only change the settings for the current file.
As of 2017, I found another solution that works on a per-language basis. Visual Studio Code was not using the proper tab sizes or space settings for Elixir, so I found that I could change the settings for all Elixir files.
I clicked on the language in the status bar ("Elixir" in my case), chose "Configure 'Elixir' language based settings. ", and edited the Elixir-specific language settings. I just copied the "editor.tabSize" and "editor.insertSpaces" settings from the default settings on the left (I'm so glad those are shown) and then modified them on the right.
It worked great, and now all Elixir language files use the proper tab size and space settings.
Для каждого машинописного файла код Visual Studio использует автоматический отступ в 8 пробелов. Это слишком много, на мой вкус, но я не могу найти, где это изменить.
Может быть, это доступно как настройка, но под другим именем, так как я не могу найти ничего, связанного с отступом.
ОБНОВИТЬ
В настоящее время я использую средство форматирования кода Преттиера, и это решает все проблемы форматирования путем автоматического форматирования при сохранении (если нет синтаксической ошибки)
Вы можете изменить это на глобальном User уровне или Workspace уровне.
Откройте настройки: С помощью клавиш ctrl + , или щелчки File > Preferences > , Settings как показано ниже.
Затем выполните следующие 2 изменения: (введите tabSize в строке поиска)
- Снимите флажок Detect Indentation
- Измените размер вкладки на 2/4 (хотя я твердо считаю, что 2 подходит для JS :))
На панели инструментов в правом нижнем углу вы увидите элемент, который выглядит следующим образом: Нажав на него, вы получите возможность сделать отступ с помощью пробелов или табуляции. После выбора типа отступа у вас будет возможность изменить размер отступа. В приведенном выше примере отступ равен 4 пробелам на отступ. Если в качестве символа отступа выбрана вкладка, то вместо размера вкладки вы увидите пробелов
Если вы хотите, чтобы это применялось ко всем файлам, а не к отдельным файлам, переопределите настройки Editor: Tab Size и в Editor: Insert Spaces настройках пользователя или в настройках рабочей области. зависимости от ваших потребностей
Редактировать 1
Чтобы перейти к настройкам пользователя или рабочей области, перейдите в « Настройки» -> « Настройки» . Убедитесь, что вы находитесь на вкладке « Пользователь» или « Рабочая область », в зависимости от ваших потребностей, и используйте панель поиска, чтобы найти настройки. Вы также можете отключить, так Editor: Detect Indentation как этот параметр переопределит то, для чего вы установили, Editor: Insert Spaces и Editor: Tab Size когда он включен
Как настроить отступы в VS Code?
Откройте настройки: С помощью клавиш ctrl + , или щелчки File > Preferences > , Settings как показано ниже. Пожалуйста, используйте 4 пробела для отступа.
Как изменить отступы Vscode?
Чтобы изменить отступ на основе языка программирования :
Как сделать отступ в Visual Studio Code?
Я хочу сделать отступ в определенном разделе кода в Visual Studio Code:
- Выберите строки, которые вы хотите сделать отступ, и
- используйте Ctrl + ] для отступа.
Как изменить размер табуляции в Visual Studio Code?
Запустите Visual Studio. Выберите меню Сервис => Параметры. Если у вас отколочена опция «Показывать все параметры», то в появившемся окне, в разделе «Общее» можно сразу установить нужный размер шага табуляции.
Как форматировать код в Visual Studio?
Форматирование кода доступно в Visual Studio Code с помощью следующих ярлыков:
- На Windows Shift + Alt + F.
- На Mac Shift + Option + F.
- На Linux Ctrl + Shift + I.
Как выделить строку в VS Code?
Выделить текущую строку: Ctrl + L.
Как включить отображение пробелов в Vscode?
Как убрать табуляцию в Visual Studio?
Как изменить размер таба?
Как сделать табуляцию в Visual Studio?
1 ответ На английской версии будет Tools → Options → Text Editor → [язык] → Tabs → Keep tabs (Ответ дал Alexander Petrov). А на русской версии будет Средства → Параметры → Текстовый редактор → [Язык] → Табуляция → Сохранять знаки табуляции.
Русские Блоги
содержание 1, основная функция MPI 2, точка-точка функция связи 3, коллективная функция связи 1, основная функция MPI MPI_Init(&argc, &argv) Информировать системы MPI для выполнения всех необх.
Примечание 9: EL выражение
JVM память
концепция Виртуальная машина JVM управляет собственной памятью, которая разделяет память во многие блоки, наиболее распространенной для памяти стека и памяти кучи. 1 структура виртуальной машины JVM H.
Проблема сетевого запроса на Android 9.0
вЗапустите Android 9 (API Уровень 28) или вышеНа устройстве операционной системы Android, чтобы обеспечить безопасность пользовательских данных и устройств, использование по умолчанию для зашифрованно.
Учебная запись по Webpack (3) В статье рассказывается о создании webpack4.0.
предисловие Для изучения веб-пакета автор также предпринял много обходных путей. Есть много вещей, которые я хочу знать, но я не могу их найти. Автор поможет вам быстро начать работу. Цель этой статьи.
Вам также может понравиться
Сетевой HDU — 3078 мультивикация LCA
The ALPC company is now working on his own network system, which is connecting all N ALPC department. To economize on spending, the backbone network has only one router for each department, and N-1 op.
Деревянная палочка Luogu P1120 [Data Enhanced Version] Поиск
Метафизический разрез, просто просмотрите поиск Я чувствую, что процедура поиска состоит в том, чтобы сначала набрать общую структуру, а затем шаг за шагом оптимизировать процесс сокращения. 1. Длина .
Используйте Maven для запуска модульных тестов
Используйте Maven для запуска модульных тестов Чтобы запустить модульные тесты через Maven, введите эту команду: Это запустит весь модульный тест в вашем проекте. Тематическое исследование Создайте дв.
Изучая sass в наши дни, вы можете компилировать файлы sass в файлы css, но когда кода слишком много, он не выглядит красиво и даже кажется немного беспорядочным.
Для кого-то вроде Libra я могу принять только элегантные и красивые вещи, поэтому для того, чтобы код выглядел красивее, нам нужно настроить vscode, чтобы иметь функцию форматирования кода.
Один: необходимо установить три подключаемых модуля
1.ESLint
2.Prettier — Code formatter
3.Vetur
Два: устанавливается при настройке
Как открыть настройку
Для окон file —> preferences —>setting
Для MAC Code —> preferences —>setting
Я беру Windows в качестве примера здесь
Три: откройте файл setting.json
В правом верхнем углу интерфейса настроек есть значок открытия, щелкните, чтобы открыть файл setting.json.
Добавить конфигурацию в файл setting.json
Код конфигурации следующий:
4: перезапустить VS Code.
Метод форматирования кода:
Выберите код, который нам нужно отформатировать, и щелкните правой кнопкой мыши, появится Format Document Вариант, нажмите, чтобы отформатировать; или выберите код и используйте горячую клавишу Shift + Alt + F Формат
Пятый: эффект следующий
Перед форматированием: переполненные строки кода и круглые скобки
После форматирования: код отделяется от скобок, так будет удобнее.
Если у вас есть ошибки, свяжитесь со мной, и мы исправим их вовремя, biubiubiu
Как настроить форматирование в редакторе visual studio code?
Два вопроса касательно форматирования кода
1) В чем разница между отступами "indent using spaces" и "indent using tabs"
Я думал, что "indent using spaces" задает отступ пробела, типа пробел нажал и на указанное количество символов получил отступ, и соответственно в случае с "indent using tabs" — отступает на указанное количество символов при нажатии Tab.
Но по факту, не важно указывай например значение 4 у "indent using spaces" или "indent using tabs", данный отступ в 4 символа будет только по нажатию на Tab, спрашивается зачем тогда "indent using spaces" ?
2) Поставил плагин для VUE vetur, по итогу при сохранении он форматирует код не совсем так как нужно, например
нужно чтобы каждый атрибут тега были на разных строках, но при форматировании все атрибуты автоматически становятся в одну строку.
До форматирования, как я хочу:
После форматирования, как не нужно:
Можно конечно полностью отключить форматирование в настройке vetur (как на скриншоте ниже), но тогда та же табуляция не будет работать. По этому полностью от форматирования отказываться не хотелось бы — только чтобы каждый атрибут тега был на новой строке.
How do you format code in Visual Studio Code (VSCode)?
What is the equivalent of Ctrl + K + F and Ctrl + K + D on Windows in Visual Studio for formatting, or "beautifying" code in the Visual Studio Code editor?
29 Answers 29
The code formatting is available in Visual Studio Code through the following shortcuts:
- On Windows Shift + Alt + F
- On Mac Shift + Option + F
- On Linux Ctrl + Shift + I
Alternatively, you can find the shortcut, as well as other shortcuts, through the ‘Command Palette’ provided in the editor with Ctrl + Shift + P (or Command + Shift + P on Mac), and then searching for format document.
For unsaved snippets
Open command palette (Win: F1 or Ctrl + Shift + P )
Find ‘Change Language Model’
Select language e.g. json . By now syntax should be highlighted.
Format document (e.g. Open Command Palette -> ‘Format Document‘)
Unformat
- Select text
- Command Palette -> Join Lines
‘Show the pics‘
Code Formatting Shortcut:
Visual Studio Code on Windows — Shift + Alt + F
Visual Studio Code on MacOS — Shift + Option + F
Visual Studio Code on Ubuntu — Ctrl + Shift + I
You can also customize this shortcut using a preference setting if needed.
Code Formatting While Saving the File:
Visual Studio Code allows the user to customize the default settings.
If you want to auto format your content while saving, add the below code snippet in the work space settings of Visual Studio Code.
для каждого файла typescript код visual studio использует автоматический отступ 8 пробелов. Это немного слишком много для моего вкуса, но я не могу найти, где его изменить.
возможно, он доступен как параметр, но под другим именем, поскольку я не могу найти ничего, связанного с отступом.
на панели инструментов в правом нижнем углу вы увидите предмет, который выглядит следующим образом: После нажатия на него вы получите возможность отступа с помощью пробелов или вкладок. После выбора типа отступа у вас будет возможность изменить размер отступа. В приведенном выше примере отступ имеет значение 4 символа пробела на отступ. Если вкладка выбрана в качестве символа отступа, вы увидите В Размере вместо помещения
Если вы хотите, чтобы это применялось ко всем файлам, а не к отдельным файлам, переопределите editor.tabSize и editor.insertSpaces настройки В либо Настройки Пользователя или Настройки Рабочего Пространства в зависимости от ваших потребностей
изменить отступ на основе языка программирования выполните одно из следующих способов:
добавьте это в настройки ( Ctrl + , ):
(пример для конкретных настроек TypeScript):
- Ctrl + Shift + P
- Настройки: Настройка языковых параметров. (идентификатор команды: workbench.action.configureLanguageBasedSettings )
- выбрать язык программирования
- добавить код как выше.
вы также можете установить editor.detectIndentation к false, в дополнение к ответу Эллиота-J.
VSCode перезапишет ваш editor.tabSize и editor.insertSpaces настройки для каждого файла, если он обнаруживает, что файл имеет другой шаблон отступов табуляции или пробелов. Эта проблема может возникнуть при добавлении существующих файлов в проект или при добавлении файлов с помощью генераторов кода, таких как Angular Cli. Вышеуказанная настройка предотвращает VSCode от этого.
в моем случае "EditorConfig для VS Code" расширение переопределяет настройки VSCode. Если он установлен, проверьте .файл editorconfig в корневой папке проекта.
вот пример конфига. "Indent_size" задает количество пробелов для вкладки.
Ярлык Форматирования Кода:
VSCode на Windows-Shift + Alt + F
VSCode на MacOS-Shift + Option + F
VSCode на Ubuntu-Ctrl + Shift + I
вы также можете настроить этот ярлык через настройки, если это необходимо.
Я хотел изменить отступ моего существующей HTML файл от 4 пробелов до 2 пробелов.
Я нажал кнопку "пробелы: 4" в строке состояния и изменил их на два в следующем диалоговом окне.
Как изменить отступ в коде Visual Studio?
Для каждого файла машинописного текста код Visual Studio использует автоматический отступ в 8 пробелов. На мой вкус это многовато, но я не могу найти, где это изменить.
Возможно, он доступен как параметр, но под другим именем, так как я не могу найти ничего, связанного с отступом.
ОБНОВЛЕНИЕ
В настоящее время я использую программу форматирования кода Prettier, которая решает все проблемы с форматированием. автоматическим форматированием при сохранении (если нет синтаксической ошибки)
Вы можете изменить это на глобальном уровне User или Workspace .
Откройте настройки: используя ярлык ctrl + , или нажав File > Preferences > Settings , как показано ниже.
Затем внесите следующие 2 изменения: (введите tabSize в строке поиска)
- Снимите флажок Detect Indentation
- Измените размер вкладки на 2/4 (хотя я считаю, что 2 подходит для JS :))
Проблема: принятый ответ на самом деле не исправляет отступ в текущем документе.
Решение: запустите Format Document , чтобы повторно обработать документ в соответствии с текущими (новыми) настройками.
Проблема: HTML-документы в моих проектах относятся к типу «Django HTML», а не «HTML», и нет доступного средства форматирования.
Решение: переключите их на синтаксис «HTML», отформатируйте их, затем снова переключитесь на «Django HTML».
Проблема: форматировщик HTML не знает, как обрабатывать теги шаблонов Django, и отменяет большую часть моих тщательно примененных вложений.
Решение: установите расширение Indent 4-2, которое выполняет отступы строго, без с учетом синтаксиса текущего языка (что я и хочу в данном случае).
Упрощенное объяснение с картинками для тех, кто искал в Google "Изменить отступ в VS Code"
Шаг 1. Нажмите "Настройки"> "Настройки" .
Шаг 2. Требуемый параметр — «Определить отступ», начните вводить его. Нажмите "Редактор: размер табуляции" .
Шаг 3. Прокрутите вниз до пункта «Редактор: размер вкладки» и введите 2 (или что угодно).
Изменения сохраняются автоматически
Пример моих изменений
Как превратить отступ с 4 пробела во всех файлах в VS Code на 2 пробела
- Поиск открытого файла
- Включите регулярные выражения
- Введите: ( )(?: )(\b|(?!=[,’";\.:\*\\\/\\[\]\(\)])) в поле поиска
- Введите: $1 в поле замены
Как превратить отступ с 2 пробела во всех файлах в VS Code на 4 пробела
- Поиск открытого файла
- Включите регулярные выражения
- Введите: ( )(\b|(?!=[,’";\.:\\*\\\/\[\]\(\)])) в поле поиска
- Введите: $1$1 в поле замены
ПРИМЕЧАНИЕ. Сначала необходимо включить PERL Regex. Вот как:
- Откройте настройки и перейдите в файл JSON
- добавьте следующее в файл JSON "search.usePCRE2": true
Надеюсь, кто-нибудь это увидит.
В моем случае расширение «EditorConfig для VS Code» переопределяет настройки VSCode. Если он у вас установлен, проверьте файл .editorconfig в корневой папке проекта.
Вот пример конфигурации. «Indent_size» устанавливает количество пробелов для табуляции.
Ярлык форматирования кода:
VSCode в Windows — Shift + Alt + F
VSCode в MacOS — Shift + Option + F
VSCode в Ubuntu — Ctrl + Shift + I
При необходимости вы также можете настроить этот ярлык, используя настройки предпочтений.
выбор столбца с помощью клавиатуры Ctrl + Shift + Alt + стрелка
Вы также можете установить для editor.detectIndentation значение false в дополнение к ответу Elliot-J.
VSCode перезапишет ваши настройки editor.tabSize и editor.insertSpaces для каждого файла, если обнаружит, что в файле есть другой шаблон отступа табуляции или пробелов. Вы можете столкнуться с этой проблемой, если вы добавите существующие файлы в свой проект или если вы добавите файлы с помощью генераторов кода, таких как Angular Cli. Приведенный выше параметр не позволяет VSCode делать это.
Проблема автоопределения возникает из-за того, что в настройках VSCode установлен флажок. Следуй этим шагам:
перейти к предпочтениям
перейти к настройкам
поиск ‘редактор: обрезка автоматического пробела’
Чтобы установить для всех существующих файлов и новых файлов отступ до 2, просто поместите его в свой файл settings.json (в корень json):
Вы можете добавить языковой тип конфигурации:
Добавление: да, вы можете использовать нижний правый интерфейс для настройки параметров пространства. Но если у вас есть существующий код, который не отформатирован для нового интервала, вы можете щелкнуть правой кнопкой мыши в любом месте файла и выбрать Форматировать документ . Мне потребовалось некоторое время, чтобы понять это, пока я не наткнулся на эту проблему.
На панели инструментов в правом нижнем углу вы увидите элемент, который выглядит следующим образом: После нажатия на нее вы получите возможность использовать для отступа пробелы или табуляции. После выбора типа отступа у вас будет возможность изменить размер отступа. В случае приведенного выше примера для каждого отступа задано 4 символа пробела. Если в качестве символа отступа выбрана табуляция, вы увидите Размер табуляции вместо Пробелов .
Если вы хотите, чтобы это применялось ко всем файлам, а не к отдельным файлам, переопределите настройки Editor: Tab Size и Editor: Insert Spaces в Настройках пользователя или Настройках рабочей области в зависимости от ваших потребностей
Редактировать 1
Чтобы перейти к настройкам пользователя или рабочей области, перейдите в Настройки -> Настройки . Убедитесь, что вы находитесь на вкладке Пользователь или Рабочая область , в зависимости от ваших потребностей, и воспользуйтесь строкой поиска, чтобы найти настройки. Вы также можете отключить Editor: Detect Indentation , поскольку этот параметр переопределит то, что вы установили для Editor: Insert Spaces и Editor: Tab Size , когда он включен.
Я хотел изменить отступ моего существующего файла HTML с 4 до 2 пробелов.
Я нажал кнопку «Пробелы: 4» в строке состояния и изменил их на два в следующем диалоговом окне.
Настройка табуляции в MS Visual Studio
- Символы табуляции занимают меньше места в исходном тексте программы. (Правда, в наше время это редко бывает актуальным; скорость процессоров и объём дисков выросли настолько, что для абсолютного большинства программ разница будет просто незаметна.)
- По отступам, состоящим из символов табуляции, можно быстрее перемещаться. Такие отступы и удалить можно гораздо быстрее. Для этого просто нужно меньше нажатий клавиш.
- Ширина символа табуляции настраивается в большинстве текстовых редакторов. Т.е. каждый человек, который будет читать Ваш код, сможет настроить, как у него будут отображаться отступы, в соответствии со своими предпочтениями и размером монитора.
Преимущества есть и у пробелов:
В этом посте я хочу описать настройки MS Visual Studio, регулирующие работу с пробелами и символами табуляции. В первую очередь нужно в главном меню выбрать пункт Tools->Options. Откроется окно Options. В его левой части расположено древовидное меню в нём нужно выбрать пункт TextEditor->AllLanguages->Tabs. Там находятся настройки отступов, которые действуют для всех языков программирования и разметки, поддерживаемых MS Visual Studio. Если требуется изменить настройки только для конкретного языка, то в дереве слева вместо пункта AllLanguages следует выбрать нужный язык (см. рисунок 1).
Рисунок 1
Рисунок 2
Рассмотрим подробно каждый параметр из этой группы:
Я использовал MS Visual Studio 2015, но показанные настройки должны работать и в более новых, и в более старых версиях.
Настройка табуляции в MS Visual Studio: 17 комментариев
Я занимаюсь версткой и решил попробовать перейти с Sublime Text на Visual Studio Code, но никак не могу привыкнуть. У меня не всегда срабатывает Emmet (создание блока по табу), не хватает автодополнения пути к файлу (в HTML и CSS), автопрефиксера для CSS, красивого форматирования кода одним кликом. Подскажите настройки, подходящие плагины. И какие вы можете подсказать полезные плагины для веб-разработки?
For every typescript file visual studio code uses an auto indentation of 8 spaces. This is a bit too much for my taste but I can't find where to change it.
Maybe it's available as a setting but under a different name as I can't find anything related to indentation.
UPDATE
I'm currently using the Prettier code formatter and that solves all formatting problems by auto formatting on save (if there is no syntax error)
18 Answers 18
In the toolbar in the bottom right corner you will see a item that looks like the following: After clicking on it you will get the option to indent using either spaces or tabs. After selecting your indent type you will then have the option to change how big an indent is. In the case of the example above, indentation is set to 4 space characters per indent. If tab is selected as your indentation character then you will see Tab Size instead of Spaces
If you want to have this apply to all files and not on an individual file basis, then override the Editor: Tab Size and Editor: Insert Spaces settings in either User Settings or Workspace Settings depending on your needs
Edit 1
To get to your user or workspace settings go to Preferences -> Settings. Verify that you are on the User or Workspace tab depending on your needs and use the search bar to locate the settings. You may also want to disable Editor: Detect Indentation as this setting will override what you set for Editor: Insert Spaces and Editor: Tab Size when it is enabled
@yildizm85 the image is working without issue for me. The image was a direct upload to SO so if its broken it may be an issue on their end.
Changing editor.tabSpaces does not change the spacing in all files. It only changes it for future-created files. There's still no solution for fixing all files in one action.
This is super unintuitive. I already have indentation set to use spaces. Why do I need to click on the spaces option to get to a second, hidden menu to set the number of spaces? Every other editor I've used is one click on the indentation details in the status bar and there's a number of spaces option. In VS Code I need to look this up on Stack Overflow because the menu I want is hidden behind an option I'm not trying to change.
You can change this in global User level or Workspace level.
Open the settings: Using the shortcut Ctrl , or clicking File > Preferences > Settings as shown below.
Then, do the following 2 changes: (type tabSize in the search bar)
- Uncheck the checkbox of Detect Indentation
- Change the tab size to be 2/4 (Although I strongly think 2 is correct for JS :))
For those wondering, this will automatically reformat all files in your project, not just new ones you create. You might have to restart vs code for changes to take effect.
Both of these settings were already good to go on my installation (box checked, spaces set as I like it; and this is on a brand new angular project, so no copy/pasted code to screw things up), but it still didn't take, at least for the typescript files. I added a language specific setting as described by Martin Schneider above, so hopefully that'll work.
Update on my previous comment: It seems angular generated a '.editorconfig' file as well that I hadn't noticed before. In that file, the property 'indent_size' was set to 2 when I wanted 4. That was probably the original culprit. I've set that to 4 and removed the language-specific setting.
To change the indentation based on programming language:
- Open the Command Palette ( Ctrl Shift P | macOS: ⇧ ⌘ P ).
- Type and select: Preferences: Configure Language Specific Settings. (command id: workbench.action.configureLanguageBasedSettings ).
- Select a programming language (for example TypeScript).
If Settings menu is opened (since 1.66.0):
4. Press → to place the cursor right beside the language filter (e.g. @lang:typescript ).
5. Type Tab Size and enter your preferred value in the text box.
If settings.json file is opened:
4. Add this code:
How (where) does one use the command id? I don't see "Configure Language Specific Settings" under File-Preferences.
@AlanBaljeu You can use command ids e.g. to define keyboard shortcuts. There is no "Configure Language Specific Settings" under File > Preferences, because step 2 is not a menu entry, but the text in italics should be entered into the input field that appears after performing step 1.
You might also want to set the editor.detectIndentation to false, in addition to Elliot-J's answer.
VSCode will overwrite your editor.tabSize and editor.insertSpaces settings per file if it detects that a file has a different tab or spaces indentation pattern. You can run into this issue if you add existing files to your project, or if you add files using code generators like Angular Cli. The above setting prevents VSCode from doing this.
Code Formatting Shortcut:
VSCode on Windows - Shift + Alt + F
VSCode on MacOS - Shift + Option + F
VSCode on Ubuntu - Ctrl + Shift + I
You can also customize this shortcut using preference setting if needed.
column selection with keyboard Ctrl + Shift + Alt + Arrow
Shift + Alt + F changed all the indents in my file from 8 spaces to my default 4 spaces. Just what I was looking for :)
In my case "EditorConfig for VS Code" extention is overriding VSCode settings. If you have it installed, then check .editorconfig file in the root folder of the project.
Here is an example config. The "indent_size" sets the number of spaces for a tab.
How to turn 4 spaces indents in all files in VS Code to 2 spaces
- Open file search
- Turn on Regular Expressions
- Enter: ( )(?: )(\b|(?!=[,'";\.:\*\\\/\\[\]\(\)])) in the search field
- Enter: $1 in the replace field
How to turn 2 spaces indents in all files in VS Code to 4 spaces
- Open file search
- Turn on Regular Expressions
- Enter: ( )(\b|(?!=[,'";\.:\\*\\\/\[\]\(\)])) in the search field
- Enter: $1$1 in the replace field
NOTE: You must turn on PERL Regex first. This is How:
- Open settings and go to the JSON file
- add the following to the JSON file "search.usePCRE2": true
Hope someone sees this.
To set all existing files and new files to space identation to 2 just put it in your settingns.json (in the root of json):
you can add the language type of the configuration:
These days I use prettier.js and the js plugin as it takes care about spacing and other re aligning long lines as well as most anything else.
Simplified explanation with pictures for those that googled "Change indentation in VS Code"
Step 1: Click on Preferences > Settings
Step 2: The setting you are looking for is "Detect Indentation", begin typing that. Click on "Editor: Tab Size"
Step 3: Scroll down to "Editor: Tab Size" and type in 2 (or whatever you need).
Changes are automatically saved
Example of my changes
Setting the indentation in preferences isn't allways the solution. Most of the time the indentation is right except you happen to copy some code code from other sources or your collegue make something for you and has different settings. Then you want to just quickly convert the indentation from 2 to 4 or the other way round.
Step 1: Open settings.json in vscode
Step 2: Add the lines as below for the programming language (an example is below)
For typescript and javascript
Open settings.json in vscode The way to do that is ctrl+shit+p and type settings or cmd+shift+p on Mac. There is a global settings.json and a workspace settings.json. I prefer using prettier.js as my formatter because it has more style settings.
Problem: The accepted answer does not actually fix the indentation in the current document.
Solution: Run Format Document to re-process the document according to current (new) settings.
Problem: The HTML docs in my projects are of type "Django HTML" not "HTML" and there is no formatter available.
Solution: Switch them to syntax "HTML", format them, then switch back to "Django HTML."
Problem: The HTML formatter doesn't know how to handle Django template tags and undoes much of my carefully applied nesting.
Solution: Install the Indent 4-2 extension, which performs indentation strictly, without regard to the current language syntax (which is what I want in this case).
I wanted to change the indentation of my existing HTML file from 4 spaces to 2 spaces.
I clicked the 'Spaces: 4' button in the status bar and changed them to two in the next dialog box.
I use 'vim' extension. I don't how to re-indent without vim
To re-indent my current file, I used this:
Adding on: yes, you can use the bottom-right UI to configure the space settings. But if you have existing code that's not formatted to the new spacing, then you can right-click anywhere within the file and click Format Document. Took me a while to figure this out until I stumbled on this issue.
Ok I installed Ruby, Ruby Formatter, and Rufo as described. Changed from 2 to 4 spaces. Then right-click and Format. Nothing changed for me.
For me it was docs-markdown andDocs Authoring Pack. Microsoft's many modules messing with each other yet again! Disabled the extensions and now good to go again 😀
The Problem of auto deintending is caused due to a checkbox being active in the settings of VSCode. Follow these steps:
search 'editor:trim auto whitespace'
Uncheck The box
The following search-and-replace regex changes the number of spaces per indentation level from 4 to 2 in existing files. It's relatively easy to understand, reliable, and doesn't require installing anything.
Instructions
- Press Ctrl H (or ⌥⌘F on macOS).
- Make sure regex matching is on by clicking on the .* button in the search popup or pressing Alt R (or ⌥⌘R on macOS).
- In the Find field, enter ^(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?
- In the Replace field, enter $1$2$3$4$5$6$7$8$9
- Finally press Ctrl Enter (or ⌘Enter on macOS) to apply to the current file.
You could also use this in the Search pane on the left to do this across all files in your project. However, note that this should only be run once per file. It will mess up the indentation of files that already use 2 spaces.
Extra Credit: How It Works
The way the regular expression works is it matches groups (?: . ) of four spaces at a time at the beginning ^ . of each line, only capturing ( . ) the first two spaces. Each indentation level is optional . ? , so it works for as many indentation levels as the pattern is repeated and there are in each line. Then it replaces the whole pattern with only the captured spaces $1 , $2 , . effectively replacing every four-space indentation level with two spaces.
This pattern only works up to 9 indentation levels (I'm not sure if $10 would work, but if so this could be expanded indefinitely).
Extra Extra Credit: Extending
You could adapt the pattern to decrease the number of spaces per indentation level in a file from any original number to another lower target number.
Put the target number of spaces inside the inner parenthesis. Then, put the remaining original number of spaces in the outer parenthesis, so the total number of spaces in the pattern is the original.
For example, if you want to change the indentation level from 6 to 4, repeat this search pattern as many times as you like:
Читайте также: