For better or worse, PHP code often includes both HTML and Javascript. Getting Vim to indent it all correctly can be tricky.

My .vimrc specifies that a tab should always be two spaces:

set tabstop=2
set softtabstop=2
set shiftwidth=2

This indent file does a good job with indenting mixed PHP and HTML and uses 2 spaces for both, but for some reason, it indents embedded Javascript with 4 spaces. The code snippet below gets auto-indented as shown.

<?PHP
  if (false) {
    $foo = 'foo';
  }
?>
<html>
  <head>
    <script type="text/javascript">
      function(){
          if (false) {

              // Four spaces!?
              var foo = 'foo';
          }
      }
    </script>
  </head>
</html>

If I create a separate javascript file, it indents as it should, like so:

if (false) {
  var foo = 'foo';
}

I'm not sure why Vim indents the Javascript in the first example as it does. Is there a way to ask Vim "what syntax or indentation are you using on this specific line?"

link|improve this question

62% accept rate
That sounds right. The convention in Javascript is to use 4 spaces. Check your Javascript syntax file. It may or may not be delegating it to that. – digitxp Aug 31 '11 at 15:58
@digitxp - I don't have a /syntax/javascript.vim currently. I do have a indent/javascript, but that just decides when to indent or unindent, not how many spaces to use for an indent. And, as I said, a separate JS file gets indented with my default of two spaces. – Nathan Long Aug 31 '11 at 19:06
Now that I think about it, I suspect that BOTH the PHP and HTML rules are being applied. – Nathan Long Aug 31 '11 at 19:07
feedback

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
or
required, but never shown

Browse other questions tagged or ask your own question.