Indentation for Structure, automated

D

Dr John Stockton

It is generally agreed that code should be indented (and spaced) to show
its logical structure, with one unit for each structure level and generally
another for a new line which does not start a statement.

Using TAB for the indent unit is alas common, but generally unsuitable for
News or printed material. Two spaces per unit is generally acceptable.

The following code, extracted from js-quick.htm, will re-indent the text
content of F.Code. Leading and trailing whitespace is removed, and new
leading whitespace added; the meaning of the code should be preserved.

The commented-out statement is somewhat /ad hoc/, recognising common
forms of statement break in my code; recognising all forms seems
difficult.

Obviously, it works by counting { & } characters; so there should be
no unbalanced { or } in string or comment in any one line (if necessary,
re-phrase or balance with commented ones.


function Indt_(F) { var In=0, S2=" ", Lines, J, L, K, SS, Line, C
Lines = F.Code.value.split("\n") // Code to Lines
for (J=0, L=Lines.length ; J < L ; J++) {
K = In ; SS = "" ; while (K--) SS += S2 // Build padding
Line = Lines[J].replace(/^\s+|\s+$/g, "") // Trim the Line
// if (!/^[A-Z]/i.test(Line)
// && !/^\/[/*]|^[{}]/.test(Line)) SS += S2 // Some Continuations
K = Line.length ; while (K--) { // Count +{ -}
C = Line.charAt(K) ; In += (C=="{") - (C=="}") }
Lines[J] = SS + Line } // Indent the Line
F.Code.value = Lines.join("\n") }

Those who like } characters to be alone on a line and aligned with the
beginning of the opener's line will need to adjust the code.

The code can be used to bulk-rectify material found in News before
amending it and posting revised code.

It's a good idea to read the newsgroup and its FAQ. See below.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top