Align Inline Comments in Code

Align trailing comments in source code so they start at the same column, improving readability of annotated code blocks.

Code Formatting

Detailed Explanation

Aligning Inline Comments

When multiple lines of code each have a trailing comment, aligning those comments at the same column makes the annotations far easier to scan. This is especially useful in configuration files, assembly language, and heavily-commented code blocks.

Before

port = 8080 # HTTP server port
host = "0.0.0.0" # Bind to all interfaces
workers = 4 # Number of worker processes
timeout = 30 # Request timeout in seconds
max_connections = 1000 # Maximum concurrent connections
debug = false # Enable debug mode

After

port            = 8080       # HTTP server port
host            = "0.0.0.0"  # Bind to all interfaces
workers         = 4          # Number of worker processes
timeout         = 30         # Request timeout in seconds
max_connections = 1000       # Maximum concurrent connections
debug           = false      # Enable debug mode

Two-Pass Approach

Aligning code with both assignments and comments requires splitting on the right delimiter. One effective approach:

  1. First pass — Use the Equals = delimiter to align the keys and values.
  2. Second pass — Use the Custom delimiter with # to align the comment markers.

Each pass aligns one set of columns, producing the clean result above.

Comment Styles

This technique works with any comment marker:

  • # — Python, Ruby, Shell, YAML
  • // — JavaScript, TypeScript, C, Go, Rust
  • -- — SQL, Lua, Haskell
  • ; — Assembly, INI files

Set the appropriate marker as the custom delimiter for each language.

Use Case

A Python developer wants to align inline comments on a block of configuration assignments before merging a pull request.

Try It — Text Column Aligner

Open full tool