[358545] Formatting a JSP file, containing Java snippets, leads to misformatted or even lost code
diff --git a/bundles/org.eclipse.jst.jsp.ui/src/org/eclipse/jst/jsp/ui/internal/format/FormattingStrategyJSPJava.java b/bundles/org.eclipse.jst.jsp.ui/src/org/eclipse/jst/jsp/ui/internal/format/FormattingStrategyJSPJava.java
index 309b910..cb961e2 100644
--- a/bundles/org.eclipse.jst.jsp.ui/src/org/eclipse/jst/jsp/ui/internal/format/FormattingStrategyJSPJava.java
+++ b/bundles/org.eclipse.jst.jsp.ui/src/org/eclipse/jst/jsp/ui/internal/format/FormattingStrategyJSPJava.java
@@ -1,5 +1,5 @@
 /*******************************************************************************
- * Copyright (c) 2004, 2005 IBM Corporation and others.
+ * Copyright (c) 2004, 2011 IBM Corporation and others.
  * All rights reserved. This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License v1.0
  * which accompanies this distribution, and is available at
@@ -51,7 +51,6 @@
 	 */
 	public void format() {
 		super.format();
-
 		final IDocument document = (IDocument) fDocuments.removeFirst();
 		final TypedPosition partition = (TypedPosition) fPartitions.removeFirst();
 
@@ -62,7 +61,12 @@
 				ICompilationUnit cu = translationUtil.getCompilationUnit();
 				if (cu != null) {
 					String cuSource = cu.getSource();
-					TextEdit textEdit = formatString(CodeFormatter.K_COMPILATION_UNIT, cuSource, 0, TextUtilities.getDefaultLineDelimiter(document), getPreferences());
+					/*
+					 * Format the entire compilation unit, but only create
+					 * edits for the requested JSP partition's range in the
+					 * Java source
+					 */
+					TextEdit textEdit = formatString(CodeFormatter.K_COMPILATION_UNIT, cuSource, translationUtil.getTranslation().getJavaOffset(partition.getOffset()), partition.getLength(), TextUtilities.getDefaultLineDelimiter(document), getPreferences());
 
 					TextEdit jspEdit = translationUtil.getTranslation().getJspEdit(textEdit);
 					if (jspEdit != null && jspEdit.hasChildren())
@@ -84,6 +88,10 @@
 		}
 	}
 
+	private TextEdit formatString(int kind, String cuSource, int javaOffset, int length, String defaultLineDelimiter, Map preferences) {
+		return ToolFactory.createCodeFormatter(preferences).format(kind, cuSource, javaOffset, length, 0, defaultLineDelimiter);
+	}
+
 	/*
 	 * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStarts(org.eclipse.jface.text.formatter.IFormattingContext)
 	 */
diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsDataTypes.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsDataTypes.java
index 8bd2ae1..8563dc8 100644
--- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsDataTypes.java
+++ b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsDataTypes.java
@@ -31,7 +31,7 @@
 			HTML40Namespace.ATTR_NAME_ONMOUSEUP, HTML40Namespace.ATTR_NAME_ONMOUSEOVER, HTML40Namespace.ATTR_NAME_ONMOUSEMOVE,
 			HTML40Namespace.ATTR_NAME_ONMOUSEOUT, HTML40Namespace.ATTR_NAME_ONKEYPRESS, HTML40Namespace.ATTR_NAME_ONKEYDOWN, HTML40Namespace.ATTR_NAME_ONKEYUP,
 			HTML40Namespace.ATTR_NAME_ONHELP };
-	public static final String[] HTMLATREVENTS = { "onload ", "onunload", "onclick", "onmousedown", "onmouseup", "onmouseover", "onmousemove", "onmouseout", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+	public static final String[] HTMLATREVENTS = { "onload", "onunload", "onclick", "onmousedown", "onmouseup", "onmouseover", "onmousemove", "onmouseout", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
 			"onfocus", "onblur", "onkeypress", "onkeydown", "onkeyup", "onsubmit", "onreset", "onselect", "onchange", }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$
 	public static final String[] JSVALIDDATATYPES = { "JAVASCRIPT", "TEXT/JAVASCRIPT" }; //$NON-NLS-1$ //$NON-NLS-2$
 	public static String[] KEYWORDS = { "abstract", "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsTranslation.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsTranslation.java
index 74fd5d3..1b04c2f 100644
--- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsTranslation.java
+++ b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsTranslation.java
@@ -1,5 +1,5 @@
 /*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
+ * Copyright (c) 2008, 2011 IBM Corporation and others.
  * All rights reserved. This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License v1.0
  * which accompanies this distribution, and is available at
@@ -51,6 +51,7 @@
 import org.eclipse.wst.jsdt.web.core.internal.Logger;
 import org.eclipse.wst.jsdt.web.core.internal.project.JsWebNature;
 import org.eclipse.wst.sse.core.StructuredModelManager;
+import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
 import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
 import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
 
@@ -141,11 +142,14 @@
 	private void setBaseLocation() {
 		IDOMModel xmlModel = null;
 		try {
-			xmlModel = (IDOMModel) StructuredModelManager.getModelManager().getExistingModelForRead(fHtmlDocument);
+			IModelManager modelManager = StructuredModelManager.getModelManager();
+			xmlModel = (IDOMModel) modelManager.getExistingModelForRead(fHtmlDocument);
 			if (xmlModel == null) {
-				xmlModel = (IDOMModel) StructuredModelManager.getModelManager().getModelForRead(fHtmlDocument);
+				xmlModel = (IDOMModel) modelManager.getModelForRead(fHtmlDocument);
 			}
-			fModelBaseLocation = xmlModel.getBaseLocation();
+			if(xmlModel != null) {
+				fModelBaseLocation = xmlModel.getBaseLocation();
+			}
 		}
 		finally {
 			if (xmlModel != null)
diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsTranslator.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsTranslator.java
index ea0ae06..f2ae833 100644
--- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsTranslator.java
+++ b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/javascript/JsTranslator.java
@@ -18,27 +18,14 @@
 
 package org.eclipse.wst.jsdt.web.core.javascript;
 
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
 import org.eclipse.core.runtime.IProgressMonitor;
 import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
 import org.eclipse.core.runtime.Platform;
 import org.eclipse.core.runtime.Status;
 import org.eclipse.core.runtime.jobs.Job;
@@ -53,7 +40,6 @@
 import org.eclipse.jface.text.Region;
 import org.eclipse.wst.jsdt.core.IBuffer;
 import org.eclipse.wst.jsdt.web.core.internal.Logger;
-import org.eclipse.wst.sse.core.StructuredModelManager;
 import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
 import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
 import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
@@ -61,7 +47,6 @@
 import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionContainer;
 import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList;
 import org.eclipse.wst.sse.core.utils.StringUtils;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
 import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
 /**
 *
@@ -194,8 +179,10 @@
 			/* if mid re-write session doc changes have been ignored,
 			 * but if jsText is specifically request we should re-translate
 			 * to pick up any changes thus far
+			 * 
+			 * Same goes for if the job has been scheduled to run but has not yet run
 			 */
-			if(this.fIsInRewriteSession) {
+			if(this.fIsInRewriteSession || this.getState() != Job.NONE) {
 				this.reset();
 			}
 			
@@ -353,56 +340,6 @@
 	}
 	
 	protected void finishedTranslation() {
-		if(DEBUG_SAVE_OUTPUT){
-			IDOMModel xmlModel = null;
-			String baseLocation = null;
-			FileOutputStream fout = null;
-			PrintStream out = null;
-			try {
-				xmlModel = (IDOMModel) StructuredModelManager.getModelManager().getExistingModelForRead(fStructuredDocument);
-				if (xmlModel == null) {
-					xmlModel = (IDOMModel) StructuredModelManager.getModelManager().getModelForRead(fStructuredDocument);
-				}
-				baseLocation = xmlModel.getBaseLocation();
-			}
-			finally {
-				if (xmlModel != null)
-					xmlModel.releaseFromRead();
-			}
-			
-			if(baseLocation!=null){
-				IWorkspace workspace = ResourcesPlugin.getWorkspace();
-				IWorkspaceRoot root = workspace.getRoot();
-				IFile tFile = workspace.getRoot().getFile(new Path(baseLocation + ".js"));
-				File tempFile = tFile.getLocation().toFile();
-				
-				  if(tempFile.exists()){
-					  tempFile.delete();
-				  }
-				 
-				  try {
-					  tempFile.createNewFile();
-					  fout = new FileOutputStream(tempFile);
-					  out = new PrintStream(fout);
-					  out.println(fScriptText);
-					  out.close();
-				} catch (FileNotFoundException e) {
-				
-				} catch (IOException e) {
-					
-				}finally{
-					if(out!=null) out.close();
-				
-					
-				}
-				 try {
-					root.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
-				} catch (CoreException e) {
-					
-				}
-			}
-			
-		}
 	}
 	
 	/* (non-Javadoc)
@@ -425,7 +362,7 @@
 				if (r.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME) {
 					int start = r.getStart();
 					int offset = r.getTextEnd();
-					String tagAttrname = container.getText().substring(start, offset).trim();
+					String tagAttrname = container.getText(r);
 					/*
 					 * Attribute values aren't case sensative, also make sure next
 					 * region is attrib value
@@ -440,9 +377,9 @@
 						if (r.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE) {
 							int valStartOffset = container.getStartOffset(r);
 							// int valEndOffset = r.getTextEnd();
-							String rawText = container.getText().substring(r.getStart(), r.getTextEnd());
+							String rawText = container.getText(r);
 							if (rawText == null || rawText.length() == 0) {
-								return;
+								continue;
 							}
 							/* Strip quotes */
 							switch (rawText.charAt(0)) {
@@ -452,7 +389,7 @@
 									valStartOffset++;
 							}
 							if (rawText == null || rawText.length() == 0) {
-								return;
+								continue;
 							}
 							switch (rawText.charAt(rawText.length() - 1)) {
 								case '\'':
@@ -462,13 +399,28 @@
 							// Position inScript = new Position(scriptOffset,
 							// rawText.length());
 							/* Quoted text starts +1 and ends -1 char */
-							if(ADD_SEMICOLON_AT_INLINE) rawText = rawText + ";"; //$NON-NLS-1$
+							if(ADD_SEMICOLON_AT_INLINE && rawText.charAt(rawText.length()-1) != ';') rawText = rawText + ";"; //$NON-NLS-1$
 							Position inHtml = new Position(valStartOffset, rawText.length());
 							scriptLocationInHtml.add(inHtml);
 							/* need to pad the script text with spaces */
 							char[] spaces = Util.getPad(valStartOffset - scriptOffset);
+							for (int i = 0; i < spaces.length; i++) {
+								try {
+									char c = fStructuredDocument.getChar(scriptOffset + i);
+									if (c == '\n')
+										spaces[i] = '\n';
+									else if (c == '\r')
+										spaces[i] = '\r';
+									else if (c == '\t')
+										spaces[i] = '\t';
+								}
+								catch (BadLocationException e) {
+								}
+							}
 							fScriptText.append(spaces);
 							fScriptText.append(rawText);
+							if(r.getLength() > rawText.length())
+								fScriptText.append(Util.getPad(r.getLength() - rawText.length()));
 							scriptOffset = fScriptText.length();
 						}
 					}
@@ -481,13 +433,27 @@
 	 * @see org.eclipse.wst.jsdt.web.core.javascript.IJsTranslator#translateJSNode(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion)
 	 */
 	public void translateJSNode(IStructuredDocumentRegion container) {
+		if(container==null) return;
+		
 		ITextRegionCollection containerRegion = container;
 		Iterator regions = containerRegion.getRegions().iterator();
 		ITextRegion region = null;
 		
-		if(container==null) return;
-		
 		char[] spaces = Util.getPad(container.getStartOffset() - scriptOffset);
+		for (int i = 0; i < spaces.length; i++) {
+			try {
+				char c = fStructuredDocument.getChar(scriptOffset + i);
+				if (c == '\n')
+					spaces[i] = '\n';
+				else if (c == '\r')
+					spaces[i] = '\r';
+				else if (c == '\t')
+					spaces[i] = '\t';
+			}
+			catch (BadLocationException e) {
+				Logger.logException(e);
+			}
+		}
 		fScriptText.append(spaces);
 		scriptOffset = container.getStartOffset();
 	
@@ -775,6 +741,7 @@
 	 * @see org.eclipse.wst.jsdt.web.core.javascript.IJsTranslator#release()
 	 */
 	public void release() {
+		cancel();
 		fStructuredDocument.removeDocumentListener(this);
 		if (fStructuredDocument instanceof IDocumentExtension4) {
 			((IDocumentExtension4) fStructuredDocument).removeDocumentRewriteSessionListener(fDocumentRewriteSessionListener);
diff --git a/bundles/org.eclipse.wst.jsdt.web.support.jsp/plugin.xml b/bundles/org.eclipse.wst.jsdt.web.support.jsp/plugin.xml
index e574dfa..5fb3b38 100644
--- a/bundles/org.eclipse.wst.jsdt.web.support.jsp/plugin.xml
+++ b/bundles/org.eclipse.wst.jsdt.web.support.jsp/plugin.xml
@@ -52,6 +52,17 @@
 		</proposalComputerExtendedActivation>
 	</extension>
 
+	<!--======================================================================================-->
+	<!-- JS Adapter factories for JSP				   						  				  -->
+	<!--======================================================================================-->
+	<extension
+		point="org.eclipse.wst.sse.ui.adapterFactoryDescription">
+		<adapterFactoryDescription
+			class="org.eclipse.wst.jsdt.web.support.jsp.internal.AdapterFactoryProviderForJSDT">
+			<contentType id="org.eclipse.jst.jsp.core.jspsource" />
+		</adapterFactoryDescription>
+	</extension>
+
    <!--
    <extension point="org.eclipse.wst.common.project.facet.core.facets">
 		<event-handler facet="jst.web" type="POST_INSTALL"  version="[2.0">
diff --git a/bundles/org.eclipse.wst.jsdt.web.support.jsp/src/org/eclipse/wst/jsdt/web/support/jsp/internal/AdapterFactoryProviderForJSDT.java b/bundles/org.eclipse.wst.jsdt.web.support.jsp/src/org/eclipse/wst/jsdt/web/support/jsp/internal/AdapterFactoryProviderForJSDT.java
new file mode 100644
index 0000000..4e95569
--- /dev/null
+++ b/bundles/org.eclipse.wst.jsdt.web.support.jsp/src/org/eclipse/wst/jsdt/web/support/jsp/internal/AdapterFactoryProviderForJSDT.java
@@ -0,0 +1,24 @@
+/*******************************************************************************
+ * Copyright (c) 2011 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ * 
+ * Contributors:
+ *     IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.wst.jsdt.web.support.jsp.internal;
+
+import org.eclipse.jst.jsp.core.internal.modelhandler.ModelHandlerForJSP;
+import org.eclipse.wst.sse.core.internal.ltk.modelhandler.IDocumentTypeHandler;
+
+public class AdapterFactoryProviderForJSDT extends org.eclipse.wst.jsdt.web.ui.internal.registry.AdapterFactoryProviderForJSDT {
+	public AdapterFactoryProviderForJSDT() {
+		super();
+	}
+	public boolean isFor(IDocumentTypeHandler contentTypeDescription) {
+		return (contentTypeDescription instanceof ModelHandlerForJSP);
+	}
+}
diff --git a/bundles/org.eclipse.wst.jsdt.web.ui/plugin.xml b/bundles/org.eclipse.wst.jsdt.web.ui/plugin.xml
index 45e6dca..ba575f4 100644
--- a/bundles/org.eclipse.wst.jsdt.web.ui/plugin.xml
+++ b/bundles/org.eclipse.wst.jsdt.web.ui/plugin.xml
@@ -327,7 +327,7 @@
 	</extension>
 	
 	<!--======================================================================================-->
-	<!-- JSP UI Adapter factories					   						  				  -->
+	<!-- JS Adapter factories for HTML				   						  				  -->
 	<!--======================================================================================-->
 	<extension
 		point="org.eclipse.wst.sse.ui.adapterFactoryDescription">
diff --git a/bundles/org.eclipse.wst.jsdt.web.ui/src/org/eclipse/wst/jsdt/web/ui/internal/format/FormattingStrategyJSDT.java b/bundles/org.eclipse.wst.jsdt.web.ui/src/org/eclipse/wst/jsdt/web/ui/internal/format/FormattingStrategyJSDT.java
index b295d82..bca0886 100644
--- a/bundles/org.eclipse.wst.jsdt.web.ui/src/org/eclipse/wst/jsdt/web/ui/internal/format/FormattingStrategyJSDT.java
+++ b/bundles/org.eclipse.wst.jsdt.web.ui/src/org/eclipse/wst/jsdt/web/ui/internal/format/FormattingStrategyJSDT.java
@@ -1,5 +1,5 @@
 /*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
+ * Copyright (c) 2007, 2011 IBM Corporation and others.
  * All rights reserved. This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License v1.0
  * which accompanies this distribution, and is available at
@@ -22,16 +22,13 @@
 import org.eclipse.core.resources.ResourcesPlugin;
 import org.eclipse.core.runtime.IPath;
 import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
 import org.eclipse.jface.text.IDocument;
 import org.eclipse.jface.text.IDocumentPartitioningListener;
-import org.eclipse.jface.text.Region;
 import org.eclipse.jface.text.TextUtilities;
 import org.eclipse.jface.text.TypedPosition;
 import org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy;
 import org.eclipse.jface.text.formatter.FormattingContextProperties;
 import org.eclipse.jface.text.formatter.IFormattingContext;
-import org.eclipse.text.edits.ReplaceEdit;
 import org.eclipse.text.edits.TextEdit;
 import org.eclipse.wst.jsdt.core.IJavaScriptProject;
 import org.eclipse.wst.jsdt.core.JavaScriptCore;
@@ -40,10 +37,7 @@
 import org.eclipse.wst.jsdt.internal.formatter.DefaultCodeFormatter;
 import org.eclipse.wst.jsdt.web.core.internal.Logger;
 import org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation;
-import org.eclipse.wst.jsdt.web.core.javascript.IJsTranslator;
-import org.eclipse.wst.jsdt.web.core.javascript.JsTranslation;
 import org.eclipse.wst.jsdt.web.core.javascript.JsTranslationAdapter;
-import org.eclipse.wst.jsdt.web.core.javascript.JsTranslator;
 import org.eclipse.wst.sse.core.StructuredModelManager;
 import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
 import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
@@ -121,60 +115,31 @@
 				String jsTextNotTranslated = document.get(partition.getOffset(), partition.getLength());
 				
 				//deal with getting the JS text and unwrapping it from any <!-- //--> statements
-				String preText = "";
-				String postText = lineDelim + scriptRegionIndent;
+				int contentStart = partition.getOffset();
+				int contentLength = partition.getLength();
 
 				//find start comment tag
 				Pattern startPattern = Pattern.compile("(\\A(\\s*<!--.*(" + lineDelim + ")?))"); //$NON-NLS-1$
 				Matcher matcher = startPattern.matcher(jsTextNotTranslated);
 				if(matcher.find()) {
+					contentStart += matcher.end();
 					jsTextNotTranslated = matcher.replaceFirst(""); //$NON-NLS-1$
-					preText = lineDelim + scriptRegionIndent + matcher.group().trim();
 				}
 				
 				//find end tag
 				matcher = END_PATTERN.matcher(jsTextNotTranslated);
 				if(matcher.find()) {
 					jsTextNotTranslated = matcher.replaceFirst(""); //$NON-NLS-1$
-					postText = lineDelim + scriptRegionIndent + matcher.group().trim() + postText;
+					contentLength = matcher.start();
 				}
 				
-				//replace the text in the document with the none-translated JS text but without HTML leading and trailing comments
-				TextEdit replaceEdit = new ReplaceEdit(partition.getOffset(), partition.getLength(), jsTextNotTranslated);
-				replaceEdit.apply(document);
-				int jsRegionLength = jsTextNotTranslated.length();
-				
 				//translate the updated document
 				IJsTranslation translation = getTranslation(document);
 				String jsTextTranslated = translation.getJsText();
 				
 				//format the text translated text
-				TextEdit edit = CodeFormatterUtil.format2(CodeFormatter.K_JAVASCRIPT_UNIT, jsTextTranslated, partition.getOffset(), jsRegionLength, startIndentLevel, lineDelim, getPreferences());
-				IDocument jsDoc = new Document(jsTextTranslated);
-				
-				//Undo the text replacements done by the translator so that it could build a CU for the JS region
-				if(translation instanceof JsTranslation) {
-					IJsTranslator translator = ((JsTranslation)translation).getTranslator();
-					
-					if(translator instanceof JsTranslator) {
-						Region[] regions = ((JsTranslator)translator).getGeneratedRanges();
-						//for each generated range, replace it with the original text
-						for(int r = 0; r < regions.length; ++r) {
-							jsDoc.replace(regions[r].getOffset(), regions[r].getLength(),
-									document.get(regions[r].getOffset(), regions[r].getLength()));
-						}
-					}
-				}
-				
-				/* error formating the code so abort */
-				if(edit==null) return;
-				edit.apply(jsDoc);
-				String replaceText = lineDelim + getIndentationString(getPreferences(), startIndentLevel) + (jsDoc.get(edit.getOffset(), edit.getLength())).trim();
-				
-				//apply edit to html doc using the formated translated text and the possible leading and trailing html comments
-				replaceText = preText + replaceText + postText;
-				replaceEdit = new ReplaceEdit(partition.getOffset(), jsRegionLength, replaceText);
-				replaceEdit.apply(document);
+				TextEdit edit = CodeFormatterUtil.format2(CodeFormatter.K_JAVASCRIPT_UNIT, jsTextTranslated, contentStart, contentLength, startIndentLevel, lineDelim, getPreferences());
+				edit.apply(document);
 			} catch (BadLocationException e) {
 			}
 		}