39

I like to fold code in the VS Code editor, but when I fold some code blocks, they are opened when I move over them with my cursor using j / k using the VS Code Vim extension. How can I protect my code folds from automatically opening like this?

2

3 Answers 3

101

It looks like this is an issue many people have had for a while, and the solution is to do the following (original source):

  1. Open up your user settings. On windows the shortcut is CTRL + ,
  2. Search for vim.foldfix and check the checkbox so the setting is set to true.

Alternatively, open your settings.json file by opening the command palette (CTRL + SHIFT + P), select Preferences: Open Settings (JSON), then add the following line: "vim.foldfix": true

Now the folds should no longer automatically expand when you scroll past them with j or k.

Be aware that this is a hack because of various problems with VS Code itself that make fixing this difficult.

7
  • same problem happened to me. Automatically my cursor up and down when I following upper way. Commented Jun 17, 2018 at 1:10
  • Did this solve your problem, or are you saying it's still not working? I'm not sure I understand your comment. Commented Jun 17, 2018 at 1:18
  • It had been worked in some manner, but the side effect generated. The side effect is overwhelming so I just toggled the option to false. My original problem was folded codes are automatically opened when I cursor crossing down to these block, But when I toggled the option as true, my cursor cannot work properly when I push 'J' or 'K'. Commented Jun 17, 2018 at 1:41
  • I see. Hopefully they will add a proper fix soon, but it might be a while. Commented Jun 17, 2018 at 1:51
  • 9
    Only works with "J" "K", folds still open with using <C-d>, and other movements.
    – Logan
    Commented Sep 9, 2020 at 2:45
8

For people who want to prevent this without implementing the hacking way suggested by the best answer, you can simply use gj & gk to navigate.

Furthermore, if gj & gk is not convenient for you, a little mapping might help.

1
  • 1
    Really helpful answer. Also thanks for linking to other issue for more context Commented Feb 22, 2023 at 16:56
0

Note that the hacky way using vim.foldfix breaks whatever the name is for "column saving?"

In other words, if you hit a newline, the cursor will be reset to the start of the line for every future line. Instead of the desired default behavior of keeping the column position.

Use gj and gk like louielyl mentioned to avoid this issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.