Search code examples
htmlwysiwygword-processoropenwysiwyg

text formatting according to indentation


Hi can someone help me understand how the stackoverflow question's code area works(technically).
I mean the way it formats the text as it indent the text.

example: without indentation

 example: with indentation ( text background color and font has changed)

can someone explain me the technology behind this. I am new to programming, is this something hard to implement. How can we implement this kind of formatting depending on the indentation of the text.


Solution

  • One approach could be to loop through each line of text in a string, and group them by indentation level into sections:

    var leadingSpaces = /^\s*/;
    blockOfText = blockOfText.replace(/\t/g, '    '); // replace tabs with 4 spaces
    var lines = blockOfText.split('\n');
    var sections = [];
    var currentIndentLevel = null;
    var currentSection = null;
    lines.forEach(function(line) {
        var indentLevel = leadingSpaces.exec(line)[0].length;
        if (indentLevel !== currentIndentLevel) {
            currentIndentLevel = indentLevel;
            currentSection = { indentLevel: currentIndentLevel, lines: [] };
            sections.push(currentSection);
        }
        currentSection.lines.push(line);
    });
    

    Then, once you have those sections, you can loop through them:

    sections.forEach(function(section) { 
        switch (section.indentLevel) {
            case 4:
                // format as code
                break;
            // etc.
            default:
                // format as markdown
                break;
        }
    });