简体   繁体   中英

How to change the indentation width in emacs javascript mode

I'd like to use 2 spaces for my indents instead of 4. I can change the default behavior of C mode using:

(setq c-basic-offset 2)

How do I change this in javascript mode?

js-indent-level can be used in the default javascript-mode, which is included by default starting in emacs 23.2.

(setq js-indent-level 2)

should do what you're looking for. If you're using an older version of emacs, you may be in java-mode. I think this mode responds to c-basic-offset , however I may be wrong.

I wish someone had told me about Custom a lot sooner! Perhaps this will help another mere mortal like me ;)

Invoke Custom:

M-x customize

Then, choose "Programming," and then "Languages," and then select a language/mode to customize. Edit the options as you see fit. When done, choose either "Save for current session" or "Save for future sessions."

If you're using js2-mode (which is more powerful IMHO), then the command is:

(setq-default js2-basic-offset 2)

Source.

您可能还希望将emacs设置为使用空格而不是制表符

(setq-default indent-tabs-mode nil)

In my javascript.el file (/usr/share/emacs/site-lisp) I found

javascript-indent-level 4

So if you are using the same lisp-mode you can change it by running

(setq javascript-indent-level 2)

You can also use

M-x customize-variable

and type

js-indent-level

( js- [TAB] shows a list of options). Then change the Js Indent Level as wanted and click [State:] and save.

如果要基于每个文件更改它,请将其放在文件的顶部:

// -*- mode: js; js-indent-level: 2; -*-

Using EditorConfig could be a good idea too. And of course, Emacs had a mode for it editorconfig-emacs .

It's also available in the package manager ( Mx package-list-packages ) through Melpa or Marmalade.

None of these solutions worked for me after upgrading to Emacs 26 (I already had js-indent-level set to 2 but my tab width went back to 8), but what did work was setting the tab-width variable to 2 , which seems to replace the old default-tab-width variable.

I found this in Mx customize by searching for tab width .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM