I have turned on Word Wrap in VSCode, so that long lines are wrapped at certain window widths.
If I want to comment out some code or text, I usually just move the cursor to the beginning of the first line of the block of code, use ctrl+shift+down to add cursors, and type the // or # etc..
The problem with Word Wrap is that I not only get cursors in the beginning of each actual line, but in the beginning of every line as it is displayed at the moment in the editor.
For example, for the following document:
1 This is the first line.
2 Second line.
It might be wrapped like this:
1 This is the first
line.
2 Second line.
So if I use the method above and add % I would get:
1 %This is the first
%line.
2 %Second line.
But what I want is the following:
1 %This is the first
line.
2 %Second line.
Otherwise, I have a % in the middle of the line, just because I resized the editor window.
At the moment, I actually turn off Word Wrap to achieve this, but I hope there is a better way?
Follow the next steps:
Alt+Shift+i to put a cursor on every selected line
Cmd/Ctrl+← to move all cursors to the beginning of the [wrapped] lines
Cmd/Ctrl+← (again) to move all cursors to the actual beginning of the [wrapped] lines
Enjoy! 🙂
Update v1.62+ (October 2021)
This is now natively available in VSCode thanks to this PR on changing the default behavior of InsertCursorAbove/Below. However, it's not enabled by default.
You'll need to update your keybindings to pass in an args like this:
{
"key": "shift+alt+down",
"command": "editor.action.insertCursorBelow",
"when": "textInputFocus",
"args": { "logicalLine": true },
},
{
"key": "shift+alt+up",
"command": "editor.action.insertCursorAbove",
"when": "textInputFocus",
"args": { "logicalLine": true },
},
This appears to be a known issue. The CursorColumnSelectOnTrueLines extension by Martin Zimmermann provides commands that show the desired behavior, by default mapped to Ctrl+Alt+Shift+Up/Down.
Related
I want to save my current cursor position, move to some other line (in the same file), do some editing and jump back to the original cursor position to continue coding.
Lets say i am in line 50 and realise i need to add a header/library file at line 5. I want save my position here so that i can jump back after making my changes at line 5. How can i do this?
I have looked into cursor navigation shortcuts but they all move cursor by tracing every position cursor was in, and its time consuming and confusing, instead i want to jump back to saved position in one shot.
You could use the selection anchor. There is no default keybinding for "Go to Selection Anchor" so you'd have to add one yourself.
There is no built-in command for that. The Go Back / Go Forward navigation commands doesn't allows you to save specific locations.
Instead, you should rely on extensions, like my Bookmarks extensions.
There is a bunch of other similar extensions, as you can see on this search https://marketplace.visualstudio.com/search?term=bookmarks&target=VSCode&category=All%20categories&sortBy=Relevance. You should take a look at some, and try out the one that better fit our needs.
Hope this helps
Thanks #scottfrazer for the suggesting selection anchor.
Thanks #alefragnani for suggesting extensions.
Based on these answers, i wrote a keybinding using multi command extension,
After installing the multi command extension,
Add the following snippets in the keybindings.json,
[
{
"key": "ctrl+alt+`",
"command": "extension.multiCommand.execute",
"when": "!selectionAnchorSet",
"args": {
"sequence": [
"editor.action.setSelectionAnchor",
]
}
},
{
"key": "ctrl+alt+`",
"command": "extension.multiCommand.execute",
"when": "selectionAnchorSet",
"args": {
"sequence": [
"editor.action.goToSelectionAnchor",
"editor.action.cancelSelectionAnchor",
]
}
},
]
Above snippet will create a key binding for "ctrl+alt+`" (Ctrl + Alt + BackTick).
When pressed,
Creates a selection anchor at cursor position
If an anchor already exists, Move to that cursor position and deletes that anchor at that position.
what's the quickest way for me, in VSCode, to find and replace a comment structured like this:
/**
* Comment here
*/
With:
// Comment here
Bearing in mind here the actual comment itself should persist, so just the comment syntax being changed.
I'm hoping there is an easy find & replace operation I haven't come across before that I can perform in the editor.
Thanks!
Unless there is a vscode command to toggle a doc comment (which would make this much easier) you can do it with an extension that can run multiple finds and replaces and commands.
Using Find and Transform, an extension I wrote, make this keybinding (in your keybindings.json):
{
"key": "alt+s", // whatever keybinding you want
"command": "findInCurrentFile",
"args": {
// 2 finds and 2 replaces
"find": ["(^[ \t]*\\/\\*\\*\n)([\\s\n\\S]*?)(^\\s*\\*\\/\n)", "^([ \t]*) \\*\\s*(.*)"],
"replace": ["$2", "$1$2"],
"isRegex": true,
"cursorMoveSelect": "$1$2", // select the result for the postCommands to act on
"postCommands": ["editor.action.commentLine", "cancelSelection"]
},
}
The first find captures the entire jdoc-style comment and keeps only the interior lines. The second find and replace removes the leading * from those lines.
The result is then selected so that the postCommands can be run adding line comments.
[I didn't spend a lot of time on the regex's so double-check those.]
Say for example I have a very long line of text in a single line in VS Code (let's pretend that the example given below is very long).
0xffffffffeeeeeeee02020202aaaaaaaa
At first I placed my cursor after the characters 0x.
(the cursor is denoted by the | character in the example below)
0x|ffffffffeeeeeeee02020202aaaaaaaa
Then I want to add more cursors after every N characters from the current cursor. In this case N is equal to 8 and I want to do this twice to add two more cursor like in the example below.
0x|ffffffff|eeeeeeee|02020202aaaaaaaa
So that after I press the following sequence of keys in the keyboard, in this case those sequence of keys are ,(space)0x I should be able to get these final result.
0x, 0x|ffffffff, 0x|eeeeeeee, 0x|02020202aaaaaaaa
After I deselect the cursors I should be getting this
0x, 0xffffffff, 0xeeeeeeee, 0x02020202aaaaaaaa
Is this possible to do in VS code?
There is a straightforward regex that can do what you want:
Find: ^0x|(.{8})(?!$)
But you have to enable the Find in Selection option and trigger the Select All Matches command yourself after entering it.
Or use a macro extension like multi-command and this keybinding to automate it:
{
"key": "alt+p",
"command": "extension.multiCommand.execute",
"args": {
"sequence": [
{
"command": "editor.actions.findWithArgs",
"args": {
"findInSelection": true,
"isRegex": true,
"searchString": "^0x|.{8}",
}
},
"editor.action.selectAllMatches",
"cursorRight"
]
},
}
You must select up to where you want the last cursor and then trigger the macro.
Because of a flaky implementation, you must start with the Find in Selection option disabled in the Find Widget. I haven't found a way around that.
The setting Editor > Find: Seed Search String From Selection must be set to never. Otherwise your selected text will over-ride the searchString from the macro above.
Here is the pure regex method with no extensions:
Enter ^0x|(.{8})(?!$) in your Find Widget with the regex option enabled.
^0x the first part of the string you ultimately want a cursor after.
(.{8})(?!$) select each 8-character block, but not the last - that is why there is a negative lookahead for the end of the line (?!$) - so the last 8 characters are not matched. Don't worry, there will be a cursor in front of those last 8 characters as you want. (.{8}) doesn't actually need to be in a capture group, it is just clearer to see.
Select all the text to match: 0xffffffffeeeeeeee. Stop the selection there - wherever you want the last cursor.
Enable the Find in Selection option in the Find Widget by Alt+L.
Alt+Enter to select all the find matches respecting the Find in Selection option: editor.action.selectHighlights.
Step (4) will select your matches - you should have 4 for the above string. But you don't want the matches selected you just want a cursor at the beginning of each, so do step (5):
Right arrow: this cancels each selection with a cursor at the right end of each.
Type.
You can use the extension Select By
It has a command to add a new cursor by keyboard
{
"key": "ctrl+i ctrl+alt+right", // or any other key combo
"when": "editorTextFocus",
"command": "selectby.addNewSelection",
"args": {"offset": 8}
}
Now the offset is hard coded but I will add an option to ask the user the offset.
The possibility of the context switch is already working. I have to update the README.
In this snippet defined in keybindings.json I'm trying to run a regex transform on the input result from choice dialogue - I need the same value inserted twice, in 1st position I need the part before the first semicolon and in 2nd position I want the full choice value.
I tried examples from the doc but they don't seem to be working with the choice, or am I missing something? How do I achieve this?
{
"key": "cmd+alt+ctrl+t",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "Before semicolon: ${2/(\\w);{1,}/$1/} & Full value: ${2|1; testValue1, 2; testValue2|}"
}
},
expected output:
BeforeSemicolon: 1 & Full value: 1; testValue1
After some experimentation I have found a partial working.
It is important that the regex matches the full string. So add .* at the end.
(This should be added to the documentation)
{
"key": "cmd+alt+ctrl+t",
"command": "editor.action.insertSnippet",
"when": "editorTextFocus",
"args": {
"snippet": "Before semicolon: ${1/([^;]*).*/$1/} && Full value: ${1|123; testValue1,223; testValue2|}" }
},
And it only works for the first choice, AND you have to move the cursor inside the option text, just 1 Left Arrow is enough, this accepts the choice but keeps the field active. And then TAB. Now the transform is applied.
You have to file a bug for this.
Transform of choice variables is not supported. There is a general discussion mentioning this at https://github.com/Microsoft/vscode/pull/51621.
There are a couple of workarounds because transforms of placeholders do work as long as there is one non-transformed usage of the placeholder somewhere in the snippet. Then a transformed version elsewhere will work. This technique works for placeholder transforms but NOT choice transforms as you are trying to do. Why that difference I don't know??
Simpler workaround 1 using one placeholder:
"snippet": "Before semicolon: ${1/([^;]*).*/$1/} && Full value: ${1:1; testValue1}"
Here you would have to accept the default placeholder value (1; testValue1) or overwrite it with another value. Then on tab the transform will be applied to any other references to that same tabstop.
Complex workaround 2 usings multiple placeholders (in this case for 3 "choices":
"snippet": "Before semicolon: ${1/([^;]*).*/$1/}${2/([^;]*).*/$1/}${3/([^;]*).*/$1/} && Full value: ${1:1; testValue}${2:2; testValue}${3:3; testValue}"
Here you have to list your three (or however many you have) choices as separate placeholder tabstops. Then you will either tab to accept that placeholder you want or deletetab those you don't. It is a little tricky getting the delete/tab sequence down but once you have it, it is repetitve. You see the cursor appears to be at the beginning of the next "choice" but it is really at the end of the previous "choice".
Here is a demo of version 2 where I choose each "choice"/placeholder in turn. [I'm just using the alti keybinding here to simplify.]
Obviously if potentially have a lot of "choices" you'll probably want to use version 1. If you have a small number of "choices" that you want to be presented with and not have to type, version 2 does work pretty well.
Is there any way to select column with keyboard shortcut and expand selection till the end of each line?
Currently, when cursor reaches the end of the line it jumps to the beginning of the next one.
How can I avoid this behavior without using mouse?
If I've understood your question correctly, you can do that with the following keys (example with OS X keybindings):
Ctrl + Shift + Up or Ctrl + Shift + Down to select a column in multiple lines.
Cmd + Shift + Right (Shift + End on other OS's) to extend the selection up to the end of each line.
The related keybindings for all OS's:
http://www.sublimetext.com/docs/2/column_selection.html
I came to this answer because I was searching how to place the cursor in all the lines until EOF (end of file) without using ctrl+alt+▲/▼ (not pratical for more than a few dozens of lines), so I could trim or select a specific part of those lines.
So I eventually ended up in the sublime text documentation where I found:
ctrl+shift+L which will place cursors in all the lines selected and at the end of them (EOL):
select those lines with ctrl+L (or ctrl+shift+End to select until EOF);
press ctrl+shift+L to add cursors at EOLs;
now you can move all the cursors simultaneously by words with ctrl+◄/► or to the BOLs/EOLs with Home/End), if you also press shift you will select while moving them;
but the most useful feature is definitely the middle click of the mouse + drag which selects the lines and simultaneously places cursors at the end of those selections:
BONUS: If you just want to place the cursors at EOLs (without selecting) click on the background (after the EOLs) and drag! (if the lines are too long you can use the minimap to position your view-screen at the longest line);
now you can move all the cursors simultaneously by words with ctrl+◄/► or to the BOLs with Home), if you also press shift you will select while moving them.
You can also get the same result by the following steps:
select lines by Shift + Up/Down
split selection into lines (of selections): Cmd + Shift + L
import sublime, sublime_plugin
class SelectToEndoflineCommand(sublime_plugin.TextCommand):
def run(self, edit):
caretPos = self.view.sel()[0].begin()
self.view.sel().add(sublime.Region(caretPos, self.view.line(caretPos).end()))
class SelectToBegoflineCommand(sublime_plugin.TextCommand):
def run(self, edit):
caretPos = self.view.sel()[0].begin()
self.view.sel().add(sublime.Region(caretPos, self.view.line(caretPos).begin()))
robertcollier4's answer solved the question for me. For some reason the super+shift+right default OSX keybinding is overwritten in Sublime Text 3, and there is no way to properly unbind it in the user-key-bindings.
To add robert's code as a plugin go to Tools > New Plugin, paste the code, save it and add a reference to it in your keymapping:
[
{ "keys": ["super+shift+right"], "command": "SelectToEndoflineCommand" }
]
The only change I made to it was to change
caretPos = self.view.sel()[0].begin()
to
caretPos = self.view.sel()[0].end()
for the EOL function, otherwise it won't work correctly for multi-line selections.
For sublime text 2 - consider the answers above such as Bart & Robert's solution
For sublime text 4 (and likely 3) - you can create custom keybindings that differentiate between moving and selecting without any extra functions. You just need to set the extends option appropriately. For example, here's my Default (linux).sublime-keymap file:
[
{"keys": ["super+left"], "command": "move_to", "args": {"to": "bol", "extend": false}},
{"keys": ["super+right"], "command": "move_to", "args": {"to": "eol", "extend": false}},
{"keys": ["super+shift+left"], "command": "move_to", "args": {"to": "bol", "extend": true}},
{"keys": ["super+shift+right"], "command": "move_to", "args": {"to": "eol", "extend": true}}
]
Note how the only difference above is in how I set extends: false for moving only, but for moving and selecting I set extends: true. If you want to support both moving and selecting, from my experience so far you need to have both custom lines in there.