Compare commits

...
Author SHA1 Message Date
Sean McManus 6bc6d4931d Fix buggy progress message. (#4039) 2019-08-08 17:57:58 -07:00
Bob Brown (DEVDIV) b7bd343019 tslint 2019-08-08 17:19:32 -07:00
Bob Brown 1a71059316 fix a broken squiggle (#4037) 2019-08-08 17:16:55 -07:00
Bob Brown (DEVDIV) d9ca558f74 Temporarily disable architecture checks. 2019-08-08 16:51:35 -07:00
Sean McManus c9a114b38f Add Find All References (#4016)
Add Find All References.
2019-08-08 16:16:00 -07:00
Bob Brown 44298673fc Implement not supported message for arm platform and alpine containers (#4027) 2019-08-08 12:50:19 -07:00
Bob Brown c9869894de Merge branch 'master' into dev/andris/NotSupportedMessage2 2019-08-08 10:14:57 -07:00
Jorge Reyes Paniagua 41893b049d Add support for x86 architecture (#4005)
* add 32 bit architecture files

* add the option for 32 bit architectures

* changes on Intellisense mode description
2019-08-08 10:06:31 -07:00
Bob Brown e9659f2c6e Merge branch 'master' into dev/andris/NotSupportedMessage2 2019-08-08 09:55:50 -07:00
Bob Brown (DEVDIV) 7f9e5758bc Merge branch 'dev/andris/NotSupportedMessage2' of https://github.com/Microsoft/vscode-cpptools into dev/andris/NotSupportedMessage2 2019-08-08 09:51:38 -07:00
Bob Brown (DEVDIV) 03fa10fbd1 tslint 2019-08-08 09:51:25 -07:00
Michelle Matias d3d9655534 Deprecate old documentation and update readme files (#3984) 2019-08-08 09:47:35 -07:00
Bob Brown 586068e874 Merge branch 'master' into dev/andris/NotSupportedMessage2 2019-08-08 09:42:53 -07:00
Bob Brown (DEVDIV) 8e69cde774 return an empty API 2019-08-08 09:41:13 -07:00
Griffin Downs ba2da8d98c Vcpkg integration (#3791) 2019-08-08 09:28:18 -07:00
Andreea Isac 007292cbda Move the unsupported error message higher up 2019-08-07 08:36:27 -07:00
Michelle Matias b608921b9d Add IntelliSense configuration property: compilerArgs (#3950) 2019-08-06 15:26:18 -07:00
Andreea Isac 8e31eb99d9 Implement not supported message for arm platform and alpine containers 2019-08-06 14:04:52 -07:00
Colen Garoutte-Carson ceac5cb95a VS Code themes that match VS Light and Dark, including semantic tokens (#4019) 2019-08-06 10:41:25 -07:00
pi1024e 14f2c9f030 Typo and grammar fixes in documentation (#4014) 2019-08-01 14:11:15 -07:00
Bob Brown 3d40ac231a Support for the V3 API (#3987)
* Support for the V3 API
2019-07-30 11:10:40 -07:00
Sean McManus baf6f50be3 Fix error in open file scenario. (#3986)
* Fix error in open file scenario.
2019-07-26 14:50:08 -07:00
Colen Garoutte-Carson d9de95ca15 Update examples in colorization.md to color entity.name.type instead of entity.name.type.class (#3973) 2019-07-24 17:10:04 -07:00
Colen Garoutte-Carson 2b3d2ac541 Remove unused 'nogrammar' files (#3974) 2019-07-24 16:56:49 -07:00
Colen Garoutte-Carson 4b4c93cd94 Restore updated doc for enhanced colorization (#3955) 2019-07-22 13:04:01 -07:00
Colen Garoutte-Carson 2cde4d6f1a Update changelog for 0.24.1 release (#3945) 2019-07-18 18:34:48 -07:00
Colen Garoutte-Carson 066c8f1247 Temporarily revert documentation until changes to feature ship (#3944) 2019-07-18 17:31:14 -07:00
Colen Garoutte-Carson 4495d0b26d Improve scope names used by Enhanced Colorization (#3896) 2019-07-18 16:30:05 -07:00
Jorge Reyes Paniagua b1d50e4336 file watcher compiler commands (#3938)
* use resolve path to create valid file watcher

* convention fix

* changes for improve implementation

* Moved validation to mantain logic
2019-07-18 15:52:51 -07:00
Sean McManus cb035dd1f2 Update dependencies. (#3931) 2019-07-15 17:05:50 -07:00
Jorge Reyes Paniagua 3faaca14c0 Add c++20 to enums (#3905)
* Add c++20 to enums

* update msvc version in json files
2019-07-15 14:47:00 -07:00
Michelle Matias 53107bc57c Update c_cpp_properties.json description in Config UI and documentation (#3872)
* Update c_cpp_properties.json desc

* minor text change

* fix casing on "the"

* update names

* update ipch on FAQ

* fix text

* fix wording

* update link in FAQ

* update ipch name and title

* missing s

* use macOS
2019-07-08 15:59:52 -07:00
Sean McManus d38740c098 Update dependencies and fwlinks. (#3885)
* Update dependencies and fwlinks.
2019-07-05 17:52:48 -07:00
Sean McManus ccc18a6f66 Add more linting and fix linter issues. (#3847)
* Add more linting and fix linter issues.
2019-07-05 14:39:06 -07:00
Colen Garoutte-Carson e26cae6838 Fix issue with didClose received after didOpen (#3844) 2019-07-03 21:05:02 -07:00
Sean McManus 9ea53681a5 Fix bug with mac crash version reading. (#3875) 2019-07-03 20:17:57 -07:00
Colen Garoutte-Carson 6bc49d595e Update release notes and changelog for June 2019 release (#3868)
* Update release notes and changelog for June 2019 release
2019-07-02 18:29:19 -07:00
Pierson Lee 6b3c0f1b10 Update default for externalConsole to false (#3828) 2019-07-02 17:12:23 -07:00
Sean McManus 35501431f8 Add the binaryVersion to Mac crash telemetry. (#3865) 2019-07-02 11:43:56 -07:00
Colen Garoutte-Carson 27a3c9958d Add output of current configuration to diagnostics command (#3866) 2019-07-01 19:38:25 -07:00
Sean McManus 5b3d4ebf44 Update dev dependencies and ThirdPartyNotices.txt (#3863)
* Update dev dependencies.
* Update ThirdPartyNotices.txt
2019-07-01 15:50:40 -07:00
Andrew Wang cfc064efcd Support resolving ${env:...} in sourceFileMap (#3857)
* Support resolving ${env:...} in sourceFileMap

This PR addresses ${env:...} variables in sourceFileMap keys and values.
2019-07-01 11:25:51 -07:00
Colen Garoutte-Carson 4f7a64a1a2 Add support parent scope syntax in theme loader for enhancedColorization (#3855) 2019-07-01 11:05:32 -07:00
Sean McManus c84cb36004 Update changelog for 0.24.0-insiders3. (#3850) 2019-06-27 19:10:25 -07:00
Andrew Wang 0502351002 Update envFile variable substitution (#3848)
* Update envFile variable substitution

In launch.json, the `envFile` configuration can substitute
${workspaceFolder}, ${workspaceRoot} and ${env::???}.

* Fix lint issues
2019-06-27 17:52:58 -07:00
Andrew Wang 5de420ee70 Decrease F5 workflow time w/ VSCode (#3843)
* Decrease F5 workflow time w/ VSCode

webpack is being called twice. Once with --mode production and then
rewritten with --mode development. Fixing tasks and launch.
2019-06-27 15:57:49 -07:00
Bob Brown 6a73275924 This message wasn't being sent by the language server (#3840) 2019-06-27 12:29:40 -07:00
Michelle Matias d12591062e validate advanced settings input (#3838) 2019-06-27 11:45:35 -07:00
Colen Garoutte-Carson 3926110b33 Update colorization.md to remove (syntactic) identifier (#3832) 2019-06-25 18:16:38 -07:00
Bob Brown f5975e6534 update fwlink for abtesting (#3830) 2019-06-25 13:19:07 -07:00
Pierson Lee b55e2c7ac5 Add useful links at the top of the README.md in the extension (#3808)
* Add useful links at the top of the README.md in the extension

* add liveshare badge
2019-06-25 10:52:38 -07:00
Colen Garoutte-Carson 73fda38d71 Enable enhanced colorization by default (#3824)
* Enable enhanced colorization by default
2019-06-25 10:21:11 -07:00
TheGreatRambler 9211292b60 Update FAQ.md (#3812) 2019-06-25 10:19:03 -07:00
Colen Garoutte-Carson f63a8da581 Remove syntactic colorization in favor of text mate colorization (#3821) 2019-06-24 17:42:10 -07:00
Colen Garoutte-Carson fd314b1b04 Handle comma-delimited scopes in JSON themes (#3814) 2019-06-21 16:54:48 -07:00
Sean McManus ea52c76595 Change to use machine scopes for clang_format_path.. (#3810)
* Change to use machine scopes for clang_format_path.
2019-06-21 11:49:23 -07:00
Colen Garoutte-Carson 7659e2826b Remove incorrect editor background setting (#3806) 2019-06-20 11:34:42 -07:00
Michelle Matias 8e898151f6 resolve cache path (#3807) 2019-06-20 11:20:24 -07:00
Colen Garoutte-Carson b2b0ad37af Avoid applying edits to cached colorization tokens until needed (#3793) 2019-06-17 18:12:28 -07:00
Bob Brown cee6ebe1d9 Disabling enhanced colorization for now. (#3785) 2019-06-17 17:31:40 -07:00
Colen Garoutte-Carson 566e657fad Make handleSquiggles no longer dependent on special escaping in parsePropertiesFile (#3778) 2019-06-17 10:38:59 -07:00
Colen Garoutte-Carson db1f631396 Fix colorization issue where only 1 of multiple get colorized (#3777) 2019-06-14 13:29:06 -07:00
Colen Garoutte-Carson 426c08293d Attempt to address colorization issue with flickering on Mac (#3775) 2019-06-14 13:00:06 -07:00
Colen Garoutte-Carson 631a4452d0 Enable enhancedColorization by default. Fix refresh race in colorization.ts (#3770) 2019-06-13 16:46:46 -07:00
Michelle Matias 9b29698b0e fix cl.exe check and other UI fixes (#3769) 2019-06-13 15:39:18 -07:00
Colen Garoutte-Carson b5c94e9e1f Address issue with AB default not applied. Fix issue with non file URIs (#3767) 2019-06-13 14:18:48 -07:00
Sean McManus 384cd35d6b Fix configuration squiggles not appearing for multiple occurrences of the same error. (#3766) 2019-06-13 13:55:55 -07:00
Sean McManus 2d4df9149f Update changelog for Insiders. (#3763)
* Update changelog for Insiders.
2019-06-12 19:44:57 -07:00
Michelle Matias d3c2ccbb93 return empty string if path is not set (#3761) 2019-06-12 17:15:56 -07:00
Colen Garoutte-Carson c637221b92 Update colorization support to only return tokens for currently visible ranges (#3738) 2019-06-12 16:28:40 -07:00
Michelle Matias 814f01b263 Change cache path default (#3747)
* change cache path default

* update check for falsy

* change default path name and location

* Update cache path description in json
2019-06-12 15:20:41 -07:00
Andrew Wang b763aa57d3 Fix windows remote attach experience (#3757)
* Check host machine for specific quotes for command

Attach to process is not working on Windows OS due to the single quote
then double inner quote. However, this is required for linux because if
you do not, it will evaluate the variables within the double quotes.
2019-06-12 15:06:02 -07:00
Michelle Matias 54b1e69975 Update IntelliSense mode and compiler compatibility validation (#3752)
* get compiler name

* get name for case when there are no args
2019-06-12 14:03:14 -07:00
Andrew Wang dacfe08033 Enable 'envFile' for cppdbg (#3723)
* Enable 'envFile' for cppdbg

This PR allows the cppdbg configuration to set environment variables
via a envFile.

Example envFile:
ENVIRONMENT_VAR_1=Hello
ENVIRONMENT_VAR_2=15
2019-06-10 17:54:00 -07:00
Michelle Matias f5aa7dc33e change text of include path. code clean up. (#3743) 2019-06-07 16:27:34 -07:00
Michelle Matias 90c6e9876a Configuration UI - V2 (#3732)
* edit config name

* button active style

* refactor settings.ts

* clean up configurations.ts

* advanced settings

* telemetry compilerPath & listen to forecedInclude

* fix lint

* fix spelling

* spelling & fix contrast color for buttons

* remove outline of button on click

* save view state & code cleanup
2019-06-07 09:46:43 -07:00
Bob Brown 9fa950db6a Add a command to rescan the workspace (#3658) 2019-06-05 15:12:29 -07:00
Bob Brown 8ea627e085 Telemetry not being logged for intellisense mode mismatch (#3726) 2019-06-04 11:39:47 -07:00
Andrew Wang 536d38e3bf Remove minify from webpack compile (#3724)
This will cause the code to still be webpacked but will not minify it.
2019-06-03 13:52:11 -07:00
Sean McManus c10c626869 Change multi-root storagePath to use the index instead of name. (#3715)
* Change multi-root storagePath to use the index as a subfolder when the name is a duplicate.
2019-05-31 14:47:45 -07:00
Sean McManus 24d37bc233 Update TPN from plist dependency. (#3719) 2019-05-31 13:35:06 -07:00
Sean McManus 158719cf46 Fixes to gcc problem matcher. (#3714)
* Fixes to gcc problem matcher.
2019-05-30 14:41:21 -07:00
Colen Garoutte-Carson b6327ed6c3 Add colorization support to cpptools (#3651) 2019-05-30 13:42:18 -07:00
Michelle Matias c60a2c6752 Add list of detected compiler paths to IntelliSense config UI (#3708)
* editable select control for compilerPath field

* set compiler path values

* update comments and width

* normalize path, update description
2019-05-30 11:27:49 -07:00
Michelle Matias 1f7c27d7f9 fix elementId.configName (#3692) 2019-05-24 17:25:50 -07:00
Karsten Thoms 1d82458a3a Fix typo in intelliSenseMode description (#3682) 2019-05-23 15:54:53 -07:00
Michelle Matias 25d122c3f7 Add telemetry to configuration UI (#3661)
* add telemetry to config ui

* cache telemetry and log when settingsPanel object is disposed

* fix linting
2019-05-22 14:41:39 -07:00
Andreea Isac 627acc535e Refresh IntelliSense time (#3680)
* Flame on timing

* Fixed linter errors

* Log IntelliSense refresh time information for debug logging level.

* Rephrasing log message

* Print the message in the output window instead of the console.
2019-05-22 14:03:04 -07:00
Sean McManus 515d858b4d Fix ${workspaceFolderBasename} resolving to "untitled", and add ${workspaceStorage} (#3643)
* Fix ${workspaceFolderBasename} resolving to "untitled".
* Enable ${workspaceStorage} in intelliSenseCachePath.
2019-05-21 15:26:05 -07:00
Bob Brown 7ec15af47c Clarify data collection policy #3299 (#3660) 2019-05-17 11:22:14 -07:00
Bob Brown cac58e9f88 Fix unit tests (#3659) 2019-05-16 11:46:29 -07:00
Sean McManus 0c28725628 Update versions. (#3641)
* Update versions.
2019-05-14 18:03:16 -07:00
Sean McManus ae564c8428 Update changelog for 0.23.1. (#3629) 2019-05-10 15:12:41 -07:00
Sean McManus 5241ce28e0 Add telemetry for missing language service extension binary (#3611)
Add telemetry for missing language service extension binary
2019-05-10 14:55:10 -07:00
Sean McManus febb880e32 Fix launch.json creation with intelliSenseEngine Disabled. (#3612)
* Fix launch.json creation with intelliSenseEngine Disabled.
2019-05-09 15:56:30 -07:00
Sean McManus d1c344b944 Fix .vscodeignore issues. (#3623) 2019-05-09 14:49:00 -07:00
Colen Garoutte-Carson a19d1c325e Fix issue with extension context not being set before initializeTemporaryCommandRegistrar (#3622) 2019-05-09 13:48:23 -07:00
Sean McManus 82225338c4 Update ThirdPartyNotices.txt -- removed a lot of unnecessary stuff. (#3606)
* Update ThirdPartyNotices.txt -- removed a lot of unnecessary stuff.
* Minor update to changelog.
2019-05-08 12:11:55 -07:00
Sean McManus fa72ab582d Seanmcm/update dependencies (#3605)
* Update the dependencies.
2019-05-07 17:19:57 -07:00
Sean McManus 0b3e43c93f Update TPN. (#3601) 2019-05-07 12:51:21 -07:00
Sean McManus 8b332a7795 Update version and fwlinks. (#3600)
* Update version and fwlinks.
* Some package-lock.json changes.
2019-05-07 12:18:10 -07:00
Sean McManus 4e20f27127 Seanmcm/0 23 0 changelog (#3593)
* 0.23.0 changelog.
2019-05-06 18:31:48 -07:00
Michelle Matias 4e2f1b8ba5 update release notes for 5-2019 (#3592)
* update release notes for 5-2019
2019-05-06 18:21:54 -07:00
Sean McManus 0cffa4e27a Dev/waan/fix test run (#3581)
* Fix integration tests and fail if tests fail
2019-05-06 16:51:51 -07:00
Colen Garoutte-Carson b67e701fc9 Address issue with trailing backslashes in config path not squiggled (#3573) 2019-05-01 15:58:19 -07:00
Sean McManus 77f3747630 Fix includePath code actions and configuration actions. (#3576)
* Fix `includePath` code actions amd configuration actions.
2019-05-01 14:26:55 -07:00
Sean McManus dc8813f449 Fix undefined access if there's no includePath. (#3572)
* Fix undefined access if there's no includePath.
2019-05-01 11:38:57 -07:00
Sean McManus e0543a64c1 Seanmcm/0 23 0 insiders2 changelog2 (#3571)
* Update changelog for crash fixes.
2019-04-30 16:12:52 -07:00
Sean McManus e5b118c707 Update changelog for 0.23.0-insiders2. (#3570)
* Update changelog for 0.23.0-insiders2.
2019-04-30 14:23:34 -07:00
Colen Garoutte-Carson f465766d1e Undo tab size change (#3568) 2019-04-30 12:29:15 -07:00
Michelle Matias 7f4fc339c7 Add input validation on configuration UI (#3563)
* show errors on config UI
2019-04-29 19:10:15 -07:00
Sean McManus 788cee3ecf Fix out dir not getting created. (#3562) 2019-04-29 16:42:43 -07:00
Michelle Matias 05939c19a9 add depends on (#3561) 2019-04-29 16:14:24 -07:00
Colen Garoutte-Carson 110e683790 Work around issue with getting stale contents from openTextDocument (#3545)
* Work around issue with getting stale contents from openTextDocument

* Avoid calling openTextDocument when creating a new file, and use only writeFile.  Unsubscribe from window activation when settings UI is not visible.

* Switch to using editorTabSize for settings file
2019-04-29 15:17:01 -07:00
Andrew Wang 6a88c9917b Adding support for .env files for cppvsdbg (#3500)
* Adding support for .env files for cppvsdbg

This PR allows users to have a .env file that listed as
KEY=VALUE or KEY="VALUE WITH SPACE" to be used as environment variables
when launching a process. Anything that begins with '#' is treated as a
comment. Blank lines are ignored.

This .env file will be used if envFile passed in with the launch.json.
It will also work with the existing environment variable, however
anything listed in the .env file will overwrite anything from the
environment field in the launch.json.

* Update 'envFile' description and add documentation
2019-04-26 14:59:43 -07:00
Sean McManus 2ac33971ed Update webpack dependency, fix linter errors (#3544)
* Update webpack dependency.
* Fix lint errors.
2019-04-26 14:43:29 -07:00
Sean McManus a5905276ce Bobbrow/webpack (#3411)
* Use webpack to consolidate JavaScript files
2019-04-25 18:34:15 -07:00
Colen Garoutte-Carson d6726e5d42 Switch to using the installExtension command for offline/insider vsix installing (#3521) 2019-04-25 18:02:23 -07:00
Colen Garoutte-Carson aa6873b84e Work around vscode not treating .C files as C++ (#3536) 2019-04-25 17:53:07 -07:00
Colen Garoutte-Carson e3ddec66ee Update config squiggle parsing to squiggle bad paths delimited by semicolons (#3517) 2019-04-25 17:45:42 -07:00
Sean McManus 26d83d136e Skip first install release notes (#3534)
* Don't show release notes if the extension has never been installed before
2019-04-25 17:13:08 -07:00
Colen Garoutte-Carson 6f4439ca88 Various settings UI load/save related changes (#3529) 2019-04-25 10:09:10 -07:00
Colen Garoutte-Carson 3fbeba779c Unescape backslashes in settings for UI (#3527) 2019-04-24 13:49:43 -07:00
Colen Garoutte-Carson cfc908a1ac Update Select Configurations command to offer Edit Configs JSON option (#3519)
* Update Select Configurations command to offer Edit Configs JSON option

* Add 'Edit Configurations (UI)' option to Select Configuration menu
2019-04-24 11:19:53 -07:00
108 changed files with 11290 additions and 7028 deletions
+1 -54
View File
@@ -1,54 +1 @@
# Pipe Transport
Pipe Transport allows communication through a pipe program to a remote shell. An example on Linux would be `ssh`.
## How-To
We have added `"pipeTransport"` as an option within the **launch.json** file. The structure looks as follows:
```json
"pipeTransport": {
"pipeCwd": "/usr/bin",
"pipeProgram": "/usr/bin/ssh",
"pipeArgs": [
"-pw",
"<password>",
"[email protected]"
],
"debuggerPath": "/usr/bin/gdb"
},
```
The `pipeArgs` can be any set of arguments necessary to setup and authenticate the pipe connection. In the example, a password is used but you can also use an ssh key.
You may also need to add a `sourceFileMap` to map the path of where the code exists on the remote shell to where it is locally:
```json
"sourceFileMap": {
// "remote": "local"
"/home/user/src": "/src/projectA/src"
}
```
## Attach
You can also use the above `pipeTransport` block to attach to a remote process. In the attach case, you will need to specify a `processId`. We have added the ability to query processes from the remote machine. To do this, change `"processId": "${command.pickProcess}"` to `"processId": "${command.pickRemoteProcess}"`. The `pipeTransport` settings will be used to query the processes on the remote machine. Then select the process from the drop down list. As with `launch`, you may need to configure `sourceFileMap`.
## Docker example
The `pipeTransport` can also be used to debug a process in a Docker container. For an attach, **launch.json** will include:
```json
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "docker",
"pipeArgs": [
"exec",
"-i",
"hello_gdb",
"sh",
"-c"
],
"debuggerPath": "/usr/bin/gdb"
},
```
Where `hello_gdb` is the name of your container.
Launching a process is accomplished by starting a container and then using the same `pipeTransport` launch additional processes in the container. See this [**launch.json**](https://github.com/andyneff/hello-world-gdb/blob/master/.vscode/launch.json) for a [full example](https://github.com/andyneff/hello-world-gdb/).
The documentation for pipe transport has moved to https://code.visualstudio.com/docs/cpp/pipe-transport.
@@ -1,91 +1 @@
# Windows 10's Windows Subsystem for Linux
With the release of Windows 10 Creators Update (Build 15063), you will now be able to use Visual Studio Code and the Microsoft C/C++ extension to debug your [Windows Subsystem for Linux (WSL)](https://msdn.microsoft.com/en-us/commandline/wsl/about) projects.
Code can be written on Windows itself using VSCode and debugged through `bash.exe` to the Bash on Windows layer.
As of the Fall Creator's Update, you can have multiple distros installed, but `bash.exe` and `wsl.exe` use the default distro. Use [WSL Config](https://msdn.microsoft.com/en-us/commandline/wsl/wsl-config) to set your default distro.
**NOTE: Creator's Update (Build 15063 or later) is required due to bug-fixes within the subsystem that we rely on to provide debugging. Debugging using a previous version of WSL is unsupported and likely will not work. To check your Windows version, enter `winver` in a command prompt.**
## Prerequisites
* [Windows 10 Creators Update or later with Windows Subsystem for Linux](https://msdn.microsoft.com/en-us/commandline/wsl/install_guide) installed.
* Install g++/gcc and gdb within `WSL` to allow compiling and debugging. You can use the package manager to do this. For example, to install g++, you can run `sudo apt install g++` in the Bash window.
* [Visual Studio Code](https://code.visualstudio.com) + Microsoft C/C++ extension for VSCode.
## How-To
To debug, commands will be routed from Windows through `bash.exe` to set up debugging. Because our extension runs as a 32-bit process, it will need to use the `C:\Windows\SysNative` folder to access the `bash.exe` executable that is normally in `C:\Windows\System32`. We will be using the `"pipeTransport"` ability within the extension to do debugging and `"sourceFileMap"` to map the source from the subsystem's paths back to Windows path.
**NOTE: Applications will need to be compiled in the `Windows Subsystem for Linux (WSL)` prior to debugging.**
### Example `launch.json` for Launching
In the following example, I have a local drive, `Z:\` that has my source code within windows for an app called _kitchensink_. I have set up the `"program"` and `"cwd"` paths to point to the directory within `WSL`. I have set up the `"pipeTransport"` to use `bash.exe`. I have also set up a `"sourceFileMap"` to have everything that is returned by `gdb` that starts with `/mnt/z` to point to `Z:\\` in Windows.
```json
{
"name": "C++ Launch",
"type": "cppdbg",
"request": "launch",
"program": "/mnt/z/Bash/kitchensink/a.out",
"args": ["-fThreading"],
"stopAtEntry": false,
"cwd": "/mnt/z/Bash/kitchensink",
"environment": [],
"externalConsole": true,
"windows": {
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"pipeTransport": {
"pipeCwd": "",
"pipeProgram": "c:\\windows\\sysnative\\bash.exe",
"pipeArgs": ["-c"],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/mnt/z": "z:\\"
}
}
```
### Example `launch.json` for Attaching to an Existing Process
This configuration similar to the launch process above. I have chosen to start the same application above from the Bash command line and now I want to attach to it for debugging. I have changed the `"processID"` to use the remote process picker by specifying the command `"${command:pickRemoteProcess}"` and set up the same `"sourceFileMap"`. When I press <kbd>F5</kbd> to attach, I get a picker drop down showing the running processes within `WSL`. I can scroll or search for the process I want to attach to and start debugging.
```json
{
"name": "C++ Attach",
"type": "cppdbg",
"request": "attach",
"program": "/mnt/z/Bash/kitchensink/a.out",
"processId": "${command:pickRemoteProcess}",
"windows": {
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
"pipeTransport": {
"pipeCwd": "",
"pipeProgram": "c:\\windows\\sysnative\\bash.exe",
"pipeArgs": ["-c"],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/mnt/z": "z:\\"
}
}
```
The documentation for GCC on Windows Subsystem for Linux (WSL) has moved to https://code.visualstudio.com/docs/cpp/config-wsl.
+1 -15
View File
@@ -1,15 +1 @@
# Natvis - Custom views for native objects
The Natvis framework allows developers to write custom schemas to help visualize native objects.
For gdb/lldb debugging (`"type": "cppdbg"`), a subset of the Natvis framework has been ported to the C/C++ extension and the code resides in the [MIEngine](https://github.com/Microsoft/MIEngine) shared component. If additional features that are not implemented are requested, please file an [issue](https://github.com/Microsoft/MIEngine/issues) on the MIEngine GitHub page with details of what is missing.
For Visual C++ debugging (`"type": "cppvsdbg"`), the debugger contains the full implementation of the Natvis framework as Visual Studio.
## Documentation
The official documentation can be found [here](https://docs.microsoft.com/en-us/visualstudio/debugger/create-custom-views-of-native-objects).
## Schema
The Natvis schema can be found [here](natvis.xsd).
The documentation for Natvis has moved to https://code.visualstudio.com/docs/cpp/natvis.
+1 -102
View File
@@ -1,102 +1 @@
# FAQs
## Table of Contents
* Setup: [Debugging Setup](#debugging-setup)
* Setup: [What is the .vscode/ipch folder?](#what-is-the-vscodeipch-folder)
* Setup: [How do I disable the IntelliSense cache (ipch)?](#how-do-i-disable-the-intellisense-cache-ipch)
* Debugger: [Why is debugging not working?](#why-is-debugging-not-working)
* Build: [How to enable debug symbols](#how-to-enable-debug-symbols)
* Logging: [How to enable logging](#how-to-enable-logging)
## Debugging Setup
The debugger needs to be configured to know which executable and debugger to use:
Click menu item: `Debug` -> `Add Configuration...`
The file **launch.json** will now be open for editing with a new configuration. The default settings will *probably* work except that you need to specify the **program** setting.
See the [**Documentation/Debugger**](https://github.com/Microsoft/vscode-cpptools/tree/master/Documentation/Debugger) folder in this repository for more in-depth documentation on how to configure the debugger.
## What is the .vscode/ipch folder?
The language server caches information about included header files to improve the performance of IntelliSense. When you edit C/C++ files in your workspace folder, the language server will store cache files in the `.vscode/ipch` folder by default. VS Code per-workspace storage folders were not selected for the following reasons:
* The workspace storage location provided by VS Code is somewhat obscure and we had reservations about writing GB's worth of files in this location where users may not see them or know where to find them.
* Parity with Visual Studio. This is how Visual Studio works and they receive little to no feedback/complaints on the location.
With this in mind we knew that we wouldn't be able to please everyone, so we provided settings to allow you to customize this the way that works best for your situation. We also figured that putting the files in the workspace folder would bring the issue to your attention quickly so that you can take action if you don't like the default behavior.
#### `"C_Cpp.intelliSenseCachePath": <string>`
This setting allows you to set workspace or global overrides for the cache path. For example, if you want to share a single cache location for all workspace folders, you just open the VS Code settings, and add a "User" setting for "IntelliSense Cache Path".
#### `"C_Cpp.intelliSenseCacheSize": <number>`
This setting allows you to set a limit on the amount of caching the extension does. This is an approximation, but the extension will make a best effort to keep the cache size as close to the limit you set as possible. If you are sharing the cache location across workspaces as explained above, you can still increase/decrease the limit, but you should make sure that you add a "User" setting for "IntelliSense Cache Size".
## How do I disable the IntelliSense cache (ipch)?
If you do not want to use the IntelliSense caching feature to improve the performance of IntelliSense, you can disable the feature by setting the "IntelliSense Cache Size" setting to 0. (or `"C_Cpp.intelliSenseCacheSize": 0"` in the JSON settings editor)
## Why is debugging not working?
### My breakpoints aren't being hit
When you start debugging, if it is showing that your breakpoints aren't bound (solid red circle) or they are not being hit, you may need to enable [debug symbols](#how-to-enable-debug-symbols) during compilation.
### Debugging starts but all the lines in my stack trace are grey
If your debugger is showing a grey stacktrace or won't stop at a breakpoint, or the symbols in the call stack are grey then your executable was compiled without [debug symbols](#how-to-enable-debug-symbols).
## How to enable debug symbols?
Enabling debug symbols are dependent on the type of compiler you are using. Below are some of the compilers and the compiler options necessary to enable debug symbols.
When in doubt, please check your compiler's documentation for the options necessary to include debug symbols in the output. This may be some variant of `-g` or `--debug`.
* #### Clang (C++)
* If you invoke the compiler manually then add the `--debug` option.
* If you're using a script then make sure the `CXXFLAGS` environment variable is set; e.g. `export CXXFLAGS="${CXXFLAGS} --debug"`
* If you're using CMake then set make sure the `CMAKE_CXX_FLAGS` is set; e.g. `export CMAKE_CXX_FLAGS=${CXXFLAGS}`
* #### Clang (C)
See Clang C++ but use `CFLAGS` instead of `CXXFLAGS`.
* #### gcc or g++
If you invoke the compiler manually, add the `-g` option.
* #### cl.exe
Symbols are located in the `*.pdb` file.
## How to enable logging
Enabling logging will show communication information between VS Code and our extension and between our extension and the debugger.
### Logging for `MI` debuggers
The logging block with its defaults is as follows:
```
"logging": {
"trace": false,
"traceResponse": false,
"engineLogging": false
}
```
#### VS Code and the CppTools extension
The logging here is called `trace` logging and can be enabled by setting `trace` and `traceResponse` to `true` in the logging block inside `launch.json`. This will help diagnose issues related to VS Code's communication to our extension and our responses.
#### CppTools extension and the debugger
The logging between CppTools and the debugger is called `engineLogging`. When using an `MI` debugger such as `gdb` or `lldb`, this will show the request, response and events using the `mi` interpreter. This logging will help us determine whether the debugger is receiving the right commands and generating the correct responses.
### Logging for `Visual C++` debugger
The logging block with its defaults is as follows:
```
"logging": {
"engineLogging": false
}
```
The `Visual C++` debugger logging will show only the communication to and from VS Code as all communication to the debugger is done internally to the process and is not visible through logging.
The FAQs for the C/C++ extension has moved to https://code.visualstudio.com/docs/cpp/faq-cpp.
@@ -1,56 +1,3 @@
This file is deprecated.
# Configuring includePath for better IntelliSense results
This page describes how to configure include paths for folders containing C or C++ files to get the full IntelliSense experience. If you're seeing the following message when opening a folder in VS Code, it means the C++ IntelliSense engine needs additional information about the paths in which your include files are located.
![Configure includePath for better IntelliSense](https://github.com/Microsoft/vscode-cpptools/raw/master/Images/configure%20includepath.jpg)
## Where are the include paths defined?
The include paths are defined in the `"includePath"` setting in a file called **c_cpp_properties.json** located in the **.vscode** directory in the opened folder.
You can create or open this file by either using the `"C/Cpp: Edit Configurations"` command in the command palette or by selecting `"Edit "includePath" setting"` in the lightbulb menu (see the screenshot below). The quickest way to locate a lightbulb is to scroll to the top of the source file and click on any green squiggle that shows up under a #include statement.
![lightbulb menu "Edit "includePath" setting"](https://github.com/Microsoft/vscode-cpptools/raw/master/Images/Lightbulb.png)
When a folder is opened, the extension attempts to locate your system headers based on your operating system, but it does not know about any other libraries that your project depends on. You can hover over the green squiggles or open the Problems window to understand which headers the IntelliSense engine is unable to open - sometimes it's the dependent headers that can't be located.
![include error message](https://github.com/Microsoft/vscode-cpptools/raw/master/Images/Include%20errors.png)
## How to specify the include paths?
You can specify the remaining paths using one of the techniques described below.
#### 1. Use `compile_commands.json` file to supply includePaths and defines information
The extension can get the information for `"includePath"` and `"defines"` from a **compile_commands.json** file, which can be auto-generated by many build systems such as CMake and Ninja. Look for the section where your current configuration is defined (by default there's one configuration per OS, such as "Win32 or "Mac"), and set the `"compileCommands"` property in **c_cpp_properties.json** to the full path to your **compile_commands.json** file and the extension will use that instead of the `"includes"` and `"defines"` properties for IntelliSense.
![use compileCommands setting](https://github.com/Microsoft/vscode-cpptools/raw/master/Images/compile_commands.png)
#### 2. Use the lightbulb suggestions to auto-resolve includePath
The first thing to try is to leverage the lightbulb path suggestions to auto-resolve the include paths. When you open a folder, the extension will **recursively** search for potential include paths that match the header files your code is using based on the paths set by the `"browse.path"` setting in **c_cpp_properties.json**. Click on the green squiggles under #include statements and you'll see a lightbulb offering suggestions of paths that will allow IntelliSense to resolve the included file.
![lightbulb suggestions](https://github.com/Microsoft/vscode-cpptools/raw/master/Images/lightbulb%20suggestion.png)
If you don't see path suggestions in the lightbulb, try adding the root folder where the headers are likely located in to the `"browse.path"` setting in **c_cpp_properties.json**. This allows the extension to **recursively** search in these folders and offer more suggestions in the lightbulb as the search process goes on.
#### 3. Manually add include paths
If none of the above fully resolves the paths, you could manually specify the paths to the headers that your project depends on in the **c_cpp_properties.json** file. Look for the section where your current configuration is defined (by default there's one configuration per OS, such as "Win32 or "Mac"), and add your paths in the `"includePath"` setting and defines in the `"defines"` setting. For example, the following screenshot shows a snippet of the file specifying path for the Mac configuration.
![c_cpp_properties file snippet](https://github.com/Microsoft/vscode-cpptools/raw/master/Images/c_cpp_properties%20file.PNG)
## Verify the include paths are correctly resolved
There are two ways to verify that the include paths are correctly resolved:
1. The green squiggles in the source file are no longer showing
2. Error messages are cleared in the Problems window
This indicates that the IntelliSense engine has got the include paths resolved so you can start enjoying the full IntelliSense for your C or C++ code for the current translation unit. Note that you may still see errors on other files if they belong to a different translation unit that requires additional include paths to be configured.
## See Also
[IntelliSense engines](https://github.com/Microsoft/vscode-cpptools/blob/master/Documentation/LanguageServer/IntelliSense%20engine.md)
[**c_cpp_properties.json** reference guide](https://github.com/Microsoft/vscode-cpptools/blob/master/Documentation/LanguageServer/c_cpp_properties.json.md)
Please find documentation for the C/C++ extension at https://code.visualstudio.com/docs/languages/cpp.
@@ -1,99 +1 @@
# Customizing Default Settings
In version 0.17.0 we introduced new settings that allow you to override the extension's default values for properties set in **c_cpp_properties.json**.
## New VS Code settings
The following `C_Cpp.default.*` settings map to each of the properties in a configuration block of **c_cpp_properties.json**. Namely:
```
C_Cpp.default.includePath : string[]
C_Cpp.default.defines : string[]
C_Cpp.default.compileCommands : string
C_Cpp.default.macFrameworkPath : string[]
C_Cpp.default.forcedIncludes : string[]
C_Cpp.default.intelliSenseMode : string
C_Cpp.default.compilerPath : string
C_Cpp.default.cStandard : c89 | c99 | c11
C_Cpp.default.cppStandard : c++98 | c++03 | c++11 | c++14 | c++17
C_Cpp.default.browse.path : string[]
C_Cpp.default.browse.databaseFilename : string
C_Cpp.default.browse.limitSymbolsToIncludedHeaders : boolean
```
These settings have all of the benefits of VS Code settings, meaning that they can have default, "User", "Workspace", and "Folder" values. So you can set a global value for `C_Cpp.default.cppStandard` in your "User" settings and have it apply to all of the folders you open. If any one folder needs a different value, you can override the value by adding a "Folder" or "Workspace" value.
This property of VS Code settings allows you to configure each of your workspaces independently - making the **c_cpp_properties.json** file optional.
## Updated **c_cpp_properties.json** syntax
A special variable has been added to the accepted syntax of **c_cpp_properties.json** that will instruct the extension to insert the value from the VS Code settings mentioned above. If you set the value of any setting in **c_cpp_properties.json** to "${default}" it will instruct the extension to read the VS Code default setting for that property and insert it. For example:
```
"configurations": [
{
"name": "Win32",
"includePath": [
"additional/paths",
"${default}"
],
"defines": [
"${default}",
],
"macFrameworkPath": [
"${default}",
"additional/paths"
],
"forceInclude": [
"${default}",
"additional/paths"
],
"compileCommands": "${default}",
"browse": {
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": "${default}",
"path": [
"${default}",
"additional/paths"
]
},
"intelliSenseMode": "${default}",
"cStandard": "${default}",
"cppStandard": "${default}",
"compilerPath": "${default}"
}
],
```
Take note that for the properties that accept string[], the syntax proposed above allows you to augment the VS Code setting with additional values, thus allowing you to have common paths listed in the VS Code settings and configuration-specific settings in **c_cpp_properties.json**.
If a property is missing from **c_cpp_properties.json**, the extension will use the value in the VS Code setting. If a developer assigns values to all of the settings that apply for a given folder, then **c_cpp_properties.json** could be removed from the .vscode folder as it will no longer be needed.
### System includes
A new setting will be added that allows you specify the system include path separate from the folder's include path. If this setting has a value, then the system include path the extension gets from the compiler specified in the `compilerPath` setting will not be added to the path array that the extension uses for IntelliSense. We may want to provide a VS Code command to populate this value from the compiler's default for users who are interested in using it in case they want to make some modifications to the defaults.
```
C_Cpp.default.systemIncludePath : string[]
```
### System Include Path/Defines Resolution Strategies
The extension determines the system includePath and defines to send to the IntelliSense engine in the following manner:
1. If `compileCommands` has a valid value and the file open in the editor is in the database, use the compile command in the database entry to determine the include path and defines.
* The system include path and defines are determined using the following logic (in order):
1. If `systemIncludePath` has a value, use it (continue to the next step to search for system defines).
2. If `compilerPath` is valid, query it.
3. Interpret the first argument in the command as the compiler and attempt to query it.
4. If `compilerPath` is `""`, use an empty array for system include path and defines.
5. If `compilerPath` is undefined, look for a compiler on the system and query it.
2. If `compileCommands` is invalid or the current file is not listed in the database, use the `includePath` and `defines` properties in the configuration for IntelliSense.
* The system include path and defines are determined using the following logic (in order):
1. If `systemIncludePath` has a value, use it (continue to the next step to search for system defines).
2. If `compilerPath` is valid, query it.
3. If `compilerPath` is `""`, use an empty array for system include path and defines (they are assumed to be in the `includePath` and `defines` for the current config already).
4. If `compilerPath` is undefined, look for a compiler on the system and query it.
System includes should no longer be added to the `"includePath"` or `"browse.path"` variables. If the extension detects any system include paths in the `"includePath"` property it will silently remove them so that it can ensure system include paths are added last and in the correct order (this is especially important for GCC/Clang). In a future update we may add a notification message to the extension to remind developers to remove system include paths from their `"includePath"` and `'browse.path"` as they will be ignored.
The documentation for customizing default settings has moved to https://code.visualstudio.com/docs/cpp/customize-default-settings-cpp.
@@ -1,12 +1 @@
# How to enable logging in the extension
If you are experiencing a problem that we are unable to diagnose based on information in your issue report, we might ask you to enable logging and send us your logs.
As of version 0.14.0 of the extension, logging information is now delivered directly to the Output window in VSCode. To turn on full logging for an issue report, add `"C_Cpp.loggingLevel": "Information"` or `"C_Cpp.loggingLevel": "Debug"` to your **settings.json**.
![image](https://user-images.githubusercontent.com/12818240/44601186-8a2af380-a790-11e8-9094-7064d1ba3cfb.png)
VS Code organizes the logging from different extensions to improve readability so you must select the "C/C++" option in the log filter selector to see logging from the C/C++ extension:
![image](https://user-images.githubusercontent.com/12818240/39769357-d6673bea-52a0-11e8-86c6-3be91618e8fc.png)
The documentation for logging has moved to https://code.visualstudio.com/docs/cpp/enable-logging-cpp.
+1 -66
View File
@@ -1,66 +1 @@
# Frequently asked questions
* [How do I get IntelliSense to work correctly?](#how-do-i-get-intellisense-to-work-correctly)
* [Why do I see red squiggles under Standard Library types?](#why-do-i-see-red-squiggles-under-standard-library-types)
* [How do I get the new IntelliSense to work with MinGW on Windows?](#how-do-i-get-the-new-intellisense-to-work-with-mingw-on-windows)
* [How do I get the new IntelliSense to work with the Windows Subsystem for Linux?](#how-do-i-get-the-new-intellisense-to-work-with-the-windows-subsystem-for-linux)
* [What is the difference between `"includePath"` and `"browse.path"` in **c_cpp_properties.json**?](#what-is-the-difference-between-includepath-and-browsepath-in-c_cpp_propertiesjson)
* [How do I re-create the IntelliSense database?](#how-do-i-re-create-the-intellisense-database)
## How do I get IntelliSense to work correctly?
There are two IntelliSense engines present in the extension: the "fuzzy" engine (or Tag Parser), and the new "Default" engine. If you are using version 0.11.0 or higher of the cpptools extension, then you can preview our new IntelliSense engine which has more accurate auto-complete suggestions and tooltips. To use the new engine, you need to ensure that `"C_Cpp.intelliSenseEngine"` is set to `"Default"` in your settings. Since the engine is still in preview it is not on by default for everyone yet.
After selecting the IntelliSense engine that you prefer, take a look at the Problems window in VS Code to see if you need to do any further configuration for your folder. For example, the Default engine will not provide squiggles and auto-complete suggestions for a translation unit (read: a source file and its dependencies) if the include path is not configured properly. You can select any of the problems in the window to navigate to the line when the problem was detected and a lightbulb will appear in the editor with some options (code actions) to help you resolve the problem:
1. Update your `includePath` (and preprocessor defines)
2. Force semantic IntelliSense
#### Update your `includePath` (and preprocessor defines)
Selecting this option will open a file called **c_cpp_properties.json**. If you haven't created this file already, it will be created for you in the **.vscode** folder of your workspace.
Add the necessary paths to your include files to the `"includePath"` array. The `${workspaceRoot}` variable is available to use to get a relative path to the folder you have opened. Also add any required symbols that need to be defined to the `"defines"` array. Both "\<var\>" and "\<var\>=\<value\>" syntax is accepted. When you edit and save this file, the IntelliSense engine will reset and reparse source your source files and headers with the new settings.
#### Force semantic IntelliSense
If you want IntelliSense to operate on your files even when all #include directives do not resolve, then you can choose the `Force semantic IntelliSense` code action to always use the new IntelliSense engine. You can also set the `C_Cpp.intelliSenseEngineFallback` setting to `"Disabled"`.
## Why do I see red squiggles under Standard Library types?
The most common reason for this is missing include paths and defines. The easiest way to fix this on each platform is as follows:
**Linux/Mac**
* Set `"intelliSenseMode": "clang-x64"` or `"intelliSenseMode": "gcc-x64"` and `"compilerPath"` in **c_cpp_properties.json** to the path to your compiler.
**Windows**
* If you are using a Microsoft compiler from Visual Studio, set `"intelliSenseMode": "msvc-x64"`, but don't add the `"compilerPath"` property to **c_cpp_properties.json**.
* If you are using Clang for Windows, set `"intelliSenseMode": "msvc-x64"`, and `"compilerPath"` in **c_cpp_properties.json** to the path to your compiler.
## How do I get the new IntelliSense to work with MinGW on Windows?
The page discussing configuration with MinGW is [here](https://github.com/Microsoft/vscode-cpptools/blob/master/Documentation/LanguageServer/MinGW.md).
## How do I get the new IntelliSense to work with the Windows Subsystem for Linux?
The page discussing configuration with WSL is [here](https://github.com/Microsoft/vscode-cpptools/blob/master/Documentation/LanguageServer/Windows%20Subsystem%20for%20Linux.md).
## What is the difference between `"includePath"` and `"browse.path"` in **c_cpp_properties.json**?
Starting with version 0.11.0 of the cpptools extension, there are now two settings in the **c_cpp_properties.json** file. They are used by the different IntelliSense engines that we support and have slightly different meanings for the components that use them.
The active IntelliSense engine is controlled via the `"C_Cpp.intelliSenseEngine"` setting in your **settings.json** file. The valid values for this setting are `"Default"` and `"Tag Parser"`.
* #### `"includePath"`
This array of path strings is used by the new "Default" IntelliSense engine that was introduced in version 0.11.0 of the extension. This new engine provides semantic-aware IntelliSense features and will be the eventual replacement for the Tag Parser that has been powering the extension since it was first released. It currently provides tooltips and error squiggles in the editor. The remaining features (e.g. code completion, signature help, go to definition, ...) are implemented using the Tag Parser's database, so it is still important to ensure that the browse.path setting is properly set.
The paths that you specify for this setting are the same paths that you would send to your compiler via the `-I` switch. When your source files are parsed, the IntelliSense engine will prepend these paths to the files specified by your #include directives while attempting to resolve them. These paths are **not** searched recursively.
* #### `"browse.path"`
This array of path strings is used by the "Tag Parser" (a.k.a. "browse engine"). This engine will _recursively_ enumerate all files under the paths specified and track them as potential includes while tag parsing your project folder. To disable recursive enumeration of a path, you can append a `/*` to the path string.
When you open a workspace for the first time, the extension adds `${workspaceRoot}` to both arrays. If this is undesirable, you can open your **c_cpp_properties.json** file and remove it.
## How do I re-create the IntelliSense database?
Starting in version 0.12.3 of the extension, we added a command that will reset your IntelliSense database. Open the command palette and choose the "C/Cpp: Reset IntelliSense Database" command.
The FAQs for the C/C++ extension has moved to https://code.visualstudio.com/docs/cpp/faq-cpp.
@@ -1,44 +0,0 @@
# IntelliSense engines
There are two IntelliSense engines used to power the C/C++ IntelliSense experience in VS Code.
* `"Default"` - Visual Studio's IntelliSense engine, which is the default engine that provides semantic-aware IntelliSense features
* `"Tag Parser"` - the "fuzzy" IntelliSense engine that provides quick but "fuzzy" results, is used to provide the fallback experience if the default engine is unable to fully resolve include paths
Ultimately all the IntelliSense and code browsing features will be powered by the "Default" engine. The following features have been implemented so far:
* Auto-complete suggestions for class/struct/namespace members
* Parameter hints
* Quick info (hover over tooltip)
* Error squiggles
* Reference highlighting
The other IntelliSense features, such as global auto-complete, and code browsing features, such as Go to definition/declaration, are currently powered by the "Tag Parser" based engine.
### `includePath` and `browse.path`
The two IntelliSense engines use two different settings in the **c_cpp_properties.json** file for specifying include paths. This file is located in the **.vscode** directory in the opened folder. You can create or open this file by either using the "C/Cpp: Edit Configurations" command in the command palette or by selecting "Edit "includePath" setting" in the lightbulb menu. Look for the following settings in the section where your current configuration is defined (by default there's one configuration per OS, such as "Win32 or "Mac").
* #### `"includePath"`
This array of path strings is used by the "Default" IntelliSense engine. The paths that you specify for this setting are the same paths that you would send to your compiler via the -I switch. When your source files are parsed, the IntelliSense engine will prepend these paths to the files specified by your #include directives while attempting to resolve them. These paths are searched **non-recursively**.
* #### `"browse.path"`
This array of path strings is used by the "Tag Parser" (a.k.a. "browse engine"). This engine will **recursively** enumerate all files under the paths specified and track them as potential includes while tag parsing your project folder. To disable recursive enumeration of a path, you can append a `/*` to the path string.
### How fallback works and how to control the behavior
The extension first tries to fully parse any opened file using the "Default" IntelliSense engine. If it discovers that it cannot find a header file or a dependency, it will fall back to the tag parser and provide the fuzzy IntelliSense behavior. The fallback affects a full translation unit (TU), not just a single open file. The Problems panel provides details about unresolved headers and dependencies. Other opened TUs will continue to use the "Default" IntelliSense engine provided that all #include dependencies are resolved.
We recognize that resolving all #includes may not be necessary for all projects and you may still want to experience the productivity benefits of using the "Default" semantic engine without customizing the default include path. For that, the “Force semantic IntelliSense” action can be chosen. When invoked, all unresolved #include squiggles will turn red and semantic member list and linting will be enabled in all files regardless of whether or not #include statements can be resolved.
### IntelliSense engine setting
We recommend using the "Default" engine for the best IntelliSense experience. However, it is possible to explicitly choose the IntelliSense engine by editing your [user or workspace settings](https://code.visualstudio.com/docs/getstarted/settings). The setting you should modify is `"C_Cpp.intelliSenseEngine"`. There are two values for this setting:
* `"Default"` - use Visual Studio's IntelliSense engine
* `"Tag Parser"` - use the "fuzzy" IntelliSense engine
### See Also
[Configuring includePath for better IntelliSense results](https://github.com/Microsoft/vscode-cpptools/blob/master/Documentation/Getting%20started%20with%20IntelliSense%20configuration.md)
[**c_cpp_properties.json** reference guide](https://github.com/Microsoft/vscode-cpptools/blob/master/Documentation/LanguageServer/c_cpp_properties.json.md)
+1 -30
View File
@@ -1,31 +1,2 @@
# MinGW
To use MinGW on Windows, we recommend you add the following configuration to your **c_cpp_properties.json** file. Select "C/Cpp: Edit Configurations" from the command palette to create this file if you haven't already.
## Extension version 0.17.0 and higher:
When you set the `compilerPath` property and change `intelliSenseMode` to `clang-x64` (or `gcc-x64` in version 0.18.0 and higher), you no longer need to copy the system include path or defines to `includePath`, `browse.path`, or `defines` to enable IntelliSense to work properly. For example:
```json
{
"name": "MinGW",
"intelliSenseMode": "gcc-x64",
"compilerPath": "C:/mingw64/bin/gcc.exe",
"includePath": [
"${workspaceFolder}"
],
"defines": [],
"cStandard": "c11",
"cppStandard": "c++17"
}
```
Replace "gcc.exe" with whatever compiler you're using, e.g. "g++.exe", "clang-5.0.exe", etc. -- just make sure the file is a valid Windows executable (not a 0 size symlink).
For Cygwin, set the `compilerPath` to the appropriate Cygwin path, e.g. "C:/cygwin64/bin/g++.exe".
If it seems like the `compilerPath` is not getting used, you can debug the issue via [enabling logging](Enabling%20logging.md).
## Extension version 0.16.1 and earlier:
If you have an older version of the C/C++ extension installed, use [these instructions](Archive/MinGW.md) instead.
The documentation for Mingw-w64 has moved to https://code.visualstudio.com/docs/cpp/config-mingw.
@@ -1,33 +1 @@
# Windows Subsystem for Linux
> **Note:** If you are on **build 17110 of Windows or higher**, you must use extension version 0.17.0 or higher for IntelliSense to work. The Windows team turned on case-sensitive folders for the WSL environment and the C/C++ extension doesn't support case-sensitive folders until version 0.17.0.
To use the Windows Subsystem for Linux with this extension you need to add a configuration to your **c_cpp_properties.json** file which adds the necessary header paths from within the WSL filesystem to the `includePath`.
Select "C/Cpp: Edit Configurations" from the command palette to create the **c_cpp_properties.json** file if you haven't already.
## With extension version 0.17.0 and higher:
In **c_cpp_properties.json** you can directly address your WSL compiler and include paths by using *nix-style paths and we will do the conversion to Windows paths for you. If you have multiple distros installed, we disambiguate the `compilerPath` by picking the one marked as Default when you run `wslconfig.exe /l` in a CMD or PowerShell window. We continue to support Windows-style paths for these properties as outlined in the [archived instructions](Archive/Windows%20Subsystem%20for%20Linux.md) if you prefer to use those.
```json
{
"name": "WSL",
"intelliSenseMode": "gcc-x64",
"compilerPath": "/usr/bin/gcc",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"cStandard": "c11",
"cppStandard": "c++17"
}
```
## Earlier versions of the extension:
If you are on a build of Windows prior to 17110 and you have an older version of the C/C++ extension installed, use [these instructions](Archive/Windows%20Subsystem%20for%20Linux.md) instead.
---
Remember to [heed the warnings of the Windows team about not creating or editing Linux files from a Windows app](https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/)!
The documentation for GCC on Windows Subsystem for Linux (WSL) has moved to https://code.visualstudio.com/docs/cpp/config-wsl.
@@ -1,100 +1 @@
# `c_cpp_properties.json` Reference Guide
> See also: [Customizing Default Settings](Customizing%20Default%20Settings.md)
### Example
```json
{
"env" : {
"myDefaultIncludePath": [
"${workspaceFolder}",
"${workspaceFolder}/include"
],
"myCompilerPath": "/usr/local/bin/gcc-7"
},
"configurations": [
{
"name": "Mac",
"intelliSenseMode": "clang-x64",
"includePath": [ "${myDefaultIncludePath}", "/another/path" ],
"macFrameworkPath": [ "/System/Library/Frameworks" ],
"defines": [ "FOO", "BAR=100" ],
"forcedInclude": [ "${workspaceFolder}/include/config.h" ],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++17",
"compileCommands": "/path/to/compile_commands.json",
"browse": {
"path": [ "${workspaceFolder}" ],
"limitSymbolsToIncludedHeaders": true,
"databaseFilename": ""
}
}
],
"version": 4
}
```
## Top-level properties
* #### `env`
An array of user-defined variables that will be available for substitution in the configurations via the standard environment variable syntax: `${<var>}` or `${env:<var>}`. Strings and arrays of strings are accepted.
* #### `configurations`
An array of configuration objects that provide the IntelliSense engine with information about your project and your preferences. By default, the extension creates a configuration for you based on your operating system. You may also add additional configurations.
* #### `version`
We recommend you don't edit this field. It tracks the current version of the **c_cpp_properties.json** file so that the extension knows what properties and settings should be present and how to upgrade this file to the latest version.
## Configuration properties
* #### `name`
A friendly name for the configuration. "Linux", "Mac", and "Win32" are special names that instruct the extension to load that configuration by default on the associated operating system unless additional configurations have been created. The status bar in VS Code will show you which configuration is active. You can also click on the label in the status bar to change the active configuration.
* #### `intelliSenseMode`
If `"C_Cpp.intelliSenseEngine"` is set to "Default" in your settings file, this property determines which mode the IntelliSense engine will run in. `"msvc-x64"` maps to Visual Studio mode with 64-bit pointer sizes. `"clang-x64"` maps to CLang mode with 64-bit pointer sizes. `"gcc-x64"` maps to GCC mode with 64-bit pointer sizes. Windows uses `"msvc-x64"` by default, macOS uses `"clang-x64"` by default, and Linux uses `"gcc-x64"` by default.
* #### `includePath`
If `"C_Cpp.intelliSenseEngine"` is set to "Default" in your settings file, this list of paths will be used by IntelliSense to search for headers included by your source files. This is basically the same as the list of paths you pass to your compiler with the `-I` switch. If a path ends with `/**` the IntelliSense engine will do a recursive search for includes starting from that directory. If on Windows with Visual Studio installed, or if a compiler is specified in the `compilerPath` setting, it is not necessary to list the system include paths in this list.
* #### `macFrameworkPath`
If `"C_Cpp.intelliSenseEngine"` is set to "Default" in your settings file, this list of paths will be used by IntelliSense to search for framework headers included by your source files. This is basically the same as the list of paths you pass to your compiler with the `-F` switch; the IntelliSense engine will not do a recursive search in these paths for includes.
* #### `defines`
If `"C_Cpp.intelliSenseEngine"` is set to "Default" in your settings file, this list of preprocessor symbols will be used by IntelliSense during the compilation of your source files. This is basically the same as the list of symbols you pass to your compiler with the `-D` switch. If on Windows with Visual Studio installed, or if a compiler is specified in the `compilerPath` setting, it is not necessary to list the system include paths in this list.
* #### `forcedInclude` (optional)
A list of files that should be included before any other characters in the source file are processed. Files are included in the order listed.
* #### `compilerPath` (optional)
The absolute path to the compiler you use to build your project. The extension will query the compiler to determine the system include paths and default defines to use for IntelliSense.
Args can be added to modify the includes/defines used, e.g. `-nostdinc++`, `-m32`, `-fno-ms-extensions`, etc., but paths with spaces must be surrounded by double quotes (`"`) if args are used.
If you want to disable automatic querying of system include paths and defines, set this value to the emptry string `""`. This is generally not recommended, but there are some cases where automatic querying of system includes and defines is undesirable.
* #### `cStandard`
The C standard revision to use for IntelliSense in your project.
* #### `cppStandard`
The C++ standard revision to use for IntelliSense in your project.
* #### `compileCommands` (optional)
If `"C_Cpp.intelliSenseEngine"` is set to "Default" in your settings file, the includes and defines discovered in this file will be used instead of the values set for `includePath` and `defines`. If the compile commands database does not contain an entry for the translation unit that corresponds to the file you opened in the editor, then a warning message will appear and the extension will use the `includePath` and `defines` settings instead.
>For more information about the file format, see the [Clang documentation](https://clang.llvm.org/docs/JSONCompilationDatabase.html). Some build systems, such as CMake, [simplify generating this file](https://cmake.org/cmake/help/v3.5/variable/CMAKE_EXPORT_COMPILE_COMMANDS.html).
* #### `browse`
The set of properties used when `"C_Cpp.intelliSenseEngine"` is set to `"Tag Parser"` (also referred to as "fuzzy" IntelliSense, or the "browse" engine). These properties are also used by the Go To Definition/Declaration features, or when the "Default" IntelliSense engine is unable to resolve the #includes in your source files.
### Browse properties
* #### `path`
This list of paths will be used by the Tag Parser to search for headers included by your source files. If omitted, `includePath` will be used as the `path`. The Tag Parser will automatically search all subfolders in these paths unless the path ends with a `/*` or `\*`. For example, `/usr/include` directs the Tag Parser to search the `include` folder and its subfolders for headers while `/usr/include/*` directs the Tag Parser not to look in any subfolders of `/usr/include`.
* #### `limitSymbolsToIncludedHeaders`
When true, the Tag Parser will only parse code files that have been directly or indirectly included by a source file in `${workspaceFolder}`. When false, the Tag Parser will parse all code files found in the paths specified in the **path** list.
* #### `databaseFilename`
When set, this instructs the extension to save the Tag Parser's symbol database somewhere other than the workspace's default storage location. If a relative path is specified, it will be made relative to the workspace's default storage location, not the workspace folder itself. The `${workspaceFolder}` variable can be used to specify a path relative to the workspace folder (e.g. `${workspaceFolder}/.vscode/browse.vc.db`)
The documentation for c_cpp_properties.json has moved to https://code.visualstudio.com/docs/cpp/c-cpp-properties-schema-reference.
@@ -0,0 +1 @@
The documentation for enhanced colorization has moved to https://code.visualstudio.com/docs/cpp/colorization-cpp.
+1
View File
@@ -3,6 +3,7 @@ node_modules
# ignore compliled typescript
out
dist
# ignore downloaded extension files and folders
server
+5 -4
View File
@@ -13,9 +13,9 @@
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": [
"${workspaceFolder}/out/**/*.js"
"${workspaceFolder}/dist/**/*.js"
],
"preLaunchTask": "TypeScript Compile",
"preLaunchTask": "Compile Dev",
},
{
"name": "Launch Tests",
@@ -47,13 +47,14 @@
"args": [
"${workspaceFolder}/test/integrationTests/testAssets/SimpleCppProject",
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/integrationTests"
"--extensionTestsPath=${workspaceFolder}/out/test/integrationTests/languageServer"
],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": [
"${workspaceFolder}/out/test/**/*.js"
]
],
"preLaunchTask": "Pretest"
},
]
}
+27
View File
@@ -53,6 +53,33 @@
"dependsOn": [
"TypeScript Compile"
]
},
{
"label": "Compile Dev",
"group": "build",
"isBackground": false,
"type": "shell",
"command": "npm",
"args": [
"run",
"compileDev"
],
"problemMatcher": "$tsc-watch"
},
{
"label": "Pretest",
"group": "build",
"isBackground": false,
"type": "shell",
"command": "npm",
"args": [
"run",
"pretest"
],
"dependsOn": [
"TypeScript Compile"
],
"problemMatcher": "$tsc-watch"
}
]
}
+30 -9
View File
@@ -1,15 +1,36 @@
obj/**
# ignore vscode settings for extension development
.vscode/**
typings/**
out/test/**
# ignore binaries
obj/**
# ignore source files
tools/**
notices/**
test/**
src/**
**/*.map
.gitignore
# ignore .js files that are webpacked or only used for development
out/src/**
out/tools/**
# ignore ts files in ui
ui/*.ts
# ignore Azure-Pipelines files
jobs/**
# ignore development files
tsconfig.json
test.tsconfig.json
tslint.json
webpack.config.js
tscCompileList.txt
gulpfile.js
.gitattributes
.gitignore
CMakeLists.txt
debugAdapters/install.lock*
out/src/Debugger/copyScript.js
tools/**
out/tools/**
notices/**
typings/**
**/*.map
+111 -21
View File
@@ -1,51 +1,141 @@
# C/C++ for Visual Studio Code Change Log
## Version 0.23.0-insiders: April 23, 2019
## Version 0.25.0-insiders: August 8, 2019
### New Features
* Add a configuration UI editor to edit IntelliSense settings defined in the underlying `c_cpp_properties.json` file. [PR #3479](https://github.com/Microsoft/vscode-cpptools/pull/3479), [PR #3487](https://github.com/Microsoft/vscode-cpptools/pull/3487)
* Add `Find All References` when `C_Cpp.experimentalFeatures` is set to `"Enabled"`. [#15](https://github.com/microsoft/vscode-cpptools/issues/15)
* Add `-x86` options for `intelliSenseMode`. [#2312](https://github.com/microsoft/vscode-cpptools/issues/2312)
* Add `c++20` option to `cppStandard`. [#3448](https://github.com/microsoft/vscode-cpptools/issues/3448)
* Add support for resolving missing includes via the `vcpkg` dependency manager. [PR #3791](https://github.com/microsoft/vscode-cpptools/pull/3791)
### Enhancements
* Added support for compile commands:
* `-iquote`. [#2088](https://github.com/microsoft/vscode-cpptools/issues/2088)
* `-imacros`. [#2417](https://github.com/microsoft/vscode-cpptools/issues/2417)
* `-idirafter`(`--include-directory-after` & `--include-directory-after=`). [#3713](https://github.com/microsoft/vscode-cpptools/issues/3713)
* Switch to using VS Code's `Go to Declaration`. [#2959](https://github.com/microsoft/vscode-cpptools/issues/2959)
* Added `compilerArgs` property setting. [PR #3950](https://github.com/microsoft/vscode-cpptools/pull/3950)
* Added support for V3 API. [#3987](https://github.com/microsoft/vscode-cpptools/pull/3987)
### Bug Fixes
* Fix previous cache path not deleted when new cache path is specified. Note that the VS Code bug [Microsoft/vscode#59391](https://github.com/microsoft/vscode/issues/59391) still occurs on the settings UI, but this fix should delete any incomplete path names as the extension receives changes from the cache path setting. [#3644](https://github.com/microsoft/vscode-cpptools/issues/3644).
* Fix `compile_commands.json` file changes not updated. [#3864](https://github.com/microsoft/vscode-cpptools/issues/3864).
* Fix `Failed to parse` error message in the open file scenario. [#3888](https://github.com/microsoft/vscode-cpptools/issues/3888)
* Fix IntelliSense-based `Go to Definition` failing with `using namespace`. [#3902](https://github.com/microsoft/vscode-cpptools/issues/3902)
* Fix typos and grammar in documentation.
* @pi1024e [PR #4014](https://github.com/microsoft/vscode-cpptools/pull/4014)
## Version 0.24.1: July 22, 2019
### Bug Fixes
* Fix an issue with the Outline not being populated when a file is opened. [#3877](https://github.com/microsoft/vscode-cpptools/issues/3877)
* Update scopes used by semantic colorization. [PR# 3896](https://github.com/microsoft/vscode-cpptools/pull/3896)
## Version 0.24.0: July 3, 2019
### New Features
* Semantic colorization [Documentation](https://github.com/microsoft/vscode-cpptools/blob/master/Documentation/LanguageServer/colorization.md) [#230](https://github.com/microsoft/vscode-cpptools/issues/230)
* Add `Rescan Workspace` command. [microsoft/vscode-cpptools-api#11](https://github.com/microsoft/vscode-cpptools-api/issues/11)
### Enhancements
* Configuration UI editor improvements:
* Add list of detected compiler paths. [PR #3708](https://github.com/microsoft/vscode-cpptools/pull/3708)
* Enable selecting/editing of other configurations and add "Advanced Settings" section. [PR #3732](https://github.com/microsoft/vscode-cpptools/pull/3732)
* Enable `envFile` for `cppdbg`. [PR #3723](https://github.com/microsoft/vscode-cpptools/pull/3723)
* Change the default path value of `C_Cpp.intelliSenseCachePath`. [#3347](https://github.com/microsoft/vscode-cpptools/issues/3347) [#3664](https://github.com/microsoft/vscode-cpptools/issues/3664)
* Change `C_Cpp.clang_format_path` to `machine` scope. [#3774](https://github.com/microsoft/vscode-cpptools/issues/3774)
* Add validation to the advanced configuration UI settings. [PR #3838](https://github.com/microsoft/vscode-cpptools/pull/3838)
* Add `Current Configuration` to `C/C++: Log Diagnostics`. [PR #3866](https://github.com/microsoft/vscode-cpptools/pull/3866)
### Bug Fixes
* Fix for gdb `follow-fork-mode` `child` not working. [#2738](https://github.com/microsoft/vscode-cpptools/issues/2738)
* Fix IntelliSense process crash on hover with certain arrays. [#3081](https://github.com/Microsoft/vscode-cpptools/issues/3081)
* Fix IntelliSense-based `Go to Definition` for goto labels. [#3111](https://github.com/microsoft/vscode-cpptools/issues/3111)
* Fix IntelliSense behaving incorrectly when files are opened with different casing on Windows. [#3229](https://github.com/microsoft/vscode-cpptools/issues/3229)
* Fix user defined literals crashing IntelliSense in clang/gcc mode. [#3481](https://github.com/microsoft/vscode-cpptools/issues/3481)
* Improve `sourceFileMap` to be more dynamic. [#3504](https://github.com/microsoft/vscode-cpptools/issues/3504)
* Fix IntelliSense-based hover document comments being shown for invalid declarations not used by the current translation unit. [#3596](https://github.com/microsoft/vscode-cpptools/issues/3596)
* Fix `Go to Definition` when is `void` missing in the parameter list of a function definition a .c file. [#3609](https://github.com/microsoft/vscode-cpptools/issues/3609)
* Fix configuration validation of compiler path and IntelliSense mode compatibility for `clang-cl.exe` compiler. [#3637](https://github.com/microsoft/vscode-cpptools/issues/3637)
* Fix resolving `${workspaceFolderBasename}` and add `${workspaceStorage}`. [#3642](https://github.com/microsoft/vscode-cpptools/issues/3642)
* Fix IntelliSense-based `Go to Definition` performance issue due to extra database iteration. [#3655](https://github.com/microsoft/vscode-cpptools/issues/3655)
* Fix `SourceRequest` causing debugging to stop with `NotImplementedException`. [#3662](https://github.com/microsoft/vscode-cpptools/issues/3662)
* Fix typo in `intelliSenseMode` description.
* Karsten Thoms (@kthoms) [PR #3682](https://github.com/microsoft/vscode-cpptools/pull/3682)
* Fix invalid warning with typedef enums in .c files. [#3685](https://github.com/microsoft/vscode-cpptools/issues/3685)
* Fix incorrect `keyword` completion occurring for pragma `#keyword`. [#3690](https://github.com/microsoft/vscode-cpptools/issues/3690)
* Fix problem matcher to show fatal errors from GCC [#3712](https://github.com/microsoft/vscode-cpptools/issues/3712)
* Fix multi-root folders with the same name sharing the same browse database. [PR #3715](https://github.com/microsoft/vscode-cpptools/pull/3715)
* Fix `remoteProcessPicker` on Windows. [#3758](https://github.com/microsoft/vscode-cpptools/issues/3758)
* Fix crash when tag parsing Objective-C code. [#3776](https://github.com/microsoft/vscode-cpptools/issues/3776)
* Fix duplicate slashes getting added to `c_cpp_properties.json`. [PR #3778](https://github.com/microsoft/vscode-cpptools/pull/3778)
* Fix `envFile` variable substitution. [#3836](https://github.com/microsoft/vscode-cpptools/issues/3836)
* Fix missing headers popup. [PR #3840](https://github.com/microsoft/vscode-cpptools/pull/3840)
* Fix multiple anonymous unions not showing correctly in Locals while debugging. [MIEngine#820](https://github.com/microsoft/MIEngine/issues/820)
* Fix pause not working when using `DebugServer`/`MIDebuggerServerAddress` on Linux and macOS. [MIEngine#844](https://github.com/microsoft/MIEngine/issues/844)
* Improvements to CPU and memory usage when editing.
## Version 0.23.1: May 13, 2019
### Bug Fixes
* Fix `launch.json` creation when `intelliSenseEngine` is `"Disabled"`. [#3583](https://github.com/microsoft/vscode-cpptools/issues/3583)
* Fix C/C++ commands not working if the language service isn't activated. [#3615](https://github.com/microsoft/vscode-cpptools/issues/3615)
* Fix missing extension `"Details"` page. [#3621](https://github.com/microsoft/vscode-cpptools/issues/3621)
* Fix some random crashes related to IntelliSense inactive region processing.
## Version 0.23.0: May 6, 2019
### New Features
* Add a configuration UI editor to edit IntelliSense settings defined in the underlying `c_cpp_properties.json` file. [PR #3479](https://github.com/Microsoft/vscode-cpptools/pull/3479), [PR #3487](https://github.com/Microsoft/vscode-cpptools/pull/3487), [PR #3519](https://github.com/Microsoft/vscode-cpptools/pull/3519), [#3524](https://github.com/Microsoft/vscode-cpptools/issues/3524), [PR #3563](https://github.com/Microsoft/vscode-cpptools/pull/3563), [#3526](https://github.com/Microsoft/vscode-cpptools/issues/3526)
* Add a new command `C/C++: Edit configurations (UI)` to open the UI editor.
* Replace the `C/C++: Edit configurations...` command with `C/C++: Edit configurations (JSON)` to open `c_cpp_properties.json`.
* The default whether to open the UI editor or JSON file is based on the `workbench.settings.editor` setting.
* Add command `C/C++: Log Diagnostics` to log language service diagnostics. [PR #3489](https://github.com/Microsoft/vscode-cpptools/pull/3489)
* Add support for `.env` files for `cppvsdbg`. [#3490](https://github.com/Microsoft/vscode-cpptools/issues/3490)
### Minor Changes
### Other Changes
* Enable flag `/permissive-` as an argument to `compilerPath` with `cl.exe`. [#1589](https://github.com/Microsoft/vscode-cpptools/issues/1589), [#3446](https://github.com/Microsoft/vscode-cpptools/issues/3446)
* Configuration squiggles for `c_cpp_properties.json` now validates if the setting values of `compilerPath` and `intelliSenseMode` match on Windows. [#2983](https://github.com/Microsoft/vscode-cpptools/issues/2983)
* Enable `-fms-extensions` to be used as an argument to `compilerPath` on Linux/Mac. [#3063](https://github.com/Microsoft/vscode-cpptools/issues/3063)
* Change the default value of `C_Cpp.intelliSenseEngineFallback` setting to `Disabled`. [#3165](https://github.com/Microsoft/vscode-cpptools/issues/3165)
* Add squiggle when `compilerPath` uses spaces and arguments without `"`. [#3357](https://github.com/Microsoft/vscode-cpptools/issues/3357)
* Change the `Disabled` value for `C_Cpp.errorSquiggles` to stop showing missing header squiggles. [#3361](https://github.com/Microsoft/vscode-cpptools/issues/3361)
* Add `enableConfigurationSquiggles` setting to allow squiggles to be disabled for `c_cpp_properties.json`. [#3403](https://github.com/Microsoft/vscode-cpptools/issues/3403)
* Switch to using the `installExtension` command for offline/insider vsix installing (to reduce install failures). [#3408](https://github.com/Microsoft/vscode-cpptools/issues/3408)
* Add a better example to the description of `C_Cpp.clang_format_style` and `C_Cpp.clang_format_fallback_style`. [#3419](https://github.com/Microsoft/vscode-cpptools/issues/3419)
* Add a new (default) value of `EnabledIfIncludesResolve` to `C_Cpp.errorSquiggles`, which only shows error squiggles if include headers are successfully resolved. [PR #3421](https://github.com/Microsoft/vscode-cpptools/pull/3421)
* Enable flag `/permissive-` as an argument to `compilerPath` with `cl.exe`. [#3446](https://github.com/Microsoft/vscode-cpptools/issues/3446)
* Disable debug heap by default with cppvsdbg. [#3484](https://github.com/Microsoft/vscode-cpptools/issues/3484)
* Reported by Djoulihen (@Djoulihen)
* Enable configuration squiggles for paths delimited by semicolons. [PR #3517](https://github.com/Microsoft/vscode-cpptools/pull/3517)
* Don't show release notes if the extension has never been installed before. [#3533](https://github.com/Microsoft/vscode-cpptools/issues/3533)
* Remove IntelliSense fallback code actions.
### Bug Fixes
* Fix browsing for functions with BOOST_FOREACH. [#953](https://github.com/Microsoft/vscode-cpptools/issues/953)
* Fix code action sometimes not appearing over a squiggled identifier. [#1436](https://github.com/microsoft/vscode-cpptools/issues/1436)
* Work around issue with VS Code not treating `.C` files as C++ files [Microsoft/vscode#59369](https://github.com/Microsoft/vscode/issues/59369) -- `.C` files become associated by name in `files.associations`. [#2558](https://github.com/Microsoft/vscode-cpptools/issues/2558)
* Fix various IntelliSense parsing bugs. [#2824](https://github.com/Microsoft/vscode-cpptools/issues/2824), [#3110](https://github.com/Microsoft/vscode-cpptools/issues/3110), [#3168](https://github.com/Microsoft/vscode-cpptools/issues/3168)
* Preserve newlines in documentation comments. [#2937](https://github.com/Microsoft/vscode-cpptools/issues/2937)
* Fix documentation comments above multi-line templates (and some other issues). [#3162](https://github.com/Microsoft/vscode-cpptools/issues/3162)
* Fix "Extension causes high cpu load" due to module loading. [#3213](https://github.com/Microsoft/vscode-cpptools/issues/3213)
* Fix auto-removal of compiler-provided paths in `includePath` when they end with a directory separator on Windows. [#3245](https://github.com/Microsoft/vscode-cpptools/issues/3245)
* Fix `.cmd` and `.bat` files not working for `compilerPath` on Windows. [#3428](https://github.com/Microsoft/vscode-cpptools/issues/3428)
* Fix `compilerPath` with arguments that are surrounded by quotes. [#3428](https://github.com/Microsoft/vscode-cpptools/issues/3428)
* Fix documentation comments interpreting special characters as markdown. [#3441](https://github.com/Microsoft/vscode-cpptools/issues/3441)
* Fix a JSON parsing error when a path in `c_cpp_properties.json` ended with `\\"`. [#3449](https://github.com/Microsoft/vscode-cpptools/issues/3449)
* Fix hover using the configuration of the active document instead of the hovered document. [#3452](https://github.com/Microsoft/vscode-cpptools/issues/3452)
* Fix `c_cpp_properties.json` squiggles when the configuration name has regex characters. [PR #3478](https://github.com/Microsoft/vscode-cpptools/pull/3478)
* Use the `editor.tabSize` setting instead of `2` when creating build tasks. [PR #3486](https://github.com/Microsoft/vscode-cpptools/pull/3486)
* Fix some potential crashes on hover. [#3509](https://github.com/Microsoft/vscode-cpptools/issues/3509)
* Fix icon of parameters in completion results.
* Fix code action sometimes not appearing over a squiggled identifier.
## Version 0.22.2-insiders: April 9, 2019
* Fix various IntelliSense parsing bugs. [#2824](https://github.com/Microsoft/vscode-cpptools/issues/2824), [#3110](https://github.com/Microsoft/vscode-cpptools/issues/3110), [#3168](https://github.com/Microsoft/vscode-cpptools/issues/3168)
* Enable `-fms-extensions` to be used as an argument to `compilerPath` on Linux/Mac. [#3063](https://github.com/Microsoft/vscode-cpptools/issues/3063)
* Fix duplicate compiler build tasks appearing when `compilerPath` has arguments. [PR #3360](https://github.com/Microsoft/vscode-cpptools/pull/3360)
* Add squiggle when `compilerPath` uses spaces and arguments without `"`. [#3357](https://github.com/Microsoft/vscode-cpptools/issues/3357)
* Fix environment variables not resolving with `C_Cpp.intelliSenseCachePath`. [#3367](https://github.com/Microsoft/vscode-cpptools/issues/3367)
* Fix the formatting of snippets text. [#3376](https://github.com/Microsoft/vscode-cpptools/issues/3376)
* Fix the default `AccessModifierOffset` used when formatting. [#3376](https://github.com/Microsoft/vscode-cpptools/issues/3376)
* Fix null reference during initialization when using custom configuration providers. [PR #3377](https://github.com/Microsoft/vscode-cpptools/pull/3377)
* Fix symbol parsing when `__MINGW_ATTRIB_*` is used. [#3390](https://github.com/Microsoft/vscode-cpptools/issues/3390)
* Fix `compile_commands.json` configuration prompt being disabled per user instead of per folder. [PR #3399](https://github.com/Microsoft/vscode-cpptools/pull/3399)
* Add `enableConfigurationSquiggles` setting to allow squiggles to be disabled for `c_cpp_properties.json`. [#3403](https://github.com/Microsoft/vscode-cpptools/issues/3403)
* Add a better example to the description of `C_Cpp.clang_format_style` and `C_Cpp.clang_format_fallback_style`. [#3419](https://github.com/Microsoft/vscode-cpptools/issues/3419)
* Fix `.cmd` and `.bat` files not working for `compilerPath` on Windows. [#3428](https://github.com/Microsoft/vscode-cpptools/issues/3428)
* Fix `compilerPath` with arguments that are surrounded by quotes. [#3428](https://github.com/Microsoft/vscode-cpptools/issues/3428)
* Fix documentation comments interpreting special characters as markdown. [#3441](https://github.com/Microsoft/vscode-cpptools/issues/3441)
* Fix hover using the configuration of the active document instead of the hovered document. [#3452](https://github.com/Microsoft/vscode-cpptools/issues/3452)
* Fix `c_cpp_properties.json` squiggles when the configuration name has regex characters. [PR #3478](https://github.com/Microsoft/vscode-cpptools/pull/3478)
* Use the `editor.tabSize` setting instead of `2` when creating build tasks. [PR #3486](https://github.com/Microsoft/vscode-cpptools/pull/3486)
* Fix some potential crashes on hover. [#3509](https://github.com/Microsoft/vscode-cpptools/issues/3509)
* Fix for `NullReferenceException` occurring when `"args"` is not specified in `launch.json`. [#3532](https://github.com/Microsoft/vscode-cpptools/issues/3532)
* Fix `Go to Definition` giving no results when IntelliSense doesn't find the symbol. [#3549](https://github.com/Microsoft/vscode-cpptools/issues/3549)
* Fix configuration squiggles with trailing backslashes. [PR #3573](https://github.com/Microsoft/vscode-cpptools/pull/3573)
* Fix `includePath` code actions, configuration prompts, and the `C/C++: Change configuration provider...` command. [PR #3576](https://github.com/Microsoft/vscode-cpptools/pull/3576)
* Fix randomly occurring crash (that could occur when opening files while IntelliSense squiggles are pending).
* Fix crash on hover (that could occur when document comments have blank lines).
* Fix icon of parameters in completion results.
## Version 0.22.1: March 21, 2019
* Fix `tasks.json` with single-line comments being overwritten when `Build and Debug Active File` is used. [#3327](https://github.com/Microsoft/vscode-cpptools/issues/3327)
+62 -30
View File
@@ -1,34 +1,66 @@
# C/C++ for Visual Studio Code
This preview release of the extension adds language support for C/C++ to Visual Studio Code including:
* Language service
* Code Formatting (clang-format)
* Auto-Completion
* Symbol Searching
* Go to Definition/Declaration
* Peek Definition/Declaration
* Class/Method Navigation
* Signature Help
* Quick Info (Hover)
* Error Squiggles
* Debugging
* Support for debugging Windows (PDB, MinGW/Cygwin), Linux and macOS applications
* Line by line code stepping
* Breakpoints (including conditional and function breakpoints)
* Variable inspection
* Multi-threaded debugging support
* Core dump debugging support
* Executing GDB or MI commands directly when using 'C++ (GDB/LLDB)' debugging environment
* For help configuring the debugger see [Configuring launch.json for C/C++ debugging](https://github.com/Microsoft/vscode-cpptools/blob/master/launch.md)
on our [GitHub page](https://github.com/Microsoft/vscode-cpptools).
You can find more detailed information about C/C++ support for Visual Studio Code at our [GitHub page](https://github.com/Microsoft/vscode-cpptools/tree/master/Documentation) and our [VS Code documentation page](https://code.visualstudio.com/docs/languages/cpp).
#### [Repository](https://github.com/microsoft/vscode-cpptools)&nbsp;&nbsp;|&nbsp;&nbsp;[Issues](https://github.com/microsoft/vscode-cpptools/issues)&nbsp;&nbsp;|&nbsp;&nbsp;[Documentation](https://code.visualstudio.com/docs/languages/cpp)&nbsp;&nbsp;|&nbsp;&nbsp;[Code Samples](https://github.com/microsoft/vscode-cpptools/tree/master/Code%20Samples)&nbsp;&nbsp;|&nbsp;&nbsp;[Offline Installers](https://github.com/microsoft/vscode-cpptools/releases)
## Installation
The extension has OS-specific binary dependencies, so installation via the Marketplace requires an Internet connection so that these additional dependencies can be downloaded. If you are working on a computer that does not have access to the Internet or is behind a strict firewall, you may need to use our OS-specific packages and install them by invoking VS Code's `"Install from VSIX..."` command. These "offline' packages are available at: https://github.com/Microsoft/vscode-cpptools/releases.
* `cpptools-linux.vsix` - for 64-bit Linux
* `cpptools-linux32.vsix` - for 32-bit Linux
* `cpptools-osx.vsix` - for macOS
* `cpptools-win32.vsix` - for 64-bit & 32-bit Windows
[![Badge](https://aka.ms/vsls-badge)](https://aka.ms/vsls)
## Contact Us
If you run into any issues or have suggestions for us, please file [issues and suggestions on GitHub](https://github.com/Microsoft/vscode-cpptools/issues). If you havent already provided us feedback, please take this [quick survey](https://www.research.net/r/VBVV6C6) and let us know what you think!
This preview release of the C/C++ extension adds language support for C/C++ to Visual Studio Code, including features such as IntelliSense and debugging.
## Overview and getting started
* [C/C++ extension overview](https://code.visualstudio.com/docs/languages/cpp)
* [Get Started with C++ and Windows Subsystem for Linux (WSL)](https://code.visualstudio.com/docs/cpp/config-wsl)
* [Get Started with C++ and Mingw-w64](https://code.visualstudio.com/docs/cpp/config-mingw)
* [Get Started with C++ and Clang/LLVM on macOS](https://code.visualstudio.com/docs/cpp/config-clang-mac)
* [Get Started with C++ and Microsoft C++ compiler (MSVC)](https://code.visualstudio.com/docs/cpp/config-msvc)
## Quick links
* [Editing features (IntelliSense)](https://code.visualstudio.com/docs/cpp/cpp-ide)
* [IntelliSense configuration](https://code.visualstudio.com/docs/cpp/customize-default-settings-cpp)
* [Enhanced colorization](https://code.visualstudio.com/docs/cpp/colorization-cpp)
* [Debugging](https://code.visualstudio.com/docs/cpp/cpp-debug)
* [Debug configuration](https://code.visualstudio.com/docs/cpp/launch-json-reference)
* [Enable logging for IntelliSense or debugging](https://code.visualstudio.com/docs/cpp/enable-logging-cpp)
## Questions and feedback
**[FAQs](https://code.visualstudio.com/docs/cpp/faq-cpp)**
<br>
Check out the FAQs before filing a question.
<br>
**[Provide feedback](https://github.com/microsoft/vscode-cpptools/issues/new/choose)**
<br>
File questions, issues, or feature requests for the extension.
<br>
**[Known issues](https://github.com/Microsoft/vscode-cpptools/issues)**
<br>
If someone has already filed an issue that encompasses your feedback, please leave a 👍 or 👎 reaction on the issue to upvote or downvote it to help us prioritize the issue.
<br>
**[Quick survey](https://www.research.net/r/VBVV6C6)**
<br>
Let us know what you think of the extension by taking the quick survey.
## Offline installation
The extension has platform-specific binary dependencies, therfore installation via the Marketplace requires an Internet connection in order to download additional dependencies. If you are working on a computer that does not have access to the Internet or is behind a strict firewall, you may need to use our platform-specific packages and install them by running VS Code's `"Install from VSIX..."` command. These "offline' packages are available at: https://github.com/Microsoft/vscode-cpptools/releases.
Package | Platform
:--- | :---
`cpptools-linux.vsix` | Linux 64-bit
`cpptools-linux32.vsix` | Linux 32-bit
`cpptools-osx.vsix` | macOS
`cpptools-win32.vsix` | Windows 64-bit & 32-bit
## Contribution
Contributions are always welcome. Please see our [contributing guide](CONTRIBUTING.md) for more details.
## Microsoft Open Source Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact opencode@microsoft.com with any additional questions or comments.
## Data and telemetry
This extension collects usage data and sends it to Microsoft to help improve our products and services. Collection of telemetry is controlled via the same setting provided by Visual Studio Code: `"telemetry.enableTelemetry"`. Read our [privacy statement](https://privacy.microsoft.com/en-us/privacystatement) to learn more.
+10 -18
View File
@@ -205,22 +205,14 @@
<tr>
<td>
<div>
<h2 class="caption">March 2019 Update</h2>
<div>Thank you for installing the C/C++ extension! We're excited to announce the following features in the March update:<br/>
<h3 style="font-weight: 600">IntelliSense caching</h3>
The extension will now cache header information to improve IntelliSense speed for your code files.<br/>
<br/>
<em style="font-weight: 600">Please Note:</em> The extension writes the cache to disk in order to achieve this performance improvement. By default the cache files will be stored in your workspace
folder's ".vscode" folder, but you can change this location by using the <code>"C_Cpp.intelliSenseCachePath"</code> setting. You can also control how much disk space can be
used for the cache with the <code>"C_Cpp.intelliSenseCacheSize"</code> setting. The default is 5120 MB as the caches for individual translation units can be large,
depending on the size and number of included headers.<br/>
<h3 style="font-weight: 600">Build and debug the active source file</h3>
We added a command to help you generate build and debug tasks for single code files. Since this feature writes out tasks.json and launch.json files, it currently requires
that a workspace folder be opened in VS Code first. After that, you can press F5 or select the command from the context menu to configure the tasks or kick off a build and debug
session.<br/>
<h3 style="font-weight: 600">Configuration squiggles</h3>
We added additional validation to the <code>c_cpp_properties.json</code> file to assist in diagnosing potential configuration mistakes. They will show up as problems in the
problems window.<br/>
<h2 class="caption">June 2019 Update</h2>
<div>Thank you for installing the C/C++ extension! We're excited to announce the following feature in the June update:<br/>
<h3 style="font-weight: 600">Enhanced Colorization</h3>
The extension now supports semantic colorization.
Enhanced colorization adds colors for tokens identified semantically by IntelliSense.
Colors can be configured by themes or customized in settings.
More information can be found <a href="https://github.com/microsoft/vscode-cpptools/blob/master/Documentation/LanguageServer/colorization.md">here</a>.
<br/>
<br/>
Additional features and bug fixes are detailed in the <a href="https://github.com/Microsoft/vscode-cpptools/releases">full release notes</a>.</div>
@@ -246,9 +238,9 @@
<td>
<div>
<h3 class="caption">Blog Posts</h3>
<div><a href="https://devblogs.microsoft.com/cppblog/vscode-cpp-may-2019-update/">May 2019 Update</a></div>
<div><a href="https://devblogs.microsoft.com/cppblog/visual-studio-code-c-c-extension-march-2019-update/">March 2019 Update</a></div>
<div><a href="https://devblogs.microsoft.com/cppblog/vs-code-cpp-extension-january-2019-update/">January 2019 Update</a></div>
<div><a href="https://devblogs.microsoft.com/cppblog/visual-studio-code-cpp-extension-october-2018-update-and-a-simplified-insiders-program/">October 2018 Update</a></div>
<div><a href="https://devblogs.microsoft.com/cppblog/visual-studio-code-c-c-extension-august-2018-update/">August 2018 Update</a></div>
</div>
</td>
</tr>
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
{
"defaults": [
"--pack_alignment",
"8"
],
"defaults_op" : "merge"
}
+17
View File
@@ -0,0 +1,17 @@
{
"defaults": [
"-D_MSC_EXTENSIONS",
"--microsoft",
"--microsoft_bugs",
"--microsoft_version",
"1923",
"--pack_alignment",
"8",
"-D_MSC_VER=1923",
"-D_MSC_FULL_VER=192327820",
"-D_MSC_BUILD=0",
"-D_M_IX86=600",
"-D_M_IX86_FP=2"
],
"defaults_op" : "merge"
}
+7
View File
@@ -0,0 +1,7 @@
{
"defaults": [
"--pack_alignment",
"8"
],
"defaults_op" : "merge"
}
+3 -3
View File
@@ -4,11 +4,11 @@
"--microsoft",
"--microsoft_bugs",
"--microsoft_version",
"1914",
"1923",
"--pack_alignment",
"8",
"-D_MSC_VER=1914",
"-D_MSC_FULL_VER=191426428",
"-D_MSC_VER=1923",
"-D_MSC_FULL_VER=192327820",
"-D_MSC_BUILD=0",
"-D_M_IX86=600",
"-D_M_IX86_FP=2"
+7
View File
@@ -0,0 +1,7 @@
{
"defaults": [
"--pack_alignment",
"8"
],
"defaults_op" : "merge"
}
+17
View File
@@ -0,0 +1,17 @@
{
"defaults": [
"-D_MSC_EXTENSIONS",
"--microsoft",
"--microsoft_bugs",
"--microsoft_version",
"1923",
"--pack_alignment",
"8",
"-D_MSC_VER=1923",
"-D_MSC_FULL_VER=192327820",
"-D_MSC_BUILD=0",
"-D_M_IX86=600",
"-D_M_IX86_FP=2"
],
"defaults_op" : "merge"
}
+3 -3
View File
@@ -4,12 +4,12 @@
"--microsoft",
"--microsoft_bugs",
"--microsoft_version",
"1914",
"1923",
"--pack_alignment",
"8",
"-D_CPPUNWIND=1",
"-D_MSC_VER=1914",
"-D_MSC_FULL_VER=191426428",
"-D_MSC_VER=1923",
"-D_MSC_FULL_VER=192327820",
"-D_MSC_BUILD=0",
"-D_M_X64=100",
"-D_M_AMD64=100"
+3 -3
View File
@@ -4,12 +4,12 @@
"--microsoft",
"--microsoft_bugs",
"--microsoft_version",
"1914",
"1923",
"--pack_alignment",
"8",
"-D_CPPUNWIND=1",
"-D_MSC_VER=1914",
"-D_MSC_FULL_VER=191426428",
"-D_MSC_VER=1923",
"-D_MSC_FULL_VER=192327820",
"-D_MSC_BUILD=0",
"-D_M_X64=100",
"-D_M_AMD64=100"
+3 -3
View File
@@ -4,12 +4,12 @@
"--microsoft",
"--microsoft_bugs",
"--microsoft_version",
"1914",
"1923",
"--pack_alignment",
"8",
"-D_CPPUNWIND=1",
"-D_MSC_VER=1914",
"-D_MSC_FULL_VER=191426428",
"-D_MSC_VER=1923",
"-D_MSC_FULL_VER=192327820",
"-D_MSC_BUILD=0",
"-D_M_X64=100",
"-D_M_AMD64=100"
+13 -2
View File
@@ -15,9 +15,16 @@
"type": "string"
},
"compilerPath": {
"description": "Full path of the compiler being used, e.g. /usr/bin/gcc, to enable more accurate IntelliSense. Args can be added to modify the includes/defines used, e.g. -nostdinc++, -m32, etc., but paths with spaces must be surrounded with \\\" if args are used.",
"description": "Full path of the compiler being used, e.g. /usr/bin/gcc, to enable more accurate IntelliSense.",
"type": "string"
},
"compilerArgs": {
"description": "Compiler arguments to modify the includes or defines used, e.g. -nostdinc++, -m32, etc.",
"type": "array",
"items": {
"type": "string"
}
},
"cStandard": {
"description": "Version of the C language standard to use for IntelliSense.",
"type": "string",
@@ -37,6 +44,7 @@
"c++11",
"c++14",
"c++17",
"c++20",
"${default}"
]
},
@@ -71,12 +79,15 @@
}
},
"intelliSenseMode": {
"description": "If set, it overrides the default mode used by the IntelliSense engine. Windows defaults to msvc-x64, Linux defaults to gcc-x64, and Mac default to clang-x64.",
"description": "The IntelliSense mode to use that maps to an architecture-specific variant of MSVC, gcc, or Clang. If not set or if set to ${default}, the extension will choose the default for that platform. Windows defaults to msvc-x64, Linux defaults to gcc-x64, and macOS defaults to clang-x64.",
"type": "string",
"enum": [
"msvc-x64",
"gcc-x64",
"clang-x64",
"msvc-x86",
"gcc-x86",
"clang-x86",
"${default}"
]
},
+2 -1
View File
@@ -2,5 +2,6 @@
"intelliSenseEngine_default_percentage": 100,
"defaultIntelliSenseEngine": 100,
"recursiveIncludes": 100,
"gotoDefIntelliSense": 100
"gotoDefIntelliSense": 100,
"enhancedColorization": 100
}
-19
View File
@@ -29,28 +29,9 @@ gulp.task('unitTests', (done) => {
});
});
gulp.task('integrationTests', (done) => {
env.set({
CODE_TESTS_PATH: "./out/test/integrationTests",
CODE_TESTS_WORKSPACE: "./test/integrationTests/testAssets/SimpleCppProject"
});
return gulp.src('./test/runVsCodeTestsWithAbsolutePaths.js', {read: false})
.pipe(mocha({ ui: "tdd" }))
.once('error', err => {
done();
process.exit(1);
})
.once('end', () => {
done();
process.exit();
});
});
/// Misc Tasks
const allTypeScript = [
'src/**/*.ts',
'tools/**/*.ts',
'!**/*.d.ts',
'!**/typings**'
];
+6 -17
View File
@@ -16,7 +16,7 @@ jobs:
- script: npm install
displayName: "Install Dependencies"
workingDirectory: '$(Build.SourcesDirectory)\Extension'
- script: npm run compile
displayName: "Compile Sources"
workingDirectory: '$(Build.SourcesDirectory)\Extension'
@@ -29,28 +29,17 @@ jobs:
displayName: 'Run Linter'
workingDirectory: '$(Build.SourcesDirectory)\Extension'
- script: npm run pretest
displayName: "Compile Test Sources"
workingDirectory: '$(Build.SourcesDirectory)\Extension'
- script: 'npm run unitTests'
displayName: 'Run unit tests'
workingDirectory: '$(Build.SourcesDirectory)\Extension'
continueOnError: true
- script: 'copy "$(Build.SourcesDirectory)\Extension\out\test\integrationTests\MockDebugger\debugAdapterDescriptorFactory.js" "$(Build.SourcesDirectory)\Extension\out\src\Debugger\debugAdapterDescriptorFactory.js" /Y'
displayName: Replace Debug Adapter Descriptor Factory
- script: 'node node_modules/vscode/bin/test'
displayName: 'Run debug integration tests'
workingDirectory: '$(Build.SourcesDirectory)\Extension'
continueOnError: true
env:
CODE_TESTS_PATH: '$(Build.SourcesDirectory)\Extension\out\test\integrationTests\debug'
CODE_EXTENSIONS_PATH: '$(Build.SourcesDirectory)\Extension'
CODE_TESTS_WORKSPACE: '$(Build.SourcesDirectory)\Extension\test\integrationTests\testAssets\SimpleCppProject'
CODE_DISABLE_EXTENSIONS: 1
- script: 'node node_modules/vscode/bin/test'
displayName: 'Run languageServer integration tests'
workingDirectory: '$(Build.SourcesDirectory)\Extension'
continueOnError: true
env:
CODE_TESTS_PATH: '$(Build.SourcesDirectory)\Extension\out\test\integrationTests\languageServer'
CODE_EXTENSIONS_PATH: '$(Build.SourcesDirectory)\Extension'
@@ -59,4 +48,4 @@ jobs:
- task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0
displayName: 'Component Detection'
continueOnError: true
continueOnError: true
+8 -22
View File
@@ -15,7 +15,7 @@ jobs:
- script: npm install
displayName: "Install Dependencies"
workingDirectory: '$(Build.SourcesDirectory)/Extension'
- script: npm run compile
displayName: "Compile Sources"
workingDirectory: '$(Build.SourcesDirectory)/Extension'
@@ -28,37 +28,23 @@ jobs:
displayName: 'Run Linter'
workingDirectory: '$(Build.SourcesDirectory)/Extension'
- script: 'npm run unitTests'
displayName: 'Run unit tests'
workingDirectory: '$(Build.SourcesDirectory)/Extension'
continueOnError: true
- script: |
set -e
/usr/bin/Xvfb :10 -ac >> /tmp/Xvfb.out 2>&1 &
disown -ar
displayName: 'Start xvfb'
- script: |
cp $(Build.SourcesDirectory)/Extension/out/test/integrationTests/MockDebugger/debugAdapterDescriptorFactory.js $(Build.SourcesDirectory)/Extension/out/src/Debugger/debugAdapterDescriptorFactory.js
displayName: Replace Debug Adapter Descriptor Factory
- script: 'node node_modules/vscode/bin/test'
displayName: 'Run debug integration tests'
- script: npm run pretest
displayName: "Compile Test Sources"
workingDirectory: '$(Build.SourcesDirectory)/Extension'
- script: 'npm run unitTests'
displayName: 'Run unit tests'
workingDirectory: '$(Build.SourcesDirectory)/Extension'
continueOnError: true
env:
MOCK_DEBUG: 1
DISPLAY: :10
CODE_TESTS_PATH: '$(Build.SourcesDirectory)/Extension/out/test/integrationTests/debug'
CODE_EXTENSIONS_PATH: '$(Build.SourcesDirectory)/Extension'
CODE_TESTS_WORKSPACE: '$(Build.SourcesDirectory)/Extension/test/integrationTests/testAssets/SimpleCppProject'
CODE_DISABLE_EXTENSIONS: 1
- script: 'node node_modules/vscode/bin/test'
displayName: 'Run languageServer integration tests'
workingDirectory: '$(Build.SourcesDirectory)/Extension'
continueOnError: true
env:
DISPLAY: :10
CODE_TESTS_PATH: '$(Build.SourcesDirectory)/Extension/out/test/integrationTests/languageServer'
@@ -68,4 +54,4 @@ jobs:
- task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0
displayName: 'Component Detection'
continueOnError: true
continueOnError: true
+2807 -1149
View File
File diff suppressed because it is too large Load Diff
+124 -112
View File
@@ -2,7 +2,7 @@
"name": "cpptools",
"displayName": "C/C++",
"description": "C/C++ IntelliSense, debugging, and code browsing.",
"version": "0.23.0-master",
"version": "0.25.0-master",
"publisher": "ms-vscode",
"preview": true,
"icon": "LanguageCCPP_color_128x.png",
@@ -41,18 +41,19 @@
"activationEvents": [
"*"
],
"main": "./out/src/main",
"main": "./dist/main",
"contributes": {
"problemMatchers": [
{
"name": "gcc",
"source": "gcc",
"owner": "cpptools",
"fileLocation": [
"relative",
"${workspaceFolder}"
],
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"regexp": "^(.*):(\\d+):(\\d+):\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
@@ -72,7 +73,7 @@
],
"default": null,
"description": "The full path of the clang-format executable.",
"scope": "resource"
"scope": "machine"
},
"C_Cpp.clang_format_style": {
"type": "string",
@@ -145,7 +146,7 @@
"C_Cpp.dimInactiveRegions": {
"type": "boolean",
"default": true,
"description": "Controls whether inactive preprocessor blocks are colored differently than active code. This setting is ignored by the Tag Parser engine.",
"description": "Controls whether inactive preprocessor blocks are colored differently than active code. This setting has no effect if IntelliSense is disabled or if using the Default High Contrast theme.",
"scope": "resource"
},
"C_Cpp.inactiveRegionOpacity": {
@@ -292,8 +293,8 @@
},
"C_Cpp.intelliSenseCachePath": {
"type": "string",
"default": "${workspaceFolder}/.vscode",
"description": "Defines the folder path for cached precompiled headers used by IntelliSense. The default path \"${workspaceFolder}/.vscode\" will be used if a specified path is invalid.",
"default": null,
"description": "Defines the folder path for cached precompiled headers used by IntelliSense. The default cache path is \"%LocalAppData%/Microsoft/vscode-cpptools\" on Windows and \"~/.vscode-cpptools\" on Linux and Mac. The default path will be used if no path is specified or if a specified path is invalid.",
"scope": "resource"
},
"C_Cpp.intelliSenseCacheSize": {
@@ -378,7 +379,10 @@
"enum": [
"msvc-x64",
"gcc-x64",
"clang-x64"
"clang-x64",
"msvc-x86",
"gcc-x86",
"clang-x86"
],
"default": null,
"description": "The value to use in a configuration if \"intelliSenseMode\" is either not specified or set to \"${default}\".",
@@ -393,6 +397,18 @@
"description": "The value to use in a configuration if \"compilerPath\" is either not specified or set to \"${default}\".",
"scope": "resource"
},
"C_Cpp.default.compilerArgs": {
"type": [
"array",
"null"
],
"items": {
"type": "string"
},
"default": null,
"description": "The value to use in configuration if \"compilerArgs\" is either not specified or set to \"${default}\".",
"scope": "resource"
},
"C_Cpp.default.cStandard": {
"type": [
"string",
@@ -417,7 +433,8 @@
"c++03",
"c++11",
"c++14",
"c++17"
"c++17",
"c++20"
],
"default": null,
"description": "The value to use in a configuration if \"cppStandard\" is either not specified or set to \"${default}\".",
@@ -490,11 +507,37 @@
"description": "Set to \"Insiders\" to automatically download and install the latest Insiders builds of the extension, which include upcoming features and bug fixes.",
"scope": "resource"
},
"C_Cpp.experimentalFeatures": {
"type": "string",
"enum": [
"Enabled",
"Disabled"
],
"default": "Disabled",
"description": "Controls whether \"experimental\" features are usable.",
"scope": "resource"
},
"C_Cpp.suggestSnippets": {
"type": "boolean",
"default": true,
"description": "If true, snippets are provided by the language server.",
"scope": "resource"
},
"C_Cpp.enhancedColorization": {
"type": "string",
"enum": [
"Enabled",
"Disabled"
],
"default": "Enabled",
"description": "If enabled, code is colorized based on IntelliSense. This setting has no effect if IntelliSense is disabled or if using the Default High Contrast theme.",
"scope": "resource"
},
"C_Cpp.vcpkg.enabled": {
"type": "boolean",
"default": true,
"markdownDescription": "Enable integration services for the [vcpkg dependency manager](https://aka.ms/vcpkg/).",
"scope": "resource"
}
}
},
@@ -519,16 +562,6 @@
"title": "%c_cpp.command.configurationEditUI.title%",
"category": "C/C++"
},
{
"command": "C_Cpp.GoToDeclaration",
"title": "%c_cpp.command.goToDeclaration.title%",
"category": "C/C++"
},
{
"command": "C_Cpp.PeekDeclaration",
"title": "%c_cpp.command.peekDeclaration.title%",
"category": "C/C++"
},
{
"command": "C_Cpp.SwitchHeaderSource",
"title": "%c_cpp.command.switchHeaderSource.title%",
@@ -569,21 +602,6 @@
"title": "%c_cpp.command.resetDatabase.title%",
"category": "C/C++"
},
{
"command": "C_Cpp.PauseParsing",
"title": "%c_cpp.command.pauseParsing.title%",
"category": "C/C++"
},
{
"command": "C_Cpp.ResumeParsing",
"title": "%c_cpp.command.resumeParsing.title%",
"category": "C/C++"
},
{
"command": "C_Cpp.ShowParsingCommands",
"title": "%c_cpp.command.showParsingCommands.title%",
"category": "C/C++"
},
{
"command": "C_Cpp.TakeSurvey",
"title": "%c_cpp.command.takeSurvey.title%",
@@ -598,29 +616,24 @@
"command": "C_Cpp.LogDiagnostics",
"title": "%c_cpp.command.logDiagnostics.title%",
"category": "C/C++"
},
{
"command": "C_Cpp.RescanWorkspace",
"title": "%c_cpp.command.rescanWorkspace.title%",
"category": "C/C++"
},
{
"command": "C_Cpp.VcpkgClipboardInstallSuggested",
"title": "%c_cpp.command.vcpkgClipboardInstallSuggested.title%",
"category": "C/C++"
},
{
"command": "C_Cpp.VcpkgOnlineHelpSuggested",
"title": "%c_cpp.command.vcpkgOnlineHelpSuggested.title%",
"category": "C/C++"
}
],
"keybindings": [
{
"command": "C_Cpp.GoToDeclaration",
"key": "Ctrl+F12",
"when": "editorTextFocus && editorLangId == 'cpp'"
},
{
"command": "C_Cpp.GoToDeclaration",
"key": "Ctrl+F12",
"when": "editorTextFocus && editorLangId == 'c'"
},
{
"command": "C_Cpp.PeekDeclaration",
"key": "Ctrl+Alt+F12",
"when": "editorTextFocus && editorLangId == 'cpp'"
},
{
"command": "C_Cpp.PeekDeclaration",
"key": "Ctrl+Alt+F12",
"when": "editorTextFocus && editorLangId == 'c'"
},
{
"command": "C_Cpp.SwitchHeaderSource",
"key": "Alt+O",
@@ -781,6 +794,11 @@
},
"default": []
},
"envFile": {
"type": "string",
"description": "Absolute path to a file containing environment variable definitions. This file has key value pairs separated by an equals sign per line. E.g. KEY=VALUE",
"default": "${workspaceFolder}/.env"
},
"additionalSOLibSearchPath": {
"type": "string",
"description": "Semicolon separated list of directories to use to search for .so files. Example: \"c:\\dir1;c:\\dir2\".",
@@ -1201,6 +1219,11 @@
},
"default": []
},
"envFile": {
"type": "string",
"description": "Absolute path to a file containing environment variable definitions. This file has key value pairs separated by an equals sign per line. E.g. KEY=VALUE",
"default": "${workspaceFolder}/.env"
},
"symbolSearchPath": {
"type": "string",
"description": "Semicolon separated list of directories to use to search for symbol (that is, pdb) files. Example: \"c:\\dir1;c:\\dir2\".",
@@ -1350,26 +1373,6 @@
],
"menus": {
"editor/context": [
{
"when": "editorLangId == c",
"command": "C_Cpp.GoToDeclaration",
"group": "navigation@2"
},
{
"when": "editorLangId == cpp",
"command": "C_Cpp.GoToDeclaration",
"group": "navigation@2"
},
{
"when": "editorLangId == c",
"command": "C_Cpp.PeekDeclaration",
"group": "navigation@3"
},
{
"when": "editorLangId == cpp",
"command": "C_Cpp.PeekDeclaration",
"group": "navigation@3"
},
{
"when": "editorLangId == c",
"command": "C_Cpp.SwitchHeaderSource",
@@ -1428,61 +1431,70 @@
},
"[c]": {
"editor.wordBasedSuggestions": false
},
"[Log]": {
"editor.wordWrap": "off"
}
}
},
"scripts": {
"compile": "npm run vscode:prepublish",
"compileDev": "npm run prepublishjs && webpack --mode development",
"generateOptionsSchema": "gulp generateOptionsSchema",
"integrationTests": "gulp integrationTests",
"postinstall": "node ./node_modules/vscode/bin/install",
"pretest": "tsc -p ./",
"prepublishjs": "node ./tools/prepublish.js",
"pretest": "tsc -p test.tsconfig.json",
"pr-check": "gulp pr-check",
"test": "gulp allTests",
"tslint": "gulp tslint",
"unitTests": "gulp unitTests",
"vscode:prepublish": "node ./src/Support/prepublish.js",
"watch": "tsc -watch -p ./"
"vscode:prepublish": "npm run prepublishjs && webpack --mode production",
"watch": "webpack --watch --mode development"
},
"devDependencies": {
"@types/mocha": "^5.2.6",
"@types/node": "^8.10.45",
"@types/minimatch": "^3.0.3",
"@types/mkdirp": "^0.5.2",
"@types/mocha": "^5.2.7",
"@types/node": "^12.6.3",
"@types/plist": "^3.0.2",
"@types/tmp": "^0.1.0",
"@types/webpack": "^4.4.35",
"@types/yauzl": "^2.9.1",
"async-child-process": "^1.1.1",
"await-notify": "^1.0.1",
"child-process": "^1.0.2",
"extend": "3.0.2",
"gulp": "^4.0.0",
"gulp-env": "0.4.0",
"gulp-mocha": "5.0.0",
"gulp-tslint": "8.1.2",
"mocha": "^5.2.0",
"tslint": "5.8.0",
"tslint-microsoft-contrib": "5.0.1",
"tslint-no-unused-expression-chai": "0.0.3",
"typescript": "^2.9.2",
"vrsource-tslint-rules": "^5.8.3",
"vscode": "^1.1.33"
"gulp": "^4.0.2",
"gulp-env": "^0.4.0",
"gulp-mocha": "^6.0.0",
"gulp-tslint": "^8.1.4",
"ts-loader": "^6.0.4",
"tslint": "^5.18.0",
"tslint-microsoft-contrib": "^6.2.0",
"tslint-no-unused-expression-chai": "^0.1.4",
"typescript": "^3.5.3",
"vrsource-tslint-rules": "^6.0.0",
"vscode": "^1.1.35",
"webpack": "^4.35.3",
"webpack-cli": "^3.3.6"
},
"dependencies": {
"@types/minimatch": "^3.0.3",
"escape-string-regexp": "1.0.5",
"http-proxy-agent": "~2.1.0",
"https-proxy-agent": "~2.2.0",
"jsonc-parser": "^1.0.0",
"minimatch": "~3.0.4",
"mkdirp": "~0.5.1",
"tmp": "~0.0.33",
"vscode-cpptools": "2.1.1",
"vscode-debugadapter": "~1.33.0",
"vscode-debugprotocol": "~1.33.0",
"vscode-extension-telemetry": "^0.1.1",
"vscode-languageclient": "5.1.1",
"yauzl": "~2.10.0"
"escape-string-regexp": "^2.0.0",
"http-proxy-agent": "^2.1.0",
"https-proxy-agent": "^2.2.2",
"jsonc-parser": "^2.1.0",
"minimatch": "^3.0.4",
"mkdirp": "^0.5.1",
"plist": "^2.0.1",
"tmp": "^0.1.0",
"vscode-cpptools": "^3.0.0",
"vscode-debugadapter": "^1.35.0",
"vscode-debugprotocol": "^1.35.0",
"vscode-extension-telemetry": "^0.1.2",
"vscode-languageclient": "^5.2.1",
"yauzl": "^2.10.0"
},
"runtimeDependencies": [
{
"description": "C/C++ language components (Linux / x86_64)",
"url": "https://go.microsoft.com/fwlink/?linkid=2085632",
"url": "https://go.microsoft.com/fwlink/?linkid=2098277",
"platforms": [
"linux"
],
@@ -1496,7 +1508,7 @@
},
{
"description": "C/C++ language components (Linux / x86)",
"url": "https://go.microsoft.com/fwlink/?linkid=2085734",
"url": "https://go.microsoft.com/fwlink/?linkid=2098276",
"platforms": [
"linux"
],
@@ -1512,7 +1524,7 @@
},
{
"description": "C/C++ language components (OS X)",
"url": "https://go.microsoft.com/fwlink/?linkid=2085735",
"url": "https://go.microsoft.com/fwlink/?linkid=2098195",
"platforms": [
"darwin"
],
@@ -1523,7 +1535,7 @@
},
{
"description": "C/C++ language components (Windows)",
"url": "https://go.microsoft.com/fwlink/?linkid=2085633",
"url": "https://go.microsoft.com/fwlink/?linkid=2098194",
"platforms": [
"win32"
],
+7 -9
View File
@@ -3,9 +3,7 @@
"c_cpp.command.configurationProviderSelect.title": "Cambia provider configurazioni...",
"c_cpp.command.configurationEditJSON.title": "Modifica configurazioni (JSON)",
"c_cpp.command.configurationEditUI.title": "Modifica configurazioni (UI)",
"c_cpp.command.goToDeclaration.title": "Vai a dichiarazione",
"c_cpp.command.peekDeclaration.title": "Visualizza dichiarazione",
"c_cpp.command.switchHeaderSource.title": "Visualizza Header/Sorgente",
"c_cpp.command.switchHeaderSource.title": "Visualizza header/sorgente",
"c_cpp.command.navigate.title": "Naviga...",
"c_cpp.command.enableErrorSquiggles.title": "Attiva sottolineamento errori",
"c_cpp.command.disableErrorSquiggles.title": "Disattiva sottolineamento errori",
@@ -13,10 +11,10 @@
"c_cpp.command.toggleDimInactiveRegions.title": "Attiva/Disattiva colorazione regioni inattive",
"c_cpp.command.showReleaseNotes.title": "Mostra note di rilascio",
"c_cpp.command.resetDatabase.title": "Reimposta il database di IntelliSense",
"c_cpp.command.pauseParsing.title": "Metti in pausa l'analisi del codice",
"c_cpp.command.resumeParsing.title": "Riprendi l'analisi del codice",
"c_cpp.command.showParsingCommands.title": "Mostra comandi per l'analisi del codice",
"c_cpp.command.takeSurvey.title": "Partecipa al Sondaggio",
"c_cpp.command.buildAndDebugActiveFile.title": "Compila ed Esegui il debug del file attivo",
"c_cpp.command.logDiagnostics.title": "Registra Diagnostica"
"c_cpp.command.takeSurvey.title": "Partecipa al sondaggio",
"c_cpp.command.buildAndDebugActiveFile.title": "Compila ed esegui il debug del file attivo",
"c_cpp.command.logDiagnostics.title": "Registra diagnostica",
"c_cpp.command.rescanWorkspace.title": "Ripetere l'analisi dell'area di lavoro",
"c_cpp.command.vcpkgClipboardInstallSuggested.title": "Copia il comando di installazione di vcpkg negli appunti",
"c_cpp.command.vcpkgOnlineHelpSuggested.title": "Visita la pagina di aiuto di vcpkg"
}
+15 -17
View File
@@ -1,22 +1,20 @@
{
"c_cpp.command.configurationSelect.title": "Select a configuration...",
"c_cpp.command.configurationProviderSelect.title": "Change configuration provider...",
"c_cpp.command.configurationEditJSON.title": "Edit configurations (JSON)",
"c_cpp.command.configurationEditUI.title": "Edit configurations (UI)",
"c_cpp.command.goToDeclaration.title": "Go to Declaration",
"c_cpp.command.peekDeclaration.title": "Peek Declaration",
"c_cpp.command.configurationSelect.title": "Select a Configuration...",
"c_cpp.command.configurationProviderSelect.title": "Change Configuration Provider...",
"c_cpp.command.configurationEditJSON.title": "Edit Configurations (JSON)",
"c_cpp.command.configurationEditUI.title": "Edit Configurations (UI)",
"c_cpp.command.switchHeaderSource.title": "Switch Header/Source",
"c_cpp.command.navigate.title": "Navigate...",
"c_cpp.command.enableErrorSquiggles.title": "Enable error squiggles",
"c_cpp.command.disableErrorSquiggles.title": "Disable error squiggles",
"c_cpp.command.toggleIncludeFallback.title": "Toggle IntelliSense engine fallback on include errors",
"c_cpp.command.toggleDimInactiveRegions.title": "Toggle inactive region colorization",
"c_cpp.command.showReleaseNotes.title": "Show release notes",
"c_cpp.command.resetDatabase.title": "Reset IntelliSense database",
"c_cpp.command.pauseParsing.title": "Pause parsing",
"c_cpp.command.resumeParsing.title": "Resume parsing",
"c_cpp.command.showParsingCommands.title": "Show parsing commands",
"c_cpp.command.takeSurvey.title": "Take survey",
"c_cpp.command.enableErrorSquiggles.title": "Enable Error Squiggles",
"c_cpp.command.disableErrorSquiggles.title": "Disable Error Squiggles",
"c_cpp.command.toggleIncludeFallback.title": "Toggle IntelliSense Engine Fallback on Include Errors",
"c_cpp.command.toggleDimInactiveRegions.title": "Toggle Inactive Region Colorization",
"c_cpp.command.showReleaseNotes.title": "Show Release Notes",
"c_cpp.command.resetDatabase.title": "Reset IntelliSense Database",
"c_cpp.command.takeSurvey.title": "Take Survey",
"c_cpp.command.buildAndDebugActiveFile.title": "Build and Debug Active File",
"c_cpp.command.logDiagnostics.title": "Log Diagnostics"
"c_cpp.command.logDiagnostics.title": "Log Diagnostics",
"c_cpp.command.rescanWorkspace.title": "Rescan Workspace",
"c_cpp.command.vcpkgClipboardInstallSuggested.title": "Copy vcpkg install command to clipboard",
"c_cpp.command.vcpkgOnlineHelpSuggested.title": "Visit the vcpkg help page"
}
+4 -6
View File
@@ -3,8 +3,6 @@
"c_cpp.command.configurationProviderSelect.title": "更换配置提供程序...",
"c_cpp.command.configurationEditJSON.title": "编辑配置 (JSON)",
"c_cpp.command.configurationEditUI.title": "编辑配置 (UI)",
"c_cpp.command.goToDeclaration.title": "跳转到声明",
"c_cpp.command.peekDeclaration.title": "查看声明",
"c_cpp.command.switchHeaderSource.title": "切换头文件/源文件",
"c_cpp.command.navigate.title": "导航...",
"c_cpp.command.enableErrorSquiggles.title": "启用错误下划线",
@@ -13,10 +11,10 @@
"c_cpp.command.toggleDimInactiveRegions.title": "切换非活跃区域着色",
"c_cpp.command.showReleaseNotes.title": "查看版本说明",
"c_cpp.command.resetDatabase.title": "重置IntelliSense数据",
"c_cpp.command.pauseParsing.title": "暂停解析",
"c_cpp.command.resumeParsing.title": "继续解析",
"c_cpp.command.showParsingCommands.title": "查看解析命令",
"c_cpp.command.takeSurvey.title": "调查问卷",
"c_cpp.command.buildAndDebugActiveFile.title": "生成和调试当前文件",
"c_cpp.command.logDiagnostics.title": "记录诊断"
"c_cpp.command.logDiagnostics.title": "记录诊断",
"c_cpp.command.rescanWorkspace.title": "重新扫描工作区",
"c_cpp.command.vcpkgClipboardInstallSuggested.title": "将vcpkg install命令复制到剪贴板",
"c_cpp.command.vcpkgOnlineHelpSuggested.title": "访问vcpkg帮助页面"
}
@@ -0,0 +1,85 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as fs from 'fs';
export interface Environment {
name: string;
value: string;
}
export class ParsedEnvironmentFile {
public Env: Environment[];
public Warning: string | null;
private constructor(env: Environment[], warning: string | null) {
this.Env = env;
this.Warning = warning;
}
public static CreateFromFile(envFile: string, initialEnv: Environment[] | undefined): ParsedEnvironmentFile {
let content: string = fs.readFileSync(envFile, "utf8");
return this.CreateFromContent(content, envFile, initialEnv);
}
public static CreateFromContent(content: string, envFile: string, initialEnv: Environment[] | undefined): ParsedEnvironmentFile {
// Remove UTF-8 BOM if present
if (content.charAt(0) === '\uFEFF') {
content = content.substr(1);
}
let parseErrors: string[] = [];
let env: Map<string, any> = new Map();
if (initialEnv) {
// Convert array to map to prevent duplicate keys being created.
// If a duplicate key is found, replace it.
initialEnv.forEach((e) => {
env.set(e.name, e.value);
});
}
content.split("\n").forEach(line => {
// Split the line between key and value
const r: RegExpMatchArray = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/);
if (r !== null) {
const key: string = r[1];
let value: string = r[2] || "";
if ((value.length > 0) && (value.charAt(0) === '"') && (value.charAt(value.length - 1) === '"')) {
value = value.replace(/\\n/gm, "\n");
}
value = value.replace(/(^['"]|['"]$)/g, "");
env.set(key, value);
} else {
// Blank lines and lines starting with # are no parse errors
const comments: RegExp = new RegExp(/^\s*(#|$)/);
if (!comments.test(line)) {
parseErrors.push(line);
}
}
});
// show error message if single lines cannot get parsed
let warning: string = null;
if (parseErrors.length !== 0) {
warning = "Ignoring non-parseable lines in envFile " + envFile + ": ";
parseErrors.forEach(function (value, idx, array): void {
warning += "\"" + value + "\"" + ((idx !== array.length - 1) ? ", " : ".");
});
}
// Convert env map back to array.
const arrayEnv: Environment[] = [];
for (let key of env.keys()) {
arrayEnv.push({name: key, value: env.get(key)});
}
return new ParsedEnvironmentFile(arrayEnv, warning);
}
}
+21 -8
View File
@@ -3,7 +3,6 @@
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import { execChildProcess } from '../common';
import { PsProcessParser } from './nativeAttach';
import { AttachItem, showQuickPick } from './attachQuickPick';
@@ -103,15 +102,29 @@ export class RemoteAttachPicker {
});
}
private getRemoteOSAndProcesses(pipeCmd: string): Promise<AttachItem[]> {
// Commands to get OS and processes
const command: string = `sh -c "uname && if [ $(uname) = \\\"Linux\\\" ] ; then ${PsProcessParser.psLinuxCommand} ; elif [ $(uname) = \\\"Darwin\\\" ] ; ` +
`then ${PsProcessParser.psDarwinCommand}; fi"`;
// Creates a string to run on the host machine which will execute a shell script on the remote machine to retrieve OS and processes
private getRemoteProcessCommand(): string {
let innerQuote: string = `'`;
let outerQuote: string = `"`;
// Must use single quotes around ${command}. Linux systems evaluate $() within double-quotes.
return execChildProcess(`${pipeCmd} '${command}'`, null, this._channel).then(output => {
// Must use single quotes around the whole command and double quotes for the argument to `sh -c` because Linux evaluates $() inside of double quotes.
// Having double quotes for the outerQuote will have $(uname) replaced before it is sent to the remote machine.
if (os.platform() !== "win32") {
innerQuote = `"`;
outerQuote = `'`;
}
return `${outerQuote}sh -c ${innerQuote}uname && if [ $(uname) = \\\"Linux\\\" ] ; then ${PsProcessParser.psLinuxCommand} ; elif [ $(uname) = \\\"Darwin\\\" ] ; ` +
`then ${PsProcessParser.psDarwinCommand}; fi${innerQuote}${outerQuote}`;
}
private getRemoteOSAndProcesses(pipeCmd: string): Promise<AttachItem[]> {
// Do not add any quoting in execCommand.
const execCommand: string = `${pipeCmd} ${this.getRemoteProcessCommand()}`;
return util.execChildProcess(execCommand, null, this._channel).then(output => {
// OS will be on first line
// Processess will follow if listed
// Processes will follow if listed
let lines: string[] = output.split(/\r?\n/);
if (lines.length === 0) {
+98 -10
View File
@@ -12,10 +12,12 @@ import * as util from '../common';
import * as fs from 'fs';
import * as Telemetry from '../telemetry';
import { buildAndDebugActiveFileStr } from './extension';
import * as logger from '../logger';
import { IConfiguration, IConfigurationSnippet, DebuggerType, MIConfigurations, WindowsConfigurations, WSLConfigurations, PipeTransportConfigurations } from './configurations';
import { parse } from 'jsonc-parser';
import { PlatformInformation } from '../platform';
import { Environment, ParsedEnvironmentFile } from './ParsedEnvironmentFile';
function isDebugLaunchStr(str: string): boolean {
return str === "(gdb) Launch" || str === "(lldb) Launch" || str === "(Windows) Launch";
@@ -35,7 +37,7 @@ export class QuickPickConfigurationProvider implements vscode.DebugConfiguration
async provideDebugConfigurations(folder: vscode.WorkspaceFolder | undefined, token?: vscode.CancellationToken): Promise<vscode.DebugConfiguration[]> {
const configs: vscode.DebugConfiguration[] = await this.underlyingProvider.provideDebugConfigurations(folder, token);
const defaultConfig: vscode.DebugConfiguration = configs.find(config => { return isDebugLaunchStr(config.name); });
const defaultConfig: vscode.DebugConfiguration = configs.find(config => isDebugLaunchStr(config.name));
console.assert(defaultConfig);
const editor: vscode.TextEditor = vscode.window.activeTextEditor;
if (!editor || !util.fileIsCOrCppSource(editor.document.fileName) || configs.length <= 1) {
@@ -94,7 +96,7 @@ class CppConfigurationProvider implements vscode.DebugConfigurationProvider {
* Returns a list of initial debug configurations based on contextual information, e.g. package.json or folder.
*/
async provideDebugConfigurations(folder: vscode.WorkspaceFolder | undefined, token?: vscode.CancellationToken): Promise<vscode.DebugConfiguration[]> {
let buildTasks: vscode.Task[] = await getBuildTasks(true);
let buildTasks: vscode.Task[] = await getBuildTasks(true);
if (buildTasks.length === 0) {
return Promise.resolve(this.provider.getInitialConfigurations(this.type));
}
@@ -126,7 +128,7 @@ class CppConfigurationProvider implements vscode.DebugConfigurationProvider {
const definition: BuildTaskDefinition = task.definition as BuildTaskDefinition;
const compilerName: string = path.basename(definition.compilerPath);
let newConfig: vscode.DebugConfiguration = Object.assign({}, defaultConfig); // Copy enumerables and properties
let newConfig: vscode.DebugConfiguration = {...defaultConfig}; // Copy enumerables and properties
newConfig.name = compilerName + buildAndDebugActiveFileStr();
newConfig.preLaunchTask = task.name;
@@ -151,11 +153,11 @@ class CppConfigurationProvider implements vscode.DebugConfigurationProvider {
} else {
debuggerName = "gdb";
}
if (platform === "win32") {
debuggerName += ".exe";
}
const compilerDirname: string = path.dirname(definition.compilerPath);
const debuggerPath: string = path.join(compilerDirname, debuggerName);
fs.stat(debuggerPath, (err, stats: fs.Stats) => {
@@ -182,13 +184,13 @@ class CppConfigurationProvider implements vscode.DebugConfigurationProvider {
if (config.type === 'cppvsdbg') {
// Fail if cppvsdbg type is running on non-Windows
if (os.platform() !== 'win32') {
vscode.window.showErrorMessage("Debugger of type: 'cppvsdbg' is only available on Windows. Use type: 'cppdbg' on the current OS platform.");
logger.getOutputChannelLogger().showWarningMessage("Debugger of type: 'cppvsdbg' is only available on Windows. Use type: 'cppdbg' on the current OS platform.");
return undefined;
}
// Disable debug heap by default, enable if 'enableDebugHeap' is set.
if (!config.enableDebugHeap) {
const disableDebugHeapEnvSetting : any = {"name" : "_NO_DEBUG_HEAP", "value" : "1"};
const disableDebugHeapEnvSetting : Environment = {"name" : "_NO_DEBUG_HEAP", "value" : "1"};
if (config.environment && util.isArray(config.environment)) {
config.environment.push(disableDebugHeapEnvSetting);
@@ -198,6 +200,11 @@ class CppConfigurationProvider implements vscode.DebugConfigurationProvider {
}
}
// Add environment variables from .env file
this.resolveEnvFile(config, folder);
this.resolveSourceFileMapVariables(config);
// Modify WSL config for OpenDebugAD7
if (os.platform() === 'win32' &&
config.pipeTransport &&
@@ -221,9 +228,90 @@ class CppConfigurationProvider implements vscode.DebugConfigurationProvider {
}
}
}
// if config or type is not specified, return null to trigger VS Code to open a configuration file https://github.com/Microsoft/vscode/issues/54213
// if config or type is not specified, return null to trigger VS Code to open a configuration file https://github.com/Microsoft/vscode/issues/54213
return config && config.type ? config : null;
}
private resolveEnvFile(config: vscode.DebugConfiguration, folder: vscode.WorkspaceFolder): void {
if (config.envFile) {
// replace ${env:???} variables
let envFilePath: string = util.resolveVariables(config.envFile, null);
try {
if (folder && folder.uri && folder.uri.fsPath) {
// Try to replace ${workspaceFolder} or ${workspaceRoot}
envFilePath = envFilePath.replace(/(\${workspaceFolder}|\${workspaceRoot})/g, folder.uri.fsPath);
}
const parsedFile: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromFile(envFilePath, config["environment"]);
// show error message if single lines cannot get parsed
if (parsedFile.Warning) {
CppConfigurationProvider.showFileWarningAsync(parsedFile.Warning, config.envFile);
}
config.environment = parsedFile.Env;
delete config.envFile;
} catch (e) {
throw new Error(`Failed to use envFile. Reason: ${e.message}`);
}
}
}
private resolveSourceFileMapVariables(config: vscode.DebugConfiguration): void {
let messages: string[] = [];
if (config.sourceFileMap) {
for (const sourceFileMapSource of Object.keys(config.sourceFileMap)) {
let message: string = "";
const sourceFileMapTarget: string = config.sourceFileMap[sourceFileMapSource];
// TODO: pass config.environment as 'additionalEnvironment' to resolveVariables when it is { key: value } instead of { "key": key, "value": value }
const newSourceFileMapSource: string = util.resolveVariables(sourceFileMapSource, null);
const newSourceFileMapTarget: string = util.resolveVariables(sourceFileMapTarget, null);
let source: string = sourceFileMapSource;
let target: string = sourceFileMapTarget;
if (sourceFileMapSource !== newSourceFileMapSource) {
message = `\tReplacing sourcePath '${sourceFileMapSource}' with '${newSourceFileMapSource}'.`;
delete config.sourceFileMap[sourceFileMapSource];
source = newSourceFileMapSource;
}
if (sourceFileMapTarget !== newSourceFileMapTarget) {
// Add a space if source was changed, else just tab the target message.
message += (message ? ' ' : '\t');
message += `Replacing targetPath '${sourceFileMapTarget}' with '${newSourceFileMapTarget}'.`;
target = newSourceFileMapTarget;
}
if (message) {
config.sourceFileMap[source] = target;
messages.push(message);
}
}
if (messages.length > 0) {
logger.getOutputChannel().appendLine("Resolving variables in sourceFileMap...");
messages.forEach((message) => {
logger.getOutputChannel().appendLine(message);
});
logger.showOutputChannel();
}
}
}
private static async showFileWarningAsync(message: string, fileName: string) : Promise<void> {
const openItem: vscode.MessageItem = { title: 'Open envFile' };
let result: vscode.MessageItem = await vscode.window.showWarningMessage(message, openItem);
if (result && result.title === openItem.title) {
let doc: vscode.TextDocument = await vscode.workspace.openTextDocument(fileName);
if (doc) {
vscode.window.showTextDocument(doc);
}
}
}
}
export class CppVsDbgConfigurationProvider extends CppConfigurationProvider {
@@ -378,10 +466,10 @@ export class ConfigurationSnippetProvider implements vscode.CompletionItemProvid
items = [];
// Make a copy of each snippet since we are adding a comma to the end of the insertText.
this.snippets.forEach((item) => items.push(Object.assign({}, item)));
this.snippets.forEach((item) => items.push({...item}));
items.map((item) => {
item.insertText = item.insertText + ','; // Add comma
item.insertText = item.insertText + ','; // Add comma
});
}
+3 -3
View File
@@ -40,7 +40,7 @@ function createLaunchString(name: string, type: string, executable: string): str
"stopAtEntry": false,
"cwd": "$\{workspaceFolder\}",
"environment": [],
"externalConsole": true
"externalConsole": false
`;
}
@@ -108,7 +108,7 @@ export class MIConfigurations extends Configuration {
let body: string = formatString(`{
\t${indentJsonString(createLaunchString(name, this.miDebugger, this.executable))},
\t"MIMode": "${this.MIMode}"{0}{1}
}`, [this.miDebugger === "cppdbg" && os.platform() === "win32" ? `,${os.EOL}\t"miDebuggerPath": "/path/to/gdb"` : "",
}`, [this.miDebugger === "cppdbg" && os.platform() === "win32" ? `,${os.EOL}\t"miDebuggerPath": "/path/to/gdb"` : "",
this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalProperties)}` : ""]);
return {
@@ -123,7 +123,7 @@ this.additionalProperties ? `,${os.EOL}\t${indentJsonString(this.additionalPrope
public GetAttachConfiguration(): IConfigurationSnippet {
let name: string = `(${this.MIMode}) Attach`;
let body: string = formatString(`{
let body: string = formatString(`{
\t${indentJsonString(createAttachString(name, this.miDebugger, this.executable))},
\t"MIMode": "${this.MIMode}"{0}{1}
}`, [this.miDebugger === "cppdbg" && os.platform() === "win32" ? `,${os.EOL}\t"miDebuggerPath": "/path/to/gdb"` : "",
@@ -71,4 +71,4 @@ export class CppvsdbgDebugAdapterDescriptorFactory extends AbstractDebugAdapterD
});
}
}
}
}
+3 -3
View File
@@ -53,7 +53,7 @@ export function initialize(context: vscode.ExtensionContext): void {
vscode.window.showErrorMessage('Cannot build and debug because the active file is not a C or C++ source file.');
return Promise.resolve();
}
let configs: vscode.DebugConfiguration[] = (await provider.provideDebugConfigurations(folder)).filter(config => {
return config.name.indexOf(buildAndDebugActiveFileStr()) !== -1;
});
@@ -75,7 +75,7 @@ export function initialize(context: vscode.ExtensionContext): void {
return {label: config.name, configuration: config};
});
vscode.window.showQuickPick(items, {placeHolder: (items.length === 0 ? "No compiler found" : "Select a compiler" )}).then(async selection => {
vscode.window.showQuickPick(items, {placeHolder: (items.length === 0 ? "No compiler found" : "Select a compiler")}).then(async selection => {
if (!selection) {
return; // User canceled it.
}
@@ -140,4 +140,4 @@ export function initialize(context: vscode.ExtensionContext): void {
export function dispose(): void {
disposables.forEach(d => d.dispose());
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ import * as os from 'os';
import { AttachItemsProvider } from './attachToProcess';
import { AttachItem } from './attachQuickPick';
class Process {
export class Process {
constructor(public name: string, public pid: string, public commandLine: string) { }
public toAttachItem(): AttachItem {
+3 -3
View File
@@ -34,8 +34,8 @@ export class ArchitectureReplacer {
return replacedPipeProgram;
}
// Checks to see if the folder name is in the path using both win and unix style path seperators.
// Returns the path seperator it detected if the folder is in the path.
// Checks to see if the folder name is in the path using both win and unix style path separators.
// Returns the path separator it detected if the folder is in the path.
// Or else it returns empty string to indicate it did not find it in the path.
public static checkForFolderInPath(path: string, folder: string): string {
if (path.indexOf(`/${folder}/`) >= 0) {
@@ -46,4 +46,4 @@ export class ArchitectureReplacer {
return "";
}
}
}
File diff suppressed because it is too large Load Diff
@@ -99,7 +99,7 @@ export class ClientCollection {
* creates a new client to replace one that crashed.
*/
public replace(client: cpptools.Client, transferFileOwnership: boolean): cpptools.Client {
let key: string = undefined;
let key: string;
for (let pair of this.languageClients) {
if (pair[1] === client) {
key = pair[0];
@@ -211,4 +211,4 @@ export class ClientCollection {
this.languageClients.clear();
return Promise.all(promises).then(() => undefined);
}
}
}
@@ -0,0 +1,657 @@
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved.
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
import * as path from 'path';
import * as vscode from 'vscode';
import * as util from '../common';
import { CppSettings, OtherSettings, TextMateRule, TextMateRuleSettings } from './settings';
import * as jsonc from 'jsonc-parser';
import * as plist from 'plist';
export enum TokenKind {
// These need to match the token_kind enum in the server
// Semantic tokens
Macro,
Enumerator,
GlobalVariable,
LocalVariable,
Parameter,
Type,
RefType,
ValueType,
Function,
MemberFunction,
MemberField,
StaticMemberFunction,
StaticMemberField,
Property,
Event,
ClassTemplate,
GenericType,
FunctionTemplate,
Namespace,
Label,
UdlRaw,
UdlNumber,
UdlString,
OperatorFunction,
MemberOperator,
NewDelete,
Count
}
interface VersionedEdits {
editVersion: number;
changes: readonly vscode.TextDocumentContentChangeEvent[];
}
class ThemeStyle {
foreground: string;
background: string;
fontStyle: string;
}
export class ColorizationSettings {
private uri: vscode.Uri;
private pendingTask: util.BlockingTask<any>;
private editorBackground: string;
public themeStyleCMap: ThemeStyle[] = [];
public themeStyleCppMap: ThemeStyle[] = [];
private static readonly scopeToTokenColorNameMap = new Map<string, string>([
["comment", "comments"],
["string", "strings"],
["keyword.operator", "keywords"],
["keyword.control", "keywords"],
["constant.numeric", "numbers"],
["entity.name.type", "types"],
["entity.name.class", "types"],
["entity.name.function", "functions"],
["variable", "variables"]
]);
constructor(uri: vscode.Uri) {
this.uri = uri;
this.reload();
}
// Given a TextMate rule 'settings' node, update a ThemeStyle to include any color or style information
private updateStyleFromTextMateRuleSettings(baseStyle: ThemeStyle, textMateRuleSettings: TextMateRuleSettings): void {
if (textMateRuleSettings.foreground) {
baseStyle.foreground = textMateRuleSettings.foreground;
}
if (textMateRuleSettings.background && textMateRuleSettings.background.toUpperCase() !== this.editorBackground.toUpperCase()) {
baseStyle.background = textMateRuleSettings.background;
}
// Any (even empty) string for fontStyle removes inherited value
if (textMateRuleSettings.fontStyle) {
baseStyle.fontStyle = textMateRuleSettings.fontStyle;
} else if (textMateRuleSettings.fontStyle === "") {
baseStyle.fontStyle = undefined;
}
}
// If the scope can be found in a set of TextMate rules, apply it to both C and Cpp ThemeStyle's
private findThemeStyleForScope(baseCStyle: ThemeStyle, baseCppStyle: ThemeStyle, scope: string, textMateRules: TextMateRule[]): void {
if (textMateRules) {
let match: TextMateRule = textMateRules.find(e => e.settings && (e.scope === scope || ((e.scope instanceof Array) && e.scope.indexOf(scope) > -1)));
if (match) {
if (baseCStyle) {
this.updateStyleFromTextMateRuleSettings(baseCStyle, match.settings);
}
if (baseCppStyle) {
this.updateStyleFromTextMateRuleSettings(baseCppStyle, match.settings);
}
}
match = textMateRules.find(e => e.settings && (e.scope === "source " + scope || ((e.scope instanceof Array) && e.scope.indexOf("source " + scope) > -1)));
if (match) {
if (baseCStyle) {
this.updateStyleFromTextMateRuleSettings(baseCStyle, match.settings);
}
if (baseCppStyle) {
this.updateStyleFromTextMateRuleSettings(baseCppStyle, match.settings);
}
}
if (baseCStyle) {
match = textMateRules.find(e => e.settings && (e.scope === "source.c " + scope || ((e.scope instanceof Array) && e.scope.indexOf("source.c " + scope) > -1)));
if (match) {
this.updateStyleFromTextMateRuleSettings(baseCStyle, match.settings);
}
}
if (baseCppStyle) {
match = textMateRules.find(e => e.settings && (e.scope === "source.cpp " + scope || ((e.scope instanceof Array) && e.scope.indexOf("source.cpp " + scope) > -1)));
if (match) {
this.updateStyleFromTextMateRuleSettings(baseCppStyle, match.settings);
}
}
}
}
// For a specific scope cascase all potential sources of style information to create a final ThemeStyle
private calculateThemeStyleForScope(baseCStyle: ThemeStyle, baseCppStyle: ThemeStyle, scope: string, themeName: string, themeTextMateRules: TextMateRule[][]): void {
// Search for settings with this scope in current theme
themeTextMateRules.forEach((rules) => {
this.findThemeStyleForScope(baseCStyle, baseCppStyle, scope, rules);
});
let otherSettings: OtherSettings = new OtherSettings(this.uri);
// Next in priority would be a global user override of token color of the equivilent scope
let colorTokenName: string | undefined = ColorizationSettings.scopeToTokenColorNameMap.get(scope);
if (colorTokenName) {
let settingValue: string = otherSettings.getCustomColorToken(colorTokenName);
if (settingValue) {
if (baseCStyle) {
baseCStyle.foreground = settingValue;
}
if (baseCppStyle) {
baseCppStyle.foreground = settingValue;
}
}
}
// Next in priority would be a global user override of this scope in textMateRules
this.findThemeStyleForScope(baseCStyle, baseCppStyle, scope, otherSettings.customTextMateRules);
// Next in priority would be a theme-specific user override of token color of the equivilent scope
if (colorTokenName) {
let settingValue: string = otherSettings.getCustomThemeSpecificColorToken(colorTokenName, themeName);
if (settingValue) {
if (baseCStyle) {
baseCStyle.foreground = settingValue;
}
if (baseCppStyle) {
baseCppStyle.foreground = settingValue;
}
}
}
// Next in priority would be a theme-specific user override of this scope in textMateRules
let textMateRules: TextMateRule[] = otherSettings.getCustomThemeSpecificTextMateRules(themeName);
this.findThemeStyleForScope(baseCStyle, baseCppStyle, scope, textMateRules);
}
// For each level of the scope, look of style information
private calculateStyleForToken(tokenKind: TokenKind, scope: string, themeName: string, themeTextMateRules: TextMateRule[][]): void {
// Try scopes, from most general to most specific, apply style in cascading manner
let parts: string[] = scope.split(".");
let accumulatedScope: string = "";
for (let i: number = 0; i < parts.length; i++) {
accumulatedScope += parts[i];
this.calculateThemeStyleForScope(this.themeStyleCMap[tokenKind], this.themeStyleCppMap[tokenKind], accumulatedScope, themeName, themeTextMateRules);
this.calculateThemeStyleForScope(this.themeStyleCMap[tokenKind], null, accumulatedScope + ".c", themeName, themeTextMateRules);
this.calculateThemeStyleForScope(null, this.themeStyleCppMap[tokenKind], accumulatedScope + ".cpp", themeName, themeTextMateRules);
accumulatedScope += ".";
}
}
public syncWithLoadingSettings(f: () => any): void {
this.pendingTask = new util.BlockingTask<void>(f, this.pendingTask);
}
public updateStyles(themeName: string, defaultStyle: ThemeStyle, textMateRules: TextMateRule[][]): void {
this.themeStyleCMap = new Array<ThemeStyle>(TokenKind.Count);
this.themeStyleCppMap = new Array<ThemeStyle>(TokenKind.Count);
// Populate with unique objects, as they will be individual modified in place
for (let i: number = 0; i < TokenKind.Count; i++) {
this.themeStyleCMap[i] = {...defaultStyle};
this.themeStyleCppMap[i] = {...defaultStyle};
}
this.calculateStyleForToken(TokenKind.Macro, "entity.name.function.preprocessor", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.Enumerator, "variable.other.enummember", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.GlobalVariable, "variable.other.global", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.LocalVariable, "variable.other.local", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.Parameter, "variable.parameter", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.Type, "entity.name.type.class", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.RefType, "entity.name.type.class.reference", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.ValueType, "entity.name.type.class.value", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.Function, "entity.name.function", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.MemberFunction, "entity.name.function.member", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.MemberField, "variable.other.property", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.StaticMemberFunction, "entity.name.function.member.static", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.StaticMemberField, "variable.other.property.static", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.Property, "variable.other.property.cli", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.Event, "variable.other.event", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.ClassTemplate, "entity.name.type.class.templated", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.GenericType, "entity.name.type.class.generic", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.FunctionTemplate, "entity.name.function.templated", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.Namespace, "entity.name.namespace", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.Label, "entity.name.label", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.UdlRaw, "entity.name.operator.custom-literal", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.UdlNumber, "entity.name.operator.custom-literal.number", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.UdlString, "entity.name.operator.custom-literal.string", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.OperatorFunction, "entity.name.function.operator", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.MemberOperator, "entity.name.function.operator.member", themeName, textMateRules);
this.calculateStyleForToken(TokenKind.NewDelete, "keyword.operator.new", themeName, textMateRules);
}
public async loadTheme(themePath: string, defaultStyle: ThemeStyle): Promise<TextMateRule[][]> {
let rules: TextMateRule[][] = [];
if (await util.checkFileExists(themePath)) {
let themeContentText: string = await util.readFileText(themePath);
let themeContent: any;
let textMateRules: TextMateRule[];
if (themePath.endsWith("tmTheme")) {
themeContent = plist.parse(themeContentText);
if (themeContent) {
textMateRules = themeContent.settings;
}
} else {
themeContent = jsonc.parse(themeContentText);
if (themeContent) {
textMateRules = themeContent.tokenColors;
if (themeContent.include) {
// parse included theme file
let includedThemePath: string = path.join(path.dirname(themePath), themeContent.include);
rules = await this.loadTheme(includedThemePath, defaultStyle);
}
if (themeContent.colors && themeContent.colors["editor.background"]) {
this.editorBackground = themeContent.colors["editor.background"];
}
}
}
if (textMateRules) {
// Convert comma delimited scopes into an array
textMateRules.forEach(e => {
if (e.scope && e.scope.includes(',')) {
e.scope = e.scope.split(',').map((s: string) => s.trim());
}
});
let scopelessSetting: any = textMateRules.find(e => e.settings && !e.scope);
if (scopelessSetting) {
if (scopelessSetting.settings.background) {
this.editorBackground = scopelessSetting.settings.background;
}
this.updateStyleFromTextMateRuleSettings(defaultStyle, scopelessSetting.settings);
}
rules.push(textMateRules);
}
}
return rules;
}
public reload(): void {
let f: () => void = async () => {
let otherSettings: OtherSettings = new OtherSettings(this.uri);
let themeName: string = otherSettings.colorTheme;
// Enumerate through all extensions, looking for this theme. (Themes are implemented as extensions - even the default ones)
// Open each package.json to check for a theme path
for (let i: number = 0; i < vscode.extensions.all.length; i++) {
let extensionPath: string = vscode.extensions.all[i].extensionPath;
let extensionPackageJsonPath: string = path.join(extensionPath, "package.json");
if (!await util.checkFileExists(extensionPackageJsonPath)) {
continue;
}
let packageJsonText: string = await util.readFileText(extensionPackageJsonPath);
let packageJson: any = jsonc.parse(packageJsonText);
if (packageJson.contributes && packageJson.contributes.themes) {
let foundTheme: any = packageJson.contributes.themes.find(e => e.id === themeName || e.label === themeName);
if (foundTheme) {
let themeRelativePath: string = foundTheme.path;
let themeFullPath: string = path.join(extensionPath, themeRelativePath);
let defaultStyle: ThemeStyle = new ThemeStyle();
let rulesSet: TextMateRule[][] = await this.loadTheme(themeFullPath, defaultStyle);
this.updateStyles(themeName, defaultStyle, rulesSet);
return;
}
}
}
};
this.syncWithLoadingSettings(f);
}
public static createDecorationFromThemeStyle(themeStyle: ThemeStyle): vscode.TextEditorDecorationType {
if (themeStyle && (themeStyle.foreground || themeStyle.background || themeStyle.fontStyle)) {
let options: vscode.DecorationRenderOptions = {};
options.rangeBehavior = vscode.DecorationRangeBehavior.OpenOpen;
if (themeStyle.foreground) {
options.color = themeStyle.foreground;
}
if (themeStyle.background) {
options.backgroundColor = themeStyle.background;
}
if (themeStyle.fontStyle) {
let parts: string[] = themeStyle.fontStyle.split(" ");
parts.forEach((part) => {
switch (part) {
case "italic":
options.fontStyle = "italic";
break;
case "bold":
options.fontWeight = "bold";
break;
case "underline":
options.textDecoration = "underline";
break;
default:
break;
}
});
}
return vscode.window.createTextEditorDecorationType(options);
}
return null;
}
}
export class ColorizationState {
private uri: vscode.Uri;
private colorizationSettings: ColorizationSettings;
private decorations: vscode.TextEditorDecorationType[] = new Array<vscode.TextEditorDecorationType>(TokenKind.Count);
private semanticRanges: vscode.Range[][] = new Array<vscode.Range[]>(TokenKind.Count);
private inactiveDecoration: vscode.TextEditorDecorationType = null;
private inactiveRanges: vscode.Range[] = [];
private versionedEdits: VersionedEdits[] = [];
private currentSemanticVersion: number = 0;
private lastReceivedSemanticVersion: number = 0;
public constructor(uri: vscode.Uri, colorizationSettings: ColorizationSettings) {
this.uri = uri;
this.colorizationSettings = colorizationSettings;
}
private createColorizationDecorations(isCpp: boolean): void {
let settings: CppSettings = new CppSettings(this.uri);
if (settings.enhancedColorization) {
// Create new decorators
// The first decorator created takes precedence, so these need to be created in reverse order
for (let i: number = TokenKind.Count; i > 0;) {
i--;
let themeStyleMap: any;
if (isCpp) {
themeStyleMap = this.colorizationSettings.themeStyleCppMap;
} else {
themeStyleMap = this.colorizationSettings.themeStyleCMap;
}
this.decorations[i] = ColorizationSettings.createDecorationFromThemeStyle(themeStyleMap[i]);
}
}
if (settings.dimInactiveRegions) {
this.inactiveDecoration = vscode.window.createTextEditorDecorationType({
opacity: settings.inactiveRegionOpacity.toString(),
backgroundColor: settings.inactiveRegionBackgroundColor,
color: settings.inactiveRegionForegroundColor,
rangeBehavior: vscode.DecorationRangeBehavior.OpenOpen
});
}
}
private disposeColorizationDecorations(): void {
// Dispose of all old decorations
if (this.inactiveDecoration) {
this.inactiveDecoration.dispose();
this.inactiveDecoration = null;
}
for (let i: number = 0; i < TokenKind.Count; i++) {
if (this.decorations[i]) {
this.decorations[i].dispose();
this.decorations[i] = null;
}
}
}
public dispose(): void {
this.disposeColorizationDecorations();
}
private refreshInner(e: vscode.TextEditor): void {
let settings: CppSettings = new CppSettings(this.uri);
if (settings.enhancedColorization) {
for (let i: number = 0; i < TokenKind.Count; i++) {
if (this.decorations[i]) {
let ranges: vscode.Range[] = this.semanticRanges[i];
if (ranges && ranges.length > 0) {
e.setDecorations(this.decorations[i], ranges);
}
}
}
}
// Normally, decorators are honored in the order in which they were created, not the
// order in which they were applied. Decorators with opacity appear to be handled
// differently, in that the opacity is applied to overlapping decorators even if
// created afterwards.
if (settings.dimInactiveRegions && this.inactiveDecoration && this.inactiveRanges) {
e.setDecorations(this.inactiveDecoration, this.inactiveRanges);
}
}
public refresh(e: vscode.TextEditor): void {
this.applyEdits();
let f: () => void = async () => {
this.refreshInner(e);
};
this.colorizationSettings.syncWithLoadingSettings(f);
}
public onSettingsChanged(uri: vscode.Uri): void {
let f: () => void = async () => {
this.applyEdits();
this.disposeColorizationDecorations();
let isCpp: boolean = util.isEditorFileCpp(uri.toString());
this.createColorizationDecorations(isCpp);
let editors: vscode.TextEditor[] = vscode.window.visibleTextEditors.filter(e => e.document.uri === uri);
for (let e of editors) {
this.refreshInner(e);
}
};
this.colorizationSettings.syncWithLoadingSettings(f);
}
// Utility function to convert a string and a start Position into a Range
private textToRange(text: string, startPosition: vscode.Position): vscode.Range {
let parts: string[] = text.split("\n");
let addedLines: number = parts.length - 1;
let newStartLine: number = startPosition.line;
let newStartCharacter: number = startPosition.character;
let newEndLine: number = newStartLine + addedLines;
let newEndCharacter: number = parts[parts.length - 1].length;
if (newStartLine === newEndLine) {
newEndCharacter += newStartCharacter;
}
return new vscode.Range(newStartLine, newStartCharacter, newEndLine, newEndCharacter);
}
// Utility function to shift a range back after removing content before it
private shiftRangeAfterRemove(range: vscode.Range, removeStartPosition: vscode.Position, removeEndPosition: vscode.Position): vscode.Range {
let lineDelta: number = removeStartPosition.line - removeEndPosition.line;
let startCharacterDelta: number = 0;
let endCharacterDelta: number = 0;
if (range.start.line === removeEndPosition.line) {
startCharacterDelta = removeStartPosition.character - removeEndPosition.character;
if (range.end.line === removeEndPosition.line) {
endCharacterDelta = startCharacterDelta;
}
}
let newStart: vscode.Position = range.start.translate(lineDelta, startCharacterDelta);
let newEnd: vscode.Position = range.end.translate(lineDelta, endCharacterDelta);
return new vscode.Range(newStart, newEnd);
}
// Utility function to shift a range forward after inserting content before it
private shiftRangeAfterInsert(range: vscode.Range, insertStartPosition: vscode.Position, insertEndPosition: vscode.Position): vscode.Range {
let addedLines: number = insertEndPosition.line - insertStartPosition.line;
let newStartLine: number = range.start.line + addedLines;
let newEndLine: number = range.end.line + addedLines;
let newStartCharacter: number = range.start.character;
let newEndCharacter: number = range.end.character;
// If starts on the same line as replacement ended
if (insertEndPosition.line === newStartLine) {
let endOffsetLength: number = insertEndPosition.character;
// If insertRange starts and ends on the same line, only offset by it's length
if (insertEndPosition.line === insertStartPosition.line) {
endOffsetLength -= insertStartPosition.character;
}
newStartCharacter += endOffsetLength;
if (insertEndPosition.line === newEndLine) {
newEndCharacter += endOffsetLength;
}
}
return new vscode.Range(newStartLine, newStartCharacter, newEndLine, newEndCharacter);
}
// Utility function to adjust a range to account for an insert and/or replace
private fixRange(range: vscode.Range, removeInsertStartPosition: vscode.Position, removeEndPosition: vscode.Position, insertEndPosition: vscode.Position): vscode.Range {
// If the replace/insert starts after this range ends, no adjustment is needed.
if (removeInsertStartPosition.isAfterOrEqual(range.end)) {
return range;
}
// Else, replace/insert range starts before this range ends.
// If replace/insert starts before/where this range starts, we don't need to extend the existing range, but need to shift it
if (removeInsertStartPosition.isBeforeOrEqual(range.start)) {
// If replace consumes the entire range, remove it
if (removeEndPosition.isAfterOrEqual(range.end)) {
return null;
}
// If replace ends within this range, we need to trim it before we shift it
let newRange: vscode.Range;
if (removeEndPosition.isAfterOrEqual(range.start)) {
newRange = new vscode.Range(removeEndPosition, range.end);
} else {
newRange = range;
}
// Else, if replace ends before this range starts, we just need to shift it.
newRange = this.shiftRangeAfterRemove(newRange, removeInsertStartPosition, removeEndPosition);
return this.shiftRangeAfterInsert(newRange, removeInsertStartPosition, insertEndPosition);
}
// Else, if replace/insert starts within (not before or after) range, extend it.
// If there replace/insert overlaps past the end of the original range, just extend existing range to the insert end position
if (removeEndPosition.isAfterOrEqual(range.end)) {
return new vscode.Range(range.start.line, range.start.character, insertEndPosition.line, insertEndPosition.character);
}
// Else, range has some left over at the end, which needs to be shifted after insertEndPosition.
// If the trailing segment is on the last line replace, we just need to extend by the remaining number of characters
if (removeEndPosition.line === range.end.line) {
return new vscode.Range(range.start.line, range.start.character, insertEndPosition.line, insertEndPosition.character + (range.end.character - removeEndPosition.character));
}
// Else, the trailing segment ends on another line, so the character position should remain the same. Just adjust based on added/removed lined.
let removedLines: number = removeEndPosition.line - removeInsertStartPosition.line;
let addedLines: number = insertEndPosition.line - removeInsertStartPosition.line;
let deltaLines: number = addedLines - removedLines;
return new vscode.Range(range.start.line, range.start.character, range.end.line + deltaLines, range.end.character);
}
private fixRanges(originalRanges: vscode.Range[], changes: readonly vscode.TextDocumentContentChangeEvent[]): vscode.Range[] {
// outer loop needs to be the versioned edits, then changes within that edit, then ranges
let ranges: vscode.Range[] = originalRanges;
if (ranges && ranges.length > 0) {
changes.forEach((change) => {
let newRanges: vscode.Range[] = [];
let insertRange: vscode.Range = this.textToRange(change.text, change.range.start);
for (let i: number = 0; i < ranges.length; i++) {
let newRange: vscode.Range = this.fixRange(ranges[i], change.range.start, change.range.end, insertRange.end);
if (newRange !== null) {
newRanges.push(newRange);
}
}
ranges = newRanges;
});
}
return ranges;
}
// Add edits to be applied when/if cached tokens need to be reapplied.
public addEdits(changes: readonly vscode.TextDocumentContentChangeEvent[], editVersion: number): void {
let edits: VersionedEdits = {
editVersion: editVersion,
changes: changes
};
this.versionedEdits.push(edits);
}
// Apply any pending edits to the currently cached tokens
private applyEdits() : void {
this.versionedEdits.forEach((edit) => {
if (edit.editVersion > this.currentSemanticVersion) {
for (let i: number = 0; i < TokenKind.Count; i++) {
this.semanticRanges[i] = this.fixRanges(this.semanticRanges[i], edit.changes);
}
this.inactiveRanges = this.fixRanges(this.inactiveRanges, edit.changes);
this.currentSemanticVersion = edit.editVersion;
}
});
}
// Remove any edits from the list if we will never receive tokens that old.
private purgeOldVersionedEdits(): void {
let minVersion: number = this.lastReceivedSemanticVersion;
let index: number = this.versionedEdits.findIndex((edit) => edit.editVersion > minVersion);
if (index === -1) {
this.versionedEdits = [];
} else if (index > 0) {
this.versionedEdits = this.versionedEdits.slice(index);
}
}
private updateColorizationRanges(uri: string): void {
let f: () => void = async () => {
this.applyEdits();
this.purgeOldVersionedEdits();
// The only way to un-apply decorators is to dispose them.
// If we dispose old decorators before applying new decorators, we see a flicker on Mac,
// likely due to a race with UI updates. Here we set aside the existing decorators to be
// disposed of after the new decorators have been applied, so there is not a gap
// in which decorators are not applied.
let oldInactiveDecoration: vscode.TextEditorDecorationType = this.inactiveDecoration;
let oldDecorations: vscode.TextEditorDecorationType[] = this.decorations;
this.inactiveDecoration = null;
this.decorations = new Array<vscode.TextEditorDecorationType>(TokenKind.Count);
let isCpp: boolean = util.isEditorFileCpp(uri);
this.createColorizationDecorations(isCpp);
// Apply the decorations to all *visible* text editors
let editors: vscode.TextEditor[] = vscode.window.visibleTextEditors.filter(e => e.document.uri.toString() === uri);
for (let e of editors) {
this.refreshInner(e);
}
// Dispose of the old decorators only after the new ones have been applied.
if (oldInactiveDecoration) {
oldInactiveDecoration.dispose();
}
if (oldDecorations) {
for (let i: number = 0; i < TokenKind.Count; i++) {
if (oldDecorations[i]) {
oldDecorations[i].dispose();
}
}
}
};
this.colorizationSettings.syncWithLoadingSettings(f);
}
public updateSemantic(uri: string, semanticRanges: vscode.Range[][], inactiveRanges: vscode.Range[], editVersion: number): void {
this.inactiveRanges = inactiveRanges;
for (let i: number = 0; i < TokenKind.Count; i++) {
this.semanticRanges[i] = semanticRanges[i];
}
this.currentSemanticVersion = editVersion;
this.lastReceivedSemanticVersion = editVersion;
this.updateColorizationRanges(uri);
}
}
+460 -219
View File
@@ -13,7 +13,7 @@ import { PersistentFolderState } from './persistentState';
import { CppSettings, OtherSettings } from './settings';
import { ABTestSettings, getABTestSettings } from '../abTesting';
import { getCustomConfigProviders } from './customProviders';
import { SettingsPanel, ViewStateEvent } from './settingsPanel';
import { SettingsPanel } from './settingsPanel';
import * as os from 'os';
import escapeStringRegExp = require('escape-string-regexp');
const configVersion: number = 4;
@@ -50,6 +50,7 @@ export interface ConfigurationJson {
export interface Configuration {
name: string;
compilerPath?: string;
compilerArgs?: string[];
knownCompilers?: KnownCompiler[];
cStandard?: string;
cppStandard?: string;
@@ -64,6 +65,17 @@ export interface Configuration {
browse?: Browse;
}
export interface ConfigurationErrors {
compilerPath?: string;
includePath?: string;
intelliSenseMode?: string;
macFrameworkPath?: string;
forcedInclude?: string;
compileCommands?: string;
browsePath?: string;
databaseFilename?: string;
}
export interface Browse {
path?: string[];
limitSymbolsToIncludedHeaders?: boolean | string;
@@ -77,6 +89,7 @@ export interface KnownCompiler {
export interface CompilerDefaults {
compilerPath: string;
compilerArgs: string[];
knownCompilers: KnownCompiler[];
cStandard: string;
cppStandard: string;
@@ -137,7 +150,6 @@ export class CppProperties {
public get Configurations(): Configuration[] { return this.configurationJson ? this.configurationJson.configurations : null; }
public get CurrentConfigurationIndex(): number { return this.currentConfigurationIndex.Value; }
public get CurrentConfiguration(): Configuration { return this.Configurations ? this.Configurations[this.CurrentConfigurationIndex] : null; }
public get CompilerPath(): string { return this.CurrentConfiguration ? this.CurrentConfiguration.compilerPath : null; }
public get KnownCompiler(): KnownCompiler[] { return this.knownCompilers; }
public get CurrentConfigurationProvider(): string|null {
@@ -167,13 +179,14 @@ export class CppProperties {
// defaultPaths is only used when there isn't a c_cpp_properties.json, but we don't send the configuration changed event
// to the language server until the default include paths and frameworks have been sent.
let configFilePath: string = path.join(this.configFolder, "c_cpp_properties.json");
if (fs.existsSync(configFilePath)) {
if (this.rootUri !== null && fs.existsSync(configFilePath)) {
this.propertiesFile = vscode.Uri.file(configFilePath);
} else {
this.propertiesFile = null;
}
this.configFileWatcher = vscode.workspace.createFileSystemWatcher(path.join(this.configFolder, this.configurationGlobPattern));
let settingsPath: string = path.join(this.configFolder, this.configurationGlobPattern);
this.configFileWatcher = vscode.workspace.createFileSystemWatcher(settingsPath);
this.disposables.push(this.configFileWatcher);
this.configFileWatcher.onDidCreate((uri) => {
this.propertiesFile = uri;
@@ -187,7 +200,24 @@ export class CppProperties {
});
this.configFileWatcher.onDidChange(() => {
this.handleConfigurationChange();
// If the file is one of the textDocument's vscode is tracking, we need to wait for an
// onDidChangeTextDocument event, or we may get old/cached contents when we open it.
let alreadyTracking: boolean = false;
for (let i: number = 0; i < vscode.workspace.textDocuments.length; i++) {
if (vscode.workspace.textDocuments[i].uri.fsPath === settingsPath) {
alreadyTracking = true;
break;
}
}
if (!alreadyTracking) {
this.handleConfigurationChange();
}
});
vscode.workspace.onDidChangeTextDocument((e: vscode.TextDocumentChangeEvent) => {
if (e.document.uri.fsPath === settingsPath) {
this.handleConfigurationChange();
}
});
this.handleConfigurationChange();
@@ -203,20 +233,6 @@ export class CppProperties {
private onSelectionChanged(): void {
this.selectionChanged.fire(this.CurrentConfigurationIndex);
if (this.settingsPanel) {
this.ensurePropertiesFile().then(() => {
if (this.propertiesFile) {
// Clear out any modifications we may have made internally by parsing the json file
if (this.parsePropertiesFile()) {
// Update the UI with new selected configuration
this.settingsPanel.updateConfigUI(this.configurationJson.configurations[this.currentConfigurationIndex.Value]);
} else {
// Parse failed, open json file
vscode.workspace.openTextDocument(this.propertiesFile);
}
}
});
}
this.handleSquiggles();
}
@@ -247,53 +263,57 @@ export class CppProperties {
private applyDefaultIncludePathsAndFrameworks(): void {
if (this.configurationIncomplete && this.defaultIncludes && this.defaultFrameworks && this.vcpkgPathReady) {
let configuration: Configuration = this.CurrentConfiguration;
let settings: CppSettings = new CppSettings(this.rootUri);
let isUnset: (input: any) => boolean = (input: any) => {
this.applyDefaultConfigurationValues(configuration);
this.configurationIncomplete = false;
}
}
private applyDefaultConfigurationValues(configuration: Configuration): void {
let settings: CppSettings = new CppSettings(this.rootUri);
let isUnset: (input: any) => boolean = (input: any) => {
// default values for "default" config settings is null.
return input === null;
};
};
// Anything that has a vscode setting for it will be resolved in updateServerOnFolderSettingsChange.
// So if a property is currently unset, but has a vscode setting, don't set it yet, otherwise the linkage
// to the setting will be lost if this configuration is saved into a c_cpp_properties.json file.
// Anything that has a vscode setting for it will be resolved in updateServerOnFolderSettingsChange.
// So if a property is currently unset, but has a vscode setting, don't set it yet, otherwise the linkage
// to the setting will be lost if this configuration is saved into a c_cpp_properties.json file.
// Only add settings from the default compiler if user hasn't explicitly set the corresponding VS Code setting.
// Only add settings from the default compiler if user hasn't explicitly set the corresponding VS Code setting.
if (isUnset(settings.defaultIncludePath)) {
// We don't add system includes to the includePath anymore. The language server has this information.
let abTestSettings: ABTestSettings = getABTestSettings();
let rootFolder: string = abTestSettings.UseRecursiveIncludes ? "${workspaceFolder}/**" : "${workspaceFolder}";
configuration.includePath = [rootFolder].concat(this.vcpkgIncludes);
}
// browse.path is not set by default anymore. When it is not set, the includePath will be used instead.
if (isUnset(settings.defaultDefines)) {
configuration.defines = (process.platform === 'win32') ? ["_DEBUG", "UNICODE", "_UNICODE"] : [];
}
if (isUnset(settings.defaultMacFrameworkPath) && process.platform === 'darwin') {
configuration.macFrameworkPath = this.defaultFrameworks;
}
if (isUnset(settings.defaultWindowsSdkVersion) && this.defaultWindowsSdkVersion && process.platform === 'win32') {
configuration.windowsSdkVersion = this.defaultWindowsSdkVersion;
}
if (isUnset(settings.defaultCompilerPath) && this.defaultCompilerPath &&
isUnset(settings.defaultCompileCommands) && !configuration.compileCommands) {
// compile_commands.json already specifies a compiler. compilerPath overrides the compile_commands.json compiler so
// don't set a default when compileCommands is in use.
configuration.compilerPath = this.defaultCompilerPath;
}
if (this.knownCompilers) {
configuration.knownCompilers = this.knownCompilers;
}
if (isUnset(settings.defaultCStandard) && this.defaultCStandard) {
configuration.cStandard = this.defaultCStandard;
}
if (isUnset(settings.defaultCppStandard) && this.defaultCppStandard) {
configuration.cppStandard = this.defaultCppStandard;
}
if (isUnset(settings.defaultIntelliSenseMode)) {
configuration.intelliSenseMode = this.defaultIntelliSenseMode;
}
this.configurationIncomplete = false;
if (isUnset(settings.defaultIncludePath)) {
// We don't add system includes to the includePath anymore. The language server has this information.
let abTestSettings: ABTestSettings = getABTestSettings();
let rootFolder: string = abTestSettings.UseRecursiveIncludes ? "${workspaceFolder}/**" : "${workspaceFolder}";
configuration.includePath = [rootFolder].concat(this.vcpkgIncludes);
}
// browse.path is not set by default anymore. When it is not set, the includePath will be used instead.
if (isUnset(settings.defaultDefines)) {
configuration.defines = (process.platform === 'win32') ? ["_DEBUG", "UNICODE", "_UNICODE"] : [];
}
if (isUnset(settings.defaultMacFrameworkPath) && process.platform === 'darwin') {
configuration.macFrameworkPath = this.defaultFrameworks;
}
if (isUnset(settings.defaultWindowsSdkVersion) && this.defaultWindowsSdkVersion && process.platform === 'win32') {
configuration.windowsSdkVersion = this.defaultWindowsSdkVersion;
}
if (isUnset(settings.defaultCompilerPath) && this.defaultCompilerPath &&
isUnset(settings.defaultCompileCommands) && !configuration.compileCommands) {
// compile_commands.json already specifies a compiler. compilerPath overrides the compile_commands.json compiler so
// don't set a default when compileCommands is in use.
configuration.compilerPath = this.defaultCompilerPath;
}
if (this.knownCompilers) {
configuration.knownCompilers = this.knownCompilers;
}
if (isUnset(settings.defaultCStandard) && this.defaultCStandard) {
configuration.cStandard = this.defaultCStandard;
}
if (isUnset(settings.defaultCppStandard) && this.defaultCppStandard) {
configuration.cppStandard = this.defaultCppStandard;
}
if (isUnset(settings.defaultIntelliSenseMode)) {
configuration.intelliSenseMode = this.defaultIntelliSenseMode;
}
}
@@ -371,21 +391,26 @@ export class CppProperties {
}
}
private isCompilerIntelliSenseModeCompatible(): boolean {
private isCompilerIntelliSenseModeCompatible(configuration: Configuration): boolean {
// Check if intelliSenseMode and compilerPath are compatible
// cl.exe and msvc mode should be used together
// Ignore if compiler path is not set
if (this.CurrentConfiguration.compilerPath === undefined) {
// Ignore if compiler path is not set or intelliSenseMode is not set
if (configuration.compilerPath === undefined ||
configuration.compilerPath === "" ||
configuration.compilerPath === "${default}" ||
configuration.intelliSenseMode === undefined ||
configuration.intelliSenseMode === "" ||
configuration.intelliSenseMode === "${default}") {
return true;
}
let compilerPathAndArgs: util.CompilerPathAndArgs = util.extractCompilerPathAndArgs(this.CurrentConfiguration.compilerPath);
return compilerPathAndArgs.compilerPath.endsWith("cl.exe") === (this.CurrentConfiguration.intelliSenseMode === "msvc-x64");
let compilerPathAndArgs: util.CompilerPathAndArgs = util.extractCompilerPathAndArgs(configuration.compilerPath);
return (compilerPathAndArgs.compilerName === "cl.exe") === (configuration.intelliSenseMode === "msvc-x64" || configuration.intelliSenseMode === "msvc-x86");
}
public addToIncludePathCommand(path: string): void {
this.handleConfigurationEditCommand((document: vscode.TextDocument) => {
this.handleConfigurationEditCommand(() => {
telemetry.logLanguageServerEvent("addToIncludePath");
this.parsePropertiesFileAndHandleSquiggles(); // Clear out any modifications we may have made internally.
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
let config: Configuration = this.CurrentConfiguration;
if (config.includePath === undefined) {
config.includePath = ["${default}"];
@@ -393,14 +418,14 @@ export class CppProperties {
config.includePath.splice(config.includePath.length, 0, path);
this.writeToJson();
this.handleConfigurationChange();
});
}, null);
}
public updateCustomConfigurationProvider(providerId: string): Thenable<void> {
return new Promise<void>((resolve) => {
if (this.propertiesFile) {
this.handleConfigurationEditCommand((document: vscode.TextDocument) => {
this.parsePropertiesFileAndHandleSquiggles(); // Clear out any modifications we may have made internally.
this.handleConfigurationEditJSONCommand(() => {
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
let config: Configuration = this.CurrentConfiguration;
if (providerId) {
config.configurationProvider = providerId;
@@ -410,7 +435,7 @@ export class CppProperties {
this.writeToJson();
this.handleConfigurationChange();
resolve();
});
}, null);
} else {
let settings: CppSettings = new CppSettings(this.rootUri);
if (providerId) {
@@ -425,30 +450,23 @@ export class CppProperties {
}
public setCompileCommands(path: string): void {
this.handleConfigurationEditCommand((document: vscode.TextDocument) => {
this.parsePropertiesFileAndHandleSquiggles(); // Clear out any modifications we may have made internally.
this.handleConfigurationEditJSONCommand(() => {
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
let config: Configuration = this.CurrentConfiguration;
config.compileCommands = path;
this.writeToJson();
this.handleConfigurationChange();
});
}, null);
}
public select(index: number): Configuration {
if (index === this.configurationJson.configurations.length) {
this.handleConfigurationEditCommand(vscode.window.showTextDocument);
this.handleConfigurationEditUICommand(null, vscode.window.showTextDocument);
return;
}
// Before changing the current configuration index, save any edits from the UI.
if (this.settingsPanel) {
if (this.settingsPanel.isDirty()) {
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
// Get the changes from the UI and save to json file
let config: Configuration = this.settingsPanel.getLastValuesFromConfigUI();
this.configurationJson.configurations[this.currentConfigurationIndex.Value] = config;
this.writeToJson();
}
if (index === this.configurationJson.configurations.length + 1) {
this.handleConfigurationEditJSONCommand(null, vscode.window.showTextDocument);
return;
}
this.currentConfigurationIndex.Value = index;
@@ -527,6 +545,7 @@ export class CppProperties {
configuration.forcedInclude = this.updateConfiguration(configuration.forcedInclude, settings.defaultForcedInclude, env);
configuration.compileCommands = this.updateConfiguration(configuration.compileCommands, settings.defaultCompileCommands, env);
configuration.compilerPath = this.updateConfiguration(configuration.compilerPath, settings.defaultCompilerPath, env);
configuration.compilerArgs = this.updateConfiguration(configuration.compilerArgs, settings.defaultCompilerArgs, env);
configuration.cStandard = this.updateConfiguration(configuration.cStandard, settings.defaultCStandard, env);
configuration.cppStandard = this.updateConfiguration(configuration.cppStandard, settings.defaultCppStandard, env);
configuration.intelliSenseMode = this.updateConfiguration(configuration.intelliSenseMode, settings.defaultIntelliSenseMode, env);
@@ -542,9 +561,9 @@ export class CppProperties {
} else if (configuration.includePath) {
// If the user doesn't set browse.path, copy the includePath over. Make sure ${workspaceFolder} is in there though...
configuration.browse.path = configuration.includePath.slice(0);
if (-1 === configuration.includePath.findIndex((value: string, index: number) => {
return !!value.match(/^\$\{(workspaceRoot|workspaceFolder)\}(\\\*{0,2}|\/\*{0,2})?$/g);
})) {
if (configuration.includePath.findIndex((value: string, index: number) =>
!!value.match(/^\$\{(workspaceRoot|workspaceFolder)\}(\\\*{0,2}|\/\*{0,2})?$/g)) === -1
) {
configuration.browse.path.push("${workspaceFolder}");
}
}
@@ -569,8 +588,11 @@ export class CppProperties {
this.compileCommandFileWatchers = []; //reset it
let filePaths: Set<string> = new Set<string>();
this.configurationJson.configurations.forEach(c => {
if (c.compileCommands !== undefined && fs.existsSync(c.compileCommands)) {
filePaths.add(c.compileCommands);
if (c.compileCommands !== undefined) {
let fileSystemCompileCommandsPath : string = this.resolvePath(c.compileCommands, os.platform() === "win32");
if (fs.existsSync(fileSystemCompileCommandsPath)) {
filePaths.add(fileSystemCompileCommandsPath);
}
}
});
try {
@@ -587,76 +609,131 @@ export class CppProperties {
}
}
public handleConfigurationEditCommand(onSuccess: (document: vscode.TextDocument) => void): void {
public handleConfigurationEditCommand(onCreation: () => void, showDocument: (document: vscode.TextDocument) => void): void {
let otherSettings: OtherSettings = new OtherSettings(this.rootUri);
if (otherSettings.settingsEditor === "ui") {
this.handleConfigurationEditUICommand(onSuccess);
this.handleConfigurationEditUICommand(onCreation, showDocument);
} else {
this.handleConfigurationEditJSONCommand(onSuccess);
this.handleConfigurationEditJSONCommand(onCreation, showDocument);
}
}
public handleConfigurationEditJSONCommand(onSuccess: (document: vscode.TextDocument) => void): void {
public handleConfigurationEditJSONCommand(onCreation: () => void, showDocument: (document: vscode.TextDocument) => void): void {
this.ensurePropertiesFile().then(() => {
console.assert(this.propertiesFile);
if (onCreation) {
onCreation();
}
// Directly open the json file
vscode.workspace.openTextDocument(this.propertiesFile).then((document: vscode.TextDocument) => {
onSuccess(document);
if (showDocument) {
showDocument(document);
}
});
});
}
public handleConfigurationEditUICommand(onSuccess: (document: vscode.TextDocument) => void): void {
private ensureSettingsPanelInitlialized(): void {
if (this.settingsPanel === undefined) {
let settings: CppSettings = new CppSettings(this.rootUri);
this.settingsPanel = new SettingsPanel();
this.settingsPanel.setKnownCompilers(this.knownCompilers, settings.preferredPathSeparator);
this.settingsPanel.SettingsPanelActivated(() => this.onSettingsPanelActivated());
this.settingsPanel.ConfigValuesChanged(() => this.saveConfigurationUI());
this.settingsPanel.ConfigSelectionChanged(() => this.onConfigSelectionChanged());
this.settingsPanel.AddConfigRequested((e) => this.onAddConfigRequested(e));
this.disposables.push(this.settingsPanel);
}
}
public handleConfigurationEditUICommand(onCreation: () => void, showDocument: (document: vscode.TextDocument) => void): void {
this.ensurePropertiesFile().then(() => {
if (this.propertiesFile) {
if (onCreation) {
onCreation();
}
if (this.parsePropertiesFile()) {
// Parse successful, show UI
if (this.settingsPanel === undefined) {
this.settingsPanel = new SettingsPanel();
this.settingsPanel.SettingsPanelViewStateChanged((e) => this.onSettingsPanelViewStateChanged(e));
this.disposables.push(this.settingsPanel);
}
this.settingsPanel.createOrShow(this.configurationJson.configurations[this.currentConfigurationIndex.Value]);
this.ensureSettingsPanelInitlialized();
// Use the active configuration as the default selected configuration to load on UI editor
this.settingsPanel.selectedConfigIndex = this.currentConfigurationIndex.Value;
this.settingsPanel.createOrShow(this.ConfigurationNames,
this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex],
this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex));
} else {
// Parse failed, open json file
vscode.workspace.openTextDocument(this.propertiesFile).then((document: vscode.TextDocument) => {
onSuccess(document);
if (showDocument) {
showDocument(document);
}
});
}
}
});
}
private onSettingsPanelViewStateChanged(e: ViewStateEvent): void {
if (!e.isDirty && e.isActive && this.configurationJson) {
private onSettingsPanelActivated(): void {
if (this.configurationJson) {
this.ensurePropertiesFile().then(() => {
if (this.propertiesFile) {
if (this.parsePropertiesFile()) {
// The settings UI became visible or active.
// Ensure settingsPanel has copy of latest current configuration
this.settingsPanel.updateConfigUI(this.configurationJson.configurations[this.currentConfigurationIndex.Value]);
if (this.settingsPanel.selectedConfigIndex >= this.configurationJson.configurations.length) {
this.settingsPanel.selectedConfigIndex = this.currentConfigurationIndex.Value;
}
this.settingsPanel.updateConfigUI(this.ConfigurationNames,
this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex],
this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex));
} else {
// Parse failed, open json file
vscode.workspace.openTextDocument(this.propertiesFile);
}
}
});
} else if (e.isDirty) {
console.assert(this.configurationJson);
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
let config: Configuration = this.settingsPanel.getLastValuesFromConfigUI();
this.configurationJson.configurations[this.currentConfigurationIndex.Value] = config;
this.writeToJson();
}
}
private saveConfigurationUI(): void {
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
let config: Configuration = this.settingsPanel.getLastValuesFromConfigUI();
this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex] = config;
this.settingsPanel.updateErrors(this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex));
this.writeToJson();
}
private onConfigSelectionChanged(): void {
this.settingsPanel.updateConfigUI(this.ConfigurationNames,
this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex],
this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex));
}
private onAddConfigRequested(configName: string): void {
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
// Create default config and add to list of configurations
let newConfig: Configuration = { name: configName };
this.applyDefaultConfigurationValues(newConfig);
delete newConfig.knownCompilers;
this.configurationJson.configurations.push(newConfig);
// Update UI
this.settingsPanel.selectedConfigIndex = this.configurationJson.configurations.length - 1;
this.settingsPanel.updateConfigUI(this.ConfigurationNames,
this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex],
null);
// Save new config to file
this.writeToJson();
}
private handleConfigurationChange(): void {
if (this.propertiesFile === undefined) {
return; // Occurs when propertiesFile hasn't been checked yet.
}
this.configFileWatcherFallbackTime = new Date();
if (this.propertiesFile) {
this.parsePropertiesFileAndHandleSquiggles();
this.parsePropertiesFile();
// parsePropertiesFile can fail, but it won't overwrite an existing configurationJson in the event of failure.
// this.configurationJson should only be undefined here if we have never successfully parsed the propertiesFile.
if (this.configurationJson) {
@@ -686,11 +763,6 @@ export class CppProperties {
}
let fullPathToFile: string = path.join(this.configFolder, "c_cpp_properties.json");
let filePath: vscode.Uri = vscode.Uri.file(fullPathToFile).with({ scheme: "untitled" });
let document: vscode.TextDocument = await vscode.workspace.openTextDocument(filePath);
let edit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit();
if (this.configurationJson) {
this.resetToDefaultSettings(true);
}
@@ -705,17 +777,8 @@ export class CppProperties {
let savedKnownCompilers: KnownCompiler[] = this.configurationJson.configurations[0].knownCompilers;
delete this.configurationJson.configurations[0].knownCompilers;
edit.insert(document.uri, new vscode.Position(0, 0), JSON.stringify(this.configurationJson, null, 4));
await util.writeFileText(fullPathToFile, JSON.stringify(this.configurationJson, null, 4));
this.configurationJson.configurations[0].knownCompilers = savedKnownCompilers;
await vscode.workspace.applyEdit(edit);
// Fix for issue 163
// https://github.com/Microsoft/vscppsamples/issues/163
// Save the file to disk so that when the user tries to re-open the file it exists.
// Before this fix the file existed but was unsaved, so we went through the same
// code path and reapplied the edit.
await document.save();
this.propertiesFile = vscode.Uri.file(path.join(this.configFolder, "c_cpp_properties.json"));
@@ -726,12 +789,6 @@ export class CppProperties {
return;
}
private parsePropertiesFileAndHandleSquiggles(): void {
if (this.parsePropertiesFile()) {
this.handleSquiggles();
}
}
private parsePropertiesFile(): boolean {
let success: boolean = true;
try {
@@ -740,12 +797,6 @@ export class CppProperties {
return; // Repros randomly when the file is initially created. The parse will get called again after the file is written.
}
// Replace all \<escape character> with \\<character>.
// Otherwise, the JSON.parse result will have the \<escape character> missing.
readResults = readResults.replace(/\\/g, '\\\\');
readResults = readResults.replace(/\\\\"/g, '\\"'); // Need to revert the change to \".
readResults = readResults.replace(/\\\\"/g, '\\"'); // Need to do it again for \\".
// Try to use the same configuration as before the change.
let newJson: ConfigurationJson = JSON.parse(readResults);
if (!newJson || !newJson.configurations || newJson.configurations.length === 0) {
@@ -818,21 +869,204 @@ export class CppProperties {
vscode.window.showErrorMessage(`Failed to parse "${this.propertiesFile.fsPath}": ${err.message}`);
success = false;
}
if (success) {
this.handleSquiggles();
}
return success;
}
private resolvePath(path: string, isWindows: boolean): string {
if (!path || path === "${default}") {
return "";
}
let result: string = "";
// first resolve variables
result = util.resolveVariables(path, this.ExtendedEnvironment);
if (result.includes("${workspaceFolder}")) {
result = result.replace("${workspaceFolder}", this.rootUri.fsPath);
}
if (result.includes("${workspaceRoot}")) {
result = result.replace("${workspaceRoot}", this.rootUri.fsPath);
}
if (result.includes("${vcpkgRoot}") && util.getVcpkgRoot()) {
result = result.replace("${vcpkgRoot}", util.getVcpkgRoot());
}
if (result.includes("*")) {
result = result.replace(/\*/g, "");
}
// resolve WSL paths
if (isWindows && result.startsWith("/")) {
const mntStr: string = "/mnt/";
if (result.length > "/mnt/c/".length && result.substr(0, mntStr.length) === mntStr) {
result = result.substr(mntStr.length);
result = result.substr(0, 1) + ":" + result.substr(1);
} else if (this.rootfs && this.rootfs.length > 0) {
result = this.rootfs + result.substr(1);
// TODO: Handle WSL symlinks.
}
}
return result;
}
private getErrorsForConfigUI(configIndex: number): ConfigurationErrors {
let errors: ConfigurationErrors = {};
const isWindows: boolean = os.platform() === 'win32';
let config: Configuration = this.configurationJson.configurations[configIndex];
// Validate compilerPath
let resolvedCompilerPath: string = this.resolvePath(config.compilerPath, isWindows);
let compilerPathAndArgs: util.CompilerPathAndArgs = util.extractCompilerPathAndArgs(resolvedCompilerPath);
if (resolvedCompilerPath &&
// Don't error cl.exe paths because it could be for an older preview build.
!(isWindows && compilerPathAndArgs.compilerName === "cl.exe")) {
resolvedCompilerPath = resolvedCompilerPath.trim();
// Error when the compiler's path has spaces without quotes but args are used.
// Except, exclude cl.exe paths because it could be for an older preview build.
let compilerPathNeedsQuotes: boolean =
compilerPathAndArgs.additionalArgs &&
!resolvedCompilerPath.startsWith('"') &&
compilerPathAndArgs.compilerPath.includes(" ");
let compilerPathErrors: string[] = [];
if (compilerPathNeedsQuotes) {
compilerPathErrors.push(`Compiler path with spaces and arguments is missing double quotes " around the path.`);
}
// Get compiler path without arguments before checking if it exists
resolvedCompilerPath = compilerPathAndArgs.compilerPath;
let pathExists: boolean = true;
let existsWithExeAdded: (path: string) => boolean = (path: string) => {
return isWindows && !path.startsWith("/") && fs.existsSync(path + ".exe");
};
if (!fs.existsSync(resolvedCompilerPath)) {
if (existsWithExeAdded(resolvedCompilerPath)) {
resolvedCompilerPath += ".exe";
} else {
// Check again for a relative path.
const relativePath: string = this.rootUri.fsPath + path.sep + resolvedCompilerPath;
if (!fs.existsSync(relativePath)) {
if (existsWithExeAdded(resolvedCompilerPath)) {
resolvedCompilerPath += ".exe";
} else {
pathExists = false;
}
} else {
resolvedCompilerPath = relativePath;
}
}
}
if (!pathExists) {
let message: string = `Cannot find: ${resolvedCompilerPath}`;
compilerPathErrors.push(message);
} else if (compilerPathAndArgs.compilerPath === "") {
let message: string = `Invalid input, cannot resolve compiler path`;
compilerPathErrors.push(message);
} else if (!util.checkFileExistsSync(resolvedCompilerPath)) {
let message: string = `Path is not a file: ${resolvedCompilerPath}`;
compilerPathErrors.push(message);
}
if (compilerPathErrors.length > 0) {
errors.compilerPath = compilerPathErrors.join('\n');
}
}
// Validate paths (directories)
errors.includePath = this.validatePath(config.includePath);
errors.macFrameworkPath = this.validatePath(config.macFrameworkPath);
errors.browsePath = this.validatePath(config.browse ? config.browse.path : undefined);
// Validate files
errors.forcedInclude = this.validatePath(config.forcedInclude, false);
errors.compileCommands = this.validatePath(config.compileCommands, false);
errors.databaseFilename = this.validatePath((config.browse ? config.browse.databaseFilename : undefined), false);
// Validate intelliSenseMode
if (isWindows && !this.isCompilerIntelliSenseModeCompatible(config)) {
errors.intelliSenseMode = `IntelliSense mode ${config.intelliSenseMode} is incompatible with compiler path.`;
}
return errors;
}
private validatePath(input: string|string[], isDirectory: boolean = true): string {
if (!input) {
return undefined;
}
const isWindows: boolean = os.platform() === 'win32';
let errorMsg: string;
let errors: string[] = [];
let paths: string[] = [];
if (util.isString(input)) {
paths.push(input);
} else {
paths = input;
}
for (let p of paths) {
let pathExists: boolean = true;
let resolvedPath: string = this.resolvePath(p, isWindows);
if (!resolvedPath) {
continue;
}
// Check if resolved path exists
if (!fs.existsSync(resolvedPath)) {
// Check for relative path if resolved path does not exists
const relativePath: string = this.rootUri.fsPath + path.sep + resolvedPath;
if (!fs.existsSync(relativePath)) {
pathExists = false;
} else {
resolvedPath = relativePath;
}
}
if (!pathExists) {
let message: string = `Cannot find: ${resolvedPath}`;
errors.push(message);
continue;
}
// Check if path is a directory or file
if (isDirectory && !util.checkDirectoryExistsSync(resolvedPath)) {
let message: string = `Path is not a directory: ${resolvedPath}`;
errors.push(message);
} else if (!isDirectory && !util.checkFileExistsSync(resolvedPath)) {
let message: string = `Path is not a file: ${resolvedPath}`;
errors.push(message);
}
}
if (errors.length > 0) {
errorMsg = errors.join('\n');
}
return errorMsg;
}
private handleSquiggles(): void {
if (!this.propertiesFile) {
return;
}
if (this.configurationJson.enableConfigurationSquiggles === false) {
if (!this.configurationJson.enableConfigurationSquiggles) {
this.diagnosticCollection.clear();
return;
}
const settings: CppSettings = new CppSettings(this.rootUri);
if (settings.defaultEnableConfigurationSquiggles === false) {
if (!settings.defaultEnableConfigurationSquiggles) {
this.diagnosticCollection.clear();
return;
}
@@ -842,8 +1076,18 @@ export class CppProperties {
// Get the text of the current configuration.
let curText: string = document.getText();
// Replace all \<escape character> with \\<character>, except for \"
// Otherwise, the JSON.parse result will have the \<escape character> missing.
let configurationsText: string = util.escapeForSquiggles(curText);
let configurations: ConfigurationJson = JSON.parse(configurationsText);
let currentConfiguration: Configuration = configurations.configurations[this.CurrentConfigurationIndex];
let curTextStartOffset: number = 0;
const configStart: number = curText.search(new RegExp(`{\\s*"name"\\s*:\\s*"${escapeStringRegExp(this.CurrentConfiguration.name)}"`));
if (!currentConfiguration.name) {
return;
}
const configStart: number = curText.search(new RegExp(`{\\s*"name"\\s*:\\s*"${escapeStringRegExp(currentConfiguration.name)}"`));
if (configStart === -1) {
telemetry.logLanguageServerEvent("ConfigSquiggles", { "error": "config name not first" });
return;
@@ -863,8 +1107,8 @@ export class CppProperties {
}
curText = curText.substr(0, nextNameStart2);
}
if (this.prevSquiggleMetrics[this.CurrentConfiguration.name] === undefined) {
this.prevSquiggleMetrics[this.CurrentConfiguration.name] = { PathNonExistent: 0, PathNotAFile: 0, PathNotADirectory: 0, CompilerPathMissingQuotes: 0, CompilerModeMismatch: 0 };
if (this.prevSquiggleMetrics[currentConfiguration.name] === undefined) {
this.prevSquiggleMetrics[currentConfiguration.name] = { PathNonExistent: 0, PathNotAFile: 0, PathNotADirectory: 0, CompilerPathMissingQuotes: 0, CompilerModeMismatch: 0 };
}
let newSquiggleMetrics: { [key: string]: number } = { PathNonExistent: 0, PathNotAFile: 0, PathNotADirectory: 0, CompilerPathMissingQuotes: 0, CompilerModeMismatch: 0 };
const isWindows: boolean = os.platform() === 'win32';
@@ -879,8 +1123,8 @@ export class CppProperties {
const intelliSenseModeValueStart: number = curText.indexOf('"', curText.indexOf(":", intelliSenseModeStart));
const intelliSenseModeValueEnd: number = intelliSenseModeStart === -1 ? -1 : curText.indexOf('"', intelliSenseModeValueStart + 1) + 1;
if (!this.isCompilerIntelliSenseModeCompatible()) {
let message: string = `intelliSenseMode ${this.CurrentConfiguration.intelliSenseMode} is incompatible with compilerPath.`;
if (!this.isCompilerIntelliSenseModeCompatible(currentConfiguration)) {
let message: string = `intelliSenseMode ${currentConfiguration.intelliSenseMode} is incompatible with compilerPath.`;
let diagnostic: vscode.Diagnostic = new vscode.Diagnostic(
new vscode.Range(document.positionAt(curTextStartOffset + intelliSenseModeValueStart),
document.positionAt(curTextStartOffset + intelliSenseModeValueEnd)),
@@ -893,21 +1137,21 @@ export class CppProperties {
// Check for path-related squiggles.
let paths: Set<string> = new Set<string>();
for (let pathArray of [ (this.CurrentConfiguration.browse ? this.CurrentConfiguration.browse.path : undefined),
this.CurrentConfiguration.includePath, this.CurrentConfiguration.macFrameworkPath, this.CurrentConfiguration.forcedInclude ] ) {
for (let pathArray of [ (currentConfiguration.browse ? currentConfiguration.browse.path : undefined),
currentConfiguration.includePath, currentConfiguration.macFrameworkPath, currentConfiguration.forcedInclude ]) {
if (pathArray) {
for (let curPath of pathArray) {
paths.add(`"${curPath}"`);
paths.add(`${curPath}`);
}
}
}
if (this.CurrentConfiguration.compileCommands) {
paths.add(`"${this.CurrentConfiguration.compileCommands}"`);
if (currentConfiguration.compileCommands) {
paths.add(`${currentConfiguration.compileCommands}`);
}
if (this.CurrentConfiguration.compilerPath) {
if (currentConfiguration.compilerPath) {
// Unlike other cases, compilerPath may not start or end with " due to trimming of whitespace and the possibility of compiler args.
paths.add(`${this.CurrentConfiguration.compilerPath}`);
paths.add(`${currentConfiguration.compilerPath}`);
}
// Get the start/end for properties that are file-only.
@@ -919,55 +1163,33 @@ export class CppProperties {
const compilerPathEnd: number = compilerPathStart === -1 ? -1 : curText.indexOf('"', curText.indexOf('"', curText.indexOf(":", compilerPathStart)) + 1) + 1;
for (let curPath of paths) {
const isCompilerPath: boolean = curPath === this.CurrentConfiguration.compilerPath;
let resolvedPath: string = isCompilerPath ? curPath : curPath.substr(1, curPath.length - 2); // Remove the surrounding quotes.
const isCompilerPath: boolean = curPath === currentConfiguration.compilerPath;
// Resolve special path cases.
if (resolvedPath === "${default}") {
if (curPath === "${default}") {
// TODO: Add squiggles for when the C_Cpp.default.* paths are invalid.
continue;
}
resolvedPath = util.resolveVariables(resolvedPath, this.ExtendedEnvironment);
if (resolvedPath.includes("${workspaceFolder}")) {
resolvedPath = resolvedPath.replace("${workspaceFolder}", this.rootUri.fsPath);
}
if (resolvedPath.includes("${workspaceRoot}")) {
resolvedPath = resolvedPath.replace("${workspaceRoot}", this.rootUri.fsPath);
}
if (resolvedPath.includes("${vcpkgRoot}")) {
resolvedPath = resolvedPath.replace("${vcpkgRoot}", util.getVcpkgRoot());
}
if (resolvedPath.includes("*")) {
resolvedPath = resolvedPath.replace(/\*/g, "");
let resolvedPath: string = this.resolvePath(curPath, isWindows);
if (!resolvedPath) {
continue;
}
// TODO: Invalid paths created from environment variables are not detected.
// Handle WSL paths.
const isWSL: boolean = isWindows && resolvedPath.startsWith("/");
if (isWSL) {
const mntStr: string = "/mnt/";
if (resolvedPath.length > "/mnt/c/".length && resolvedPath.substr(0, mntStr.length) === mntStr) {
resolvedPath = resolvedPath.substr(mntStr.length);
resolvedPath = resolvedPath.substr(0, 1) + ":" + resolvedPath.substr(1);
} else if (this.rootfs && this.rootfs.length > 0) {
resolvedPath = this.rootfs + resolvedPath.substr(1);
// TODO: Handle WSL symlinks.
}
}
let compilerPathNeedsQuotes: boolean = false;
if (isCompilerPath) {
resolvedPath = resolvedPath.trim();
let compilerPathAndArgs: util.CompilerPathAndArgs = util.extractCompilerPathAndArgs(resolvedPath);
if (isWindows && compilerPathAndArgs.compilerPath.endsWith("cl.exe")) {
if (isWindows && compilerPathAndArgs.compilerName === "cl.exe") {
continue; // Don't squiggle invalid cl.exe paths because it could be for an older preview build.
}
// Squiggle when the compiler's path has spaces without quotes but args are used.
compilerPathNeedsQuotes = compilerPathAndArgs.additionalArgs && !resolvedPath.startsWith('"') && compilerPathAndArgs.compilerPath.includes(" ");
resolvedPath = compilerPathAndArgs.compilerPath;
curPath = curPath.replace(/\"/g, `\\"`);
}
const isWSL: boolean = isWindows && resolvedPath.startsWith("/");
let pathExists: boolean = true;
let existsWithExeAdded: (path: string) => boolean = (path: string) => {
return isCompilerPath && isWindows && !isWSL && fs.existsSync(path + ".exe");
@@ -998,39 +1220,55 @@ export class CppProperties {
}
// Iterate through the text and apply squiggles.
for (let curOffset: number = curText.indexOf(curPath); curOffset !== -1; curOffset = curText.indexOf(curPath, curOffset + curPath.length)) {
let message: string;
if (!pathExists) {
message = `Cannot find "${resolvedPath}".`;
newSquiggleMetrics.PathNonExistent++;
} else {
// Check for file versus path mismatches.
if ((curOffset >= forcedIncludeStart && curOffset <= forcedeIncludeEnd) ||
(curOffset >= compileCommandsStart && curOffset <= compileCommandsEnd) ||
(curOffset >= compilerPathStart && curOffset <= compilerPathEnd)) {
if (compilerPathNeedsQuotes) {
message = `Compiler path with spaces and arguments is missing \\" around the path.`;
newSquiggleMetrics.CompilerPathMissingQuotes++;
// Escape the path string for literal use in a regular expression
// Need to escape any quotes to match the original text
let escapedPath: string = curPath.replace(/\"/g, '\\\"');
escapedPath = escapedPath.replace(/[-\"\/\\^$*+?.()|[\]{}]/g, '\\$&');
// Create a pattern to search for the path with either a quote or semicolon immediately before and after,
// and extend that pattern to the next quote before and next quote after it.
let pattern: RegExp = new RegExp(`"[^"]*?(?<="|;)${escapedPath}(?="|;).*?"`, "g");
let matches: string[] = curText.match(pattern);
if (matches) {
let curOffset: number = 0;
let endOffset: number = 0;
for (let curMatch of matches) {
curOffset = curText.substr(endOffset).search(pattern) + endOffset;
endOffset = curOffset + curMatch.length;
let message: string;
if (!pathExists) {
message = `Cannot find "${resolvedPath}".`;
newSquiggleMetrics.PathNonExistent++;
} else {
// Check for file versus path mismatches.
if ((curOffset >= forcedIncludeStart && curOffset <= forcedeIncludeEnd) ||
(curOffset >= compileCommandsStart && curOffset <= compileCommandsEnd) ||
(curOffset >= compilerPathStart && curOffset <= compilerPathEnd)) {
if (compilerPathNeedsQuotes) {
message = `Compiler path with spaces and arguments is missing \\" around the path.`;
newSquiggleMetrics.CompilerPathMissingQuotes++;
} else {
if (util.checkFileExistsSync(resolvedPath)) {
continue;
}
message = `Path is not a file: "${resolvedPath}".`;
newSquiggleMetrics.PathNotAFile++;
}
} else {
if (util.checkFileExistsSync(resolvedPath)) {
if (util.checkDirectoryExistsSync(resolvedPath)) {
continue;
}
message = `Path is not a file: "${resolvedPath}".`;
newSquiggleMetrics.PathNotAFile++;
message = `Path is not a directory: "${resolvedPath}".`;
newSquiggleMetrics.PathNotADirectory++;
}
} else {
if (util.checkDirectoryExistsSync(resolvedPath)) {
continue;
}
message = `Path is not a directory: "${resolvedPath}".`;
newSquiggleMetrics.PathNotADirectory++;
}
let diagnostic: vscode.Diagnostic = new vscode.Diagnostic(
new vscode.Range(document.positionAt(curTextStartOffset + curOffset),
document.positionAt(curTextStartOffset + endOffset)),
message, vscode.DiagnosticSeverity.Warning);
diagnostics.push(diagnostic);
}
let diagnostic: vscode.Diagnostic = new vscode.Diagnostic(
new vscode.Range(document.positionAt(curTextStartOffset + curOffset),
document.positionAt(curTextStartOffset + curOffset + curPath.length + (!isCompilerPath ? -1 : 0))),
message, vscode.DiagnosticSeverity.Warning);
diagnostics.push(diagnostic);
}
}
if (diagnostics.length !== 0) {
@@ -1041,22 +1279,25 @@ export class CppProperties {
// Send telemetry on squiggle changes.
let changedSquiggleMetrics: { [key: string]: number } = {};
if (newSquiggleMetrics.PathNonExistent !== this.prevSquiggleMetrics[this.CurrentConfiguration.name].PathNonExistent) {
if (newSquiggleMetrics.PathNonExistent !== this.prevSquiggleMetrics[currentConfiguration.name].PathNonExistent) {
changedSquiggleMetrics.PathNonExistent = newSquiggleMetrics.PathNonExistent;
}
if (newSquiggleMetrics.PathNotAFile !== this.prevSquiggleMetrics[this.CurrentConfiguration.name].PathNotAFile) {
if (newSquiggleMetrics.PathNotAFile !== this.prevSquiggleMetrics[currentConfiguration.name].PathNotAFile) {
changedSquiggleMetrics.PathNotAFile = newSquiggleMetrics.PathNotAFile;
}
if (newSquiggleMetrics.PathNotADirectory !== this.prevSquiggleMetrics[this.CurrentConfiguration.name].PathNotADirectory) {
if (newSquiggleMetrics.PathNotADirectory !== this.prevSquiggleMetrics[currentConfiguration.name].PathNotADirectory) {
changedSquiggleMetrics.PathNotADirectory = newSquiggleMetrics.PathNotADirectory;
}
if (newSquiggleMetrics.CompilerPathMissingQuotes !== this.prevSquiggleMetrics[this.CurrentConfiguration.name].CompilerPathMissingQuotes) {
if (newSquiggleMetrics.CompilerPathMissingQuotes !== this.prevSquiggleMetrics[currentConfiguration.name].CompilerPathMissingQuotes) {
changedSquiggleMetrics.CompilerPathMissingQuotes = newSquiggleMetrics.CompilerPathMissingQuotes;
}
if (newSquiggleMetrics.CompilerModeMismatch !== this.prevSquiggleMetrics[currentConfiguration.name].CompilerModeMismatch) {
changedSquiggleMetrics.CompilerModeMismatch = newSquiggleMetrics.CompilerModeMismatch;
}
if (Object.keys(changedSquiggleMetrics).length > 0) {
telemetry.logLanguageServerEvent("ConfigSquiggles", null, changedSquiggleMetrics);
}
this.prevSquiggleMetrics[this.CurrentConfiguration.name] = newSquiggleMetrics;
this.prevSquiggleMetrics[currentConfiguration.name] = newSquiggleMetrics;
});
}
@@ -50,6 +50,9 @@ class CustomProviderWrapper implements CustomConfigurationProvider1 {
if (valid && this._version > Version.v1) {
valid = !!(this.provider.canProvideBrowseConfiguration && this.provider.provideBrowseConfiguration);
}
if (valid && this._version > Version.v2) {
valid = !!(this.provider.canProvideBrowseConfigurationsPerFolder && this.provider.provideFolderBrowseConfiguration);
}
return valid;
}
@@ -82,6 +85,15 @@ class CustomProviderWrapper implements CustomConfigurationProvider1 {
return this._version < Version.v2 ? Promise.resolve({browsePath: []}) : this.provider.provideBrowseConfiguration(token);
}
public canProvideBrowseConfigurationsPerFolder(token?: vscode.CancellationToken): Thenable<boolean> {
return this._version < Version.v3 ? Promise.resolve(false) : this.provider.canProvideBrowseConfigurationsPerFolder(token);
}
public provideFolderBrowseConfiguration(uri: vscode.Uri, token?: vscode.CancellationToken): Thenable<WorkspaceBrowseConfiguration> {
console.assert(this._version >= Version.v3);
return this._version < Version.v3 ? Promise.resolve({browsePath: []}) : this.provider.provideFolderBrowseConfiguration(uri, token);
}
public dispose(): void {
if (this._version !== Version.v0) {
this.provider.dispose();
@@ -115,6 +127,12 @@ export class CustomConfigurationProviderCollection {
if (version >= Version.v2 && !provider.provideBrowseConfiguration) {
missing.push("'provideBrowseConfiguration'");
}
if (version >= Version.v3 && !provider.canProvideBrowseConfigurationsPerFolder) {
missing.push("'canProvideBrowseConfigurationsPerFolder'");
}
if (version >= Version.v3 && !provider.provideFolderBrowseConfiguration) {
missing.push("'provideFolderBrowseConfiguration'");
}
console.error(`CustomConfigurationProvider was not registered. The following properties are missing from the implementation: ${missing.join(", ")}.`);
}
@@ -171,7 +189,7 @@ export class CustomConfigurationProviderCollection {
}
public forEach(func: (provider: CustomConfigurationProvider1) => void): void {
this.providers.forEach(provider => func(provider));
this.providers.forEach(func);
}
public remove(provider: CustomConfigurationProvider): void {
@@ -212,4 +230,4 @@ let providerCollection: CustomConfigurationProviderCollection = new CustomConfig
export function getCustomConfigProviders(): CustomConfigurationProviderCollection {
return providerCollection;
}
}
+1 -1
View File
@@ -44,4 +44,4 @@ export class DataBinding<T> {
this.deactivate();
this.valueChanged.dispose();
}
}
}
+338 -86
View File
@@ -25,6 +25,9 @@ import { getTargetBuildInfo, BuildInfo } from '../githubAPI';
import * as configs from './configurations';
import { PackageVersion } from '../packageVersion';
import { getTemporaryCommandRegistrarInstance } from '../commands';
import * as rd from 'readline';
import * as yauzl from 'yauzl';
import { Readable } from 'stream';
let prevCrashFile: string;
let clients: ClientCollection;
@@ -42,6 +45,97 @@ let buildInfoCache: BuildInfo | null = null;
const taskSourceStr: string = "C/C++";
const cppInstallVsixStr: string = 'C/C++: Install vsix -- ';
let taskProvider: vscode.Disposable;
let codeActionProvider: vscode.Disposable;
const intelliSenseDisabledError: string = "Do not activate the extension when IntelliSense is disabled.";
type vcpkgDatabase = { [key: string]: string[] }; // Stored as <header file entry> -> [<port name>]
let vcpkgDbPromise: Promise<vcpkgDatabase>;
function initVcpkgDatabase(): Promise<vcpkgDatabase> {
return new Promise((resolve, reject) => {
yauzl.open(util.getExtensionFilePath('VCPkgHeadersDatabase.zip'), { lazyEntries: true }, (err? : Error, zipfile?: yauzl.ZipFile) => {
if (err) {
resolve({});
return;
}
zipfile.readEntry();
let dbFound: boolean = false;
zipfile.on('entry', entry => {
if (entry.fileName !== 'VCPkgHeadersDatabase.txt') {
return;
}
dbFound = true;
zipfile.openReadStream(entry, (err?: Error, stream?: Readable) => {
if (err) {
resolve({});
return;
}
let database: vcpkgDatabase = {};
let reader: rd.ReadLine = rd.createInterface(stream);
reader.on('line', (lineText: string) => {
let portFilePair: string[] = lineText.split(':');
if (portFilePair.length !== 2) {
return;
}
const portName: string = portFilePair[0];
const relativeHeader: string = portFilePair[1];
if (!database[relativeHeader]) {
database[relativeHeader] = [];
}
database[relativeHeader].push(portName);
});
reader.on('close', () => {
resolve(database);
});
});
});
zipfile.on('end', () => {
if (!dbFound) {
resolve({});
}
});
});
});
}
function getVcpkgHelpAction(): vscode.CodeAction {
const dummy: any[] = [{}]; // To distinguish between entry from CodeActions and the command palette
return {
command: { title: 'vcpkgOnlineHelpSuggested', command: 'C_Cpp.VcpkgOnlineHelpSuggested', arguments: dummy },
title: "Learn how to install a library for this header with vcpkg",
kind: vscode.CodeActionKind.QuickFix
};
}
function getVcpkgClipboardInstallAction(port: string): vscode.CodeAction {
return {
command: { title: 'vcpkgClipboardInstallSuggested', command: 'C_Cpp.VcpkgClipboardInstallSuggested', arguments: [[port]] },
title: `Copy vcpkg command to install '${port}' to the clipboard`,
kind: vscode.CodeActionKind.QuickFix
};
}
async function lookupIncludeInVcpkg(document: vscode.TextDocument, line: number): Promise<string[]> {
const matches : RegExpMatchArray = document.lineAt(line).text.match(/#include\s*[<"](?<includeFile>[^>"]*)[>"]/);
if (!matches.length) {
return [];
}
const missingHeader: string = matches.groups['includeFile'].replace('/', '\\');
let portsWithHeader: string[];
const vcpkgDb: vcpkgDatabase = await vcpkgDbPromise;
if (vcpkgDb) {
portsWithHeader = vcpkgDb[missingHeader];
}
return portsWithHeader ? portsWithHeader : [];
}
function isMissingIncludeDiagnostic(diagnostic: vscode.Diagnostic): boolean {
const missingIncludeCode: number = 1696;
return diagnostic.code && diagnostic.code === missingIncludeCode && diagnostic.source && diagnostic.source === 'cpptools';
}
/**
* activate: set up the extension for language services
@@ -60,7 +154,7 @@ export function activate(activationEventOccurred: boolean): void {
}
if (tempCommands.length === 0) { // Only needs to be added once.
tempCommands.push(vscode.workspace.onDidOpenTextDocument(d => onDidOpenTextDocument(d)));
tempCommands.push(vscode.workspace.onDidOpenTextDocument(onDidOpenTextDocument));
}
// Check if an activation event has already occurred.
@@ -84,6 +178,33 @@ export function activate(activationEventOccurred: boolean): void {
}
});
const selector: vscode.DocumentSelector = [
{ scheme: 'file', language: 'cpp' },
{ scheme: 'file', language: 'c' }
];
codeActionProvider = vscode.languages.registerCodeActionsProvider(selector, {
provideCodeActions: async (document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken): Promise<vscode.CodeAction[]> => {
if (!await clients.ActiveClient.getVcpkgEnabled()) {
return [];
}
// Generate vcpkg install/help commands if the incoming doc/range is a missing include error
if (!context.diagnostics.some(isMissingIncludeDiagnostic)) {
return [];
}
telemetry.logLanguageServerEvent('codeActionsProvided', { "source": "vcpkg" });
if (!await clients.ActiveClient.getVcpkgInstalled()) {
return [getVcpkgHelpAction()];
}
const ports: string[] = await lookupIncludeInVcpkg(document, range.start.line);
const actions: vscode.CodeAction[] = ports.map<vscode.CodeAction>(getVcpkgClipboardInstallAction);
return actions;
}
});
// handle "workspaceContains:/.vscode/c_cpp_properties.json" activation event.
if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) {
for (let i: number = 0; i < vscode.workspace.workspaceFolders.length; ++i) {
@@ -114,7 +235,7 @@ export interface BuildTaskDefinition extends vscode.TaskDefinition {
/**
* Generate tasks to build the current file based on the user's detected compilers, the user's compilerPath setting, and the current file's extension.
*/
export async function getBuildTasks(returnComplerPath: boolean): Promise<vscode.Task[]> {
export async function getBuildTasks(returnCompilerPath: boolean): Promise<vscode.Task[]> {
const editor: vscode.TextEditor = vscode.window.activeTextEditor;
if (!editor) {
return [];
@@ -122,7 +243,7 @@ export async function getBuildTasks(returnComplerPath: boolean): Promise<vscode.
const fileExt: string = path.extname(editor.document.fileName);
if (!fileExt) {
return;
return [];
}
// Don't offer tasks for header files.
@@ -146,13 +267,22 @@ export async function getBuildTasks(returnComplerPath: boolean): Promise<vscode.
return [];
}
// Get a list of compilers found from the C++ side, then filter them based on the file type to get a reduced list appropriate
// for the active file, remove duplicate compiler names, then finally add the user's compilerPath setting.
let compilerPaths: string[];
// Get compiler paths.
const isWindows: boolean = os.platform() === 'win32';
const activeClient: Client = getActiveClient();
let userCompilerPath: string = await activeClient.getCompilerPath();
if (userCompilerPath) {
let activeClient: Client;
try {
activeClient = getActiveClient();
} catch (e) {
if (!e || e.message !== intelliSenseDisabledError) {
console.error("Unknown error calling getActiveClient().");
}
return []; // Language service features may be disabled.
}
// Get user compiler path.
const userCompilerPathAndArgs: util.CompilerPathAndArgs = await activeClient.getCurrentCompilerPathAndArgs();
let userCompilerPath: string = userCompilerPathAndArgs.compilerPath;
if (userCompilerPath && userCompilerPathAndArgs.compilerName) {
userCompilerPath = userCompilerPath.trim();
if (isWindows && userCompilerPath.startsWith("/")) { // TODO: Add WSL compiler support.
userCompilerPath = null;
@@ -161,38 +291,20 @@ export async function getBuildTasks(returnComplerPath: boolean): Promise<vscode.
}
}
// Get known compiler paths. Do not include the known compiler path that is the same as user compiler path.
// Filter them based on the file type to get a reduced list appropriate for the active file.
let knownCompilerPaths: string[];
let knownCompilers: configs.KnownCompiler[] = await activeClient.getKnownCompilers();
if (knownCompilers) {
knownCompilers = knownCompilers.filter(info => {
return ((fileIsCpp && !info.isC) || (fileIsC && info.isC)) &&
(path.basename(info.path) !== userCompilerPathAndArgs.compilerName) &&
(!isWindows || !info.path.startsWith("/")); // TODO: Add WSL compiler support.
});
compilerPaths = knownCompilers.map<string>(info => { return info.path; });
let map: Map<string, string> = new Map<string, string>();
const insertOrAssignEntry: (compilerPath: string) => void = (compilerPath: string): void => {
let basename: string = compilerPath;
if (compilerPath === userCompilerPath) {
// Make sure the compiler args are not part of the basename.
const compilerPathAndArgs: util.CompilerPathAndArgs = util.extractCompilerPathAndArgs(compilerPath);
basename = compilerPathAndArgs.compilerPath;
}
basename = path.basename(basename);
map.set(basename, compilerPath);
};
compilerPaths.forEach(insertOrAssignEntry);
// Ensure that the user's compilerPath setting is used by inserting/assigning last.
if (userCompilerPath) {
insertOrAssignEntry(userCompilerPath);
}
compilerPaths = [...map.values()];
} else if (userCompilerPath) {
compilerPaths = [userCompilerPath];
knownCompilerPaths = knownCompilers.map<string>(info => info.path);
}
if (!compilerPaths) {
if (!knownCompilerPaths || !userCompilerPath) {
// Don't prompt a message yet until we can make a data-based decision.
telemetry.logLanguageServerEvent('noCompilerFound');
// Display a message prompting the user to install compilers if none were found.
@@ -219,41 +331,56 @@ export async function getBuildTasks(returnComplerPath: boolean): Promise<vscode.
return [];
}
// Generate tasks.
return compilerPaths.map<vscode.Task>(compilerPath => {
// Handle compiler args in compilerPath.
let compilerPathAndArgs: util.CompilerPathAndArgs = util.extractCompilerPathAndArgs(compilerPath);
compilerPath = compilerPathAndArgs.compilerPath;
let createTask: (compilerPath: string, compilerArgs?: string []) => vscode.Task = (compilerPath: string, compilerArgs?: string []) => {
const filePath: string = path.join('${fileDirname}', '${fileBasenameNoExtension}');
const compilerPathBase: string = path.basename(compilerPath);
const taskName: string = compilerPathBase + " build active file";
const isCl: boolean = taskName.startsWith("cl.exe");
let args: string[] = isCl ? [ '/Zi', '/EHsc', '/Fe:', filePath + '.exe', '${file}' ] : ['-g', '${file}', '-o', filePath + (isWindows ? '.exe' : '')];
if (compilerPathAndArgs.additionalArgs) {
args = args.concat(compilerPathAndArgs.additionalArgs);
}
const isCl: boolean = compilerPathBase === "cl.exe";
const cwd: string = isCl ? "" : path.dirname(compilerPath);
const kind: BuildTaskDefinition = {
let args: string[] = isCl ? ['/Zi', '/EHsc', '/Fe:', filePath + '.exe', '${file}'] : ['-g', '${file}', '-o', filePath + (isWindows ? '.exe' : '')];
if (compilerArgs && compilerArgs.length > 0) {
args = args.concat(compilerArgs);
}
let kind: vscode.TaskDefinition = {
type: 'shell',
label: taskName,
command: isCl ? compilerPathBase : compilerPath,
args: args,
options: isCl ? undefined : {"cwd": cwd},
compilerPath: isCl ? compilerPathBase : compilerPath
};
if (returnCompilerPath) {
kind = kind as BuildTaskDefinition;
kind.compilerPath = isCl ? compilerPathBase : compilerPath;
}
const command: vscode.ShellExecution = new vscode.ShellExecution(compilerPath, [...args], { cwd: cwd });
const target: vscode.WorkspaceFolder = vscode.workspace.getWorkspaceFolder(clients.ActiveClient.RootUri);
let task: vscode.Task = new vscode.Task(kind, target, taskName, taskSourceStr, command, '$gcc');
task.definition = kind; // The constructor for vscode.Task will eat the definition. Reset it by reassigning.
task.definition = kind; // The constructor for vscode.Task will consume the definition. Reset it by reassigning.
task.group = vscode.TaskGroup.Build;
if (!returnComplerPath) {
delete task.definition.compilerPath;
}
return task;
});
};
// Create a build task per compiler path
let buildTasks: vscode.Task[] = [];
// Tasks for known compiler paths
if (knownCompilerPaths) {
buildTasks = knownCompilerPaths.map<vscode.Task>(compilerPath => {
return createTask(compilerPath);
});
}
// Task for user compiler path setting
if (userCompilerPath) {
let task: vscode.Task = createTask(userCompilerPath, userCompilerPathAndArgs.additionalArgs);
buildTasks.push(task);
}
return buildTasks;
}
function onDidOpenTextDocument(document: vscode.TextDocument): void {
@@ -280,7 +407,7 @@ function onActivationEvent(): void {
function realActivation(): void {
if (new CppSettings().intelliSenseEngine === "Disabled") {
throw new Error("Do not activate the extension when IntelliSense is disabled.");
throw new Error(intelliSenseDisabledError);
} else {
console.log("activating extension");
let checkForConflictingExtensions: PersistentState<boolean> = new PersistentState<boolean>("CPP." + util.packageJson.version + ".checkForConflictingExtensions", true);
@@ -317,13 +444,16 @@ function realActivation(): void {
disposables.push(vscode.window.onDidChangeActiveTextEditor(onDidChangeActiveTextEditor));
disposables.push(vscode.window.onDidChangeTextEditorSelection(onDidChangeTextEditorSelection));
disposables.push(vscode.window.onDidChangeVisibleTextEditors(onDidChangeVisibleTextEditors));
disposables.push(vscode.window.onDidChangeTextEditorVisibleRanges(onDidChangeTextEditorVisibleRanges));
updateLanguageConfigurations();
reportMacCrashes();
const settings: CppSettings = new CppSettings(clients.ActiveClient.RootUri);
vcpkgDbPromise = initVcpkgDatabase();
if (settings.updateChannel === 'Default') {
suggestInsidersChannel();
} else if (settings.updateChannel === 'Insiders') {
@@ -346,9 +476,14 @@ export function updateLanguageConfigurations(): void {
* workspace events
*********************************************/
function onDidChangeSettings(): void {
const changedActiveClientSettings: { [key: string] : string } = clients.ActiveClient.onDidChangeSettings();
clients.forEach(client => client.onDidChangeSettings());
function onDidChangeSettings(event: vscode.ConfigurationChangeEvent): void {
let activeClient: Client = clients.ActiveClient;
const changedActiveClientSettings: { [key: string] : string } = activeClient.onDidChangeSettings(event);
clients.forEach(client => {
if (client !== activeClient) {
client.onDidChangeSettings(event);
}
});
const newUpdateChannel: string = changedActiveClientSettings['updateChannel'];
if (newUpdateChannel) {
@@ -357,7 +492,7 @@ function onDidChangeSettings(): void {
} else if (newUpdateChannel === 'Insiders') {
insiderUpdateTimer = setInterval(checkAndApplyUpdate, insiderUpdateTimerInterval);
}
checkAndApplyUpdate(newUpdateChannel);
}
}
@@ -409,7 +544,30 @@ function onDidChangeTextEditorSelection(event: vscode.TextEditorSelectionChangeE
}
function onDidChangeVisibleTextEditors(editors: vscode.TextEditor[]): void {
clients.forEach(client => client.onDidChangeVisibleTextEditors(editors));
clients.forEach(client => {
let editorsForThisClient: vscode.TextEditor[] = [];
editors.forEach(editor => {
if (editor.document.languageId === "c" || editor.document.languageId === "cpp") {
if (clients.checkOwnership(client, editor.document)) {
editorsForThisClient.push(editor);
}
}
});
if (editorsForThisClient.length > 0) {
client.onDidChangeVisibleTextEditors(editorsForThisClient);
}
});
}
function onDidChangeTextEditorVisibleRanges(textEditorVisibleRangesChangeEvent: vscode.TextEditorVisibleRangesChangeEvent): void {
let languageId: String = textEditorVisibleRangesChangeEvent.textEditor.document.languageId;
if (languageId === "c" || languageId === "cpp") {
clients.forEach(client => {
if (clients.checkOwnership(client, textEditorVisibleRangesChangeEvent.textEditor.document)) {
client.onDidChangeTextEditorVisibleRanges(textEditorVisibleRangesChangeEvent);
}
});
}
}
function onInterval(): void {
@@ -421,7 +579,15 @@ function onInterval(): void {
* Install a VSIX package. This helper function will exist until VSCode offers a command to do so.
* @param updateChannel The user's updateChannel setting.
*/
function installVsix(vsixLocation: string, updateChannel: string): Promise<void> {
function installVsix(vsixLocation: string): Thenable<void> {
let userVersion: PackageVersion = new PackageVersion(vscode.version);
// 1.33.0 introduces workbench.extensions.installExtension. 1.32.3 was immediately prior.
let lastVersionWithoutInstallExtensionCommand: PackageVersion = new PackageVersion('1.32.3');
if (userVersion.isGreaterThan(lastVersionWithoutInstallExtensionCommand)) {
return vscode.commands.executeCommand('workbench.extensions.installExtension', vscode.Uri.file(vsixLocation));
}
// Get the path to the VSCode command -- replace logic later when VSCode allows calling of
// workbench.extensions.action.installVSIX from TypeScript w/o instead popping up a file dialog
return PlatformInformation.GetPlatformInformation().then((platformInfo) => {
@@ -455,21 +621,20 @@ function installVsix(vsixLocation: string, updateChannel: string): Promise<void>
return Promise.reject(new Error('Failed to find VS Code script'));
}
// 1.28.0 changes the CLI for making installations
let userVersion: PackageVersion = new PackageVersion(vscode.version);
let breakingVersion: PackageVersion = new PackageVersion('1.28.0');
if (userVersion.isGreaterThan(breakingVersion, 'insider')) {
// 1.28.0 changes the CLI for making installations. 1.27.2 was immediately prior.
let oldVersion: PackageVersion = new PackageVersion('1.27.2');
if (userVersion.isGreaterThan(oldVersion)) {
return new Promise<void>((resolve, reject) => {
let process: ChildProcess;
try {
process = spawn(vsCodeScriptPath, ['--install-extension', vsixLocation, '--force']);
// Timeout the process if no response is sent back. Ensures this Promise resolves/rejects
const timer: NodeJS.Timer = setTimeout(() => {
process.kill();
reject(new Error('Failed to receive response from VS Code script process for installation within 30s.'));
}, 30000);
process.on('exit', (code: number) => {
clearInterval(timer);
if (code !== 0) {
@@ -563,14 +728,14 @@ async function suggestInsidersChannel(): Promise<void> {
}
}
function applyUpdate(buildInfo: BuildInfo, updateChannel: string): Promise<void> {
function applyUpdate(buildInfo: BuildInfo): Promise<void> {
return new Promise<void>((resolve, reject) => {
tmp.file({postfix: '.vsix'}, async (err, vsixPath, fd, cleanupCallback) => {
if (err) {
reject(new Error('Failed to create vsix file'));
return;
}
// Place in try/catch as the .catch call catches a rejection in downloadFileToDestination
// then the .catch call will return a resolved promise
// Thusly, the .catch call must also throw, as a return would simply return an unused promise
@@ -601,7 +766,7 @@ function applyUpdate(buildInfo: BuildInfo, updateChannel: string): Promise<void>
break;
}
try {
await installVsix(vsixPath, updateChannel);
await installVsix(vsixPath);
} catch (error) {
reject(error);
return;
@@ -632,7 +797,7 @@ async function checkAndApplyUpdate(updateChannel: string): Promise<void> {
let buildInfo: BuildInfo | null = buildInfoCache;
// clear buildInfo cache.
buildInfoCache = null;
if (!buildInfo) {
try {
buildInfo = await getTargetBuildInfo(updateChannel);
@@ -643,7 +808,7 @@ async function checkAndApplyUpdate(updateChannel: string): Promise<void> {
if (!buildInfo) {
return; // No need to update.
}
await applyUpdate(buildInfo, updateChannel);
await applyUpdate(buildInfo);
}
/*********************************************
@@ -655,17 +820,17 @@ export function registerCommands(): void {
if (commandsRegistered) {
return;
}
commandsRegistered = true;
getTemporaryCommandRegistrarInstance().clearTempCommands();
disposables.push(vscode.commands.registerCommand('C_Cpp.Navigate', onNavigate));
disposables.push(vscode.commands.registerCommand('C_Cpp.GoToDeclaration', onGoToDeclaration));
disposables.push(vscode.commands.registerCommand('C_Cpp.PeekDeclaration', onPeekDeclaration));
disposables.push(vscode.commands.registerCommand('C_Cpp.SwitchHeaderSource', onSwitchHeaderSource));
disposables.push(vscode.commands.registerCommand('C_Cpp.ResetDatabase', onResetDatabase));
disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationSelect', onSelectConfiguration));
disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationProviderSelect', onSelectConfigurationProvider));
disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEditJSON', onEditConfigurationJSON));
disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEditUI', onEditConfigurationUI));
disposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEdit', onEditConfiguration));
disposables.push(vscode.commands.registerCommand('C_Cpp.AddToIncludePath', onAddToIncludePath));
disposables.push(vscode.commands.registerCommand('C_Cpp.EnableErrorSquiggles', onEnableSquiggles));
disposables.push(vscode.commands.registerCommand('C_Cpp.DisableErrorSquiggles', onDisableSquiggles));
@@ -675,8 +840,12 @@ export function registerCommands(): void {
disposables.push(vscode.commands.registerCommand('C_Cpp.PauseParsing', onPauseParsing));
disposables.push(vscode.commands.registerCommand('C_Cpp.ResumeParsing', onResumeParsing));
disposables.push(vscode.commands.registerCommand('C_Cpp.ShowParsingCommands', onShowParsingCommands));
disposables.push(vscode.commands.registerCommand('C_Cpp.ShowReferencesProgress', onShowReferencesProgress));
disposables.push(vscode.commands.registerCommand('C_Cpp.TakeSurvey', onTakeSurvey));
disposables.push(vscode.commands.registerCommand('C_Cpp.LogDiagnostics', onLogDiagnostics));
disposables.push(vscode.commands.registerCommand('C_Cpp.RescanWorkspace', onRescanWorkspace));
disposables.push(vscode.commands.registerCommand('C_Cpp.VcpkgClipboardInstallSuggested', onVcpkgClipboardInstallSuggested));
disposables.push(vscode.commands.registerCommand('C_Cpp.VcpkgOnlineHelpSuggested', onVcpkgOnlineHelpSuggested));
disposables.push(vscode.commands.registerCommand('cpptools.activeConfigName', onGetActiveConfigName));
getTemporaryCommandRegistrarInstance().executeDelayedCommands();
}
@@ -693,16 +862,6 @@ function onNavigate(): void {
});
}
function onGoToDeclaration(): void {
onActivationEvent();
clients.ActiveClient.requestGoToDeclaration().then(() => vscode.commands.executeCommand("editor.action.goToDeclaration"));
}
function onPeekDeclaration(): void {
onActivationEvent();
clients.ActiveClient.requestGoToDeclaration().then(() => vscode.commands.executeCommand("editor.action.previewDeclaration"));
}
function onSwitchHeaderSource(): void {
onActivationEvent();
let activeEditor: vscode.TextEditor = vscode.window.activeTextEditor;
@@ -812,6 +971,15 @@ function onEditConfigurationUI(): void {
}
}
function onEditConfiguration(): void {
onActivationEvent();
if (!isFolderOpen()) {
vscode.window.showInformationMessage('Open a folder first to edit configurations');
} else {
selectClient().then(client => client.handleConfigurationEditCommand(), rejected => {});
}
}
function onAddToIncludePath(path: string): void {
if (!isFolderOpen()) {
vscode.window.showInformationMessage('Open a folder first to add to includePath');
@@ -870,6 +1038,11 @@ function onShowParsingCommands(): void {
selectClient().then(client => client.handleShowParsingCommands(), rejected => {});
}
function onShowReferencesProgress(): void {
onActivationEvent();
selectClient().then(client => client.handleReferencesIcon(), rejected => {});
}
function onTakeSurvey(): void {
onActivationEvent();
telemetry.logLanguageServerEvent("onTakeSurvey");
@@ -877,6 +1050,67 @@ function onTakeSurvey(): void {
vscode.commands.executeCommand('vscode.open', uri);
}
function onVcpkgOnlineHelpSuggested(dummy?: any): void {
telemetry.logLanguageServerEvent('vcpkgAction', { 'source': dummy ? 'CodeAction' : 'CommandPalette', 'action': 'vcpkgOnlineHelpSuggested' });
const uri: vscode.Uri = vscode.Uri.parse(`https://aka.ms/vcpkg`);
vscode.commands.executeCommand('vscode.open', uri);
}
async function onVcpkgClipboardInstallSuggested(ports?: string[]): Promise<void> {
onActivationEvent();
let source: string;
if (ports && ports.length) {
source = 'CodeAction';
} else {
source = 'CommandPalette';
// Glob up all existing diagnostics for missing includes and look them up in the vcpkg database
const missingIncludeLocations: [vscode.TextDocument, number[]][] = [];
vscode.languages.getDiagnostics().forEach(uriAndDiagnostics => {
// Extract textDocument
const textDocument: vscode.TextDocument = vscode.workspace.textDocuments.find(doc => doc.uri.fsPath === uriAndDiagnostics[0].fsPath);
if (!textDocument) {
return;
}
// Extract lines numbers for missing include diagnostics
let lines: number[] = uriAndDiagnostics[1].filter(isMissingIncludeDiagnostic).map<number>(d => d.range.start.line);
if (!lines.length) {
return;
}
// Filter duplicate lines
lines = lines.filter((line: number, index: number) => {
const foundIndex: number = lines.indexOf(line);
return foundIndex === index;
});
missingIncludeLocations.push([textDocument, lines]);
});
if (!missingIncludeLocations.length) {
return;
}
// Queue look ups in the vcpkg database for missing ports; filter out duplicate results
let portsPromises: Promise<string[]>[] = [];
missingIncludeLocations.forEach(docAndLineNumbers => {
docAndLineNumbers[1].forEach(async line => {
portsPromises.push(lookupIncludeInVcpkg(docAndLineNumbers[0], line));
});
});
ports = [].concat(...(await Promise.all(portsPromises)));
if (!ports.length) {
return;
}
ports = ports.filter((port: string, index: number) => ports.indexOf(port) === index);
}
let installCommand: string = 'vcpkg install';
ports.forEach(port => installCommand += ` ${port}`);
telemetry.logLanguageServerEvent('vcpkgAction', { 'source': source, 'action': 'vcpkgClipboardInstallSuggested', 'ports': ports.toString() });
await vscode.env.clipboard.writeText(installCommand);
}
function onGetActiveConfigName(): Thenable<string> {
return clients.ActiveClient.getCurrentConfigName();
}
@@ -886,6 +1120,11 @@ function onLogDiagnostics(): void {
clients.ActiveClient.logDiagnostics();
}
function onRescanWorkspace(): void {
onActivationEvent();
clients.forEach(client => client.rescanFolder());
}
function reportMacCrashes(): void {
if (process.platform === "darwin") {
prevCrashFile = "";
@@ -942,6 +1181,16 @@ function handleCrashFileRead(err: NodeJS.ErrnoException, data: string): void {
return logCrashTelemetry("readFile: " + err.code);
}
// Extract the crashing process version, because the version might not match
// if multiple VS Codes are running with different extension versions.
let binaryVersion: string = "";
let startVersion: number = data.indexOf("Version:");
if (startVersion >= 0) {
data = data.substr(startVersion);
const binaryVersionMatches: string[] = data.match(/^Version:\s*(\d*\.\d*\.\d*\.\d*|\d)/);
binaryVersion = binaryVersionMatches && binaryVersionMatches.length > 1 ? binaryVersionMatches[1] : "";
}
// Extract the crashing thread's call stack.
const crashStart: string = " Crashed:";
let startCrash: number = data.indexOf(crashStart);
@@ -957,7 +1206,7 @@ function handleCrashFileRead(err: NodeJS.ErrnoException, data: string): void {
return logCrashTelemetry("No crash end");
}
data = data.substr(startCrash, endCrash - startCrash);
// Get rid of the memory addresses (which breaks being able get a hit count for each crash call stack).
data = data.replace(/0x................ /g, "");
data = data.replace(/0x1........ \+ 0/g, "");
@@ -967,10 +1216,10 @@ function handleCrashFileRead(err: NodeJS.ErrnoException, data: string): void {
const process2: string = "Microsoft.VSCode.CPP.Extension.darwin\t";
if (data.includes(process1)) {
data = data.replace(new RegExp(process1, "g"), "");
data = process1 + "\n" + data;
data = `${process1}${binaryVersion}\n${data}`;
} else if (data.includes(process2)) {
data = data.replace(new RegExp(process2, "g"), "");
data = process2 + "\n" + data;
data = `${process2}${binaryVersion}\n${data}`;
} else {
return logCrashTelemetry("No process"); // Not expected, but just in case.
}
@@ -1005,6 +1254,9 @@ export function deactivate(): Thenable<void> {
if (taskProvider) {
taskProvider.dispose();
}
if (codeActionProvider) {
codeActionProvider.dispose();
}
return clients.dispose();
}
@@ -162,7 +162,7 @@ function getMLContinuationRule(comment: CommentPattern): vscode.OnEnterRule | un
return undefined;
}
// When Enter is pressed while the cursor is after '*/' (and '*/' plus leading whitespace is all that is on the line)
// When Enter is pressed while the cursor is after '*/' (and '*/' plus leading whitespace is all that is on the line)
function getMLEndRule(comment: CommentPattern): vscode.OnEnterRule | undefined {
if (comment) {
let endPattern: string = getMLEndPattern(comment.continue);
@@ -318,4 +318,4 @@ function constructCommentRules(comment: CommentPattern, languageId: string): Rul
continue: [],
end: []
};
}
}
@@ -12,19 +12,24 @@ class PersistentStateBase<T> {
private key: string;
private defaultvalue: T;
private state: vscode.Memento;
private curvalue: T;
constructor(key: string, defaultValue: T, state: vscode.Memento) {
this.key = key;
this.defaultvalue = defaultValue;
this.state = state;
this.curvalue = defaultValue;
}
public get Value(): T {
return this.state.get<T>(this.key, this.defaultvalue);
return this.state ? this.state.get<T>(this.key, this.defaultvalue) : this.curvalue;
}
public set Value(newValue: T) {
this.state.update(this.key, newValue);
if (this.state) {
this.state.update(this.key, newValue);
}
this.curvalue = newValue;
}
public get DefaultValue(): T {
@@ -35,13 +40,13 @@ class PersistentStateBase<T> {
// Abstraction for global state that persists across activations but is not present in a settings file
export class PersistentState<T> extends PersistentStateBase<T> {
constructor(key: string, defaultValue: T) {
super(key, defaultValue, util.extensionContext.globalState);
super(key, defaultValue, util.extensionContext ? util.extensionContext.globalState : null);
}
}
export class PersistentWorkspaceState<T> extends PersistentStateBase<T> {
constructor(key: string, defaultValue: T) {
super(key, defaultValue, util.extensionContext.workspaceState);
super(key, defaultValue, util.extensionContext ? util.extensionContext.workspaceState : null);
}
}
+19 -6
View File
@@ -4,6 +4,7 @@
* ------------------------------------------------------------------------------------------ */
'use strict';
import * as path from 'path';
import { Middleware } from 'vscode-languageclient';
import { ClientCollection } from './clientCollection';
import { Client } from './client';
@@ -23,14 +24,25 @@ export function createProtocolFilter(me: Client, clients: ClientCollection): Mid
didOpen: (document, sendMessage) => {
if (clients.checkOwnership(me, document)) {
me.TrackedDocuments.add(document);
me.provideCustomConfiguration(document).then(() => {
sendMessage(document);
}, () => {
sendMessage(document);
});
// Work around vscode treating ".C" as c, by adding this file name to file associations as cpp
if (document.uri.path.endsWith(".C")) {
let fileName: string = path.basename(document.uri.fsPath);
let mappingString: string = fileName + "@" + document.uri.fsPath;
me.addFileAssociations(mappingString, false);
}
me.onDidOpenTextDocument(document);
me.provideCustomConfiguration(document.uri, null);
me.notifyWhenReady(() => sendMessage(document));
}
},
didChange: (textDocumentChangeEvent, sendMessage) => {
if (clients.ActiveClient === me) {
me.onDidChangeTextDocument(textDocumentChangeEvent);
me.notifyWhenReady(() => sendMessage(textDocumentChangeEvent));
}
},
didChange: defaultHandler,
willSave: defaultHandler,
willSaveWaitUntil: (event, sendMessage) => {
if (clients.ActiveClient === me) {
@@ -70,6 +82,7 @@ export function createProtocolFilter(me: Client, clients: ClientCollection): Mid
provideRenameEdits: invoke4,
provideDocumentLinks: invoke2,
resolveDocumentLink: invoke2,
provideDeclaration: invoke3
// I believe the default handler will do the same thing.
// workspace: {
+38 -6
View File
@@ -29,20 +29,20 @@ export class CppSettings extends Settings {
constructor(resource?: vscode.Uri) {
super("C_Cpp", resource);
}
public get clangFormatPath(): string { return super.Section.get<string>("clang_format_path"); }
public get clangFormatStyle(): string { return super.Section.get<string>("clang_format_style"); }
public get clangFormatFallbackStyle(): string { return super.Section.get<string>("clang_format_fallbackStyle"); }
public get clangFormatSortIncludes(): string { return super.Section.get<string>("clang_format_sortIncludes"); }
public get clangFormatOnSave(): string { return super.Section.get<string>("clang_format_formatOnSave"); }
public get formatting(): string { return super.Section.get<string>("formatting"); }
public get experimentalFeatures(): string { return super.Section.get<string>("experimentalFeatures"); }
public get suggestSnippets(): boolean { return super.Section.get<boolean>("suggestSnippets"); }
public get intelliSenseEngine(): string { return super.Section.get<string>("intelliSenseEngine"); }
public get intelliSenseEngineFallback(): string { return super.Section.get<string>("intelliSenseEngineFallback"); }
public get intelliSenseCachePath(): string { return super.Section.get<string>("intelliSenseCachePath"); }
public get intelliSenseCacheSize(): number { return super.Section.get<number>("intelliSenseCacheSize"); }
public get errorSquiggles(): string { return super.Section.get<string>("errorSquiggles"); }
public get dimInactiveRegions(): boolean { return super.Section.get<boolean>("dimInactiveRegions"); }
public get inactiveRegionOpacity(): number { return super.Section.get<number>("inactiveRegionOpacity"); }
public get inactiveRegionForegroundColor(): string { return super.Section.get<string>("inactiveRegionForegroundColor"); }
public get inactiveRegionBackgroundColor(): string { return super.Section.get<string>("inactiveRegionBackgroundColor"); }
@@ -57,6 +57,7 @@ export class CppSettings extends Settings {
public get configurationWarnings(): string { return super.Section.get<string>("configurationWarnings"); }
public get preferredPathSeparator(): string { return super.Section.get<string>("preferredPathSeparator"); }
public get updateChannel(): string { return super.Section.get<string>("updateChannel"); }
public get vcpkgEnabled(): boolean { return super.Section.get<boolean>("vcpkg.enabled"); }
public get defaultIncludePath(): string[] { return super.Section.get<string[]>("default.includePath"); }
public get defaultDefines(): string[] { return super.Section.get<string[]>("default.defines"); }
public get defaultMacFrameworkPath(): string[] { return super.Section.get<string[]>("default.macFrameworkPath"); }
@@ -65,6 +66,7 @@ export class CppSettings extends Settings {
public get defaultForcedInclude(): string[] { return super.Section.get<string[]>("default.forcedInclude"); }
public get defaultIntelliSenseMode(): string { return super.Section.get<string>("default.intelliSenseMode"); }
public get defaultCompilerPath(): string { return super.Section.get<string>("default.compilerPath"); }
public get defaultCompilerArgs(): string[] { return super.Section.get<string[]>("default.compilerArgs"); }
public get defaultCStandard(): string { return super.Section.get<string>("default.cStandard"); }
public get defaultCppStandard(): string { return super.Section.get<string>("default.cppStandard"); }
public get defaultConfigurationProvider(): string { return super.Section.get<string>("default.configurationProvider"); }
@@ -74,6 +76,18 @@ export class CppSettings extends Settings {
public get defaultSystemIncludePath(): string[] { return super.Section.get<string[]>("default.systemIncludePath"); }
public get defaultEnableConfigurationSquiggles(): boolean { return super.Section.get<boolean>("default.enableConfigurationSquiggles"); }
public get enhancedColorization(): boolean {
return super.Section.get<string>("enhancedColorization") === "Enabled"
&& super.Section.get<string>("intelliSenseEngine") === "Default"
&& vscode.workspace.getConfiguration("workbench").get<string>("colorTheme") !== "Default High Contrast";
}
public get dimInactiveRegions(): boolean {
return super.Section.get<boolean>("dimInactiveRegions")
&& super.Section.get<string>("intelliSenseEngine") === "Default"
&& vscode.workspace.getConfiguration("workbench").get<string>("colorTheme") !== "Default High Contrast";
}
public toggleSetting(name: string, value1: string, value2: string): void {
let value: string = super.Section.get<string>(name);
super.Section.update(name, value === value1 ? value2 : value1, getTarget());
@@ -83,6 +97,17 @@ export class CppSettings extends Settings {
}
}
export interface TextMateRuleSettings {
foreground: string | undefined;
background: string | undefined;
fontStyle: string | undefined;
}
export interface TextMateRule {
scope: any;
settings: TextMateRuleSettings;
}
export class OtherSettings {
private resource: vscode.Uri;
@@ -95,11 +120,18 @@ export class OtherSettings {
public get editorTabSize(): number { return vscode.workspace.getConfiguration("editor", this.resource).get<number>("tabSize"); }
public get filesAssociations(): any { return vscode.workspace.getConfiguration("files", null).get("associations"); }
public set filesAssociations(value: any) {
vscode.workspace.getConfiguration("files", null).update("associations", value, vscode.ConfigurationTarget.Workspace);
}
public get filesExclude(): vscode.WorkspaceConfiguration { return vscode.workspace.getConfiguration("files", this.resource).get("exclude"); }
public get searchExclude(): vscode.WorkspaceConfiguration { return vscode.workspace.getConfiguration("search", this.resource).get("exclude"); }
public get settingsEditor(): string { return vscode.workspace.getConfiguration("workbench.settings").get<string>("editor"); }
public set filesAssociations(value: any) {
vscode.workspace.getConfiguration("files", null).update("associations", value, vscode.ConfigurationTarget.Workspace);
}
}
public get colorTheme(): string { return vscode.workspace.getConfiguration("workbench").get<string>("colorTheme"); }
public getCustomColorToken(colorTokenName: string): string { return vscode.workspace.getConfiguration("editor.tokenColorCustomizations").get<string>(colorTokenName); }
public getCustomThemeSpecificColorToken(themeName: string, colorTokenName: string): string { return vscode.workspace.getConfiguration(`editor.tokenColorCustomizations.[${themeName}]`, this.resource).get<string>(colorTokenName); }
public get customTextMateRules(): TextMateRule[] { return vscode.workspace.getConfiguration("editor.tokenColorCustomizations").get<TextMateRule[]>("textMateRules"); }
public getCustomThemeSpecificTextMateRules(themeName: string): TextMateRule[] { return vscode.workspace.getConfiguration(`editor.tokenColorCustomizations.[${themeName}]`, this.resource).get<TextMateRule[]>("textMateRules"); }
}
+207 -64
View File
@@ -9,30 +9,65 @@ import * as fs from 'fs';
import * as vscode from 'vscode';
import * as util from '../common';
import * as config from './configurations';
import * as telemetry from '../telemetry';
// TODO: share ElementId between SettingsPanel and SettingsApp. Investigate why SettingsApp cannot import/export
const elementId: { [key: string]: string } = {
activeConfig: "activeConfig",
// Basic settings
configName: "configName",
configSelection: "configSelection",
addConfigBtn: "addConfigBtn",
addConfigOk: "addConfigOk",
addConfigCancel: "addConfigCancel",
addConfigName: "addConfigName",
compilerPath: "compilerPath",
intelliSenseMode: "intelliSenseMode",
compilerPathInvalid: "compilerPathInvalid",
knownCompilers: "knownCompilers",
compilerArgs: "compilerArgs",
intelliSenseMode: "intelliSenseMode",
intelliSenseModeInvalid: "intelliSenseModeInvalid",
includePath: "includePath",
includePathInvalid: "includePathInvalid",
defines: "defines",
cStandard: "cStandard",
cppStandard: "cppStandard"
cppStandard: "cppStandard",
// Advanced settings
windowsSdkVersion: "windowsSdkVersion",
macFrameworkPath: "macFrameworkPath",
compileCommands: "compileCommands",
configurationProvider: "configurationProvider",
forcedInclude: "forcedInclude",
// Browse properties
browsePath: "browsePath",
limitSymbolsToIncludedHeaders: "limitSymbolsToIncludedHeaders",
databaseFilename: "databaseFilename",
// Other
showAdvancedBtn: "showAdvancedBtn"
};
export interface ViewStateEvent {
isActive: boolean;
isDirty: boolean;
}
export class SettingsPanel {
private telemetry: { [key: string]: number } = {};
private disposable: vscode.Disposable = undefined;
// Events
private settingsPanelActivated = new vscode.EventEmitter<void>();
private configValuesChanged = new vscode.EventEmitter<void>();
private configSelectionChanged = new vscode.EventEmitter<void>();
private addConfigRequested = new vscode.EventEmitter<string>();
// Configuration data
private configValues: config.Configuration;
private isIntelliSenseModeDefined: boolean = false;
private configDirty: boolean = false;
private settingsPanelViewStateChanged = new vscode.EventEmitter<ViewStateEvent>();
private configIndexSelected: number = 0;
private compilerPaths: string[] = [];
// WebviewPanel objects
private panel: vscode.WebviewPanel;
private disposable: vscode.Disposable = undefined;
private disposablesPanel: vscode.Disposable = undefined;
private static readonly viewType: string = 'settingsPanel';
private static readonly title: string = 'C/C++ Configurations';
@@ -40,12 +75,14 @@ export class SettingsPanel {
constructor() {
this.configValues = { name: undefined };
this.disposable = vscode.Disposable.from(
this.settingsPanelViewStateChanged,
vscode.window.onDidChangeWindowState(this.onWindowStateChanged, this)
this.settingsPanelActivated,
this.configValuesChanged,
this.configSelectionChanged,
this.addConfigRequested
);
}
public createOrShow(activeConfiguration: config.Configuration): void {
public createOrShow(configSelection: string[], activeConfiguration: config.Configuration, errors: config.ConfigurationErrors): void {
const column: vscode.ViewColumn = vscode.window.activeTextEditor
? vscode.window.activeTextEditor.viewColumn
: undefined;
@@ -67,9 +104,9 @@ export class SettingsPanel {
// Restrict the webview to only loading content from these directories
localResourceRoots: [
vscode.Uri.file(util.extensionContext.extensionPath),
vscode.Uri.file(path.join(util.extensionContext.extensionPath, 'ui')),
vscode.Uri.file(path.join(util.extensionContext.extensionPath, 'out', 'ui'))]
vscode.Uri.file(util.extensionPath),
vscode.Uri.file(path.join(util.extensionPath, 'ui')),
vscode.Uri.file(path.join(util.extensionPath, 'out', 'ui'))]
}
);
@@ -79,40 +116,79 @@ export class SettingsPanel {
this.panel,
this.panel.onDidDispose(this.onPanelDisposed, this),
this.panel.onDidChangeViewState(this.onViewStateChanged, this),
this.panel.webview.onDidReceiveMessage(this.onMessageReceived, this)
this.panel.webview.onDidReceiveMessage(this.onMessageReceived, this),
vscode.window.onDidChangeWindowState(this.onWindowStateChanged, this)
);
this.panel.webview.html = this.getHtml();
this.updateWebview(activeConfiguration);
this.updateWebview(configSelection, activeConfiguration, errors);
}
public get SettingsPanelViewStateChanged(): vscode.Event<ViewStateEvent> {
return this.settingsPanelViewStateChanged.event;
public get SettingsPanelActivated(): vscode.Event<void> {
return this.settingsPanelActivated.event;
}
public isDirty(): boolean {
return this.configDirty;
public get ConfigValuesChanged(): vscode.Event<void> {
return this.configValuesChanged.event;
}
public get ConfigSelectionChanged(): vscode.Event<void> {
return this.configSelectionChanged.event;
}
public get AddConfigRequested(): vscode.Event<string> {
return this.addConfigRequested.event;
}
public get selectedConfigIndex(): number {
return this.configIndexSelected;
}
public set selectedConfigIndex(index: number) {
this.configIndexSelected = index;
}
public getLastValuesFromConfigUI(): config.Configuration {
return this.configValues;
}
public updateConfigUI(configuration: config.Configuration): void {
public updateConfigUI(configSelection: string[], configuration: config.Configuration, errors: config.ConfigurationErrors|null): void {
if (this.panel) {
this.updateWebview(configuration);
this.updateWebview(configSelection, configuration, errors);
}
}
//TODO: validate input paths
// public validatePaths(invalid: boolean) {
// if (this.panel) {
// this.panel.webview.postMessage({ command: 'validateCompilerPath', invalid: invalid });
// }
// }
public setKnownCompilers(knownCompilers: config.KnownCompiler[], pathSeparator: string): void {
if (knownCompilers && knownCompilers.length) {
for (let compiler of knownCompilers) {
// Normalize path separators.
let path: string = compiler.path;
if (pathSeparator === "Forward Slash") {
path = path.replace(/\\/g, '/');
} else {
path = path.replace(/\//g, '\\');
}
// Do not add duplicate paths in case the default compilers for cpp and c are the same.
if (this.compilerPaths.indexOf(path) === -1) {
this.compilerPaths.push(path);
}
}
}
}
public updateErrors(errors: config.ConfigurationErrors): void {
if (this.panel) {
this.panel.webview.postMessage({ command: 'updateErrors', errors: errors});
}
}
public dispose(): void {
// Log any telemetry
if (Object.keys(this.telemetry).length) {
telemetry.logLanguageServerEvent("ConfigUI", null, this.telemetry);
}
// Clean up resources
this.panel.dispose();
@@ -120,47 +196,40 @@ export class SettingsPanel {
this.disposable.dispose();
}
if (this.disposablesPanel) {
this.disposablesPanel.dispose();
if (this.disposablesPanel) {
this.disposablesPanel.dispose();
}
}
private onPanelDisposed(): void {
// Notify listener config panel is not active
if (this.configDirty) {
let viewState: ViewStateEvent = { isActive: false, isDirty: this.configDirty };
this.settingsPanelViewStateChanged.fire(viewState);
}
if (this.disposablesPanel) {
this.disposablesPanel.dispose();
if (this.disposablesPanel) {
this.disposablesPanel.dispose();
this.panel = undefined;
}
}
private updateWebview(configuration: config.Configuration): void {
this.configValues = Object.assign({}, configuration); // Copy configuration values
private updateWebview(configSelection: string[], configuration: config.Configuration, errors: config.ConfigurationErrors|null): void {
this.configValues = {...configuration}; // Copy configuration values
this.isIntelliSenseModeDefined = (this.configValues.intelliSenseMode !== undefined);
if (this.panel) {
// Send a message to the webview to update the values
this.panel.webview.postMessage({ command: 'update', config: this.configValues });
this.configDirty = false;
this.panel.webview.postMessage({ command: 'setKnownCompilers', compilers: this.compilerPaths });
this.panel.webview.postMessage({ command: 'updateConfigSelection', selections: configSelection, selectedIndex: this.configIndexSelected });
this.panel.webview.postMessage({ command: 'updateConfig', config: this.configValues });
if (errors !== null) {
this.panel.webview.postMessage({ command: 'updateErrors', errors: errors });
}
}
}
private onViewStateChanged(e: vscode.WebviewPanelOnDidChangeViewStateEvent): void {
let viewState: ViewStateEvent = { isActive: e.webviewPanel.active, isDirty: this.configDirty };
if (this.configDirty || e.webviewPanel.active) {
this.settingsPanelViewStateChanged.fire(viewState);
this.configDirty = false;
if (e.webviewPanel.active) {
this.settingsPanelActivated.fire();
}
}
private onWindowStateChanged(e: vscode.WindowState): void {
let viewState: ViewStateEvent = { isActive: this.panel.active, isDirty: this.configDirty };
if (this.configDirty || this.panel.active) {
this.settingsPanelViewStateChanged.fire(viewState);
this.configDirty = false;
if (e.focused) {
this.settingsPanelActivated.fire();
}
}
@@ -171,27 +240,58 @@ export class SettingsPanel {
switch (message.command) {
case 'change':
this.updateConfig(message);
break;
case 'configSelect':
this.configSelect(message.index);
break;
case 'addConfig':
this.addConfig(message.name);
break;
case 'knownCompilerSelect':
this.knownCompilerSelect();
break;
}
}
private addConfig(name: string): void {
this.addConfigRequested.fire(name);
this.logTelemetryForElement(elementId.addConfigName);
}
private configSelect(index: number): void {
this.configIndexSelected = index;
this.configSelectionChanged.fire();
this.logTelemetryForElement(elementId.configSelection);
}
private knownCompilerSelect(): void {
this.logTelemetryForElement(elementId.knownCompilers);
// Remove one count from compilerPath because selecting a different compiler causes a change on the compiler path
if (this.telemetry[elementId.compilerPath]) {
this.telemetry[elementId.compilerPath]--;
}
}
private updateConfig(message: any): void {
let entries: string[];
this.configDirty = true;
let splitEntries: (input: any) => string[] = (input: any) => {
return input.split("\n").filter((e: string) => e);
};
switch (message.key) {
case elementId.activeConfig:
case elementId.configName:
this.configValues.name = message.value;
break;
case elementId.compilerPath:
this.configValues.compilerPath = message.value;
break;
case elementId.compilerArgs:
this.configValues.compilerArgs = splitEntries(message.value);
break;
case elementId.includePath:
entries = message.value.split("\n");
this.configValues.includePath = entries.filter(e => e);
this.configValues.includePath = splitEntries(message.value);
break;
case elementId.defines:
entries = message.value.split("\n");
this.configValues.defines = entries.filter(e => e);
this.configValues.defines = splitEntries(message.value);
break;
case elementId.intelliSenseMode:
if (message.value !== "${default}" || this.isIntelliSenseModeDefined) {
@@ -206,6 +306,49 @@ export class SettingsPanel {
case elementId.cppStandard:
this.configValues.cppStandard = message.value;
break;
case elementId.windowsSdkVersion:
this.configValues.windowsSdkVersion = message.value;
break;
case elementId.macFrameworkPath:
this.configValues.macFrameworkPath = splitEntries(message.value);
break;
case elementId.compileCommands:
this.configValues.compileCommands = message.value;
break;
case elementId.configurationProvider:
this.configValues.configurationProvider = message.value;
break;
case elementId.forcedInclude:
this.configValues.forcedInclude = splitEntries(message.value);
break;
case elementId.browsePath:
this.initializeBrowseProperties();
this.configValues.browse.path = splitEntries(message.value);
break;
case elementId.limitSymbolsToIncludedHeaders:
this.initializeBrowseProperties();
this.configValues.browse.limitSymbolsToIncludedHeaders = message.value;
break;
case elementId.databaseFilename:
this.initializeBrowseProperties();
this.configValues.browse.databaseFilename = message.value;
break;
}
this.configValuesChanged.fire();
this.logTelemetryForElement(message.key);
}
private logTelemetryForElement(elementId: string): void {
if (this.telemetry[elementId] === undefined) {
this.telemetry[elementId] = 0;
}
this.telemetry[elementId]++;
}
private initializeBrowseProperties(): void {
if (this.configValues.browse === undefined) {
this.configValues.browse = {};
}
}
@@ -214,13 +357,13 @@ export class SettingsPanel {
content = fs.readFileSync(util.getExtensionFilePath("ui/settings.html")).toString();
content = content.replace(
/{{root}}/g,
vscode.Uri.file(util.extensionContext.extensionPath)
/{{root}}/g,
vscode.Uri.file(util.extensionPath)
.with({ scheme: 'vscode-resource' })
.toString());
content = content.replace(
/{{nonce}}/g,
/{{nonce}}/g,
this.getNonce());
return content;
@@ -14,7 +14,7 @@ type FilterFunction = (key: string, val: string, settings: vscode.WorkspaceConfi
type KeyValuePair = { key: string; value: string };
const maxSettingLengthForTelemetry: number = 50;
let cache: SettingsTracker = undefined;
let cache: SettingsTracker;
export class SettingsTracker {
private previousCppSettings: { [key: string]: any } = {};
+42 -7
View File
@@ -5,7 +5,7 @@
'use strict';
import * as vscode from 'vscode';
import { Client } from './client';
import { Client, ReferencesCommandMode, referencesCommandModeToString } from './client';
import { getCustomConfigProviders, CustomConfigurationProviderCollection } from './customProviders';
let ui: UI;
@@ -34,7 +34,9 @@ export class UI {
private configStatusBarItem: vscode.StatusBarItem;
private browseEngineStatusBarItem: vscode.StatusBarItem;
private intelliSenseStatusBarItem: vscode.StatusBarItem;
private referencesStatusBarItem: vscode.StatusBarItem;
private configurationUIPromise: Thenable<ConfigurationResult>;
private readonly referencesPreviewTooltip: string = " (click to preview results)";
constructor() {
// 1000 = priority, it needs to be high enough to be on the left of the Ln/Col.
@@ -43,11 +45,18 @@ export class UI {
this.navigationStatusBarItem.command = "C_Cpp.Navigate";
this.ShowNavigation = true;
this.configStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 2);
this.configStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 3);
this.configStatusBarItem.command = "C_Cpp.ConfigurationSelect";
this.configStatusBarItem.tooltip = "C/C++ Configuration";
this.ShowConfiguration = true;
this.referencesStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 2);
this.referencesStatusBarItem.text = "";
this.referencesStatusBarItem.tooltip = "";
this.referencesStatusBarItem.color = new vscode.ThemeColor("statusBar.foreground");
this.referencesStatusBarItem.command = "C_Cpp.ShowReferencesProgress";
this.ShowReferencesIcon = true;
this.intelliSenseStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 1);
this.intelliSenseStatusBarItem.text = "";
this.intelliSenseStatusBarItem.tooltip = "Updating IntelliSense...";
@@ -85,11 +94,28 @@ export class UI {
private get IsUpdatingIntelliSense(): boolean {
return this.intelliSenseStatusBarItem.text !== "";
}
private set IsUpdatingIntelliSense(val: boolean) {
this.intelliSenseStatusBarItem.text = val ? "$(flame)" : "";
this.ShowFlameIcon = val;
}
private get ReferencesCommand(): ReferencesCommandMode {
return this.referencesStatusBarItem.tooltip === "" ? ReferencesCommandMode.None :
(this.referencesStatusBarItem.tooltip === referencesCommandModeToString(ReferencesCommandMode.Peek) ? ReferencesCommandMode.Peek : ReferencesCommandMode.Find);
}
private set ReferencesCommand(val: ReferencesCommandMode) {
if (val === ReferencesCommandMode.None) {
this.referencesStatusBarItem.text = "";
this.ShowReferencesIcon = false;
} else {
this.referencesStatusBarItem.text = "$(search)";
this.referencesStatusBarItem.tooltip = referencesCommandModeToString(val) + (val === ReferencesCommandMode.Find ? this.referencesPreviewTooltip : "");
this.ShowReferencesIcon = true;
}
}
private set ShowNavigation(show: boolean) {
if (show) {
this.navigationStatusBarItem.show();
@@ -114,6 +140,14 @@ export class UI {
}
}
private set ShowReferencesIcon(show: boolean) {
if (show && this.ReferencesCommand !== ReferencesCommandMode.None) {
this.referencesStatusBarItem.show();
} else {
this.referencesStatusBarItem.hide();
}
}
private set ShowConfiguration(show: boolean) {
if (show) {
this.configStatusBarItem.show();
@@ -130,14 +164,13 @@ export class UI {
let isSettingsJson: boolean = (activeEditor && (activeEditor.document.fileName.endsWith("c_cpp_properties.json") || activeEditor.document.fileName.endsWith("settings.json")));
this.ShowConfiguration = isCpp || isSettingsJson;
this.ShowDBIcon = isCpp || isSettingsJson;
this.ShowFlameIcon = isCpp || isSettingsJson;
this.ShowNavigation = isCpp;
}
public bind(client: Client): void {
client.TagParsingChanged(value => { this.IsTagParsing = value; });
client.IntelliSenseParsingChanged(value => { this.IsUpdatingIntelliSense = value; });
client.ReferencesCommandModeChanged(value => { this.ReferencesCommand = value; });
client.NavigationLocationChanged(value => { this.NavigationLocation = value; });
client.TagParserStatusChanged(value => { this.TagParseStatus = value; });
client.ActiveConfigChanged(value => { this.ActiveConfig = value; });
@@ -171,7 +204,8 @@ export class UI {
for (let i: number = 0; i < configurationNames.length; i++) {
items.push({ label: configurationNames[i], description: "", index: i });
}
items.push({ label: "Edit Configurations...", description: "", index: configurationNames.length });
items.push({ label: "Edit Configurations (UI)", description: "", index: configurationNames.length });
items.push({ label: "Edit Configurations (JSON)", description: "", index: configurationNames.length + 1 });
return vscode.window.showQuickPick(items, options)
.then(selection => (selection) ? selection.index : -1);
@@ -231,7 +265,7 @@ export class UI {
} else {
items.push({ label: "Pause Parsing", description: "", index: 0 });
}
return vscode.window.showQuickPick(items, options)
.then(selection => (selection) ? selection.index : -1);
}
@@ -283,6 +317,7 @@ export class UI {
this.configStatusBarItem.dispose();
this.browseEngineStatusBarItem.dispose();
this.intelliSenseStatusBarItem.dispose();
this.referencesStatusBarItem.dispose();
this.navigationStatusBarItem.dispose();
}
}
@@ -292,4 +327,4 @@ export function getUI(): UI {
ui = new UI();
}
return ui;
}
}
+13 -3
View File
@@ -17,6 +17,7 @@ interface Settings {
defaultIntelliSenseEngine?: number;
recursiveIncludes?: number;
gotoDefIntelliSense?: number;
enhancedColorization?: number;
}
export class ABTestSettings {
@@ -24,16 +25,19 @@ export class ABTestSettings {
private intelliSenseEngineDefault: PersistentState<number>;
private recursiveIncludesDefault: PersistentState<number>;
private gotoDefIntelliSenseDefault: PersistentState<number>;
private enhancedColorizationDefault: PersistentState<number>;
private bucket: PersistentState<number>;
constructor() {
this.intelliSenseEngineDefault = new PersistentState<number>("ABTest.1", 100);
this.recursiveIncludesDefault = new PersistentState<number>("ABTest.2", 100);
this.gotoDefIntelliSenseDefault = new PersistentState<number>("ABTest.3", 100);
this.enhancedColorizationDefault = new PersistentState<number>("ABTest.4", 100);
this.settings = {
defaultIntelliSenseEngine: this.intelliSenseEngineDefault.Value,
recursiveIncludes: this.recursiveIncludesDefault.Value,
gotoDefIntelliSense: this.gotoDefIntelliSenseDefault.Value
gotoDefIntelliSense: this.gotoDefIntelliSenseDefault.Value,
enhancedColorization: this.enhancedColorizationDefault.Value
};
this.bucket = new PersistentState<number>(userBucketString, -1);
if (this.bucket.Value === -1) {
@@ -61,6 +65,10 @@ export class ABTestSettings {
return util.isNumber(this.settings.gotoDefIntelliSense) ? this.settings.gotoDefIntelliSense >= this.bucket.Value : true;
}
public get UseEnhancedColorization(): boolean {
return util.isNumber(this.settings.enhancedColorization) ? this.settings.enhancedColorization >= this.bucket.Value : true;
}
private updateSettings(): void {
const cpptoolsJsonFile: string = util.getExtensionFilePath(localConfigFile);
@@ -72,10 +80,12 @@ export class ABTestSettings {
this.intelliSenseEngineDefault.Value = util.isNumber(newSettings.defaultIntelliSenseEngine) ? newSettings.defaultIntelliSenseEngine : this.intelliSenseEngineDefault.DefaultValue;
this.recursiveIncludesDefault.Value = util.isNumber(newSettings.recursiveIncludes) ? newSettings.recursiveIncludes : this.recursiveIncludesDefault.DefaultValue;
this.gotoDefIntelliSenseDefault.Value = util.isNumber(newSettings.gotoDefIntelliSense) ? newSettings.gotoDefIntelliSense : this.gotoDefIntelliSenseDefault.DefaultValue;
this.enhancedColorizationDefault.Value = util.isNumber(newSettings.enhancedColorization) ? newSettings.enhancedColorization : this.enhancedColorizationDefault.DefaultValue;
this.settings = {
defaultIntelliSenseEngine: this.intelliSenseEngineDefault.Value,
recursiveIncludes: this.recursiveIncludesDefault.Value,
gotoDefIntelliSense: this.gotoDefIntelliSenseDefault.Value
gotoDefIntelliSense: this.gotoDefIntelliSenseDefault.Value,
enhancedColorization: this.enhancedColorizationDefault.Value
};
}
} catch (error) {
@@ -87,7 +97,7 @@ export class ABTestSettings {
let hasError: boolean = false;
let telemetryProperties: { [key: string]: string } = {};
const localConfigPath: string = util.getExtensionFilePath(localConfigFile);
return util.downloadFileToDestination("https://go.microsoft.com/fwlink/?linkid=2026205", localConfigPath)
return util.downloadFileToDestination("https://go.microsoft.com/fwlink/?linkid=2097702", localConfigPath)
.catch((error) => {
// More specific error info is not likely to be helpful, and we get detailed download data from the initial install.
hasError = true;
+13 -12
View File
@@ -6,6 +6,7 @@
import * as vscode from 'vscode';
import * as LanguageServer from './LanguageServer/extension';
import * as util from './common';
class TemporaryCommandRegistrar {
// Used to save/re-execute commands used before the extension has activated (e.g. delayed by dependency downloading).
@@ -21,19 +22,17 @@ class TemporaryCommandRegistrar {
"C_Cpp.ConfigurationProviderSelect",
"C_Cpp.SwitchHeaderSource",
"C_Cpp.Navigate",
"C_Cpp.GoToDeclaration",
"C_Cpp.PeekDeclaration",
"C_Cpp.EnableErrorSquiggles",
"C_Cpp.DisableErrorSquiggles",
"C_Cpp.ToggleIncludeFallback",
"C_Cpp.ToggleDimInactiveRegions",
"C_Cpp.ShowReleaseNotes",
"C_Cpp.ResetDatabase",
"C_Cpp.PauseParsing",
"C_Cpp.ResumeParsing",
"C_Cpp.ShowParsingCommands",
"C_Cpp.TakeSurvey",
"C_Cpp.LogDiagnostics"
"C_Cpp.LogDiagnostics",
"C_Cpp.RescanWorkspace",
"C_Cpp.VcpkgClipboardInstallSuggested",
"C_Cpp.VcpkgOnlineHelpSuggested"
];
constructor() {
@@ -41,15 +40,17 @@ class TemporaryCommandRegistrar {
this.delayedCommandsToExecute = new Set<string>();
// Add temp commands that invoke the real commands after download/install is complete (preventing an error message)
this.commandsToRegister.forEach(command => {
this.registerTempCommand(command);
});
if (util.extensionContext) {
this.commandsToRegister.forEach(command => {
this.registerTempCommand(command);
});
}
}
public registerTempCommand(command: string): void {
this.tempCommands.push(vscode.commands.registerCommand(command, () => {
if (this.isLanguageServerDisabled) {
vscode.window.showInformationMessage("The command is disabled because \"C_Cpp.intelliSenseEngine\" is set to \"Disabled\".");
vscode.window.showInformationMessage("This command is disabled because \"C_Cpp.intelliSenseEngine\" is set to \"Disabled\".");
return;
}
this.delayedCommandsToExecute.add(command);
@@ -68,7 +69,7 @@ class TemporaryCommandRegistrar {
LanguageServer.activate(this.delayedCommandsToExecute.size > 0);
this.isActivationReady = true;
}
public clearTempCommands(): void {
this.tempCommands.forEach((command) => {
command.dispose();
@@ -92,4 +93,4 @@ export function initializeTemporaryCommandRegistrar(): void {
export function getTemporaryCommandRegistrarInstance(): TemporaryCommandRegistrar {
return tempCommandRegistrar;
}
}
+129 -18
View File
@@ -19,9 +19,18 @@ import { ClientRequest, OutgoingHttpHeaders } from 'http';
import { getBuildTasks } from './LanguageServer/extension';
import { OtherSettings } from './LanguageServer/settings';
export type Mutable<T> = {
-readonly [P in keyof T]: T[P] extends ReadonlyArray<infer U> ? Mutable<U>[] : Mutable<T[P]>
};
export let extensionPath: string;
export let extensionContext: vscode.ExtensionContext;
export function setExtensionContext(context: vscode.ExtensionContext): void {
extensionContext = context;
extensionPath = extensionContext.extensionPath;
}
export function setExtensionPath(path: string): void {
extensionPath = path;
}
export const failedToParseTasksJson: string = "Failed to parse tasks.json, possibly due to comments or trailing commas.";
@@ -54,7 +63,7 @@ export function getRawTasksJson(): Promise<any> {
fileContents = fileContents.replace(/^\s*\/\/.*$/gm, ""); // Remove start of line // comments.
let rawTasks: any = {};
try {
rawTasks = JSON.parse(fileContents);
rawTasks = JSON.parse(fileContents);
} catch (error) {
return reject(new Error(failedToParseTasksJson));
}
@@ -84,10 +93,10 @@ export async function ensureBuildTaskExists(taskName: string): Promise<void> {
rawTasksJson.version = "2.0.0";
if (!rawTasksJson.tasks.find(task => { return task.label === selectedTask.definition.label; })) {
if (!rawTasksJson.tasks.find(task => task.label === selectedTask.definition.label)) {
rawTasksJson.tasks.push(selectedTask.definition);
}
// TODO: It's dangerous to overwrite this file. We could be wiping out comments.
let settings: OtherSettings = new OtherSettings();
await writeFileText(getTasksJsonPath(), JSON.stringify(rawTasksJson, null, settings.editorTabSize));
@@ -98,6 +107,11 @@ export function fileIsCOrCppSource(file: string): boolean {
return [".C", ".c", ".cpp", ".cc", ".cxx", ".mm", ".ino", ".inl"].some(ext => fileExtLower === ext);
}
export function isEditorFileCpp(file: string): boolean {
let editor: vscode.TextEditor = vscode.window.visibleTextEditors.find(e => e.document.uri.toString() === file);
return editor && editor.document.languageId === "cpp";
}
// This function is used to stringify the rawPackageJson.
// Do not use with util.packageJson or else the expanded
// package.json will be written back.
@@ -106,7 +120,7 @@ export function stringifyPackageJson(packageJson: string): string {
}
export function getExtensionFilePath(extensionfile: string): string {
return path.resolve(extensionContext.extensionPath, extensionfile);
return path.resolve(extensionPath, extensionfile);
}
export function getPackageJsonPath(): string {
@@ -195,15 +209,15 @@ let installProgressStr: string = "CPP." + packageJson.version + ".Progress";
let intelliSenseProgressStr: string = "CPP." + packageJson.version + ".IntelliSenseProgress";
export function getProgress(): number {
return extensionContext.globalState.get<number>(installProgressStr, -1);
return extensionContext ? extensionContext.globalState.get<number>(installProgressStr, -1) : -1;
}
export function getIntelliSenseProgress(): number {
return extensionContext.globalState.get<number>(intelliSenseProgressStr, -1);
return extensionContext ? extensionContext.globalState.get<number>(intelliSenseProgressStr, -1) : -1;
}
export function setProgress(progress: number): void {
if (getProgress() < progress) {
if (extensionContext && getProgress() < progress) {
extensionContext.globalState.update(installProgressStr, progress);
let telemetryProperties: { [key: string]: string } = {};
let progressName: string;
@@ -220,7 +234,7 @@ export function setProgress(progress: number): void {
}
export function setIntelliSenseProgress(progress: number): void {
if (getIntelliSenseProgress() < progress) {
if (extensionContext && getIntelliSenseProgress() < progress) {
extensionContext.globalState.update(intelliSenseProgressStr, progress);
let telemetryProperties: { [key: string]: string } = {};
let progressName: string;
@@ -238,7 +252,7 @@ export function getProgressExecutableSuccess(): number { return progressExecutab
export function getProgressParseRootSuccess(): number { return progressParseRootSuccess; } // Parse root was successful (i.e. not blocked by processing taking too long).
export function getProgressIntelliSenseNoSquiggles(): number { return progressIntelliSenseNoSquiggles; } // IntelliSense was successful and the user got no squiggles.
let releaseNotesPanel: vscode.WebviewPanel = undefined;
let releaseNotesPanel: vscode.WebviewPanel;
export async function showReleaseNotes(): Promise<void> {
if (releaseNotesPanel) {
@@ -275,13 +289,26 @@ export function isOptionalString(input: any): input is string|undefined {
}
export function isArrayOfString(input: any): input is string[] {
return isArray(input) && input.every(item => isString(item));
return isArray(input) && input.every(isString);
}
export function isOptionalArrayOfString(input: any): input is string[]|undefined {
return input === undefined || isArrayOfString(input);
}
export function resolveCachePath(input: string, additionalEnvironment: {[key: string]: string | string[]}): string {
let resolvedPath: string = "";
if (!input) {
// If no path is set, return empty string to language service process, where it will set the default path as
// Windows: %LocalAppData%/Microsoft/vscode-cpptools/
// Linux and Mac: ~/.vscode-cpptools/
return resolvedPath;
}
resolvedPath = resolveVariables(input, additionalEnvironment);
return resolvedPath;
}
export function resolveVariables(input: string, additionalEnvironment: {[key: string]: string | string[]}): string {
if (!input) {
return "";
@@ -421,7 +448,7 @@ export function touchInstallLockFile(): Promise<void> {
export function touchExtensionFolder(): Promise<void> {
return new Promise<void>((resolve, reject) => {
fs.utimes(path.resolve(extensionContext.extensionPath, ".."), new Date(Date.now()), new Date(Date.now()), (err) => {
fs.utimes(path.resolve(extensionPath, ".."), new Date(Date.now()), new Date(Date.now()), (err) => {
if (err) {
reject(err);
}
@@ -761,22 +788,31 @@ export function downloadFileToStr(urlStr: string, headers?: OutgoingHttpHeaders)
export interface CompilerPathAndArgs {
compilerPath: string;
compilerName: string;
additionalArgs: string[];
}
export function extractCompilerPathAndArgs(inputCompilerPath: string): CompilerPathAndArgs {
export function extractCompilerPathAndArgs(inputCompilerPath: string, inputCompilerArgs?: string[]): CompilerPathAndArgs {
let compilerPath: string = inputCompilerPath;
let additionalArgs: string[];
let compilerName: string = "";
let additionalArgs: string[] = [];
let isWindows: boolean = os.platform() === 'win32';
if (compilerPath) {
if (compilerPath.startsWith("\"")) {
if (compilerPath === "cl.exe") {
// Input is only compiler name, this is only for cl.exe
compilerName = compilerPath;
} else if (compilerPath.startsWith("\"")) {
// Input has quotes around compiler path
let endQuote: number = compilerPath.substr(1).search("\"") + 1;
if (endQuote !== -1) {
additionalArgs = compilerPath.substr(endQuote + 1).split(" ");
additionalArgs = additionalArgs.filter((arg: string) => { return arg.trim().length !== 0; }); // Remove empty args.
additionalArgs = additionalArgs.filter((arg: string) => arg.trim().length !== 0); // Remove empty args.
compilerPath = compilerPath.substr(1, endQuote - 1);
compilerName = path.basename(compilerPath);
}
} else {
// Input has no quotes but can have a compiler path with spaces and args.
// Go from right to left checking if a valid path is to the left of a space.
let spaceStart: number = compilerPath.lastIndexOf(" ");
if (spaceStart !== -1 && (!isWindows || !compilerPath.endsWith("cl.exe")) && !checkFileExistsSync(compilerPath)) {
@@ -793,11 +829,86 @@ export function extractCompilerPathAndArgs(inputCompilerPath: string): CompilerP
if (compilerPath !== potentialCompilerPath) {
// Found a valid compilerPath and args.
additionalArgs = compilerPath.substr(spaceStart + 1).split(" ");
additionalArgs = additionalArgs.filter((arg: string) => { return arg.trim().length !== 0; }); // Remove empty args.
additionalArgs = additionalArgs.filter((arg: string) => arg.trim().length !== 0); // Remove empty args.
compilerPath = potentialCompilerPath;
}
}
// Get compiler name if there are no args but path is valid or a valid path was found with args.
if (compilerPath === "cl.exe" || checkFileExistsSync(compilerPath)) {
compilerName = path.basename(compilerPath);
}
}
}
return { compilerPath, additionalArgs };
}
// Combine args from inputCompilerPath and inputCompilerArgs and remove duplicates
if (inputCompilerArgs && inputCompilerArgs.length) {
additionalArgs = inputCompilerArgs.concat(additionalArgs.filter(
function (item: string): boolean {
return inputCompilerArgs.indexOf(item) < 0;
}));
}
return { compilerPath, compilerName, additionalArgs };
}
export function escapeForSquiggles(s: string): string {
// Replace all \<escape character> with \\<character>, except for \"
// Otherwise, the JSON.parse result will have the \<escape character> missing.
let newResults: string = "";
let lastWasBackslash: Boolean = false;
let lastBackslashWasEscaped: Boolean = false;
for (let i: number = 0; i < s.length; i++) {
if (s[i] === '\\') {
if (lastWasBackslash) {
newResults += "\\";
lastBackslashWasEscaped = !lastBackslashWasEscaped;
} else {
lastBackslashWasEscaped = false;
}
newResults += "\\";
lastWasBackslash = true;
} else {
if (lastWasBackslash && (lastBackslashWasEscaped || (s[i] !== '"'))) {
newResults += "\\";
}
lastWasBackslash = false;
lastBackslashWasEscaped = false;
newResults += s[i];
}
}
if (lastWasBackslash) {
newResults += "\\";
}
return newResults;
}
export class BlockingTask<T> {
private dependency: BlockingTask<any>;
private done: boolean = false;
private promise: Thenable<T>;
constructor(task: () => Thenable<T>, dependency?: BlockingTask<any>) {
if (!dependency) {
this.promise = task();
} else {
this.dependency = dependency;
this.promise = new Promise<T>((resolve, reject) => {
let f1: () => void = () => {
task().then(resolve, reject);
};
let f2: (err: any) => void = (err) => {
console.log(err);
task().then(resolve, reject);
};
this.dependency.promise.then(f1, f2);
});
}
this.promise.then(() => this.done = true, () => this.done = true);
}
public get Done(): boolean {
return this.done;
}
public getPromise(): Thenable<T> {
return this.promise;
}
}
+1 -1
View File
@@ -75,7 +75,7 @@ export class CppTools implements CppToolsTestApi {
client.updateCustomBrowseConfiguration(p);
});
} else if (this.failedRegistrations.find(p => p === provider)) {
console.warn("provider not successfully registered, 'notifyReady' ignored");
console.warn("provider not successfully registered; 'notifyReady' ignored");
} else {
console.warn("provider should be registered before signaling it's ready to provide configurations");
}
+33 -1
View File
@@ -4,7 +4,7 @@
* ------------------------------------------------------------------------------------------ */
'use strict';
import { CustomConfigurationProvider, Version, CppToolsApi } from 'vscode-cpptools';
import { CustomConfigurationProvider, Version, CppToolsApi, CppToolsExtension } from 'vscode-cpptools';
import { CppToolsTestApi, CppToolsTestHook, CppToolsTestExtension } from 'vscode-cpptools/out/testApi';
import { CppTools } from './cppTools';
@@ -63,3 +63,35 @@ export class CppTools1 implements CppToolsTestApi, CppToolsTestExtension {
return this.BackupApi.getTestHook();
}
}
/**
* This is an empty implementation of the API. Used when the extension is activated on
* an unsupported platform.
*/
export class NullCppTools implements CppToolsApi, CppToolsExtension {
private version: Version;
getApi(version: Version): CppToolsApi {
this.version = version;
return this;
}
getVersion(): Version {
return this.version;
}
registerCustomConfigurationProvider(provider: CustomConfigurationProvider): void {
}
notifyReady(provider: CustomConfigurationProvider): void {
}
didChangeCustomConfiguration(provider: CustomConfigurationProvider): void {
}
didChangeCustomBrowseConfiguration(provider: CustomConfigurationProvider): void {
}
dispose(): void {
}
}
+5 -5
View File
@@ -69,7 +69,7 @@ function isBuild(input: any): input is Build {
* @return Whether input is of type Asset[].
*/
function isArrayOfAssets(input: any): input is Asset[] {
return input instanceof Array && input.every(item => isAsset(item));
return input instanceof Array && input.every(isAsset);
}
/**
@@ -174,17 +174,17 @@ function getTargetBuild(builds: Build[], userVersion: PackageVersion, updateChan
let needsUpdate: (installed: PackageVersion, target: PackageVersion) => boolean;
let useBuild: (build: Build) => boolean;
if (updateChannel === 'Insiders') {
needsUpdate = (installed: PackageVersion, target: PackageVersion) => { return testingInsidersVsixInstall || target.isGreaterThan(installed); };
useBuild = (build: Build): boolean => { return true; };
needsUpdate = (installed: PackageVersion, target: PackageVersion) => testingInsidersVsixInstall || target.isGreaterThan(installed);
useBuild = (build: Build): boolean => true;
} else if (updateChannel === 'Default') {
needsUpdate = function(installed: PackageVersion, target: PackageVersion): boolean { return installed.isGreaterThan(target); };
useBuild = (build: Build): boolean => { return build.name.indexOf('-') === -1; };
useBuild = (build: Build): boolean => build.name.indexOf('-') === -1;
} else {
throw new Error('Incorrect updateChannel setting provided');
}
// Get the build to install
const targetBuild: Build = builds.find((build) => useBuild(build));
const targetBuild: Build = builds.find(useBuild);
if (!targetBuild) {
throw new Error('Failed to determine installation candidate');
}
+1 -1
View File
@@ -35,4 +35,4 @@ export function setInstallationStage(stage: string): void {
export function setInstallationType(type: InstallationType): void {
getInstallationInformation().type = type;
}
}
+3 -3
View File
@@ -36,13 +36,13 @@ export class Logger {
public showInformationMessage(message: string, items?: string[]): Thenable<string> {
this.appendLine(message);
return vscode.window.showInformationMessage(message, ...items);
}
public showWarningMessage(message: string, items?: string[]): Thenable<string> {
this.appendLine(message);
return vscode.window.showWarningMessage(message, ...items);
}
@@ -73,4 +73,4 @@ export function getOutputChannelLogger(): Logger {
outputChannelLogger = new Logger(message => getOutputChannel().append(message));
}
return outputChannelLogger;
}
}
+45 -19
View File
@@ -22,15 +22,27 @@ import { getInstallationInformation, InstallationInformation, setInstallationSta
import { Logger, getOutputChannelLogger, showOutputChannel } from './logger';
import { CppTools1 } from './cppTools1';
const releaseNotesVersion: number = 4;
const releaseNotesVersion: number = 5;
const cppTools: CppTools1 = new CppTools1();
let languageServiceDisabled: boolean = false;
let reloadMessageShown: boolean = false;
let disposables: vscode.Disposable[] = [];
export async function activate(context: vscode.ExtensionContext): Promise<CppToolsApi & CppToolsExtension> {
initializeTemporaryCommandRegistrar();
/*
let errMsg: string = "";
if (process.arch !== 'x32' && process.arch !== 'x64') {
errMsg = "Architecture " + String(process.arch) + " is not supported. ";
} else if (process.platform === 'linux' && fs.existsSync('/etc/alpine-release')) {
errMsg = "Alpine containers are not supported. ";
}
if (errMsg) {
vscode.window.showErrorMessage(errMsg);
return new NullCppTools();
}*/
util.setExtensionContext(context);
initializeTemporaryCommandRegistrar();
Telemetry.activate();
util.setProgress(0);
@@ -68,17 +80,17 @@ async function processRuntimeDependencies(): Promise<void> {
// Send the failure telemetry since postInstall will not be called.
sendTelemetry(await PlatformInformation.GetPlatformInformation());
}
// The extension have been installed and activated before.
} else {
// The extension has been installed and activated before.
await finalizeExtensionActivation();
}
// No lock file, need to download and install dependencies.
} else {
// No lock file, need to download and install dependencies.
try {
await onlineInstallation();
} catch (error) {
handleError(error);
// Send the failure telemetry since postInstall will not be called.
sendTelemetry(await PlatformInformation.GetPlatformInformation());
}
@@ -247,7 +259,9 @@ function sendTelemetry(info: PlatformInformation): boolean {
util.setProgress(util.getProgressInstallSuccess());
let versionShown: PersistentState<number> = new PersistentState<number>("CPP.ReleaseNotesVersion", -1);
if (versionShown.Value < releaseNotesVersion) {
util.showReleaseNotes();
if (versionShown.Value !== versionShown.DefaultValue) {
util.showReleaseNotes();
}
versionShown.Value = releaseNotesVersion;
}
}
@@ -271,7 +285,7 @@ async function postInstall(info: PlatformInformation): Promise<void> {
if (!installSuccess) {
return Promise.reject<void>("");
} else {
// Notify user's if debugging may not be supported on their OS.
// Notify users if debugging may not be supported on their OS.
util.checkDistro(info);
return finalizeExtensionActivation();
@@ -300,11 +314,12 @@ async function finalizeExtensionActivation(): Promise<void> {
// Update default for C_Cpp.intelliSenseEngine based on A/B testing settings.
// (this may result in rewriting the package.json file)
let abTestSettings: cpptoolsJsonUtils.ABTestSettings = cpptoolsJsonUtils.getABTestSettings();
let packageJson: any = util.getRawPackageJson();
let writePackageJson: boolean = false;
let packageJsonPath: string = util.getExtensionFilePath("package.json");
if (!packageJsonPath.includes(".vscode-insiders") && !packageJsonPath.includes(".vscode-exploration")) {
let abTestSettings: cpptoolsJsonUtils.ABTestSettings = cpptoolsJsonUtils.getABTestSettings();
let packageJson: any = util.getRawPackageJson();
let prevIntelliSenseEngineDefault: any = packageJson.contributes.configuration.properties["C_Cpp.intelliSenseEngine"].default;
if (abTestSettings.UseDefaultIntelliSenseEngine) {
packageJson.contributes.configuration.properties["C_Cpp.intelliSenseEngine"].default = "Default";
@@ -312,21 +327,34 @@ async function finalizeExtensionActivation(): Promise<void> {
packageJson.contributes.configuration.properties["C_Cpp.intelliSenseEngine"].default = "Tag Parser";
}
if (prevIntelliSenseEngineDefault !== packageJson.contributes.configuration.properties["C_Cpp.intelliSenseEngine"].default) {
return util.writeFileText(util.getPackageJsonPath(), util.stringifyPackageJson(packageJson));
writePackageJson = true;
}
} else {
let packageJson: any = util.getRawPackageJson();
if (packageJson.contributes.configuration.properties['C_Cpp.updateChannel'].default === 'Default') {
packageJson.contributes.configuration.properties['C_Cpp.updateChannel'].default = 'Insiders';
return util.writeFileText(util.getPackageJsonPath(), util.stringifyPackageJson(packageJson));
writePackageJson = true;
}
}
let prevEnhancedColorizationDefault: any = packageJson.contributes.configuration.properties["C_Cpp.enhancedColorization"].default;
if (abTestSettings.UseEnhancedColorization) {
packageJson.contributes.configuration.properties["C_Cpp.enhancedColorization"].default = "Enabled";
} else {
packageJson.contributes.configuration.properties["C_Cpp.enhancedColorization"].default = "Disabled";
}
if (prevEnhancedColorizationDefault !== packageJson.contributes.configuration.properties["C_Cpp.enhancedColorization"].default) {
writePackageJson = true;
}
if (writePackageJson) {
return util.writeFileText(util.getPackageJsonPath(), util.stringifyPackageJson(packageJson));
}
}
function rewriteManifest(): Promise<void> {
// Replace activationEvents with the events that the extension should be activated for subsequent sessions.
let packageJson: any = util.getRawPackageJson();
packageJson.activationEvents = [
"onLanguage:cpp",
"onLanguage:c",
@@ -339,19 +367,17 @@ function rewriteManifest(): Promise<void> {
"onCommand:C_Cpp.ConfigurationProviderSelect",
"onCommand:C_Cpp.SwitchHeaderSource",
"onCommand:C_Cpp.Navigate",
"onCommand:C_Cpp.GoToDeclaration",
"onCommand:C_Cpp.PeekDeclaration",
"onCommand:C_Cpp.EnableErrorSquiggles",
"onCommand:C_Cpp.DisableErrorSquiggles",
"onCommand:C_Cpp.ToggleIncludeFallback",
"onCommand:C_Cpp.ToggleDimInactiveRegions",
"onCommand:C_Cpp.ShowReleaseNotes",
"onCommand:C_Cpp.ResetDatabase",
"onCommand:C_Cpp.PauseParsing",
"onCommand:C_Cpp.ResumeParsing",
"onCommand:C_Cpp.ShowParsingCommands",
"onCommand:C_Cpp.TakeSurvey",
"onCommand:C_Cpp.LogDiagnostics",
"onCommand:C_Cpp.RescanWorkspace",
"onCommand:C_Cpp.VcpkgClipboardInstallSuggested",
"onCommand:C_Cpp.VcpkgClipboardOnlineHelpSuggested",
"onDebug",
"workspaceContains:/.vscode/c_cpp_properties.json"
];
+10 -10
View File
@@ -36,7 +36,7 @@ export interface IPackage {
binaries: string[];
// Internal location to which the package was downloaded
tmpFile: tmp.SyncResult;
tmpFile: tmp.FileResult;
}
export class PackageManagerError extends Error {
@@ -151,23 +151,23 @@ export class PackageManager {
progress.report({message: `Downloading ${progressCount}: ${pkg.description}`});
const tmpResult: tmp.SyncResult = await this.CreateTempFile(pkg);
const tmpResult: tmp.FileResult = await this.CreateTempFile(pkg);
await this.DownloadPackageWithRetries(pkg, tmpResult, progress);
}
private async CreateTempFile(pkg: IPackage): Promise<tmp.SyncResult> {
return new Promise<tmp.SyncResult>((resolve, reject) => {
private async CreateTempFile(pkg: IPackage): Promise<tmp.FileResult> {
return new Promise<tmp.FileResult>((resolve, reject) => {
tmp.file({ prefix: "package-" }, (err, path, fd, cleanupCallback) => {
if (err) {
return reject(new PackageManagerError('Error from temp.file', 'DownloadPackage', pkg, err));
}
return resolve(<tmp.SyncResult>{ name: path, fd: fd, removeCallback: cleanupCallback });
return resolve(<tmp.FileResult>{ name: path, fd: fd, removeCallback: cleanupCallback });
});
});
}
private async DownloadPackageWithRetries(pkg: IPackage, tmpResult: tmp.SyncResult, progress: vscode.Progress<{message?: string; increment?: number}>): Promise<void> {
private async DownloadPackageWithRetries(pkg: IPackage, tmpResult: tmp.FileResult, progress: vscode.Progress<{message?: string; increment?: number}>): Promise<void> {
pkg.tmpFile = tmpResult;
let success: boolean = false;
@@ -333,7 +333,7 @@ export class PackageManager {
if (entry.fileName.endsWith("/")) {
// Directory - create it
mkdirp.mkdirp(absoluteEntryPath, { mode: 0o775 }, (err) => {
mkdirp(absoluteEntryPath, { mode: 0o775 }, (err) => {
if (err) {
return reject(new PackageManagerError('Error creating directory', 'InstallPackage', pkg, err, err.code));
}
@@ -353,12 +353,12 @@ export class PackageManager {
return reject(new PackageManagerError('Error in readStream', 'InstallPackage', pkg, err));
});
mkdirp.mkdirp(path.dirname(absoluteEntryPath), { mode: 0o775 }, async (err) => {
mkdirp(path.dirname(absoluteEntryPath), { mode: 0o775 }, async (err) => {
if (err) {
return reject(new PackageManagerError('Error creating directory', 'InstallPackage', pkg, err, err.code));
}
// Create as a .tmp file to avoid partially unzipped files
// Create as a .tmp file to avoid partially unzipped files
// counting as completed files.
let absoluteEntryTempFile: string = absoluteEntryPath + ".tmp";
if (fs.existsSync(absoluteEntryTempFile)) {
@@ -420,4 +420,4 @@ export class PackageManager {
this.outputChannel.appendLine(text);
}
}
}
}
+13 -7
View File
@@ -48,14 +48,20 @@ export class PackageVersion {
let diff: number = this.major - other.major;
if (diff) {
return diff > 0;
} else if (diff = this.minor - other.minor) {
return diff > 0;
} else if (diff = this.patch - other.patch) {
return diff > 0;
} else if (this.suffix) {
return (other.suffix && this.suffixVersion > other.suffixVersion);
} else {
return other.suffix ? true : false;
diff = this.minor - other.minor;
if (diff) {
return diff > 0;
} else {
diff = this.patch - other.patch;
if (diff) {
return diff > 0;
} else if (this.suffix) {
return (other.suffix && this.suffixVersion > other.suffixVersion);
} else {
return other.suffix ? true : false;
}
}
}
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ export class PlatformInformation {
public static GetUnknownArchitecture(): string { return "Unknown"; }
private static GetWindowsArchitecture(): Promise<string> {
return util.execChildProcess('wmic os get osarchitecture', util.extensionContext.extensionPath)
return util.execChildProcess('wmic os get osarchitecture', util.extensionPath)
.then((architecture) => {
if (architecture) {
let archArray: string[] = architecture.split(os.EOL);
+7 -5
View File
@@ -30,23 +30,25 @@ export function deactivate(): void {
}
export function logDebuggerEvent(eventName: string, properties?: { [key: string]: string }): void {
const eventNamePrefix: string = "cppdbg/VS/Diagnostics/Debugger/";
if (telemetryReporter) {
const eventNamePrefix: string = "cppdbg/VS/Diagnostics/Debugger/";
telemetryReporter.sendTelemetryEvent(eventNamePrefix + eventName, properties);
}
}
export function logLanguageServerEvent(eventName: string, properties?: { [key: string]: string }, metrics?: { [key: string]: number }): void {
const eventNamePrefix: string = "C_Cpp/LanguageServer/";
if (telemetryReporter) {
const eventNamePrefix: string = "C_Cpp/LanguageServer/";
telemetryReporter.sendTelemetryEvent(eventNamePrefix + eventName, properties, metrics);
}
}
function createReporter(): TelemetryReporter {
let packageInfo: IPackageInfo = getPackageInfo();
if (packageInfo && packageInfo.aiKey) {
return new TelemetryReporter(packageInfo.name, packageInfo.version, packageInfo.aiKey);
if (util.extensionContext) {
let packageInfo: IPackageInfo = getPackageInfo();
if (packageInfo && packageInfo.aiKey) {
return new TelemetryReporter(packageInfo.name, packageInfo.version, packageInfo.aiKey);
}
}
return null;
}
+1 -1
View File
@@ -35,4 +35,4 @@ export function getTestHook(): TestHook {
testHook = new TestHook();
}
return testHook;
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"outDir": "out",
"lib": [
"es6", "dom"
],
"sourceMap": true,
"rootDir": ".",
"removeComments": true,
"noImplicitUseStrict": true
},
"include": [
"test/**/*.ts"
]
}
@@ -44,4 +44,4 @@ export class CppvsdbgDebugAdapterDescriptorFactory extends AbstractDebugAdapterD
return new vscode.DebugAdapterExecutable('node', [path.join(this.context.extensionPath, './out/test/integrationTests/MockDebugger/mockDebug.js')]);
}
}
}
@@ -5,4 +5,4 @@
import { MockDebugSession } from './mockDebugSession';
MockDebugSession.run(MockDebugSession);
MockDebugSession.run(MockDebugSession);
@@ -8,60 +8,58 @@ import { DebugProtocol } from 'vscode-debugprotocol';
import { Subject } from 'await-notify';
interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments {
/** An absolute path to the "program" to debug. */
/** An absolute path to the "program" to debug. */
program: string;
/** enable logging the Debug Adapter Protocol */
/** enable logging the Debug Adapter Protocol */
logPath?: string;
}
export class MockDebugSession extends LoggingDebugSession
{
private _configurationDone = new Subject();
export class MockDebugSession extends LoggingDebugSession {
private _configurationDone = new Subject();
public constructor() {
super("mock-debug.txt");
}
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
// build and return the capabilities of this debug adapter:
response.body = response.body || {};
// the adapter implements the configurationDoneRequest.
// build and return the capabilities of this debug adapter:
response.body = response.body || {};
response.body.supportsConfigurationDoneRequest = true;
this.sendResponse(response);
// since this debug adapter can accept configuration requests like 'setBreakpoint' at any time,
// we request them early by sending an 'initializeRequest' to the frontend.
// The frontend will end the configuration sequence by calling 'configurationDone' request.
this.sendEvent(new InitializedEvent());
// the adapter implements the configurationDoneRequest.
}
response.body.supportsConfigurationDoneRequest = true;
protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void {
this.sendResponse(response);
// since this debug adapter can accept configuration requests like 'setBreakpoint' at any time,
// we request them early by sending an 'initializeRequest' to the frontend.
// The frontend will end the configuration sequence by calling 'configurationDone' request.
this.sendEvent(new InitializedEvent());
super.configurationDoneRequest(response, args);
// notify the launchRequest that configuration has finished
this._configurationDone.notify();
}
}
protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void {
protected async launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments) {
// make sure to 'Stop' the buffered logging if 'trace' is not set
logger.setup(Logger.LogLevel.Verbose, args.logPath);
// wait until configuration has finished (and configurationDoneRequest has been called)
await this._configurationDone.wait(1000);
super.configurationDoneRequest(response, args);
// notify the launchRequest that configuration has finished
this._configurationDone.notify();
this.sendResponse(response);
}
// Terminate after launch.
this.sendEvent(new TerminatedEvent());
}
protected async launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): Promise<void> {
// make sure to 'Stop' the buffered logging if 'trace' is not set
logger.setup(Logger.LogLevel.Verbose, args.logPath);
protected async disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments)
{
this.sendResponse(response);
}
}
// wait until configuration has finished (and configurationDoneRequest has been called)
await this._configurationDone.wait(1000);
this.sendResponse(response);
// Terminate after launch.
this.sendEvent(new TerminatedEvent());
}
protected async disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments): Promise<void> {
this.sendResponse(response);
}
}
@@ -3,14 +3,13 @@
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import * as fs from "fs";
import * as path from 'path';
import { subscribeToAllLoggers } from "../../../src/logger";
//
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// This file is providing the test runner to use when running extension tests.
// By default the test runner in use is Mocha based.
@@ -22,23 +21,23 @@ import { subscribeToAllLoggers } from "../../../src/logger";
// to report the results back to the caller. When the tests are finished, return
// a possible error to the callback or null if none.
var testRunner = require('vscode/lib/testrunner');
import testRunner = require('vscode/lib/testrunner');
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: 'tdd', // the TDD UI is being used in *.test.ts (suite, test, etc.)
useColors: true, // colored output from test results
fullTrace: true,
fullStackTrace: true,
timeout: 60000
});
const logFolder = path.join( __dirname, ".logs")
const logFolder: string = path.join(__dirname, ".logs");
if (!fs.existsSync(logFolder)) {
fs.mkdirSync(logFolder);
}
const logFilePath = path.join(logFolder, "integrationTests.log");
const logFilePath: string = path.join(logFolder, "integrationTests.log");
subscribeToAllLoggers(message => fs.appendFileSync(logFilePath, message));
module.exports = testRunner;
module.exports = testRunner;
@@ -1,24 +1,24 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as assert from 'assert';
suite(`Debug Integration Test: `, function(): void {
let origFactoryFile: string;
let tempFactoryFile: string;
let hijackedFactoryFile: string;
suiteSetup(async function(): Promise<void> {
let extension: vscode.Extension<any> = vscode.extensions.getExtension("ms-vscode.cpptools");
let extension: vscode.Extension<any> = vscode.extensions.getExtension("ms-vscode.cpptools");
if (!extension.isActive) {
await extension.activate();
await extension.activate();
}
});
test("Starting (gdb) Launch from the workspace root should create an Active Debug Session", async function() {
test("Starting (gdb) Launch from the workspace root should create an Active Debug Session", async () => {
// If it is failing on startDebugging. Investigate the SimpleCppProject's tasks.json or launch.json.
await vscode.debug.startDebugging(vscode.workspace.workspaceFolders[0], "(gdb) Launch");
@@ -34,4 +34,4 @@ suite(`Debug Integration Test: `, function(): void {
await debugSessionTerminated;
});
});
});
@@ -3,41 +3,40 @@
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import * as fs from "fs";
import * as path from 'path';
import { subscribeToAllLoggers } from "../../../src/logger";
//
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// This file is providing the test runner to use when running extension tests.
// By default the test runner in use is Mocha based.
//
//
// You can provide your own test runner if you want to override it by exporting
// a function run(testRoot: string, clb: (error:Error) => void) that the extension
// host can call to run the tests. The test runner is expected to use console.log
// to report the results back to the caller. When the tests are finished, return
// a possible error to the callback or null if none.
var testRunner = require('vscode/lib/testrunner');
import testRunner = require('vscode/lib/testrunner');
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: 'tdd', // the TDD UI is being used in *.test.ts (suite, test, etc.)
useColors: true, // colored output from test results
fullTrace: true,
fullStackTrace: true,
timeout: 60000
});
const logFolder = path.join( __dirname, ".logs")
const logFolder: string = path.join(__dirname, ".logs");
if (!fs.existsSync(logFolder)) {
fs.mkdirSync(logFolder);
}
const logFilePath = path.join(logFolder, "integrationTests.log");
const logFilePath: string = path.join(logFolder, "integrationTests.log");
subscribeToAllLoggers(message => fs.appendFileSync(logFilePath, message));
module.exports = testRunner;
module.exports = testRunner;
@@ -1,6 +1,6 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
@@ -10,14 +10,18 @@ import * as util from '../../../src/common';
import * as api from 'vscode-cpptools';
import * as apit from 'vscode-cpptools/out/testApi';
import * as config from '../../../src/LanguageServer/configurations';
import { CppSettings } from '../../../src/LanguageServer/settings';
import { getActiveClient } from '../../../src/LanguageServer/extension';
import { initializeTemporaryCommandRegistrar } from '../../../src/commands';
const defaultTimeout: number = 60000;
suite("multiline comment setting tests", function(): void {
suiteSetup(async function(): Promise<void> {
let extension: vscode.Extension<any> = vscode.extensions.getExtension("ms-vscode.cpptools");
if (!extension.isActive) {
await extension.activate();
suiteSetup(async function(): Promise<void> {
let extension: vscode.Extension<any> = vscode.extensions.getExtension("ms-vscode.cpptools");
util.setExtensionPath(extension.extensionPath);
initializeTemporaryCommandRegistrar();
if (!extension.isActive) {
await extension.activate();
}
});
@@ -107,6 +111,109 @@ async function changeCppProperties(cppProperties: config.ConfigurationJson, disp
/******************************************************************************/
suite("extensibility tests v3", function(): void {
let cpptools: apit.CppToolsTestApi;
let lastResult: api.SourceFileConfigurationItem[];
let defaultConfig: api.SourceFileConfiguration = {
includePath: [ "${workspaceFolder}", "/v3/folder" ],
defines: [ "${workspaceFolder}" ],
intelliSenseMode: "msvc-x64",
standard: "c++17"
};
let lastBrowseResult: api.WorkspaceBrowseConfiguration;
let defaultBrowseConfig: api.WorkspaceBrowseConfiguration = {
browsePath: [ "/v3/folder" ],
compilerPath: "",
standard: "c++14",
windowsSdkVersion: "8.1"
};
let defaultFolderBrowseConfig: api.WorkspaceBrowseConfiguration = {
browsePath: [ "/v3/folder-1" ],
compilerPath: "",
standard: "c++14",
windowsSdkVersion: "8.1"
};
let provider: api.CustomConfigurationProvider = {
name: "cpptoolsTest-v3",
extensionId: "ms-vscode.cpptools-test3",
canProvideConfiguration(document: vscode.Uri): Thenable<boolean> {
return Promise.resolve(true);
},
provideConfigurations(uris: vscode.Uri[]): Thenable<api.SourceFileConfigurationItem[]> {
let result: api.SourceFileConfigurationItem[] = [];
uris.forEach(uri => {
result.push({
uri: uri.toString(),
configuration: defaultConfig
});
});
lastResult = result;
return Promise.resolve(result);
},
canProvideBrowseConfiguration(): Thenable<boolean> {
return Promise.resolve(true);
},
provideBrowseConfiguration(): Thenable<api.WorkspaceBrowseConfiguration> {
lastBrowseResult = defaultBrowseConfig;
return Promise.resolve(defaultBrowseConfig);
},
canProvideBrowseConfigurationsPerFolder(): Thenable<boolean> {
return Promise.resolve(true);
},
provideFolderBrowseConfiguration(uri: vscode.Uri): Thenable<api.WorkspaceBrowseConfiguration> {
lastBrowseResult = defaultFolderBrowseConfig;
return Promise.resolve(defaultFolderBrowseConfig);
},
dispose(): void {
console.log(" disposed");
}
};
let disposables: vscode.Disposable[] = [];
suiteSetup(async function(): Promise<void> {
cpptools = await apit.getCppToolsTestApi(api.Version.v3);
cpptools.registerCustomConfigurationProvider(provider);
cpptools.notifyReady(provider);
disposables.push(cpptools);
await changeCppProperties({
configurations: [ {name: "test3", configurationProvider: provider.extensionId} ],
version: 4
},
disposables);
});
suiteTeardown(function(): void {
disposables.forEach(d => d.dispose());
});
test("Check provider", async () => {
// Open a c++ file to start the language server.
let path: string = vscode.workspace.workspaceFolders[0].uri.fsPath + "/main3.cpp";
let uri: vscode.Uri = vscode.Uri.file(path);
let testHook: apit.CppToolsTestHook = cpptools.getTestHook();
let testResult: any = new Promise<void>((resolve, reject) => {
disposables.push(testHook.StatusChanged(status => {
if (status === apit.Status.IntelliSenseReady) {
let expected: api.SourceFileConfigurationItem[] = [ {uri: uri.toString(), configuration: defaultConfig} ];
assert.deepEqual(lastResult, expected);
assert.deepEqual(lastBrowseResult, defaultFolderBrowseConfig);
resolve();
}
}));
setTimeout(() => { reject(new Error("timeout")); }, defaultTimeout);
});
disposables.push(testHook);
await vscode.workspace.openTextDocument(path);
await testResult;
});
});
/******************************************************************************/
suite("extensibility tests v2", function(): void {
let cpptools: apit.CppToolsTestApi;
let lastResult: api.SourceFileConfigurationItem[];
@@ -125,7 +232,7 @@ suite("extensibility tests v2", function(): void {
};
// Has to be 'any' instead of api.CustomConfigurationProvider because of missing interface members.
let provider: api.CustomConfigurationProvider = {
let provider: any = {
name: "cpptoolsTest-v2",
extensionId: "ms-vscode.cpptools-test2",
canProvideConfiguration(document: vscode.Uri): Thenable<boolean> {
@@ -187,7 +294,7 @@ suite("extensibility tests v2", function(): void {
resolve();
}
}));
setTimeout(() => { reject(new Error("timeout")); }, 2500);
setTimeout(() => { reject(new Error("timeout")); }, defaultTimeout);
});
disposables.push(testHook);
@@ -262,7 +369,7 @@ suite("extensibility tests v1", function(): void {
resolve();
}
}));
setTimeout(() => { reject(new Error("timeout")); }, 2500);
setTimeout(() => { reject(new Error("timeout")); }, defaultTimeout);
});
disposables.push(testHook);
@@ -334,7 +441,7 @@ suite("extensibility tests v0", function(): void {
resolve();
}
}));
setTimeout(() => { reject(new Error("timeout")); }, 2500);
setTimeout(() => { reject(new Error("timeout")); }, defaultTimeout);
});
disposables.push(testHook);
@@ -345,10 +452,10 @@ suite("extensibility tests v0", function(): void {
/*
suite("configuration tests", function() {
suiteSetup(async function() {
let extension: vscode.Extension<any> = vscode.extensions.getExtension("ms-vscode.cpptools");
if (!extension.isActive) {
await extension.activate();
suiteSetup(async function() {
let extension: vscode.Extension<any> = vscode.extensions.getExtension("ms-vscode.cpptools");
if (!extension.isActive) {
await extension.activate();
}
// Open a c++ file to start the language server.
await vscode.workspace.openTextDocument({ language: "cpp", content: "int main() { return 0; }"});
@@ -391,4 +498,4 @@ suite("configuration tests", function() {
}
});
});
*/
*/
@@ -0,0 +1,3 @@
int main(int argc, char* arv[]) {
return 0;
}
@@ -0,0 +1,110 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Environment, ParsedEnvironmentFile } from '../../src/Debugger/ParsedEnvironmentFile';
import * as assert from 'assert';
// Because the environment variable is set as an array, the index does not matter.
function assertEnvironmentEqual(env: Environment[], name: string, value: string): void {
let found: boolean = false;
for (let e of env) {
if (e.name === name) {
assert(e.value === value, `Checking if ${e.value} == ${value}`);
found = true;
break;
}
}
assert(found, `${name} was not found in env.`);
}
suite("ParsedEnvironmentFile", () => {
test("Add single variable", () => {
const content: string = `MyName=VALUE`;
const fakeConfig : Environment[] = [];
const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", fakeConfig["env"]);
assert(result.Warning === null, `Failed to assert that Warning was empty: ${result.Warning}`);
assertEnvironmentEqual(result.Env, "MyName", "VALUE");
});
test("Handle quoted values", () => {
const content: string = `MyName="VALUE"`;
const fakeConfig : Environment[] = [];
const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", fakeConfig["env"]);
assert(result.Warning === null, `Failed to assert that Warning was empty: ${result.Warning}`);
assertEnvironmentEqual(result.Env, "MyName", "VALUE");
});
test("Handle BOM", () => {
const content: string = "\uFEFFMyName=VALUE";
const fakeConfig : Environment[] = [];
const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", fakeConfig["env"]);
assert(result.Warning === null, `Failed to assert that Warning was empty: ${result.Warning}`);
assertEnvironmentEqual(result.Env, "MyName", "VALUE");
});
test("Add multiple variables", () => {
const content: string = `
MyName1=Value1
MyName2=Value2
`;
const fakeConfig : Environment[] = [];
const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", fakeConfig["env"]);
assert(result.Warning === null, `Failed to assert that Warning was empty: ${result.Warning}`);
assertEnvironmentEqual(result.Env, "MyName1", "Value1");
assertEnvironmentEqual(result.Env, "MyName2", "Value2");
});
test("Update variable", () => {
const content: string = `
MyName1=Value1
MyName2=Value2
`;
const initialEnv : Environment[] = [];
initialEnv.push({name : "MyName1", value: "Value7"});
initialEnv.push({name : "ThisShouldNotChange", value : "StillHere"});
const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", initialEnv);
assert(result.Warning === null, `Failed to assert that Warning was empty: ${result.Warning}`);
assertEnvironmentEqual(result.Env, "MyName1", "Value1");
assertEnvironmentEqual(result.Env, "ThisShouldNotChange", "StillHere");
assertEnvironmentEqual(result.Env, "MyName2", "Value2");
});
test("Handle comments", () => {
const content: string = `# This is an environment file
MyName1=Value1
# This is a comment in the middle of the file
MyName2=Value2
`;
const fakeConfig : Environment[] = [];
const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", fakeConfig["env"]);
assert(result.Warning === null, `Failed to assert that Warning was empty: ${result.Warning}`);
assertEnvironmentEqual(result.Env, "MyName1", "Value1");
assertEnvironmentEqual(result.Env, "MyName2", "Value2");
});
test("Handle invalid lines", () => {
const content: string = `
This_Line_Is_Wrong
MyName1=Value1
MyName2=Value2
`;
const fakeConfig : Environment[] = [];
const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", fakeConfig["env"]);
assert(result.Warning.startsWith("Ignoring non-parseable lines in envFile TestEnvFileName"), 'Checking if warning exists');
assertEnvironmentEqual(result.Env, "MyName1", "Value1");
assertEnvironmentEqual(result.Env, "MyName2", "Value2");
});
});
+23 -5
View File
@@ -4,7 +4,7 @@
* ------------------------------------------------------------------------------------------ */
import * as assert from "assert";
import { resolveVariables } from "../../src/common";
import { resolveVariables, escapeForSquiggles } from "../../src/common";
suite("Common Utility validation", () => {
suite("resolveVariables", () => {
@@ -198,12 +198,31 @@ suite("Common Utility validation", () => {
.shouldLookupSymbol("Root");
});
test("escapeForSquiggles:", () => {
let testEscapeForSquigglesScenario: any = (input: string, expectedOutput: string) => {
let result: string = escapeForSquiggles(input);
if (result !== expectedOutput) {
throw new Error(`escapeForSquiggles failure: for \"${input}\", \"${result}\" !== \"${expectedOutput}\"`);
}
};
testEscapeForSquigglesScenario("\\", "\\\\"); // single backslash
testEscapeForSquigglesScenario("\\\"", "\\\""); // escaped quote
testEscapeForSquigglesScenario("\\\t", "\\\\\t"); // escaped non-quote
testEscapeForSquigglesScenario("\\\\\"", "\\\\\\\\\""); // escaped backslash, unescaped quote
testEscapeForSquigglesScenario("\\\\\t", "\\\\\\\\\t"); // escaped backslash, unescaped non-quote
testEscapeForSquigglesScenario("\\t", "\\\\t"); // escaped non-quote
testEscapeForSquigglesScenario("\\\\\\t", "\\\\\\\\\\\\t"); // escaped backslash, unescaped non-quote
testEscapeForSquigglesScenario("\"\"", "\"\""); // empty quoted string
testEscapeForSquigglesScenario("\"\\\\\"", "\"\\\\\\\\\""); // quoted string containing escaped backslash
});
interface ResolveTestFlowEnvironment {
withEnvironment(additionalEnvironment: {[key: string]: string | string[]}): ResolveTestFlowAssert;
shouldLookupSymbol: (key: string) => void;
shouldLookupSymbol(key: string): void;
}
interface ResolveTestFlowAssert {
shouldResolveTo: (x: string) => void;
shouldResolveTo(x: string): void;
}
function resolveVariablesWithInput(input: string): ResolveTestFlowEnvironment {
@@ -229,6 +248,5 @@ suite("Common Utility validation", () => {
}
};
}
});
});
});
+19 -19
View File
@@ -6,11 +6,11 @@
import * as assert from 'assert';
import * as os from 'os';
import { LinuxDistribution } from '../../src/linuxDistribution';
import { WmicProcessParser, PsProcessParser } from '../../src/Debugger/nativeAttach';
import { Process, WmicProcessParser, PsProcessParser } from '../../src/Debugger/nativeAttach';
suite("LinuxDistro Tests", () => {
test("Parse valid os-release file", () => {
const dataUbuntu1404 = 'NAME="Ubuntu"' + os.EOL +
const dataUbuntu1404: string = 'NAME="Ubuntu"' + os.EOL +
'VERSION="14.04.4 LTS, Trusty Tahr"' + os.EOL +
'ID=ubuntu' + os.EOL +
'ID_LIKE=debian' + os.EOL +
@@ -20,7 +20,7 @@ suite("LinuxDistro Tests", () => {
'SUPPORT_URL="http://help.ubuntu.com/"' + os.EOL +
'BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"';
const dataUbuntu1510 = 'NAME="Ubuntu"' + os.EOL +
const dataUbuntu1510: string = 'NAME="Ubuntu"' + os.EOL +
'VERSION="15.10 (Wily Werewolf)"' + os.EOL +
'ID=ubuntu' + os.EOL +
'ID_LIKE=debian' + os.EOL +
@@ -30,7 +30,7 @@ suite("LinuxDistro Tests", () => {
'SUPPORT_URL="http://help.ubuntu.com/"' + os.EOL +
'BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"';
const dataCentos73 = 'NAME="CentOS Linux"' + os.EOL +
const dataCentos73: string = 'NAME="CentOS Linux"' + os.EOL +
'VERSION="7 (Core)"' + os.EOL +
'ID="centos"' + os.EOL +
'ID_LIKE="rhel fedora"' + os.EOL +
@@ -46,9 +46,9 @@ suite("LinuxDistro Tests", () => {
'REDHAT_SUPPORT_PRODUCT="centos"' + os.EOL +
'REDHAT_SUPPORT_PRODUCT_VERSION="7"';
let ubuntu1404 = LinuxDistribution.getDistroInformation(dataUbuntu1404);
let ubuntu1510 = LinuxDistribution.getDistroInformation(dataUbuntu1510);
let centos73 = LinuxDistribution.getDistroInformation(dataCentos73);
let ubuntu1404: LinuxDistribution = LinuxDistribution.getDistroInformation(dataUbuntu1404);
let ubuntu1510: LinuxDistribution = LinuxDistribution.getDistroInformation(dataUbuntu1510);
let centos73: LinuxDistribution = LinuxDistribution.getDistroInformation(dataCentos73);
assert.equal(ubuntu1404.name, 'ubuntu');
assert.equal(ubuntu1404.version, '"14.04"');
@@ -61,9 +61,9 @@ suite("LinuxDistro Tests", () => {
});
test("Parse invalid os-release file", () => {
const data = 'garbage"';
const data: string = 'garbage"';
let unknown = LinuxDistribution.getDistroInformation(data);
let unknown: LinuxDistribution = LinuxDistribution.getDistroInformation(data);
assert.equal(unknown.name, 'unknown');
assert.equal(unknown.version, 'unknown');
});
@@ -72,7 +72,7 @@ suite("LinuxDistro Tests", () => {
suite("Pick Process Tests", () => {
test("Parse valid wmic output", () => {
// output from the command used in WmicAttachItemsProvider
const wmicOutput = 'CommandLine=' + os.EOL +
const wmicOutput: string = 'CommandLine=' + os.EOL +
'Name=System Idle Process' + os.EOL +
'ProcessId=0' + os.EOL +
'' + os.EOL +
@@ -86,11 +86,11 @@ suite("Pick Process Tests", () => {
'Name=conhost.exe' + os.EOL +
'ProcessId=59148' + os.EOL;
let parsedOutput = WmicProcessParser.ParseProcessFromWmic(wmicOutput);
let parsedOutput: Process[] = WmicProcessParser.ParseProcessFromWmic(wmicOutput);
let process1 = parsedOutput[0];
let process2 = parsedOutput[1];
let process3 = parsedOutput[2];
let process1: Process = parsedOutput[0];
let process2: Process = parsedOutput[1];
let process3: Process = parsedOutput[2];
assert.equal(process1.commandLine, '');
assert.equal(process1.name, 'System Idle Process');
@@ -107,15 +107,15 @@ suite("Pick Process Tests", () => {
test("Parse valid ps output", () => {
// output from the command used in PsAttachItemsProvider
const psOutput = ' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + os.EOL +
const psOutput: string = ' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + os.EOL +
'15470 ScopedBookmarkAgent ScopedBookmarkAgent' + os.EOL +
'15220 mdworker mdworker -s mdworker -c MDSImporterWorker -m com.apple.mdworker.shared' + os.EOL;
let parsedOutput = PsProcessParser.ParseProcessFromPs(psOutput);
let parsedOutput: Process[] = PsProcessParser.ParseProcessFromPs(psOutput);
let process1 = parsedOutput[0];
let process2 = parsedOutput[1];
let process3 = parsedOutput[2];
let process1: Process = parsedOutput[0];
let process2: Process = parsedOutput[1];
let process3: Process = parsedOutput[2];
assert.equal(process1.commandLine, 'ScopedBookmarkAgent');
assert.equal(process1.name, 'ScopedBookmarkAgent');
+7 -7
View File
@@ -3,25 +3,25 @@
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
//
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// This file is providing the test runner to use when running extension tests.
// By default the test runner in use is Mocha based.
//
//
// You can provide your own test runner if you want to override it by exporting
// a function run(testRoot: string, clb: (error:Error) => void) that the extension
// host can call to run the tests. The test runner is expected to use console.log
// to report the results back to the caller. When the tests are finished, return
// a possible error to the callback or null if none.
var testRunner = require('vscode/lib/testrunner');
import testRunner = require('vscode/lib/testrunner');
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
});
module.exports = testRunner;
module.exports = testRunner;
+5 -5
View File
@@ -10,7 +10,7 @@ function appendFieldsToObject(reference: any, obj: any): any {
// Make sure it is an object type
if (typeof obj === 'object') {
for (let referenceKey in reference) {
// If key exists in original object and is an object.
// If key exists in original object and is an object.
if (obj.hasOwnProperty(referenceKey)) {
obj[referenceKey] = appendFieldsToObject(reference[referenceKey], obj[referenceKey]);
} else {
@@ -23,7 +23,7 @@ function appendFieldsToObject(reference: any, obj: any): any {
return obj;
}
// Combines two object's fields, giving the parentDefault a higher precedence.
// Combines two object's fields, giving the parentDefault a higher precedence.
function mergeDefaults(parentDefault: any, childDefault: any): any {
let newDefault: any = {};
@@ -80,7 +80,7 @@ function replaceReferences(definitions: any, objects: any): any {
objects[key] = refReplace(definitions, objects[key]);
}
// Recursively replace references if this object has properties.
// Recursively replace references if this object has properties.
if (objects[key].hasOwnProperty('type') && objects[key].type === 'object' && objects[key].properties !== null) {
objects[key].properties = replaceReferences(definitions, objects[key].properties);
objects[key].properties = updateDefaults(objects[key].properties, objects[key].default);
@@ -114,7 +114,7 @@ export function generateOptionsSchema(): void {
if (os.platform() === 'win32') {
content = content.replace(/\n/gm, "\r\n");
}
// We use '\u200b' (unicode zero-length space character) to break VS Code's URL detection regex for URLs that are examples. This process will
// convert that from the readable espace sequence, to just an invisible character. Convert it back to the visible espace sequence.
content = content.replace(/\u200b/gm, "\\u200b");
@@ -122,4 +122,4 @@ export function generateOptionsSchema(): void {
fs.writeFileSync('package.json', content);
}
generateOptionsSchema();
generateOptionsSchema();
+10
View File
@@ -196,6 +196,11 @@
},
"default": []
},
"envFile": {
"type": "string",
"description": "Absolute path to a file containing environment variable definitions. This file has key value pairs separated by an equals sign per line. E.g. KEY=VALUE",
"default": "${workspaceFolder}/.env"
},
"additionalSOLibSearchPath": {
"type": "string",
"description": "Semicolon separated list of directories to use to search for .so files. Example: \"c:\\dir1;c:\\dir2\".",
@@ -429,6 +434,11 @@
},
"default": []
},
"envFile": {
"type": "string",
"description": "Absolute path to a file containing environment variable definitions. This file has key value pairs separated by an equals sign per line. E.g. KEY=VALUE",
"default": "${workspaceFolder}/.env"
},
"symbolSearchPath": {
"type": "string",
"description": "Semicolon separated list of directories to use to search for symbol (that is, pdb) files. Example: \"c:\\dir1;c:\\dir2\".",
@@ -10,9 +10,17 @@
*/
const fs = require("fs");
const os = require("os");
const cp = require("child_process");
const path = require("path");
let compile = function(tsPath) {
const folderName = path.dirname(tsPath);
console.log(">> tsc " + tsPath + " --outDir out/" + folderName);
cp.execSync("tsc " + tsPath + " --outDir out/" + folderName, {stdio:[0, 1, 2]});
};
if (!process.env.CPPTOOLS_DEV && fs.existsSync('./node_modules')) {
console.warn("WARNING: Skipping npm install since it appears to have been executed already.");
} else {
@@ -20,13 +28,17 @@ if (!process.env.CPPTOOLS_DEV && fs.existsSync('./node_modules')) {
cp.execSync("npm install", { stdio: [0, 1, 2] });
}
// Compile the TypeScript code
console.log(">> tsc -p ./");
cp.execSync("tsc -p ./", {stdio:[0, 1, 2]});
const tscCompileListStr = fs.readFileSync("./tscCompileList.txt").toString();
tscCompileListStr.split(/\r?\n/).forEach(filePath => {
if (!filePath.startsWith("#") && /\S/.test(filePath)) {
compile(filePath);
}
});
// If the required debugger file doesn't exist, make sure it is copied.
if (process.env.CPPTOOLS_DEV || !fs.existsSync('./debugAdapters/bin/cppdbg.ad7Engine.json')) {
const copyDebuggerDependenciesJSFile = './out/src/Support/copyDebuggerDependencies.js';
const copyDebuggerDependenciesJSFile = './out/tools/copyDebuggerDependencies.js';
// Required for nightly builds. Nightly builds do not enable CPPTOOLS_DEV.
console.log(">> node " + copyDebuggerDependenciesJSFile);
+13
View File
@@ -0,0 +1,13 @@
# This file is consumed in tools\prepublish.js
# '#' at the start of the line is treated as a comment and is ignored.
# whitespace empty lines are also ignores.
#
# This file is to be used if you do not wish to webpack a .ts file
# If you do not want it to be webpacked:
# 1. Please make sure it is not in the src directory
# 2. Add it to the list below
# 3. If you created a new folder, please make sure it is added to the .vscodeignore
tools/GenerateOptionsSchema.ts
tools/copyDebuggerDependencies.ts
ui/settings.ts
+4 -3
View File
@@ -11,8 +11,9 @@
"removeComments": true,
"noImplicitUseStrict": true
},
"exclude": [
"node_modules",
"server"
"include": [
"src/**/*.ts",
"./node_modules/vscode/vscode.d.ts",
"./node_modules/vscode/lib/*",
]
}
+99 -9
View File
@@ -1,31 +1,121 @@
{
"rules": {
"adjacent-overload-signatures": true,
"align": true,
"array-type": [true, "array"],
"arrow-return-shorthand": true,
"ban-comma-operator": true,
"binary-expression-operand-order": true,
"callable-types": true,
"class-name": true,
"comment-format": true,
"curly": true,
"encoding": true,
"eofline": true,
"ext-variable-name": [
true,
["class", "pascal"],
["function", "camel"]
[
"class",
"pascal"
],
[
"function",
"camel"
]
],
"file-header": [true, ".*"],
"indent": [true, "spaces", 4],
"file-header": [
true,
".*"
],
"import-spacing": true,
"indent": [
true,
"spaces",
4
],
"label-position": true,
"match-default-export-name": true,
"member-ordering": true,
"new-parens": true,
"no-arg": true,
"no-bitwise": true,
"no-boolean-literal-compare": true,
"no-conditional-assignment": true,
"no-consecutive-blank-lines": true,
"no-construct": true,
"no-debugger": true,
"no-default-export": true,
"no-duplicate-imports": true,
"no-duplicate-super": true,
"no-duplicate-switch-case": true,
"no-duplicate-variable": true,
"no-unused-expression-chai": true,
"no-eval": true,
"no-import-side-effect": true,
"no-internal-module": true,
"no-invalid-this": true,
"no-irregular-whitespace": true,
"no-mergeable-namespace": true,
"no-misused-new": true,
"no-namespace": true,
"no-non-null-assertion": true,
"no-redundant-jsdoc": true,
"no-reference": true,
"no-reference-import": true,
"no-return-await": true,
"no-sparse-arrays": true,
"no-switch-case-fall-through": true,
"no-this-assignment": true,
"no-trailing-whitespace": true,
"no-unnecessary-callback-wrapper": true,
"no-unnecessary-initializer": true,
"no-unnecessary-qualifier": true,
"no-unsafe-finally": true,
"no-unused-expression": true,
"no-unused-variable": true,
"no-var-keyword": true,
"one-line": [true, "check-catch", "check-finally", "check-else", "check-open-brace", "check-whitespace"],
"no-var-requires": true,
"number-literal-format": true,
"one-line": [
true,
"check-catch",
"check-finally",
"check-else",
"check-open-brace",
"check-whitespace"
],
"one-variable-per-declaration": true,
"prefer-method-signature": true,
"prefer-object-spread": true,
"prefer-while": true,
"promise-must-complete": true,
"semicolon": true,
"space-within-parens": true,
"trailing-comma": true,
"triple-equals": true,
"type-literal-delimiter": true,
"typedef": [true, "variable-declaration", "call-signature"],
"whitespace": [true, "check-branch", "check-operator", "check-separator", "check-preblock", "check-type"]
"typedef": [
true,
"variable-declaration",
"call-signature"
],
"typedef-whitespace": true,
"typeof-compare": true,
"unified-signatures": true,
"use-default-type-parameter": true,
"use-isnan": true,
"whitespace": [
true,
"check-branch",
"check-operator",
"check-separator",
"check-preblock",
"check-type"
]
},
"rulesDirectory": [
"node_modules/tslint-microsoft-contrib",
"node_modules/tslint-microsoft-contrib",
"node_modules/tslint-no-unused-expression-chai/rules",
"node_modules/vrsource-tslint-rules/rules"
]
}
}
+542 -272
View File
@@ -6,281 +6,393 @@
<meta http-equiv="Content-Security-Policy" content="style-src 'unsafe-inline'; img-src vscode-resource:; script-src 'nonce-{{nonce}}';">
<style type="text/css">
@media (max-width: 1140px) {
#sidebar {
display: none;
}
#main {
@media (max-width: 1140px) {
#sidebar {
display: none;
}
#main {
max-width: 800px;
padding: 0px 20px;
margin: auto;
}
}
.page-margins {
vertical-align: top;
padding-top: 40px;
padding-bottom: 10px
}
.sidebar {
width: 290px;
position: fixed;
z-index: 1;
left: 45px;
overflow-x: hidden;
}
.error {
color: var(--vscode-inputValidation-errorForeground);
background: var(--vscode-inputValidation-errorBackground);
border: solid 1px var(--vscode-inputValidation-errorBorder);
white-space: pre-wrap;
display: none;
padding: 1px 4px 4px 4px;
}
.headerBtn,
.headerBtn:hover,
.headerBtn:active {
cursor: pointer;
color: var(--vscode-foreground);
background: var(--vscode-background);
border: 0px;
padding: 0px;
outline: none;
}
.headerBtn:focus {
outline: 1px solid -webkit-focus-ring-color;
outline-offset: 3px;
}
.expand:after {
font-weight: bold;
float: right;
margin-right: 6px;
margin-top: -4px;
content: '\276E';
transform: rotate(270deg);
}
.collapse:after {
font-weight: bold;
float: right;
margin-right: 6px;
margin-top: -4px;
content: '\276E';
transform: rotate(90deg);
}
.main {
max-width: 800px;
padding: 0px 20px;
margin-left: 320px;
padding: 0px 30px;
}
.main-title {
font-weight: 500;
font-size: 22px;
padding-bottom: 6px;
color: var(--vscode-foreground);
}
.section {
padding-bottom: 35px;
}
.section-title {
font-weight: 500;
font-size: 14px;
padding-bottom: 4px;
color: var(--vscode-foreground);
}
.section-text {
font-size: 14px;
padding-bottom: 8px;
color: var(--vscode-foreground);
}
.section-note {
font-size: 14px;
font-style: italic;
padding-bottom: 2px;
color: var(--vscode-foreground);
}
.codeblock {
vertical-align: middle;
padding: 2px 8px;
margin-top: 8px;
display: inline-block;
font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback";
border-radius: 5px;
}
body {
line-height: 19px
}
body:not(.tabbing) button:focus {
outline: none;
}
a {
text-decoration: none
}
checkbox {
color: var(--vscode-settings-checkboxForeground);
background: var(--vscode-settings-checkboxForeground);
border: var(--vscode-settings-checkboxBorder);
}
a:focus,
input:focus,
select:focus,
textarea:focus {
outline: 1px solid -webkit-focus-ring-color;
outline-offset: -1px
}
hr {
border: 0;
height: 1px;
border-bottom: 1px solid;
}
h1 {
padding-bottom: .3em;
}
h1,
h2,
h3 {
font-weight: 400
}
a:hover {
text-decoration: underline
}
::placeholder {
color: var(--vscode-input-placeholderForeground);
}
input {
height: 17px;
padding: 6px;
border: solid 1px;
font-size: 13px;
font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback";
color: var(--vscode-settings-textInputForeground);
background: var(--vscode-settings-textInputBackground);
border: 1px solid var(--vscode-settings-textInputBorder);
}
textarea {
white-space: nowrap;
padding: 4px, 4px;
font-size: 13px;
font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback";
color: var(--vscode-settings-textInputForeground);
background: var(--vscode-settings-textInputBackground);
border: 1px solid var(--vscode-settings-textInputBorder);
}
button {
color: var(--vscode-button-foreground);
background-color: var(--vscode-button-background);
border: solid 1px var(--vscode-contrastBorder);
padding: 6px 14px;
}
button:hover {
background-color: var(--vscode-button-hoverBackground);
}
button:focus {
outline: 1px solid -webkit-focus-ring-color;
outline-offset: 2px
}
button:active {
outline: none;
}
.select-default {
width: 300px;
height: 27px;
font-size: 13px;
font-family:sans-serif;
color: var(--vscode-settings-dropdownForeground);
background: var(--vscode-settings-dropdownBackground);
border: 1px solid var(--vscode-settings-dropdownBorder);
}
.select-editable {
position: relative;
background-color: var(--vscode-settings-textInputBackground);
width: 800px;
height: 31px;
}
.select-editable select {
position: absolute;
font-size: 13px;
font-family: sans-serif;
border: 1px solid var(--vscode-settings-textInputBorder);
height: 31px;
margin: auto;
}
}
color: var(--vscode-settings-textInputForeground);
background: var(--vscode-settings-textInputBackground);
}
.page-margins {
vertical-align: top;
padding-top: 40px;
padding-bottom: 10px
}
.select-editable input {
position: absolute;
top: 1px;
left: 1px;
right: 1px;
bottom: 1px;
height: 17px;
font-size: 13px;
border: none;
color: var(--vscode-settings-textInputForeground);
background: var(--vscode-settings-textInputBackground);
}
.sidebar {
width: 290px;
position: fixed;
z-index: 1;
left: 45px;
overflow-x: hidden;
}
.select-editable input:focus {
outline-offset: 0px;
}
.main {
max-width: 800px;
margin-left: 320px;
padding: 0px 30px;
}
blockquote {
margin: 0 7px 0 5px;
padding: 0 16px 0 10px;
border-left: 5px solid;
}
.main-title {
font-weight: 500;
font-size: 22px;
padding-bottom: 6px;
color: var(--vscode-foreground);
}
code {
font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback";
line-height: 19px
}
.section {
padding-bottom: 30px;
}
.mac code {
line-height: 18px
}
.section-title {
font-weight: 500;
font-size: 14px;
padding-bottom: 4px;
color: var(--vscode-foreground);
}
code > div {
padding: 16px;
border-radius: 3px;
overflow: auto
}
.section-text {
font-size: 14px;
padding-bottom: 8px;
color: var(--vscode-foreground);
}
.monaco-tokenized-source {
white-space: pre
}
.section-note {
font-size: 14px;
font-style: italic;
padding-bottom: 2px;
color: var(--vscode-foreground);
}
/** Theming */
.codeblock {
vertical-align: middle;
padding: 2px 8px;
margin-top: 8px;
display: inline-block;
font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback";
border-radius: 5px;
}
.vscode-light {
color: #1e1e1e
}
body {
line-height: 19px
}
.vscode-dark {
color: #ddd
}
a {
text-decoration: none
}
.vscode-high-contrast {
color: #fff
}
a:focus,
input:focus,
select:focus,
textarea:focus {
outline: 1px solid -webkit-focus-ring-color;
outline-offset: -1px
}
.vscode-light code {
color: #a31515
}
hr {
border: 0;
height: 1px;
border-bottom: 1px solid;
}
.vscode-dark code {
color: #d7ba7d
}
h1 {
padding-bottom: .3em;
}
.vscode-light code > div {
background-color: rgba(220, 220, 220, .4)
}
h1,
h2,
h3 {
font-weight: 400
}
.vscode-dark code > div {
background-color: rgba(10, 10, 10, .4)
}
a:hover {
text-decoration: underline
}
.vscode-light .input-disabled {
background-color:rgba(255, 255, 255, 0.4);
color: rgb(138, 138, 138);
border: solid 1px rgb(201, 198, 198);
}
input {
height: 17px;
padding: 4px;
border: solid 1px;
font-size: 13px;
font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback";
color: var(--vscode-settings-textInputForeground);
background: var(--vscode-settings-textInputBackground);
border: 1px solid var(--vscode-settings-textInputBorder);
}
.vscode-dark .input-disabled {
background-color: rgba(255, 255, 255, 0.1);
color: rgb(167, 167, 167);
}
textarea {
white-space: nowrap;
padding: 4px;
font-size: 13px;
font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback";
color: var(--vscode-settings-textInputForeground);
background: var(--vscode-settings-textInputBackground);
border: 1px solid var(--vscode-settings-textInputBorder);
}
.vscode-high-contrast .input-disabled {
background-color: transparent;
color: #fff;
border: solid 1px rgb(255, 255, 255);
}
select {
width: 300px;
height: 27px;
font-size: 13px;
font-family:sans-serif;
color: var(--vscode-settings-dropdownForeground);
background: var(--vscode-settings-dropdownBackground);
border: 1px solid var(--vscode-settings-dropdownBorder);
}
.vscode-high-contrast code > div {
background-color: #000
}
blockquote {
margin: 0 7px 0 5px;
padding: 0 16px 0 10px;
border-left: 5px solid;
}
.vscode-high-contrast h1 {
border-color: #000
}
code {
font-family: Menlo, Monaco, Consolas, "Droid Sans Mono", "Courier New", monospace, "Droid Sans Fallback";
line-height: 19px
}
.vscode-light table > thead > tr > th {
border-color: rgba(0, 0, 0, .69)
}
.mac code {
line-height: 18px
}
.vscode-dark table > thead > tr > th {
border-color: rgba(255, 255, 255, .69)
}
code > div {
padding: 16px;
border-radius: 3px;
overflow: auto
}
.vscode-light h1,
.vscode-light hr,
.vscode-light table > tbody > tr + tr > td {
border-color: rgba(0, 0, 0, .18)
}
.monaco-tokenized-source {
white-space: pre
}
.vscode-dark h1,
.vscode-dark hr,
.vscode-dark table > tbody > tr + tr > td {
border-color: rgba(255, 255, 255, 0.18)
}
/** Theming */
.vscode-light blockquote,
.vscode-dark blockquote {
background: rgba(127, 127, 127, .1);
border-color: rgba(0, 122, 204, .5)
}
.vscode-light {
color: #1e1e1e
}
.vscode-high-contrast blockquote {
background: transparent;
border-color: #fff
}
.vscode-dark {
color: #ddd
}
.vscode-light div.codeblock {
background-color: rgba(0, 0, 0, 0.048)
}
.vscode-high-contrast {
color: #fff
}
.vscode-dark div.codeblock {
background-color: rgba(255, 255, 255, 0.1)
}
.vscode-light code {
color: #a31515
}
.vscode-high-contrast div.codeblock {
background-color: rgba(255, 255, 255, 0.15)
}
.vscode-dark code {
color: #d7ba7d
}
.footer {
padding: 25px;
text-align: center
}
.vscode-light code > div {
background-color: rgba(220, 220, 220, .4)
}
.vscode-light a {
color: #4080D0
}
.vscode-dark code > div {
background-color: rgba(10, 10, 10, .4)
}
.vscode-dark a {
color: #a2c1e8
}
.vscode-light .input-disabled {
background-color:rgba(255, 255, 255, 0.4);
color: rgb(138, 138, 138);
border: solid 1px rgb(201, 198, 198);
}
.vscode-dark .input-disabled {
background-color: rgba(255, 255, 255, 0.1);
color: rgb(167, 167, 167);
}
.vscode-high-contrast .input-disabled {
background-color: transparent;
color: #fff;
border: solid 1px rgb(255, 255, 255);
}
.vscode-high-contrast code > div {
background-color: #000
}
.vscode-high-contrast h1 {
border-color: #000
}
.vscode-light table > thead > tr > th {
border-color: rgba(0, 0, 0, .69)
}
.vscode-dark table > thead > tr > th {
border-color: rgba(255, 255, 255, .69)
}
.vscode-light h1,
.vscode-light hr,
.vscode-light table > tbody > tr + tr > td {
border-color: rgba(0, 0, 0, .18)
}
.vscode-dark h1,
.vscode-dark hr,
.vscode-dark table > tbody > tr + tr > td {
border-color: rgba(255, 255, 255, 0.18)
}
.vscode-light blockquote,
.vscode-dark blockquote {
background: rgba(127, 127, 127, .1);
border-color: rgba(0, 122, 204, .5)
}
.vscode-high-contrast blockquote {
background: transparent;
border-color: #fff
}
.vscode-light div.codeblock {
background-color: rgba(0, 0, 0, 0.048)
}
.vscode-dark div.codeblock {
background-color: rgba(255, 255, 255, 0.1)
}
.vscode-high-contrast div.codeblock {
background-color: rgba(255, 255, 255, 0.15)
}
.footer {
padding: 25px;
text-align: center
}
.vscode-light a {
color: #4080D0
}
.vscode-dark a {
color: #a2c1e8
}
</style>
</style>
</head>
@@ -322,9 +434,9 @@
<div style=" height: 90px; display: inline-block;">
<div class="main-title">IntelliSense Configurations</div>
<div style="color: var(--vscode-foreground);">
Use this editor to edit basic IntelliSense settings defined in the underlying <a href="command:C_Cpp.ConfigurationEditJSON" title="Edit configurations in JSON file">c_cpp_properties.json</a> file.
Changes made in this editor only apply to the active configuration. To modify other configurations <a href="command:C_Cpp.ConfigurationSelect" title="Change the active configuration">change the active configuration</a>.
To edit multiple configurations at once, or additional settings not shown here, go to <a href="command:C_Cpp.ConfigurationEditJSON" title="Edit configurations in JSON file">c_cpp_properties.json</a>.
Use this editor to edit IntelliSense settings defined in the underlying <a href="command:C_Cpp.ConfigurationEditJSON" title="Edit configurations in JSON file">c_cpp_properties.json</a> file.
Changes made in this editor only apply to the selected configuration.
To edit multiple configurations at once go to <a href="command:C_Cpp.ConfigurationEditJSON" title="Edit configurations in JSON file">c_cpp_properties.json</a>.
</div>
</div>
@@ -335,50 +447,98 @@
<div class="section">
<div class="section-title">Configuration name</div>
<div class="section-text">
A friendly name that identifies a configuration. <code>Mac</code>, <code>Linux</code>, and <code>Win32</code> are special identifiers for configurations that will be auto-selected on those platforms, but the name of the identifier can be anything.
To edit the name of the current active configuration, go to the <a href="command:C_Cpp.ConfigurationEditJSON" title="Edit configurations in JSON file">c_cpp_properties.json</a> file and edit the <code>name</code> property.
A friendly name that identifies a configuration. <code>Linux</code>, <code>Mac</code>, and <code>Win32</code> are special identifiers
for configurations that will be auto-selected on those platforms.
</div>
<div class="section-input"><input class="input-disabled" type="text" id=activeConfig style="width: 290px" disabled>
<a style="padding-left: 6px;" href="command:C_Cpp.ConfigurationSelect" title="Change the active configuration">Change the active configuration</a>
</div>
<div>
<div class="section-note">Select a configuration set to edit.</div>
<table>
<tr>
<!-- select configuration name -->
<td>
<div class="select-editable" style="width: 300px; margin-right: 10px">
<select id="configSelection" style="width: 300px"></select>
<input id=configName style="width: 267px" type="text"/>
</div>
</td>
<!-- input configuration name -->
<td style="vertical-align: middle;">
<div id=addConfigDiv style="display: block">
<button id=addConfigBtn >Add Configuration</button>
</div>
<div id=addConfigInputDiv style="display: none; width: 400px;">
<input id=addConfigName type=text style="width: 200px; margin-right: 6px" placeholder="Configuration name..."/>
<button id=addConfigOk style="margin-right: 6px">OK</button>
<button id=addConfigCancel>CANCEL</button>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="section">
<div class="section-title">Compiler path</div>
<div class="section-text">
The full path of the compiler being used to build, e.g. <code>/usr/bin/gcc</code>, to enable more accurate IntelliSense.
Args can be added to modify the includes/defines used, e.g. <code>-nostdinc++</code>, <code>-m32</code>, etc., but paths with spaces must be surrounded by double quotes <code>"</code> if args are used.
The full path to the compiler you use to build your project, e.g. <code>/usr/bin/gcc</code>, to enable more accurate IntelliSense.
The extension will query the compiler to determine the system include paths and default defines to use for IntelliSense.
</div>
<div class="section-input">
<input id="compilerPath" style="width: 666px"></textarea>
<!-- input compilerPath -->
<div class="section-note">Specify a compiler path or select a detected compiler path from the drop-down list.</div>
<div class="select-editable">
<select id="knownCompilers" style="width: 810px"></select>
<input name="inputValue" id="compilerPath" style="width: 777px" type="text"/>
</div>
<div id="compilerPathInvalid" class="error" style="width: 800px"></div>
<!-- input compilerPath end -->
</div>
<div class="section">
<div class="section-title">Compiler arguments</div>
<div class="section-text">
Compiler arguments to modify the includes or defines used, e.g. <code>-nostdinc++</code>, <code>-m32</code>, etc.
</div>
<div>
<div class="section-note">One argument per line.</div>
<textarea name="inputValue" id="compilerArgs" rows="4" cols="93" style="width: 800px"></textarea>
</div>
</div>
<div class="section">
<div class="section-title">IntelliSense mode</div>
<div class="section-text">
The IntelliSense mode used by the IntelliSense engine. The <code>${default}</code> mode will choose the default for that platform.
Windows defaults to <code>msvc-x64</code>, Linux defaults to <code>gcc-x64</code>, and Mac defaults to <code>clang-x64</code>.
The IntelliSense mode to use that maps to an architecture-specific variant of MSVC, gcc, or Clang.
If not set or if set to <code>${default}</code>, the extension will choose the default for that platform.
Windows defaults to <code>msvc-x64</code>, Linux defaults to <code>gcc-x64</code>, and macOS defaults to <code>clang-x64</code>.
Select a specific IntelliSense mode to override the <code>${default}</code> mode.
</div>
<div class="section-input">
<select id="intelliSenseMode">
<div>
<select name="inputValue" id="intelliSenseMode" class="select-default">
<option value="${default}">${default}</option>
<option value="msvc-x64">msvc-x64</option>
<option value="gcc-x64">gcc-x64</option>
<option value="clang-x86">clang-x86</option>
<option value="clang-x64">clang-x64</option>
<option value="gcc-x86">gcc-x86</option>
<option value="gcc-x64">gcc-x64</option>
<option value="msvc-x86">msvc-x86</option>
<option value="msvc-x64">msvc-x64</option>
</select>
</div>
<div id="intelliSenseModeInvalid" class="error" style="width: 290px"></div>
</div>
<div class="section">
<div class="section-title">Include path</div>
<div class="section-text">
A list of paths for the IntelliSense engine to use while searching for included headers. If a path ends with <code>/**</code> the IntelliSense engine will do a recursive search for headers starting from that directory.
An include path is a folder that contains header files (such as <code>#include "myHeaderFile.h"</code>) that are included in a source file.
Specify a list paths for the IntelliSense engine to use while searching for included header files.
If a path ends with <code>/**</code> the IntelliSense engine will do a recursive search for header files starting from that directory.
If on Windows with Visual Studio installed, or if a compiler is specified in the <code>compilerPath</code> setting,
it is not necessary to list the system include paths in this list.
</div>
<div class="section-input">
<div>
<div class="section-note">One include path per line.</div>
<textarea id="includePath" rows="4" cols="93"></textarea>
<textarea name="inputValue" id="includePath" rows="4" cols="93" style="width: 800px"></textarea>
<div id="includePathInvalid" class="error" style="margin-top: -4px; width: 794px"></div>
</div>
</div>
@@ -387,39 +547,149 @@
<div class="section-text">
A list of preprocessor definitions for the IntelliSense engine to use while parsing files. Optionally, use <code>=</code> to set a value, e.g. <code>VERSION=1</code>.
</div>
<div class="section-input">
<div>
<div class="section-note">One definition per line.</div>
<textarea id="defines" rows="4" cols="39"></textarea>
<textarea name="inputValue" id="defines" rows="4" cols="39"></textarea>
</div>
</div>
<div class="section">
<div class="section-title">C Standard</div>
<div class="section-title">C standard</div>
<div class="section-text">The version of the C language standard to use for IntelliSense.</div>
<div class="section-input">
<select id="cStandard">
<div>
<select name="inputValue" id="cStandard" class="select-default">
<option value="c11">c11</option>
<option value="c99">c99</option>
<option value="c89">c89</option>
</select>
</select>
</div>
</div>
<div class="section">
<div class="section-title">C++ Standard</div>
<div class="section-title">C++ standard</div>
<div class="section-text">The version of the C++ language standard to use for IntelliSense.</div>
<div class="section-input">
<select id="cppStandard">
<div>
<select name="inputValue" id="cppStandard" class="select-default">
<option value="c++20">c++20</option>
<option value="c++17">c++17</option>
<option value="c++14">c++14</option>
<option value="c++11">c++11</option>
<option value="c++03">c++03</option>
<option value="c++98">c++98</option>
</select>
</div> <!-- sections end -->
</div>
</div>
<hr>
<button id=showAdvanced class="headerBtn" style="margin-top: 5px; font-size: 20px; font-weight: 500; width: 100%; text-align: left">
Advanced Settings
</button>
<div style="height: 30px; display: block"></div>
<div id=advancedSection>
<div class="section">
<div class="section-title">Configuration provider</div>
<div class="section-text">
The ID of a VS Code extension that can provide IntelliSense configuration information for source files. For example, use the VS Code extension ID
<code>vector-of-bool.cmake-tools</code> to provide configuration information from the CMake Tools extension.
</div>
<div>
<input name="inputValue" id="configurationProvider" style="width: 290px"></input>
</div>
</div>
<div class="section">
<div class="section-title">Windows SDK version</div>
<div class="section-text">
The version of the Windows SDK include path to use on Windows, e.g. <code>10.0.17134.0</code>.
</div>
<div>
<input name="inputValue" id="windowsSdkVersion" style="width: 290px"></input>
</div>
</div>
<div class="section">
<div class="section-title">Mac framework path</div>
<div class="section-text">
A list of paths for the Intellisense engine to use while searching for included headers from Mac frameworks. Only supported on configurations for macOS.
</div>
<div>
<div class="section-note">One path per line.</div>
<textarea name="inputValue" id="macFrameworkPath" rows="4" cols="93" style="width: 800px"></textarea>
<div id="macFrameworkPathInvalid" class="error" style="margin-top: -4px; width: 794px"></div>
</div>
</div>
<div class="section">
<div class="section-title">Forced include</div>
<div class="section-text">
A list of files that should be included before any other characters in the source file are processed. Files are included in the order listed.
</div>
<div>
<div class="section-note">One file per line.</div>
<textarea name="inputValue" id="forcedInclude" rows="4" cols="93" style="width: 800px"></textarea>
<div id="forcedIncludeInvalid" class="error" style="margin-top: -4px; width: 794px"></div>
</div>
</div>
<div class="section">
<div class="section-title">Compile commands</div>
<div class="section-text">
The full path to the <code>compile_commands.json</code> file for the workspace. The include paths and defines discovered in this file will
be used instead of the values set for <code>includePath</code> and <code>defines</code> settings. If the compile commands database
does not contain an entry for the translation unit that corresponds to the file you opened in the editor,
then a warning message will appear and the extension will use the <code>includePath</code> and <code>defines</code> settings instead.
</div>
<div>
<input name="inputValue" id="compileCommands" style="width: 798px"></input>
<div id="compileCommandsInvalid" class="error" style="width: 800px"></div>
</div>
</div>
<div class="section">
<div class="section-title">Browse: path</div>
<div class="section-text">
A list of paths for the Tag Parser to search for headers included by your source files. If omitted, <code>includePath</code> will be used as the <code>path</code>.
Searching on these paths is recursive by default. Specify <code>*</code> to indicate non-recursive search.
For example: <code>/usr/include</code> will search through all subdirectories while <code>/usr/include/*</code> will not.
</div>
<div>
<div class="section-note">One browse path per line.</div>
<textarea name="inputValue" id="browsePath" rows="4" cols="93" style="width: 800px"></textarea>
<div id="browsePathInvalid" class="error" style="margin-top: -4px; width: 794px"></div>
</div>
</div>
<div class="section">
<div class="section-title">Browse: limit symbols to included headers</div>
<div>
<input type="checkbox" id="limitSymbolsToIncludedHeaders" style="vertical-align: middle; transform: scale(1.5)">
When true (or checked), the Tag Parser will only parse code files that have been directly or indirectly included by a source file
in <code>${workspaceFolder}</code>. When false (or not checked), the Tag Parser will parse all code files found in the paths specified
in the <code>Browse: path</code> list.
</input>
</div>
</div>
<div class="section">
<div class="section-title">Browse: database filename</div>
<div class="section-text">
The path to the generated symbol database. This instructs the extension to save the Tag Parser's symbol database somewhere other than
the workspace's default storage location. If a relative path is specified, it will be made relative to the workspace's default storage location,
not the workspace folder itself. The <code>${workspaceFolder}</code> variable can be used to specify a path relative to the workspace folder
(e.g. <code>${workspaceFolder}/.vscode/browse.vc.db</code>)
</div>
<div>
<input name="inputValue" id="databaseFilename" style="width: 798px"></input>
<div id="databaseFilenameInvalid" class="error" style="width: 800px"></div>
</div>
</div>
</div> <!-- advanced settings end -->
<!-- sections end -->
</div> <!-- main end -->
<script nonce="{{nonce}}" src="{{root}}/out/ui/settings.js"></script>
+307 -46
View File
@@ -5,16 +5,49 @@
'use strict';
const elementId: { [key: string]: string } = {
activeConfig: "activeConfig",
// Basic settings
configName: "configName",
configSelection: "configSelection",
addConfigDiv: "addConfigDiv",
addConfigBtn: "addConfigBtn",
addConfigInputDiv: "addConfigInputDiv",
addConfigOk: "addConfigOk",
addConfigCancel: "addConfigCancel",
addConfigName: "addConfigName",
compilerPath: "compilerPath",
intelliSenseMode: "intelliSenseMode",
compilerPathInvalid: "compilerPathInvalid",
knownCompilers: "knownCompilers",
compilerArgs: "compilerArgs",
intelliSenseMode: "intelliSenseMode",
intelliSenseModeInvalid: "intelliSenseModeInvalid",
includePath: "includePath",
includePathInvalid: "includePathInvalid",
defines: "defines",
cStandard: "cStandard",
cppStandard: "cppStandard"
//TODO: validate input paths
// compilerPathInvalid: "compilerPathInvalid",
// includePathInvalid: "includePathInvalid"
cppStandard: "cppStandard",
// Advanced settings
windowsSdkVersion: "windowsSdkVersion",
macFrameworkPath: "macFrameworkPath",
macFrameworkPathInvalid: "macFrameworkPathInvalid",
compileCommands: "compileCommands",
compileCommandsInvalid: "compileCommandsInvalid",
configurationProvider: "configurationProvider",
forcedInclude: "forcedInclude",
forcedIncludeInvalid: "forcedIncludeInvalid",
// Browse properties
browsePath: "browsePath",
browsePathInvalid: "browsePathInvalid",
limitSymbolsToIncludedHeaders: "limitSymbolsToIncludedHeaders",
databaseFilename: "databaseFilename",
databaseFilenameInvalid: "databaseFilenameInvalid",
// Other
showAdvanced: "showAdvanced",
advancedSection: "advancedSection"
};
interface VsCodeApi {
@@ -32,79 +65,307 @@ class SettingsApp {
constructor() {
this.vsCodeApi = acquireVsCodeApi();
window.addEventListener('message', this.onMessageReceived.bind(this));
window.addEventListener("keydown", this.onTabKeyDown.bind(this));
window.addEventListener("message", this.onMessageReceived.bind(this));
document.getElementById(elementId.activeConfig).addEventListener("change", this.onChanged.bind(this, elementId.activeConfig));
document.getElementById(elementId.compilerPath).addEventListener("change", this.onChanged.bind(this, elementId.compilerPath));
document.getElementById(elementId.intelliSenseMode).addEventListener("change", this.onChanged.bind(this, elementId.intelliSenseMode));
// Add event listeners to UI elements
this.addEventsToConfigNameChanges();
this.addEventsToInputValues();
document.getElementById(elementId.knownCompilers).addEventListener("change", this.onKnownCompilerSelect.bind(this));
document.getElementById(elementId.includePath).addEventListener("change", this.onChanged.bind(this, elementId.includePath));
document.getElementById(elementId.defines).addEventListener("change", this.onChanged.bind(this, elementId.defines));
// Set view state of advanced settings and add event
const oldState: any = this.vsCodeApi.getState();
const advancedShown: boolean = (oldState && oldState.advancedShown);
document.getElementById(elementId.advancedSection).style.display = advancedShown ? "block" : "none";
document.getElementById(elementId.showAdvanced).classList.toggle(advancedShown ? "collapse" : "expand", true);
document.getElementById(elementId.showAdvanced).addEventListener("click", this.onShowAdvanced.bind(this));
}
document.getElementById(elementId.cStandard).addEventListener("change", this.onChanged.bind(this, elementId.cStandard));
document.getElementById(elementId.cppStandard).addEventListener("change", this.onChanged.bind(this, elementId.cppStandard));
private addEventsToInputValues(): void {
const elements: NodeListOf<HTMLElement> = document.getElementsByName("inputValue");
elements.forEach(el => {
el.addEventListener("change", this.onChanged.bind(this, el.id));
});
//TODO: validate input paths
// document.getElementById(ElementId.compilerPathInvalid).style.visibility = "hidden";
// document.getElementById(ElementId.includePathInvalid).style.visibility = "hidden";
// Special case for checkbox element
document.getElementById(elementId.limitSymbolsToIncludedHeaders).addEventListener("change", this.onChangedCheckbox.bind(this, elementId.limitSymbolsToIncludedHeaders));
}
private addEventsToConfigNameChanges(): void {
document.getElementById(elementId.configName).addEventListener("change", this.onConfigNameChanged.bind(this));
document.getElementById(elementId.configSelection).addEventListener("change", this.onConfigSelect.bind(this));
document.getElementById(elementId.addConfigBtn).addEventListener("click", this.onAddConfigBtn.bind(this));
document.getElementById(elementId.addConfigOk).addEventListener("click", this.OnAddConfigConfirm.bind(this, true));
document.getElementById(elementId.addConfigCancel).addEventListener("click", this.OnAddConfigConfirm.bind(this, false));
}
private onTabKeyDown(e: any): void {
if (e.keyCode === 9) {
document.body.classList.add("tabbing");
window.removeEventListener("keydown", this.onTabKeyDown);
window.addEventListener("mousedown", this.onMouseDown.bind(this));
}
}
private onMouseDown(): void {
document.body.classList.remove("tabbing");
window.removeEventListener("mousedown", this.onMouseDown);
window.addEventListener("keydown", this.onTabKeyDown.bind(this));
}
private onShowAdvanced(): void {
const isShown: boolean = (document.getElementById(elementId.advancedSection).style.display === "block");
document.getElementById(elementId.advancedSection).style.display = isShown ? "none" : "block";
// Save view state
this.vsCodeApi.setState({ advancedShown: !isShown });
// Update chevron on button
const element: HTMLElement = document.getElementById(elementId.showAdvanced);
element.classList.toggle("collapse");
element.classList.toggle("expand");
}
private onAddConfigBtn(): void {
this.showElement(elementId.addConfigDiv, false);
this.showElement(elementId.addConfigInputDiv, true);
}
private OnAddConfigConfirm(request: boolean): void {
this.showElement(elementId.addConfigInputDiv, false);
this.showElement(elementId.addConfigDiv, true);
// If request is yes, send message to create new config
if (request) {
const el: HTMLInputElement = <HTMLInputElement>document.getElementById(elementId.addConfigName);
if (el.value !== undefined && el.value !== "") {
this.vsCodeApi.postMessage({
command: "addConfig",
name: el.value
});
el.value = "";
}
}
}
private onConfigNameChanged(): void {
if (this.updating) {
return;
}
const configName: HTMLInputElement = <HTMLInputElement>document.getElementById(elementId.configName);
let list: HTMLSelectElement = <HTMLSelectElement>document.getElementById(elementId.configSelection);
if (configName.value === "") {
(<HTMLInputElement>document.getElementById(elementId.configName)).value = list.options[list.selectedIndex].value;
return;
}
// Update name on selection
list.options[list.selectedIndex].value = configName.value;
list.options[list.selectedIndex].text = configName.value;
this.onChanged(elementId.configName);
}
private onConfigSelect(): void {
if (this.updating) {
return;
}
const el: HTMLSelectElement = <HTMLSelectElement>document.getElementById(elementId.configSelection);
(<HTMLInputElement>document.getElementById(elementId.configName)).value = el.value;
this.vsCodeApi.postMessage({
command: "configSelect",
index: el.selectedIndex
});
}
private onKnownCompilerSelect(): void {
if (this.updating) {
return;
}
const el: HTMLInputElement = <HTMLInputElement>document.getElementById(elementId.knownCompilers);
(<HTMLInputElement>document.getElementById(elementId.compilerPath)).value = el.value;
this.onChanged(elementId.compilerPath);
// Post message that this control was used for telemetry
this.vsCodeApi.postMessage({
command: "knownCompilerSelect"
});
// Reset selection to none
el.value = "";
}
private onChangedCheckbox(id: string): void {
if (this.updating) {
return;
}
const el: HTMLInputElement = <HTMLInputElement>document.getElementById(id);
this.vsCodeApi.postMessage({
command: "change",
key: id,
value: el.checked
});
}
private onChanged(id: string): void {
if (this.updating) {
return;
return;
}
var x = <HTMLInputElement>document.getElementById(id);
const el: HTMLInputElement = <HTMLInputElement>document.getElementById(id);
this.vsCodeApi.postMessage({
command: "change",
key: id,
value: x.value
value: el.value
});
}
private onMessageReceived(e: MessageEvent): void {
const message = e.data; // The json data that the extension sent
const message: any = e.data; // The json data that the extension sent
switch (message.command) {
case 'update':
this.update(message.config);
case 'updateConfig':
this.updateConfig(message.config);
break;
case 'updateErrors':
this.updateErrors(message.errors);
break;
case 'setKnownCompilers':
this.setKnownCompilers(message.compilers);
break;
case 'updateConfigSelection':
this.updateConfigSelection(message);
break;
//TODO: validate input paths
// case 'validateCompilerPath':
// this.validateInput(ElementId.compilerPathInvalid, message.invalid);
// break;
// case 'validateIncludePath':
// this.validateInput(ElementId.includePathInvalid, message.invalid);
// break;
}
}
private update(config: any): void {
private updateConfig(config: any): void {
this.updating = true;
try {
(<HTMLInputElement>document.getElementById(elementId.activeConfig)).value = config.name;
let joinEntries: (input: any) => string = (input: string[]) => {
return (input && input.length) ? input.join("\n") : "";
};
// Basic settings
(<HTMLInputElement>document.getElementById(elementId.configName)).value = config.name;
(<HTMLInputElement>document.getElementById(elementId.compilerPath)).value = config.compilerPath ? config.compilerPath : "";
(<HTMLInputElement>document.getElementById(elementId.compilerArgs)).value = joinEntries(config.compilerArgs);
(<HTMLInputElement>document.getElementById(elementId.intelliSenseMode)).value = config.intelliSenseMode ? config.intelliSenseMode : "${default}";
(<HTMLInputElement>document.getElementById(elementId.includePath)).value =
(config.includePath && config.includePath.length > 0) ? config.includePath.join("\n") : "";
(<HTMLInputElement>document.getElementById(elementId.defines)).value =
(config.defines && config.defines.length > 0 ) ? config.defines.join("\n") : "";
(<HTMLInputElement>document.getElementById(elementId.includePath)).value = joinEntries(config.includePath);
(<HTMLInputElement>document.getElementById(elementId.defines)).value = joinEntries(config.defines);
(<HTMLInputElement>document.getElementById(elementId.cStandard)).value = config.cStandard;
(<HTMLInputElement>document.getElementById(elementId.cppStandard)).value = config.cppStandard;
}
finally {
// Advanced settings
(<HTMLInputElement>document.getElementById(elementId.windowsSdkVersion)).value = config.windowsSdkVersion ? config.windowsSdkVersion : "";
(<HTMLInputElement>document.getElementById(elementId.macFrameworkPath)).value = joinEntries(config.macFrameworkPath);
(<HTMLInputElement>document.getElementById(elementId.compileCommands)).value = config.compileCommands ? config.compileCommands : "";
(<HTMLInputElement>document.getElementById(elementId.configurationProvider)).value = config.configurationProvider ? config.configurationProvider : "";
(<HTMLInputElement>document.getElementById(elementId.forcedInclude)).value = joinEntries(config.forcedInclude);
if (config.browse) {
(<HTMLInputElement>document.getElementById(elementId.browsePath)).value = joinEntries(config.browse.path);
(<HTMLInputElement>document.getElementById(elementId.limitSymbolsToIncludedHeaders)).checked =
(config.browse.limitSymbolsToIncludedHeaders && config.browse.limitSymbolsToIncludedHeaders);
(<HTMLInputElement>document.getElementById(elementId.databaseFilename)).value = config.browse.databaseFilename ? config.browse.databaseFilename : "";
} else {
(<HTMLInputElement>document.getElementById(elementId.browsePath)).value = "";
(<HTMLInputElement>document.getElementById(elementId.limitSymbolsToIncludedHeaders)).checked = false;
(<HTMLInputElement>document.getElementById(elementId.databaseFilename)).value = "";
}
} finally {
this.updating = false;
}
}
//TODO: validate input paths
// private validateInput(elementID: string, invalid: boolean): void {
// document.getElementById(elementID).style.visibility = invalid ? "visible" : "hidden";
// }
private updateErrors(errors: any): void {
this.updating = true;
try {
this.showErrorWithInfo(elementId.intelliSenseModeInvalid, errors.intelliSenseMode);
this.showErrorWithInfo(elementId.compilerPathInvalid, errors.compilerPath);
this.showErrorWithInfo(elementId.includePathInvalid, errors.includePath);
this.showErrorWithInfo(elementId.macFrameworkPathInvalid, errors.macFrameworkPath);
this.showErrorWithInfo(elementId.forcedIncludeInvalid, errors.forcedInclude);
this.showErrorWithInfo(elementId.compileCommandsInvalid, errors.compileCommands);
this.showErrorWithInfo(elementId.browsePathInvalid, errors.browsePath);
this.showErrorWithInfo(elementId.databaseFilenameInvalid, errors.databaseFilename);
} finally {
this.updating = false;
}
}
private showErrorWithInfo(elementID: string, errorInfo: string): void {
this.showElement(elementID, errorInfo ? true : false);
document.getElementById(elementID).innerHTML = errorInfo ? errorInfo : "";
}
private updateConfigSelection(message: any): void {
this.updating = true;
try {
let list: HTMLSelectElement = <HTMLSelectElement>document.getElementById(elementId.configSelection);
// Clear list before updating
list.options.length = 0;
// Update list
for (let name of message.selections) {
let option: HTMLOptionElement = document.createElement("option");
option.text = name;
option.value = name;
list.append(option);
}
list.selectedIndex = message.selectedIndex;
} finally {
this.updating = false;
}
}
private setKnownCompilers(compilers: string[]): void {
this.updating = true;
try {
let list: HTMLSelectElement = <HTMLSelectElement>document.getElementById(elementId.knownCompilers);
// No need to add items unless webview is reloaded, in which case it will not have any elements.
// Otherwise, add items again.
if (list.firstChild) {
return;
}
if (compilers.length === 0) {
const noCompilers: string = "(No compiler paths detected)";
let option: HTMLOptionElement = document.createElement("option");
option.text = noCompilers;
option.value = noCompilers;
list.append(option);
// Set the selection to this one item so that no selection change event will be fired
list.value = noCompilers;
return;
}
for (let path of compilers) {
let option: HTMLOptionElement = document.createElement("option");
option.text = path;
option.value = path;
list.append(option);
}
// Initialize list with no selected item
list.value = "";
} finally {
this.updating = false;
}
}
private showElement(elementID: string, show: boolean): void {
document.getElementById(elementID).style.display = show ? "block" : "none";
}
}
let app: SettingsApp = new SettingsApp();
+47
View File
@@ -0,0 +1,47 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const path = require('path');
/**@type {import('webpack').Configuration}*/
const config = {
target: 'node', // vscode extensions run in a Node.js-context 📖 -> https://webpack.js.org/configuration/node/
entry: './src/main.ts', // the entry point of this extension, 📖 -> https://webpack.js.org/configuration/entry-context/
output: { // the bundle is stored in the 'dist' folder (check package.json), 📖 -> https://webpack.js.org/configuration/output/
path: path.resolve(__dirname, 'dist'),
filename: 'main.js',
libraryTarget: "commonjs2",
devtoolModuleFilenameTemplate: "../[resource-path]",
},
devtool: 'source-map',
externals: {
vscode: "commonjs vscode" // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed, 📖 -> https://webpack.js.org/configuration/externals/
},
resolve: { // support reading TypeScript and JavaScript files, 📖 -> https://github.com/TypeStrong/ts-loader
extensions: ['.ts', '.js']
},
module: {
rules: [{
test: /\.ts$/,
exclude: /node_modules/,
use: [{
loader: 'ts-loader'
}]
}]
},
optimization: {
minimize: false
},
stats: {
warnings: false
}
}
module.exports = config;
+53 -18
View File
@@ -1,31 +1,66 @@
# vscode-cpptools
# C/C++ for Visual Studio Code
This is the official repository for the [Microsoft C/C++ extension for VS Code](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools).
#### [Repository](https://github.com/microsoft/vscode-cpptools)&nbsp;&nbsp;|&nbsp;&nbsp;[Issues](https://github.com/microsoft/vscode-cpptools/issues)&nbsp;&nbsp;|&nbsp;&nbsp;[Documentation](https://code.visualstudio.com/docs/languages/cpp)&nbsp;&nbsp;|&nbsp;&nbsp;[Code Samples](https://github.com/microsoft/vscode-cpptools/tree/master/Code%20Samples)&nbsp;&nbsp;|&nbsp;&nbsp;[Offline Installers](https://github.com/microsoft/vscode-cpptools/releases)
The `vscode-cpptools` repository is where we do development and there are many ways you can support the extension, for example:
[![Badge](https://aka.ms/vsls-badge)](https://aka.ms/vsls)
* [Report issues or request features](https://github.com/Microsoft/vscode-cpptools/issues)
- If someone has filed a similar issue, please provide any additional information that can help us resolve it on the issue
- If someone has filed a similar feature request, please leave a thumbs up reaction on the issue
- [List of popular feature requests](https://github.com/Microsoft/vscode-cpptools/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3A%22Feature+Request%22)
* [Contribute to the extension](Extension)
This preview release of the C/C++ extension adds language support for C/C++ to Visual Studio Code, including features such as IntelliSense and debugging.
## Getting Started
## Overview and getting started
* [C/C++ extension overview](https://code.visualstudio.com/docs/languages/cpp)
* [Get Started with C++ and Windows Subsystem for Linux (WSL)](https://code.visualstudio.com/docs/cpp/config-wsl)
* [Get Started with C++ and Mingw-w64](https://code.visualstudio.com/docs/cpp/config-mingw)
* [Get Started with C++ and Clang/LLVM on macOS](https://code.visualstudio.com/docs/cpp/config-clang-mac)
* [Get Started with C++ and Microsoft C++ compiler (MSVC)](https://code.visualstudio.com/docs/cpp/config-msvc)
You can learn how to use the extension at [VS Code for C/C++](https://code.visualstudio.com/docs/languages/cpp).
## Quick links
* [Editing features (IntelliSense)](https://code.visualstudio.com/docs/cpp/cpp-ide)
* [IntelliSense configuration](https://code.visualstudio.com/docs/cpp/customize-default-settings-cpp)
* [Enhanced colorization](https://code.visualstudio.com/docs/cpp/colorization-cpp)
* [Debugging](https://code.visualstudio.com/docs/cpp/cpp-debug)
* [Debug configuration](https://code.visualstudio.com/docs/cpp/launch-json-reference)
* [Enable logging for IntelliSense or debugging](https://code.visualstudio.com/docs/cpp/enable-logging-cpp)
If you clone this repository, you can also try out our [Code Samples](Code%20Samples).
## Questions and feedback
If you have any questions, check out our [**Documentation**](Documentation) folder. If you do not find your answer there, feel free to ask it in our [issues page](https://github.com/Microsoft/vscode-cpptools/issues).
**[FAQs](https://code.visualstudio.com/docs/cpp/faq-cpp)**
<br>
Check out the FAQs before filing a question.
<br>
### Contribution
**[Provide feedback](https://github.com/microsoft/vscode-cpptools/issues/new/choose)**
<br>
File questions, issues, or feature requests for the extension.
<br>
**[Known issues](https://github.com/Microsoft/vscode-cpptools/issues)**
<br>
If someone has already filed an issue that encompasses your feedback, please leave a 👍 or 👎 reaction on the issue to upvote or downvote it to help us prioritize the issue.
<br>
**[Quick survey](https://www.research.net/r/VBVV6C6)**
<br>
Let us know what you think of the extension by taking the quick survey.
## Offline installation
The extension has platform-specific binary dependencies, therfore installation via the Marketplace requires an Internet connection in order to download additional dependencies. If you are working on a computer that does not have access to the Internet or is behind a strict firewall, you may need to use our platform-specific packages and install them by running VS Code's `"Install from VSIX..."` command. These "offline' packages are available at: https://github.com/Microsoft/vscode-cpptools/releases.
Package | Platform
:--- | :---
`cpptools-linux.vsix` | Linux 64-bit
`cpptools-linux32.vsix` | Linux 32-bit
`cpptools-osx.vsix` | macOS
`cpptools-win32.vsix` | Windows 64-bit & 32-bit
## Contribution
Contributions are always welcome. Please see our [contributing guide](CONTRIBUTING.md) for more details.
### Microsoft Open Source Code of Conduct
## Microsoft Open Source Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact opencode@microsoft.com with any additional questions or comments.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact opencode@microsoft.com with any additional questions or comments.
### Data/Telemetry
This project collects usage data and sends it to Microsoft to help improve our products and services. Read our [privacy statement](https://privacy.microsoft.com/en-us/privacystatement) to learn more.
## Data and telemetry
This extension collects usage data and sends it to Microsoft to help improve our products and services. Collection of telemetry is controlled via the same setting provided by Visual Studio Code: `"telemetry.enableTelemetry"`. Read our [privacy statement](https://privacy.microsoft.com/en-us/privacystatement) to learn more.

Some files were not shown because too many files have changed in this diff Show More