How to preserve whitespace indentation of text enclosed in HTML
 tags excluding the current indentation level of the 
 tag in the document?

后端 未结 11 1454
萌比男神i
萌比男神i 2020-12-02 18:32

I\'m trying to display my code on a website but I\'m having problems preserving the whitespace indentation correctly.

For instance given the following snippet:

相关标签:
11条回答
  • 2020-12-02 18:38

    This can be done in four lines of JavaScript:

    var pre= document.querySelector('pre');
    
    //insert a span in front of the first letter.  (the span will automatically close.)
    pre.innerHTML= pre.textContent.replace(/(\w)/, '<span>$1');
    
    //get the new span's left offset:
    var left= pre.querySelector('span').getClientRects()[0].left;
    
    //move the code to the left, taking into account the body's margin:
    pre.style.marginLeft= (-left + pre.getClientRects()[0].left)+'px';
     <body>
       Here is my code:
       <pre>
         def some_funtion
           return 'Hello, World!'
         end
       </pre>
     <body>

    0 讨论(0)
  • 2020-12-02 18:39

    This is cumbersome, but it works if code folding is important to you:

            <pre>def some_funtion</pre>
            <pre>    return 'Hello, World!'</pre>
            <pre>end</pre>
    

    In your css,

        pre { margin:0 }
    

    In vim, writing your code normally and then executing:

        :s/\t\t\([^\n]\+\)/<pre>\1<\/pre>/
    

    for each line would work.

    0 讨论(0)
  • 2020-12-02 18:42

    PRE is intended to preserve whitespace exactly as it appears (unless altered by white-space in CSS, which doesn't have enough flexibility to support formatting code).

    Before

    Formatting is preserved, but so is all the indentation outside of the PRE tag. It would be nice to have whitespace preservation that used the location of the tag as a starting point.

    enter image description here

    After

    Contents are still formatted as declared, but the extraneous leading whitespace caused by the position of the PRE tag within the document is removed.

    enter image description here

    I have come up with the following plugin to solve the issue of wanting to remove superfluous whitespace caused by the indentation of the document outline. This code uses the first line inside the PRE tag to determine how much it has been indented purely due to the indentation of the document.

    This code works in IE7, IE8, IE9, Firefox, and Chrome. I have tested it briefly with the Prettify library to combine the preserved formatting with pretty printing. Make sure that the first line inside the PRE actually represents the baseline level of indenting that you want to ignore (or, you can modify the plugin to be more intelligent).

    This is rough code. If you find a mistake or it does not work the way you want, please fix/comment; don't just downvote. I wrote this code to fix a problem that I was having and I am actively using it so I would like it to be as solid as possible!

    /*!
    *** prettyPre ***/
    
    (function( $ ) {
    
        $.fn.prettyPre = function( method ) {
    
            var defaults = {
                ignoreExpression: /\s/ // what should be ignored?
            };
    
            var methods = {
                init: function( options ) {
                    this.each( function() {
                        var context = $.extend( {}, defaults, options );
                        var $obj = $( this );
                        var usingInnerText = true;
                        var text = $obj.get( 0 ).innerText;
    
                        // some browsers support innerText...some don't...some ONLY work with innerText.
                        if ( typeof text == "undefined" ) {
                            text = $obj.html();
                            usingInnerText = false;
                        }
    
                        // use the first line as a baseline for how many unwanted leading whitespace characters are present
                        var superfluousSpaceCount = 0;
                        var currentChar = text.substring( 0, 1 );
    
                        while ( context.ignoreExpression.test( currentChar ) ) {
                            currentChar = text.substring( ++superfluousSpaceCount, superfluousSpaceCount + 1 );
                        }
    
                        // split
                        var parts = text.split( "\n" );
                        var reformattedText = "";
    
                        // reconstruct
                        var length = parts.length;
                        for ( var i = 0; i < length; i++ ) {
                            // cleanup, and don't append a trailing newline if we are on the last line
                            reformattedText += parts[i].substring( superfluousSpaceCount ) + ( i == length - 1 ? "" : "\n" );
                        }
    
                        // modify original
                        if ( usingInnerText ) {
                            $obj.get( 0 ).innerText = reformattedText;
                        }
                        else {
                            // This does not appear to execute code in any browser but the onus is on the developer to not 
                            // put raw input from a user anywhere on a page, even if it doesn't execute!
                            $obj.html( reformattedText );
                        }
                    } );
                }
            }
    
            if ( methods[method] ) {
                return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ) );
            }
            else if ( typeof method === "object" || !method ) {
                return methods.init.apply( this, arguments );
            }
            else {
                $.error( "Method " + method + " does not exist on jQuery.prettyPre." );
            }
        }
    } )( jQuery );
    

    This plugin can then be applied using a standard jQuery selector:

    <script>
        $( function() { $("PRE").prettyPre(); } );
    </script>
    
    0 讨论(0)
  • 2020-12-02 18:44

    If you are using this on a code block like:

    <pre>
      <code>
        ...
      </code>
    </pre>
    

    You can just use css like this to offset that large amount of white space in the front.

    pre code {
      position: relative;
      left: -95px; // or whatever you want
    }
    
    0 讨论(0)
  • 2020-12-02 18:45

    I also found that if you're using haml you can use the preserve method. For example:

    preserve yield
    

    This will preserve the whitespace in the produced yield which is usually markdown containing the code blocks.

    0 讨论(0)
  • 2020-12-02 18:49

    The pre tag preserves all the white spaces you have used while writing in the body. Where as normally if you do not use pre it will display the text normally...(HTML will make the browser to neglect those white spaces) Here try this I have used the paragraph tag. Output:-

    Here is my code:

    def some_function

      return 'Hello, World!'

    end

    <html> <body> Here is my code: <p> def some_function<br> <pre> return 'Hello, World!'<br></pre> end </p> </body> </html>

    0 讨论(0)
提交回复
热议问题