title: Indent Selected Text With Javascript
body: <p>How can I indent each line of the selected text in a textarea control using JavaScript. Something similar to the <strong>Code Sample</strong> button of the <strong>Stack Overflow</strong>'s editor.</p>
  
  <p><strong>UPDATE:</strong> Viewing the code of <strong>And</strong>, I wrote a solution, but only works with Firefox (also).</p>
  
  <p>The functions is:</p>
  
  <pre><code>function indentSelection() {
      var selection, newValue;
      var txt = document.getElementById("txt");
      var start = txt.selectionStart;
      var end = txt.selectionEnd;
      // extend the selecction start until the previous line feed
      start = txt.value.lastIndexOf("\n", start);
      // if there isn't a line feed before,
      // then extend the selection until the begging of the text
      if (start == -1) {
          start = 0;
      }
      // if the selection ends with a line feed,
      // remove it from the selection
      if (txt.value.charAt(end - 1) == "\n") {
          end = end - 1;
      }
      // extend the selection end until the next line feed
      end = txt.value.indexOf("\n", end);
      // if there isn't a line feed after,
      // then extend the selection end until the end of the text
      if (end == -1) {
          end = txt.value.length;
      }
      // move the selection to a new variable
      selection = txt.value.substring(start, end);
      // add four spaces before line feeds
      selection = selection.replace(/^(?=.+)/mg, "    ");
      // rebuild the textarea content
      newValue = txt.value.substring(0, start);
      newValue += selection;
      newValue += txt.value.substring(end);
      txt.value = newValue;
  }
  </code></pre>
  
  <p>An example could be:</p>
  
  <pre><code>&lt;textarea id="txt" cols="80" rows="8"&gt;bla bla bla
  bla bla bla
  bla bla bla
  bla bla bla&lt;/textarea&gt;
  &lt;a href="#" onclick="indentSelection();return false;"&gt;indent selection!&lt;/a&gt;
  </code></pre>