This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

View | Details | Raw Unified | Return to bug 177192
Collapse All | Expand All

(-)a/xml.text/src/org/netbeans/modules/xml/text/folding/TokenElement.java (+1 lines)
Lines 80-85 Link Here
80
        return indentLevel;
80
        return indentLevel;
81
    }
81
    }
82
    
82
    
83
    @Override
83
    public String toString() {
84
    public String toString() {
84
        return type + ", " + name + ", " + startOffset + ", " + endOffset;
85
        return type + ", " + name + ", " + startOffset + ", " + endOffset;
85
    }
86
    }
(-)a/xml.text/src/org/netbeans/modules/xml/text/indent/XMLLexerFormatter.java (-89 / +150 lines)
Lines 1-7 Link Here
1
/*
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
3
 *
4
 * Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
4
 * Copyright 1997-2010 Sun Microsystems, Inc. All rights reserved.
5
 *
5
 *
6
 * The contents of this file are subject to the terms of either the GNU
6
 * The contents of this file are subject to the terms of either the GNU
7
 * General Public License Version 2 only ("GPL") or the Common
7
 * General Public License Version 2 only ("GPL") or the Common
Lines 42-47 Link Here
42
42
43
import java.io.IOException;
43
import java.io.IOException;
44
import java.util.ArrayList;
44
import java.util.ArrayList;
45
import java.util.LinkedList;
45
import java.util.List;
46
import java.util.List;
46
import java.util.Stack;
47
import java.util.Stack;
47
import javax.swing.text.AbstractDocument;
48
import javax.swing.text.AbstractDocument;
Lines 53-59 Link Here
53
import org.netbeans.api.lexer.TokenSequence;
54
import org.netbeans.api.lexer.TokenSequence;
54
import org.netbeans.api.xml.lexer.XMLTokenId;
55
import org.netbeans.api.xml.lexer.XMLTokenId;
55
import org.netbeans.editor.BaseDocument;
56
import org.netbeans.editor.BaseDocument;
56
import org.netbeans.editor.Formatter;
57
import org.netbeans.editor.Utilities;
57
import org.netbeans.editor.Utilities;
58
import org.netbeans.modules.editor.indent.api.IndentUtils;
58
import org.netbeans.modules.editor.indent.api.IndentUtils;
59
import org.netbeans.modules.editor.indent.spi.Context;
59
import org.netbeans.modules.editor.indent.spi.Context;
Lines 61-67 Link Here
61
import org.netbeans.modules.editor.structure.formatting.TagBasedLexerFormatter;
61
import org.netbeans.modules.editor.structure.formatting.TagBasedLexerFormatter;
62
import org.netbeans.modules.xml.text.folding.TokenElement;
62
import org.netbeans.modules.xml.text.folding.TokenElement;
63
import org.netbeans.modules.xml.text.folding.TokenElement.TokenType;
63
import org.netbeans.modules.xml.text.folding.TokenElement.TokenType;
64
import org.netbeans.modules.xml.text.syntax.XMLKit;
65
64
66
/**
65
/**
67
 * New XML formatter based on Lexer APIs.
66
 * New XML formatter based on Lexer APIs.
Lines 71-77 Link Here
71
70
72
    private static final String TAG_OPENING_PREFIX = "<"; //NOI18N
71
    private static final String TAG_OPENING_PREFIX = "<"; //NOI18N
73
    private static final String TAG_CLOSING_PREFIX = "</"; //NOI18N
72
    private static final String TAG_CLOSING_PREFIX = "</"; //NOI18N
74
75
    private final LanguagePath languagePath;
73
    private final LanguagePath languagePath;
76
    private int spacesPerTab = 4;
74
    private int spacesPerTab = 4;
77
75
Lines 158-165 Link Here
158
            jts.moveNext();
156
            jts.moveNext();
159
            Token token = jts.token();
157
            Token token = jts.token();
160
158
161
            if (token.id() == XMLTokenId.TAG &&
159
            if (token.id() == XMLTokenId.TAG
162
                    !token.text().toString().endsWith("/>")) { //NOI18N
160
                    && !token.text().toString().endsWith("/>")) { //NOI18N
163
161
164
                while (jts.movePrevious()) {
162
                while (jts.movePrevious()) {
165
                    int tokenOffset = jts.offset();
163
                    int tokenOffset = jts.offset();
Lines 218-242 Link Here
218
    }
216
    }
219
217
220
// # 170343
218
// # 170343
221
//    @Override
219
    @Override
222
//    public void reformat(Context context, final int startOffset, final int endOffset)
220
    public void reformat(Context context, final int startOffset, final int endOffset)
223
//            throws BadLocationException {
221
            throws BadLocationException {
224
//       final BaseDocument doc = (BaseDocument) context.document();
222
        final BaseDocument doc = (BaseDocument) context.document();
225
//       doc.render(new Runnable() {
223
        doc.render(new Runnable() {
226
//           public void run() {
224
227
//               doReformat(doc, startOffset, endOffset);            
225
            public void run() {
228
//           }
226
                doReformat(doc, startOffset, endOffset);
229
//       }); 
227
            }
230
//    }
228
        });
229
    }
231
230
232
    public BaseDocument doReformat(BaseDocument doc, int startOffset, int endOffset) {
231
    public BaseDocument doReformat(BaseDocument doc, int startOffset, int endOffset) {
233
        spacesPerTab = IndentUtils.indentLevelSize(doc);
232
        spacesPerTab = IndentUtils.indentLevelSize(doc);
234
        try {
233
        try {
235
            List<TokenElement> tags = getTags(doc, startOffset, endOffset);
234
            List<TokenIndent> tags = getTags(doc, startOffset, endOffset);
236
            for (int i = tags.size() - 1; i >= 0; i--) {
235
            for (int i = tags.size() - 1; i >= 0; i--) {
237
                TokenElement tag = tags.get(i);
236
                if (tags.get(i).isPreserveIndent()) {
237
                    continue;
238
                }
239
                TokenElement tag = tags.get(i).getToken();
240
238
                int so = tag.getStartOffset();
241
                int so = tag.getStartOffset();
239
                int lineOffset = Utilities.getLineOffset(doc, so);
242
                int lineOffset = Utilities.getLineOffset(doc, so);
243
240
                String tagName = tag.getName();
244
                String tagName = tag.getName();
241
                if (tagName.startsWith("</")) {
245
                if (tagName.startsWith("</")) {
242
                    /* For Eg:-
246
                    /* For Eg:-
Lines 252-258 Link Here
252
                    int ndx = lineStr.lastIndexOf(tagName);
256
                    int ndx = lineStr.lastIndexOf(tagName);
253
                    if (ndx != -1) {
257
                    if (ndx != -1) {
254
                        lineStr = lineStr.substring(0, ndx);
258
                        lineStr = lineStr.substring(0, ndx);
255
                        int ndx2 = lineStr.lastIndexOf("<" + tagName.substring(2) );
259
                        int ndx2 = lineStr.lastIndexOf("<" + tagName.substring(2));
256
                        if (ndx2 == -1) {//no start found in this line, so indent this tag
260
                        if (ndx2 == -1) {//no start found in this line, so indent this tag
257
                            changePrettyText(doc, tag, so);
261
                            changePrettyText(doc, tag, so);
258
                        } else {
262
                        } else {
Lines 266-301 Link Here
266
                } else {
270
                } else {
267
                    changePrettyText(doc, tag, so);
271
                    changePrettyText(doc, tag, so);
268
                }
272
                }
269
            }            
273
            }
270
        } catch (BadLocationException ble) {
274
        } catch (BadLocationException ble) {
271
            //ignore exception
275
            //ignore exception
272
        } catch (IOException iox) {
276
        } catch (IOException iox) {
273
           //ignore exception
277
            //ignore exception
274
        } finally {
278
        } finally {
275
           //((AbstractDocument)doc).readUnlock();
279
            //((AbstractDocument)doc).readUnlock();
276
        }
280
        }
277
        return doc;
281
        return doc;
278
    }
282
    }
279
283
280
    private void changePrettyText(BaseDocument doc, TokenElement tag, int so) throws BadLocationException {
284
    private void changePrettyText(BaseDocument doc, TokenElement tag, int so) throws BadLocationException {
281
        Formatter formatter = Formatter.getFormatter(XMLKit.class);
282
        formatter.setExpandTabs(false);
283
        //i expected the call IndentUtils.createIndentString() to return
285
        //i expected the call IndentUtils.createIndentString() to return
284
        //the correct string for the indent level, but it doesn't.
286
        //the correct string for the indent level, but it doesn't.
285
        //so this is just a workaround.
287
        //so this is just a workaround.
286
        String newIndentText = IndentUtils.createIndentString(doc,
288
        String newIndentText = IndentUtils.createIndentString(doc,
287
                tag.getIndentLevel()*spacesPerTab);
289
                tag.getIndentLevel() * spacesPerTab);
288
        //String newIndentText = formatter.getIndentString(doc, tag.getIndentLevel());
290
        //String newIndentText = formatter.getIndentString(doc, tag.getIndentLevel());
289
        int previousEndOffset = Utilities.getFirstNonWhiteBwd(doc, so) + 1;
291
        int previousEndOffset = Utilities.getFirstNonWhiteBwd(doc, so) + 1;
290
        String temp = doc.getText(previousEndOffset, so - previousEndOffset);
292
        String temp = doc.getText(previousEndOffset, so - previousEndOffset);
291
        if(temp.indexOf("\n") != -1){
293
        if (temp.indexOf("\n") != -1) {
292
            int i = Utilities.getRowFirstNonWhite(doc, so);
294
            int i = Utilities.getRowFirstNonWhite(doc, so);
293
            int rowStart = Utilities.getRowStart(doc, so);
295
            int rowStart = Utilities.getRowStart(doc, so);
294
            doc.insertString(so, newIndentText, null);
296
            doc.insertString(so, newIndentText, null);
295
            doc.remove(rowStart, i - rowStart);            
297
            doc.remove(rowStart, i - rowStart);
296
        }
298
        } else {
297
        else {
299
            doc.insertString(so, "\n" + newIndentText, null);
298
             doc.insertString(so, "\n" + newIndentText, null);
299
        }
300
        }
300
    }
301
    }
301
302
Lines 304-321 Link Here
304
     * This method parses the document using lexer and creates folds and adds
305
     * This method parses the document using lexer and creates folds and adds
305
     * them to the fold hierarchy.
306
     * them to the fold hierarchy.
306
     */
307
     */
307
    private List<TokenElement> getTags(BaseDocument basedoc, int startOffset, int endOffset)
308
    private List<TokenIndent> getTags(BaseDocument basedoc, int startOffset, int endOffset)
308
            throws BadLocationException, IOException {
309
            throws BadLocationException, IOException {
309
        List<TokenElement> tags = new ArrayList<TokenElement>();
310
        List<TokenIndent> tags = new ArrayList<TokenIndent>();
311
        LinkedList<Boolean> preserveNesting_outdent = new LinkedList<Boolean>();
312
        preserveNesting_outdent.add(Boolean.FALSE);
313
        boolean preserveWhitespace = false;
314
        boolean settingSpaceValue = false;
315
        int indentLevel = -1;
310
        basedoc.readLock();
316
        basedoc.readLock();
311
        int incrIndentLevelBy = 0;
317
        int incrIndentLevelBy = 0;
312
        try {
318
        try {
313
            //are we formatting from the beginning of doc or a subsection
319
            //are we formatting from the beginning of doc or a subsection
314
            int line = Utilities.getLineOffset(basedoc, startOffset);
320
            int line = Utilities.getLineOffset(basedoc, startOffset);
315
            if(line > 0) {
321
            if (line > 0) {
316
                boolean nested = isSubSectionToFormatNested(basedoc, startOffset);
322
                boolean nested = isSubSectionToFormatNested(basedoc, startOffset);
317
                //we are formatting a subsection
323
                //we are formatting a subsection
318
                int precedingWordLoc = Utilities.getFirstNonWhiteBwd(basedoc, startOffset) ;
324
                int precedingWordLoc = Utilities.getFirstNonWhiteBwd(basedoc, startOffset);
319
                int previousLine = Utilities.getLineOffset(basedoc, precedingWordLoc);
325
                int previousLine = Utilities.getLineOffset(basedoc, precedingWordLoc);
320
                int previousLineIndentation = 0;
326
                int previousLineIndentation = 0;
321
                //we need to get the previous line and find its indentation
327
                //we need to get the previous line and find its indentation
Lines 323-345 Link Here
323
                //has selected the entire line to format
329
                //has selected the entire line to format
324
                //the previous line will be the same as current line if user
330
                //the previous line will be the same as current line if user
325
                //selected a part of line to format
331
                //selected a part of line to format
326
                if(previousLine != line){
332
                if (previousLine != line) {
327
                    previousLineIndentation = Utilities.getRowIndent(basedoc, precedingWordLoc);
333
                    previousLineIndentation = Utilities.getRowIndent(basedoc, precedingWordLoc);
328
                } else
334
                } else {
329
                    previousLineIndentation = Utilities.getRowIndent(basedoc, startOffset);
335
                    previousLineIndentation = Utilities.getRowIndent(basedoc, startOffset);
336
                }
330
                //the section being formatted should be idented wrt to previous line's indentation
337
                //the section being formatted should be idented wrt to previous line's indentation
331
              
338
332
                    int div = previousLineIndentation / spacesPerTab;
339
                int div = previousLineIndentation / spacesPerTab;
333
                    if(nested)
340
                if (nested) {
334
                       incrIndentLevelBy = div +1;
341
                    incrIndentLevelBy = div + 1;
335
                    else
342
                } else {
336
                        incrIndentLevelBy = div;
343
                    incrIndentLevelBy = div;
337
                
344
                }
345
338
            }
346
            }
339
            TokenHierarchy tokenHierarchy = TokenHierarchy.get(basedoc);
347
            TokenHierarchy tokenHierarchy = TokenHierarchy.get(basedoc);
340
            TokenSequence<XMLTokenId> tokenSequence = tokenHierarchy.tokenSequence();
348
            TokenSequence<XMLTokenId> tokenSequence = tokenHierarchy.tokenSequence();
341
            org.netbeans.api.lexer.Token<XMLTokenId> token = tokenSequence.token();
349
            org.netbeans.api.lexer.Token<XMLTokenId> token = tokenSequence.token();
342
            // Add the text token, if any, before xml decalration to document node
350
            // Add the text token, if any, before xml declaration to document node
343
            if (token != null && token.id() == XMLTokenId.TEXT) {
351
            if (token != null && token.id() == XMLTokenId.TEXT) {
344
                if (tokenSequence.moveNext()) {
352
                if (tokenSequence.moveNext()) {
345
                    token = tokenSequence.token();
353
                    token = tokenSequence.token();
Lines 347-367 Link Here
347
            }
355
            }
348
            int currentTokensSize = 0;
356
            int currentTokensSize = 0;
349
            Stack<TokenElement> stack = new Stack<TokenElement>();
357
            Stack<TokenElement> stack = new Stack<TokenElement>();
350
            String currentNode = null;
351
            while (tokenSequence.moveNext()) {
358
            while (tokenSequence.moveNext()) {
352
                token = tokenSequence.token();
359
                token = tokenSequence.token();
353
                XMLTokenId tokenId = token.id();
360
                XMLTokenId tokenId = token.id();
354
                String image = token.text().toString();
361
                String image = token.text().toString();
355
                if( ! (tokenSequence.offset() >= startOffset && tokenSequence.offset() <endOffset) ) {
362
                if (tokenSequence.offset() > endOffset) {
356
                    currentTokensSize += image.length();
363
                    break;
357
                    continue;
358
                }
364
                }
365
                boolean tokenInSelectionRange = tokenSequence.offset() >= startOffset;
359
                TokenType tokenType = TokenType.TOKEN_WHITESPACE;
366
                TokenType tokenType = TokenType.TOKEN_WHITESPACE;
360
                switch (tokenId) {
367
                switch (tokenId) {
361
                    case TAG: {
368
                    case TAG: {
362
                        int len = image.length();
369
                        int len = image.length();
363
                        if (image.charAt(len - 1) == '>') {// '/>'
370
                        if (image.charAt(len - 1) == '>') {// '/>'
364
                            if (len == 2) {
371
                            if (len == 2) {
372
                                if (!preserveWhitespace) {
373
                                    --indentLevel;
374
                                }
365
                                if (!stack.empty()) {
375
                                if (!stack.empty()) {
366
                                    stack.pop();
376
                                    stack.pop();
367
                                }
377
                                }
Lines 369-395 Link Here
369
                        } else {
379
                        } else {
370
                            tokenType = TokenType.TOKEN_ELEMENT_START_TAG;
380
                            tokenType = TokenType.TOKEN_ELEMENT_START_TAG;
371
                            if (image.startsWith("</")) {
381
                            if (image.startsWith("</")) {
372
                                String tagName = image.substring(2);
373
                                currentNode = tagName;
374
                                int begin = currentTokensSize;
382
                                int begin = currentTokensSize;
375
                                int end = begin + image.length();
383
                                int end = begin + image.length();
376
                                int indentLevel = incrIndentLevelBy;
384
377
                                if (!stack.empty()) {
385
                                boolean preservingWhitespaceOnClose = preserveNesting_outdent.removeLast();
378
                                    stack.pop();
386
                                if (indentLevel < 0) {
379
                                    indentLevel = stack.size() +incrIndentLevelBy;
387
                                    indentLevel = 0;
380
                                }
388
                                }
381
                                
382
                                TokenElement tag = new TokenElement(tokenType, image, begin, end, indentLevel);
389
                                TokenElement tag = new TokenElement(tokenType, image, begin, end, indentLevel);
383
                                tags.add(tag);
390
                                if (tokenInSelectionRange) {
391
                                    tags.add(new TokenIndent(tag, preservingWhitespaceOnClose));
392
                                }
393
                                if (!preserveNesting_outdent.getLast()) {
394
                                    --indentLevel;
395
                                }
384
                            } else {
396
                            } else {
385
                                String tagName = image.substring(1);
397
                                String tagName = image.substring(1);
386
                                int begin = currentTokensSize;
398
                                int begin = currentTokensSize;
387
                                int end = begin + image.length();
399
                                int end = begin + image.length();
388
                                int indentLevel = stack.size() + incrIndentLevelBy;
400
                                preserveWhitespace = preserveNesting_outdent.getLast();
401
                                if (!preserveWhitespace) {
402
                                    ++indentLevel;
403
                                }
404
                                preserveNesting_outdent.add(preserveWhitespace);
389
                                TokenElement tag = new TokenElement(tokenType, tagName, begin, end, indentLevel);
405
                                TokenElement tag = new TokenElement(tokenType, tagName, begin, end, indentLevel);
390
                                tags.add(tag);
406
                                if (tokenInSelectionRange) {
391
                                stack.push(tag);
407
                                    tags.add(new TokenIndent(tag, preserveWhitespace));
408
                                }
392
                            }
409
                            }
410
                            settingSpaceValue = false;
393
                        }
411
                        }
394
                        break;
412
                        break;
395
                    }
413
                    }
Lines 399-418 Link Here
399
                    case PI_TARGET:
417
                    case PI_TARGET:
400
                    case PI_CONTENT:
418
                    case PI_CONTENT:
401
                    case PI_END:
419
                    case PI_END:
402
                    case ARGUMENT: //attribute of an element
403
                    case VALUE:
404
                    case TEXT:
420
                    case TEXT:
405
                    case CHARACTER:
421
                    case CHARACTER:
406
                    case WS:
422
                    case WS:
407
                    case OPERATOR:
423
                    case OPERATOR:
408
                    case DECLARATION:
424
                    case DECLARATION:
409
                        break; //Do nothing for above case's
425
                        break; //Do nothing for above case's
426
                    case ARGUMENT: //attribute of an element
427
                        settingSpaceValue = token.text().equals("xml:space");
428
                        break;
429
                    case VALUE:
430
                        if (settingSpaceValue) {
431
                            if (token.text().equals("\"preserve\"")) {
432
                                preserveWhitespace = true;
433
                            } else if (token.text().equals("\"default\"")) {
434
                                preserveWhitespace = false;
435
                            }
436
                            preserveNesting_outdent.set(preserveNesting_outdent.size() - 1, preserveWhitespace);
437
                            settingSpaceValue = false;
438
                        }
439
                        break;
410
440
411
                    case ERROR:
441
                    case ERROR:
412
                    case EOL:
442
                    case EOL:
413
                    default:
443
                    default:
414
                        throw new IOException("Invalid token found in document: " +
444
                        throw new IOException("Invalid token found in document: "
415
                                "Please use the text editor to resolve the issues...");
445
                                + "Please use the text editor to resolve the issues...");
416
                }
446
                }
417
                currentTokensSize += image.length();
447
                currentTokensSize += image.length();
418
            }
448
            }
Lines 424-459 Link Here
424
454
425
    public boolean isOneLiner(int start, int end, BaseDocument doc) {
455
    public boolean isOneLiner(int start, int end, BaseDocument doc) {
426
        try {
456
        try {
427
            return Utilities.getLineOffset(doc, start) ==
457
            return Utilities.getLineOffset(doc, start)
428
                    Utilities.getLineOffset(doc, end);
458
                    == Utilities.getLineOffset(doc, end);
429
        } catch (BadLocationException ex) {
459
        } catch (BadLocationException ex) {
430
            //Exceptions.printStackTrace(ex);
460
            //Exceptions.printStackTrace(ex);
431
            return false;
461
            return false;
432
        }
462
        }
433
    }
463
    }
434
    
464
435
    private boolean isSubSectionToFormatNested(BaseDocument baseDoc, int startOffset){
465
    private boolean isSubSectionToFormatNested(BaseDocument baseDoc, int startOffset) {
436
      AbstractDocument doc = (AbstractDocument)baseDoc;
466
        AbstractDocument doc = (AbstractDocument) baseDoc;
437
      doc.readLock();
467
        doc.readLock();
438
      try {
468
        try {
439
          TokenHierarchy th = TokenHierarchy.get(doc);
469
            TokenHierarchy th = TokenHierarchy.get(doc);
440
          TokenSequence ts = th.tokenSequence();
470
            TokenSequence ts = th.tokenSequence();
441
          ts.move(startOffset);
471
            ts.move(startOffset);
442
          while(ts.movePrevious()) {
472
            while (ts.movePrevious()) {
443
              Token t = ts.token();
473
                Token t = ts.token();
444
              if(t.id() == XMLTokenId.PI_END)
474
                if (t.id() == XMLTokenId.PI_END) {
445
                  return false;
475
                    return false;
446
              String tagText = t.text().toString();
476
                }
447
              if(tagText.startsWith("</") || tagText.equals("/>"))
477
                String tagText = t.text().toString();
448
                  return false;
478
                if (tagText.startsWith("</") || tagText.equals("/>")) {
449
              if(tagText.startsWith("<"))
479
                    return false;
450
                  return true;
480
                }
451
          }
481
                if (tagText.startsWith("<")) {
452
      } catch  (Exception ex) {
482
                    return true;
453
          //return false anyway
483
                }
454
      } finally {
484
            }
455
          doc.readUnlock();
485
        } catch (Exception ex) {
456
      }
486
            //return false anyway
457
      return false;
487
        } finally {
488
            doc.readUnlock();
489
        }
490
        return false;
491
    }
492
493
    private class TokenIndent {
494
495
        private TokenElement token;
496
        private boolean preserveIndent;
497
498
        public TokenIndent(TokenElement token, boolean preserveIndent) {
499
            this.token = token;
500
            this.preserveIndent = preserveIndent;
501
        }
502
503
        public TokenElement getToken() {
504
            return token;
505
        }
506
507
        public boolean isPreserveIndent() {
508
            return preserveIndent;
509
        }
510
511
        public void setPreserveIndent(boolean preserveIndent) {
512
            this.preserveIndent = preserveIndent;
513
        }
514
515
        @Override
516
        public String toString() {
517
            return "TokenIndent: name=" + token.getName() + " preserveIndent=" + preserveIndent;
518
        }
458
    }
519
    }
459
}
520
}
(-)a/xml.text/test/unit/src/org/netbeans/modules/xml/text/indent/XMLLexerFormatterTest.java (-23 / +60 lines)
Lines 1-7 Link Here
1
/*
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 * 
3
 * 
4
 * Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
4
 * Copyright 1997-2010 Sun Microsystems, Inc. All rights reserved.
5
 * 
5
 * 
6
 * The contents of this file are subject to the terms of either the GNU
6
 * The contents of this file are subject to the terms of either the GNU
7
 * General Public License Version 2 only ("GPL") or the Common
7
 * General Public License Version 2 only ("GPL") or the Common
Lines 48-54 Link Here
48
 * @author Samaresh (samaresh.panda@sun.com)
48
 * @author Samaresh (samaresh.panda@sun.com)
49
 */
49
 */
50
public class XMLLexerFormatterTest extends AbstractTestCase {
50
public class XMLLexerFormatterTest extends AbstractTestCase {
51
    
51
52
    public XMLLexerFormatterTest(String testName) {
52
    public XMLLexerFormatterTest(String testName) {
53
        super(testName);
53
        super(testName);
54
    }
54
    }
Lines 61-69 Link Here
61
        suite.addTest(new XMLLexerFormatterTest("testFormatPerformance"));
61
        suite.addTest(new XMLLexerFormatterTest("testFormatPerformance"));
62
        suite.addTest(new XMLLexerFormatterTest("testFormatSubsection1"));
62
        suite.addTest(new XMLLexerFormatterTest("testFormatSubsection1"));
63
        suite.addTest(new XMLLexerFormatterTest("testFormatSubsection2"));
63
        suite.addTest(new XMLLexerFormatterTest("testFormatSubsection2"));
64
        suite.addTest(new XMLLexerFormatterTest("testFormat_PreserveWhitespace"));
65
        suite.addTest(new XMLLexerFormatterTest("testFormat_WithNestedPreserveWhitespace"));
66
        suite.addTest(new XMLLexerFormatterTest("testFormatSubsection_PreserveWhitespace"));
64
        return suite;
67
        return suite;
65
    }
68
    }
66
    
69
67
    /**
70
    /**
68
     * Formats an input document and then compares the formatted doc
71
     * Formats an input document and then compares the formatted doc
69
     * with a document that represents expected outcome.
72
     * with a document that represents expected outcome.
Lines 74-93 Link Here
74
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
77
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
75
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 0, inputDoc.getLength());
78
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 0, inputDoc.getLength());
76
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
79
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
77
        BaseDocument outputDoc = getDocument("indent/output.xml");        
80
        BaseDocument outputDoc = getDocument("indent/output.xml");
78
        assert(compare(formattedDoc, outputDoc));
81
        assert (compare(formattedDoc, outputDoc));
79
    }
82
    }
80
    
83
81
    public void testFormatSubsection() throws Exception {
84
    public void testFormatSubsection() throws Exception {
82
        BaseDocument inputDoc = getDocument("indent/input_sub.xml");
85
        BaseDocument inputDoc = getDocument("indent/input_sub.xml");
83
        //format a subsection of the inputDoc
86
        //format a subsection of the inputDoc
84
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
87
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
85
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 72, 97);
88
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 72, 97);
86
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
89
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
87
        BaseDocument outputDoc = getDocument("indent/output_sub.xml");        
90
        BaseDocument outputDoc = getDocument("indent/output_sub.xml");
88
        assert(compare(formattedDoc, outputDoc));
91
        assert (compare(formattedDoc, outputDoc));
89
    }
92
    }
90
    
93
91
    //for bug 139160
94
    //for bug 139160
92
    public void testFormatForTab() throws Exception {
95
    public void testFormatForTab() throws Exception {
93
        BaseDocument inputDoc = getDocument("indent/input2.xsd");
96
        BaseDocument inputDoc = getDocument("indent/input2.xsd");
Lines 95-105 Link Here
95
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
98
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
96
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 0, inputDoc.getLength());
99
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 0, inputDoc.getLength());
97
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
100
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
98
        BaseDocument outputDoc = getDocument("indent/output2.xsd");        
101
        BaseDocument outputDoc = getDocument("indent/output2.xsd");
99
        assert(compare(formattedDoc, outputDoc));
102
        assert (compare(formattedDoc, outputDoc));
100
    }
103
    }
101
    
104
102
      
103
    public void testFormatPerformance() throws Exception {
105
    public void testFormatPerformance() throws Exception {
104
        BaseDocument inputDoc = getDocument("indent/1998stats.xml");
106
        BaseDocument inputDoc = getDocument("indent/1998stats.xml");
105
        //format the inputDoc
107
        //format the inputDoc
Lines 107-114 Link Here
107
        long t1 = System.currentTimeMillis();
109
        long t1 = System.currentTimeMillis();
108
        formatter.doReformat(inputDoc, 0, inputDoc.getLength());
110
        formatter.doReformat(inputDoc, 0, inputDoc.getLength());
109
        long t2 = System.currentTimeMillis();
111
        long t2 = System.currentTimeMillis();
110
        System.out.println("Time taken to format NFL XML in ms:: " + (t2-t1) );
112
        System.out.println("Time taken to format NFL XML in ms:: " + (t2 - t1));
111
        
113
112
        //try OTA Schema
114
        //try OTA Schema
113
        inputDoc = getDocument("indent/1998stats.xml");
115
        inputDoc = getDocument("indent/1998stats.xml");
114
        //format the inputDoc
116
        //format the inputDoc
Lines 116-140 Link Here
116
        t1 = System.currentTimeMillis();
118
        t1 = System.currentTimeMillis();
117
        formatter.doReformat(inputDoc, 0, inputDoc.getLength());
119
        formatter.doReformat(inputDoc, 0, inputDoc.getLength());
118
        t2 = System.currentTimeMillis();
120
        t2 = System.currentTimeMillis();
119
        System.out.println("Time taken to format OTA Schema in ms:: " + (t2-t1) );
121
        System.out.println("Time taken to format OTA Schema in ms:: " + (t2 - t1));
120
    }
122
    }
123
121
    public void testFormatSubsection1() throws Exception {
124
    public void testFormatSubsection1() throws Exception {
122
        BaseDocument inputDoc = getDocument("indent/input_sub1.xml");
125
        BaseDocument inputDoc = getDocument("indent/input_sub1.xml");
123
        //format a subsection of the inputDoc
126
        //format a subsection of the inputDoc
124
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
127
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
125
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 39, 68);
128
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 46, 74);
126
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
129
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
127
        BaseDocument outputDoc = getDocument("indent/output_sub1.xml");        
130
        BaseDocument outputDoc = getDocument("indent/output_sub1.xml");
128
        assert(compare(formattedDoc, outputDoc));
131
        assert (compare(formattedDoc, outputDoc));
129
    }
132
    }
130
    
133
131
    public void testFormatSubsection2() throws Exception {
134
    public void testFormatSubsection2() throws Exception {
132
        BaseDocument inputDoc = getDocument("indent/input_sub2.xml");
135
        BaseDocument inputDoc = getDocument("indent/input_sub2.xml");
133
        //format a subsection of the inputDoc
136
        //format a subsection of the inputDoc
134
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
137
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
135
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 68, 83);
138
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 51, 80);
136
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
139
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
137
        BaseDocument outputDoc = getDocument("indent/output_sub2.xml");        
140
        BaseDocument outputDoc = getDocument("indent/output_sub2.xml");
138
        assert(compare(formattedDoc, outputDoc));
141
        assert (compare(formattedDoc, outputDoc));
142
    }
143
144
    //for bug 170343
145
    public void testFormat_PreserveWhitespace() throws Exception {
146
        BaseDocument inputDoc = getDocument("indent/input_preserve.xml");
147
        //format the inputDoc
148
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
149
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 0, inputDoc.getLength());
150
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
151
        BaseDocument outputDoc = getDocument("indent/output_preserve.xml");
152
        assert (compare(formattedDoc, outputDoc));
153
    }
154
155
    //for bug 170343
156
    public void testFormat_WithNestedPreserveWhitespace() throws Exception {
157
        BaseDocument inputDoc = getDocument("indent/input_withpreserve.xml");
158
        //format the inputDoc
159
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
160
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 0, inputDoc.getLength());
161
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
162
        BaseDocument outputDoc = getDocument("indent/output_withpreserve.xml");
163
        assert (compare(formattedDoc, outputDoc));
164
    }
165
166
    //for bug 170343
167
    public void testFormatSubsection_PreserveWhitespace() throws Exception {
168
        BaseDocument inputDoc = getDocument("indent/input_preserve.xml");
169
        //format the inputDoc
170
        XMLLexerFormatter formatter = new XMLLexerFormatter(null);
171
        System.out.println("SECTION:" + inputDoc.getText(91, 87));
172
        BaseDocument formattedDoc = formatter.doReformat(inputDoc, 91, 91 + 87);
173
        System.out.println(formattedDoc.getText(0, formattedDoc.getLength()));
174
        BaseDocument outputDoc = getDocument("indent/output_preserve.xml");
175
        assert (compare(formattedDoc, outputDoc));
139
    }
176
    }
140
}
177
}
(-)a/xml.text/test/unit/src/org/netbeans/modules/xml/text/indent/input.xml (-23 / +24 lines)
Lines 1-31 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
2
3
<!-- hello world -->
3
<!-- hello world -->
4
<wrap>
5
    <root>
6
        <a><b>hello world</b></a>
7
    </root>
4
8
5
<root>
6
    <a><b>hello world</b></a>
7
</root>
8
9
10
    <!-- bug# 135478 -->
11
    <root>
9
12
10
<!-- bug# 135478 -->
13
        <a>
11
<root>
12
    
13
    <a>
14
        
15
    <b>test</b>
16
    
17
    
18
    </a>
19
</root>
20
14
21
<!-- bug# 135217-->
15
            <b>test</b>
22
<root>
23
    <a>
24
    <b>test</b>
25
    </a>
26
</root>
27
16
28
<!-- bug#135107 -->
17
29
<root>
18
        </a>
30
    <property name="AVERAGE">1</property>
19
    </root>
31
</root>
20
21
    <!-- bug# 135217-->
22
    <root>
23
        <a>
24
            <b>test</b>
25
        </a>
26
    </root>
27
28
    <!-- bug#135107 -->
29
    <root>
30
        <property name="AVERAGE">1</property>
31
    </root>
32
</wrap>
(-)a/xml.text/test/unit/src/org/netbeans/modules/xml/text/indent/input_sub1.xml (-2 / +2 lines)
Lines 1-5 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<root>
2
<test attr="replace"></test>
3
<test attr="replace"></test>
3
<root>
4
<a/>
4
</root>
5
</root>
5
(-)a/xml.text/test/unit/src/org/netbeans/modules/xml/text/indent/input_sub2.xml (-1 / +2 lines)
Lines 1-4 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<root>
2
<root>
3
<a/>
4
<test attr="replace"></test>
3
</root>
5
</root>
4
<test attr="replace"></test>
(-)a/xml.text/test/unit/src/org/netbeans/modules/xml/text/indent/output.xml (-25 / +26 lines)
Lines 1-33 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
2
3
<!-- hello world -->
3
<!-- hello world -->
4
<wrap>
5
    <root>
6
        <a>
7
            <b>hello world</b>
8
        </a>
9
    </root>
4
10
5
<root>
6
    <a>
7
        <b>hello world</b>
8
    </a>
9
</root>
10
11
12
    <!-- bug# 135478 -->
13
    <root>
11
14
12
<!-- bug# 135478 -->
15
        <a>
13
<root>
14
    
15
    <a>
16
        
17
        <b>test</b>
18
    
19
    
20
    </a>
21
</root>
22
16
23
<!-- bug# 135217-->
17
            <b>test</b>
24
<root>
25
    <a>
26
        <b>test</b>
27
    </a>
28
</root>
29
18
30
<!-- bug#135107 -->
19
31
<root>
20
        </a>
32
    <property name="AVERAGE">1</property>
21
    </root>
33
</root>
22
23
    <!-- bug# 135217-->
24
    <root>
25
        <a>
26
            <b>test</b>
27
        </a>
28
    </root>
29
30
    <!-- bug#135107 -->
31
    <root>
32
        <property name="AVERAGE">1</property>
33
    </root>
34
</wrap>
(-)a/xml.text/test/unit/src/org/netbeans/modules/xml/text/indent/output_sub1.xml (-2 / +2 lines)
Lines 1-5 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<test attr="replace"></test>
3
<root>
2
<root>
3
    <test attr="replace"></test>
4
<a/>
4
</root>
5
</root>
5
(-)a/xml.text/test/unit/src/org/netbeans/modules/xml/text/indent/output_sub2.xml (-1 / +2 lines)
Lines 1-4 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
1
<?xml version="1.0" encoding="UTF-8"?>
2
<root>
2
<root>
3
<a/>
4
    <test attr="replace"></test>
3
</root>
5
</root>
4
<test attr="replace"></test>

Return to bug 177192