Visual studio code как включить автозаполнение
Есть ли способ использовать компоненты или завершение HTML в коде Visual Studio? Потому что вводить каждую букву вручную - не лучшая идея, когда у нас есть классы вроде Bootstrap и т. Д. Например, завершение, как в Emmet: ul>li*2>a
Код Visual Studio обнаруживает расширения .jsx и по умолчанию добавляет поддержку emmet (я использую VS code 1.8.1)
Но если вы предпочитаете использовать расширение .js для всех ваших файлов реакции, вы можете связать режим JavaScript React с файлами .js в правом нижнем углу окна VS Code.
Если кто-то все еще борется с этой проблемой:
Я обнаружил, что просто установив
Не включает завершение HTML. Но, используя:
"emmet.includeLanguages": <>
Включите сокращения emmet на языках, которые не поддерживаются по умолчанию. Добавьте здесь сопоставление между языком и языком, поддерживаемым emmet.
Например:
Автоматическое закрытие тегов в форматах HTML, js и jsx
Работает "из коробки". То есть, после ввода закрывающей скобки открывающего тега закрывающий тег будет вставлен автоматически.
Emmet с базовым HTML в файлах .jsx
Работает "из коробки".
Эммет с базовым HTML в файлах .js:
Добавьте следующий параметр, необходимый для предложения сокращений Эммета и необходимый для последовательной работы расширения вкладок.
Emmet с настраиваемыми тегами (например, React Components) в файлах .js и .jsx
Добавьте следующую настройку:
Обратите внимание, что с этим параметром Emmet будет раскрывать все слова как пользовательские теги (а не только имена компонентов React).
Также обратите внимание, что при использовании Emmet для развертывания компонентов React в качестве настраиваемых тегов вам нужно фактически выбрать имя компонента из списка предложений и заполнить его первым (или ввести все имя вручную и закрыть меню предложений с помощью клавиши ESC). После того, как слово расширяется, вам нужно снова перейти на вкладку, чтобы Эммет развернул настраиваемый тег.
Есть запрос активной функции, чтобы потенциально удалить этот дополнительный шаг (автоматически расширять при выборе предложения, чтобы что он работает так же, как расширение стандартных тегов html).
Устранение неполадок
Убедитесь, что у вас установлена последняя версия VSCode.
Убедитесь, что вы не изменили следующие настройки по умолчанию:
Я решил проблему, просто выполнив следующие действия:
- В левом нижнем углу VSCode щелкните Javascript
- Затем вверху вы увидите список, нажмите «Настроить языковые настройки Javascript».
Добавьте в файл следующие строки:
Если вы хотите получить более подробную информацию, вы можете проверить эту ссылку.
Простой ответ в 2020 году
Сначала выберите Сопоставление файлов в правом нижнем углу окна.
Во-вторых, выберите Настроить сопоставление файлов для .js из меню, которое раскрывается в верхней центральной части окна. Измените его на JavaScript React.
Вы можете использовать расширение автоматического закрытия в коде Visual Studio. пс. когда вы устанавливаете расширение, автозаполнение не будет работать, пока вы не перезагрузите VS Code, просто повторно откройте VS Code или не перейдете к расширению автоматического закрытия тега и не нажмете «Обновить».
Выполните только эти два шага:
- Внизу VSCode, где определяется язык, нажмите на него
- Нажмите "Настроить языковые настройки Javascript (Babel)" . "или что-нибудь еще.
- вставьте этот код, разделив его запятой ',' и сохраните его.
"emmet.includeLanguages": < "javascript": "javascriptreact" >, "emmet.triggerExpansionOnTab": true
Я бросил все ответы, и эта конфигурация у меня сработала. пришлось включить язык, а также добавить syntaxProfile. без расширения триггера ничего не работало, но теперь я нажимаю только кнопку Tab, чтобы получить результат.
Я работал над разными проектами, и у меня есть большой файл настроек.
Я проверил настройки и обнаружил, что эти настройки все портят.
Я это прокомментировал. И все отлично работает в React Apps. Благодарность
2019: краткий ответ для React
Самый простой способ получить автозаполнение JSX / HTML в ваших проектах React - добавить это в свои пользовательские настройки или настройки рабочего пространства ( /.vscode/settings.json ):
Возможно, вам придется перезапустить VS Code, чтобы изменения вступили в силу.
P.S. Если вы не делаете это сопоставление для проекта React.js, то ответ Кехкашана Фазала, вероятно, должен сработать для вас.
Просто выберите соответствующий языковой режим в правом нижнем углу экрана: установите для него JavaScript React .
Мне потребовалось два шага, чтобы получить автоматически закрывающиеся теги в JSX.
- Следуйте приведенным выше инструкциям Кехкашана Фазала по настройке "emmet.includeLanguages"
- Загрузите расширение Auto Close Tag из VSCode ( formulahendry.auto-close-tag )
И теперь у вас есть красивые автоматически закрывающиеся JSX-теги!
Работает только в файлах JSX. Пусть это не работает с JS.
Автозаполнение для React Babel до вчерашнего дня у меня работало нормально.
Я использую VSCode (ver 1.27.2)
Основываясь на моем опыте, хотя я работаю с React . Обнаруженный язык на моем VSCode все еще ванильный JavaScript . И у Эммета не получилось.
- Один из способов заставить его снова работать - это изменить обнаруженный язык VSCode на JavaScript React . Это только для одного файла JS .
- Чтобы изменить его один раз полностью, нужно его связать.
Нажмите Configure File Association for .js.
И выберите JSX , что в моем случае я уже сделал.
- Для настройки на рабочем месте и в последнюю очередь, если ни один из них не работает для вас. Чтобы открыть его, перейдите в «Предпочтение» только до ctrl + , (comma) .
Введите и найдите emmet или Emmet . Затем скопируйте параметр, который хотите переопределить. В моем случае:
Примечание : я не пробовал использовать jsx только javascriptreact .
IntelliSense is a general term for various code editing features including: code completion, parameter info, quick info, and member lists. IntelliSense features are sometimes called by other names such as "code completion", "content assist", and "code hinting."
IntelliSense for your programming language
Visual Studio Code IntelliSense is provided for JavaScript, TypeScript, JSON, HTML, CSS, SCSS, and Less out of the box. VS Code supports word based completions for any programming language but can also be configured to have richer IntelliSense by installing a language extension.
Below are the most popular language extensions in the Marketplace. Select an extension tile below to read the description and reviews to decide which extension is best for you.
IntelliSense features
VS Code IntelliSense features are powered by a language service. A language service provides intelligent code completions based on language semantics and an analysis of your source code. If a language service knows possible completions, the IntelliSense suggestions will pop up as you type. If you continue typing characters, the list of members (variables, methods, etc.) is filtered to only include members containing your typed characters. Pressing Tab or Enter will insert the selected member.
You can trigger IntelliSense in any editor window by typing ⌃Space (Windows, Linux Ctrl+Space ) or by typing a trigger character (such as the dot character ( . ) in JavaScript).
Tip: The suggestions widget supports CamelCase filtering, meaning you can type the letters which are upper cased in a method name to limit the suggestions. For example, "cra" will quickly bring up "createApplication".
If you prefer, you can turn off IntelliSense while you type. See Customizing IntelliSense below to learn how to disable or customize VS Code's IntelliSense features.
As provided by the language service, you can see quick info for each method by either pressing ⌃Space (Windows, Linux Ctrl+Space ) or clicking the info icon. The accompanying documentation for the method will now expand to the side. The expanded documentation will stay so and will update as you navigate the list. You can close this by pressing ⌃Space (Windows, Linux Ctrl+Space ) again or by clicking on the close icon.
After choosing a method you are provided with parameter info.
When applicable, a language service will surface the underlying types in the quick info and method signatures. In the image above, you can see several any types. Because JavaScript is dynamic and doesn't need or enforce types, any suggests that the variable can be of any type.
Types of completions
The JavaScript code below illustrates IntelliSense completions. IntelliSense gives both inferred proposals and the global identifiers of the project. The inferred symbols are presented first, followed by the global identifiers (shown by the Word icon).
VS Code IntelliSense offers different types of completions, including language server suggestions, snippets, and simple word based textual completions.
Methods and Functions | method , function , constructor |
Variables | variable |
Fields | field |
Type parameters | typeParameter |
Constants | constant |
Classes | class |
Interfaces | interface |
Structures | struct |
Events | event |
Operators | operator |
Modules | module |
Properties and Attributes | property |
Values and Enumerations | value , enum |
References | reference |
Keywords | keyword |
Files | file |
Folders | folder |
Colors | color |
Unit | unit |
Snippet prefixes | snippet |
Words | text |
Customizing IntelliSense
You can customize your IntelliSense experience in settings and key bindings.
Settings
The settings shown below are the default settings. You can change these settings in your settings.json file as described in User and Workspace Settings.
Tab Completion
The editor supports "tab completion" which inserts the best matching completion when pressing Tab . This works regardless of the suggest widget showing or not. Also, pressing Tab after inserting a suggestions will insert the next best suggestion.
By default, tab completion is disabled. Use the editor.tabCompletion setting to enable it. These values exist:
- off - (default) Tab completion is disabled.
- on - Tab completion is enabled for all suggestions and repeated invocations insert the next best suggestion.
- onlySnippets - Tab completion only inserts static snippets which prefix match the current line prefix.
Locality Bonus
Sorting of suggestions depends on extension information and on how well they match the current word you are typing. In addition, you can ask the editor to boost suggestions that appear closer to the cursor position, using the editor.suggest.localityBonus setting.
In above images you can see that count , context , and colocated are sorted based on the scopes in which they appear (loop, function, file).
Suggestion selection
By default, VS Code pre-selects the previously used suggestion in the suggestion list. This is very useful as you can quickly insert the same completion multiple times. If you'd like different behavior, for example, always select the top item in the suggestion list, you can use the editor.suggestSelection setting.
- first - (default) Always select the top list item.
- recentlyUsed - The previously used item is selected unless a prefix (type to select) selects a different item.
- recentlyUsedByPrefix - Select items based on previous prefixes that have completed those suggestions.
"Type to select" means that the current prefix (roughly the text left of the cursor) is used to filter and sort suggestions. When this happens and when its result differs from the result of recentlyUsed it will be given precedence.
When using the last option, recentlyUsedByPrefix , VS Code remembers which item was selected for a specific prefix (partial text). For example, if you typed co and then selected console , the next time you typed co , the suggestion console would be pre-selected. This lets you quickly map various prefixes to different suggestions, for example co -> console and con -> const .
Snippets in suggestions
By default, VS Code shows snippets and completion proposals in one widget. You can control the behavior with the editor.snippetSuggestions setting. To remove snippets from the suggestions widget, set the value to "none" . If you'd like to see snippets, you can specify the order relative to suggestions; at the top ( "top" ), at the bottom ( "bottom" ), or inline ordered alphabetically ( "inline" ). The default is "inline" .
Key bindings
The key bindings shown below are the default key bindings. You can change these in your keybindings.json file as described in Key Bindings.
Note: There are many more key bindings relating to IntelliSense. Open the Default Keyboard Shortcuts (File > Preferences > Keyboard Shortcuts) and search for "suggest".
Troubleshooting
If you find IntelliSense has stopped working, the language service may not be running. Try restarting VS Code and this should solve the issue. If you are still missing IntelliSense features after installing a language extension, open an issue in the repository of the language extension.
Tip: For configuring and troubleshooting JavaScript IntelliSense, see the JavaScript documentation.
A particular language extension may not support all the VS Code IntelliSense features. Review the extension's README to find out what is supported. If you think there are issues with a language extension, you can usually find the issue repository for an extension through the VS Code Marketplace. Navigate to the extension's Details page and select the Support link.
Next steps
-
- Get the most out of your JavaScript development, including configuring IntelliSense. - See an example of IntelliSense in action in the Node.js walkthrough. - Learn how to set up debugging for your application. - Learn how to create extensions that add IntelliSense for new programming languages.
Common questions
Why am I not getting any suggestions?
This can be caused by a variety of reasons. First, try restarting VS Code. If the problem persists, consult the language extension's documentation. For JavaScript specific troubleshooting, please see the JavaScript language topic.
Why am I not seeing method and variable suggestions?
This issue is caused by missing type declaration (typings) files in JavaScript. You can check if a type declaration file package is available for a specific library by using the TypeSearch site. There is more information about this issue in the JavaScript language topic. For other languages, please consult the extension's documentation.
Unofficial TabNine client (all-language autocomplete) for the VS Code.
Difference between official TabNine extension:
- Updated README to contain as much documentation as possible.
- Added more VS Code settings and TabNine commands.
- Kept only . and : trigger characters.
- Removed restriction to show only 1 result if end of the word is . or :: .
- Always shows correct suggestion detail for e.g. 41% or TabNine .
- Won't preselect TabNine suggestions.
- De-prioritized TabNine suggestions to be at the end of the list whenever it's possible.
- Changed TabNine suggestions kind from property to text in order to avoid misunderstanding which suggestions are from TabNine.
- Triggers suggestion list if suggestion ends with . or :: .
- Included postfix in suggestions for e.g. instead of log( it will show log() .
- Disabled suggestions in Git input (commit message), for VS Code JSON files like settings.json , etc.
- Starts TabNine process on VS Code startup.
- Automatically downloads latest TabNine binary on VS Code startup.
- Bundled extension for faster startup.
- For a full list of changes you can take a look at the CHANGELOG.
Installation
Install through VS Code extensions, search for Code Autocomplete by Benas Svipas . If you can't find extension by name try to search by publisher name.
Usage
After installing this extension latest TabNine binary is automatically downloaded. After TabNine binary is downloaded you can immediately start to use TabNine in VS Code, you don't need to do anything additionally. But if you want to improve experience with TabNine, continue to read below.
Semantic completion
Semantic completion permits suggestions which make use of language-specific information via Language Server Protocol. In other words it improves suggestions.
If you want to enable semantic completion for specific language open file in text editor and use command palette or type command in active file.
Plans
- Project size limit: 400 KB
- Code completions for all languages: ✓
- Code completions based on your code: ✓ completions based on millions of open source projects: ✓
- Works offline: ✓ - use GPU-accelerated cloud servers (optional): x
- Priority support: x
- Self-hosted option: x
- Train a model specialized for your code: x
- Project size limit: Unlimited
- Code completions for all languages: ✓
- Code completions based on your code: ✓ completions based on millions of open source projects: ✓
- Works offline: ✓ - use GPU-accelerated cloud servers (optional): ✓
- Priority support: ✓
- Self-hosted option: x
- Train a model specialized for your code: x
- Project size limit: Unlimited
- Code completions for all languages: ✓
- Code completions based on your code: ✓ completions based on millions of open source projects: ✓
- Works offline: ✓ - use GPU-accelerated cloud servers (optional): ✓
- Priority support: ✓
- Self-hosted option: ✓
- Train a model specialized for your code: ✓
Local vs Cloud
TabNine Local uses your machine's CPU to run a deep learning model for providing completions. Your code stays on your machine.
Cloud
Enabling TabNine Cloud sends small parts of your code to our servers to provide GPU-accelerated completions. Other than for the purpose of fulfilling your query, your data isn't used, saved or logged in any way.
Commands & Settings
Commands below are available in VS Code command palette.
- TabNine: open config : opens configuration panel
- TabNine: restart : restarts TabNine
- TabNine: enable semantic completion for current language : enables semantic completion for current language
- TabNine: disable semantic completion for current language : disables semantic completion for current language
Commands below are available in VS Code active file, to use them simply type the command.
- TabNine::config : opens configuration panel
- TabNine::version : returns current TabNine version
- TabNine::config_dir : returns directory where TabNine stores its configuration
- TabNine::active : checks whether TabNine has been activated
- TabNine::restart : restarts TabNine
- TabNine::become_beta_tester : enables beta releases of TabNine
- TabNine::disable_auto_update : disables automatic updates
- TabNine::enable_auto_update : enables automatic updates
- TabNine::ignore_semantic : ignores semantic completion error messages
- TabNine::unignore_semantic : enables semantic completion error messages
- TabNine::sem : enables semantic completion for current language
- TabNine::no_sem : disables semantic completion for current language
Settings below are available in VS Code.
Contributing
Feel free to open issues or PRs!
Credits
All credits belongs to Codota, TabNine and Jacob Jackson.
License
This repository includes source code of VS Code extension as well as bundled TabNine binaries. The MIT license only applies to the source code of VS Code extension, not the binaries! The binaries are covered by the TabNine End User License Agreement.
Я использую новый код Visual Studio , который явно еще не готов к использованию в прайм-тайм, но я надеюсь решить возникшую у меня проблему.
Каждый раз, когда вы вводите SQL-файл, c a s e он автоматически добавляется end , как если бы вы строили case блок. Даже если вы находитесь в комментарии или используете Case как часть слова (например, select CaseID from. ). Я бы хотел полностью отключить всю эту ерунду, поскольку она не очень хорошо справляется с автоматическим завершением вещей для меня.
Единственные параметры конфигурации, которые я могу найти, я уже установил:
Есть ли другие идеи, как это остановить?
Также верно для таких вещей, как b e g i n (он добавляет end ) и я уверен, что многое другое.
В самой последней версии Visual Studio Code я обнаружил, что
конфигурация отключает это поведение.
Спасибо тебе за это. Я печатал render( и получал CanvasRenderingContext2D вместо этого. WTF. Это не позволяло мне писать то, что я набирал, без отключения символа фиксации. Какой ужасный дефолт. Редакторы не должны заменять то, что вы печатаете, без вашего разрешения.
Еще хуже, когда он меняется на что-то безумное и автоматически вставляет импорт для этого нежелательного символа ..
@shybovycha Да, я добавляю "editor.acceptSuggestionOnCommitCharacter": false в settings.json вручную, но он работает не так, как ожидалось. Я имею в виду, что он все еще автоматически завершается после перезапуска VScode. Не знаю почему.
Благодарю вас за то, что getData + ( => __acrt_get_locale_data_prefix() просто не способствует моей производительности.
Я изменил это, потому что это сводило меня с ума от импорта JS. Однако мне также пришлось добавить: "editor.quickSuggestions": false, чтобы каждый раз, когда я набирал «const», я не получал огромного и нерелевантного списка, требующего щелкнуть ESC между ключевым словом и именем переменной.
К настоящему времени, год спустя, Visual Studio Code довольно крут и готов к использованию в прайм-тайм. Но я до сих пор не нашел способа просто полностью отключить автозаполнение.
Обычно я кладу это в свой, settings.json чтобы попробовать выключить его для рабочего места. Но мне еще предстоит это оценить.
Я , вероятно , используя новую версию , так как это было написано , но для меня "editor.quickSuggestions" это объект , где можно настроить 3 дополнительных значений: < "other": false, "comments": false, "strings": false >. Кроме того, возможно, VS Code достаточно умен, чтобы увидеть "editor.quickSuggestions": false и установить для всех 3 значение false
пожалуйста, посмотрите видео. На старте нормальная ситуация (из учебника), вторая часть показывает мою проблему.
видео с проблемой
например, transform класс не показывают предложение или автозаполнение.
Изображение с проблемой:
версия Unity: 5.5.2f1
Visual studio 2015
Установлены средства Visual Studio для Unity
нет автоматического завершения, потому что скрипт говорит"Разное Файлы " вместо названия проекта. Взгляните на изображение ниже, которое пришло из видео в вашем вопросе:
2.Это также может произойти из-за того, что Unity разбился, когда Visual Studio все еще открыта, поэтому повреждает некоторые файлы.
3.Это может произойти, потому что Unity был закрыт, а затем снова открыт, но больше не подключен к Visual Studio. При открытии Visual Studio вы получаете"Разное Файлы " и нет автоматического завершения.
4.Это может произойти, когда инструменты Visual Studio для unity is не установить.
5.Когда вы создаете сценарий из Unity, быстро откройте его до завершения обработки Unity или до завершения анимации круглых значков.
Я не могу сказать, какой из них вызывает проблему, но я рассмотрю наиболее вероятное решение для исправления этого.
2.Из редактора Unity перейдите в редактировать --> предпочтения. --> Внешние Инструменты. На Внешний Редактор Скриптов выпадающее меню, измените это на Visual Studio 2015.
1.Из Visual Studio, перейдите к инструменты --> параметры. --> инструменты для Unity --> разное. Под показать значок подключения, установить true затем перезапустите Visual Studio.
все еще не исправлено?
1.Закройте Visual Studio.
2.Из Unity повторно импортируйте проект, перейдя в активы --> реимпорт Все!--3-->.
все еще не исправлено?
1.Нажмите на Показать Все Файлы.
2.Выберите сценарий, который не выполняет автозаполнение, затем щелкните правой кнопкой мыши и выберите Включить В Проект.
еще не исправлена?
заслуга chrisvarnz для этого конкретного решения, которое, похоже, сработало для нескольких людей.
1.Закройте Visual Studio
2.Перейдите в каталог проекта и удалите все созданные файлы Visual Studio.
Это расширения файлов для исключить:
предположим, что имя вашего проекта называется "Target Shoot", вот как должны выглядеть файлы для удаления:
- Цель Стрелять.csproj файл
- Цель Стрелять.Редактор.csproj файл
- Цель Стрелять.Редактор.csproj файл.
- цель Стрелять.Игрок.csproj файл
- Цель Стрелять.Игрок.csproj файл.
- Цель Стрелять.sln
больше ничего не удалять.
3.Дважды щелкните по скрипту еще раз из Unity который должен создать новый файл Visual Studio, а затем открыть Visual Studio. Это может решить вашу проблему.
если не работает, проверьте если у вас возникли этой ошибка:
задача "GetReferenceNearestTargetFrameworktask" не найдена
1.Установить Диспетчер Пакетов NuGet Для С здесь.
2.Перезапустите Visual Visual.
посмотреть этой ответа для получения дополнительной информации.
- выберите сломанный файл в обозревателе решений.
- открыть его свойства.
- переключить поле " Build Action "с" Compile "на"None".
- затем переключите его обратно на "Compile".
Это каким-то образом убьет синхронизацию между Unity и Visual Studio.
в следующий раз, когда Visual Studio перезагрузит проект, он предложит предупреждающий. Просто нажмите "отбросить".
выгрузить и перезагрузить проект в Visual Studio:
- щелкните правой кнопкой мыши проект в Обозреватель
- выберите Выгрузить Проект
- выберите Перезагрузить Проект
Я нашел это решение, чтобы работать лучше (проще всего), столкнувшись с проблемой несколько раз.
- выберите проект в Visual Studio
- нажать кнопку "Обновить"
сегодня я столкнулся с теми же проблемами, используя Visual Studio 2017 15.4.5 с Unity 2017.
Я смог устранить проблему, щелкнув правой кнопкой мыши по проекту в Visual Studio и изменив целевую платформу с 3.5 на 4.5.
надеюсь, что это поможет кому-то еще в аналогичном сценарии.
Два Альтернативных Варианта:
@singleton указал мне в этом направлении. Вместо изменения целевого объекта в Visual Studio следует изменить его в Unity, так как проект создается автоматически.
Сначала удалите автоматически созданные файлы Visual Studio: .csproj файл .пользователь .sln
затем из Unity перейдите в PlayerSettings и в разделе "Другие настройки" измените "версию среды выполнения сценариев" со стабильной 3.5 на экспериментальную 4.6.
однако, это не исправило это для меня.
Я заметил, что все ссылки на код, связанный с Unity, были отмечены желтым предупреждением. Проверьте свои журналы ошибок и посмотрите, так ли это. В частности, см., Если вы получаете следующую ошибку: getreferenceNearestTargetframeworktask
Если так попробовать: Снова запустите установщик Visual Studio.
в инструментах сборки 2017 нажмите кнопку Изменить,
обеспечить "Цели Nuget и задачи сборки" отмечены галочкой. Это должно стать галочкой, если вы нажмете на универсальную разработку платформы Windows.
Я нашел свое решение, создав .cs-файл из самой visual studio вместо редактора unity
- правой кнопкой мыши на папке проекта в обозревателе решений
- добавить > новый элемент
- введите "unity" в поле поиска в правом верхнем углу
- выберите "CSharp MonoBehaviour"
- назовите свой скрипт внизу и нажмите Add
для Windows или macOS:
при установке, убедитесь, что вы включили установку
оттуда, вы должны быть в состоянии видеть то, что вы ищете.
для Linux (предложение):
попробовать MonoDevelop выступает - Дополнительная Информация, он обеспечивает завершение кода / подсказки.
мой автозаполнение также не работает, потому что инструменты Visual Studio для Unity не был установлен. После установки удалите автоматически созданные файлы Visual Studio. Другие сказали, что вы снова открываете файл, и проблема решена, но это не так.
ни одно из вышеперечисленных решений не сработало для меня. Однако я открыл имя проекта.Файл CSPROJ и вручную добавил новый файл, и он работал как charm
я исправил это, изменив цель в Unity как -
после этого Visual Studio работала отлично, и автозамена тоже была исправлена.
Читайте также: