Skip to content

Instantly share code, notes, and snippets.

@wittman
Created January 6, 2010 23:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wittman/270790 to your computer and use it in GitHub Desktop.
Save wittman/270790 to your computer and use it in GitHub Desktop.
stackoverflowIndentFourSpaces - Indent Four Spaces (for stackoverflow.com)
<?php
/*
Copyright (C) 2010 Micah Wittman | http://wittman.org/ | stackoverflow.m[a][t]wittman.org | http://stackoverflow.com/users/11181/micahwittman | http://twitter.com/micahwittman
Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.gnu.org/licenses/) licenses.
Hosted application:
http://wittman.org/projects/stackoverflowindentfourspaces/
Repositories:
http://wittman.org/projects/stackoverflowindentfourspaces/stackoverflowIndentFourSpaces.php
http://wittman.org/projects/stackoverflowindentfourspaces/stackoverflowIndentFourSpaces.txt
http://gist.github.com/270790
Versions:
* 2010-01-09 - version 0.12 - Fixed parsing bug where input had no new lines.
* 2010-01-07 - version 0.11 - Normalize tabs to 4 spaces before parsing each line.
* 2010-01-07 - version 0.10 - Initial Release.
*/
//error_reporting(E_ALL);
function stripslashes_array(&$array, $iterations=0)
{
if($iterations < 3)
{
foreach($array as $key => $value)
{
if(is_array($value))
{
stripslashes_array($array[$key], $iterations + 1);
}
else
{
$array[$key] = stripslashes($array[$key]);
}
}
}
}
if(get_magic_quotes_gpc())
{
//stripslashes_array($_GET);
stripslashes_array($_POST);
//stripslashes_array($_COOKIE);
}
function h($s)
{
echo htmlspecialchars($s, ENT_QUOTES);
}
function normalize_indent($code, $num_of_spaces_to_indent)
{
/* This function is a port/fork of [Michael Stum](http://meta.stackoverflow.com/users/91/michael-stum)'s
* #C/.NET code <http://meta.stackoverflow.com/questions/34588/4-spaces-for-code-tags-is-annoying/34594#34594>.
*/
$spaces = str_repeat(' ', $num_of_spaces_to_indent);
$removeIndent = 0;
$code = str_replace("\t", ' ', $code);
$code = $code . " \n\t"; //append an extra line with a some non-space character (tab) or code with no line breaks fail to parse correctly
$codeLines = preg_split("/\012\015?/", $code);
$codeLineLastIndex = count($codeLines) - 1;
foreach($codeLines as $s)
{
if($s === '') continue;
$tmp = 0;
foreach(str_split($s) as $c)
{
if ($c != " ")
{
break;
}
$tmp++;
}
if($removeIndent == 0 || $tmp < $removeIndent)
{
$removeIndent = $tmp;
}
}
$lineCounter = 0;
$codeFormatted = '';
foreach($codeLines as $s)
{
if($lineCounter == $codeLineLastIndex) break; //don't include appended extra line
$codeFormatted .= $spaces;
$codeFormatted .= (strlen($s) >= $removeIndent ? substr_replace($s, '', 0, $removeIndent) : $s) . "\n";
$lineCounter++;
}
return $codeFormatted;
}
$code = isset($_POST['code']) ? $_POST['code'] : '';
$example = isset($_GET['example']);
$num_of_spaces_to_indent = isset($_POST['add_indent']) ? 4 : 0;
$codeFormatted = normalize_indent($code, $num_of_spaces_to_indent);
$disabled = '';
$msg = 'PROCESSING COMPLETE (copy from RIGHT)';
$outputBackgroundColor = 'wheat;';
if($code == '')
{
$disabled = ' disabled="disabled" ';
$outputBackgroundColor = 'white;';
$msg = 'Paste code on LEFT. Copy on RIGHT.';
}
$infoHideClass = "hide";
$infoHref = "./?example=1";
if($example)
{
$infoHideClass = "";
$infoHref = "./";
}
if(isset($_POST['ajax']) && $_POST['ajax'] == 'Y')
{
echo json_encode($codeFormatted);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>wittman.org - Indent Four Spaces for StackOverflow</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style type="text/css">
body {
font-family:Helvetica, Geneva, Arial, sans-serif;
}
a {
text-decoration: none;
}
a:hover {
color:red;
}
table, tr, td {
vertical-align:middle;
}
.column {
width:500px; height:400px
}
.column_short {
width:500px; height:100px
}
.code_out_history_entry {
background-color:rgb(240,240,240);
}
.submitter {
text-align:center; margin: 0 auto;
}
.subtitle_msg {
color:maroon;
}
.small{
font-size:10pt;
}
.history_container {
padding-left:8px;
}
.in_out {
margin-left:15%;
margin-bottom: 10px;
}
.in_out_or {
margin-left:30%;
margin-bottom: 10px;
font-style: italic;
font-size: .8em;
}
.pre {
margin-left:15%;
font-family: 'Courier New', Courier, fixed-width;
}
.dim {
color: #999900;
}
.highlight {
color: #990000;
}
.highlight_alt {
color: #4D9900;
}
.hide {
display: none;
}
.inline_input {
margin-left: 15px;
}
.author {
font-weight:bold;
font-size: 10pt;
padding: 5px 0 5px 0;
}
#info_header {
font-size: 12pt;
margin-left: 15px;
}
</style>
</head>
<body>
<div class="box">
<div id="header">
<h1>Indent Four Spaces (for stackoverflow.com)</h1>
</div>
<div id="content">
<form action="./" method="post" id="main">
<h2 class="subtitle_msg">
<?php h($msg);?> <a href="<?php echo $infoHref;?>" id="info_header">Example (+)</a>
</h2>
<div id="info" class="<?php echo $infoHideClass;?>">
<h4>Normalizes indented code snippets so the outer block level of indention becomes four spaces.<br />
<span class="small">Below is pseudo code with {TAB} = tab and {SP} = space: </span>
</h4>
<div>&nbsp;</div>
<div class="in_out">IN</div>
<div class="pre">
<span class="dim">{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}</span>foreach(item in collection)<br />
<span class="dim">{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}</span><span class="highlight">{TAB}</span>x = item<br />
<span class="dim">{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}</span>end foreach<br />
</div>
<div>&nbsp;</div>
<div class="in_out_or">
OR
</div>
<div class="pre">
<span class="dim">{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}</span>foreach(item in collection)<br />
<span class="dim">{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}</span><span class="highlight">{SP}</span>y = item<br />
<span class="dim">{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}{SP}</span>end foreach<br />
</div>
<div>&nbsp;</div>
<div class="in_out">OUT</div>
<div class="pre">
<span class="highlight_alt">{SP}{SP}{SP}{SP}</span>foreach(item in collection)<br />
<span class="highlight_alt">{SP}{SP}{SP}{SP}</span><span class="highlight">{TAB}</span>x = item<br />
<span class="highlight_alt">{SP}{SP}{SP}{SP}</span>end foreach<br />
</div>
</div>
<table>
<tr>
<td>
<table>
<tr>
<td>
<h2>Code IN </h2>
</td>
<td>
<input type="submit" name="submit_top" id="submit_top" class="inline_input" value=" &gt; " />
</td>
</tr>
</table>
<textarea class="column" id="code" name="code" rows="60" cols="40"><?php h($code);?></textarea>
</td>
<td>
<h2 id="code_out_title">Code OUT <input class="inline_input" type="checkbox" id="add_indent" name="add_indent" checked="checked" /><span class="small">Add 4-space Indent</span></h2>
<textarea <?php echo $disabled;?> class="column" style="background-color:<?php echo $outputBackgroundColor;?>" id="code_out" name="code_out" rows="60" cols="40"><?php h($codeFormatted);?></textarea>
</td>
</tr>
</table>
<div class="submitter">
<div>
<img id="spinner" style="display:none" src="data:image/gif;base64,R0lGODlhEAAQAPQAAP///wAAAPDw8IqKiuDg4EZGRnp6egAAAFhYWCQkJKysrL6+vhQUFJycnAQEBDY2NmhoaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH+GkNyZWF0ZWQgd2l0aCBhamF4bG9hZC5pbmZvACH5BAAKAAAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAEAAQAAAFdyAgAgIJIeWoAkRCCMdBkKtIHIngyMKsErPBYbADpkSCwhDmQCBethRB6Vj4kFCkQPG4IlWDgrNRIwnO4UKBXDufzQvDMaoSDBgFb886MiQadgNABAokfCwzBA8LCg0Egl8jAggGAA1kBIA1BAYzlyILczULC2UhACH5BAAKAAEALAAAAAAQABAAAAV2ICACAm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MJCshACH5BAAKAAcALAAAAAAQABAAAAV3ICACAkkQZTmOAiosiyAoxCq+KPxCNVsSMRgBsiClWrLTSWFoIQZHl6pleBh6suxKMIhlvzbAwkBWfFWrBQTxNLq2RG2yhSUkDs2b63AYDAoJXAcFRwADeAkJDX0AQCsEfAQMDAIPBz0rCgcxky0JRWE1AmwpKyEAIfkEAAoACAAsAAAAABAAEAAABXkgIAICKZzkqJ4nQZxLqZKv4NqNLKK2/Q4Ek4lFXChsg5ypJjs1II3gEDUSRInEGYAw6B6zM4JhrDAtEosVkLUtHA7RHaHAGJQEjsODcEg0FBAFVgkQJQ1pAwcDDw8KcFtSInwJAowCCA6RIwqZAgkPNgVpWndjdyohACH5BAAKAAkALAAAAAAQABAAAAV5ICACAimc5KieLEuUKvm2xAKLqDCfC2GaO9eL0LABWTiBYmA06W6kHgvCqEJiAIJiu3gcvgUsscHUERm+kaCxyxa+zRPk0SgJEgfIvbAdIAQLCAYlCj4DBw0IBQsMCjIqBAcPAooCBg9pKgsJLwUFOhCZKyQDA3YqIQAh+QQACgAKACwAAAAAEAAQAAAFdSAgAgIpnOSonmxbqiThCrJKEHFbo8JxDDOZYFFb+A41E4H4OhkOipXwBElYITDAckFEOBgMQ3arkMkUBdxIUGZpEb7kaQBRlASPg0FQQHAbEEMGDSVEAA1QBhAED1E0NgwFAooCDWljaQIQCE5qMHcNhCkjIQAh+QQACgALACwAAAAAEAAQAAAFeSAgAgIpnOSoLgxxvqgKLEcCC65KEAByKK8cSpA4DAiHQ/DkKhGKh4ZCtCyZGo6F6iYYPAqFgYy02xkSaLEMV34tELyRYNEsCQyHlvWkGCzsPgMCEAY7Cg04Uk48LAsDhRA8MVQPEF0GAgqYYwSRlycNcWskCkApIyEAOwAAAAAAAAAAAA%3D%3D" alt="spinner" />
</div>
<input type="hidden" id="ajax" name="ajax" value="" />
<input type="submit" name="submit" id="submit" value="Format" />
</div>
<table>
<tr>
<td>
<h2 class="column">&nbsp;</h2>
</td>
<td class="history_container">
<h2 id="code_out_history_title">History</h2>
</td>
</tr>
</table>
</form>
<div>
<h4><em>Indent Four Spaces for StackOverflow</em> Open Source Code:</h4>
<a title="code @ wittman.org" href="http://wittman.org/projects/stackoverflowindentfourspaces/stackoverflowIndentFourSpaces.txt">http://wittman.org/projects/stackoverflowindentfourspaces/stackoverflowIndentFourSpaces.txt</a><br />
<a title="code @ github" href="http://gist.github.com/270790">http://gist.github.com/270790</a><br />
</div>
<div>
&nbsp;
</div>
<div class="author">
The core formatting function is a port/fork of <a title="Michael Stum" href="http://meta.stackoverflow.com/questions/34588/4-spaces-for-code-tags-is-annoying/34594#34594">Michael Stum's #C/.NET code</a>
<br /><br />
Copyright (C) 2010 Micah Wittman | <a title="wittman.org" href="http://wittman.org/">http://wittman.org/</a> | stackoverflow.m[a][t]wittman.org | <a title="wittman.org" href="http://stackoverflow.com/users/11181/micahwittman">http://stackoverflow.com/users/11181/micahwittman</a> | <a title="micahwittman @ twitter" href="http://twitter.com/micahwittman">@micahwittman</a>
</div>
<div>
&nbsp;
</div>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
$('input#ajax').val('Y');
$('input#submit, input#submit_top').click( function() {
$('#spinner').show();
$('input#submit').attr('disabled', 'disabled');
$.post( './', $('form#main').serialize(), function(data) {
$('#code_out').fadeOut('fast').fadeIn('fast', function(){
$(this).val(data).css('background-color', 'wheat').removeAttr('disabled');
$('<div><textarea class="code_out_history_entry column_short" rows="60" cols="40"></textarea></div>').insertAfter("#code_out_history_title").children(':first').val(data);
});
$('input#submit').removeAttr('disabled');
$('#spinner').hide();
},
'json'
);
return false;
});
$('#info_header').click(function(){
$('#info').slideToggle('fast');
return false;
});
});
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
try {
var pageTracker = _gat._getTracker("UA-1238775-7");
pageTracker._trackPageview();
} catch(err) {}
//]]>
</script>
</body>
</html>
@Zeokat
Copy link

Zeokat commented Mar 7, 2014

Zeokat, interesting code. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment