Support » Plugin: Pastacode » Unindent code

  • Hello again again 😉

    I have another request: when displaying an extract, the base indentation is not useful for the extract and should be removed.

    For example, instead of displaying this code in a condition in a loop in a method in a class:

    //
    				if ($firstConnection) {
    					echo "hello world!";
    				}

    it should be more interesting to display:

    if ($firstConnection) {
    	echo "hello world!";
    }

    That’s all… for now 😉

    David

    https://wordpress.org/plugins/pastacode/

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Willy Bahuaud

    (@willybahuaud)

    Hello,

    I try a little function, but I encountered a problem. I need do determine, for each code, tab length…

    <?php
    $var = '	// this is a test
    	with a second line
    	//and a third line';
    
    $regex = '/(^\t|^:space:+)/';
    $count = array();
    $var2 = explode( "\n", $var );
    $mini = PHP_INT_MAX;
    foreach( $var2 as $v ) {
    	if ( ! preg_match( $regex, $v, $match ) ) {
    		$mini = PHP_INT_MAX;
    		break;
    	} elseif ( strlen( $match[0] ) < $mini ) {
    		$mini = strlen( $match[0] ); //how many spaces for a tab ?
    	}
    }
    if ( $mini != PHP_INT_MAX ) {
    	$regex2 = '/(^\t|^:space:{' . $mini . '})/';
    	$regex4 = '/\n\t|\n:space:{' . $mini . '}/';
    	$var = preg_replace( $regex2, "", $var );
    	$var = preg_replace( $regex4, "\n", $var );
    }
    // $var is now indented correctly
    Thread Starter partage-it

    (@partage-it)

    Yes, it is not simple 🙂

    A simple solution is maybe to remove first white char (space or \t) of every lines until at least one line first char is not a white char.

    For example:

    __a
    ____b
    ______c

    becomes in the first iteration:

    _a
    ___b
    _____c

    and finally:

    a
    __b
    ____c

    David

    Thread Starter partage-it

    (@partage-it)

    Hello Willy,

    As i am not confident with regexp, so i have tried with a simple class to handle code indentation.

    The result is here, if you need:
    https://gist.github.com/partageit/869fa0fbf9f89582d5f0

    David

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Unindent code’ is closed to new replies.