Search code examples
visual-studiogithubindentation

GitHub breaks Visual Studio indentation


I wonder why my code gets messy after I push it to GitHub.
For example, when I indent members of some class, so they are all aligned it looks nice in Visual Studio and ugly in GitHub.

Here is an example:

Indentation in Visual Studio

And how it looks in GitHub:

Indentation in GitHub


Solution

  • First, make sure all your indent as actual tabs, not spaces.

    Second, by default, GitHub would display tabs as 8 characters. So try and see the same GitHub page, but adding at the end of its URL: ?ts=4

    That is:

    https://gist.github.com/razzorflame/ef776ddef260608bc1a8799090af629e?ts=4

    tabs looks good

    Or... configure your Visual Studio to use a tab width of 8 (not ideal though).


    As mentioned here, you can add a .editorconfig (like this one for gist) with:

    root = true
    
    [*]
    end_of_line = lf
    insert_final_newline = true
    
    # Matches multiple files with brace expansion notation
    [*.{js,jsx,html,sass}]
    charset = utf-8
    indent_style = tab
    indent_size = 4
    trim_trailing_whitespace = true
    
    [*.md]
    trim_trailing_whitespace = false 
    

    Then GitHub should display tabs using the right width (4).


    As an illustration of the use of .editorconfig, Git itself, with Git 2.26 (Q1 2020), tells .editorconfig that in this project, *.txt files are indented with tabs.

    See commit 7047f75 (05 Jan 2020) by Hans Jerry Illikainen (illikainen).
    (Merged by Junio C Hamano -- gitster -- in commit 34246a1, 30 Jan 2020)

    editorconfig: indent text files with tabs

    Signed-off-by: Hans Jerry Illikainen

    Previously, the .editorconfig did not specify an indentation style for text files.

    However, a quick look for indentation-like spacing suggest that tabs are more common for documentation:

    $ git grep -Pe '^ {4}' -- '*.txt' |wc -l 
    2683 
    $ git grep -Pe '^\t' -- '*.txt' |wc -l 
    14011
    

    Note that there are a lot of files that indent list continuations (and other things) with a single space -- if the first search was made without the fixed quantifier the result would look very different.
    However, the result does correspond with my anecdotal experience when editing Git documentation.

    This commit adds *.txt to .editorconfig as an extension that should be indented with tabs.