or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Detect Indent

Detect Indent analyzes text content to identify indentation patterns in source code. It determines whether tabs or spaces are used for indentation and calculates the indentation amount, making it ideal for preserving existing code style when modifying files.

Package Information

  • Package Name: detect-indent
  • Package Type: npm
  • Language: JavaScript (ES Module)
  • Installation: npm install detect-indent

Core Imports

ESM (ES Modules):

import detectIndent from "detect-indent";

For TypeScript projects:

import detectIndent, { Indent } from "detect-indent";

CommonJS:

const detectIndent = require("detect-indent");

Basic Usage

import fs from 'node:fs';
import detectIndent from 'detect-indent';

// Read a file with existing indentation
const fileContent = fs.readFileSync('example.js', 'utf8');

// Detect the indentation pattern
const result = detectIndent(fileContent);
console.log(result);
// { amount: 4, type: 'space', indent: '    ' }

// Use detected indent or fallback to default
const indent = result.indent || '    ';

// Apply the detected indentation when modifying the file
const modifiedContent = JSON.stringify(data, null, indent);

Capabilities

Indentation Detection

Analyzes text content to detect indentation patterns by examining differences between consecutive non-empty lines.

/**
 * Detect the indentation of code
 * @param string - A string of any kind of text to analyze
 * @returns Indent object containing indentation statistics
 * @throws TypeError if input is not a string
 */
function detectIndent(string: string): Indent;

Algorithm Details:

The detection algorithm analyzes indentation by examining differences between consecutive non-empty lines:

  1. Primary Detection: Looks for the most common difference between consecutive non-empty lines
  2. Single Space Handling: Ignores single space indents by default to avoid false positives from comments or alignment
  3. Fallback Strategy: If no indentation is detected, re-analyzes including single spaces for comprehensive detection
  4. Tie Breaking: When usage counts are equal, prefers tab indentation and uses a weighting system based on line frequency
  5. Weight Calculation: Lines with the same indentation level contribute weight for tie-breaking without counting as new "uses"

Example Analysis: In code with mixed indentation, even if 4-space indentation appears 3 times vs 2-space appearing 2 times, the algorithm detects 2-space as more common if there were 4 consecutive line differences with 2-space vs only 2 differences with 4-space:

html {
  box-sizing: border-box;  /* 2-space difference */
}

body {
  background: gray;        /* 2-space difference */
}

p {
    line-height: 1.3em;     /* 4-space difference */
    margin-top: 1em;        /* Same level (weight +1) */
    text-indent: 2em;       /* Same level (weight +1) */
}

Result: 2-space indentation detected (4 uses/differences vs 2 uses/differences for 4-space)

Usage Examples:

// Detect space indentation
const spaceCode = `
function example() {
    const a = 1;
    const b = 2;
}`;
const spaceResult = detectIndent(spaceCode);
// { amount: 4, type: 'space', indent: '    ' }

// Detect tab indentation
const tabCode = `
function example() {
\tconst a = 1;
\tconst b = 2;
}`;
const tabResult = detectIndent(tabCode);
// { amount: 1, type: 'tab', indent: '\t' }

// No indentation detected
const noIndentCode = `const a = 1;
const b = 2;`;
const noIndentResult = detectIndent(noIndentCode);
// { amount: 0, type: undefined, indent: '' }

Types

interface Indent {
  /**
   * The type of indentation detected
   * 'tab' for tab characters, 'space' for spaces, undefined if no indentation
   */
  type: 'tab' | 'space' | undefined;
  
  /**
   * The amount of indentation characters
   * For spaces: number of spaces (e.g., 2, 4)
   * For tabs: number of tab characters (usually 1)
   */
  amount: number;
  
  /**
   * The actual indentation string
   * For spaces: the space characters (e.g., '  ', '    ')
   * For tabs: the tab characters (e.g., '\t', '\t\t')
   * Empty string if no indentation detected
   */
  indent: string;
}

Error Handling

The function validates its input and handles various edge cases:

  • TypeError: Thrown when the input is not a string
  • No indentation: Returns { amount: 0, type: undefined, indent: '' } when no indentation pattern is detected
  • Empty input: Returns { amount: 0, type: undefined, indent: '' } for empty strings
  • Mixed indentation: Analyzes patterns to determine the most prevalent indentation style
// Error handling example
try {
  const result = detectIndent(123); // TypeError: Expected a string
} catch (error) {
  console.error(error.message); // "Expected a string"
}

// Fallback pattern for no indentation
const result = detectIndent('no indentation here');
const safeIndent = result.indent || '  '; // Use detected or fallback to 2 spaces