outdent

repository·main·Indexed 41 days ago

https://github.com/cspotcode/outdent

A utility for removing leading indentation from ES6 template literals, allowing for readable, indented code in source files without including that indentation in the resulting string values. Version 0.8.0 supports Deno, ECMAScript modules, and CommonJS. It provides a tagged template literal interface, a .string() method for plain strings, and configurable options for trimming leading/trailing newlines and normalizing newline characters.

Tokens
2.1K
Snippets
10
Records
12
Agent score
2%

What's inside outdent

  1. Specify a custom indentation level with ${outdent}

    main

    You can explicitly set the indentation level by placing ${outdent} as the first interpolated value in the template string. The indentation level of this placeholder is used as the baseline and is removed from the final output.

    Requirement: ${outdent} must be alone on its own line without any preceding or following non-whitespace characters.

    const output = outdent`
          ${outdent}
            Yo
        12345
              Hello world
    `;
    
    assert(output === '  Yo\n345\n    Hello world');
  2. Install and import outdent

    main

    Import outdent using your preferred module system. It supports Deno (via JSR or DenoLand), ECMAScript modules, and CommonJS.

    // Deno w/JSR
    import outdent from 'jsr:@cspotcode/outdent';
    
    // Deno w/DenoLand
    import outdent from 'https://deno.land/x/outdent/mod.ts';
    
    // ECMAScript modules
    import outdent from 'outdent';
    
    // CommonJS
    const outdent = require('outdent');
  3. Best practices for using outdent

    main

    To ensure correct indentation detection, follow these guidelines:

    1. Start on a new line: Always start your content on a new line after the opening backtick. If you start content on the same line as the opening backtick, outdent may fail to detect the indentation of subsequent lines correctly.
    2. Consistency: Spaces and tabs are treated identically. While outdent handles both, you should use them consistently within your strings to avoid unexpected results.
    // BAD: Content starts on the same line as the backtick
    const output = outdent `* item 1
                              * sub-item
    `;
    
    // GOOD: Content starts on a new line
    const output = outdent `
        * item 1
          * sub-item
    `;
  4. Configure outdent options

    main

    You can pass an options object to outdent to customize its behavior. Note that when passing options, you call outdent as a function rather than using it as a tag directly (e.g., outdent({...})`string``).

    // Example: Disabling newline trimming
    const output = outdent({trimLeadingNewline: false, trimTrailingNewline: false})`
        Hello world!
    `;
    assert(output === '\nHello world!\n');
    
    // Example: Normalizing newlines
    const s = outdent({newline: '\r\n'}) `
        first
        second
    `;
    assert(s === 'first\r\nsecond');
  5. Import outdent in different module systems

    main

    The package supports multiple import patterns depending on your environment:

    ES Modules (Recommended):

    import outdent from 'outdent';
    // or
    import { outdent } from 'outdent';

    CommonJS:

    const outdent = require('outdent');
  6. Use outdent as a template tag

    main

    Use outdent as a tagged template literal to remove leading indentation from multi-line strings. By default, it also removes the leading and trailing newlines created by the template literal syntax.

    import outdent from 'outdent';
    
    const markdown = outdent`
        # My Markdown File
    
        Here is some indented code:
    
            console.log("hello world!");
    `;
    
    console.log(markdown);
    // Output:
    // # My Markdown File
    //
    // Here is some indented code:
    //
    //     console.log("hello world!");
  7. Remove indentation from plain strings with outdent.string()

    main

    If you are not using template literals, you can use the outdent.string() method to process a standard string.

    import outdent from 'outdent';
    
    const output = outdent.string('\n    Hello world!\n');
    
    assert(output === 'Hello world!');
  8. Configure outdent via the Options interface

    main

    When creating a custom instance, you can provide an Options object to control the transformation behavior:

    • trimLeadingNewline (boolean, optional): If true, removes the first newline from the template literal. Defaults to true in the default instance.
    • trimTrailingNewline (boolean, optional): If true, removes the last newline from the template literal. Defaults to true in the default instance.
    • newline (string | null, optional): If a string is provided, all newlines (\r\n, \r, or \n) in the template literal are normalized to this value. If null, newlines are left untouched. Note that newlines within interpolated values are never normalized.
  9. Reference: outdent configuration options

    main

    The following options can be passed to the outdent function to control string processing.

    {
      "trimLeadingNewline": {
        "type": "boolean",
        "default": true,
        "description": "Whether or not outdent should remove the leading newline from your template string."
      },
      "trimTrailingNewline": {
        "type": "boolean",
        "default": true,
        "description": "Whether or not outdent should remove the trailing newline from your template string."
      },
      "newline": {
        "type": "string | null",
        "default": null,
        "description": "If set to a string, normalize all newlines (\r\n, \r, \n) in the template literal to this value."
      }
    }
  10. Use outdent as a tagged template literal

    main

    The primary way to use outdent is as a tagged template literal. It removes the common leading indentation from all lines within the template string, making it easier to write multi-line strings in code without including the surrounding code's indentation in the resulting string.

    By default, it trims the leading newline from the first line and the trailing newline from the last line.

    import outdent from 'outdent';
    
    const text = outdent`
        Line 1
        Line 2
        Line 3
    `;
    
    console.log(text);
    // "Line 1\n    Line 2\n    Line 3"
  11. Remove indentation from a standard string using .string()

    main

    If you have a regular string (not a template literal) and want to apply the same outdent logic, use the .string(str) method on an Outdent instance.

    import outdent from 'outdent';
    
    const rawString = "    Line 1\n    Line 2";
    const cleaned = outdent.string(rawString);
    
    console.log(cleaned);
    // "Line 1\nLine 2"
  12. Create a custom outdent instance with Options

    main

    You can create a new Outdent instance by calling outdent(options). This allows you to customize how indentation and newlines are handled for all subsequent template literals processed by that instance.

    Common use cases include changing the newline character or disabling the automatic trimming of leading/trailing newlines.

    import { outdent } from 'outdent';
    
    const customOutdent = outdent({
      trimLeadingNewline: false,
      trimTrailingNewline: false,
      newline: '\n'
    });
    
    const text = customOutdent`
        Indented Line
    `;