Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Inserting Indentation Before Tags

Here's what your code will do: find the first instance of a < character, insert a return and some number of spaces before it, and repeat this procedure with all the remaining < characters. The code will indent opening HTML tags (such as <table>) and also closing tags (such as </table>). There are other cases when a < might appear in an HTML document, but for now, you'll ignore them.

You'll also ignore—but only for this set of steps—the fact that you want your indentation to show the different levels of nesting of the tags. First, you'll just get the code to indent every tag by the same amount.

If you try to follow the same procedure you used for removing spaces, you'll see a problem. That technique—looping as long as there is a particular string in the source string—works only if you delete the string you find on each step through the loop. Otherwise, you'll keep finding the same instance of the string forever.

To get around this problem, you'll write two loops. The first loop will find all the < characters, replacing them with an odd character that will never appear naturally in HTML text. You'll use the Chr function to get such a character. The second loop will find all these odd characters and replace each of them with a return character, a number of spaces for the indent, and the < character. The result is to replace each < character with a return character, some spaces, and the < character itself.

This trick gets around the problem: In each loop, you are eliminating the found instance of the searched-for string on each step, so that the loops won't go on forever.

To add indents:

  1. Open the Indent method in the Code Editor.

  2. Enter this code at the end of the method:

    // Indent before every tag.
    // Replace every C with OddChar.
    While Instr(S,C) <> 0
       S = Replace(S,C,OddC)
    Wend // Replace every OddChar with return +
    → tab + C.
    While Instr(S,OddC) <> 0
      IndentS = Mid(SpaceS,1,TabSize)
       S = Replace(S,OddC,ReturnC+IndentS+C)
    // Add extra space before closing tabs.
    // Replace every C/ with OddChar.
    While Instr(S,C+SlashC) <> 0
    S = Replace(S,C+SlashC,OddC)
    // Replace every OddChar with tab + C/.
    While Instr(S,OddC) <> 0   
       IndentS = Mid(SpaceS,1,TabSize)
       S = Replace(S,OddC,IndentS+C+SlashC)
    Return S

But you're not quite there.

  • + Share This
  • 🔖 Save To Your Account