In VSCode, how can I turn a multi-line comment into a paragraph with no line breaks? - visual-studio-code

What's an easy way to convert a multi-line comment (e.g. JSDoc with each line separated by line breaks) into a paragraph without any line breaks that I can copy into an email or another document?
I know I can use search & replace with regular expressions, but is there a more ergonomic way to do it?

You probably knew that you can use multiple cursors to change multiple lines at once, but did you know you can also use them to remove line breaks? Assume you start with this comment:
/**
* Returns a new `Temporal.LocalDateTime` instance representing the first
* valid time during the current calendar day and time zone of `this`.
*
* The local time of the result is almost always `00:00`, but in rare cases it
* could be a later time e.g. if DST starts at midnight in a time zone. For
* example:
* ```
* const ldt = Temporal.LocalDateTime.from('2015-10-18T12:00-02:00[America/Sao_Paulo]');
* ldt.startOfDay; // => 2015-10-18T01:00-02:00[America/Sao_Paulo]
* ```
*/
First part: use multiple cursors to remove the prefix characters on each line.
Click on the upper-left corner of the comment (the /**).
Now hold down Cmd+Shift (Alt+Shift on PC) and click after the */ on the last line of the comment section.
This will create a columnar, multi-line selection that includes the non-text prefix characters on each line. If the selection doesn't include all the prefix characters, you can hold down the Shift key and use the left or right arrow keys to adjust the width of the selection.
Press the Delete key to remove prefix characters on all lines.
Second part: it's time to delete the line breaks and replace them with spaces. I discovered today that you can use multiple cursors for this part too!
After you've deleted the prefix text above, but before you've pressed any other keys, press the backspace key. It will delete the line breaks but leave each cursor in the same place!
Type the spacebar once to insert one space to replace each line break.
Press ESC to clear multiple selections, and delete the extra space at the start of the line. You may have an extra space(s) at the end of the line too that may need trimming.
Copy the resulting one-line text.
Use Cmd+Z (Ctrl+Z on Windows) to undo the last few changes so your code comment will be back to normal.
Now you can paste the copied text into an email!
The same solution works to replace line breaks with spaces in any multi-line text, not only code comments.
I'm sure that many of you already knew how to do this trick, but I found it so easy and so cool that I thought it was worth sharing as a Q&A here so others can learn about this trick too.
Here's what the steps look like in the VSCode IDE:
Before deleting, you should see something like this:
After deleting prefix characters:
After deleting line breaks (note the multiple cursors are still there):
After inserting spaces in place of the deleted line breaks:

I usually select the first line break, then hit/hold command+D repeatedly to add cursors at all line endings I want to edit. Then, just hit space once.

Related

How to convert embedded CRLF codes to their REAL newlines in Vscode?

I searched everywhere for this, the problem is that the search criteria is very similar to other questions.
The issue I have is that file (script actually) is embedded in another file. So when I open the parent file I can see the script as massive string with several \n and \r\n codes. I need a way to convert these codes to what they should be so that it formats the code correctly then I can read said code and work on it.
Quick snippet:
\n\n\n\n\nlocal scriptingFunctions\n\n\n\n\nlocal measuringCircles = {}\r\nlocal isCurrentlyCheckingCoherency
Should covert to:
local scriptingFunctions
local measuringCircles = {}
local isCurrentlyCheckingCoherency
perform a Regex Find-Replace
Find: (\\r)?\\n
Replace: \n
If you don't need to reconvert from newlines to \n after you're done working on the code, you can accomplish the trick by simply pressing ctrl-f and substituting every occurrence of \n with a new line (you can type enter in the replace box by pressing ctrl-enter or shift-enter).
See an example ctrl-f to do this:
If after you're done working on the code you need to reconvert to \n, you can add an invisible char to the replace string (typing it like ctrl-enter invisibleChar), and after you're done you can re-replace it with \n.
There's plenty of invisible chars, but I'd personally suggest [U+200b] (you can copy it from here); another good one is [U+2800] (⠀), as it renders as a normal whitespace, and thus is noticeable.
A thing to notice is that recent versions of vscode will show a highlight around invisible chars, but you can easily disable it by clicking on Adjust settings and then selecting Exclude from being highlighted.
If you need to reenable highlighting in the future, you'll have to look for "editor.unicodeHighlight.allowedCharacters" in the settings.

How do you delete lines with certain keywords in VScode

I have this regular expression to find certain keywords on a line:
.*(word1|word2|word3).*
In the find and replace feature of the latest VSCode it works ok and finds the words but it just blanks the lines leaving big gaps in-between.
I would like to delete the entire line including linefeed.
The find and replace feature doesnt seem to support reg exp in the replace field.
If you want to delete the entire line make your regex find the entire line and include the linefeed as well. Something like:
^.*(word1|word2|word3).*\n?
Then ALT-Enter will select all lines that match and Delete will eliminate them including the lines they occupied.

Regex to delete all empty lines whatsoever?

In Windows 10 I use a text editor (I'd like not to point out a particular one but I usually use Visual Studio Code AKA "VSCODE").
I need a way to delete all blank lines whatsoever only with regex after I matched them with this code:
^\s*$
After I match the lines themselves, how is it possible to delete the lines?
AFAIK, regex only edit lines, not deleting lines or adding lines.
I desire a way to delete all matched (empty).
Hitting "Enter" or "Delete" in the empty "replace" box doesn't delete lines:
You were close. You were missing the new line character in your regex. This worked for me:
^\s*$\n
Without the newline character, you are matching the blank line itself which you then replace with nothing but you've left the newline character so it still leaves an empty line in place.

How can I remove duplicate lines in Visual Studio Code?

Say you have the following text:
abc
123
abc
456
789
abc
abc
I want to remove all "abc" lines and just keep one. I don't mind sorting. The result should be like this:
abc
123
456
789
If the order of lines is not important
Sort lines alphabetically, if they aren't already, and perform these steps:
(based on this related question: How do I find and remove duplicate lines from a file using Regular Expressions?)
Control+F
Toggle "Replace mode"
Toggle "Use Regular Expression" (the icon with the .* symbol)
In the search field, type ^(.*)(\n\1)+$
In the "replace with" field, type $1
Click ("Replace All").
If the order of lines is important so you can't sort
In this case, either resort to a solution outside VS Code (see here), or - if your document is not very large and you don't mind spamming the Replace All button - follow the previous steps, but in steps 4 and 5, enter these:
(based on Remove specific duplicate lines without sorting)
Caution: Blocks for files with too many lines (1000+); may cause VS Code to crash; may introduce blank lines in some cases.
search: ((^[^\S$]*?(?=\S)(?:.*)+$)[\S\s]*?)^\2$(?:\n)?
replace with: $1
and then click the "Replace All" button as many times as there are duplicate occurrences.
You'll know it's enough when the line count stops decreasing when you click the button. Navigate to the last line of the document to keep an eye on that.
Coming in vscode v1.62 is a command to eliminate duplicate lines from a selection:
Delete Duplicate Lines in the Command Palette
or
editor.action.removeDuplicateLines as a command in a keybinding
(there is no default keybinding for this command)
Here is a very interesting extension: Transformer
Features:
Unique Lines As New Document
Unique Lines
Align CSV
Align To Cursor
Compact CSV
Copy To New Document
Count Duplicate Lines As New Document
Encode / Decode
Filter Lines As New Document
Filter Lines
Join Lines
JSON String As Text
Lines As JSON String Array
Normalize Diacritical Marks
Randomize Lines
Randomize Selections
Reverse Lines
Reverse Selections
Rotate Backward Selections
Rotate Forward Selections
Select Highlights
Select Lines
Selection As JSON String
Sort Lines By Length
Sort Lines
Sort Selections
Split Lines After
Split Lines Before
Split Lines
Trim Lines
Trim Selections
Unique Lines
Removes duplicate lines from the document Operates on selection or
current block if no selection
Unique Lines As New Document
Unique lines are opened in a new document Operates on selection or
current block if no selection
I haven't played with it much besides the "Unique Lines" command but it seems quite nicely done (including attempting a macro recorder!).
To add to #Marc.2377 's reply.
If the order is important and you don't care that you just keep the last of the duplicate lines, simply search for the following regexp if you want to only remove duplicte non-empty lines
^(.+)\n(?=(?:.*\n)*?\1$)
If you also want to remove duplicate empty lines, use * instead of +
^(.*)\n(?=(?:.*\n)*?\1$)
and replace with nothing.
This will take a line and try to find ahead some more (maybe 0) lines followed by the exact same line taken. It will remove the taken line.
This is just a one-shot regex. No need to spam the replace button.
This now also takes the comment of #awk into account, in where the last line has to have a linefeed in order to be identified as a duplicate. This is no longer the case now by excluding the \n from the line to search and adding a $ to the line found.
I just had the same issue and found the Visual Studio Code package "Sort lines". See the Visual Studio Code market place for details (e.g. Sort lines).
This package has the option "Sorting lines (unique)", which did it for me. Take care of any white spaces at the beginning/end of lines. They influence whether lines are considered unique or not.
Install the DupChecker extension, hit F1, and type "Check Duplicates".
It will check for duplicates and ask if you want to remove them.
Try find and replace with a regular expression.
Find:
^(.+)((?:\r?\n.*)*)(?:\r?\n\1)$
Replace:
$1$2
It is possible to introduce some variance in the first group.
If you don't mind some Vim in your VS Code. You can install Vim emulation plugin.
Then you can use vim commands
:sort u
It will sort lines and it will remove duplicates
Sublime Text 3
It has blisteringly fast native permutation functions.
Edit > Permute Lines > Unique or ⇧⌘U, and
Edit > Permute Selections > Unique
Visual Studio Code is my daily driver. But, I keep Sublime Text on standby for these situations.
Not actually in Visual Studio Code, but if it works, it works.
Open a new Excel spreadsheet
Paste the data into a column
Go to the Data tab
Select the column of data (if you haven't already)
Click Remove Duplicates (somewhat in the middle of the bar)
Click OK to remove duplicates.
It is not the best answer, as you specified Visual Studio Code, but as I said: If it works, it works :)

How do I get a cursor on every line in vscode

I'm trying to use the multi cursor functionality of vscode on a large(ish) file.
the file is too large to select every line individually with ctrl-alt-up or down. In sublime-text I would select everything and push ctrl-shift-l. Is there a similar thing in vscode. I've tried using a regex search for ^, but that gives me an error stating "Expression matches everything".
The command Selection / Add Cursors to Line Ends altshifti will put a cursor on every line in the current selection. (For mac use optshifti)
Tip: You can pull up the keyboard shortcut reference sheet with ctrlk,ctrls (as in, those two keyboard combos in sequence).
(For mac use cmdk,cmds)
Hold Alt+Shift and select the block. Then press End or Right button.
You get selected individual lines.
I use version VSCode 1.5.3 in Windows.
Hold Alt+Shift+i
Hold Home (fn+-> Mac) for right-most or End for left most(fn+<- Mac)
This feature is actually called split selection into lines in many editors.
Sublime Text uses the default keybinding, CTRLSHIFT L
VSCode uses ALTSHIFTI
For Atom you actually need to edit your keymap to something like this
'.platform-win32 .editor, .platform-linux .editor':
'ctrl-shift-L': 'editor:split-selections-into-lines'
Real Lines vs Display Lines
First we have to understand the difference between Real Lines and Display Lines to completely understand the answer of the question.
When Word Wrap is enabled, each line of text that exceeds the width of the window will display as wrapped. As a result, a single line in the file may be represented by multiple lines on the display.
The easiest way to tell the difference between Real Lines and Display Lines is by looking at the line number in the left margin of the text editor. Lines that begin with a number correspond to the real lines, which may span one or more display lines. Each time a line is wrapped to fit inside the window, it begins without a line number.
Cursor At the Beginning of each Display Lines:
Cursor At the Beginning of each Real Lines:
Answer to the Question
Now that we know the difference between Display Lines and Real Lines, we can now properly answer the actual question.
Hold AltShift and select the text block.
Press Home to put cursor on the beginning of every Display Line.
Press End to put cursor on the end of every Display Line.
Press HomeHome (Home twice) to put cursor on the beginning of every Real Line.
Press EndEnd (End twice) to put cursor on the end of every Real Line.
Please understand that AltShiftI put cursor on the end of every Real Line.
Install the extension Sublime Commands.
[Sublime Commands] Adds commands from Sublime Text to VS Code: Transpose, Expand Selection to Line, Split into Lines, Join Lines.
(Don't forget to add the keybinding(s) from the extensions details page to your keybindings.json)
Doesn't VS Code already have a "split into lines" command?
Yes, yes it does. However it differs from the one in Sublime.
In VS Code, when you split into lines your selection gets deselected and a cursor appears at the end of each line that was selected (except for the last line where the cursor appears at the end of the selection).
In Sublime, when you split into lines a cursor appears at the end of each line (with the same exception as in VS Code) and the selection is divided on each line and "given" to the same line.
I have the same problem, i'm used to Alt + drag to do 'box selections' in visual studio but it does'n work in code.
It seems to be impossible for now to do it differently than by selecting every single line.
However plugins should be supported soon so we will likely see a plugin for this if not implemented directly by microsoft.
From visual studio uservoice forums:
We plan to offer plugin support for Visual Studio Code. Thank you for your interests and look for more details in our blog in the coming weeks. http://blogs.msdn.com/b/vscode.
For the preview we are looking for exactly this type of feedback. Keep it coming.
Sean McBreen – VS Code Team Member