Javascript formatter?

J

John Dalberg

I am using a utility that creates Javascript. However the javascript is one
hugely long stream of characters. Is there a utility that can format the
Javascipt so that it put each statement in a seperate line and indents
properly?
 
L

Lasse Reichstein Nielsen

Ira Baxter said:

Or let the browser do it:
---
<script type="text/javascript">
function reformat(code) {
try {
var func = Function("",code);
var text = func.toString();
var match = text.match(/function\s*\w*\(\)\s*\{([\s\S]*)}/);
if (match) {
return match[1];
} else {
return "ERROR\n" + code; //something wrong.
}
} catch (e) {
return "ERROR: " + e + "\n" + code;
}
}
</script>
<form action=""
onsubmit="this.elements['input'].value =
reformat(this.elements['input'].value);
return false;">
<textarea name="input" rows="10" cols="72">code here</textarea><br><input type="submit" value="Reformat">
</form>
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Tue, 5 Apr 2005
20:44:00, seen in Lasse Reichstein Nielsen
var text = func.toString();
Personally, I prefer the way Mozilla formats its Javascript :)
IE doesn't do any formatting at all, so don't use that.

Code display within my javascript pages is largely based on
function.toString(); I only see the results in MSIE.

I write my code (E&OE) to fit within 69-character-wide boxes (as seen in
IE 4), and I choose the height of each box to suit the code.

Are the results generally acceptable in other browsers, and could
anything be done to make the average better (given the wide use of IE)?
 
L

Lasse Reichstein Nielsen

Code display within my javascript pages is largely based on
function.toString(); I only see the results in MSIE.

I write my code (E&OE) to fit within 69-character-wide boxes (as seen in
IE 4), and I choose the height of each box to suit the code.

Yes, checking in IE, I can see that the code doesn't have to overflow the
box :)
Are the results generally acceptable in other browsers, and could
anything be done to make the average better (given the wide use of IE)?

The boxes overflow in both Mozilla and Opera.

One of the problems is the number of empty lines between functions in
boxes with more than one function. In IE, there is one line, in both
Mozilla and Opera, there are three (an extra line before and after
each function). It shouldn't hurt to remove these empty lines, if they
exist.

Another difference is that IE doesn't reformat the body of the
function at all, whereas the other browsers do. In particular, they
move "}"'s to a line of their own. Opera also moves "{"'s to their
own line (the thing that makes me prefer Mozilla's format).
I don't see a simple solution to this.

The non-IE browsers also doesn't include comments in the output. All
in all, lines are probably shorter than in IE.

A non-simple solution would be to make the ShowFF function calculate
the necessary number of lines for the textarea, instead of providing
it as an argument. E.g.:

---
function trim(str) {
var match = /\S([\s\S]*\S)*/.exec(str);
return match ? match[0] : "";
}

function countLines(str, lineLength) {//counts lines when wrapped at lineLength
var lines = str.split(/[\n\r]/g);
var lineCount = lines.length;
for (var i = 0; i < lines.length; i++) {
lineCount += Math.floor(lines.length / lineLength);
}
return lineCount;
}

function ShowFF() { // Args are functions, last Arg is unused
var Len = arguments.length-1, S = ""
for (var j=0 ; j<Len ; j++) {
if (j>0) { S += "\n\n"; }
S += trim(arguments[j].toString());
}
var numLines = countLines(S, BoxX);
Depict(BoxX, numLines, S, "lightgreen") ; return "" }

function ShowDo(Fn, Ht) { // N.B. this calls Fn()
var string = trim(Fn.toString());
Depict(BoxX, countLines(string, BoxX), string, "red" ) ; Fn() ; return "" }
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Thu, 7 Apr 2005
22:12:52, seen in Lasse Reichstein Nielsen
Yes, checking in IE, I can see that the code doesn't have to overflow the
box :)


The boxes overflow in both Mozilla and Opera.
...
A non-simple solution would be to make the ShowFF function calculate
the necessary number of lines for the textarea, instead of providing
it as an argument. E.g.:
...

It's not quite that easy, since when I have

ShowFF(UsefulFunction(s), Demo(s)OfThatFunction, Length)

I often choose to make the box show only UsefulFunction(s) , with
Demo(s)OfThatFunction being visible to those who have noticed the thumb
on the vertical scroll-bar. You may not have seen the absence of the
thumb in cases without demo functions :-( .

Perhaps I'll make an empty parameter terminate size-counting.

Since I have 311 ShowFF and 122 ShowDo in 35 files, I think I'll use new
names and make the change slowly ...

Good luck

With code written by you, surely that is not needed?

Thanks.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Thu, 7 Apr 2005
22:12:52, seen in Lasse Reichstein Nielsen
var lines = str.split(/[\n\r]/g);

In IE4, it appears that blank lines do not generate a corresponding
element in the array lines .

ISTR reading about varying behaviours of split().

Test page, showing old & new code in operation, is
<URL:http://www.merlyn.demon.co.uk/js-boxes.htm> .


Code should be self-documenting; but how to do a self-documenting blank
line ???
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Thu, 7 Apr 2005
22:12:52, seen in Lasse Reichstein Nielsen
var lines = str.split(/[\n\r]/g);


This, I think, does what countLines should have done :-


function LineCount(S, M) { // counts lines when wrapped at lineLength - blank lines ? A test blank line follows :-

var j = xj = R = N = 0, L = S.length, X = 1, C
while (j<L) { C = S.charCodeAt(j++)
if (C!=10 && C!=13) continue
if (C==10) N++
if (C==13) R++
X += Math.max(Math.floor((j-xj-2)/M), 0) ; xj = j }
// Not good enough, as MSIE splits at whitespace
return X + Math.max(N, R) }

// countLines = LineCount


Note that from "function" to ":-" is coded, posted, and transmitted
as a single line; how you see it depends on your choice of service,
software, and settings.

If the code is written so that coded line-length fits in box-size,
as I "always" do, then there is no need on my system to allow for
line-wrap. Is there then an actual need to consider line-wrap in
any other system? If there is, do other browsers wrap at exactly N,
rather than at the previous whitespace?

H'mmm - IE4 has a bug; although whitespace is reduced to newline
at such a wrap, the choice of wrap point is affected by the size
of the whitespace. However, that should only matter here if a
line is wrapped more than once.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Thu, 7 Apr 2005
22:12:52, seen in Lasse Reichstein Nielsen
Good luck

That worked.

Now I'm trying to improve the Pop-Up code display. It now puts a <pre>
rather than a <textarea> in the new window, and allows the window to
scroll. I also propose to incorporate auto-calculation of the "rows"
parameter, as in the Code Display section a little higher up the page.

It can be seen in the section Btn & PopCode which is just above
<URL:http://www.merlyn.demon.co.uk/js-nclds.htm#Inc3>.


Questions :

(A) In PopCode, the window height and width are somewhat pragmatical :-
var Wndw = window.open("", "X"+new Date().getTime(), // /scr-bar?
"height=" + (17*btn.btnargs[1]+28) + ",width=" + (8*BoxX+20) +
",resizable,scrollbars")
where btnargs[1] is the number of lines I want to show, BoxX the number
of characters per line I want to show, 20 and 28 give the right and
bottom margins matching the top and left ones, all empirical for my
present browser setup.

Without undue effort, can the initial height and width be set in due
proportion to the actual font size?


(B) In Btn, should document.close() be there (Btn is for execution
in-line during page display)? It's there as a result of possibly-
misinterpreted advice.


(C) Can SafeHTML be coded so that it is shown properly both in the page
proper and in the pop-up, and if so how? Its real code is
function SafeHTML(S) { // may be displayed incorrectly
return S.replace(/&/g, "&amp;").
replace(/</g, "&lt;").replace(/>/g, "&gt;") }



(D) Anything else?
 

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

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top