Force Sublime Text Editor to use 4 spaces for indentation
Asked Answered
D

4

8

I've been looking for the reason why my code kept showing 2 spaces instead of 4.

In the bottom also show as Spaces : 4.

enter image description here


Code

<!DOCTYPE html>
<html lang="en">

<head>

  @include('layouts.fe.meta')
  @include('layouts.fe.links')
  <link rel="stylesheet" type="text/css" href="{{ elixir('assets/fe/css/all.css') }}"/>

  <link href="https://fonts.googleapis.com/css?family=Roboto:400,500" rel="stylesheet">
  <link rel="stylesheet" href="/css/hover-min.css">
  <link rel="stylesheet" href="/css/magnific-popup.css">
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

  <style type="text/css">
  body{
    font-family: 'Roboto', sans-serif !important;
  }

  #back_home {
    position: absolute;
    left: 10px;
    top: 5px;
  }
</style>

</head>

<body>

  <a href="/#portfolio" style="color:white;" class="btn btn-sm btn-success" id="back_home">Back Home</a>

  <section id="page-portfolio" class="page-portfolio">
    <div class="container">
      <div class="row text-center" style="padding: 0px !important; margin: 0px !important;">

        <header class="section-header">
          <h2 class="section-title"><span>Portfolio</span></h2>
          <div class="spacer"></div>
          <p class="section-subtitle">While designing, I always balance usability and standard elements with other design criteria. </p>
        </header>


        <div class="clearfix">
          <div class="cbp-l-filters-button cbp-l-filters-left">
            <div data-filter="*" class="cbp-filter-item-active cbp-filter-item">All</div>
            <div data-filter=".personal" class="cbp-filter-item">Personal</div>
            <div data-filter=".professional" class="cbp-filter-item">Professional</div>
            <div data-filter=".freelance" class="cbp-filter-item">Freelance</div>
          </div>
        </div>

        <div class="gallery">

          @if(count($portfolios)>0)
          @foreach($portfolios as $portfolio)
          <?php $images = $portfolio->portfolioimages()->get()->toArray(); ?>


          <div class="col-xs-6 col-sm-2 img-pop cbp-item {{ $portfolio->type }} " style="padding: 0px !important; margin: 0px !important;">
           <a href="{!! $images[0]['image_path'] !!}">
             <img class="hvr-shrink" src="{!! $images[0]['image_path'] !!}">
           </a>
         </div>


         @endforeach
         @endif
       </div>



       <a style="color:#555" href="/" class="btn btn-default hire-me">Go Back</a>

     </div>
   </div>
 </section>


 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <script src="/js/jquery.cubeportfolio.js"></script>

 <script src="/js/jquery.magnific-popup.min.js"></script>
 <script type="text/javascript">


  /* Magnific Popup */
  $('.img-pop').magnificPopup({
    delegate: 'a',
    type: 'image',
    gallery: {
      enabled: true
    }
  });

  // init cubeportfolio
  $('.gallery').cubeportfolio({
    filters: '.cbp-l-filters-button',
    loadMore: '#js-loadMore-lightbox-gallery',
    loadMoreAction: 'click',
    layoutMode: 'grid',
    mediaQueries: [{
      width: 1500,
      cols: 5
    }, {
      width: 1100,
      cols: 4
    }, {
      width: 800,
      cols: 3
    }, {
      width: 480,
      cols: 2
    }, {
      width: 320,
      cols: 1
    }],
    defaultFilter: '*',
    animationType: 'rotateSides',
    gapHorizontal: 10,
    gapVertical: 10,
    gridAdjustment: 'responsive',
    caption: 'zoom',
    displayType: 'sequentially',
    displayTypeSpeed: 100,

    // lightbox
    lightboxDelegate: '.cbp-lightbox',
    lightboxGallery: true,
    lightboxTitleSrc: 'data-title',

  });

</script>

</body>

</html>

This is hard to see.


Settings

I added these 3 lines

 "tab_size": 4,
 "translate_tabs_to_spaces": true,
 "detect_indentation": false

All settings

{
    "caret_extra_width": 2,
    "caret_style": "phase",
    "close_windows_when_empty": false,
    "color_scheme": "Packages/User/SublimeLinter/Monokai (SL).tmTheme",
    "copy_with_empty_selection": false,
    "drag_text": false,
    "draw_minimap_border": true,
    "enable_tab_scrolling": false,
    "findreplace_small": true,
    "font_face": "Source Code Pro",
    "font_options":
    [
        "no_round"
    ],
    "font_size": 12,
    "highlight_line": true,
    "highlight_modified_tabs": true,
    "ignored_packages":
    [
        "SublimeLinter",
        "Vintage"
    ],
    "match_brackets_content": false,
    "match_selection": false,
    "match_tags": false,
    "open_files_in_new_window": false,
    "overlay_scroll_bars": "enabled",
    "predawn_findreplace_small": true,
    "predawn_quick_panel_small": true,
    "predawn_sidebar_arrows": false,
    "predawn_sidebar_large": true,
    "predawn_sidebar_medium": false,
    "predawn_sidebar_small": false,
    "predawn_sidebar_xlarge": false,
    "predawn_sidebar_xsmall": false,
    "predawn_tabs_active_underline": true,
    "predawn_tabs_large": true,
    "predawn_tabs_medium": false,
    "preview_on_click": true,
    "scroll_past_end": false,
    "scroll_speed": 5.0,
    "show_full_path": true,
    "sidebar_default": true,
    "theme": "predawn-DEV.sublime-theme",
    "translate_tabs_to_spaces": true,
    "trim_trailing_white_space_on_save": true,
    "word_wrap": true,
    "tab_size": 4,
    "translate_tabs_to_spaces": true,
    "detect_indentation": false
}

How would one achieve this?

Dovetailed answered 18/9, 2018 at 15:35 Comment(14)
Select all the code (ctrl + a) and cut it (ctrl + x) and then paste it back in (ctrl + v) - that should trigger the reformat of the code and adhere to the tab size.Edgar
you want to use tab size 4 and spaces 4 is that what you mean?Toothpick
@ChristianGallarmin : yes. That is what I want.Dovetailed
are you using sublime text 3?Toothpick
@ChristianGallarmin : Yes, I used Sublime Text 3. I added that tag in my post.Dovetailed
@Edgar : I tried what you suggested (cmd+a, cmd+x, cmd+v), and re-indent after. My code indentation still messed up with 2 spaces.Dovetailed
There's a setting: Sublime Text -> Preferences -> Key Bindings. You can manually set bindings there. For example, I use { "keys": ["f12"], "command": "reindent"}, so highlighting code and pressing F12 will reindent. Your settings look ok otherwise. Did you quit and reopen?Skidproof
@TimLewis I mentioned I’ve tried indent already. 👍🏼Dovetailed
@kyo can you put use_tab_stops": true, as well?Toothpick
@ChristianGallarmin : let me try that now, and update you guys.Dovetailed
If your indent preference doesn't match your file and you want to change it, use the options in the indent menu (click the status bar where it says Spaces: 4); set the tab size to what it looks like visually (2), select convert indentation to tabs, change the indent back to what you want (4), select convert indentation to spaces.Prawn
Note also that if you're working with files that aren't visibly indented correctly, in order to ensure that Sublime honors your indent preference you may need to turn off the detect_indentation setting; it's true by default and will (potentially) make the settings in a file different than what you expect when you open it.Prawn
@Prawn I tried ur suggestion and it didn’t seem to work. I’m not sure if I follow u correctly. Can u use the file that I posted and see if you can properly indented and pasted it back along in your answer below. I’ll follow your steps again when u can show that it working. Thanks for your help so far.Dovetailed
What more are you expecting from answers? The answers look detailed enough.Bhopal
P
9

The issue you're facing here is that you have set your preferred indent size in Sublime, but the file that you're working with is already indented in a way that doesn't match your settings.

As such you should be able to notice that when you press Tab it skips four spaces like it should, and newly added code is indented the way you want it to be but existing code is left alone unless you manually fix it.

The three settings that control this are the ones that you mentioned in your question:

  • tab_size controls how wide a tab character is assumed to be, in characters, which is used in a visual setting to determine not only how much space a tab should take up, but also things like the positioning of the indent guides.

  • translate_tabs_to_spaces tells Sublime that any time it would insert a literal tab character, it should instead convert that tab into tab_size spaces on the fly. This is visualized in menus as an item named Indent Using Spaces being either checked or unchecked as appropriate.

  • detect_indentation controls whether or not Sublime honours the above two settings to the letter or not. When it's set to true (the default, but not what you're using) when a file is loaded Sublime tries to guess the appropriate indent settings by analyzing the file.

Looking at the image in your question, you can see that the status line says Spaces: 4 to indicate that the settings are tab_size of 4 and translate_tabs_to_spaces being true, and the indent guides are positioned the way you want, but the code is indented wrong.

Since we know that the indent is definitely set to 4 but the code looks like it's indented only 2, we know that your code doesn't contain any tab characters, or it would appear the way you want it to. If you had detect_indentation turned on, the file would visually appear the same, but Sublime would change the tab_size to 2 for that file to match what it sees in the buffer.

In any case, you have to take steps to manually fix the file so that it matches your preferred indentation settings.

Perhaps the simplest way to do that would be to select the entire file with Selection > Select All (or the appropriate key), and then select Edit > Line > Reindent from the menu or Indentation: Reindent Lines from the command palette.

Results of this may or may not be mixed; it uses the same internal logic that Sublime uses for indenting while you're typing. So based on the type of file that you're editing and the contents of that file, it's possible that the contents may be changed in ways other than just changing the indent.

If that's not desirable, you can perform the change manually with a few steps, using commands Sublime already has built in. The easiest place to find those commands is in the menu that pops up when you click the status bar where it's showing you your indent settings (Spaces: 4), but make sure that you're actively editing the appropriate file first because every open file is allowed to have different settings:

  • Use Guess Settings From Buffer or Tab Width: 2 to change the tab size to the one uses in the file. The status line will change to Spaces: 2 and you'll see the number of indent guides double as the new setting takes effect.

  • Use Convert Indentation to Tabs to convert all of the leading indent from spaces to tabs. The status line will change to Tab Size: 2 to show you that it's using tabs, and if you select text in the buffer you can see that the leading white space is now tab characters.

  • Use Tab Width: 4 to change the size of the tabs. The status line will change to Tab Size: 4 and you'll see the indent in the file visibly jump out to your new setting.

  • Use Convert Indentation to Spaces. The status line will change back to Spaces: 4, which puts everything back to how it started originally, but with a modified file.

If you have a lot of such files to fix, these steps may be a bit tedious to take. In such a case, you can shortcut all of the steps by opening up a file that needs to be changed, opening the Sublime console with View > Show Console (or the key binding), and then entering the following command in the console input and hitting Enter:

view.run_command("detect_indentation"); view.run_command("unexpand_tabs", {"set_translate_tabs": True}); view.settings().set("tab_size", 4); view.run_command("expand_tabs", {"set_translate_tabs": True})

I've formatted it here as a wrapped line for visibility, but when you paste it should be one long line. This executes each of the commands mentioned above one after the other, which should fix the file for you in one step.

Sample of the conversion in process

Prawn answered 20/9, 2018 at 3:55 Comment(0)
L
2

In Sublime Text Editor

  1. Click on View tab

  2. Select Indentation

  3. Then select Tab Width:4

You will get your code with 4 spaces and at the bottom you will see as Tab Size:2

Lutherlutheran answered 30/9, 2018 at 18:52 Comment(1)
This helped me. My actual tab size was correct, but the visualization was wrong (showing as Tab 2). So my file was good, just a view setting. Thanks for the response.Muniments
B
0

You have

"tab_size": 4,
"translate_tabs_to_spaces": true,
"detect_indentation": false

In my opinion line 3 negates line 1. Try with:

"tab_size": 4,
"translate_tabs_to_spaces": true,
"detect_indentation": true
Baseball answered 1/10, 2018 at 14:49 Comment(0)
A
0

Select all then press:

View → Indentation → Tab 4

Aeroneurosis answered 7/6, 2021 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.