Formatter.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. /*
  2. * Copyright (C) 2013 Apple Inc. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. * 1. Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * 2. Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. *
  13. * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
  14. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  15. * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  16. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
  17. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  18. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  19. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  20. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  21. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  22. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  23. * THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. function Formatter(codeMirror, builder)
  26. {
  27. console.assert(codeMirror);
  28. console.assert(builder);
  29. this._codeMirror = codeMirror;
  30. this._builder = builder;
  31. this._lastToken = null;
  32. this._lastContent = "";
  33. };
  34. Formatter.prototype = {
  35. constructor: Formatter,
  36. // Public
  37. format: function(from, to)
  38. {
  39. console.assert(this._builder.originalContent === null);
  40. if (this._builder.originalContent !== null)
  41. return;
  42. var outerMode = this._codeMirror.getMode();
  43. var content = this._codeMirror.getRange(from, to);
  44. var state = CodeMirror.copyState(outerMode, this._codeMirror.getTokenAt(from).state);
  45. this._builder.setOriginalContent(content);
  46. var lineOffset = 0;
  47. var lines = content.split("\n");
  48. for (var i = 0; i < lines.length; ++i) {
  49. var line = lines[i];
  50. var startOfNewLine = true;
  51. var firstTokenOnLine = true;
  52. var stream = new CodeMirror.StringStream(line);
  53. while (!stream.eol()) {
  54. var innerMode = CodeMirror.innerMode(outerMode, state);
  55. var token = outerMode.token(stream, state);
  56. var isWhiteSpace = token === null && /^\s*$/.test(stream.current());
  57. this._handleToken(innerMode.mode, token, state, stream, lineOffset + stream.start, isWhiteSpace, startOfNewLine, firstTokenOnLine);
  58. stream.start = stream.pos;
  59. startOfNewLine = false;
  60. if (firstTokenOnLine && !isWhiteSpace)
  61. firstTokenOnLine = false;
  62. }
  63. if (firstTokenOnLine)
  64. this._handleEmptyLine();
  65. lineOffset += line.length + 1; // +1 for the "\n" removed in split.
  66. this._handleLineEnding(lineOffset - 1); // -1 for the index of the "\n".
  67. }
  68. this._builder.finish();
  69. },
  70. // Private
  71. _handleToken: function(mode, token, state, stream, originalPosition, isWhiteSpace, startOfNewLine, firstTokenOnLine)
  72. {
  73. // String content of the token.
  74. var content = stream.current();
  75. // Start of a new line. Insert a newline to be safe if code was not-ASI safe. These are collapsed.
  76. if (startOfNewLine)
  77. this._builder.appendNewline();
  78. // Whitespace. Collapse to a single space.
  79. if (isWhiteSpace) {
  80. this._builder.appendSpace();
  81. return;
  82. }
  83. // Avoid some hooks for content in comments.
  84. var isComment = token && /\bcomment\b/.test(token);
  85. if (mode.modifyStateForTokenPre)
  86. mode.modifyStateForTokenPre(this._lastToken, this._lastContent, token, state, content, isComment);
  87. // Should we remove the last newline?
  88. if (this._builder.lastTokenWasNewline && mode.removeLastNewline(this._lastToken, this._lastContent, token, state, content, isComment, firstTokenOnLine))
  89. this._builder.removeLastNewline();
  90. // Add whitespace after the last token?
  91. if (!this._builder.lastTokenWasWhitespace && mode.shouldHaveSpaceAfterLastToken(this._lastToken, this._lastContent, token, state, content, isComment))
  92. this._builder.appendSpace();
  93. // Add whitespace before this token?
  94. if (!this._builder.lastTokenWasWhitespace && mode.shouldHaveSpaceBeforeToken(this._lastToken, this._lastContent, token, state, content, isComment))
  95. this._builder.appendSpace();
  96. // Should we dedent before this token?
  97. var dedents = mode.dedentsBeforeToken(this._lastToken, this._lastContent, token, state, content, isComment);
  98. while (dedents-- > 0)
  99. this._builder.dedent();
  100. // Should we add a newline before this token?
  101. if (mode.newlineBeforeToken(this._lastToken, this._lastContent, token, state, content, isComment))
  102. this._builder.appendNewline();
  103. // Should we indent before this token?
  104. if (mode.indentBeforeToken(this._lastToken, this._lastContent, token, state, content, isComment))
  105. this._builder.indent();
  106. // Append token.
  107. this._builder.appendToken(content, originalPosition);
  108. // Let the pretty printer update any state it keeps track of.
  109. if (mode.modifyStateForTokenPost)
  110. mode.modifyStateForTokenPost(this._lastToken, this._lastContent, token, state, content, isComment);
  111. // Should we indent or dedent after this token?
  112. if (!isComment && mode.indentAfterToken(this._lastToken, this._lastContent, token, state, content, isComment))
  113. this._builder.indent();
  114. // Should we add newlines after this token?
  115. var newlines = mode.newlinesAfterToken(this._lastToken, this._lastContent, token, state, content, isComment);
  116. if (newlines)
  117. this._builder.appendMultipleNewlines(newlines);
  118. // Record this token as the last token.
  119. this._lastToken = token;
  120. this._lastContent = content;
  121. },
  122. _handleEmptyLine: function()
  123. {
  124. // Preserve original whitespace only lines by adding a newline.
  125. // However, don't do this if the builder just added multiple newlines.
  126. if (!(this._builder.lastTokenWasNewline && this._builder.lastNewlineAppendWasMultiple))
  127. this._builder.appendNewline(true);
  128. },
  129. _handleLineEnding: function(originalNewLinePosition)
  130. {
  131. // Record the original line ending.
  132. this._builder.addOriginalLineEnding(originalNewLinePosition);
  133. }
  134. };