Буфер обмена visual studio code
In Visual Studio Code Ctrl+V is not working on editor.
However from the command palette Ctrl+Shift+V is working.
Look up what Ctrl+V is bound to in the keyboard shortcuts. [Gear icon/Keyboard shortcuts] - search for "ctrl+V" anything there that would conflict with paste?
@Mark you are right there was a conflict issue, you can put in answer if you want to so i can select it
Ensure that an added extension is not the root cause. Disable them all, then turn one at a time back on. Good luck!
in my VSCode settings is fine. ctrl+a and ctrl+z is working, but ctrl+c and ctrl+v is wrong. rebooting VSCode is helped me.
24 Answers 24
I´ve had this problem when I enabled the "VIM" plugin for VSCode.
After uninstalling it, the problem was fixed.
Thanks, this was the culprit for me too. When I disabled the plugin, reloaded VS Code, re-enabled VIM the problem was gone though.
Open the keyboard shortcuts preferences by pressing CTRL + SHIFT + P and search for open keyboard shortcuts file.
Then, search for the editor.action.clipboardPasteAction property. In your case, it might be CTRL+SHIFT+V. Try changing it to Ctrl + V. Like so:
+1 Just as a for instance of what such a conflict could look like, I have the VIm emulation plugin installed, and extension.vim_cmd+v had grabbed control of paste in ways I don't think it intended to. Swapped the shortcut for that command to ctrl-option-command-v in Keyboard Shortcuts (not the json version) and things are happy again.
If you want Ctrl+V to paste in a VS Code terminal as well open your keyboard shortcuts and find workbench.action.terminal.paste and replace it with Ctrl+V .
@WebD'is answer is very helpful and I have upvoted it. But my comment focused on whether there was a conflicting binding for CTRL - V and how to find it. You can literally type " Ctrl+V " (note the "plus+" sign, not a hyphen) and it will find all keybindings that use that binding in whole or part. I suggest that there must be a something else also bound to CTRL - V .
Since this original answer, vscode introduced another way to see what other commands might be bound to given keystrokes. With the Gear/Keyboard Shortcuts file open click on the little keyboardy icon to the right (or Alt + K with this file open) and it will indicate Recording Keys next to it. Now you can literally press Ctrl + V (or whichever keybinding you are interested in) and those corresponding commands, if any, that use that keybinding will be filtered up.
Remember to disable the Recording Keys functionality by clicking the keyboardy icon if you want to go back to regular searching in the Keyboard Shortcuts file.
If you install the vim extension for visual studio code and find that ctrl + x, ctrl + v .. or other shortcuts stopped working, this is because they are overwritten by extension.vim_
If you prefer to get those shortcuts back go to keyboard shortcuts (ctrl + shift + p, then search for open keyboard shortcuts file).
- Search for extension.vim_ and check too see if any shortcuts are assigned to your key combination like ctrl + v. Remove it (right click, delete).
- Also check for any other conflict by searching the file.
- Save the file, it should work now.
This was the problem for me, but with AmVim. Strangely, although it had entries for Ctrl+c and Ctrl+v, only Copy wasn't working. Paste was fine. But deleting the AmVim Ctrl+C entry got back my shortcut.
For me I had to open settings.json and add "vim.useCtrlKeys": false to the file and then all ctrl shortcuts worked again.
I have the same problem: can't CTRL+X, CTRL+C, CTRL+V on VSCode editor. I uninstall the Vim extension and the problem is fixed.
For future searchers who do not have Vim (or any other extension) installed which is causing the issue, and who might have verified that their keyboard bindings are correct.
I have the Salesforce Extension Pack installed and had right-clicked on a file and run SFDX: Deploy Source to Org. The deployment had errors, so in the Panel area (which I have at the bottom of my screen) [see image] I had clicked on both the OUTPUT and PROBLEMS tabs, which shifted focus away from my PowerShell TERMINAL tab.
My Ctrl-V issue was when I was trying to correct my Apex code in the EDITOR pane. Ctrl-V was not pasting the code I had just Cut or Copied (but right-clicking and choosing Paste was working).
I ultimately discovered, when I changed my Panel focus back to my PowerShell TERMINAL tab, that ALL of the Ctrl-V pasting I had attempted had shown up after my PowerShell prompt! ["circled" in blue in image]
tl;dr
Make sure your pasted text did not show up in your TERMINAL - even if it is not in focus or even if your cursor is in another Panel tab or in the EDITOR.
The Visual Studio Code 1.21 release includes a brand new text buffer implementation which is much more performant, both in terms of speed and memory usage. In this blog post, I'd like to tell the story of how we selected and designed the data structures and algorithms that led to those improvements.
Performance discussions about JavaScript programs usually involve a discussion about how much should be implemented in native code. For the VS Code text buffer, these discussions started more than a year ago. During an in-depth exploration, we found that a C++ implementation of the text buffer could lead to significant memory savings, but we didn't see the performance enhancements we were hoping for. Converting strings between a custom native representation and V8's strings is costly and in our case, compromised any performance gained from implementing text buffer operations in C++. We will discuss this in more detail at the end of this post.
Not going native, we had to find ways to improve our JavaScript/TypeScript code. Inspiring blog posts like this one from Vyacheslav Egorov show ways to push a JavaScript engine to its limits and squeeze out as much performance as possible. Even without low level engine tricks, it is still possible to improve speed by one or more orders of magnitude by using better suited data structures and faster algorithms.
Previous text buffer data structure
The mental model for an editor is line based. Developers read and write source code line by line, compilers provide line/column based diagnostics, stack traces contain line numbers, tokenization engines run line by line, etc. Although simple, the text buffer implementation powering VS Code hadn't changed much since the first day we kicked off the Monaco project. We used an array of lines, and it worked pretty well because typical text documents are relatively small. When the user is typing, we located the line to modify in the array and replaced it. When inserting a new line, we spliced a new line object into the line array and the JavaScript engine would do the heavy lifting for us.
However, we kept receiving reports that opening certain files would cause Out-Of-Memory crashes in VS Code. For example, one user failed to open a 35 MB file. The root cause was that the file had too many lines, 13.7 million. We would create a ModelLine object for each line and every object used around 40-60 bytes, so the line array used around 600MB memory to store the document. That's roughly 20 times the initial file size!
Another problem with the line array representation was the speed of opening a file. To construct the array of lines, we had to split the content by line breaks, such that we would get a string object per line. The split itself hurts performance which you'll see in benchmarks further down.
Finding a new text buffer implementation
The old line array representation can take a lot of time to create and consumes a lot of memory, but it gives fast line look-up. In a perfect world, we would store only the text of the file and no additional metadata. Thus, we started looking for data structures that require less metadata. After reviewing various data structures, I found that piece table may be a good candidate to start with.
Avoiding too much meta-data by using a piece table
Piece table is a data structure used to represent a series of edits on a text document (source code in TypeScript):
After the file is initially loaded, the piece table contains the whole file contents in the original field. The added field is empty. There is a single node of type NodeType.Original . When a user types at the end of a file, we append the new content to the added field, and we will insert a new node of type NodeType.Added at the end of the node list. Similarly, when a user makes edits in the middle of a node, we will split that node and insert a new one as needed.
The animation below shows how to access the document line by line in a piece table structure. It has two buffers ( original and added ) and three nodes (which is caused by an insertion in the middle of the original content`).
The initial memory usage of a piece table is close to the size of the document and the memory needed for modifications is proportional to the number of edits and text added. So typically a piece table makes good use of memory. However, the price for low memory usage is that accessing a logical line is slow. For example, if you want to get the content of the 1000th line, the only way is to iterate over every character starting at the beginning of the document, find the first 999 line breaks, and read each character until the next line break.
Use caching for faster line lookup
The traditional piece table nodes only contain offsets, but we can add line break information to make line content lookup faster. The intuitive way to store line break positions is to store the offsets for each line break encountered in a node's text:
For example, if you want to access the second line in a given Node instance, you can read node.lineStarts[0] and node.lineStarts[1] which will give the relative offsets at which a line begins and ends. Since we know how many line breaks a node has, accessing a random line in the document is straight forward: read each node starting from the first one until we find the target line break.
The algorithm remains simple, and it works better than before as we can now jump over entire chunks of text rather than iterate character-by-character. We'll see later on that we can do even better than that.
Avoid the string concatenation trap
The piece table holds two buffers, one for original content loaded from disk, and another for user edits. In VS Code, we are loading text files using Node.js fs.readFile that delivers content in 64KB chunks. So when the file is large, for example 64 MB, we'll receive 1000 chunks. After having received all of the chunks, we can concatenate them into one large string and store it in the original field of the piece table.
This sounds reasonable until V8 steps on your toes. I tried to open a 500MB file and got an exception because in the version of V8 I used, the maximum string length is 256MB. This limit will be lifted to 1GB in future versions of V8 but that doesn't really solve the problem.
Instead of holding an original and an added buffer, we can hold a list of buffers. We can try to keep that list short or we can be inspired by what we get back from fs.readFile and avoid any string concatenation. Each time we receive a 64KB chunk from disk, we push it directly to the buffers array and create a node that points to this buffer:
Boost line lookup by using a balanced binary tree
With string concatenation out of the way, we can now open large files but this leads us to another potential performance issue. Say we load a 64MB file, the piece table will have 1000 nodes. Even though we cache line break positions in every node, we don't know which absolute line number is in which node. To get the content of a line, we have to go through all nodes until we find the node containing that line. In our example, we have to iterate through up to 1000 nodes depending on which line number we look for. Thus, the time complexity of the worst case is O(N) (N is the count of nodes).
Caching the absolute line numbers in each node and using binary search on the list of nodes boosts lookup speed but whenever we modify a node, we have to visit all following nodes to apply the line number delta. This is a no-go but the idea of binary search is good. To achieve the same effect, we can leverage a balanced binary tree.
We now have to decide what metadata we should use as the key to compare tree nodes. As said, using the node's offset in the document or the absolute line number will bring the time complexity of editing operations to O(N). If we want a time complexity of O(log n), we need something that's only related to a tree node's subtree. Thus, when a user edits text, we recompute the metadata for the modified nodes, and then bubble the metadata change along the parent nodes all the way to the root.
If a Node has only four properties ( bufferIndex , start , length , lineStarts ), it takes seconds to find the result. To get faster, we can also store the text length and the line break count of a node's left subtree. This way searching by offset or line number from the root of the tree can be efficient. Storing metadata of the right subtree is the same but we don't need to cache both.
The classes now look like this:
Among all the different types of balanced binary trees, we choose red-black tree because it is more 'editing' friendly.
Reduce objects allocation
Assume we store the line break offsets in each node. Whenever we change the node, we might have to update the line break offsets. For example, say we have a node that contains 999 line breaks, the lineStarts array has 1000 elements. If we split the node evenly, then we'll create two nodes, each has an array containing around 500 elements. As we are not directly operating on linear memory space, splitting an array into two is more costly than just moving pointers.
The good news is that the buffers in a piece table are either readonly (original buffers) or append-only (changed buffers), so the line breaks within a buffer don't move. Node can simply hold two references to the line break offsets on its corresponding buffer. The less we do, the better the performance is. Our benchmarks showed that applying this change made the text buffer operations in our implementation three times faster. But more about the actual implementation later.
Piece tree
I'd love to call this text buffer "Multiple buffer piece table with red-black tree, optimized for line model". But in our daily standup, when everyone is limited to 90 seconds to share what they've been up to, repeating this long name multiple times would not be wise. So I simply started calling it "piece tree", which reflects what it is.
Having a theoretical understanding of this data structure is one thing, real world performance is another. The language you use, the environment the code runs in, the way clients invoke your API, and other factors may significantly affect the outcome. Benchmarks can provide a comprehensive picture so we ran benchmarks on small/medium/large files against the original line array implementation and the piece tree implementation.
Preparations
For telling results, I looked for realistic files online:
-
- 1.46 MB, 26k lines. - 4.31MB, 128k lines. - 14MB, 552k lines.
and manually created a couple of large files:
- Chromium heap snapshot of newly opened VS Code Insider - 54MB, 3M lines.
- checker.ts X 128 - 184MB, 3M lines.
1. Memory usage
The memory usage of the piece tree immediately after loading is very close to the original file size, and it is significantly lower than the old implementation. First round, piece tree wins:
2. File opening times
Finding and caching line breaks is much faster than splitting the file into an array of strings:
3. Editing
I have simulated two workflows:
- Making edits in random positions in the document.
- Typing in sequence.
I tried to mimic these two scenarios: Apply 1000 random edits or 1000 sequential inserts to the document, then see how much time every text buffer needs:
As expected, line array wins when the file is very small. Accessing a random position in a small array and tweaking a string which has around 100~150 characters is really fast. The line array starts to choke when the file has many lines (100k+). Sequential inserts in large files make this situation worse as the JavaScript engine does a lot of work in order to resize the large array. Piece tree behaves in a stable fashion as each edit is just a string append and a couple red-black tree operations.
4. Reading
For our text buffers, the hottest method is getLineContent . It is invoked by the view code, by the tokenizer, the link detector, and pretty much every component relying on document content. Some of the code traverses the entire file, like the link detector, while other code reads only a window of sequential lines, like the view code. So I set out to benchmark this method in various scenarios:
- Call getLineContent for all lines after doing 1000 random edits.
- Call getLineContent for all lines after doing 1000 sequential inserts.
- Read 10 distinct line windows after doing 1000 random edits.
- Read 10 distinct line windows after doing 1000 sequential inserts.
TA DA, we found the Achilles heel of piece tree. A large file, with 1000s of edits, will lead to thousands or tens of thousands of nodes. Even though looking up a line is O(log N) , where N is the number of nodes, that is significantly more than O(1) which the line array enjoyed.
Having thousands of edits is relatively rare. You might get there after replacing a commonly occurring sequence of characters in a large file. Also, we are talking about microseconds for each getLineContent call so it is not something we are concerned about at this time. Most of getLineContent calls are from view rendering and tokenization, and the post processes of line contents are much more time consuming. DOM construction and rendering or tokenization of a view port usually takes tens of milliseconds, in which getLineContent only accounts for less than 1%. Nevertheless, we are considering eventually implementing a normalization step, where we would recreate buffers and nodes if certain conditions such as a high number of nodes are met.
Conclusion and gotchas
Piece tree outperforms line array in most scenarios, with the exception of line based lookup, which was to be expected.
Lessons learned
- The most important lesson this reimplementation taught me is to always do real world profiling. Every time I found that my assumptions about which methods would be hot did not match reality. For example, when I started the piece tree implementation, I focused on tuning the three atomic operations: insert , delete and search . But when I integrated it in VS Code, none of those optimizations mattered. The hottest method was getLineContent .
- Dealing with CRLF or mixed line breaks sequences is a programmer's nightmare. For every modification, we need to check if it splits a Carriage Return/Line Feed (CRLF) sequence, or if it creates a new CRLF sequence. Dealing with all the possible cases, in the context of a tree, took several attempts until I had a solution that was correct and fast.
- GC can easily eat your CPU time. Our text model used to assume that the buffer is stored in an array and we frequently use getLineContent even though sometimes it wasn't necessary. For example, if we just want to know the character code of the first character of a line, we used a getLineContent first and then did charCodeAt . With piece tree, getLineContent creates a substring and after checking the character code, the line substring is thrown away immediately. This is wasteful and we are working on adopting better suited methods.
Why not native?
I promised at the beginning that I would get back to this question.
TL;DR: We tried. It didn't work out for us.
We built a text buffer implementation in C++ and used native node module bindings to integrate it in VS Code. The text buffer is a popular component in VS Code and thus many calls were being made to the text buffer. When both the caller and the implementation were written in JavaScript, V8 was able to inline many of these calls. With a native text buffer, there are JavaScript C++ round trips and given the number to round-trips, they slowed everything down.
For example, the VS Code Toggle Line Comment command is implemented by looping through all the selected lines, and analyzing them one-by-one. This logic is written in JavaScript, and will invoke TextBuffer.getLineContent for each line. For each call, we end up crossing the C++/JavaScript boundary and we have to return a JavaScript string in order to respect the API that all of our code is built on top of.
Our options are simple. In C++, we either allocate a new JavaScript string on each call to getLineContent which implies copying the actual string bytes around, or we leverage V8's SlicedString or ConstString types. However, we can use V8's string types only if our underlying storage is also using V8's strings. Unfortunately, V8's strings are not multi-thread safe.
We could have tried to overcome this by changing the TextBuffer API, or by moving more and more code to C++ to avoid the JavaScript/C++ boundary cost. However, we realized we were doing two things at the same time: we were writing a text buffer using a different data structure than a line array, and we were writing it in C++ rather than JavaScript. So, rather than spending half a year on something we didn't know would pay off, we decided to keep the text buffer's runtime in JavaScript, and only change the data structure and associated algorithms. In our opinion, this was the right decision.
Future work
We still have a handful of cases that need to be optimized. For example, the Find command currently runs line-by-line but shouldn't. We can also avoid needless calls to getLineContent when only a line substring is needed. We will incrementally release these optimizations. Even without these further optimizations, the new text buffer implementation provides a better user experience then what we had before and is now the default in the latest stable VS Code version.
VSCode — это кроссплатформенный редактор с открытым исходным кодом, ставший любимым среди программистов, особенно среди веб-разработчиков. Он быстрый, расширяемый и имеет массу возможностей и настроек. Если вы до сих пор не работали с ним, то советую попробовать.
Для VSCode созданы тысячи расширений. Я намерен представить несколько из них, которые использую каждый день. Приступим!
Quokka.js
Quokka.js — это плагин для JavaScript и TypeScript, который отображает результаты выполнения кода в редакторе, непосредственно во время его написания. Попробуйте сами!
Установив расширение, нажмите Ctrl/Cmd(⌘) + Shift + P, чтобы запустить палитру команд редактора, и затем введите Quokka, чтобы увидеть список доступных команд плагина. Выберите и запустите команду New JavaScript File или нажмите ⌘ + K + J, чтобы создать новый файл. Любой введенный код будет выполнен немедленно.
Похожие расширения:
-
— поддерживает множество языков (C, C++, Java, JavaScript, PHP, Python, Perl, Perl 6 и другие); .
Bracket Pair Colorizer & Indent Rainbow
Квадратные и круглые скобки — неотъемлемая часть многих языков программирования. В таком языке как Javascript, простая станица может иметь целый поток этих символов, среди которых тяжело отличить пары открытых и закрытых скобок. В этот момент на помощь приходят Bracket Pair Colorizer и Indent Rainbow. Это два разных расширения. Однако, вместе они представляют отличную комбинацию. Эти расширения наполнят ваш редактор морем красок, сделают блоки кода отличимыми друг от друга и придадут им приятный вид.
Без Bracket Pair Colorizer и Indent Rainbow
Установив Bracket Pair Colorizer и Indent Rainbow
Сниппеты
Сниппеты — это сокращения в редакторе, трансформируемые в полноценный код. Вместо import React from 'react'; пишем imr и жмем Tab, чтобы развернуть сниппет. В частности, clg разворачивается в console.log .
Существует множество сниппетов для разных направлений: JavaScript (или другие языки), React, Redux, Angular, Vue, Jest. Лично я считаю JavaScript сниппеты очень полезными, особенно с тех пор как начал работать преимущественно с JS.
Несколько хороших расширений со сниппетами:
Todo Highlighter
Часто бывает, написав функцию, вы понимаете, что есть лучший способ написать то же самое. Вы оставляете комментарий // TODO: Необходим рефакторинг , но затем забываете об этом и выкладываете код в production. C Todo Highlighter подобного не произойдет.
Плагин выделяет TODO/FIXME или другие комментарии в яркие цвета, что довольно тяжело не заметить. Модное нововведение Todo Highlighter — список выделенных комментариев, который выводится в консоли.
Todo Highlighter
Похожие расширения:
-
— более мощный плагин, с множеством новых возможностей; .
Import Cost
Это расширение позволяет увидеть размер импортируемых модулей. Вы сможете понять, в каком месте вы импортируете библиотеку целиком, а в каком конкретную ее часть. Это окажет неоценимую помощь со сборкой проекта в Webpack.
Import Cost
Rest Client
Rest Client
Auto Close Tag & Auto Rename Tag
Они также работают с JSX и множеством других языков (XML, PHP, Vue, JavaScript, TypeScript, TSX).
Auto Rename Tag
Auto Close Tag
Похожие расширения:
GitLens
Со слов автора, GitLens расширяет возможности Git, встроенного в Visual Studio Code. Плагин включает удивительное количество функций, таких как указание автора, поиск коммитов, история и проводник. Вы можете изучить полное описание этих возможностей здесь. Если вы работаете с Git, то вы обязаны установить этот плагин.
Существуют другие расширения, выполняющие специфические задачи. Если GitLens оказался для вас слишком объемным или вам не требуется большая часть его функций, то советую взглянуть на следующий список:
-
— отображает красивый граф истории коммитов. Рекомендуется. — позволяет увидеть информацию о текущей строке. Похожая функция встроена в GitLens. — позволяет увидеть изменения в файлах и количество добавленных и удаленных строк. — дает возможность, одной командой, открыть репозиторий в браузере.
Git Project Manager
GPM позволяет открыть окно с новым репозиторием напрямую из редактора. Проще говоря, вы можете открыть другой репозиторий не покидая VSCode.
После установки данного расширения, пропишите gitProjectManager.baseProjectsFolders в список адресов, содержащих репозитории.
Похожие расширения:
-
— лично не использовал, но он имеет более миллиона загрузок. Стоит попробовать.
Indenticator
Визуально выделяет текущую глубину отступа. С этим плагином, вы легко различите блоки, расположенные на разных уровнях.
Indenticator
Похожие расширения:
VSCode Icons
Новые иконки придадут редактору привлекательности!
VSCode Icons
Похожие расширения:
Dracula (Theme)
Полюбившийся мне внешний вид.
Dracula theme
Сочетания клавиш позволяют получать доступ к различным командам и окнам Visual Studio. В этом разделе перечислены сочетания клавиш по умолчанию для команд в профиле обычных параметров, который мог быть выбран при установке Visual Studio. Независимо от выбранного профиля сочетание клавиш для той или иной команды можно определить, открыв диалоговое окно Параметры, развернув узел Среда и выбрав элемент Клавиатура. Кроме того, сочетания клавиш можно настраивать, назначая командам другие сочетания клавиш.
Список распространенных сочетаний клавиш и другие сведения о средствах повышения производительности см. в следующих статьях:
Памятка по быстрым клавишам для печати
Популярные сочетания клавиш в Visual Studio
Все сочетания клавиш в этом разделе применяются глобально, если не указано иное. Глобальный контекст означает, что сочетание применяется в любом окне инструментов в Visual Studio.
Сочетание клавиш для той или иной команды можно определить, открыв диалоговое окно Параметры, развернув узел Среда и выбрав элемент Клавиатура.
Сборка: популярные сочетания клавиш
Отладка: популярные сочетания клавиш
Команды | Сочетания клавиш [специальные контексты] | Идентификатор команды |
---|---|---|
Прерывание на функции | CTRL+B | Debug.BreakatFunction |
Приостановить все | CTRL+ALT+BREAK | Debug.BreakAll |
Удаление всех точек останова | CTRL+SHIFT+F9 | Debug.DeleteAllBreakpoints |
Исключения | CTRL+ALT+E | Debug.Exceptions |
Быстрая проверка | CTRL+ALT+Q |
Редактирование: популярные сочетания клавиш
Команды | Сочетания клавиш [специальные контексты] | Идентификатор команды |
---|---|---|
Разрыв строки | ВВОД [текстовый редактор, конструктор отчетов, конструктор Windows Forms] |
или CTRL+ПРОБЕЛ [текстовый редактор, конструктор рабочих процессов]
или CTRL+K, W [конструктор рабочих процессов]
или SHIFT+DELETE [схема последовательностей, схема действий UML, схема слоев]
или CTRL+K, CTRL+L [конструктор рабочих процессов]
или CTRL+K, CTRL+P [конструктор рабочих процессов]
или SHIFT + ALT + BACKSPACE
Файл: популярные сочетания клавиш
Команды | Сочетания клавиш [специальные контексты] | Идентификатор команды |
---|---|---|
Выход | ALT+F4 | File.Exit |
Создание файла | CTRL+N | File.NewFile |
Новый проект | CTRL+SHIFT+N | File.NewProject |
Новый веб-сайт | SHIFT+ALT+N | File.NewWebSite |
Открывает файл | CTRL+O | File.OpenFile |
Открытие проекта | CTRL+SHIFT+O | File.OpenProject |
Открыть веб-сайт | Shift+Alt+O | File.OpenWebSite |
Переименовать | F2 [Team Explorer] | File.Rename |
Сохранить все | CTRL+SHIFT+S | File.SaveAll |
Сохранить выбранные элементы | CTRL+S | File.SaveSelectedItems |
Просмотр в браузере | CTRL+SHIFT+W | File.ViewinBrowser |
Проект: популярные сочетания клавиш
Команды | Сочетания клавиш [специальные контексты] | Идентификатор команды |
---|---|---|
Добавить существующий элемент | SHIFT+ALT+A | Project.AddExistingItem |
Добавление нового элемента | CTRL+SHIFT+A | Project.AddNewItem |
Рефакторинг: популярные сочетания клавиш
Команда | Сочетание клавиш [специальные контексты] | Идентификатор команды |
---|---|---|
Извлечение метода | CTRL+R, CTRL+M | Refactor.ExtractMethod |
Средства: популярные сочетания клавиш
Команда | Сочетание клавиш [специальные контексты] | Идентификатор команды |
---|---|---|
Присоединение к процессу | CTRL+ALT+P | Tools.AttachtoProcess |
Представление: популярные сочетания клавиш
Команды | Сочетания клавиш [специальные контексты] | Идентификатор команды |
---|---|---|
Окно классов | CTRL+SHIFT+C | View.ClassView |
Изменить метку | F2 | View.EditLabel |
Список ошибок | CTRL+\, CTRL+E |
Окно: популярные сочетания клавиш
Команды | Сочетания клавиш [специальные контексты] | Идентификатор команды |
---|---|---|
Активировать окно документа | ESC | Window.ActivateDocumentWindow |
Закрыть окно документа | CTRL+F4 | Window.CloseDocumentWindow |
Следующее окно документа | CTRL+F6 | Window.NextDocumentWindow |
Следующая панель навигации окна документа | CTRL+TAB | Window.NextDocumentWindowNav |
Следующая область разделения | F6 | Window.NextSplitPane |
Глобальные сочетания клавиш
Следующие сочетания клавиш являются глобальными. Это означает, что их можно использовать в любом окне Visual Studio, которое находится в фокусе.
Анализ: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Перейти назад | SHIFT+ALT+3 | Analyze.NavigateBackward |
Перейти вперед | SHIFT+ALT+4 | Analyze.NavigateForward |
Архитектура: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Создать схему | CTRL+\, CTRL+N | Architecture.NewDiagram |
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Повторить операцию скрипта мобильной службы | CTRL+NUM *, CTRL+R | WindowsAzure.RetryMobileServiceScriptOperation |
Показать сведения об ошибке скрипта мобильной службы | CTRL+NUM *, CTRL+D | WindowsAzure.ShowMobileServiceScriptErrorDetails |
Сборка: глобальные сочетания клавиш
Контекстные меню представления классов: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Свойства | ALT+ВВОД | ClassViewContextMenus.ClassViewMultiselectProjectreferencesItems.Properties |
Отладка: глобальные сочетания клавиш
Контекстные меню отладчика: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Удалить | ALT+F9, D | DebuggerContextMenus.BreakpointsWindow.Delete |
Перейти к дизассемблированию | ALT+F9, A | DebuggerContextMenus.BreakpointsWindow.GoToDisassembly |
Перейти к исходному коду | ALT+F9, S | DebuggerContextMenus.BreakpointsWindow.GoToSourceCode |
Центр диагностики: глобальные сочетания клавиш
Команда | Сочетание клавиш | Идентификатор команды |
---|---|---|
Остановка сбора | CTRL+ALT+F2 | DiagnosticsHub.StopCollection |
Редактирование: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Копировать | CTRL+C |
CTRL+SHIFT+Z
Контекстные меню редактора: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Условия точки останова | ALT+F9, C | EditorContextMenus.CodeWindow.Breakpoint.BreakpointConditions |
Метки изменения точки останова | ALT+F9, L | EditorContextMenus.CodeWindow.Breakpoint.BreakpointEditlabels |
Вставка временной точки останова | SHIFT+ALT+F9, T | EditorContextMenus.CodeWindow.Breakpoint.InsertTemporaryBreakpoint |
Показать элемент | CTRL+` | EditorContextMenus.CodeWindow.CodeMap.ShowItem |
Execute | CTRL+ALT+F5 | EditorContextMenus.CodeWindow.Execute |
Перейти к представлению | CTRL+M, CTRL+G | EditorContextMenus.CodeWindow.GoToView |
Переключить файл заголовков кода | CTRL+K, CTRL+O (латинская буква O) | EditorContextMenus.CodeWindow.ToggleHeaderCodeFile |
Просмотр иерархии вызовов | CTRL+K, CTRL+T |
Файл: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Выход | ALT+F4 | File.Exit |
Создание файла | CTRL+N | File.NewFile |
Новый проект | CTRL+SHIFT+N | File.NewProject |
Новый веб-сайт | SHIFT+ALT+N | File.NewWebSite |
Открывает файл | CTRL+O (латинская буква O) | File.OpenFile |
Открытие проекта | CTRL+SHIFT+O (латинская буква O) | File.OpenProject |
Открыть веб-сайт | SHIFT+ALT+O (латинская буква O) | File.OpenWebSite |
Печать | CTRL+P | File.Print |
Сохранить все | CTRL+SHIFT+S | File.SaveAll |
Сохранить выбранные элементы | CTRL+S | File.SaveSelectedItems |
Просмотр в браузере | CTRL+SHIFT+W | File.ViewinBrowser |
Справка: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Добавить и удалить содержимое справки | CTRL+ALT+F1 | Help.AddandRemoveHelpContent |
Справка F1 | F1 | Help.F1Help |
Посмотреть справку | CTRL+F1 | Help.ViewHelp |
Справка окна | SHIFT+F1 | Help.WindowHelp |
Нагрузочный тест: глобальные сочетания клавиш
Команда | Сочетание клавиш | Идентификатор команды |
---|---|---|
Перейти в область счетчиков | CTRL+R, Q | LoadTest.JumpToCounterPane |
Другие контекстные меню: глобальные сочетания клавиш
Команда | Сочетание клавиш | Идентификатор команды |
---|---|---|
Добавить новую диаграмму | Вставить | OtherContextMenus.MicrosoftDataEntityDesignContext.AddNewDiagram |
Проект: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Добавить существующий элемент | SHIFT+ALT+A | Project.AddExistingItem |
Добавление нового элемента | CTRL+SHIFT+A | Project.AddNewItem |
Мастер классов | CTRL+SHIFT+X | Project.ClassWizard |
Переопределение | CTRL+ALT+INS | Project.Override |
Предварительный просмотр изменений | ALT+; затем ALT+C | Project.Previewchanges |
Опубликовать выбранные файлы | ALT+; затем ALT+P | Project.Publishselectedfiles |
Заменить выбранные файлы с сервера | ALT+; затем ALT+R | Project.Replaceselectedfilesfromserver |
Контекстные меню проекта и решения: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Переместить вниз | ALT+СТРЕЛКА ВНИЗ | ProjectandSolutionContextMenus.Item.MoveDown |
Переместить вверх | ALT+СТРЕЛКА ВВЕРХ | ProjectandSolutionContextMenus.Item.MoveUp |
Рефакторинг: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Инкапсуляция поля | CTRL+R, CTRL+E | Refactor.EncapsulateField |
Извлечение интерфейса | CTRL+R, CTRL+I | Refactor.ExtractInterface |
Извлечение метода | CTRL+R, CTRL+M | Refactor.ExtractMethod |
Удалить параметры | CTRL+R, CTRL+V | Refactor.RemoveParameters |
Переименовать | CTRL+R, CTRL+R | Refactor.Rename |
Упорядочить параметры | CTRL+R, CTRL+O (латинская буква O) | Refactor.ReorderParameters |
Обозреватель решений: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Открыть фильтр файлов | CTRL+[ , O (латинская буква O) |
Команда: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Перейти к веткам Git | CTRL+0 (ноль), CTRL+N |
Контекстные меню Team Foundation: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Перейти к сборкам | CTRL+0 (ноль), CTRL+B |
Тестирование: глобальные сочетания клавиш
Обозреватель тестов: глобальные сочетания клавиш
Средства: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Присоединение к процессу | CTRL+ALT+P | Tools.AttachtoProcess |
Диспетчер фрагментов кода | CTRL+K, CTRL+B | Tools.CodeSnippetsManager |
Принудительная сборка мусора | CTRL+SHIFT+ALT+F12, CTRL+SHIFT+ALT+F12 | Tools.ForceGC |
Представление: глобальные сочетания клавиш
Окно: глобальные сочетания клавиш
Команды | Сочетания клавиш | Идентификатор команды |
---|---|---|
Активировать окно документа | ESC | Window.ActivateDocumentWindow |
Добавить вкладку в выделенный фрагмент | CTRL+SHIFT+ALT+ПРОБЕЛ | Window.AddTabtoSelection |
Закрыть окно документа | CTRL+F4 | Window.CloseDocumentWindow |
Закрыть окно инструментов | SHIFT+ESC | Window.CloseToolWindow |
Не закрывать вкладку | CTRL+ALT+HOME | Window.KeepTabOpen |
Перейти к панели навигации | CTRL+F2 | Window.MovetoNavigationBar |
Следующее окно документа | CTRL+F6 | Window.NextDocumentWindow |
Следующая панель навигации окна документа | CTRL+TAB | Window.NextDocumentWindowNav |
Следующая область | ALT+F6 | Window.NextPane |
Следующая область разделения | F6 | Window.NextSplitPane |
Следующая вкладка | CTRL+ALT+PGDN |
Сочетания клавиш, зависящие от контекста
Эти сочетания клавиш зависят от контекста. Это означает, что вы можете использовать их с меню и элементами в Visual Studio, которые относятся к типу проекта, языку программирования или платформе.
You can access a variety of commands and windows in Visual Studio by choosing the appropriate keyboard shortcut. This page lists the default command shortcuts for the General profile, which you might have chosen when you installed Visual Studio. No matter which profile you chose, you can identify the shortcut for a command by opening the Options dialog box, expanding the Environment node, and then choosing Keyboard. You can also customize your shortcuts by assigning a different shortcut to any given command.
For a list of common keyboard shortcuts and other productivity information, see:
For more information about accessibility in Visual Studio, see Accessibility tips and tricks and How to: Use the keyboard exclusively.
Printable shortcut cheatsheet
Popular keyboard shortcuts for Visual Studio
All shortcuts in this section apply globally unless otherwise specified. The Global context means that the shortcut is applicable in any tool window in Visual Studio.
You can look up the shortcut for any command by opening the Options dialog box, expanding the Environment node, and then choosing Keyboard.
Build: popular shortcuts
Debug: popular shortcuts
Commands | Keyboard shortcuts [Special contexts] | Command ID |
---|---|---|
Break at function | Ctrl+B | Debug.BreakatFunction |
Break all | Ctrl+Alt+Break | Debug.BreakAll |
Delete all breakpoints | Ctrl+Shift+F9 | Debug.DeleteAllBreakpoints |
Exceptions | Ctrl+Alt+E | Debug.Exceptions |
Quick watch | Ctrl+Alt+Q |
Edit: popular shortcuts
Commands | Keyboard shortcuts [Special contexts] | Command ID |
---|---|---|
Break line | Enter [Text Editor, Report Designer, Windows Forms Designer] |
or Ctrl+Spacebar [Text Editor, Workflow Designer]
or Ctrl+K, W [Workflow Designer]
or Shift+Delete [Sequence Diagram, UML Activity Diagram, Layer Diagram]
or Ctrl+K, Ctrl+L [Workflow Designer]
or Ctrl+K, Ctrl+P [Workflow Designer]
or Shift+Alt+Backspace
File: popular shortcuts
Commands | Keyboard shortcuts [Special contexts] | Command ID |
---|---|---|
Exit | Alt+F4 | File.Exit |
New file | Ctrl+N | File.NewFile |
New project | Ctrl+Shift+N | File.NewProject |
New web site | Shift+Alt+N | File.NewWebSite |
Open file | Ctrl+O | File.OpenFile |
Open project | Ctrl+Shift+O | File.OpenProject |
Open web site | Shift+Alt+O | File.OpenWebSite |
Rename | F2 [Team Explorer] | File.Rename |
Save all | Ctrl+Shift+S | File.SaveAll |
Save selected items | Ctrl+S | File.SaveSelectedItems |
View in browser | Ctrl+Shift+W | File.ViewinBrowser |
Project: popular shortcuts
Commands | Keyboard shortcuts [Special contexts] | Command ID |
---|---|---|
Add existing item | Shift+Alt+A | Project.AddExistingItem |
Add new item | Ctrl+Shift+A | Project.AddNewItem |
Refactor: popular shortcuts
Command | Keyboard shortcut [Special contexts] | Command ID |
---|---|---|
Extract method | Ctrl+R, Ctrl+M | Refactor.ExtractMethod |
Tools: popular shortcuts
Command | Keyboard shortcut [Special contexts] | Command ID |
---|---|---|
Attach to process | Ctrl+Alt+P | Tools.AttachtoProcess |
View: popular shortcuts
Commands | Keyboard shortcuts [Special contexts] | Command ID |
---|---|---|
Class view | Ctrl+Shift+C | View.ClassView |
Edit label | F2 | View.EditLabel |
Error list | Ctrl+\, Ctrl+E |
Window: popular shortcuts
Commands | Keyboard shortcuts [Special contexts] | Command ID |
---|---|---|
Activate document window | Esc | Window.ActivateDocumentWindow |
Close document window | Ctrl+F4 | Window.CloseDocumentWindow |
Next document window | Ctrl+F6 | Window.NextDocumentWindow |
Next document window nav | Ctrl+Tab | Window.NextDocumentWindowNav |
Next split pane | F6 | Window.NextSplitPane |
Global shortcuts
These keyboard shortcuts are global, which means that you can use them when any Visual Studio window has focus.
Analyze: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Navigate backward | Shift+Alt+3 | Analyze.NavigateBackward |
Navigate forward | Shift+Alt+4 | Analyze.NavigateForward |
Commands | Keyboard shortcuts | Command ID |
---|---|---|
New diagram | Ctrl+\, Ctrl+N | Architecture.NewDiagram |
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Retry mobile service script operation | Ctrl+Num *, Ctrl+R | WindowsAzure.RetryMobileServiceScriptOperation |
Show mobile service script error details | Ctrl+Num *, Ctrl+D | WindowsAzure.ShowMobileServiceScriptErrorDetails |
Build: global shortcuts
Class View context menus: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Properties | Alt+Enter | ClassViewContextMenus.ClassViewMultiselectProjectreferencesItems.Properties |
Debug: global shortcuts
Debugger context menus: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Delete | Alt+F9, D | DebuggerContextMenus.BreakpointsWindow.Delete |
Go to disassembly | Alt+F9, A | DebuggerContextMenus.BreakpointsWindow.GoToDisassembly |
Go to source code | Alt+F9, S | DebuggerContextMenus.BreakpointsWindow.GoToSourceCode |
Diagnostics Hub: global shortcuts
Command | Keyboard shortcut | Command ID |
---|---|---|
Stop collection | Ctrl+Alt+F2 | DiagnosticsHub.StopCollection |
Edit: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Copy | Ctrl+C |
Ctrl+Shift+Z
Editor context menus: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Breakpoint conditions | Alt+F9, C | EditorContextMenus.CodeWindow.Breakpoint.BreakpointConditions |
Breakpoint edit labels | Alt+F9, L | EditorContextMenus.CodeWindow.Breakpoint.BreakpointEditlabels |
Insert temporary breakpoint | Shift+Alt+F9, T | EditorContextMenus.CodeWindow.Breakpoint.InsertTemporaryBreakpoint |
Show item | Ctrl+` | EditorContextMenus.CodeWindow.CodeMap.ShowItem |
Execute | Ctrl+Alt+F5 | EditorContextMenus.CodeWindow.Execute |
Go to view | Ctrl+M, Ctrl+G | EditorContextMenus.CodeWindow.GoToView |
Toggle header code file | Ctrl+K, Ctrl+O (letter 'O') | EditorContextMenus.CodeWindow.ToggleHeaderCodeFile |
View call hierarchy | Ctrl+K, Ctrl+T |
File: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Exit | Alt+F4 | File.Exit |
New file | Ctrl+N | File.NewFile |
New project | Ctrl+Shift+N | File.NewProject |
New web site | Shift+Alt+N | File.NewWebSite |
Open file | Ctrl+O (letter 'O') | File.OpenFile |
Open project | Ctrl+Shift+O (letter 'O') | File.OpenProject |
Open web site | Shift+Alt+O (letter 'O') | File.OpenWebSite |
Ctrl+P | File.Print | |
Save all | Ctrl+Shift+S | File.SaveAll |
Save selected items | Ctrl+S | File.SaveSelectedItems |
View in browser | Ctrl+Shift+W | File.ViewinBrowser |
Help: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Add and remove help content | Ctrl+Alt+F1 | Help.AddandRemoveHelpContent |
F1 help | F1 | Help.F1Help |
View help | Ctrl+F1 | Help.ViewHelp |
Window help | Shift+F1 | Help.WindowHelp |
Load Test: global shortcuts
Command | Keyboard shortcut | Command ID |
---|---|---|
Jump to counter pane | Ctrl+R, Q | LoadTest.JumpToCounterPane |
Other context menus: global shortcuts
Command | Keyboard shortcut | Command ID |
---|---|---|
Add new diagram | Insert | OtherContextMenus.MicrosoftDataEntityDesignContext.AddNewDiagram |
Project: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Add existing item | Shift+Alt+A | Project.AddExistingItem |
Add new item | Ctrl+Shift+A | Project.AddNewItem |
Class wizard | Ctrl+Shift+X | Project.ClassWizard |
Override | Ctrl+Alt+Ins | Project.Override |
Preview changes | Alt+; then Alt+C | Project.Previewchanges |
Publish selected files | Alt+; then Alt+P | Project.Publishselectedfiles |
Replace selected files from server | Alt+; then Alt+R | Project.Replaceselectedfilesfromserver |
Project and Solution context menus: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Move down | Alt+Down Arrow | ProjectandSolutionContextMenus.Item.MoveDown |
Move up | Alt+Up Arrow | ProjectandSolutionContextMenus.Item.MoveUp |
Refactor: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Encapsulate field | Ctrl+R, Ctrl+E | Refactor.EncapsulateField |
Extract interface | Ctrl+R, Ctrl+I | Refactor.ExtractInterface |
Extract method | Ctrl+R, Ctrl+M | Refactor.ExtractMethod |
Remove parameters | Ctrl+R, Ctrl+V | Refactor.RemoveParameters |
Rename | Ctrl+R, Ctrl+R | Refactor.Rename |
Reorder parameters | Ctrl+R, Ctrl+O (letter 'O') | Refactor.ReorderParameters |
Solution Explorer: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Open files filter | Ctrl+[, O (letter 'O') |
Team: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Go to git branches | Ctrl+0 (zero), Ctrl+N |
Team Foundation context menus: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Go to builds | Ctrl+0 (zero), Ctrl+B |
Test: global shortcuts
Test Explorer: global shortcuts
Tools: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Attach to process | Ctrl+Alt+P | Tools.AttachtoProcess |
Code snippets manager | Ctrl+K, Ctrl+B | Tools.CodeSnippetsManager |
Force gc | Ctrl+Shift+Alt+F12, Ctrl+Shift+Alt+F12 | Tools.ForceGC |
View: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
All windows | Shift+Alt+M | View.AllWindows |
Architecture explorer | Ctrl+\, Ctrl+R | View.ArchitectureExplorer |
Backward | Alt+Left Arrow (Functions differently from View.NavigateBackward in Text Editor) | View.Backward |
Bookmark window | Ctrl+K, Ctrl+W | View.BookmarkWindow |
Browse next | Ctrl+Shift+1 | View.BrowseNext |
Browse previous | Ctrl+Shift+2 | View.BrowsePrevious |
Call hierarchy | Ctrl+Alt+K | View.CallHierarchy |
Class view | Ctrl+Shift+C | View.ClassView |
Class view go to search combo | Ctrl+K, Ctrl+V | View.ClassViewGoToSearchCombo |
Code definition window | Ctrl+\, D |
Window: global shortcuts
Commands | Keyboard shortcuts | Command ID |
---|---|---|
Activate document window | Esc | Window.ActivateDocumentWindow |
Add tab to selection | Ctrl+Shift+Alt+Space | Window.AddTabtoSelection |
Close document window | Ctrl+F4 | Window.CloseDocumentWindow |
Close tool window | Shift+Esc | Window.CloseToolWindow |
Keep tab open | Ctrl+Alt+Home | Window.KeepTabOpen |
Move to navigation bar | Ctrl+F2 | Window.MovetoNavigationBar |
Next document window | Ctrl+F6 | Window.NextDocumentWindow |
Next document window nav | Ctrl+Tab | Window.NextDocumentWindowNav |
Next pane | Alt+F6 | Window.NextPane |
Next split pane | F6 | Window.NextSplitPane |
Next tab | Ctrl+Alt+PgDn |
Context-specific shortcuts
These keyboard shortcuts are context specific, which means that you can use them with menus and items in Visual Studio that are specific to a project type, programming language, or platform.
Читайте также: