Bug 1311240 Fix odd "{" and "}" of control statements in editor for conforming to our coding rules r?smaug draft
authorMasayuki Nakano <masayuki@d-toybox.com>
Mon, 24 Oct 2016 11:27:45 +0900
changeset 428506 42b300c42036a0b6e0274c6a6ea8ee24b453c992
parent 428476 215f9686117673a2c914ed207bc7da9bb8d741ad
child 428539 aaa37797b9b44d6a834d6bb7e66b91fd9db20f64
child 428682 55c0784f332a521daef288667d81cad25d4cf961
child 428686 33c54e594ac7f42a923f29ab792f76cddf38389c
child 428738 b218e92e8b1a40e7d98161a734e72faade20eb4f
child 428739 46277881f3eb0d9c21a273884db638438b5bc2ab
child 428742 dd3dc34a032f22abf3fd7f85556b47ffbeec55b2
push id33315
push usermasayuki@d-toybox.com
push dateMon, 24 Oct 2016 02:29:41 +0000
reviewerssmaug
bugs1311240
milestone52.0a1
Bug 1311240 Fix odd "{" and "}" of control statements in editor for conforming to our coding rules r?smaug Currently, editor code uses following style (or similar style) in a lot of places: if (foo) { } else { } This patch fixes this as conforming to our coding rules, i.e., it becomes: if (foo) { } else { } Additionally, this fixes other odd control statements in the files which include above issue because it's difficult to find following issues with searching the files: * if (foo) bar; * if (foo) { bar; } * if (foo) bar; Finally, if it becomes much simpler than current code, this patch rewrites existing code with "early return style". But this case is only a few places because this is risky. MozReview-Commit-ID: 2Gs26goWXrF
editor/composer/nsComposerCommands.cpp
editor/composer/nsComposerCommandsUpdater.cpp
editor/composer/nsComposerDocumentCommands.cpp
editor/composer/nsComposerRegistration.cpp
editor/composer/nsEditingSession.cpp
editor/composer/nsEditorSpellCheck.cpp
editor/libeditor/EditAggregateTransaction.cpp
editor/libeditor/EditorBase.cpp
editor/libeditor/EditorUtils.cpp
editor/libeditor/HTMLAnonymousNodeEditor.cpp
editor/libeditor/HTMLEditRules.cpp
editor/libeditor/HTMLEditUtils.cpp
editor/libeditor/HTMLEditor.cpp
editor/libeditor/HTMLEditorDataTransfer.cpp
editor/libeditor/HTMLEditorObjectResizer.cpp
editor/libeditor/HTMLStyleEditor.cpp
editor/libeditor/HTMLTableEditor.cpp
editor/libeditor/HTMLURIRefObject.cpp
editor/libeditor/InternetCiter.cpp
editor/libeditor/PlaceholderTransaction.cpp
editor/libeditor/SelectionState.cpp
editor/libeditor/TextEditRules.cpp
editor/libeditor/TextEditRulesBidi.cpp
editor/libeditor/TextEditor.cpp
editor/libeditor/TextEditorDataTransfer.cpp
editor/libeditor/TypeInState.cpp
editor/libeditor/WSRunObject.cpp
editor/txmgr/nsTransactionManager.cpp
editor/txmgr/tests/TestTXMgr.cpp
editor/txtsvc/nsTextServicesDocument.cpp
--- a/editor/composer/nsComposerCommands.cpp
+++ b/editor/composer/nsComposerCommands.cpp
@@ -322,18 +322,17 @@ nsListItemCommand::GetCurrentState(nsIEd
   nsCOMPtr<nsIHTMLEditor>  htmlEditor = do_QueryInterface(aEditor);
   NS_ENSURE_TRUE(htmlEditor, NS_NOINTERFACE);
 
   bool bMixed, bLI, bDT, bDD;
   nsresult rv = htmlEditor->GetListItemState(&bMixed, &bLI, &bDT, &bDD);
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool inList = false;
-  if (!bMixed)
-  {
+  if (!bMixed) {
     if (bLI) {
       inList = mTagName == nsGkAtoms::li;
     } else if (bDT) {
       inList = mTagName == nsGkAtoms::dt;
     } else if (bDD) {
       inList = mTagName == nsGkAtoms::dd;
     }
   }
@@ -413,18 +412,17 @@ nsRemoveListCommand::IsCommandEnabled(co
 
 
 NS_IMETHODIMP
 nsRemoveListCommand::DoCommand(const char *aCommandName, nsISupports *refCon)
 {
   nsCOMPtr<nsIHTMLEditor> editor = do_QueryInterface(refCon);
 
   nsresult rv = NS_OK;
-  if (editor)
-  {
+  if (editor) {
     // This removes any list type
     rv = editor->RemoveList(EmptyString());
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
@@ -459,18 +457,17 @@ nsIndentCommand::IsCommandEnabled(const 
 
 
 NS_IMETHODIMP
 nsIndentCommand::DoCommand(const char *aCommandName, nsISupports *refCon)
 {
   nsCOMPtr<nsIHTMLEditor> editor = do_QueryInterface(refCon);
 
   nsresult rv = NS_OK;
-  if (editor)
-  {
+  if (editor) {
     rv = editor->Indent(NS_LITERAL_STRING("indent"));
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsIndentCommand::DoCommandParams(const char *aCommandName,
@@ -578,18 +575,17 @@ nsMultiStateCommand::DoCommand(const cha
 NS_IMETHODIMP
 nsMultiStateCommand::DoCommandParams(const char *aCommandName,
                                      nsICommandParams *aParams,
                                      nsISupports *refCon)
 {
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
 
   nsresult rv = NS_OK;
-  if (editor)
-  {
+  if (editor) {
       nsAutoString tString;
 
       if (aParams) {
         nsXPIDLCString s;
         rv = aParams->GetCStringValue(STATE_ATTRIBUTE, getter_Copies(s));
         if (NS_SUCCEEDED(rv))
           tString.AssignWithConversion(s);
         else
@@ -604,18 +600,17 @@ nsMultiStateCommand::DoCommandParams(con
 
 NS_IMETHODIMP
 nsMultiStateCommand::GetCommandStateParams(const char *aCommandName,
                                            nsICommandParams *aParams,
                                            nsISupports *refCon)
 {
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
   nsresult rv = NS_OK;
-  if (editor)
-  {
+  if (editor) {
       rv = GetCurrentState(editor, aParams);
   }
   return rv;
 }
 
 nsParagraphStateCommand::nsParagraphStateCommand()
 : nsMultiStateCommand()
 {
@@ -628,18 +623,17 @@ nsParagraphStateCommand::GetCurrentState
   NS_ASSERTION(aEditor, "Need an editor here");
 
   nsCOMPtr<nsIHTMLEditor> htmlEditor = do_QueryInterface(aEditor);
   NS_ENSURE_TRUE(htmlEditor, NS_ERROR_FAILURE);
 
   bool outMixed;
   nsAutoString outStateString;
   nsresult rv = htmlEditor->GetParagraphState(&outMixed, outStateString);
-  if (NS_SUCCEEDED(rv))
-  {
+  if (NS_SUCCEEDED(rv)) {
     nsAutoCString tOutStateString;
     tOutStateString.AssignWithConversion(outStateString);
     aParams->SetBooleanValue(STATE_MIXED,outMixed);
     aParams->SetCStringValue(STATE_ATTRIBUTE, tOutStateString.get());
   }
   return rv;
 }
 
@@ -665,18 +659,17 @@ nsFontFaceStateCommand::GetCurrentState(
 {
   NS_ASSERTION(aEditor, "Need an editor here");
   nsCOMPtr<nsIHTMLEditor> htmlEditor = do_QueryInterface(aEditor);
   NS_ENSURE_TRUE(htmlEditor, NS_ERROR_FAILURE);
 
   nsAutoString outStateString;
   bool outMixed;
   nsresult rv = htmlEditor->GetFontFaceState(&outMixed, outStateString);
-  if (NS_SUCCEEDED(rv))
-  {
+  if (NS_SUCCEEDED(rv)) {
     aParams->SetBooleanValue(STATE_MIXED,outMixed);
     aParams->SetCStringValue(STATE_ATTRIBUTE, NS_ConvertUTF16toUTF8(outStateString).get());
   }
   return rv;
 }
 
 
 nsresult
@@ -928,18 +921,17 @@ nsAlignCommand::GetCurrentState(nsIEdito
 
   nsIHTMLEditor::EAlignment firstAlign;
   bool outMixed;
   nsresult rv = htmlEditor->GetAlignment(&outMixed, &firstAlign);
 
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsAutoString outStateString;
-  switch (firstAlign)
-  {
+  switch (firstAlign) {
     default:
     case nsIHTMLEditor::eLeft:
       outStateString.AssignLiteral("left");
       break;
 
     case nsIHTMLEditor::eCenter:
       outStateString.AssignLiteral("center");
       break;
@@ -977,18 +969,17 @@ nsAbsolutePositioningCommand::nsAbsolute
 
 NS_IMETHODIMP
 nsAbsolutePositioningCommand::IsCommandEnabled(const char * aCommandName,
                                                nsISupports *aCommandRefCon,
                                                bool *outCmdEnabled)
 {
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(aCommandRefCon);
   nsCOMPtr<nsIHTMLAbsPosEditor> htmlEditor = do_QueryInterface(aCommandRefCon);
-  if (htmlEditor)
-  {
+  if (htmlEditor) {
     bool isEditable = false;
     nsresult rv = editor->GetIsSelectionEditable(&isEditable);
     NS_ENSURE_SUCCESS(rv, rv);
     if (isEditable)
       return htmlEditor->GetAbsolutePositioningEnabled(outCmdEnabled);
   }
 
   *outCmdEnabled = false;
@@ -1166,18 +1157,17 @@ nsRemoveStylesCommand::IsCommandEnabled(
 
 NS_IMETHODIMP
 nsRemoveStylesCommand::DoCommand(const char *aCommandName,
                                  nsISupports *refCon)
 {
   nsCOMPtr<nsIHTMLEditor> editor = do_QueryInterface(refCon);
 
   nsresult rv = NS_OK;
-  if (editor)
-  {
+  if (editor) {
     rv = editor->RemoveAllInlineProperties();
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsRemoveStylesCommand::DoCommandParams(const char *aCommandName,
@@ -1214,18 +1204,17 @@ nsIncreaseFontSizeCommand::IsCommandEnab
 
 NS_IMETHODIMP
 nsIncreaseFontSizeCommand::DoCommand(const char *aCommandName,
                                      nsISupports *refCon)
 {
   nsCOMPtr<nsIHTMLEditor> editor = do_QueryInterface(refCon);
 
   nsresult rv = NS_OK;
-  if (editor)
-  {
+  if (editor) {
     rv = editor->IncreaseFontSize();
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsIncreaseFontSizeCommand::DoCommandParams(const char *aCommandName,
@@ -1262,18 +1251,17 @@ nsDecreaseFontSizeCommand::IsCommandEnab
 
 NS_IMETHODIMP
 nsDecreaseFontSizeCommand::DoCommand(const char *aCommandName,
                                      nsISupports *refCon)
 {
   nsCOMPtr<nsIHTMLEditor> editor = do_QueryInterface(refCon);
 
   nsresult rv = NS_OK;
-  if (editor)
-  {
+  if (editor) {
     rv = editor->DecreaseFontSize();
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsDecreaseFontSizeCommand::DoCommandParams(const char *aCommandName,
--- a/editor/composer/nsComposerCommandsUpdater.cpp
+++ b/editor/composer/nsComposerCommandsUpdater.cpp
@@ -29,18 +29,17 @@ nsComposerCommandsUpdater::nsComposerCom
 ,  mSelectionCollapsed(eStateUninitialized)
 ,  mFirstDoOfFirstUndo(true)
 {
 }
 
 nsComposerCommandsUpdater::~nsComposerCommandsUpdater()
 {
   // cancel any outstanding update timer
-  if (mUpdateTimer)
-  {
+  if (mUpdateTimer) {
     mUpdateTimer->Cancel();
   }
 }
 
 NS_IMPL_ISUPPORTS(nsComposerCommandsUpdater, nsISelectionListener,
                   nsIDocumentStateListener, nsITransactionListener, nsITimerCallback)
 
 #if 0
@@ -54,18 +53,17 @@ nsComposerCommandsUpdater::NotifyDocumen
   UpdateOneCommand("obs_documentCreated");
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsComposerCommandsUpdater::NotifyDocumentWillBeDestroyed()
 {
   // cancel any outstanding update timer
-  if (mUpdateTimer)
-  {
+  if (mUpdateTimer) {
     mUpdateTimer->Cancel();
     mUpdateTimer = nullptr;
   }
 
   // We can't call this right now; it is too late in some cases and the window
   // is already partially destructed (e.g. JS objects may be gone).
 #if 0
   // Trigger an nsIObserve notification that the document will be destroyed
@@ -103,20 +101,20 @@ nsComposerCommandsUpdater::WillDo(nsITra
 
 NS_IMETHODIMP
 nsComposerCommandsUpdater::DidDo(nsITransactionManager *aManager,
   nsITransaction *aTransaction, nsresult aDoResult)
 {
   // only need to update if the status of the Undo menu item changes.
   int32_t undoCount;
   aManager->GetNumberOfUndoItems(&undoCount);
-  if (undoCount == 1)
-  {
-    if (mFirstDoOfFirstUndo)
+  if (undoCount == 1) {
+    if (mFirstDoOfFirstUndo) {
       UpdateCommandGroup(NS_LITERAL_STRING("undo"));
+    }
     mFirstDoOfFirstUndo = false;
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsComposerCommandsUpdater::WillUndo(nsITransactionManager *aManager,
@@ -219,50 +217,47 @@ nsComposerCommandsUpdater::Init(nsPIDOMW
   mDOMWindow = do_GetWeakReference(aDOMWindow);
   mDocShell = do_GetWeakReference(aDOMWindow->GetDocShell());
   return NS_OK;
 }
 
 nsresult
 nsComposerCommandsUpdater::PrimeUpdateTimer()
 {
-  if (!mUpdateTimer)
-  {
+  if (!mUpdateTimer) {
     nsresult rv = NS_OK;
     mUpdateTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   const uint32_t kUpdateTimerDelay = 150;
   return mUpdateTimer->InitWithCallback(static_cast<nsITimerCallback*>(this),
                                         kUpdateTimerDelay,
                                         nsITimer::TYPE_ONE_SHOT);
 }
 
 
 void nsComposerCommandsUpdater::TimerCallback()
 {
   // if the selection state has changed, update stuff
   bool isCollapsed = SelectionIsCollapsed();
-  if (static_cast<int8_t>(isCollapsed) != mSelectionCollapsed)
-  {
+  if (static_cast<int8_t>(isCollapsed) != mSelectionCollapsed) {
     UpdateCommandGroup(NS_LITERAL_STRING("select"));
     mSelectionCollapsed = isCollapsed;
   }
 
   // isn't this redundant with the UpdateCommandGroup above?
   // can we just nuke the above call? or create a meta command group?
   UpdateCommandGroup(NS_LITERAL_STRING("style"));
 }
 
 nsresult
 nsComposerCommandsUpdater::UpdateDirtyState(bool aNowDirty)
 {
-  if (mDirtyState != static_cast<int8_t>(aNowDirty))
-  {
+  if (mDirtyState != static_cast<int8_t>(aNowDirty)) {
     UpdateCommandGroup(NS_LITERAL_STRING("save"));
     UpdateCommandGroup(NS_LITERAL_STRING("undo"));
     mDirtyState = aNowDirty;
   }
 
   return NS_OK;
 }
 
@@ -270,24 +265,24 @@ nsresult
 nsComposerCommandsUpdater::UpdateCommandGroup(const nsAString& aCommandGroup)
 {
   nsCOMPtr<nsPICommandUpdater> commandUpdater = GetCommandUpdater();
   NS_ENSURE_TRUE(commandUpdater, NS_ERROR_FAILURE);
 
 
   // This hardcoded list of commands is temporary.
   // This code should use nsIControllerCommandGroup.
-  if (aCommandGroup.EqualsLiteral("undo"))
-  {
+  if (aCommandGroup.EqualsLiteral("undo")) {
     commandUpdater->CommandStatusChanged("cmd_undo");
     commandUpdater->CommandStatusChanged("cmd_redo");
+    return NS_OK;
   }
-  else if (aCommandGroup.EqualsLiteral("select") ||
-           aCommandGroup.EqualsLiteral("style"))
-  {
+
+  if (aCommandGroup.EqualsLiteral("select") ||
+      aCommandGroup.EqualsLiteral("style")) {
     commandUpdater->CommandStatusChanged("cmd_bold");
     commandUpdater->CommandStatusChanged("cmd_italic");
     commandUpdater->CommandStatusChanged("cmd_underline");
     commandUpdater->CommandStatusChanged("cmd_tt");
 
     commandUpdater->CommandStatusChanged("cmd_strikethrough");
     commandUpdater->CommandStatusChanged("cmd_superscript");
     commandUpdater->CommandStatusChanged("cmd_subscript");
@@ -305,23 +300,26 @@ nsComposerCommandsUpdater::UpdateCommand
     commandUpdater->CommandStatusChanged("cmd_increaseFont");
     commandUpdater->CommandStatusChanged("cmd_decreaseFont");
 
     commandUpdater->CommandStatusChanged("cmd_paragraphState");
     commandUpdater->CommandStatusChanged("cmd_fontFace");
     commandUpdater->CommandStatusChanged("cmd_fontColor");
     commandUpdater->CommandStatusChanged("cmd_backgroundColor");
     commandUpdater->CommandStatusChanged("cmd_highlight");
+    return NS_OK;
   }
-  else if (aCommandGroup.EqualsLiteral("save"))
-  {
+
+  if (aCommandGroup.EqualsLiteral("save")) {
     // save commands (most are not in C++)
     commandUpdater->CommandStatusChanged("cmd_setDocumentModified");
     commandUpdater->CommandStatusChanged("cmd_save");
+    return NS_OK;
   }
+
   return NS_OK;
 }
 
 nsresult
 nsComposerCommandsUpdater::UpdateOneCommand(const char *aCommand)
 {
   nsCOMPtr<nsPICommandUpdater> commandUpdater = GetCommandUpdater();
   NS_ENSURE_TRUE(commandUpdater, NS_ERROR_FAILURE);
@@ -332,26 +330,24 @@ nsComposerCommandsUpdater::UpdateOneComm
 }
 
 bool
 nsComposerCommandsUpdater::SelectionIsCollapsed()
 {
   nsCOMPtr<nsPIDOMWindowOuter> domWindow = do_QueryReferent(mDOMWindow);
   NS_ENSURE_TRUE(domWindow, true);
 
-  if (nsCOMPtr<nsISelection> domSelection = domWindow->GetSelection())
-  {
-    bool selectionCollapsed = false;
-    domSelection->GetIsCollapsed(&selectionCollapsed);
-    return selectionCollapsed;
+  nsCOMPtr<nsISelection> domSelection = domWindow->GetSelection();
+  if (NS_WARN_IF(!domSelection)) {
+    return false;
   }
 
-  NS_WARNING("nsComposerCommandsUpdater::SelectionIsCollapsed - no domSelection");
-
-  return false;
+  bool selectionCollapsed = false;
+  domSelection->GetIsCollapsed(&selectionCollapsed);
+  return selectionCollapsed;
 }
 
 already_AddRefed<nsPICommandUpdater>
 nsComposerCommandsUpdater::GetCommandUpdater()
 {
   nsCOMPtr<nsIDocShell> docShell = do_QueryReferent(mDocShell);
   NS_ENSURE_TRUE(docShell, nullptr);
   nsCOMPtr<nsICommandManager> manager = docShell->GetCommandManager();
--- a/editor/composer/nsComposerDocumentCommands.cpp
+++ b/editor/composer/nsComposerDocumentCommands.cpp
@@ -57,18 +57,19 @@ GetPresContextFromEditor(nsIEditor *aEdi
 
 NS_IMETHODIMP
 nsSetDocumentOptionsCommand::IsCommandEnabled(const char * aCommandName,
                                               nsISupports *refCon,
                                               bool *outCmdEnabled)
 {
   NS_ENSURE_ARG_POINTER(outCmdEnabled);
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
-  if (editor)
+  if (editor) {
     return editor->GetIsSelectionEditable(outCmdEnabled);
+  }
 
   *outCmdEnabled = false;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSetDocumentOptionsCommand::DoCommand(const char *aCommandName,
                                        nsISupports *refCon)
@@ -88,27 +89,25 @@ nsSetDocumentOptionsCommand::DoCommandPa
 
   RefPtr<nsPresContext> presContext;
   nsresult rv = GetPresContextFromEditor(editor, getter_AddRefs(presContext));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(presContext, NS_ERROR_FAILURE);
 
   int32_t animationMode;
   rv = aParams->GetLongValue("imageAnimation", &animationMode);
-  if (NS_SUCCEEDED(rv))
-  {
+  if (NS_SUCCEEDED(rv)) {
     // for possible values of animation mode, see:
     // http://lxr.mozilla.org/seamonkey/source/image/public/imgIContainer.idl
     presContext->SetImageAnimationMode(animationMode);
   }
 
   bool allowPlugins;
   rv = aParams->GetBooleanValue("plugins", &allowPlugins);
-  if (NS_SUCCEEDED(rv))
-  {
+  if (NS_SUCCEEDED(rv)) {
     nsCOMPtr<nsIDocShell> docShell(presContext->GetDocShell());
     NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
 
     rv = docShell->SetAllowPlugins(allowPlugins);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return NS_OK;
@@ -135,29 +134,27 @@ nsSetDocumentOptionsCommand::GetCommandS
   // get pres context
   RefPtr<nsPresContext> presContext;
   rv = GetPresContextFromEditor(editor, getter_AddRefs(presContext));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(presContext, NS_ERROR_FAILURE);
 
   int32_t animationMode;
   rv = aParams->GetLongValue("imageAnimation", &animationMode);
-  if (NS_SUCCEEDED(rv))
-  {
+  if (NS_SUCCEEDED(rv)) {
     // for possible values of animation mode, see
     // http://lxr.mozilla.org/seamonkey/source/image/public/imgIContainer.idl
     rv = aParams->SetLongValue("imageAnimation",
                                presContext->ImageAnimationMode());
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   bool allowPlugins = false;
   rv = aParams->GetBooleanValue("plugins", &allowPlugins);
-  if (NS_SUCCEEDED(rv))
-  {
+  if (NS_SUCCEEDED(rv)) {
     nsCOMPtr<nsIDocShell> docShell(presContext->GetDocShell());
     NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
 
     allowPlugins = docShell->PluginsAllowedInCurrentDoc();
 
     rv = aParams->SetBooleanValue("plugins", allowPlugins);
     NS_ENSURE_SUCCESS(rv, rv);
   }
@@ -195,92 +192,88 @@ nsSetDocumentStateCommand::DoCommand(con
 NS_IMETHODIMP
 nsSetDocumentStateCommand::DoCommandParams(const char *aCommandName,
                                            nsICommandParams *aParams,
                                            nsISupports *refCon)
 {
   nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
   NS_ENSURE_TRUE(editor, NS_ERROR_INVALID_ARG);
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentModified"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentModified")) {
     NS_ENSURE_ARG_POINTER(aParams);
 
     bool modified;
     nsresult rv = aParams->GetBooleanValue(STATE_ATTRIBUTE, &modified);
 
     // Should we fail if this param wasn't set?
     // I'm not sure we should be that strict
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (modified)
+    if (modified) {
       return editor->IncrementModificationCount(1);
+    }
 
     return editor->ResetModificationCount();
   }
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentReadOnly"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentReadOnly")) {
     NS_ENSURE_ARG_POINTER(aParams);
     bool isReadOnly;
     nsresult rvRO = aParams->GetBooleanValue(STATE_ATTRIBUTE, &isReadOnly);
     NS_ENSURE_SUCCESS(rvRO, rvRO);
 
     uint32_t flags;
     editor->GetFlags(&flags);
-    if (isReadOnly)
+    if (isReadOnly) {
       flags |= nsIPlaintextEditor::eEditorReadonlyMask;
-    else
+    } else {
       flags &= ~(nsIPlaintextEditor::eEditorReadonlyMask);
+    }
 
     return editor->SetFlags(flags);
   }
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentUseCSS"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentUseCSS")) {
     NS_ENSURE_ARG_POINTER(aParams);
     nsCOMPtr<nsIHTMLEditor> htmleditor = do_QueryInterface(refCon);
     NS_ENSURE_TRUE(htmleditor, NS_ERROR_INVALID_ARG);
 
     bool desireCSS;
     nsresult rvCSS = aParams->GetBooleanValue(STATE_ATTRIBUTE, &desireCSS);
     NS_ENSURE_SUCCESS(rvCSS, rvCSS);
 
     return htmleditor->SetIsCSSEnabled(desireCSS);
   }
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_insertBrOnReturn"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_insertBrOnReturn")) {
     NS_ENSURE_ARG_POINTER(aParams);
     nsCOMPtr<nsIHTMLEditor> htmleditor = do_QueryInterface(refCon);
     NS_ENSURE_TRUE(htmleditor, NS_ERROR_INVALID_ARG);
 
     bool insertBrOnReturn;
     nsresult rvBR = aParams->GetBooleanValue(STATE_ATTRIBUTE,
                                               &insertBrOnReturn);
     NS_ENSURE_SUCCESS(rvBR, rvBR);
 
     return htmleditor->SetReturnInParagraphCreatesNewParagraph(!insertBrOnReturn);
   }
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_enableObjectResizing"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_enableObjectResizing")) {
     NS_ENSURE_ARG_POINTER(aParams);
     nsCOMPtr<nsIHTMLObjectResizer> resizer = do_QueryInterface(refCon);
     NS_ENSURE_TRUE(resizer, NS_ERROR_INVALID_ARG);
 
     bool enabled;
     nsresult rvOR = aParams->GetBooleanValue(STATE_ATTRIBUTE, &enabled);
     NS_ENSURE_SUCCESS(rvOR, rvOR);
 
     return resizer->SetObjectResizingEnabled(enabled);
   }
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_enableInlineTableEditing"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_enableInlineTableEditing")) {
     NS_ENSURE_ARG_POINTER(aParams);
     nsCOMPtr<nsIHTMLInlineTableEditor> editor = do_QueryInterface(refCon);
     NS_ENSURE_TRUE(editor, NS_ERROR_INVALID_ARG);
 
     bool enabled;
     nsresult rvOR = aParams->GetBooleanValue(STATE_ATTRIBUTE, &enabled);
     NS_ENSURE_SUCCESS(rvOR, rvOR);
 
@@ -303,70 +296,64 @@ nsSetDocumentStateCommand::GetCommandSta
   NS_ENSURE_TRUE(editor, NS_ERROR_INVALID_ARG);
 
   // Always get the enabled state
   bool outCmdEnabled = false;
   IsCommandEnabled(aCommandName, refCon, &outCmdEnabled);
   nsresult rv = aParams->SetBooleanValue(STATE_ENABLED, outCmdEnabled);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentModified"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentModified")) {
     bool modified;
     rv = editor->GetDocumentModified(&modified);
     NS_ENSURE_SUCCESS(rv, rv);
 
     return aParams->SetBooleanValue(STATE_ATTRIBUTE, modified);
   }
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentReadOnly"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentReadOnly")) {
     NS_ENSURE_ARG_POINTER(aParams);
 
     uint32_t flags;
     editor->GetFlags(&flags);
     bool isReadOnly = flags & nsIPlaintextEditor::eEditorReadonlyMask;
     return aParams->SetBooleanValue(STATE_ATTRIBUTE, isReadOnly);
   }
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentUseCSS"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_setDocumentUseCSS")) {
     NS_ENSURE_ARG_POINTER(aParams);
     nsCOMPtr<nsIHTMLEditor> htmleditor = do_QueryInterface(refCon);
     NS_ENSURE_TRUE(htmleditor, NS_ERROR_INVALID_ARG);
 
     bool isCSS;
     htmleditor->GetIsCSSEnabled(&isCSS);
     return aParams->SetBooleanValue(STATE_ALL, isCSS);
   }
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_insertBrOnReturn"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_insertBrOnReturn")) {
     NS_ENSURE_ARG_POINTER(aParams);
     nsCOMPtr<nsIHTMLEditor> htmleditor = do_QueryInterface(refCon);
     NS_ENSURE_TRUE(htmleditor, NS_ERROR_INVALID_ARG);
 
     bool createPOnReturn;
     htmleditor->GetReturnInParagraphCreatesNewParagraph(&createPOnReturn);
     return aParams->SetBooleanValue(STATE_ATTRIBUTE, !createPOnReturn);
   }
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_enableObjectResizing"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_enableObjectResizing")) {
     NS_ENSURE_ARG_POINTER(aParams);
     nsCOMPtr<nsIHTMLObjectResizer> resizer = do_QueryInterface(refCon);
     NS_ENSURE_TRUE(resizer, NS_ERROR_INVALID_ARG);
 
     bool enabled;
     resizer->GetObjectResizingEnabled(&enabled);
     return aParams->SetBooleanValue(STATE_ATTRIBUTE, enabled);
   }
 
-  if (!nsCRT::strcmp(aCommandName, "cmd_enableInlineTableEditing"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "cmd_enableInlineTableEditing")) {
     NS_ENSURE_ARG_POINTER(aParams);
     nsCOMPtr<nsIHTMLInlineTableEditor> editor = do_QueryInterface(refCon);
     NS_ENSURE_TRUE(editor, NS_ERROR_INVALID_ARG);
 
     bool enabled;
     editor->GetInlineTableEditingEnabled(&enabled);
     return aParams->SetBooleanValue(STATE_ATTRIBUTE, enabled);
   }
@@ -441,56 +428,53 @@ NS_IMETHODIMP
 nsDocumentStateCommand::GetCommandStateParams(const char *aCommandName,
                                               nsICommandParams *aParams,
                                               nsISupports *refCon)
 {
   NS_ENSURE_ARG_POINTER(aParams);
   NS_ENSURE_ARG_POINTER(aCommandName);
   nsresult rv;
 
-  if (!nsCRT::strcmp(aCommandName, "obs_documentCreated"))
-  {
+  if (!nsCRT::strcmp(aCommandName, "obs_documentCreated")) {
     uint32_t editorStatus = nsIEditingSession::eEditorErrorUnknown;
 
     nsCOMPtr<nsIEditingSession> editingSession = do_QueryInterface(refCon);
-    if (editingSession)
-    {
+    if (editingSession) {
       // refCon is initially set to nsIEditingSession until editor
       //  is successfully created and source doc is loaded
       // Embedder gets error status if this fails
       // If called before startup is finished,
       //    status = eEditorCreationInProgress
       rv = editingSession->GetEditorStatus(&editorStatus);
       NS_ENSURE_SUCCESS(rv, rv);
-    }
-    else
-    {
+    } else {
       // If refCon is an editor, then everything started up OK!
       nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
-      if (editor)
+      if (editor) {
         editorStatus = nsIEditingSession::eEditorOK;
+      }
     }
 
     // Note that if refCon is not-null, but is neither
     // an nsIEditingSession or nsIEditor, we return "eEditorErrorUnknown"
     aParams->SetLongValue(STATE_DATA, editorStatus);
     return NS_OK;
   }
-  else if (!nsCRT::strcmp(aCommandName, "obs_documentLocationChanged"))
-  {
+
+  if (!nsCRT::strcmp(aCommandName, "obs_documentLocationChanged")) {
     nsCOMPtr<nsIEditor> editor = do_QueryInterface(refCon);
-    if (editor)
-    {
-      nsCOMPtr<nsIDOMDocument> domDoc;
-      editor->GetDocument(getter_AddRefs(domDoc));
-      nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
-      NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE);
+    if (!editor) {
+      return NS_OK;
+    }
 
-      nsIURI *uri = doc->GetDocumentURI();
-      NS_ENSURE_TRUE(uri, NS_ERROR_FAILURE);
+    nsCOMPtr<nsIDOMDocument> domDoc;
+    editor->GetDocument(getter_AddRefs(domDoc));
+    nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
+    NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE);
 
-      return aParams->SetISupportsValue(STATE_DATA, (nsISupports*)uri);
-    }
-    return NS_OK;
+    nsIURI *uri = doc->GetDocumentURI();
+    NS_ENSURE_TRUE(uri, NS_ERROR_FAILURE);
+
+    return aParams->SetISupportsValue(STATE_DATA, (nsISupports*)uri);
   }
 
   return NS_ERROR_NOT_IMPLEMENTED;
 }
--- a/editor/composer/nsComposerRegistration.cpp
+++ b/editor/composer/nsComposerRegistration.cpp
@@ -53,23 +53,21 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(nsEditorS
 // Here we are creating the same object with two different contract IDs
 // and then initializing it different.
 // Basically, we need to tell the filter whether it is doing mail or not
 static nsresult
 nsComposeTxtSrvFilterConstructor(nsISupports *aOuter, REFNSIID aIID,
                                  void **aResult, bool aIsForMail)
 {
     *aResult = nullptr;
-    if (nullptr != aOuter)
-    {
+    if (aOuter) {
         return NS_ERROR_NO_AGGREGATION;
     }
     nsComposeTxtSrvFilter * inst = new nsComposeTxtSrvFilter();
-    if (nullptr == inst)
-    {
+    if (!inst) {
         return NS_ERROR_OUT_OF_MEMORY;
     }
     NS_ADDREF(inst);
 	  inst->Init(aIsForMail);
     nsresult rv = inst->QueryInterface(aIID, aResult);
     NS_RELEASE(inst);
     return rv;
 }
--- a/editor/composer/nsEditingSession.cpp
+++ b/editor/composer/nsEditingSession.cpp
@@ -164,25 +164,25 @@ nsEditingSession::MakeWindowEditable(moz
   // such as creation and "dirty flag"
   rv = SetupEditorCommandController("@mozilla.org/editor/editordocstatecontroller;1",
                                     aWindow,
                                     static_cast<nsIEditingSession*>(this),
                                     &mDocStateControllerId);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // aDoAfterUriLoad can be false only when making an existing window editable
-  if (!aDoAfterUriLoad)
-  {
+  if (!aDoAfterUriLoad) {
     rv = SetupEditorOnWindow(aWindow);
 
     // mEditorStatus is set to the error reason
     // Since this is used only when editing an existing page,
     //  it IS ok to destroy current editor
-    if (NS_FAILED(rv))
+    if (NS_FAILED(rv)) {
       TearDownEditorOnWindow(aWindow);
+    }
   }
   return rv;
 }
 
 NS_IMETHODIMP
 nsEditingSession::DisableJSAndPlugins(mozIDOMWindowProxy* aWindow)
 {
   NS_ENSURE_TRUE(aWindow, NS_ERROR_FAILURE);
@@ -275,25 +275,20 @@ const char* const gSupportedTextTypes[] 
   nullptr   // IMPORTANT! Null must be at end
 };
 
 bool
 IsSupportedTextType(const char* aMIMEType)
 {
   NS_ENSURE_TRUE(aMIMEType, false);
 
-  int32_t i = 0;
-  while (gSupportedTextTypes[i])
-  {
-    if (strcmp(gSupportedTextTypes[i], aMIMEType) == 0)
-    {
+  for (size_t i = 0; gSupportedTextTypes[i]; ++i) {
+    if (!strcmp(gSupportedTextTypes[i], aMIMEType)) {
       return true;
     }
-
-    i ++;
   }
 
   return false;
 }
 
 /*---------------------------------------------------------------------------
 
   SetupEditorOnWindow
@@ -312,30 +307,26 @@ nsEditingSession::SetupEditorOnWindow(mo
 
   //MIME CHECKING
   //must get the content type
   // Note: the doc gets this from the network channel during StartPageLoad,
   //    so we don't have to get it from there ourselves
   nsAutoCString mimeCType;
 
   //then lets check the mime type
-  if (nsCOMPtr<nsIDocument> doc = window->GetDoc())
-  {
+  if (nsCOMPtr<nsIDocument> doc = window->GetDoc()) {
     nsAutoString mimeType;
     if (NS_SUCCEEDED(doc->GetContentType(mimeType)))
       AppendUTF16toUTF8(mimeType, mimeCType);
 
-    if (IsSupportedTextType(mimeCType.get()))
-    {
+    if (IsSupportedTextType(mimeCType.get())) {
       mEditorType.AssignLiteral("text");
       mimeCType = "text/plain";
-    }
-    else if (!mimeCType.EqualsLiteral("text/html") &&
-             !mimeCType.EqualsLiteral("application/xhtml+xml"))
-    {
+    } else if (!mimeCType.EqualsLiteral("text/html") &&
+               !mimeCType.EqualsLiteral("application/xhtml+xml")) {
       // Neither an acceptable text or html type.
       mEditorStatus = eEditorErrorCantEditMimeType;
 
       // Turn editor into HTML -- we will load blank page later
       mEditorType.AssignLiteral("html");
       mimeCType.AssignLiteral("text/html");
     }
 
@@ -352,58 +343,51 @@ nsEditingSession::SetupEditorOnWindow(mo
           htmlDocument->SetEditingState(nsIHTMLDocument::eDesignMode);
         }
       }
     }
   }
   bool needHTMLController = false;
 
   const char *classString = "@mozilla.org/editor/htmleditor;1";
-  if (mEditorType.EqualsLiteral("textmail"))
-  {
+  if (mEditorType.EqualsLiteral("textmail")) {
     mEditorFlags = nsIPlaintextEditor::eEditorPlaintextMask |
                    nsIPlaintextEditor::eEditorEnableWrapHackMask |
                    nsIPlaintextEditor::eEditorMailMask;
-  }
-  else if (mEditorType.EqualsLiteral("text"))
-  {
+  } else if (mEditorType.EqualsLiteral("text")) {
     mEditorFlags = nsIPlaintextEditor::eEditorPlaintextMask |
                    nsIPlaintextEditor::eEditorEnableWrapHackMask;
-  }
-  else if (mEditorType.EqualsLiteral("htmlmail"))
-  {
-    if (mimeCType.EqualsLiteral("text/html"))
-    {
+  } else if (mEditorType.EqualsLiteral("htmlmail")) {
+    if (mimeCType.EqualsLiteral("text/html")) {
       needHTMLController = true;
       mEditorFlags = nsIPlaintextEditor::eEditorMailMask;
-    }
-    else //set the flags back to textplain.
+    } else {
+      // Set the flags back to textplain.
       mEditorFlags = nsIPlaintextEditor::eEditorPlaintextMask |
                      nsIPlaintextEditor::eEditorEnableWrapHackMask;
-  }
-  else // Defaulted to html
-  {
+    }
+  } else {
+    // Defaulted to html
     needHTMLController = true;
   }
 
   if (mInteractive) {
     mEditorFlags |= nsIPlaintextEditor::eEditorAllowInteraction;
   }
 
   // make the UI state maintainer
   mStateMaintainer = new nsComposerCommandsUpdater();
 
   // now init the state maintainer
   // This allows notification of error state
   //  even if we don't create an editor
   rv = mStateMaintainer->Init(window);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (mEditorStatus != eEditorCreationInProgress)
-  {
+  if (mEditorStatus != eEditorCreationInProgress) {
     mStateMaintainer->NotifyDocumentCreated();
     return NS_ERROR_FAILURE;
   }
 
   // Create editor and do other things
   //  only if we haven't found some error above,
   nsCOMPtr<nsIDocShell> docShell = window->GetDocShell();
   NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
@@ -435,18 +419,17 @@ nsEditingSession::SetupEditorOnWindow(mo
     NS_ENSURE_SUCCESS(rv, rv);
     mExistingEditor = do_GetWeakReference(editor);
   }
   // set the editor on the docShell. The docShell now owns it.
   rv = docShell->SetEditor(editor);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // setup the HTML editor command controller
-  if (needHTMLController)
-  {
+  if (needHTMLController) {
     // The third controller takes an nsIEditor as the context
     rv = SetupEditorCommandController("@mozilla.org/editor/htmleditorcontroller;1",
                                       aWindow, editor,
                                       &mHTMLCommandControllerId);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Set mimetype on editor
@@ -478,18 +461,19 @@ nsEditingSession::SetupEditorOnWindow(mo
   NS_ENSURE_TRUE(selPriv, NS_ERROR_FAILURE);
 
   rv = selPriv->AddSelectionListener(mStateMaintainer);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // and as a transaction listener
   nsCOMPtr<nsITransactionManager> txnMgr;
   editor->GetTransactionManager(getter_AddRefs(txnMgr));
-  if (txnMgr)
+  if (txnMgr) {
     txnMgr->AddListener(mStateMaintainer);
+  }
 
   // Set context on all controllers to be the editor
   rv = SetEditorOnControllers(aWindow, editor);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Everything went fine!
   mEditorStatus = eEditorOK;
 
@@ -497,32 +481,34 @@ nsEditingSession::SetupEditorOnWindow(mo
   return editor->PostCreate();
 }
 
 // Removes all listeners and controllers from aWindow and aEditor.
 void
 nsEditingSession::RemoveListenersAndControllers(nsPIDOMWindowOuter* aWindow,
                                                 nsIEditor *aEditor)
 {
-  if (!mStateMaintainer || !aEditor)
+  if (!mStateMaintainer || !aEditor) {
     return;
+  }
 
   // Remove all the listeners
   nsCOMPtr<nsISelection> selection;
   aEditor->GetSelection(getter_AddRefs(selection));
   nsCOMPtr<nsISelectionPrivate> selPriv = do_QueryInterface(selection);
   if (selPriv)
     selPriv->RemoveSelectionListener(mStateMaintainer);
 
   aEditor->RemoveDocumentStateListener(mStateMaintainer);
 
   nsCOMPtr<nsITransactionManager> txnMgr;
   aEditor->GetTransactionManager(getter_AddRefs(txnMgr));
-  if (txnMgr)
+  if (txnMgr) {
     txnMgr->RemoveListener(mStateMaintainer);
+  }
 
   // Remove editor controllers from the window now that we're not
   // editing in that window any more.
   RemoveEditorControllers(aWindow);
 }
 
 /*---------------------------------------------------------------------------
 
@@ -537,64 +523,62 @@ nsEditingSession::TearDownEditorOnWindow
     return NS_OK;
   }
 
   NS_ENSURE_TRUE(aWindow, NS_ERROR_NULL_POINTER);
 
   nsresult rv;
 
   // Kill any existing reload timer
-  if (mLoadBlankDocTimer)
-  {
+  if (mLoadBlankDocTimer) {
     mLoadBlankDocTimer->Cancel();
     mLoadBlankDocTimer = nullptr;
   }
 
   mDoneSetup = false;
 
   // Check if we're turning off editing (from contentEditable or designMode).
   auto* window = nsPIDOMWindowOuter::From(aWindow);
 
   nsCOMPtr<nsIDocument> doc = window->GetDoc();
   nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(doc);
   bool stopEditing = htmlDoc && htmlDoc->IsEditingOn();
-  if (stopEditing)
+  if (stopEditing) {
     RemoveWebProgressListener(window);
+  }
 
   nsCOMPtr<nsIDocShell> docShell = window->GetDocShell();
   NS_ENSURE_STATE(docShell);
 
   nsCOMPtr<nsIEditor> editor;
   rv = docShell->GetEditor(getter_AddRefs(editor));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (stopEditing)
+  if (stopEditing) {
     htmlDoc->TearingDownEditor(editor);
+  }
 
-  if (mStateMaintainer && editor)
-  {
+  if (mStateMaintainer && editor) {
     // Null out the editor on the controllers first to prevent their weak
     // references from pointing to a destroyed editor.
     SetEditorOnControllers(aWindow, nullptr);
   }
 
   // Null out the editor on the docShell to trigger PreDestroy which
   // needs to happen before document state listeners are removed below.
   docShell->SetEditor(nullptr);
 
   RemoveListenersAndControllers(window, editor);
 
-  if (stopEditing)
-  {
+  if (stopEditing) {
     // Make things the way they were before we started editing.
     RestoreJSAndPlugins(aWindow);
     RestoreAnimationMode(window);
 
-    if (mMakeWholeDocumentEditable)
-    {
+    if (mMakeWholeDocumentEditable) {
       doc->SetEditableFlag(false);
       nsCOMPtr<nsIHTMLDocument> htmlDocument = do_QueryInterface(doc);
       if (htmlDocument) {
         htmlDocument->SetEditingState(nsIHTMLDocument::eOff);
       }
     }
   }
 
@@ -626,52 +610,48 @@ nsEditingSession::GetEditorForWindow(moz
 NS_IMETHODIMP
 nsEditingSession::OnStateChange(nsIWebProgress *aWebProgress,
                                 nsIRequest *aRequest,
                                 uint32_t aStateFlags, nsresult aStatus)
 {
 
 #ifdef NOISY_DOC_LOADING
   nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
-  if (channel)
-  {
+  if (channel) {
     nsAutoCString contentType;
     channel->GetContentType(contentType);
-    if (!contentType.IsEmpty())
+    if (!contentType.IsEmpty()) {
       printf(" ++++++ MIMETYPE = %s\n", contentType.get());
+    }
   }
 #endif
 
   //
   // A Request has started...
   //
-  if (aStateFlags & nsIWebProgressListener::STATE_START)
-  {
+  if (aStateFlags & nsIWebProgressListener::STATE_START) {
 #ifdef NOISY_DOC_LOADING
-  {
-    nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
-    if (channel)
     {
-      nsCOMPtr<nsIURI> uri;
-      channel->GetURI(getter_AddRefs(uri));
-      if (uri)
-      {
-        nsXPIDLCString spec;
-        uri->GetSpec(spec);
-        printf(" **** STATE_START: CHANNEL URI=%s, flags=%x\n",
-               spec.get(), aStateFlags);
+      nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
+      if (channel) {
+        nsCOMPtr<nsIURI> uri;
+        channel->GetURI(getter_AddRefs(uri));
+        if (uri) {
+          nsXPIDLCString spec;
+          uri->GetSpec(spec);
+          printf(" **** STATE_START: CHANNEL URI=%s, flags=%x\n",
+                 spec.get(), aStateFlags);
+        }
+      } else {
+        printf("    STATE_START: NO CHANNEL flags=%x\n", aStateFlags);
       }
     }
-    else
-      printf("    STATE_START: NO CHANNEL flags=%x\n", aStateFlags);
-  }
 #endif
     // Page level notification...
-    if (aStateFlags & nsIWebProgressListener::STATE_IS_NETWORK)
-    {
+    if (aStateFlags & nsIWebProgressListener::STATE_IS_NETWORK) {
       nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
       StartPageLoad(channel);
 #ifdef NOISY_DOC_LOADING
       printf("STATE_START & STATE_IS_NETWORK flags=%x\n", aStateFlags);
 #endif
     }
 
     // Document level notification...
@@ -679,106 +659,93 @@ nsEditingSession::OnStateChange(nsIWebPr
         !(aStateFlags & nsIWebProgressListener::STATE_RESTORING)) {
 #ifdef NOISY_DOC_LOADING
       printf("STATE_START & STATE_IS_DOCUMENT flags=%x\n", aStateFlags);
 #endif
 
       bool progressIsForTargetDocument =
         IsProgressForTargetDocument(aWebProgress);
 
-      if (progressIsForTargetDocument)
-      {
+      if (progressIsForTargetDocument) {
         nsCOMPtr<mozIDOMWindowProxy> window;
         aWebProgress->GetDOMWindow(getter_AddRefs(window));
 
         auto* piWindow = nsPIDOMWindowOuter::From(window);
         nsCOMPtr<nsIDocument> doc = piWindow->GetDoc();
 
         nsCOMPtr<nsIHTMLDocument> htmlDoc(do_QueryInterface(doc));
 
-        if (htmlDoc && htmlDoc->IsWriting())
-        {
+        if (htmlDoc && htmlDoc->IsWriting()) {
           nsCOMPtr<nsIDOMHTMLDocument> htmlDomDoc = do_QueryInterface(doc);
           nsAutoString designMode;
           htmlDomDoc->GetDesignMode(designMode);
 
-          if (designMode.EqualsLiteral("on"))
-          {
+          if (designMode.EqualsLiteral("on")) {
             // This notification is for data coming in through
             // document.open/write/close(), ignore it.
 
             return NS_OK;
           }
         }
 
         mCanCreateEditor = true;
         StartDocumentLoad(aWebProgress, progressIsForTargetDocument);
       }
     }
   }
   //
   // A Request is being processed
   //
-  else if (aStateFlags & nsIWebProgressListener::STATE_TRANSFERRING)
-  {
-    if (aStateFlags & nsIWebProgressListener::STATE_IS_DOCUMENT)
-    {
+  else if (aStateFlags & nsIWebProgressListener::STATE_TRANSFERRING) {
+    if (aStateFlags & nsIWebProgressListener::STATE_IS_DOCUMENT) {
       // document transfer started
     }
   }
   //
   // Got a redirection
   //
-  else if (aStateFlags & nsIWebProgressListener::STATE_REDIRECTING)
-  {
-    if (aStateFlags & nsIWebProgressListener::STATE_IS_DOCUMENT)
-    {
+  else if (aStateFlags & nsIWebProgressListener::STATE_REDIRECTING) {
+    if (aStateFlags & nsIWebProgressListener::STATE_IS_DOCUMENT) {
       // got a redirect
     }
   }
   //
   // A network or document Request has finished...
   //
-  else if (aStateFlags & nsIWebProgressListener::STATE_STOP)
-  {
-
+  else if (aStateFlags & nsIWebProgressListener::STATE_STOP) {
 #ifdef NOISY_DOC_LOADING
-  {
-    nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
-    if (channel)
     {
-      nsCOMPtr<nsIURI> uri;
-      channel->GetURI(getter_AddRefs(uri));
-      if (uri)
-      {
-        nsXPIDLCString spec;
-        uri->GetSpec(spec);
-        printf(" **** STATE_STOP: CHANNEL URI=%s, flags=%x\n",
-               spec.get(), aStateFlags);
+      nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest));
+      if (channel) {
+        nsCOMPtr<nsIURI> uri;
+        channel->GetURI(getter_AddRefs(uri));
+        if (uri) {
+          nsXPIDLCString spec;
+          uri->GetSpec(spec);
+          printf(" **** STATE_STOP: CHANNEL URI=%s, flags=%x\n",
+                 spec.get(), aStateFlags);
+        }
+      } else {
+        printf("     STATE_STOP: NO CHANNEL  flags=%x\n", aStateFlags);
       }
     }
-    else
-      printf("     STATE_STOP: NO CHANNEL  flags=%x\n", aStateFlags);
-  }
 #endif
 
     // Document level notification...
-    if (aStateFlags & nsIWebProgressListener::STATE_IS_DOCUMENT)
-    {
+    if (aStateFlags & nsIWebProgressListener::STATE_IS_DOCUMENT) {
       nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
       EndDocumentLoad(aWebProgress, channel, aStatus,
                       IsProgressForTargetDocument(aWebProgress));
 #ifdef NOISY_DOC_LOADING
       printf("STATE_STOP & STATE_IS_DOCUMENT flags=%x\n", aStateFlags);
 #endif
     }
 
     // Page level notification...
-    if (aStateFlags & nsIWebProgressListener::STATE_IS_NETWORK)
-    {
+    if (aStateFlags & nsIWebProgressListener::STATE_IS_NETWORK) {
       nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
       (void)EndPageLoad(aWebProgress, channel, aStatus);
 #ifdef NOISY_DOC_LOADING
       printf("STATE_STOP & STATE_IS_NETWORK flags=%x\n", aStateFlags);
 #endif
     }
   }
 
@@ -907,18 +874,19 @@ nsEditingSession::StartDocumentLoad(nsIW
                                     bool aIsToBeMadeEditable)
 {
 #ifdef NOISY_DOC_LOADING
   printf("======= StartDocumentLoad ========\n");
 #endif
 
   NS_ENSURE_ARG_POINTER(aWebProgress);
 
-  if (aIsToBeMadeEditable)
+  if (aIsToBeMadeEditable) {
     mEditorStatus = eEditorCreationInProgress;
+  }
 
   return NS_OK;
 }
 
 /*---------------------------------------------------------------------------
 
   EndDocumentLoad
 
@@ -948,64 +916,59 @@ nsEditingSession::EndDocumentLoad(nsIWeb
 
   // OK, time to make an editor on this document
   nsCOMPtr<mozIDOMWindowProxy> domWindow;
   aWebProgress->GetDOMWindow(getter_AddRefs(domWindow));
   NS_ENSURE_TRUE(domWindow, NS_ERROR_FAILURE);
 
   // Set the error state -- we will create an editor
   // anyway and load empty doc later
-  if (aIsToBeMadeEditable) {
-    if (aStatus == NS_ERROR_FILE_NOT_FOUND)
-      mEditorStatus = eEditorErrorFileNotFound;
+  if (aIsToBeMadeEditable && aStatus == NS_ERROR_FILE_NOT_FOUND) {
+    mEditorStatus = eEditorErrorFileNotFound;
   }
 
   nsIDocShell *docShell = nsPIDOMWindowOuter::From(domWindow)->GetDocShell();
   NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);       // better error handling?
 
   // cancel refresh from meta tags
   // we need to make sure that all pages in editor (whether editable or not)
   // can't refresh contents being edited
   nsCOMPtr<nsIRefreshURI> refreshURI = do_QueryInterface(docShell);
-  if (refreshURI)
+  if (refreshURI) {
     refreshURI->CancelRefreshURITimers();
+  }
 
   nsresult rv = NS_OK;
 
   // did someone set the flag to make this shell editable?
-  if (aIsToBeMadeEditable && mCanCreateEditor)
-  {
+  if (aIsToBeMadeEditable && mCanCreateEditor) {
     bool    makeEditable;
     docShell->GetEditable(&makeEditable);
 
-    if (makeEditable)
-    {
+    if (makeEditable) {
       // To keep pre Gecko 1.9 behavior, setup editor always when
       // mMakeWholeDocumentEditable.
       bool needsSetup = false;
       if (mMakeWholeDocumentEditable) {
         needsSetup = true;
       } else {
         // do we already have an editor here?
         nsCOMPtr<nsIEditor> editor;
         rv = docShell->GetEditor(getter_AddRefs(editor));
         NS_ENSURE_SUCCESS(rv, rv);
 
         needsSetup = !editor;
       }
 
-      if (needsSetup)
-      {
+      if (needsSetup) {
         mCanCreateEditor = false;
         rv = SetupEditorOnWindow(domWindow);
-        if (NS_FAILED(rv))
-        {
+        if (NS_FAILED(rv)) {
           // If we had an error, setup timer to load a blank page later
-          if (mLoadBlankDocTimer)
-          {
+          if (mLoadBlankDocTimer) {
             // Must cancel previous timer?
             mLoadBlankDocTimer->Cancel();
             mLoadBlankDocTimer = nullptr;
           }
 
           mLoadBlankDocTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
           NS_ENSURE_SUCCESS(rv, rv);
 
@@ -1021,22 +984,21 @@ nsEditingSession::EndDocumentLoad(nsIWeb
   return rv;
 }
 
 
 void
 nsEditingSession::TimerCallback(nsITimer* aTimer, void* aClosure)
 {
   nsCOMPtr<nsIDocShell> docShell = do_QueryReferent(static_cast<nsIWeakReference*> (aClosure));
-  if (docShell)
-  {
+  if (docShell) {
     nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(docShell));
-    if (webNav)
-      webNav->LoadURI(u"about:blank",
-                      0, nullptr, nullptr, nullptr);
+    if (webNav) {
+      webNav->LoadURI(u"about:blank", 0, nullptr, nullptr, nullptr);
+    }
   }
 }
 
 /*---------------------------------------------------------------------------
 
   StartPageLoad
 
   Called on start load of the entire page (incl. subframes)
@@ -1067,39 +1029,42 @@ nsEditingSession::EndPageLoad(nsIWebProg
   nsXPIDLCString spec;
   if (NS_SUCCEEDED(aChannel->GetURI(getter_AddRefs(uri)))) {
     uri->GetSpec(spec);
     printf("uri %s\n", spec.get());
   }
 
   nsAutoCString contentType;
   aChannel->GetContentType(contentType);
-  if (!contentType.IsEmpty())
+  if (!contentType.IsEmpty()) {
     printf("   flags = %d, status = %d, MIMETYPE = %s\n",
                mEditorFlags, mEditorStatus, contentType.get());
+  }
 #endif
 
   // Set the error state -- we will create an editor anyway
   // and load empty doc later
-  if (aStatus == NS_ERROR_FILE_NOT_FOUND)
+  if (aStatus == NS_ERROR_FILE_NOT_FOUND) {
     mEditorStatus = eEditorErrorFileNotFound;
+  }
 
   nsCOMPtr<mozIDOMWindowProxy> domWindow;
   aWebProgress->GetDOMWindow(getter_AddRefs(domWindow));
 
   nsIDocShell *docShell =
     domWindow ? nsPIDOMWindowOuter::From(domWindow)->GetDocShell() : nullptr;
   NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
 
   // cancel refresh from meta tags
   // we need to make sure that all pages in editor (whether editable or not)
   // can't refresh contents being edited
   nsCOMPtr<nsIRefreshURI> refreshURI = do_QueryInterface(docShell);
-  if (refreshURI)
+  if (refreshURI) {
     refreshURI->CancelRefreshURITimers();
+  }
 
 #if 0
   // Shouldn't we do this when we want to edit sub-frames?
   return MakeWindowEditable(domWindow, "html", false, mInteractive);
 #else
   return NS_OK;
 #endif
 }
@@ -1108,18 +1073,19 @@ nsEditingSession::EndPageLoad(nsIWebProg
 
   PrepareForEditing
 
   Set up this editing session for one or more editors
 ----------------------------------------------------------------------------*/
 nsresult
 nsEditingSession::PrepareForEditing(nsPIDOMWindowOuter* aWindow)
 {
-  if (mProgressListenerRegistered)
+  if (mProgressListenerRegistered) {
     return NS_OK;
+  }
 
   nsIDocShell *docShell = aWindow ? aWindow->GetDocShell() : nullptr;
 
   // register callback
   nsCOMPtr<nsIWebProgress> webProgress = do_GetInterface(docShell);
   NS_ENSURE_TRUE(webProgress, NS_ERROR_FAILURE);
 
   nsresult rv =
@@ -1156,18 +1122,17 @@ nsEditingSession::SetupEditorCommandCont
   MOZ_ASSERT(piWindow);
 
   nsCOMPtr<nsIControllers> controllers;
   nsresult rv = piWindow->GetControllers(getter_AddRefs(controllers));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // We only have to create each singleton controller once
   // We know this has happened once we have a controllerId value
-  if (!*aControllerId)
-  {
+  if (!*aControllerId) {
     nsCOMPtr<nsIController> controller;
     controller = do_CreateInstance(aControllerClassName, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // We must insert at head of the list to be sure our
     //   controller is found before other implementations
     //   (e.g., not-implemented versions by browser)
     rv = controllers->InsertControllerAt(0, controller);
@@ -1196,33 +1161,32 @@ nsEditingSession::SetEditorOnControllers
 
   auto* piWindow = nsPIDOMWindowOuter::From(aWindow);
 
   nsCOMPtr<nsIControllers> controllers;
   nsresult rv = piWindow->GetControllers(getter_AddRefs(controllers));
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsISupports> editorAsISupports = do_QueryInterface(aEditor);
-  if (mBaseCommandControllerId)
-  {
+  if (mBaseCommandControllerId) {
     rv = SetContextOnControllerById(controllers, editorAsISupports,
                                     mBaseCommandControllerId);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  if (mDocStateControllerId)
-  {
+  if (mDocStateControllerId) {
     rv = SetContextOnControllerById(controllers, editorAsISupports,
                                     mDocStateControllerId);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  if (mHTMLCommandControllerId)
+  if (mHTMLCommandControllerId) {
     rv = SetContextOnControllerById(controllers, editorAsISupports,
                                     mHTMLCommandControllerId);
+  }
 
   return rv;
 }
 
 nsresult
 nsEditingSession::SetContextOnControllerById(nsIControllers* aControllers,
                                              nsISupports* aContext,
                                              uint32_t aID)
@@ -1247,88 +1211,86 @@ nsEditingSession::RemoveEditorController
   // Remove editor controllers from the aWindow, call when we're
   // tearing down/detaching editor.
 
   nsCOMPtr<nsIControllers> controllers;
   if (aWindow) {
     aWindow->GetControllers(getter_AddRefs(controllers));
   }
 
-  if (controllers)
-  {
+  if (controllers) {
     nsCOMPtr<nsIController> controller;
-    if (mBaseCommandControllerId)
-    {
+    if (mBaseCommandControllerId) {
       controllers->GetControllerById(mBaseCommandControllerId,
                                      getter_AddRefs(controller));
-      if (controller)
+      if (controller) {
         controllers->RemoveController(controller);
+      }
     }
 
-    if (mDocStateControllerId)
-    {
+    if (mDocStateControllerId) {
       controllers->GetControllerById(mDocStateControllerId,
                                      getter_AddRefs(controller));
-      if (controller)
+      if (controller) {
         controllers->RemoveController(controller);
+      }
     }
 
-    if (mHTMLCommandControllerId)
-    {
+    if (mHTMLCommandControllerId) {
       controllers->GetControllerById(mHTMLCommandControllerId,
                                      getter_AddRefs(controller));
-      if (controller)
+      if (controller) {
         controllers->RemoveController(controller);
+      }
     }
   }
 
   // Clear IDs to trigger creation of new controllers.
   mBaseCommandControllerId = 0;
   mDocStateControllerId = 0;
   mHTMLCommandControllerId = 0;
 }
 
 void
 nsEditingSession::RemoveWebProgressListener(nsPIDOMWindowOuter* aWindow)
 {
   nsIDocShell *docShell = aWindow ? aWindow->GetDocShell() : nullptr;
   nsCOMPtr<nsIWebProgress> webProgress = do_GetInterface(docShell);
-  if (webProgress)
-  {
+  if (webProgress) {
     webProgress->RemoveProgressListener(this);
     mProgressListenerRegistered = false;
   }
 }
 
 void
 nsEditingSession::RestoreAnimationMode(nsPIDOMWindowOuter* aWindow)
 {
-  if (!mInteractive)
-  {
-    nsCOMPtr<nsIDocShell> docShell = aWindow ? aWindow->GetDocShell() : nullptr;
-    NS_ENSURE_TRUE(docShell, );
-    nsCOMPtr<nsIPresShell> presShell = docShell->GetPresShell();
-    NS_ENSURE_TRUE(presShell, );
-    nsPresContext* presContext = presShell->GetPresContext();
-    NS_ENSURE_TRUE(presContext, );
+  if (mInteractive) {
+    return;
+  }
 
-    presContext->SetImageAnimationMode(mImageAnimationMode);
-  }
+  nsCOMPtr<nsIDocShell> docShell = aWindow ? aWindow->GetDocShell() : nullptr;
+  NS_ENSURE_TRUE_VOID(docShell);
+  nsCOMPtr<nsIPresShell> presShell = docShell->GetPresShell();
+  NS_ENSURE_TRUE_VOID(presShell);
+  nsPresContext* presContext = presShell->GetPresContext();
+  NS_ENSURE_TRUE_VOID(presContext);
+
+  presContext->SetImageAnimationMode(mImageAnimationMode);
 }
 
 nsresult
 nsEditingSession::DetachFromWindow(mozIDOMWindowProxy* aWindow)
 {
   NS_ENSURE_TRUE(mDoneSetup, NS_OK);
 
   NS_ASSERTION(mStateMaintainer, "mStateMaintainer should exist.");
 
   // Kill any existing reload timer
-  if (mLoadBlankDocTimer)
-  {
+  if (mLoadBlankDocTimer) {
     mLoadBlankDocTimer->Cancel();
     mLoadBlankDocTimer = nullptr;
   }
 
   auto* window = nsPIDOMWindowOuter::From(aWindow);
 
   // Remove controllers, webprogress listener, and otherwise
   // make things the way they were before we started editing.
@@ -1357,18 +1319,17 @@ nsEditingSession::ReattachToWindow(mozID
   nsresult rv;
 
   auto* window = nsPIDOMWindowOuter::From(aWindow);
   nsIDocShell *docShell = window->GetDocShell();
   NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
   mDocShell = do_GetWeakReference(docShell);
 
   // Disable plugins.
-  if (!mInteractive)
-  {
+  if (!mInteractive) {
     rv = DisableJSAndPlugins(aWindow);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Tells embedder that startup is in progress.
   mEditorStatus = eEditorCreationInProgress;
 
   // Adds back web progress listener.
@@ -1383,26 +1344,26 @@ nsEditingSession::ReattachToWindow(mozID
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = SetupEditorCommandController("@mozilla.org/editor/editordocstatecontroller;1",
                                     aWindow,
                                     static_cast<nsIEditingSession*>(this),
                                     &mDocStateControllerId);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (mStateMaintainer)
+  if (mStateMaintainer) {
     mStateMaintainer->Init(window);
+  }
 
   // Get editor
   nsCOMPtr<nsIEditor> editor;
   rv = GetEditorForWindow(aWindow, getter_AddRefs(editor));
   NS_ENSURE_TRUE(editor, NS_ERROR_FAILURE);
 
-  if (!mInteractive)
-  {
+  if (!mInteractive) {
     // Disable animation of images in this document:
     nsCOMPtr<nsIPresShell> presShell = docShell->GetPresShell();
     NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
     nsPresContext* presContext = presShell->GetPresContext();
     NS_ENSURE_TRUE(presContext, NS_ERROR_FAILURE);
 
     mImageAnimationMode = presContext->ImageAnimationMode();
     presContext->SetImageAnimationMode(imgIContainer::kDontAnimMode);
--- a/editor/composer/nsEditorSpellCheck.cpp
+++ b/editor/composer/nsEditorSpellCheck.cpp
@@ -425,18 +425,18 @@ nsEditorSpellCheck::GetNextMisspelledWor
   *aNextMisspelledWord = ToNewUnicode(nextMisspelledWord);
   return rv;
 }
 
 NS_IMETHODIMP
 nsEditorSpellCheck::GetSuggestedWord(char16_t **aSuggestedWord)
 {
   nsAutoString word;
-  if ( mSuggestedWordIndex < int32_t(mSuggestedWordList.Length()))
-  {
+  // XXX This is buggy if mSuggestedWordList.Length() is over INT32_MAX.
+  if (mSuggestedWordIndex < static_cast<int32_t>(mSuggestedWordList.Length())) {
     *aSuggestedWord = ToNewUnicode(mSuggestedWordList[mSuggestedWordIndex]);
     mSuggestedWordIndex++;
   } else {
     // A blank string signals that there are no more strings
     *aSuggestedWord = ToNewUnicode(EmptyString());
   }
   return NS_OK;
 }
@@ -490,18 +490,18 @@ nsEditorSpellCheck::GetPersonalDictionar
   mDictionaryList.Clear();
   mDictionaryIndex = 0;
   return mSpellChecker->GetPersonalDictionary(&mDictionaryList);
 }
 
 NS_IMETHODIMP
 nsEditorSpellCheck::GetPersonalDictionaryWord(char16_t **aDictionaryWord)
 {
-  if ( mDictionaryIndex < int32_t( mDictionaryList.Length()))
-  {
+  // XXX This is buggy if mDictionaryList.Length() is over INT32_MAX.
+  if (mDictionaryIndex < static_cast<int32_t>(mDictionaryList.Length())) {
     *aDictionaryWord = ToNewUnicode(mDictionaryList[mDictionaryIndex]);
     mDictionaryIndex++;
   } else {
     // A blank string signals that there are no more strings
     *aDictionaryWord = ToNewUnicode(EmptyString());
   }
 
   return NS_OK;
@@ -536,18 +536,17 @@ nsEditorSpellCheck::GetDictionaryList(ch
   nsTArray<nsString> dictList;
 
   nsresult rv = mSpellChecker->GetDictionaryList(&dictList);
 
   NS_ENSURE_SUCCESS(rv, rv);
 
   char16_t **tmpPtr = 0;
 
-  if (dictList.Length() < 1)
-  {
+  if (dictList.IsEmpty()) {
     // If there are no dictionaries, return an array containing
     // one element and a count of one.
 
     tmpPtr = (char16_t **)moz_xmalloc(sizeof(char16_t *));
 
     NS_ENSURE_TRUE(tmpPtr, NS_ERROR_OUT_OF_MEMORY);
 
     *tmpPtr          = 0;
@@ -559,20 +558,17 @@ nsEditorSpellCheck::GetDictionaryList(ch
 
   tmpPtr = (char16_t **)moz_xmalloc(sizeof(char16_t *) * dictList.Length());
 
   NS_ENSURE_TRUE(tmpPtr, NS_ERROR_OUT_OF_MEMORY);
 
   *aDictionaryList = tmpPtr;
   *aCount          = dictList.Length();
 
-  uint32_t i;
-
-  for (i = 0; i < *aCount; i++)
-  {
+  for (uint32_t i = 0; i < *aCount; i++) {
     tmpPtr[i] = ToNewUnicode(dictList[i]);
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsEditorSpellCheck::GetCurrentDictionary(nsAString& aDictionary)
@@ -940,27 +936,28 @@ nsEditorSpellCheck::DictionaryFetched(Di
   if (NS_FAILED(rv)) {
   // Still no success.
 
   // Priority 5:
   // If we have a current dictionary, don't try anything else.
     nsAutoString currentDictionary;
     rv2 = GetCurrentDictionary(currentDictionary);
 #ifdef DEBUG_DICT
-    if (NS_SUCCEEDED(rv2))
+    if (NS_SUCCEEDED(rv2)) {
         printf("***** Retrieved current dict |%s|\n",
                NS_ConvertUTF16toUTF8(currentDictionary).get());
+    }
 #endif
 
     if (NS_FAILED(rv2) || currentDictionary.IsEmpty()) {
       // Priority 6:
       // Try to get current dictionary from environment variable LANG.
       // LANG = language[_territory][.charset]
       char* env_lang = getenv("LANG");
-      if (env_lang != nullptr) {
+      if (env_lang) {
         nsString lang = NS_ConvertUTF8toUTF16(env_lang);
         // Strip trailing charset, if there is any.
         int32_t dot_pos = lang.FindChar('.');
         if (dot_pos != -1) {
           lang = Substring(lang, 0, dot_pos);
         }
 
         int32_t underScore = lang.FindChar('_');
@@ -973,28 +970,27 @@ nsEditorSpellCheck::DictionaryFetched(Di
           nsAutoString lang2;
           lang2.Assign(lang);
           rv = TryDictionary(lang2, dictList, DICT_COMPARE_CASE_INSENSITIVE);
         }
       }
 
       // Priority 7:
       // If it does not work, pick the first one.
-      if (NS_FAILED(rv)) {
-        if (dictList.Length() > 0) {
-          nsAutoString firstInList;
-          firstInList.Assign(dictList[0]);
-          rv = TryDictionary(firstInList, dictList, DICT_NORMAL_COMPARE);
+      if (NS_FAILED(rv) && !dictList.IsEmpty()) {
+        nsAutoString firstInList;
+        firstInList.Assign(dictList[0]);
+        rv = TryDictionary(firstInList, dictList, DICT_NORMAL_COMPARE);
 #ifdef DEBUG_DICT
-          printf("***** Trying first of list |%s|\n",
-                 NS_ConvertUTF16toUTF8(dictList[0]).get());
-          if (NS_SUCCEEDED(rv))
-            printf ("***** Setting worked.\n");
+        printf("***** Trying first of list |%s|\n",
+               NS_ConvertUTF16toUTF8(dictList[0]).get());
+        if (NS_SUCCEEDED(rv)) {
+          printf ("***** Setting worked.\n");
+        }
 #endif
-        }
       }
     }
   }
 
   // If an error was thrown while setting the dictionary, just
   // fail silently so that the spellchecker dialog is allowed to come
   // up. The user can manually reset the language to their choice on
   // the dialog if it is wrong.
--- a/editor/libeditor/EditAggregateTransaction.cpp
+++ b/editor/libeditor/EditAggregateTransaction.cpp
@@ -29,83 +29,89 @@ NS_IMPL_ADDREF_INHERITED(EditAggregateTr
 NS_IMPL_RELEASE_INHERITED(EditAggregateTransaction, EditTransactionBase)
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(EditAggregateTransaction)
 NS_INTERFACE_MAP_END_INHERITING(EditTransactionBase)
 
 NS_IMETHODIMP
 EditAggregateTransaction::DoTransaction()
 {
   nsresult result=NS_OK;  // it's legal (but not very useful) to have an empty child list
-  for (uint32_t i = 0, length = mChildren.Length(); i < length; ++i)
-  {
+  for (uint32_t i = 0, length = mChildren.Length(); i < length; ++i) {
     nsITransaction *txn = mChildren[i];
-    if (!txn) { return NS_ERROR_NULL_POINTER; }
+    if (!txn) {
+      return NS_ERROR_NULL_POINTER;
+    }
     result = txn->DoTransaction();
-    if (NS_FAILED(result))
+    if (NS_FAILED(result)) {
       break;
+    }
   }
   return result;
 }
 
 NS_IMETHODIMP
 EditAggregateTransaction::UndoTransaction()
 {
   nsresult result=NS_OK;  // it's legal (but not very useful) to have an empty child list
   // undo goes through children backwards
-  for (uint32_t i = mChildren.Length(); i-- != 0; )
-  {
+  for (uint32_t i = mChildren.Length(); i--; ) {
     nsITransaction *txn = mChildren[i];
-    if (!txn) { return NS_ERROR_NULL_POINTER; }
+    if (!txn) {
+      return NS_ERROR_NULL_POINTER;
+    }
     result = txn->UndoTransaction();
-    if (NS_FAILED(result))
+    if (NS_FAILED(result)) {
       break;
+    }
   }
   return result;
 }
 
 NS_IMETHODIMP
 EditAggregateTransaction::RedoTransaction()
 {
   nsresult result=NS_OK;  // it's legal (but not very useful) to have an empty child list
-  for (uint32_t i = 0, length = mChildren.Length(); i < length; ++i)
-  {
+  for (uint32_t i = 0, length = mChildren.Length(); i < length; ++i) {
     nsITransaction *txn = mChildren[i];
-    if (!txn) { return NS_ERROR_NULL_POINTER; }
+    if (!txn) {
+      return NS_ERROR_NULL_POINTER;
+    }
     result = txn->RedoTransaction();
-    if (NS_FAILED(result))
+    if (NS_FAILED(result)) {
       break;
+    }
   }
   return result;
 }
 
 NS_IMETHODIMP
 EditAggregateTransaction::Merge(nsITransaction* aTransaction,
                                 bool* aDidMerge)
 {
-  nsresult result=NS_OK;  // it's legal (but not very useful) to have an empty child list
-  if (aDidMerge)
+  if (aDidMerge) {
     *aDidMerge = false;
+  }
+  if (mChildren.IsEmpty()) {
+    return NS_OK;
+  }
   // FIXME: Is this really intended not to loop?  It looks like the code
   // that used to be here sort of intended to loop, but didn't.
-  if (mChildren.Length() > 0)
-  {
-    nsITransaction *txn = mChildren[0];
-    if (!txn) { return NS_ERROR_NULL_POINTER; }
-    result = txn->Merge(aTransaction, aDidMerge);
+  nsITransaction *txn = mChildren[0];
+  if (!txn) {
+    return NS_ERROR_NULL_POINTER;
   }
-  return result;
+  return txn->Merge(aTransaction, aDidMerge);
 }
 
 NS_IMETHODIMP
 EditAggregateTransaction::GetTxnDescription(nsAString& aString)
 {
   aString.AssignLiteral("EditAggregateTransaction: ");
 
-  if (mName)
-  {
+  if (mName) {
     nsAutoString name;
     mName->ToString(name);
     aString += name;
   }
 
   return NS_OK;
 }
 
@@ -123,18 +129,17 @@ EditAggregateTransaction::AppendChild(Ed
 
   *slot = aTransaction;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EditAggregateTransaction::GetName(nsIAtom** aName)
 {
-  if (aName && mName)
-  {
+  if (aName && mName) {
     *aName = mName;
     NS_ADDREF(*aName);
     return NS_OK;
   }
   return NS_ERROR_NULL_POINTER;
 }
 
 } // namespace mozilla
--- a/editor/libeditor/EditorBase.cpp
+++ b/editor/libeditor/EditorBase.cpp
@@ -389,17 +389,17 @@ EditorBase::GetDesiredSpellCheckState()
   // Check user override on this element
   if (mSpellcheckCheckboxState != eTriUnset) {
     return (mSpellcheckCheckboxState == eTriTrue);
   }
 
   // Check user preferences
   int32_t spellcheckLevel = Preferences::GetInt("layout.spellcheckDefault", 1);
 
-  if (spellcheckLevel == 0) {
+  if (!spellcheckLevel) {
     return false;                    // Spellchecking forced off globally
   }
 
   if (!CanEnableSpellCheck()) {
     return false;
   }
 
   nsCOMPtr<nsIPresShell> presShell = GetPresShell();
@@ -912,18 +912,17 @@ EditorBase::EndTransaction()
 // while the batch is open.  The advantage of this is that
 // placeholder transactions can later merge, if needed.  Merging
 // is unavailable between transaction manager batches.
 
 NS_IMETHODIMP
 EditorBase::BeginPlaceHolderTransaction(nsIAtom* aName)
 {
   NS_PRECONDITION(mPlaceHolderBatch >= 0, "negative placeholder batch count!");
-  if (!mPlaceHolderBatch)
-  {
+  if (!mPlaceHolderBatch) {
     NotifyEditorObservers(eNotifyEditorObserversOfBefore);
     // time to turn on the batch
     BeginUpdateViewBatch();
     mPlaceHolderTxn = nullptr;
     mPlaceHolderName = aName;
     RefPtr<Selection> selection = GetSelection();
     if (selection) {
       mSelState = new SelectionState();
@@ -934,18 +933,17 @@ EditorBase::BeginPlaceHolderTransaction(
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EditorBase::EndPlaceHolderTransaction()
 {
   NS_PRECONDITION(mPlaceHolderBatch > 0, "zero or negative placeholder batch count when ending batch!");
-  if (mPlaceHolderBatch == 1)
-  {
+  if (mPlaceHolderBatch == 1) {
     RefPtr<Selection> selection = GetSelection();
 
     // By making the assumption that no reflow happens during the calls
     // to EndUpdateViewBatch and ScrollSelectionIntoView, we are able to
     // allow the selection to cache a frame offset which is used by the
     // caret drawing code. We only enable this cache here; at other times,
     // we have no way to know whether reflow invalidates it
     // See bugs 35296 and 199412.
@@ -954,49 +952,46 @@ EditorBase::EndPlaceHolderTransaction()
     }
 
     {
       // Hide the caret here to avoid hiding it twice, once in EndUpdateViewBatch
       // and once in ScrollSelectionIntoView.
       RefPtr<nsCaret> caret;
       nsCOMPtr<nsIPresShell> presShell = GetPresShell();
 
-      if (presShell)
+      if (presShell) {
         caret = presShell->GetCaret();
+      }
 
       // time to turn off the batch
       EndUpdateViewBatch();
       // make sure selection is in view
 
       // After ScrollSelectionIntoView(), the pending notifications might be
       // flushed and PresShell/PresContext/Frames may be dead. See bug 418470.
       ScrollSelectionIntoView(false);
     }
 
     // cached for frame offset are Not available now
     if (selection) {
       selection->SetCanCacheFrameOffset(false);
     }
 
-    if (mSelState)
-    {
+    if (mSelState) {
       // we saved the selection state, but never got to hand it to placeholder
       // (else we ould have nulled out this pointer), so destroy it to prevent leaks.
       delete mSelState;
       mSelState = nullptr;
     }
-    if (mPlaceHolderTxn)  // we might have never made a placeholder if no action took place
-    {
+    // We might have never made a placeholder if no action took place.
+    if (mPlaceHolderTxn) {
       nsCOMPtr<nsIAbsorbingTransaction> plcTxn = do_QueryReferent(mPlaceHolderTxn);
-      if (plcTxn)
-      {
+      if (plcTxn) {
         plcTxn->EndPlaceHolderBatch();
-      }
-      else
-      {
+      } else {
         // in the future we will check to make sure undo is off here,
         // since that is the only known case where the placeholdertxn would disappear on us.
         // For now just removing the assert.
       }
       // notify editor observers of action but if composing, it's done by
       // compositionchange event handler.
       if (!mComposition) {
         NotifyEditorObservers(eNotifyEditorObserversOfEnd);
@@ -1037,28 +1032,32 @@ EditorBase::GetDocumentIsEmpty(bool* aDo
   return NS_OK;
 }
 
 // XXX: The rule system should tell us which node to select all on (ie, the
 //      root, or the body)
 NS_IMETHODIMP
 EditorBase::SelectAll()
 {
-  if (!mDocWeak) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mDocWeak) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
   ForceCompositionEnd();
 
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_NOT_INITIALIZED);
   return SelectEntireDocument(selection);
 }
 
 NS_IMETHODIMP
 EditorBase::BeginningOfDocument()
 {
-  if (!mDocWeak) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mDocWeak) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
 
   // get the selection
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_NOT_INITIALIZED);
 
   // get the root element
   dom::Element* rootElement = GetRoot();
   NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER);
@@ -1290,18 +1289,19 @@ EditorBase::GetInlineSpellChecker(bool a
   nsresult rv;
   if (!mInlineSpellChecker && autoCreate) {
     mInlineSpellChecker = do_CreateInstance(MOZ_INLINESPELLCHECKER_CONTRACTID, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   if (mInlineSpellChecker) {
     rv = mInlineSpellChecker->Init(this);
-    if (NS_FAILED(rv))
+    if (NS_FAILED(rv)) {
       mInlineSpellChecker = nullptr;
+    }
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   NS_IF_ADDREF(*aInlineSpellChecker = mInlineSpellChecker);
 
   return NS_OK;
 }
 
@@ -1947,18 +1947,19 @@ EditorBase::DebugDumpContent()
 {
 #ifdef DEBUG
   nsCOMPtr<nsIDOMHTMLDocument> doc = do_QueryReferent(mDocWeak);
   NS_ENSURE_TRUE(doc, NS_ERROR_NOT_INITIALIZED);
 
   nsCOMPtr<nsIDOMHTMLElement>bodyElem;
   doc->GetBody(getter_AddRefs(bodyElem));
   nsCOMPtr<nsIContent> content = do_QueryInterface(bodyElem);
-  if (content)
+  if (content) {
     content->List();
+  }
 #endif
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EditorBase::DebugUnitTests(int32_t* outNumTests,
                            int32_t* outNumTestsFailed)
 {
@@ -1979,17 +1980,19 @@ EditorBase::PreserveSelectionAcrossActio
 {
   mSavedSel.SaveSelection(aSel);
   mRangeUpdater.RegisterSelectionState(mSavedSel);
 }
 
 nsresult
 EditorBase::RestorePreservedSelection(Selection* aSel)
 {
-  if (mSavedSel.IsEmpty()) return NS_ERROR_FAILURE;
+  if (mSavedSel.IsEmpty()) {
+    return NS_ERROR_FAILURE;
+  }
   mSavedSel.RestoreSelection(aSel);
   StopPreservingSelection();
   return NS_OK;
 }
 
 void
 EditorBase::StopPreservingSelection()
 {
@@ -2053,20 +2056,21 @@ EditorBase::EndIMEComposition()
 
   // notify editor observers of action
   NotifyEditorObservers(eNotifyEditorObserversOfEnd);
 }
 
 NS_IMETHODIMP
 EditorBase::GetPhonetic(nsAString& aPhonetic)
 {
-  if (mPhonetic)
+  if (mPhonetic) {
     aPhonetic = *mPhonetic;
-  else
+  } else {
     aPhonetic.Truncate(0);
+  }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EditorBase::ForceCompositionEnd()
 {
   nsCOMPtr<nsIPresShell> ps = GetPresShell();
@@ -2176,20 +2180,21 @@ EditorBase::CloneAttribute(const nsAStri
 
   nsAutoString attrValue;
   bool isAttrSet;
   nsresult rv = GetAttributeValue(sourceElement,
                                   aAttribute,
                                   attrValue,
                                   &isAttrSet);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (isAttrSet)
+  if (isAttrSet) {
     rv = SetAttribute(destElement, aAttribute, attrValue);
-  else
+  } else {
     rv = RemoveAttribute(destElement, aAttribute);
+  }
 
   return rv;
 }
 
 /**
  * @param aDest     Must be a DOM element.
  * @param aSource   Must be a DOM element.
  */
@@ -2251,22 +2256,22 @@ EditorBase::CloneAttributes(Element* aDe
     }
   }
 }
 
 NS_IMETHODIMP
 EditorBase::ScrollSelectionIntoView(bool aScrollToAnchor)
 {
   nsCOMPtr<nsISelectionController> selCon;
-  if (NS_SUCCEEDED(GetSelectionController(getter_AddRefs(selCon))) && selCon)
-  {
+  if (NS_SUCCEEDED(GetSelectionController(getter_AddRefs(selCon))) && selCon) {
     int16_t region = nsISelectionController::SELECTION_FOCUS_REGION;
 
-    if (aScrollToAnchor)
+    if (aScrollToAnchor) {
       region = nsISelectionController::SELECTION_ANCHOR_REGION;
+    }
 
     selCon->ScrollSelectionIntoView(nsISelectionController::SELECTION_NORMAL,
       region, nsISelectionController::SCROLL_OVERFLOW_HIDDEN);
   }
 
   return NS_OK;
 }
 
@@ -2299,17 +2304,17 @@ EditorBase::FindBetterInsertionPoint(nsC
   nsCOMPtr<nsINode> node = aNode;
   int32_t offset = aOffset;
 
   nsCOMPtr<nsINode> root = GetRoot();
   if (aNode == root) {
     // In some cases, aNode is the anonymous DIV, and offset is 0.  To avoid
     // injecting unneeded text nodes, we first look to see if we have one
     // available.  In that case, we'll just adjust node and offset accordingly.
-    if (offset == 0 && node->HasChildren() &&
+    if (!offset && node->HasChildren() &&
         node->GetFirstChild()->IsNodeOfType(nsINode::eTEXT)) {
       aNode = node->GetFirstChild();
       aOffset = 0;
       return;
     }
 
     // In some other cases, aNode is the anonymous DIV, and offset points to the
     // terminating mozBR.  In that case, we'll adjust aInOutNode and
@@ -2511,20 +2516,24 @@ EditorBase::InsertTextIntoTextNodeImpl(c
   }
 
   return rv;
 }
 
 nsresult
 EditorBase::SelectEntireDocument(Selection* aSelection)
 {
-  if (!aSelection) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(GetRoot());
-  if (!rootElement) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!rootElement) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
 
   return aSelection->SelectAllChildren(rootElement);
 }
 
 nsINode*
 EditorBase::GetFirstEditableNode(nsINode* aRoot)
 {
   MOZ_ASSERT(aRoot);
@@ -2545,53 +2554,54 @@ EditorBase::NotifyDocumentListeners(
     // Maybe there just aren't any.
     return NS_OK;
   }
 
   nsTArray<OwningNonNull<nsIDocumentStateListener>>
     listeners(mDocStateListeners);
   nsresult rv = NS_OK;
 
-  switch (aNotificationType)
-  {
+  switch (aNotificationType) {
     case eDocumentCreated:
       for (auto& listener : listeners) {
         rv = listener->NotifyDocumentCreated();
-        if (NS_FAILED(rv))
+        if (NS_FAILED(rv)) {
           break;
+        }
       }
       break;
 
     case eDocumentToBeDestroyed:
       for (auto& listener : listeners) {
         rv = listener->NotifyDocumentWillBeDestroyed();
-        if (NS_FAILED(rv))
+        if (NS_FAILED(rv)) {
           break;
-      }
-      break;
-
-    case eDocumentStateChanged:
-      {
-        bool docIsDirty;
-        rv = GetDocumentModified(&docIsDirty);
-        NS_ENSURE_SUCCESS(rv, rv);
-
-        if (static_cast<int8_t>(docIsDirty) == mDocDirtyState)
-          return NS_OK;
-
-        mDocDirtyState = docIsDirty;
-
-        for (auto& listener : listeners) {
-          rv = listener->NotifyDocumentStateChanged(mDocDirtyState);
-          if (NS_FAILED(rv))
-            break;
         }
       }
       break;
 
+    case eDocumentStateChanged: {
+      bool docIsDirty;
+      rv = GetDocumentModified(&docIsDirty);
+      NS_ENSURE_SUCCESS(rv, rv);
+
+      if (static_cast<int8_t>(docIsDirty) == mDocDirtyState) {
+        return NS_OK;
+      }
+
+      mDocDirtyState = docIsDirty;
+
+      for (auto& listener : listeners) {
+        rv = listener->NotifyDocumentStateChanged(mDocDirtyState);
+        if (NS_FAILED(rv)) {
+          break;
+        }
+      }
+      break;
+    }
     default:
       NS_NOTREACHED("Unknown notification");
   }
 
   return rv;
 }
 
 already_AddRefed<InsertTextTransaction>
@@ -2890,17 +2900,17 @@ EditorBase::JoinNodesImpl(nsINode* aNode
     nsCOMPtr<nsINodeList> childNodes = aNodeToJoin->ChildNodes();
     MOZ_ASSERT(childNodes);
 
     // Remember the first child in aNodeToKeep, we'll insert all the children of aNodeToJoin in front of it
     // GetFirstChild returns nullptr firstNode if aNodeToKeep has no children, that's OK.
     nsCOMPtr<nsIContent> firstNode = aNodeToKeep->GetFirstChild();
 
     // Have to go through the list backwards to keep deletes from interfering with iteration.
-    for (uint32_t i = childNodes->Length(); i > 0; --i) {
+    for (uint32_t i = childNodes->Length(); i; --i) {
       nsCOMPtr<nsIContent> childNode = childNodes->Item(i - 1);
       if (childNode) {
         // prepend children of aNodeToJoin
         ErrorResult err;
         aNodeToKeep->InsertBefore(*childNode, firstNode, err);
         NS_ENSURE_TRUE(!err.Failed(), err.StealNSResult());
         firstNode = childNode.forget();
       }
@@ -3281,44 +3291,44 @@ EditorBase::IsBlockNode(nsINode* aNode)
   return false;
 }
 
 bool
 EditorBase::CanContain(nsINode& aParent,
                        nsIContent& aChild)
 {
   switch (aParent.NodeType()) {
-  case nsIDOMNode::ELEMENT_NODE:
-  case nsIDOMNode::DOCUMENT_FRAGMENT_NODE:
-    return TagCanContain(*aParent.NodeInfo()->NameAtom(), aChild);
+    case nsIDOMNode::ELEMENT_NODE:
+    case nsIDOMNode::DOCUMENT_FRAGMENT_NODE:
+      return TagCanContain(*aParent.NodeInfo()->NameAtom(), aChild);
   }
   return false;
 }
 
 bool
 EditorBase::CanContainTag(nsINode& aParent,
                           nsIAtom& aChildTag)
 {
   switch (aParent.NodeType()) {
-  case nsIDOMNode::ELEMENT_NODE:
-  case nsIDOMNode::DOCUMENT_FRAGMENT_NODE:
-    return TagCanContainTag(*aParent.NodeInfo()->NameAtom(), aChildTag);
+    case nsIDOMNode::ELEMENT_NODE:
+    case nsIDOMNode::DOCUMENT_FRAGMENT_NODE:
+      return TagCanContainTag(*aParent.NodeInfo()->NameAtom(), aChildTag);
   }
   return false;
 }
 
 bool
 EditorBase::TagCanContain(nsIAtom& aParentTag,
                           nsIContent& aChild)
 {
   switch (aChild.NodeType()) {
-  case nsIDOMNode::TEXT_NODE:
-  case nsIDOMNode::ELEMENT_NODE:
-  case nsIDOMNode::DOCUMENT_FRAGMENT_NODE:
-    return TagCanContainTag(aParentTag, *aChild.NodeInfo()->NameAtom());
+    case nsIDOMNode::TEXT_NODE:
+    case nsIDOMNode::ELEMENT_NODE:
+    case nsIDOMNode::DOCUMENT_FRAGMENT_NODE:
+      return TagCanContainTag(aParentTag, *aChild.NodeInfo()->NameAtom());
   }
   return false;
 }
 
 bool
 EditorBase::TagCanContainTag(nsIAtom& aParentTag,
                              nsIAtom& aChildTag)
 {
@@ -3396,17 +3406,17 @@ static inline bool
 IsElementVisible(Element* aElement)
 {
   if (aElement->GetPrimaryFrame()) {
     // It's visible, for our purposes
     return true;
   }
 
   nsIContent *cur = aElement;
-  for (; ;) {
+  for (;;) {
     // Walk up the tree looking for the nearest ancestor with a frame.
     // The state of the child right below it will determine whether
     // we might possibly have a frame or not.
     bool haveLazyBitOnChild = cur->HasFlag(NODE_NEEDS_FRAME);
     cur = cur->GetFlattenedTreeParent();
     if (!cur) {
       if (!haveLazyBitOnChild) {
         // None of our ancestors have lazy bits set, so we shouldn't
@@ -3510,19 +3520,20 @@ EditorBase::CountEditableChildren(nsINod
 
 NS_IMETHODIMP
 EditorBase::IncrementModificationCount(int32_t inNumMods)
 {
   uint32_t oldModCount = mModCount;
 
   mModCount += inNumMods;
 
-  if ((oldModCount == 0 && mModCount != 0)
-   || (oldModCount != 0 && mModCount == 0))
+  if ((!oldModCount && mModCount) ||
+      (oldModCount && !mModCount)) {
     NotifyDocumentListeners(eDocumentStateChanged);
+  }
   return NS_OK;
 }
 
 
 NS_IMETHODIMP
 EditorBase::GetModificationCount(int32_t* outModCount)
 {
   NS_ENSURE_ARG_POINTER(outModCount);
@@ -3533,49 +3544,46 @@ EditorBase::GetModificationCount(int32_t
 
 NS_IMETHODIMP
 EditorBase::ResetModificationCount()
 {
   bool doNotify = (mModCount != 0);
 
   mModCount = 0;
 
-  if (doNotify)
+  if (doNotify) {
     NotifyDocumentListeners(eDocumentStateChanged);
+  }
   return NS_OK;
 }
 
 nsIAtom*
 EditorBase::GetTag(nsIDOMNode* aNode)
 {
   nsCOMPtr<nsIContent> content = do_QueryInterface(aNode);
 
-  if (!content)
-  {
+  if (!content) {
     NS_ASSERTION(aNode, "null node passed to EditorBase::GetTag()");
-
     return nullptr;
   }
 
   return content->NodeInfo()->NameAtom();
 }
 
 nsresult
 EditorBase::GetTagString(nsIDOMNode* aNode,
                          nsAString& outString)
 {
-  if (!aNode)
-  {
+  if (!aNode) {
     NS_NOTREACHED("null node passed to EditorBase::GetTagString()");
     return NS_ERROR_NULL_POINTER;
   }
 
   nsIAtom *atom = GetTag(aNode);
-  if (!atom)
-  {
+  if (!atom) {
     return NS_ERROR_FAILURE;
   }
 
   atom->ToString(outString);
   return NS_OK;
 }
 
 bool
@@ -3603,18 +3611,17 @@ EditorBase::AreNodesSameType(nsIContent*
   MOZ_ASSERT(aNode1);
   MOZ_ASSERT(aNode2);
   return aNode1->NodeInfo()->NameAtom() == aNode2->NodeInfo()->NameAtom();
 }
 
 bool
 EditorBase::IsTextNode(nsIDOMNode* aNode)
 {
-  if (!aNode)
-  {
+  if (!aNode) {
     NS_NOTREACHED("null node passed to IsTextNode()");
     return false;
   }
 
   uint16_t nodeType;
   aNode->GetNodeType(&nodeType);
   return (nodeType == nsIDOMNode::TEXT_NODE);
 }
@@ -3777,18 +3784,17 @@ EditorBase::IsPreformatted(nsIDOMNode* a
     content = content->GetParent();
   }
   if (content && content->IsElement()) {
     elementStyle = nsComputedDOMStyle::GetStyleContextForElementNoFlush(content->AsElement(),
                                                                         nullptr,
                                                                         ps);
   }
 
-  if (!elementStyle)
-  {
+  if (!elementStyle) {
     // Consider nodes without a style context to be NOT preformatted:
     // For instance, this is true of JS tags inside the body (which show
     // up as #text nodes but have no style context).
     *aResult = false;
     return NS_OK;
   }
 
   const nsStyleText* styleText = elementStyle->StyleText();
@@ -3933,47 +3939,41 @@ EditorBase::JoinNodeDeep(nsIContent& aLe
   return ret;
 }
 
 void
 EditorBase::BeginUpdateViewBatch()
 {
   NS_PRECONDITION(mUpdateCount >= 0, "bad state");
 
-  if (0 == mUpdateCount)
-  {
+  if (!mUpdateCount) {
     // Turn off selection updates and notifications.
-
     RefPtr<Selection> selection = GetSelection();
-
     if (selection) {
       selection->StartBatchChanges();
     }
   }
 
   mUpdateCount++;
 }
 
 nsresult
 EditorBase::EndUpdateViewBatch()
 {
   NS_PRECONDITION(mUpdateCount > 0, "bad state");
 
-  if (mUpdateCount <= 0)
-  {
+  if (mUpdateCount <= 0) {
     mUpdateCount = 0;
     return NS_ERROR_FAILURE;
   }
 
   mUpdateCount--;
 
-  if (0 == mUpdateCount)
-  {
+  if (!mUpdateCount) {
     // Turn selection updating and notifications back on.
-
     RefPtr<Selection> selection = GetSelection();
     if (selection) {
       selection->EndBatchChanges();
     }
   }
 
   return NS_OK;
 }
@@ -4107,17 +4107,17 @@ EditorBase::DeleteSelectionAndPrepareToC
   if (node && node->IsNodeOfType(nsINode::eDATA_NODE)) {
     NS_ASSERTION(node->GetParentNode(),
                  "It's impossible to insert into chardata with no parent -- "
                  "fix the caller");
     NS_ENSURE_STATE(node->GetParentNode());
 
     uint32_t offset = selection->AnchorOffset();
 
-    if (offset == 0) {
+    if (!offset) {
       nsresult rv = selection->Collapse(node->GetParentNode(),
                                         node->GetParentNode()->IndexOf(node));
       MOZ_ASSERT(NS_SUCCEEDED(rv));
       NS_ENSURE_SUCCESS(rv, rv);
     } else if (offset == node->Length()) {
       nsresult rv =
         selection->Collapse(node->GetParentNode(),
                             node->GetParentNode()->IndexOf(node) + 1);
@@ -4137,26 +4137,26 @@ EditorBase::DeleteSelectionAndPrepareToC
 }
 
 void
 EditorBase::DoAfterDoTransaction(nsITransaction* aTxn)
 {
   bool isTransientTransaction;
   MOZ_ALWAYS_SUCCEEDS(aTxn->GetIsTransient(&isTransientTransaction));
 
-  if (!isTransientTransaction)
-  {
+  if (!isTransientTransaction) {
     // we need to deal here with the case where the user saved after some
     // edits, then undid one or more times. Then, the undo count is -ve,
     // but we can't let a do take it back to zero. So we flip it up to
     // a +ve number.
     int32_t modCount;
     GetModificationCount(&modCount);
-    if (modCount < 0)
+    if (modCount < 0) {
       modCount = -modCount;
+    }
 
     // don't count transient transactions
     MOZ_ALWAYS_SUCCEEDS(IncrementModificationCount(1));
   }
 }
 
 void
 EditorBase::DoAfterUndoTransaction()
@@ -4374,17 +4374,17 @@ EditorBase::CreateTxnForDeleteInsertionP
 
   int32_t offset = aRange->StartOffset();
 
   // determine if the insertion point is at the beginning, middle, or end of
   // the node
 
   uint32_t count = node->Length();
 
-  bool isFirst = (0 == offset);
+  bool isFirst = !offset;
   bool isLast  = (count == (uint32_t)offset);
 
   // XXX: if isFirst && isLast, then we'll need to delete the node
   //      as well as the 1 child
 
   // build a transaction for deleting the appropriate data
   // XXX: this has to come from rule section
   if (aAction == ePrevious && isFirst) {
@@ -4736,17 +4736,17 @@ EditorBase::InitializeSelection(nsIDOMEv
   } else {
     selection->SetAncestorLimiter(nullptr);
   }
 
   // XXX What case needs this?
   if (isTargetDoc) {
     int32_t rangeCount;
     selection->GetRangeCount(&rangeCount);
-    if (rangeCount == 0) {
+    if (!rangeCount) {
       BeginningOfDocument();
     }
   }
 
   // If there is composition when this is called, we may need to restore IME
   // selection because if the editor is reframed, this already forgot IME
   // selection and the transaction.
   if (mComposition && !mIMETextNode && mIMETextLength) {
@@ -4822,21 +4822,19 @@ EditorBase::FinalizeSelection()
 
   selCon->RepaintSelection(nsISelectionController::SELECTION_NORMAL);
   return NS_OK;
 }
 
 Element*
 EditorBase::GetRoot()
 {
-  if (!mRootElement)
-  {
+  if (!mRootElement) {
+    // Let GetRootElement() do the work
     nsCOMPtr<nsIDOMElement> root;
-
-    // Let GetRootElement() do the work
     GetRootElement(getter_AddRefs(root));
   }
 
   return mRootElement;
 }
 
 Element*
 EditorBase::GetEditorRoot()
@@ -4863,17 +4861,16 @@ EditorBase::DetermineCurrentDirection()
   // Get the current root direction from its frame
   nsIContent* rootElement = GetExposedRoot();
   NS_ENSURE_TRUE(rootElement, NS_ERROR_FAILURE);
 
   // If we don't have an explicit direction, determine our direction
   // from the content's direction
   if (!(mFlags & (nsIPlaintextEditor::eEditorLeftToRight |
                   nsIPlaintextEditor::eEditorRightToLeft))) {
-
     nsIFrame* frame = rootElement->GetPrimaryFrame();
     NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE);
 
     // Set the flag here, to enable us to use the same code path below.
     // It will be flipped before returning from the function.
     if (frame->StyleVisibility()->mDirection == NS_STYLE_DIRECTION_RTL) {
       mFlags |= nsIPlaintextEditor::eEditorRightToLeft;
     } else {
@@ -4946,51 +4943,44 @@ EditorBase::SwitchTextDirectionTo(uint32
   }
 }
 
 #if DEBUG_JOE
 void
 EditorBase::DumpNode(nsIDOMNode* aNode,
                      int32_t indent)
 {
-  int32_t i;
-  for (i=0; i<indent; i++)
+  for (int32_t i = 0; i < indent; i++) {
     printf("  ");
+  }
 
   nsCOMPtr<nsIDOMElement> element = do_QueryInterface(aNode);
   nsCOMPtr<nsIDOMDocumentFragment> docfrag = do_QueryInterface(aNode);
 
-  if (element || docfrag)
-  {
-    if (element)
-    {
+  if (element || docfrag) {
+    if (element) {
       nsAutoString tag;
       element->GetTagName(tag);
       printf("<%s>\n", NS_LossyConvertUTF16toASCII(tag).get());
-    }
-    else
-    {
+    } else {
       printf("<document fragment>\n");
     }
     nsCOMPtr<nsIDOMNodeList> childList;
     aNode->GetChildNodes(getter_AddRefs(childList));
     NS_ENSURE_TRUE(childList, NS_ERROR_NULL_POINTER);
     uint32_t numChildren;
     childList->GetLength(&numChildren);
     nsCOMPtr<nsIDOMNode> child, tmp;
     aNode->GetFirstChild(getter_AddRefs(child));
-    for (i=0; i<numChildren; i++)
-    {
-      DumpNode(child, indent+1);
+    for (uint32_t i = 0; i < numChildren; i++) {
+      DumpNode(child, indent + 1);
       child->GetNextSibling(getter_AddRefs(tmp));
       child = tmp;
     }
-  }
-  else if (IsTextNode(aNode))
-  {
+  } else if (IsTextNode(aNode)) {
     nsCOMPtr<nsIDOMCharacterData> textNode = do_QueryInterface(aNode);
     nsAutoString str;
     textNode->GetData(str);
     nsAutoCString cstr;
     LossyCopyUTF16toASCII(str, cstr);
     cstr.ReplaceChar('\n', ' ');
     printf("<textnode> %s\n", cstr.get());
   }
--- a/editor/libeditor/EditorUtils.cpp
+++ b/editor/libeditor/EditorUtils.cpp
@@ -199,30 +199,28 @@ EditorHookUtils::DoInsertionHook(nsIDOMD
                                  nsIDOMEvent* aDropEvent,
                                  nsITransferable *aTrans)
 {
   nsCOMPtr<nsISimpleEnumerator> enumerator;
   GetHookEnumeratorFromDocument(aDoc, getter_AddRefs(enumerator));
   NS_ENSURE_TRUE(enumerator, true);
 
   bool hasMoreHooks = false;
-  while (NS_SUCCEEDED(enumerator->HasMoreElements(&hasMoreHooks)) && hasMoreHooks)
-  {
+  while (NS_SUCCEEDED(enumerator->HasMoreElements(&hasMoreHooks)) &&
+         hasMoreHooks) {
     nsCOMPtr<nsISupports> isupp;
-    if (NS_FAILED(enumerator->GetNext(getter_AddRefs(isupp))))
+    if (NS_FAILED(enumerator->GetNext(getter_AddRefs(isupp)))) {
       break;
+    }
 
     nsCOMPtr<nsIClipboardDragDropHooks> override = do_QueryInterface(isupp);
-    if (override)
-    {
+    if (override) {
       bool doInsert = true;
-#ifdef DEBUG
-      nsresult hookResult =
-#endif
-      override->OnPasteOrDrop(aDropEvent, aTrans, &doInsert);
+      DebugOnly<nsresult> hookResult =
+        override->OnPasteOrDrop(aDropEvent, aTrans, &doInsert);
       NS_ASSERTION(NS_SUCCEEDED(hookResult), "hook failure in OnPasteOrDrop");
       NS_ENSURE_TRUE(doInsert, false);
     }
   }
 
   return true;
 }
 
--- a/editor/libeditor/HTMLAnonymousNodeEditor.cpp
+++ b/editor/libeditor/HTMLAnonymousNodeEditor.cpp
@@ -76,22 +76,23 @@ static int32_t GetCSSFloatValue(nsIDOMCS
       rv = val->GetFloatValue(nsIDOMCSSPrimitiveValue::CSS_PX, &f);
       NS_ENSURE_SUCCESS(rv, 0);
       break;
     case nsIDOMCSSPrimitiveValue::CSS_IDENT: {
       // the value is keyword, we have to map these keywords into
       // numeric values
       nsAutoString str;
       val->GetStringValue(str);
-      if (str.EqualsLiteral("thin"))
+      if (str.EqualsLiteral("thin")) {
         f = 1;
-      else if (str.EqualsLiteral("medium"))
+      } else if (str.EqualsLiteral("medium")) {
         f = 3;
-      else if (str.EqualsLiteral("thick"))
+      } else if (str.EqualsLiteral("thick")) {
         f = 5;
+      }
       break;
     }
   }
 
   return (int32_t) f;
 }
 
 class ElementDeletionObserver final : public nsStubMutationObserver
@@ -277,27 +278,29 @@ HTMLEditor::DeleteRefToAnonymousNode(nsI
       // See bug 338129.
       if (content->IsInComposedDoc() && aShell && aShell->GetPresContext() &&
           aShell->GetPresContext()->GetPresShell() == aShell) {
         nsCOMPtr<nsIDocumentObserver> docObserver = do_QueryInterface(aShell);
         if (docObserver) {
           // Call BeginUpdate() so that the nsCSSFrameConstructor/PresShell
           // knows we're messing with the frame tree.
           nsCOMPtr<nsIDocument> document = GetDocument();
-          if (document)
+          if (document) {
             docObserver->BeginUpdate(document, UPDATE_CONTENT_MODEL);
+          }
 
           // XXX This is wrong (bug 439258).  Once it's fixed, the NS_WARNING
           // in RestyleManager::RestyleForRemove should be changed back
           // to an assertion.
           docObserver->ContentRemoved(content->GetComposedDoc(),
                                       aParentContent, content, -1,
                                       content->GetPreviousSibling());
-          if (document)
+          if (document) {
             docObserver->EndUpdate(document, UPDATE_CONTENT_MODEL);
+          }
         }
       }
       content->UnbindFromTree();
     }
   }
 }
 
 // The following method is mostly called by a selection listener. When a
@@ -506,18 +509,17 @@ HTMLEditor::GetPositionAndDimensions(nsI
     aMarginTop  = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("margin-top"));
 
     aX = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("left")) +
          aMarginLeft + aBorderLeft;
     aY = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("top")) +
          aMarginTop + aBorderTop;
     aW = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("width"));
     aH = GetCSSFloatValue(cssDecl, NS_LITERAL_STRING("height"));
-  }
-  else {
+  } else {
     mResizedObjectIsAbsolutelyPositioned = false;
     nsCOMPtr<nsIDOMHTMLElement> htmlElement = do_QueryInterface(aElement);
     if (!htmlElement) {
       return NS_ERROR_NULL_POINTER;
     }
     GetElementOrigin(aElement, aX, aY);
 
     if (NS_WARN_IF(NS_FAILED(htmlElement->GetOffsetWidth(&aW))) ||
--- a/editor/libeditor/HTMLEditRules.cpp
+++ b/editor/libeditor/HTMLEditRules.cpp
@@ -139,18 +139,19 @@ public:
   {
     if (mHTMLEditor->IsEditable(aNode) &&
         (HTMLEditUtils::IsListItem(aNode) ||
          HTMLEditUtils::IsTableCellOrCaption(*aNode))) {
       bool bIsEmptyNode;
       nsresult rv =
         mHTMLEditor->IsEmptyNode(aNode, &bIsEmptyNode, false, false);
       NS_ENSURE_SUCCESS(rv, false);
-      if (bIsEmptyNode)
+      if (bIsEmptyNode) {
         return true;
+      }
     }
     return false;
   }
 
 protected:
   HTMLEditor* mHTMLEditor;
 };
 
@@ -208,18 +209,19 @@ HTMLEditRules::InitFields()
 
 HTMLEditRules::~HTMLEditRules()
 {
   // remove ourselves as a listener to edit actions
   // In some cases, we have already been removed by
   // ~HTMLEditor, in which case we will get a null pointer here
   // which we ignore.  But this allows us to add the ability to
   // switch rule sets on the fly if we want.
-  if (mHTMLEditor)
+  if (mHTMLEditor) {
     mHTMLEditor->RemoveEditActionListener(this);
+  }
 }
 
 NS_IMPL_ADDREF_INHERITED(HTMLEditRules, TextEditRules)
 NS_IMPL_RELEASE_INHERITED(HTMLEditRules, TextEditRules)
 NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(HTMLEditRules)
   NS_INTERFACE_TABLE_INHERITED(HTMLEditRules, nsIEditActionListener)
 NS_INTERFACE_TABLE_TAIL_INHERITING(TextEditRules)
 
@@ -409,81 +411,79 @@ HTMLEditRules::AfterEdit(EditAction acti
   return NS_OK;
 }
 
 nsresult
 HTMLEditRules::AfterEditInner(EditAction action,
                               nsIEditor::EDirection aDirection)
 {
   ConfirmSelectionInBody();
-  if (action == EditAction::ignore) return NS_OK;
+  if (action == EditAction::ignore) {
+    return NS_OK;
+  }
 
   NS_ENSURE_STATE(mHTMLEditor);
   RefPtr<Selection> selection = mHTMLEditor->GetSelection();
   NS_ENSURE_STATE(selection);
 
   nsCOMPtr<nsIDOMNode> rangeStartParent, rangeEndParent;
   int32_t rangeStartOffset = 0, rangeEndOffset = 0;
   // do we have a real range to act on?
   bool bDamagedRange = false;
-  if (mDocChangeRange)
-  {
+  if (mDocChangeRange) {
     mDocChangeRange->GetStartContainer(getter_AddRefs(rangeStartParent));
     mDocChangeRange->GetEndContainer(getter_AddRefs(rangeEndParent));
     mDocChangeRange->GetStartOffset(&rangeStartOffset);
     mDocChangeRange->GetEndOffset(&rangeEndOffset);
     if (rangeStartParent && rangeEndParent)
       bDamagedRange = true;
   }
 
-  if (bDamagedRange && !((action == EditAction::undo) || (action == EditAction::redo)))
-  {
+  if (bDamagedRange && !((action == EditAction::undo) ||
+                         (action == EditAction::redo))) {
     // don't let any txns in here move the selection around behind our back.
     // Note that this won't prevent explicit selection setting from working.
     NS_ENSURE_STATE(mHTMLEditor);
     AutoTransactionsConserveSelection dontSpazMySelection(mHTMLEditor);
 
     // expand the "changed doc range" as needed
     PromoteRange(*mDocChangeRange, action);
 
     // if we did a ranged deletion or handling backspace key, make sure we have
     // a place to put caret.
     // Note we only want to do this if the overall operation was deletion,
     // not if deletion was done along the way for EditAction::loadHTML, EditAction::insertText, etc.
     // That's why this is here rather than DidDeleteSelection().
-    if ((action == EditAction::deleteSelection) && mDidRangedDelete)
-    {
+    if (action == EditAction::deleteSelection && mDidRangedDelete) {
       nsresult rv = InsertBRIfNeeded(selection);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     // add in any needed <br>s, and remove any unneeded ones.
     AdjustSpecialBreaks();
 
     // merge any adjacent text nodes
-    if ( (action != EditAction::insertText &&
-         action != EditAction::insertIMEText) )
-    {
+    if (action != EditAction::insertText &&
+        action != EditAction::insertIMEText) {
       NS_ENSURE_STATE(mHTMLEditor);
       nsresult rv = mHTMLEditor->CollapseAdjacentTextNodes(mDocChangeRange);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     // clean up any empty nodes in the selection
     nsresult rv = RemoveEmptyNodes();
     NS_ENSURE_SUCCESS(rv, rv);
 
     // attempt to transform any unneeded nbsp's into spaces after doing various operations
-    if ((action == EditAction::insertText) ||
-        (action == EditAction::insertIMEText) ||
-        (action == EditAction::deleteSelection) ||
-        (action == EditAction::insertBreak) ||
-        (action == EditAction::htmlPaste ||
-        (action == EditAction::loadHTML)))
-    {
+    if (action == EditAction::insertText ||
+        action == EditAction::insertIMEText ||
+        action == EditAction::deleteSelection ||
+        action == EditAction::insertBreak ||
+        action == EditAction::htmlPaste ||
+        action == EditAction::loadHTML) {
       rv = AdjustWhitespace(selection);
       NS_ENSURE_SUCCESS(rv, rv);
 
       // also do this for original selection endpoints.
       NS_ENSURE_STATE(mHTMLEditor);
       NS_ENSURE_STATE(mRangeItem->startNode);
       NS_ENSURE_STATE(mRangeItem->endNode);
       WSRunObject(mHTMLEditor, mRangeItem->startNode,
@@ -493,30 +493,28 @@ HTMLEditRules::AfterEditInner(EditAction
           mRangeItem->startOffset != mRangeItem->endOffset) {
         NS_ENSURE_STATE(mHTMLEditor);
         WSRunObject(mHTMLEditor, mRangeItem->endNode,
                     mRangeItem->endOffset).AdjustWhitespace();
       }
     }
 
     // if we created a new block, make sure selection lands in it
-    if (mNewBlock)
-    {
+    if (mNewBlock) {
       rv = PinSelectionToNewBlock(selection);
       mNewBlock = 0;
     }
 
     // adjust selection for insert text, html paste, and delete actions
-    if ((action == EditAction::insertText) ||
-        (action == EditAction::insertIMEText) ||
-        (action == EditAction::deleteSelection) ||
-        (action == EditAction::insertBreak) ||
-        (action == EditAction::htmlPaste ||
-        (action == EditAction::loadHTML)))
-    {
+    if (action == EditAction::insertText ||
+        action == EditAction::insertIMEText ||
+        action == EditAction::deleteSelection ||
+        action == EditAction::insertBreak ||
+        action == EditAction::htmlPaste ||
+        action == EditAction::loadHTML) {
       rv = AdjustSelection(selection, aDirection);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     // check for any styles which were removed inappropriately
     if (action == EditAction::insertText ||
         action == EditAction::insertIMEText ||
         action == EditAction::deleteSelection ||
@@ -539,18 +537,17 @@ HTMLEditRules::AfterEditInner(EditAction
                                         rangeEndParent, rangeEndOffset);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // detect empty doc
   rv = CreateBogusNodeIfNeeded(selection);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // adjust selection HINT if needed
-  if (!mDidExplicitlySetInterline)
-  {
+  if (!mDidExplicitlySetInterline) {
     CheckInterlinePosition(*selection);
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditRules::WillDoAction(Selection* aSelection,
@@ -654,18 +651,17 @@ HTMLEditRules::WillDoAction(Selection* a
 }
 
 NS_IMETHODIMP
 HTMLEditRules::DidDoAction(Selection* aSelection,
                            RulesInfo* aInfo,
                            nsresult aResult)
 {
   TextRulesInfo* info = static_cast<TextRulesInfo*>(aInfo);
-  switch (info->action)
-  {
+  switch (info->action) {
     case EditAction::insertBreak:
       return DidInsertBreak(aSelection, aResult);
     case EditAction::deleteSelection:
       return DidDeleteSelection(aSelection, info->collapsedAction, aResult);
     case EditAction::makeBasicBlock:
     case EditAction::indent:
     case EditAction::outdent:
     case EditAction::align:
@@ -769,17 +765,19 @@ HTMLEditRules::GetListItemState(bool* aM
       *aDT |= bDT;
       *aDD |= bDD;
     } else {
       bNonList = true;
     }
   }
 
   // hokey arithmetic with booleans
-  if ( (*aDT + *aDD + bNonList) > 1) *aMixed = true;
+  if (*aDT + *aDD + bNonList > 1) {
+    *aMixed = true;
+  }
 
   return NS_OK;
 }
 
 nsresult
 HTMLEditRules::GetAlignment(bool* aMixed,
                             nsIHTMLEditor::EAlignment* aAlign)
 {
@@ -941,18 +939,17 @@ HTMLEditRules::GetIndentState(bool* aCan
   // these we can outdent.  Note that we return true for canOutdent
   // if *any* of the selection is outdentable, rather than all of it.
   NS_ENSURE_STATE(mHTMLEditor);
   bool useCSS = mHTMLEditor->IsCSSEnabled();
   for (auto& curNode : Reversed(arrayOfNodes)) {
     if (HTMLEditUtils::IsNodeThatCanOutdent(GetAsDOMNode(curNode))) {
       *aCanOutdent = true;
       break;
-    }
-    else if (useCSS) {
+    } else if (useCSS) {
       // we are in CSS mode, indentation is done using the margin-left (or margin-right) property
       NS_ENSURE_STATE(mHTMLEditor);
       nsIAtom& marginProperty =
         MarginPropertyAtomForIndent(*mHTMLEditor->mCSSEditUtils, curNode);
       nsAutoString value;
       // retrieve its specified value
       NS_ENSURE_STATE(mHTMLEditor);
       mHTMLEditor->mCSSEditUtils->GetSpecifiedProperty(*curNode,
@@ -965,18 +962,17 @@ HTMLEditRules::GetIndentState(bool* aCan
       // if the number part is strictly positive, outdent is possible
       if (0 < f) {
         *aCanOutdent = true;
         break;
       }
     }
   }
 
-  if (!*aCanOutdent)
-  {
+  if (!*aCanOutdent) {
     // if we haven't found something to outdent yet, also check the parents
     // of selection endpoints.  We might have a blockquote or list item
     // in the parent hierarchy.
 
     // gather up info we need for test
     NS_ENSURE_STATE(mHTMLEditor);
     nsCOMPtr<nsIDOMNode> parent, tmp, root = do_QueryInterface(mHTMLEditor->GetRoot());
     NS_ENSURE_TRUE(root, NS_ERROR_NULL_POINTER);
@@ -985,38 +981,36 @@ HTMLEditRules::GetIndentState(bool* aCan
     RefPtr<Selection> selection = mHTMLEditor->GetSelection();
     NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
 
     // test start parent hierarchy
     NS_ENSURE_STATE(mHTMLEditor);
     rv = mHTMLEditor->GetStartNodeAndOffset(selection, getter_AddRefs(parent),
                                             &selOffset);
     NS_ENSURE_SUCCESS(rv, rv);
-    while (parent && (parent!=root))
-    {
+    while (parent && parent != root) {
       if (HTMLEditUtils::IsNodeThatCanOutdent(parent)) {
         *aCanOutdent = true;
         break;
       }
-      tmp=parent;
+      tmp = parent;
       tmp->GetParentNode(getter_AddRefs(parent));
     }
 
     // test end parent hierarchy
     NS_ENSURE_STATE(mHTMLEditor);
     rv = mHTMLEditor->GetEndNodeAndOffset(selection, getter_AddRefs(parent),
                                           &selOffset);
     NS_ENSURE_SUCCESS(rv, rv);
-    while (parent && (parent!=root))
-    {
+    while (parent && parent != root) {
       if (HTMLEditUtils::IsNodeThatCanOutdent(parent)) {
         *aCanOutdent = true;
         break;
       }
-      tmp=parent;
+      tmp = parent;
       tmp->GetParentNode(getter_AddRefs(parent));
     }
   }
   return NS_OK;
 }
 
 
 nsresult
@@ -1048,17 +1042,17 @@ HTMLEditRules::GetParagraphState(bool* a
       // arrayOfNodes.RemoveObject(curNode);
       rv = AppendInnerFormatNodes(arrayOfNodes, curNode);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
   // we might have an empty node list.  if so, find selection parent
   // and put that on the list
-  if (!arrayOfNodes.Length()) {
+  if (arrayOfNodes.IsEmpty()) {
     nsCOMPtr<nsINode> selNode;
     int32_t selOffset;
     NS_ENSURE_STATE(mHTMLEditor);
     RefPtr<Selection> selection = mHTMLEditor->GetSelection();
     NS_ENSURE_STATE(selection);
     NS_ENSURE_STATE(mHTMLEditor);
     rv = mHTMLEditor->GetStartNodeAndOffset(selection, getter_AddRefs(selNode),
                                             &selOffset);
@@ -1079,42 +1073,39 @@ HTMLEditRules::GetParagraphState(bool* a
     if (HTMLEditUtils::IsFormatNode(curNode)) {
       GetFormatString(GetAsDOMNode(curNode), format);
     } else if (IsBlockNode(curNode)) {
       // this is a div or some other non-format block.
       // we should ignore it.  Its children were appended to this list
       // by AppendInnerFormatNodes() call above.  We will get needed
       // info when we examine them instead.
       continue;
-    }
-    else
-    {
+    } else {
       nsCOMPtr<nsIDOMNode> node, tmp = GetAsDOMNode(curNode);
       tmp->GetParentNode(getter_AddRefs(node));
-      while (node)
-      {
+      while (node) {
         if (node == rootElem) {
           format.Truncate(0);
           break;
         } else if (HTMLEditUtils::IsFormatNode(node)) {
           GetFormatString(node, format);
           break;
         }
         // else keep looking up
         tmp = node;
         tmp->GetParentNode(getter_AddRefs(node));
       }
     }
 
     // if this is the first node, we've found, remember it as the format
-    if (formatStr.EqualsLiteral("x"))
+    if (formatStr.EqualsLiteral("x")) {
       formatStr = format;
+    }
     // else make sure it matches previously found format
-    else if (format != formatStr)
-    {
+    else if (format != formatStr) {
       bMixed = true;
       break;
     }
   }
 
   *aMixed = bMixed;
   outFormat = formatStr;
   return NS_OK;
@@ -1154,20 +1145,19 @@ nsresult
 HTMLEditRules::GetFormatString(nsIDOMNode* aNode,
                                nsAString& outFormat)
 {
   NS_ENSURE_TRUE(aNode, NS_ERROR_NULL_POINTER);
 
   if (HTMLEditUtils::IsFormatNode(aNode)) {
     nsCOMPtr<nsIAtom> atom = EditorBase::GetTag(aNode);
     atom->ToString(outFormat);
-  }
-  else
+  } else {
     outFormat.Truncate();
-
+  }
   return NS_OK;
 }
 
 void
 HTMLEditRules::WillInsert(Selection& aSelection,
                           bool* aCancel)
 {
   MOZ_ASSERT(aCancel);
@@ -1228,17 +1218,19 @@ nsresult
 HTMLEditRules::WillInsertText(EditAction aAction,
                               Selection* aSelection,
                               bool* aCancel,
                               bool* aHandled,
                               const nsAString* inString,
                               nsAString* outString,
                               int32_t aMaxLength)
 {
-  if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   if (inString->IsEmpty() && aAction != EditAction::insertIMEText) {
     // HACK: this is a fix for bug 19395
     // I can't outlaw all empty insertions
     // because IME transaction depend on them
     // There is more work to do to make the
     // world safe for IME.
     *aCancel = true;
@@ -1293,35 +1285,32 @@ HTMLEditRules::WillInsertText(EditAction
     NS_ENSURE_STATE(mHTMLEditor);
     // If there is one or more IME selections, its minimum offset should be
     // the insertion point.
     int32_t IMESelectionOffset =
       mHTMLEditor->GetIMESelectionStartOffsetIn(selNode);
     if (IMESelectionOffset >= 0) {
       selOffset = IMESelectionOffset;
     }
-    if (inString->IsEmpty())
-    {
+    if (inString->IsEmpty()) {
       rv = mHTMLEditor->InsertTextImpl(*inString, address_of(selNode),
                                        &selOffset, doc);
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
-    }
-    else
-    {
+    } else {
       WSRunObject wsObj(mHTMLEditor, selNode, selOffset);
       rv = wsObj.InsertText(*inString, address_of(selNode), &selOffset, doc);
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
     }
   }
-  else // aAction == kInsertText
-  {
+  // aAction == kInsertText
+  else {
     // find where we are
     nsCOMPtr<nsINode> curNode = selNode;
     int32_t curOffset = selOffset;
 
     // is our text going to be PREformatted?
     // We remember this so that we know how to handle tabs.
     bool isPRE;
     NS_ENSURE_STATE(mHTMLEditor);
@@ -1340,116 +1329,101 @@ HTMLEditRules::WillInsertText(EditAction
     nsAutoString tString(*inString);
     const char16_t *unicodeBuf = tString.get();
     int32_t pos = 0;
     NS_NAMED_LITERAL_STRING(newlineStr, LFSTR);
 
     // for efficiency, break out the pre case separately.  This is because
     // its a lot cheaper to search the input string for only newlines than
     // it is to search for both tabs and newlines.
-    if (isPRE || IsPlaintextEditor())
-    {
-      while (unicodeBuf && (pos != -1) && (pos < (int32_t)(*inString).Length()))
-      {
+    if (isPRE || IsPlaintextEditor()) {
+      while (unicodeBuf && pos != -1 &&
+             pos < static_cast<int32_t>(inString->Length())) {
         int32_t oldPos = pos;
         int32_t subStrLen;
         pos = tString.FindChar(nsCRT::LF, oldPos);
 
-        if (pos != -1)
-        {
+        if (pos != -1) {
           subStrLen = pos - oldPos;
           // if first char is newline, then use just it
-          if (subStrLen == 0)
+          if (!subStrLen) {
             subStrLen = 1;
-        }
-        else
-        {
+          }
+        } else {
           subStrLen = tString.Length() - oldPos;
           pos = tString.Length();
         }
 
         nsDependentSubstring subStr(tString, oldPos, subStrLen);
 
         // is it a return?
-        if (subStr.Equals(newlineStr))
-        {
+        if (subStr.Equals(newlineStr)) {
           NS_ENSURE_STATE(mHTMLEditor);
           nsCOMPtr<Element> br =
             mHTMLEditor->CreateBRImpl(address_of(curNode), &curOffset,
                                       nsIEditor::eNone);
           NS_ENSURE_STATE(br);
           pos++;
-        }
-        else
-        {
+        } else {
           NS_ENSURE_STATE(mHTMLEditor);
           rv = mHTMLEditor->InsertTextImpl(subStr, address_of(curNode),
                                            &curOffset, doc);
           NS_ENSURE_SUCCESS(rv, rv);
         }
       }
-    }
-    else
-    {
+    } else {
       NS_NAMED_LITERAL_STRING(tabStr, "\t");
       NS_NAMED_LITERAL_STRING(spacesStr, "    ");
       char specialChars[] = {TAB, nsCRT::LF, 0};
-      while (unicodeBuf && (pos != -1) && (pos < (int32_t)inString->Length()))
-      {
+      while (unicodeBuf && pos != -1 &&
+             pos < static_cast<int32_t>(inString->Length())) {
         int32_t oldPos = pos;
         int32_t subStrLen;
         pos = tString.FindCharInSet(specialChars, oldPos);
 
-        if (pos != -1)
-        {
+        if (pos != -1) {
           subStrLen = pos - oldPos;
           // if first char is newline, then use just it
-          if (subStrLen == 0)
+          if (!subStrLen) {
             subStrLen = 1;
-        }
-        else
-        {
+          }
+        } else {
           subStrLen = tString.Length() - oldPos;
           pos = tString.Length();
         }
 
         nsDependentSubstring subStr(tString, oldPos, subStrLen);
         NS_ENSURE_STATE(mHTMLEditor);
         WSRunObject wsObj(mHTMLEditor, curNode, curOffset);
 
         // is it a tab?
-        if (subStr.Equals(tabStr))
-        {
+        if (subStr.Equals(tabStr)) {
           rv =
             wsObj.InsertText(spacesStr, address_of(curNode), &curOffset, doc);
           NS_ENSURE_SUCCESS(rv, rv);
           pos++;
         }
         // is it a return?
-        else if (subStr.Equals(newlineStr))
-        {
+        else if (subStr.Equals(newlineStr)) {
           nsCOMPtr<Element> br = wsObj.InsertBreak(address_of(curNode),
                                                    &curOffset,
                                                    nsIEditor::eNone);
           NS_ENSURE_TRUE(br, NS_ERROR_FAILURE);
           pos++;
-        }
-        else
-        {
+        } else {
           rv = wsObj.InsertText(subStr, address_of(curNode), &curOffset, doc);
           NS_ENSURE_SUCCESS(rv, rv);
         }
       }
     }
     aSelection->SetInterlinePosition(false);
     if (curNode) aSelection->Collapse(curNode, curOffset);
     // manually update the doc changed range so that AfterEdit will clean up
     // the correct portion of the document.
-    if (!mDocChangeRange)
-    {
+    if (!mDocChangeRange) {
       mDocChangeRange = new nsRange(selNode);
     }
     rv = mDocChangeRange->SetStart(selNode, selOffset);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (curNode) {
       rv = mDocChangeRange->SetEnd(curNode, curOffset);
       if (NS_WARN_IF(NS_FAILED(rv))) {
@@ -1471,18 +1445,17 @@ HTMLEditRules::WillLoadHTML(Selection* a
 {
   NS_ENSURE_TRUE(aSelection && aCancel, NS_ERROR_NULL_POINTER);
 
   *aCancel = false;
 
   // Delete mBogusNode if it exists. If we really need one,
   // it will be added during post-processing in AfterEditInner().
 
-  if (mBogusNode)
-  {
+  if (mBogusNode) {
     mTextEditor->DeleteNode(mBogusNode);
     mBogusNode = nullptr;
   }
 
   return NS_OK;
 }
 
 nsresult
@@ -1699,18 +1672,17 @@ HTMLEditRules::SplitMailCites(Selection*
   nsCOMPtr<Element> citeNode;
   int32_t selOffset;
   NS_ENSURE_STATE(mHTMLEditor);
   nsresult rv =
     mHTMLEditor->GetStartNodeAndOffset(aSelection, getter_AddRefs(selNode),
                                        &selOffset);
   NS_ENSURE_SUCCESS(rv, rv);
   citeNode = GetTopEnclosingMailCite(*selNode);
-  if (citeNode)
-  {
+  if (citeNode) {
     // If our selection is just before a break, nudge it to be
     // just after it.  This does two things for us.  It saves us the trouble of having to add
     // a break here ourselves to preserve the "blockness" of the inline span mailquote
     // (in the inline case), and :
     // it means the break won't end up making an empty line that happens to be inside a
     // mailquote (in either inline or block case).
     // The latter can confuse a user if they click there and start typing,
     // because being in the mailquote may affect wrapping behavior, or font color, etc.
@@ -1768,33 +1740,31 @@ HTMLEditRules::SplitMailCites(Selection*
           NS_ENSURE_STATE(mHTMLEditor);
           brNode = mHTMLEditor->CreateBR(selNode, newOffset);
           NS_ENSURE_STATE(brNode);
         }
       }
     }
     // delete any empty cites
     bool bEmptyCite = false;
-    if (leftCite)
-    {
+    if (leftCite) {
       NS_ENSURE_STATE(mHTMLEditor);
       rv = mHTMLEditor->IsEmptyNode(leftCite, &bEmptyCite, true, false);
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
       if (bEmptyCite) {
         NS_ENSURE_STATE(mHTMLEditor);
         rv = mHTMLEditor->DeleteNode(leftCite);
         if (NS_WARN_IF(NS_FAILED(rv))) {
           return rv;
         }
       }
     }
-    if (rightCite)
-    {
+    if (rightCite) {
       NS_ENSURE_STATE(mHTMLEditor);
       rv = mHTMLEditor->IsEmptyNode(rightCite, &bEmptyCite, true, false);
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
       if (bEmptyCite) {
         NS_ENSURE_STATE(mHTMLEditor);
         rv = mHTMLEditor->DeleteNode(rightCite);
@@ -1861,17 +1831,16 @@ HTMLEditRules::WillDeleteSelection(Selec
   nsCOMPtr<nsINode> selNode;
   int32_t selOffset;
 
   NS_ENSURE_STATE(aSelection->GetRangeAt(0));
   nsCOMPtr<nsINode> startNode = aSelection->GetRangeAt(0)->GetStartParent();
   int32_t startOffset = aSelection->GetRangeAt(0)->StartOffset();
   NS_ENSURE_TRUE(startNode, NS_ERROR_FAILURE);
 
-
   if (bCollapsed) {
     // If we are inside an empty block, delete it.
     NS_ENSURE_STATE(mHTMLEditor);
     nsCOMPtr<Element> host = mHTMLEditor->GetActiveEditingHost();
     NS_ENSURE_TRUE(host, NS_ERROR_FAILURE);
     rv = CheckForEmptyBlock(startNode, host, aSelection, aAction, aHandled);
     NS_ENSURE_SUCCESS(rv, rv);
     if (*aHandled) {
@@ -1947,17 +1916,17 @@ HTMLEditRules::WillDeleteSelection(Selec
     }
 
     if (wsType == WSType::text) {
       // Found normal text to delete.
       OwningNonNull<Text> nodeAsText = *visNode->GetAsText();
       int32_t so = visOffset;
       int32_t eo = visOffset + 1;
       if (aAction == nsIEditor::ePrevious) {
-        if (so == 0) {
+        if (!so) {
           return NS_ERROR_UNEXPECTED;
         }
         so--;
         eo--;
         // Bug 1068979: delete both codepoints if surrogate pair
         if (so > 0) {
           const nsTextFragment *text = nodeAsText->GetText();
           if (NS_IS_LOW_SURROGATE(text->CharAt(so)) &&
@@ -2328,29 +2297,29 @@ HTMLEditRules::WillDeleteSelection(Selec
         NS_ENSURE_STATE(mHTMLEditor);
         if (leftBlockParent == rightBlockParent &&
             mHTMLEditor->NodesSameType(GetAsDOMNode(leftParent),
                                        GetAsDOMNode(rightParent)) &&
             // XXX What's special about these three types of block?
             (leftParent->IsHTMLElement(nsGkAtoms::p) ||
              HTMLEditUtils::IsListItem(leftParent) ||
              HTMLEditUtils::IsHeader(*leftParent))) {
-            // First delete the selection
-            NS_ENSURE_STATE(mHTMLEditor);
-            rv = mHTMLEditor->DeleteSelectionImpl(aAction, aStripWrappers);
-            NS_ENSURE_SUCCESS(rv, rv);
-            // Join blocks
-            NS_ENSURE_STATE(mHTMLEditor);
-            EditorDOMPoint pt =
-              mHTMLEditor->JoinNodeDeep(*leftParent, *rightParent);
-            NS_ENSURE_STATE(pt.node);
-            // Fix up selection
-            rv = aSelection->Collapse(pt.node, pt.offset);
-            NS_ENSURE_SUCCESS(rv, rv);
-            return NS_OK;
+          // First delete the selection
+          NS_ENSURE_STATE(mHTMLEditor);
+          rv = mHTMLEditor->DeleteSelectionImpl(aAction, aStripWrappers);
+          NS_ENSURE_SUCCESS(rv, rv);
+          // Join blocks
+          NS_ENSURE_STATE(mHTMLEditor);
+          EditorDOMPoint pt =
+            mHTMLEditor->JoinNodeDeep(*leftParent, *rightParent);
+          NS_ENSURE_STATE(pt.node);
+          // Fix up selection
+          rv = aSelection->Collapse(pt.node, pt.offset);
+          NS_ENSURE_SUCCESS(rv, rv);
+          return NS_OK;
         }
 
         // Else blocks not same type, or not siblings.  Delete everything
         // except table elements.
         join = true;
 
         uint32_t rangeCount = aSelection->RangeCount();
         for (uint32_t rangeIdx = 0; rangeIdx < rangeCount; ++rangeIdx) {
@@ -2391,17 +2360,17 @@ HTMLEditRules::WillDeleteSelection(Selec
           }
         }
 
         // Check endpoints for possible text deletion.  We can assume that if
         // text node is found, we can delete to end or to begining as
         // appropriate, since the case where both sel endpoints in same text
         // node was already handled (we wouldn't be here)
         if (startNode->GetAsText() &&
-            startNode->Length() > uint32_t(startOffset)) {
+            startNode->Length() > static_cast<uint32_t>(startOffset)) {
           // Delete to last character
           OwningNonNull<nsGenericDOMDataNode> dataNode =
             *static_cast<nsGenericDOMDataNode*>(startNode.get());
           NS_ENSURE_STATE(mHTMLEditor);
           rv = mHTMLEditor->DeleteText(dataNode, startOffset,
                                        startNode->Length() - startOffset);
           NS_ENSURE_SUCCESS(rv, rv);
         }
@@ -2929,17 +2898,19 @@ HTMLEditRules::DeleteNonTableElements(ns
   return NS_OK;
 }
 
 nsresult
 HTMLEditRules::DidDeleteSelection(Selection* aSelection,
                                   nsIEditor::EDirection aDir,
                                   nsresult aResult)
 {
-  if (!aSelection) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   // find where we are
   nsCOMPtr<nsINode> startNode;
   int32_t startOffset;
   nsresult rv = mTextEditor->GetStartNodeAndOffset(aSelection,
                                                    getter_AddRefs(startNode),
                                                    &startOffset);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -2947,25 +2918,23 @@ HTMLEditRules::DidDeleteSelection(Select
 
   // find any enclosing mailcite
   nsCOMPtr<Element> citeNode = GetTopEnclosingMailCite(*startNode);
   if (citeNode) {
     bool isEmpty = true, seenBR = false;
     NS_ENSURE_STATE(mHTMLEditor);
     mHTMLEditor->IsEmptyNodeImpl(citeNode, &isEmpty, true, true, false,
                                  &seenBR);
-    if (isEmpty)
-    {
+    if (isEmpty) {
       int32_t offset;
       nsCOMPtr<nsINode> parent = EditorBase::GetNodeLocation(citeNode, &offset);
       NS_ENSURE_STATE(mHTMLEditor);
       rv = mHTMLEditor->DeleteNode(citeNode);
       NS_ENSURE_SUCCESS(rv, rv);
-      if (parent && seenBR)
-      {
+      if (parent && seenBR) {
         NS_ENSURE_STATE(mHTMLEditor);
         nsCOMPtr<Element> brNode = mHTMLEditor->CreateBR(parent, offset);
         NS_ENSURE_STATE(brNode);
         aSelection->Collapse(parent, offset);
       }
     }
   }
 
@@ -3030,17 +2999,17 @@ HTMLEditRules::WillMakeList(Selection* a
         !IsEmptyInline(curNode)) {
       bOnlyBreaks = false;
       break;
     }
   }
 
   // if no nodes, we make empty list.  Ditto if the user tried to make a list
   // of some # of breaks.
-  if (!arrayOfNodes.Length() || bOnlyBreaks) {
+  if (arrayOfNodes.IsEmpty() || bOnlyBreaks) {
     // if only breaks, delete them
     if (bOnlyBreaks) {
       for (auto& node : arrayOfNodes) {
         NS_ENSURE_STATE(mHTMLEditor);
         rv = mHTMLEditor->DeleteNode(node);
         NS_ENSURE_SUCCESS(rv, rv);
       }
     }
@@ -3285,17 +3254,19 @@ HTMLEditRules::WillMakeList(Selection* a
 
 
 nsresult
 HTMLEditRules::WillRemoveList(Selection* aSelection,
                               bool aOrdered,
                               bool* aCancel,
                               bool* aHandled)
 {
-  if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
   // initialize out param
   *aCancel = false;
   *aHandled = true;
 
   nsresult rv = NormalizeSelection(aSelection);
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_STATE(mHTMLEditor);
   AutoSelectionRestorer selectionRestorer(aSelection, mHTMLEditor);
@@ -3304,52 +3275,43 @@ HTMLEditRules::WillRemoveList(Selection*
   GetPromotedRanges(*aSelection, arrayOfRanges, EditAction::makeList);
 
   // use these ranges to contruct a list of nodes to act on.
   nsTArray<OwningNonNull<nsINode>> arrayOfNodes;
   rv = GetListActionNodes(arrayOfNodes, EntireList::no);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Remove all non-editable nodes.  Leave them be.
-  int32_t listCount = arrayOfNodes.Length();
-  int32_t i;
-  for (i=listCount-1; i>=0; i--)
-  {
+  for (int32_t i = arrayOfNodes.Length() - 1; i >= 0; i--) {
     OwningNonNull<nsINode> testNode = arrayOfNodes[i];
     NS_ENSURE_STATE(mHTMLEditor);
-    if (!mHTMLEditor->IsEditable(testNode))
-    {
+    if (!mHTMLEditor->IsEditable(testNode)) {
       arrayOfNodes.RemoveElementAt(i);
     }
   }
 
-  // reset list count
-  listCount = arrayOfNodes.Length();
-
   // Only act on lists or list items in the array
   for (auto& curNode : arrayOfNodes) {
     // here's where we actually figure out what to do
     if (HTMLEditUtils::IsListItem(curNode)) {
       // unlist this listitem
       bool bOutOfList;
-      do
-      {
+      do {
         rv = PopListItem(GetAsDOMNode(curNode), &bOutOfList);
         NS_ENSURE_SUCCESS(rv, rv);
       } while (!bOutOfList); // keep popping it out until it's not in a list anymore
     } else if (HTMLEditUtils::IsList(curNode)) {
       // node is a list, move list items out
       rv = RemoveListStructure(*curNode->AsElement());
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
   return NS_OK;
 }
 
-
 nsresult
 HTMLEditRules::WillMakeDefListItem(Selection* aSelection,
                                    const nsAString *aItemType,
                                    bool aEntireList,
                                    bool* aCancel,
                                    bool* aHandled)
 {
   // for now we let WillMakeList handle this
@@ -3524,17 +3486,19 @@ HTMLEditRules::WillIndent(Selection* aSe
   return NS_OK;
 }
 
 nsresult
 HTMLEditRules::WillCSSIndent(Selection* aSelection,
                              bool* aCancel,
                              bool* aHandled)
 {
-  if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   WillInsert(*aSelection, aCancel);
 
   // initialize out param
   // we want to ignore result of WillInsert()
   *aCancel = false;
   *aHandled = true;
 
@@ -3558,33 +3522,29 @@ HTMLEditRules::WillCSSIndent(Selection* 
                                          getter_AddRefs(node), &offset);
     NS_ENSURE_SUCCESS(rv, rv);
     nsCOMPtr<Element> block = mHTMLEditor->GetBlock(*node);
     if (block && HTMLEditUtils::IsListItem(block)) {
       liNode = block;
     }
   }
 
-  if (liNode)
-  {
+  if (liNode) {
     arrayOfNodes.AppendElement(*liNode);
-  }
-  else
-  {
+  } else {
     // convert the selection ranges into "promoted" selection ranges:
     // this basically just expands the range to include the immediate
     // block parent, and then further expands to include any ancestors
     // whose children are all in the range
     rv = GetNodesFromSelection(*aSelection, EditAction::indent, arrayOfNodes);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // if nothing visible in list, make an empty block
-  if (ListIsEmptyLine(arrayOfNodes))
-  {
+  if (ListIsEmptyLine(arrayOfNodes)) {
     // get selection location
     NS_ENSURE_STATE(aSelection->RangeCount());
     nsCOMPtr<nsINode> parent = aSelection->GetRangeAt(0)->GetStartParent();
     int32_t offset = aSelection->GetRangeAt(0)->StartOffset();
     NS_ENSURE_STATE(parent);
 
     // make sure we can put a block here
     rv = SplitAsNeeded(*nsGkAtoms::div, parent, offset);
@@ -3609,65 +3569,67 @@ HTMLEditRules::WillCSSIndent(Selection* 
     rv = aSelection->Collapse(theBlock, 0);
     // Don't restore the selection
     selectionRestorer.Abort();
     return rv;
   }
 
   // Ok, now go through all the nodes and put them in a blockquote,
   // or whatever is appropriate.  Wohoo!
-  int32_t i;
   nsCOMPtr<nsINode> curParent;
   nsCOMPtr<Element> curList, curQuote;
   nsCOMPtr<nsIContent> sibling;
   int32_t listCount = arrayOfNodes.Length();
-  for (i=0; i<listCount; i++)
-  {
+  for (int32_t i = 0; i < listCount; i++) {
     // here's where we actually figure out what to do
     NS_ENSURE_STATE(arrayOfNodes[i]->IsContent());
     nsCOMPtr<nsIContent> curNode = arrayOfNodes[i]->AsContent();
 
     // Ignore all non-editable nodes.  Leave them be.
     NS_ENSURE_STATE(mHTMLEditor);
-    if (!mHTMLEditor->IsEditable(curNode)) continue;
+    if (!mHTMLEditor->IsEditable(curNode)) {
+      continue;
+    }
 
     curParent = curNode->GetParentNode();
     int32_t offset = curParent ? curParent->IndexOf(curNode) : -1;
 
     // some logic for putting list items into nested lists...
     if (HTMLEditUtils::IsList(curParent)) {
       sibling = nullptr;
 
       // Check for whether we should join a list that follows curNode.
       // We do this if the next element is a list, and the list is of the
       // same type (li/ol) as curNode was a part it.
       NS_ENSURE_STATE(mHTMLEditor);
       sibling = mHTMLEditor->GetNextHTMLSibling(curNode);
-      if (sibling && HTMLEditUtils::IsList(sibling)) {
-        if (curParent->NodeInfo()->NameAtom() == sibling->NodeInfo()->NameAtom() &&
-            curParent->NodeInfo()->NamespaceID() == sibling->NodeInfo()->NamespaceID()) {
-          NS_ENSURE_STATE(mHTMLEditor);
-          rv = mHTMLEditor->MoveNode(curNode, sibling, 0);
-          NS_ENSURE_SUCCESS(rv, rv);
-          continue;
-        }
+      if (sibling && HTMLEditUtils::IsList(sibling) &&
+          curParent->NodeInfo()->NameAtom() ==
+            sibling->NodeInfo()->NameAtom() &&
+          curParent->NodeInfo()->NamespaceID() ==
+            sibling->NodeInfo()->NamespaceID()) {
+        NS_ENSURE_STATE(mHTMLEditor);
+        rv = mHTMLEditor->MoveNode(curNode, sibling, 0);
+        NS_ENSURE_SUCCESS(rv, rv);
+        continue;
       }
       // Check for whether we should join a list that preceeds curNode.
       // We do this if the previous element is a list, and the list is of
       // the same type (li/ol) as curNode was a part of.
       NS_ENSURE_STATE(mHTMLEditor);
       sibling = mHTMLEditor->GetPriorHTMLSibling(curNode);
-      if (sibling && HTMLEditUtils::IsList(sibling)) {
-        if (curParent->NodeInfo()->NameAtom() == sibling->NodeInfo()->NameAtom() &&
-            curParent->NodeInfo()->NamespaceID() == sibling->NodeInfo()->NamespaceID()) {
-          NS_ENSURE_STATE(mHTMLEditor);
-          rv = mHTMLEditor->MoveNode(curNode, sibling, -1);
-          NS_ENSURE_SUCCESS(rv, rv);
-          continue;
-        }
+      if (sibling && HTMLEditUtils::IsList(sibling) &&
+          curParent->NodeInfo()->NameAtom() ==
+            sibling->NodeInfo()->NameAtom() &&
+          curParent->NodeInfo()->NamespaceID() ==
+            sibling->NodeInfo()->NamespaceID()) {
+        NS_ENSURE_STATE(mHTMLEditor);
+        rv = mHTMLEditor->MoveNode(curNode, sibling, -1);
+        NS_ENSURE_SUCCESS(rv, rv);
+        continue;
       }
       sibling = nullptr;
 
       // check to see if curList is still appropriate.  Which it is if
       // curNode is still right after it in the same list.
       if (curList) {
         NS_ENSURE_STATE(mHTMLEditor);
         sibling = mHTMLEditor->GetPriorHTMLSibling(curNode);
@@ -3687,26 +3649,23 @@ HTMLEditRules::WillCSSIndent(Selection* 
         mNewBlock = curList;
       }
       // tuck the node into the end of the active list
       uint32_t listLen = curList->Length();
       NS_ENSURE_STATE(mHTMLEditor);
       rv = mHTMLEditor->MoveNode(curNode, curList, listLen);
       NS_ENSURE_SUCCESS(rv, rv);
     }
-
-    else // not a list item
-    {
+    // Not a list item.
+    else {
       if (curNode && IsBlockNode(*curNode)) {
         ChangeIndentation(*curNode->AsElement(), Change::plus);
         curQuote = nullptr;
-      }
-      else {
-        if (!curQuote)
-        {
+      } else {
+        if (!curQuote) {
           // First, check that our element can contain a div.
           if (!mTextEditor->CanContainTag(*curParent, *nsGkAtoms::div)) {
             return NS_OK; // cancelled
           }
 
           rv = SplitAsNeeded(*nsGkAtoms::div, curParent, offset);
           NS_ENSURE_SUCCESS(rv, rv);
           NS_ENSURE_STATE(mHTMLEditor);
@@ -3730,17 +3689,19 @@ HTMLEditRules::WillCSSIndent(Selection* 
   return NS_OK;
 }
 
 nsresult
 HTMLEditRules::WillHTMLIndent(Selection* aSelection,
                               bool* aCancel,
                               bool* aHandled)
 {
-  if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
   WillInsert(*aSelection, aCancel);
 
   // initialize out param
   // we want to ignore result of WillInsert()
   *aCancel = false;
   *aHandled = true;
 
   nsresult rv = NormalizeSelection(aSelection);
@@ -3757,18 +3718,17 @@ HTMLEditRules::WillHTMLIndent(Selection*
   GetPromotedRanges(*aSelection, arrayOfRanges, EditAction::indent);
 
   // use these ranges to contruct a list of nodes to act on.
   nsTArray<OwningNonNull<nsINode>> arrayOfNodes;
   rv = GetNodesForOperation(arrayOfRanges, arrayOfNodes, EditAction::indent);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // if nothing visible in list, make an empty block
-  if (ListIsEmptyLine(arrayOfNodes))
-  {
+  if (ListIsEmptyLine(arrayOfNodes)) {
     // get selection location
     NS_ENSURE_STATE(aSelection->RangeCount());
     nsCOMPtr<nsINode> parent = aSelection->GetRangeAt(0)->GetStartParent();
     int32_t offset = aSelection->GetRangeAt(0)->StartOffset();
     NS_ENSURE_STATE(parent);
 
     // make sure we can put a block here
     rv = SplitAsNeeded(*nsGkAtoms::blockquote, parent, offset);
@@ -3792,77 +3752,80 @@ HTMLEditRules::WillHTMLIndent(Selection*
     rv = aSelection->Collapse(theBlock, 0);
     // Don't restore the selection
     selectionRestorer.Abort();
     return rv;
   }
 
   // Ok, now go through all the nodes and put them in a blockquote,
   // or whatever is appropriate.  Wohoo!
-  int32_t i;
   nsCOMPtr<nsINode> curParent;
   nsCOMPtr<nsIContent> sibling;
   nsCOMPtr<Element> curList, curQuote, indentedLI;
   int32_t listCount = arrayOfNodes.Length();
-  for (i=0; i<listCount; i++)
-  {
+  for (int32_t i = 0; i < listCount; i++) {
     // here's where we actually figure out what to do
     NS_ENSURE_STATE(arrayOfNodes[i]->IsContent());
     nsCOMPtr<nsIContent> curNode = arrayOfNodes[i]->AsContent();
 
     // Ignore all non-editable nodes.  Leave them be.
     NS_ENSURE_STATE(mHTMLEditor);
-    if (!mHTMLEditor->IsEditable(curNode)) continue;
+    if (!mHTMLEditor->IsEditable(curNode)) {
+      continue;
+    }
 
     curParent = curNode->GetParentNode();
     int32_t offset = curParent ? curParent->IndexOf(curNode) : -1;
 
     // some logic for putting list items into nested lists...
     if (HTMLEditUtils::IsList(curParent)) {
       sibling = nullptr;
 
       // Check for whether we should join a list that follows curNode.
       // We do this if the next element is a list, and the list is of the
       // same type (li/ol) as curNode was a part it.
       NS_ENSURE_STATE(mHTMLEditor);
       sibling = mHTMLEditor->GetNextHTMLSibling(curNode);
       if (sibling && HTMLEditUtils::IsList(sibling) &&
-          curParent->NodeInfo()->NameAtom() == sibling->NodeInfo()->NameAtom() &&
-          curParent->NodeInfo()->NamespaceID() == sibling->NodeInfo()->NamespaceID()) {
+          curParent->NodeInfo()->NameAtom() ==
+            sibling->NodeInfo()->NameAtom() &&
+          curParent->NodeInfo()->NamespaceID() ==
+            sibling->NodeInfo()->NamespaceID()) {
         NS_ENSURE_STATE(mHTMLEditor);
         rv = mHTMLEditor->MoveNode(curNode, sibling, 0);
         NS_ENSURE_SUCCESS(rv, rv);
         continue;
       }
 
       // Check for whether we should join a list that preceeds curNode.
       // We do this if the previous element is a list, and the list is of
       // the same type (li/ol) as curNode was a part of.
       NS_ENSURE_STATE(mHTMLEditor);
       sibling = mHTMLEditor->GetPriorHTMLSibling(curNode);
       if (sibling && HTMLEditUtils::IsList(sibling) &&
-          curParent->NodeInfo()->NameAtom() == sibling->NodeInfo()->NameAtom() &&
-          curParent->NodeInfo()->NamespaceID() == sibling->NodeInfo()->NamespaceID()) {
+          curParent->NodeInfo()->NameAtom() ==
+            sibling->NodeInfo()->NameAtom() &&
+          curParent->NodeInfo()->NamespaceID() ==
+            sibling->NodeInfo()->NamespaceID()) {
         NS_ENSURE_STATE(mHTMLEditor);
         rv = mHTMLEditor->MoveNode(curNode, sibling, -1);
         NS_ENSURE_SUCCESS(rv, rv);
         continue;
       }
 
       sibling = nullptr;
 
       // check to see if curList is still appropriate.  Which it is if
       // curNode is still right after it in the same list.
       if (curList) {
         NS_ENSURE_STATE(mHTMLEditor);
         sibling = mHTMLEditor->GetPriorHTMLSibling(curNode);
       }
 
-      if (!curList || (sibling && sibling != curList) )
-      {
+      if (!curList || (sibling && sibling != curList)) {
         // create a new nested list of correct type
         rv =
           SplitAsNeeded(*curParent->NodeInfo()->NameAtom(), curParent, offset);
         NS_ENSURE_SUCCESS(rv, rv);
         NS_ENSURE_STATE(mHTMLEditor);
         curList = mHTMLEditor->CreateNode(curParent->NodeInfo()->NameAtom(),
                                           curParent, offset);
         NS_ENSURE_STATE(curList);
@@ -3872,72 +3835,65 @@ HTMLEditRules::WillHTMLIndent(Selection*
       }
       // tuck the node into the end of the active list
       NS_ENSURE_STATE(mHTMLEditor);
       rv = mHTMLEditor->MoveNode(curNode, curList, -1);
       NS_ENSURE_SUCCESS(rv, rv);
       // forget curQuote, if any
       curQuote = nullptr;
     }
-
-    else // not a list item, use blockquote?
-    {
+    // Not a list item, use blockquote?
+    else {
       // if we are inside a list item, we don't want to blockquote, we want
       // to sublist the list item.  We may have several nodes listed in the
       // array of nodes to act on, that are in the same list item.  Since
       // we only want to indent that li once, we must keep track of the most
       // recent indented list item, and not indent it if we find another node
       // to act on that is still inside the same li.
       nsCOMPtr<Element> listItem = IsInListItem(curNode);
       if (listItem) {
         if (indentedLI == listItem) {
           // already indented this list item
           continue;
         }
         curParent = listItem->GetParentNode();
         offset = curParent ? curParent->IndexOf(listItem) : -1;
         // check to see if curList is still appropriate.  Which it is if
         // curNode is still right after it in the same list.
-        if (curList)
-        {
+        if (curList) {
           sibling = nullptr;
           NS_ENSURE_STATE(mHTMLEditor);
           sibling = mHTMLEditor->GetPriorHTMLSibling(curNode);
         }
 
-        if (!curList || (sibling && sibling != curList) )
-        {
+        if (!curList || (sibling && sibling != curList)) {
           // create a new nested list of correct type
           rv = SplitAsNeeded(*curParent->NodeInfo()->NameAtom(), curParent,
                              offset);
           NS_ENSURE_SUCCESS(rv, rv);
           NS_ENSURE_STATE(mHTMLEditor);
           curList = mHTMLEditor->CreateNode(curParent->NodeInfo()->NameAtom(),
                                             curParent, offset);
           NS_ENSURE_STATE(curList);
         }
         NS_ENSURE_STATE(mHTMLEditor);
         rv = mHTMLEditor->MoveNode(listItem, curList, -1);
         NS_ENSURE_SUCCESS(rv, rv);
         // remember we indented this li
         indentedLI = listItem;
-      }
-
-      else
-      {
+      } else {
         // need to make a blockquote to put things in if we haven't already,
         // or if this node doesn't go in blockquote we used earlier.
         // One reason it might not go in prio blockquote is if we are now
         // in a different table cell.
         if (curQuote && InDifferentTableElements(curQuote, curNode)) {
           curQuote = nullptr;
         }
 
-        if (!curQuote)
-        {
+        if (!curQuote) {
           // First, check that our element can contain a blockquote.
           if (!mTextEditor->CanContainTag(*curParent, *nsGkAtoms::blockquote)) {
             return NS_OK; // cancelled
           }
 
           rv = SplitAsNeeded(*nsGkAtoms::blockquote, curParent, offset);
           NS_ENSURE_SUCCESS(rv, rv);
           NS_ENSURE_STATE(mHTMLEditor);
@@ -4066,31 +4022,30 @@ HTMLEditRules::WillOutdent(Selection& aS
       }
       // Do we have a blockquote that we are already committed to removing?
       if (curBlockQuote) {
         // If so, is this node a descendant?
         if (EditorUtils::IsDescendantOf(curNode, curBlockQuote)) {
           lastBQChild = curNode;
           // Then we don't need to do anything different for this node
           continue;
-        } else {
-          // Otherwise, we have progressed beyond end of curBlockQuote, so
-          // let's handle it now.  We need to remove the portion of
-          // curBlockQuote that contains [firstBQChild - lastBQChild].
-          rv = OutdentPartOfBlock(*curBlockQuote, *firstBQChild, *lastBQChild,
-                                  curBlockQuoteIsIndentedWithCSS,
-                                  getter_AddRefs(rememberedLeftBQ),
-                                  getter_AddRefs(rememberedRightBQ));
-          NS_ENSURE_SUCCESS(rv, rv);
-          curBlockQuote = nullptr;
-          firstBQChild = nullptr;
-          lastBQChild = nullptr;
-          curBlockQuoteIsIndentedWithCSS = false;
-          // Fall out and handle curNode
         }
+        // Otherwise, we have progressed beyond end of curBlockQuote, so
+        // let's handle it now.  We need to remove the portion of
+        // curBlockQuote that contains [firstBQChild - lastBQChild].
+        rv = OutdentPartOfBlock(*curBlockQuote, *firstBQChild, *lastBQChild,
+                                curBlockQuoteIsIndentedWithCSS,
+                                getter_AddRefs(rememberedLeftBQ),
+                                getter_AddRefs(rememberedRightBQ));
+        NS_ENSURE_SUCCESS(rv, rv);
+        curBlockQuote = nullptr;
+        firstBQChild = nullptr;
+        lastBQChild = nullptr;
+        curBlockQuoteIsIndentedWithCSS = false;
+        // Fall out and handle curNode
       }
 
       // Are we inside a blockquote?
       OwningNonNull<nsINode> n = curNode;
       curBlockQuoteIsIndentedWithCSS = false;
       // Keep looking up the hierarchy as long as we don't hit the body or the
       // active editing host or a table element (other than an entire table)
       while (!n->IsHTMLElement(nsGkAtoms::body) && 
@@ -4321,18 +4276,17 @@ HTMLEditRules::ConvertListType(Element* 
                                nsIAtom* aItemType)
 {
   MOZ_ASSERT(aList);
   MOZ_ASSERT(aOutList);
   MOZ_ASSERT(aListType);
   MOZ_ASSERT(aItemType);
 
   nsCOMPtr<nsINode> child = aList->GetFirstChild();
-  while (child)
-  {
+  while (child) {
     if (child->IsElement()) {
       dom::Element* element = child->AsElement();
       if (HTMLEditUtils::IsListItem(element) &&
           !element->IsHTMLElement(aItemType)) {
         child = mHTMLEditor->ReplaceContainer(element, aItemType);
         NS_ENSURE_STATE(child);
       } else if (HTMLEditUtils::IsList(element) &&
                  !element->IsHTMLElement(aListType)) {
@@ -4661,17 +4615,18 @@ HTMLEditRules::WillAlign(Selection& aSel
       rv = RemoveAlignment(GetAsDOMNode(curNode), aAlignType, true);
       NS_ENSURE_SUCCESS(rv, rv);
       if (useCSS) {
         htmlEditor->mCSSEditUtils->SetCSSEquivalentToHTMLStyle(
             curNode->AsElement(), nullptr, &NS_LITERAL_STRING("align"),
             &aAlignType, false);
         curDiv = nullptr;
         continue;
-      } else if (HTMLEditUtils::IsList(curParent)) {
+      }
+      if (HTMLEditUtils::IsList(curParent)) {
         // If we don't use CSS, add a contraint to list element: they have to
         // be inside another list, i.e., >= second level of nesting
         rv = AlignInnerBlocks(*curNode, &aAlignType);
         NS_ENSURE_SUCCESS(rv, rv);
         curDiv = nullptr;
         continue;
       }
       // Clear out curDiv so that we don't put nodes after this one into it
@@ -4746,66 +4701,60 @@ HTMLEditRules::AlignBlockContents(nsIDOM
 
   bool useCSS = mHTMLEditor->IsCSSEnabled();
 
   NS_ENSURE_STATE(mHTMLEditor);
   firstChild = mHTMLEditor->GetFirstEditableChild(*node);
   NS_ENSURE_STATE(mHTMLEditor);
   lastChild = mHTMLEditor->GetLastEditableChild(*node);
   NS_NAMED_LITERAL_STRING(attr, "align");
-  if (!firstChild)
-  {
+  if (!firstChild) {
     // this cell has no content, nothing to align
   } else if (firstChild == lastChild &&
              firstChild->IsHTMLElement(nsGkAtoms::div)) {
     // the cell already has a div containing all of its content: just
     // act on this div.
     nsCOMPtr<nsIDOMElement> divElem = do_QueryInterface(firstChild);
     if (useCSS) {
       NS_ENSURE_STATE(mHTMLEditor);
       nsresult rv = mHTMLEditor->SetAttributeOrEquivalent(divElem, attr,
                                                           *alignType, false);
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
-    }
-    else {
+    } else {
       NS_ENSURE_STATE(mHTMLEditor);
       nsresult rv = mHTMLEditor->SetAttribute(divElem, attr, *alignType);
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
     }
-  }
-  else
-  {
+  } else {
     // else we need to put in a div, set the alignment, and toss in all the children
     NS_ENSURE_STATE(mHTMLEditor);
     divNode = mHTMLEditor->CreateNode(nsGkAtoms::div, node, 0);
     NS_ENSURE_STATE(divNode);
     // set up the alignment on the div
     nsCOMPtr<nsIDOMElement> divElem = do_QueryInterface(divNode);
     if (useCSS) {
       NS_ENSURE_STATE(mHTMLEditor);
       nsresult rv =
         mHTMLEditor->SetAttributeOrEquivalent(divElem, attr, *alignType, false);
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
-    }
-    else {
+    } else {
       NS_ENSURE_STATE(mHTMLEditor);
       nsresult rv = mHTMLEditor->SetAttribute(divElem, attr, *alignType);
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
     }
     // tuck the children into the end of the active div
-    while (lastChild && (lastChild != divNode))
-    {
+    while (lastChild && (lastChild != divNode)) {
       NS_ENSURE_STATE(mHTMLEditor);
       nsresult rv = mHTMLEditor->MoveNode(lastChild, divNode, 0);
       NS_ENSURE_SUCCESS(rv, rv);
       NS_ENSURE_STATE(mHTMLEditor);
       lastChild = mHTMLEditor->GetLastEditableChild(*node);
     }
   }
   return NS_OK;
@@ -5040,17 +4989,17 @@ HTMLEditRules::ExpandSelectionForDeletio
       selStartNode = wsObj.mStartReasonNode->GetParentNode();
       selStartOffset = selStartNode ?
         selStartNode->IndexOf(wsObj.mStartReasonNode) : -1;
     }
   }
 
   // Find next visible thingy after end of selection
   if (selEndNode != selCommon && selEndNode != root) {
-    while (true) {
+    for (;;) {
       WSRunObject wsObj(mHTMLEditor, selEndNode, selEndOffset);
       wsObj.NextVisibleNode(selEndNode, selEndOffset, address_of(unused),
                             &visOffset, &wsType);
       if (wsType == WSType::br) {
         if (mHTMLEditor->IsVisBreak(wsObj.mEndReasonNode)) {
           break;
         }
         if (!firstBRParent) {
@@ -5132,17 +5081,19 @@ HTMLEditRules::NormalizeSelection(Select
     return NS_OK;
   }
 
   int32_t rangeCount;
   nsresult rv = inSelection->GetRangeCount(&rangeCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // we don't need to mess with cell selections, and we assume multirange selections are those.
-  if (rangeCount != 1) return NS_OK;
+  if (rangeCount != 1) {
+    return NS_OK;
+  }
 
   RefPtr<nsRange> range = inSelection->GetRangeAt(0);
   NS_ENSURE_TRUE(range, NS_ERROR_NULL_POINTER);
   nsCOMPtr<nsIDOMNode> startNode, endNode;
   int32_t startOffset, endOffset;
   nsCOMPtr<nsIDOMNode> newStartNode, newEndNode;
   int32_t newStartOffset, newEndOffset;
 
@@ -5176,29 +5127,27 @@ HTMLEditRules::NormalizeSelection(Select
   if (wsType != WSType::text && wsType != WSType::normalWS) {
     // eThisBlock and eOtherBlock conveniently distinquish cases
     // of going "down" into a block and "up" out of a block.
     if (wsEndObj.mStartReason == WSType::otherBlock) {
       // endpoint is just after the close of a block.
       nsCOMPtr<nsIDOMNode> child =
         GetAsDOMNode(mHTMLEditor->GetRightmostChild(wsEndObj.mStartReasonNode,
                                                     true));
-      if (child)
-      {
+      if (child) {
         newEndNode = EditorBase::GetNodeLocation(child, &newEndOffset);
         ++newEndOffset; // offset *after* child
       }
       // else block is empty - we can leave selection alone here, i think.
     } else if (wsEndObj.mStartReason == WSType::thisBlock) {
       // endpoint is just after start of this block
       nsCOMPtr<nsIDOMNode> child;
       NS_ENSURE_STATE(mHTMLEditor);
       mHTMLEditor->GetPriorHTMLNode(endNode, endOffset, address_of(child));
-      if (child)
-      {
+      if (child) {
         newEndNode = EditorBase::GetNodeLocation(child, &newEndOffset);
         ++newEndOffset; // offset *after* child
       }
       // else block is empty - we can leave selection alone here, i think.
     } else if (wsEndObj.mStartReason == WSType::br) {
       // endpoint is just after break.  lets adjust it to before it.
       newEndNode =
         EditorBase::GetNodeLocation(GetAsDOMNode(wsEndObj.mStartReasonNode),
@@ -5217,28 +5166,26 @@ HTMLEditRules::NormalizeSelection(Select
   if (wsType != WSType::text && wsType != WSType::normalWS) {
     // eThisBlock and eOtherBlock conveniently distinquish cases
     // of going "down" into a block and "up" out of a block.
     if (wsStartObj.mEndReason == WSType::otherBlock) {
       // startpoint is just before the start of a block.
       nsCOMPtr<nsIDOMNode> child =
         GetAsDOMNode(mHTMLEditor->GetLeftmostChild(wsStartObj.mEndReasonNode,
                                                    true));
-      if (child)
-      {
+      if (child) {
         newStartNode = EditorBase::GetNodeLocation(child, &newStartOffset);
       }
       // else block is empty - we can leave selection alone here, i think.
     } else if (wsStartObj.mEndReason == WSType::thisBlock) {
       // startpoint is just before end of this block
       nsCOMPtr<nsIDOMNode> child;
       NS_ENSURE_STATE(mHTMLEditor);
       mHTMLEditor->GetNextHTMLNode(startNode, startOffset, address_of(child));
-      if (child)
-      {
+      if (child) {
         newStartNode = EditorBase::GetNodeLocation(child, &newStartOffset);
       }
       // else block is empty - we can leave selection alone here, i think.
     } else if (wsStartObj.mEndReason == WSType::br) {
       // startpoint is just before a break.  lets adjust it to after it.
       newStartNode =
         EditorBase::GetNodeLocation(GetAsDOMNode(wsStartObj.mEndReasonNode),
                                     &newStartOffset);
@@ -5252,20 +5199,24 @@ HTMLEditRules::NormalizeSelection(Select
   // a block it was never in, etc.  There are a variety of strategies one might use to try to
   // detect these cases, but I think the most straightforward is to see if the adjusted locations
   // "cross" the old values: ie, new end before old start, or new start after old end.  If so
   // then just leave things alone.
 
   int16_t comp;
   comp = nsContentUtils::ComparePoints(startNode, startOffset,
                                        newEndNode, newEndOffset);
-  if (comp == 1) return NS_OK;  // new end before old start
+  if (comp == 1) {
+    return NS_OK;  // New end before old start.
+  }
   comp = nsContentUtils::ComparePoints(newStartNode, newStartOffset,
                                        endNode, endOffset);
-  if (comp == 1) return NS_OK;  // new start after old end
+  if (comp == 1) {
+    return NS_OK;  // New start after old end.
+  }
 
   // otherwise set selection to new values.
   inSelection->Collapse(newStartNode, newStartOffset);
   inSelection->Extend(newEndNode, newEndOffset);
   return NS_OK;
 }
 
 /**
@@ -5297,22 +5248,22 @@ HTMLEditRules::GetPromotedPoint(RulesEnd
     nsCOMPtr<nsIContent> content = do_QueryInterface(node), temp;
     // for text actions, we want to look backwards (or forwards, as
     // appropriate) for additional whitespace or nbsp's.  We may have to act on
     // these later even though they are outside of the initial selection.  Even
     // if they are in another node!
     while (content) {
       int32_t offset;
       if (aWhere == kStart) {
-        NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+        NS_ENSURE_TRUE_VOID(mHTMLEditor);
         mHTMLEditor->IsPrevCharInNodeWhitespace(content, *outOffset,
                                                 &isSpace, &isNBSP,
                                                 getter_AddRefs(temp), &offset);
       } else {
-        NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+        NS_ENSURE_TRUE_VOID(mHTMLEditor);
         mHTMLEditor->IsNextCharInNodeWhitespace(content, *outOffset,
                                                 &isSpace, &isNBSP,
                                                 getter_AddRefs(temp), &offset);
       }
       if (isSpace || isNBSP) {
         content = temp;
         *outOffset = offset;
       } else {
@@ -5336,33 +5287,33 @@ HTMLEditRules::GetPromotedPoint(RulesEnd
         return;
       }
       offset = node->GetParentNode()->IndexOf(node);
       node = node->GetParentNode();
     }
 
     // look back through any further inline nodes that aren't across a <br>
     // from us, and that are enclosed in the same block.
-    NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+    NS_ENSURE_TRUE_VOID(mHTMLEditor);
     nsCOMPtr<nsINode> priorNode =
       mHTMLEditor->GetPriorHTMLNode(node, offset, true);
 
     while (priorNode && priorNode->GetParentNode() &&
            mHTMLEditor && !mHTMLEditor->IsVisBreak(priorNode) &&
            !IsBlockNode(*priorNode)) {
       offset = priorNode->GetParentNode()->IndexOf(priorNode);
       node = priorNode->GetParentNode();
-      NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+      NS_ENSURE_TRUE_VOID(mHTMLEditor);
       priorNode = mHTMLEditor->GetPriorHTMLNode(node, offset, true);
     }
 
     // finding the real start for this point.  look up the tree for as long as
     // we are the first node in the container, and as long as we haven't hit
     // the body node.
-    NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+    NS_ENSURE_TRUE_VOID(mHTMLEditor);
     nsCOMPtr<nsIContent> nearNode =
       mHTMLEditor->GetPriorHTMLNode(node, offset, true);
     while (!nearNode && !node->IsHTMLElement(nsGkAtoms::body) &&
            node->GetParentNode()) {
       // some cutoffs are here: we don't need to also include them in the
       // aWhere == kEnd case.  as long as they are in one or the other it will
       // work.  special case for outdent: don't keep looking up if we have
       // found a blockquote element to act on
@@ -5377,27 +5328,27 @@ HTMLEditRules::GetPromotedPoint(RulesEnd
       // Don't walk past the editable section. Note that we need to check
       // before walking up to a parent because we need to return the parent
       // object, so the parent itself might not be in the editable area, but
       // it's OK if we're not performing a block-level action.
       bool blockLevelAction = actionID == EditAction::indent ||
                               actionID == EditAction::outdent ||
                               actionID == EditAction::align ||
                               actionID == EditAction::makeBasicBlock;
-      NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+      NS_ENSURE_TRUE_VOID(mHTMLEditor);
       if (!mHTMLEditor->IsDescendantOfEditorRoot(parent) &&
           (blockLevelAction || !mHTMLEditor ||
            !mHTMLEditor->IsDescendantOfEditorRoot(node))) {
-        NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+        NS_ENSURE_TRUE_VOID(mHTMLEditor);
         break;
       }
 
       node = parent;
       offset = parentOffset;
-      NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+      NS_ENSURE_TRUE_VOID(mHTMLEditor);
       nearNode = mHTMLEditor->GetPriorHTMLNode(node, offset, true);
     }
     *outNode = node->AsDOMNode();
     *outOffset = offset;
     return;
   }
 
   // aWhere == kEnd
@@ -5416,69 +5367,69 @@ HTMLEditRules::GetPromotedPoint(RulesEnd
   // us, and that are enclosed in the same block.
   NS_ENSURE_TRUE(mHTMLEditor, /* void */);
   nsCOMPtr<nsIContent> nextNode =
     mHTMLEditor->GetNextHTMLNode(node, offset, true);
 
   while (nextNode && !IsBlockNode(*nextNode) && nextNode->GetParentNode()) {
     offset = 1 + nextNode->GetParentNode()->IndexOf(nextNode);
     node = nextNode->GetParentNode();
-    NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+    NS_ENSURE_TRUE_VOID(mHTMLEditor);
     if (mHTMLEditor->IsVisBreak(nextNode)) {
       break;
     }
 
     // Check for newlines in pre-formatted text nodes.
     bool isPRE;
     mHTMLEditor->IsPreformatted(nextNode->AsDOMNode(), &isPRE);
     if (isPRE) {
       nsCOMPtr<nsIDOMText> textNode = do_QueryInterface(nextNode);
       if (textNode) {
         nsAutoString tempString;
         textNode->GetData(tempString);
         int32_t newlinePos = tempString.FindChar(nsCRT::LF);
         if (newlinePos >= 0) {
-          if ((uint32_t)newlinePos + 1 == tempString.Length()) {
+          if (static_cast<uint32_t>(newlinePos) + 1 == tempString.Length()) {
             // No need for special processing if the newline is at the end.
             break;
           }
           *outNode = nextNode->AsDOMNode();
           *outOffset = newlinePos + 1;
           return;
         }
       }
     }
-    NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+    NS_ENSURE_TRUE_VOID(mHTMLEditor);
     nextNode = mHTMLEditor->GetNextHTMLNode(node, offset, true);
   }
 
   // finding the real end for this point.  look up the tree for as long as we
   // are the last node in the container, and as long as we haven't hit the body
   // node.
-  NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+  NS_ENSURE_TRUE_VOID(mHTMLEditor);
   nsCOMPtr<nsIContent> nearNode =
     mHTMLEditor->GetNextHTMLNode(node, offset, true);
   while (!nearNode && !node->IsHTMLElement(nsGkAtoms::body) &&
          node->GetParentNode()) {
     int32_t parentOffset = node->GetParentNode()->IndexOf(node);
     nsCOMPtr<nsINode> parent = node->GetParentNode();
 
     // Don't walk past the editable section. Note that we need to check before
     // walking up to a parent because we need to return the parent object, so
     // the parent itself might not be in the editable area, but it's OK.
     if ((!mHTMLEditor || !mHTMLEditor->IsDescendantOfEditorRoot(node)) &&
         (!mHTMLEditor || !mHTMLEditor->IsDescendantOfEditorRoot(parent))) {
-      NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+      NS_ENSURE_TRUE_VOID(mHTMLEditor);
       break;
     }
 
     node = parent;
     // we want to be AFTER nearNode
     offset = parentOffset + 1;
-    NS_ENSURE_TRUE(mHTMLEditor, /* void */);
+    NS_ENSURE_TRUE_VOID(mHTMLEditor);
     nearNode = mHTMLEditor->GetNextHTMLNode(node, offset, true);
   }
   *outNode = node->AsDOMNode();
   *outOffset = offset;
 }
 
 /**
  * GetPromotedRanges() runs all the selection range endpoint through
@@ -5618,17 +5569,17 @@ HTMLEditRules::GetNodesForOperation(
         continue;
       }
       nsCOMPtr<nsIDOMText> textNode = do_QueryInterface(endParent);
       if (textNode) {
         int32_t offset = r->EndOffset();
         nsAutoString tempString;
         textNode->GetData(tempString);
 
-        if (0 < offset && offset < (int32_t)(tempString.Length())) {
+        if (0 < offset && offset < static_cast<int32_t>(tempString.Length())) {
           // Split the text node.
           nsCOMPtr<nsIDOMNode> tempNode;
           nsresult rv = htmlEditor->SplitNode(endParent->AsDOMNode(), offset,
                                               getter_AddRefs(tempNode));
           NS_ENSURE_SUCCESS(rv, rv);
 
           // Correct the range.
           // The new end parent becomes the parent node of the text.
@@ -5668,17 +5619,17 @@ HTMLEditRules::GetNodesForOperation(
     }
     NS_ENSURE_SUCCESS(rv, rv);
   }
   // Gather up a list of all the nodes
   for (auto& range : aArrayOfRanges) {
     DOMSubtreeIterator iter;
     nsresult rv = iter.Init(*range);
     NS_ENSURE_SUCCESS(rv, rv);
-    if (aOutArrayOfNodes.Length() == 0) {
+    if (aOutArrayOfNodes.IsEmpty()) {
       iter.AppendList(TrivialFunctor(), aOutArrayOfNodes);
     } else {
       // We don't want duplicates in aOutArrayOfNodes, so we use an
       // iterator/functor that only return nodes that are not already in
       // aOutArrayOfNodes.
       nsTArray<OwningNonNull<nsINode>> nodes;
       iter.AppendList(UniqueFunctor(aOutArrayOfNodes), nodes);
       aOutArrayOfNodes.AppendElements(nodes);
@@ -5691,21 +5642,22 @@ HTMLEditRules::GetNodesForOperation(
     for (int32_t i = aOutArrayOfNodes.Length() - 1; i >= 0; i--) {
       OwningNonNull<nsINode> node = aOutArrayOfNodes[i];
       if (HTMLEditUtils::IsListItem(node)) {
         int32_t j = i;
         aOutArrayOfNodes.RemoveElementAt(i);
         GetInnerContent(*node, aOutArrayOfNodes, &j);
       }
     }
+  }
   // Indent/outdent already do something special for list items, but we still
   // need to make sure we don't act on table elements
-  } else if (aOperationType == EditAction::outdent ||
-             aOperationType == EditAction::indent ||
-             aOperationType == EditAction::setAbsolutePosition) {
+  else if (aOperationType == EditAction::outdent ||
+           aOperationType == EditAction::indent ||
+           aOperationType == EditAction::setAbsolutePosition) {
     for (int32_t i = aOutArrayOfNodes.Length() - 1; i >= 0; i--) {
       OwningNonNull<nsINode> node = aOutArrayOfNodes[i];
       if (HTMLEditUtils::IsTableElementButNotTable(node)) {
         int32_t j = i;
         aOutArrayOfNodes.RemoveElementAt(i);
         GetInnerContent(*node, aOutArrayOfNodes, &j);
       }
     }
@@ -5783,17 +5735,17 @@ HTMLEditRules::GetListActionNodes(
         if (HTMLEditUtils::IsList(parent)) {
           aOutArrayOfNodes.AppendElement(*parent);
           break;
         }
       }
     }
     // If we didn't find any nodes this way, then try the normal way.  Perhaps
     // the selection spans multiple lists but with no common list parent.
-    if (aOutArrayOfNodes.Length()) {
+    if (!aOutArrayOfNodes.IsEmpty()) {
       return NS_OK;
     }
   }
 
   {
     // We don't like other people messing with our selection!
     AutoTransactionsConserveSelection dontSpazMySelection(htmlEditor);
 
@@ -5833,18 +5785,17 @@ void
 HTMLEditRules::LookInsideDivBQandList(
                  nsTArray<OwningNonNull<nsINode>>& aNodeArray)
 {
   NS_ENSURE_TRUE(mHTMLEditor, );
   RefPtr<HTMLEditor> htmlEditor(mHTMLEditor);
 
   // If there is only one node in the array, and it is a list, div, or
   // blockquote, then look inside of it until we find inner list or content.
-  int32_t listCount = aNodeArray.Length();
-  if (listCount != 1) {
+  if (aNodeArray.Length() != 1) {
     return;
   }
 
   OwningNonNull<nsINode> curNode = aNodeArray[0];
 
   while (curNode->IsHTMLElement(nsGkAtoms::div) ||
          HTMLEditUtils::IsList(curNode) ||
          curNode->IsHTMLElement(nsGkAtoms::blockquote)) {
@@ -5944,35 +5895,33 @@ HTMLEditRules::GetParagraphFormatNodes(
 nsresult
 HTMLEditRules::BustUpInlinesAtRangeEndpoints(RangeItem& item)
 {
   bool isCollapsed = ((item.startNode == item.endNode) && (item.startOffset == item.endOffset));
 
   nsCOMPtr<nsIContent> endInline = GetHighestInlineParent(*item.endNode);
 
   // if we have inline parents above range endpoints, split them
-  if (endInline && !isCollapsed)
-  {
+  if (endInline && !isCollapsed) {
     nsCOMPtr<nsINode> resultEndNode = endInline->GetParentNode();
     NS_ENSURE_STATE(mHTMLEditor);
     // item.endNode must be content if endInline isn't null
     int32_t resultEndOffset =
       mHTMLEditor->SplitNodeDeep(*endInline, *item.endNode->AsContent(),
                                  item.endOffset,
                                  EditorBase::EmptyContainers::no);
     NS_ENSURE_TRUE(resultEndOffset != -1, NS_ERROR_FAILURE);
     // reset range
     item.endNode = resultEndNode;
     item.endOffset = resultEndOffset;
   }
 
   nsCOMPtr<nsIContent> startInline = GetHighestInlineParent(*item.startNode);
 
-  if (startInline)
-  {
+  if (startInline) {
     nsCOMPtr<nsINode> resultStartNode = startInline->GetParentNode();
     NS_ENSURE_STATE(mHTMLEditor);
     int32_t resultStartOffset =
       mHTMLEditor->SplitNodeDeep(*startInline, *item.startNode->AsContent(),
                                  item.startOffset,
                                  EditorBase::EmptyContainers::no);
     NS_ENSURE_TRUE(resultStartOffset != -1, NS_ERROR_FAILURE);
     // reset range
@@ -5993,17 +5942,17 @@ HTMLEditRules::BustUpInlinesAtBRs(
 
   // First build up a list of all the break nodes inside the inline container.
   nsTArray<OwningNonNull<nsINode>> arrayOfBreaks;
   BRNodeFunctor functor;
   DOMIterator iter(aNode);
   iter.AppendList(functor, arrayOfBreaks);
 
   // If there aren't any breaks, just put inNode itself in the array
-  if (!arrayOfBreaks.Length()) {
+  if (arrayOfBreaks.IsEmpty()) {
     aOutArrayOfNodes.AppendElement(aNode);
     return NS_OK;
   }
 
   // Else we need to bust up inNode along all the breaks
   nsCOMPtr<nsINode> inlineParentNode = aNode.GetParentNode();
   nsCOMPtr<nsIContent> splitDeepNode = &aNode;
   nsCOMPtr<nsIContent> leftNode, rightNode;
@@ -6147,17 +6096,18 @@ Element*
 HTMLEditRules::IsInListItem(nsINode* aNode)
 {
   NS_ENSURE_TRUE(aNode, nullptr);
   if (HTMLEditUtils::IsListItem(aNode)) {
     return aNode->AsElement();
   }
 
   Element* parent = aNode->GetParentElement();
-  while (parent && mHTMLEditor && mHTMLEditor->IsDescendantOfEditorRoot(parent) &&
+  while (parent &&
+         mHTMLEditor && mHTMLEditor->IsDescendantOfEditorRoot(parent) &&
          !HTMLEditUtils::IsTableElement(parent)) {
     if (HTMLEditUtils::IsListItem(parent)) {
       return parent;
     }
     parent = parent->GetParentElement();
   }
   return nullptr;
 }
@@ -6387,18 +6337,17 @@ HTMLEditRules::SplitParagraph(nsIDOMNode
   NS_ENSURE_STATE(mHTMLEditor);
   NS_ENSURE_STATE(selNode->IsContent());
   mHTMLEditor->SplitNodeDeep(*para, *selNode->AsContent(), *aOffset,
                              HTMLEditor::EmptyContainers::yes,
                              getter_AddRefs(leftPara),
                              getter_AddRefs(rightPara));
   // get rid of the break, if it is visible (otherwise it may be needed to prevent an empty p)
   NS_ENSURE_STATE(mHTMLEditor);
-  if (mHTMLEditor->IsVisBreak(aBRNode))
-  {
+  if (mHTMLEditor->IsVisBreak(aBRNode)) {
     NS_ENSURE_STATE(mHTMLEditor);
     rv = mHTMLEditor->DeleteNode(aBRNode);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // remove ID attribute on the paragraph we just created
   nsCOMPtr<nsIDOMElement> rightElt = do_QueryInterface(rightPara);
   NS_ENSURE_STATE(mHTMLEditor);
@@ -6413,22 +6362,19 @@ HTMLEditRules::SplitParagraph(nsIDOMNode
 
   // selection to beginning of right hand para;
   // look inside any containers that are up front.
   nsCOMPtr<nsINode> rightParaNode = do_QueryInterface(rightPara);
   NS_ENSURE_STATE(mHTMLEditor && rightParaNode);
   nsCOMPtr<nsIDOMNode> child =
     GetAsDOMNode(mHTMLEditor->GetLeftmostChild(rightParaNode, true));
   if (mHTMLEditor->IsTextNode(child) ||
-      mHTMLEditor->IsContainer(child))
-  {
+      mHTMLEditor->IsContainer(child)) {
     aSelection->Collapse(child,0);
-  }
-  else
-  {
+  } else {
     int32_t offset;
     nsCOMPtr<nsIDOMNode> parent = EditorBase::GetNodeLocation(child, &offset);
     aSelection->Collapse(parent,offset);
   }
   return NS_OK;
 }
 
 /**
@@ -6693,25 +6639,24 @@ HTMLEditRules::RemoveBlockStyle(nsTArray
       NS_ENSURE_SUCCESS(rv, rv);
     } else if (IsInlineNode(curNode)) {
       if (curBlock) {
         // If so, is this node a descendant?
         if (EditorUtils::IsDescendantOf(curNode, curBlock)) {
           // Then we don't need to do anything different for this node
           lastNode = curNode->AsContent();
           continue;
-        } else {
-          // Otherwise, we have progressed beyond end of curBlock, so let's
-          // handle it now.  We need to remove the portion of curBlock that
-          // contains [firstNode - lastNode].
-          nsresult rv = RemovePartOfBlock(*curBlock, *firstNode, *lastNode);
-          NS_ENSURE_SUCCESS(rv, rv);
-          firstNode = lastNode = curBlock = nullptr;
-          // Fall out and handle curNode
         }
+        // Otherwise, we have progressed beyond end of curBlock, so let's
+        // handle it now.  We need to remove the portion of curBlock that
+        // contains [firstNode - lastNode].
+        nsresult rv = RemovePartOfBlock(*curBlock, *firstNode, *lastNode);
+        NS_ENSURE_SUCCESS(rv, rv);
+        firstNode = lastNode = curBlock = nullptr;
+        // Fall out and handle curNode
       }
       curBlock = htmlEditor->GetBlockNodeParent(curNode);
       if (curBlock && HTMLEditUtils::IsFormatNode(curBlock)) {
         firstNode = lastNode = curNode->AsContent();
       } else {
         // Not a block kind that we care about.
         curBlock = nullptr;
       }
@@ -6787,17 +6732,17 @@ HTMLEditRules::ApplyBlockStyle(nsTArray<
                                             nsGkAtoms::li,
                                             nsGkAtoms::blockquote,
                                             nsGkAtoms::div)) {
       // Forget any previous block used for previous inline nodes
       curBlock = nullptr;
       // Recursion time
       nsTArray<OwningNonNull<nsINode>> childArray;
       GetChildNodesForOperation(*curNode, childArray);
-      if (childArray.Length()) {
+      if (!childArray.IsEmpty()) {
         nsresult rv = ApplyBlockStyle(childArray, aBlockTag);
         NS_ENSURE_SUCCESS(rv, rv);
       } else {
         // Make sure we can put a block here
         nsresult rv = SplitAsNeeded(aBlockTag, curParent, offset);
         NS_ENSURE_SUCCESS(rv, rv);
         nsCOMPtr<Element> theBlock =
           htmlEditor->CreateNode(&aBlockTag, curParent, offset);
@@ -6888,16 +6833,17 @@ HTMLEditRules::SplitAsNeeded(nsIAtom& aT
   nsCOMPtr<nsINode> tagParent, splitNode;
   for (nsCOMPtr<nsINode> parent = inOutParent; parent;
        parent = parent->GetParentNode()) {
     // Sniffing up the parent tree until we find a legal place for the block
 
     // Don't leave the active editing host
     NS_ENSURE_STATE(mHTMLEditor);
     if (!mHTMLEditor->IsDescendantOfEditorRoot(parent)) {
+      // XXX Why do we need to check mHTMLEditor again here?
       NS_ENSURE_STATE(mHTMLEditor);
       if (parent != mHTMLEditor->GetActiveEditingHost()) {
         return NS_ERROR_FAILURE;
       }
     }
 
     NS_ENSURE_STATE(mHTMLEditor);
     if (mHTMLEditor->CanContainTag(*parent, aTag)) {
@@ -7007,18 +6953,17 @@ HTMLEditRules::GetTopEnclosingMailCite(n
 nsresult
 HTMLEditRules::CacheInlineStyles(nsIDOMNode* aNode)
 {
   NS_ENSURE_TRUE(aNode, NS_ERROR_NULL_POINTER);
 
   NS_ENSURE_STATE(mHTMLEditor);
   bool useCSS = mHTMLEditor->IsCSSEnabled();
 
-  for (int32_t j = 0; j < SIZE_STYLE_TABLE; ++j)
-  {
+  for (int32_t j = 0; j < SIZE_STYLE_TABLE; ++j) {
     // If type-in state is set, don't intervene
     bool typeInSet, unused;
     if (NS_WARN_IF(!mHTMLEditor)) {
       return NS_ERROR_UNEXPECTED;
     }
     mHTMLEditor->mTypeInState->GetTypingState(typeInSet, unused,
       mCachedStyles[j].tag, mCachedStyles[j].attr, nullptr);
     if (typeInSet) {
@@ -7029,26 +6974,23 @@ HTMLEditRules::CacheInlineStyles(nsIDOMN
     nsAutoString outValue;
     // Don't use CSS for <font size>, we don't support it usefully (bug 780035)
     if (!useCSS || (mCachedStyles[j].tag == nsGkAtoms::font &&
                     mCachedStyles[j].attr.EqualsLiteral("size"))) {
       NS_ENSURE_STATE(mHTMLEditor);
       mHTMLEditor->IsTextPropertySetByContent(aNode, mCachedStyles[j].tag,
                                               &(mCachedStyles[j].attr), nullptr,
                                               isSet, &outValue);
-    }
-    else
-    {
+    } else {
       NS_ENSURE_STATE(mHTMLEditor);
       mHTMLEditor->mCSSEditUtils->IsCSSEquivalentToHTMLInlineStyleSet(aNode,
         mCachedStyles[j].tag, &(mCachedStyles[j].attr), isSet, outValue,
         CSSEditUtils::eComputed);
     }
-    if (isSet)
-    {
+    if (isSet) {
       mCachedStyles[j].mPresent = true;
       mCachedStyles[j].value.Assign(outValue);
     }
   }
   return NS_OK;
 }
 
 nsresult
@@ -7127,17 +7069,17 @@ HTMLEditRules::ClearCachedStyles()
     mCachedStyles[j].mPresent = false;
     mCachedStyles[j].value.Truncate();
   }
 }
 
 void
 HTMLEditRules::AdjustSpecialBreaks()
 {
-  NS_ENSURE_TRUE(mHTMLEditor, );
+  NS_ENSURE_TRUE_VOID(mHTMLEditor);
 
   // Gather list of empty nodes
   nsTArray<OwningNonNull<nsINode>> nodeArray;
   EmptyEditableFunctor functor(mHTMLEditor);
   DOMIterator iter;
   if (NS_WARN_IF(NS_FAILED(iter.Init(*mDocChangeRange)))) {
     return;
   }
@@ -7200,48 +7142,41 @@ HTMLEditRules::PinSelectionToNewBlock(Se
   rv = range->SetEnd(selNode, selOffset);
   NS_ENSURE_SUCCESS(rv, rv);
   nsCOMPtr<nsIContent> block = mNewBlock.get();
   NS_ENSURE_TRUE(block, NS_ERROR_NO_INTERFACE);
   bool nodeBefore, nodeAfter;
   rv = nsRange::CompareNodeToRange(block, range, &nodeBefore, &nodeAfter);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (nodeBefore && nodeAfter)
+  if (nodeBefore && nodeAfter) {
     return NS_OK;  // selection is inside block
-  else if (nodeBefore)
-  {
+  } else if (nodeBefore) {
     // selection is after block.  put at end of block.
     nsCOMPtr<nsIDOMNode> tmp = GetAsDOMNode(mNewBlock);
     NS_ENSURE_STATE(mHTMLEditor);
     tmp = GetAsDOMNode(mHTMLEditor->GetLastEditableChild(*block));
     uint32_t endPoint;
     if (mHTMLEditor->IsTextNode(tmp) ||
-        mHTMLEditor->IsContainer(tmp))
-    {
+        mHTMLEditor->IsContainer(tmp)) {
       rv = EditorBase::GetLengthOfDOMNode(tmp, endPoint);
       NS_ENSURE_SUCCESS(rv, rv);
-    }
-    else
-    {
+    } else {
       tmp = EditorBase::GetNodeLocation(tmp, (int32_t*)&endPoint);
       endPoint++;  // want to be after this node
     }
     return aSelection->Collapse(tmp, (int32_t)endPoint);
-  }
-  else
-  {
+  } else {
     // selection is before block.  put at start of block.
     nsCOMPtr<nsIDOMNode> tmp = GetAsDOMNode(mNewBlock);
     NS_ENSURE_STATE(mHTMLEditor);
     tmp = GetAsDOMNode(mHTMLEditor->GetFirstEditableChild(*block));
     int32_t offset;
     if (mHTMLEditor->IsTextNode(tmp) ||
-        mHTMLEditor->IsContainer(tmp))
-    {
+        mHTMLEditor->IsContainer(tmp)) {
       tmp = EditorBase::GetNodeLocation(tmp, &offset);
     }
     return aSelection->Collapse(tmp, 0);
   }
 }
 
 void
 HTMLEditRules::CheckInterlinePosition(Selection& aSelection)
@@ -7304,18 +7239,17 @@ HTMLEditRules::AdjustSelection(Selection
   nsresult rv =
     mHTMLEditor->GetStartNodeAndOffset(aSelection,
                                        getter_AddRefs(selNode), &selOffset);
   NS_ENSURE_SUCCESS(rv, rv);
   temp = selNode;
 
   // are we in an editable node?
   NS_ENSURE_STATE(mHTMLEditor);
-  while (!mHTMLEditor->IsEditable(selNode))
-  {
+  while (!mHTMLEditor->IsEditable(selNode)) {
     // scan up the tree until we find an editable place to be
     selNode = EditorBase::GetNodeLocation(temp, &selOffset);
     NS_ENSURE_TRUE(selNode, NS_ERROR_FAILURE);
     temp = selNode;
     NS_ENSURE_STATE(mHTMLEditor);
   }
 
   // make sure we aren't in an empty block - user will see no cursor.  If this
@@ -7329,18 +7263,17 @@ HTMLEditRules::AdjustSelection(Selection
     rv = mHTMLEditor->IsEmptyNode(theblock, &bIsEmptyNode, false, false);
     NS_ENSURE_SUCCESS(rv, rv);
     // check if br can go into the destination node
     NS_ENSURE_STATE(mHTMLEditor);
     if (bIsEmptyNode && mHTMLEditor->CanContainTag(*selNode, *nsGkAtoms::br)) {
       NS_ENSURE_STATE(mHTMLEditor);
       nsCOMPtr<Element> rootNode = mHTMLEditor->GetRoot();
       NS_ENSURE_TRUE(rootNode, NS_ERROR_FAILURE);
-      if (selNode == rootNode)
-      {
+      if (selNode == rootNode) {
         // Our root node is completely empty. Don't add a <br> here.
         // AfterEditInner() will add one for us when it calls
         // CreateBogusNodeIfNeeded()!
         return NS_OK;
       }
 
       // we know we can skip the rest of this routine given the cirumstance
       return CreateMozBR(GetAsDOMNode(selNode), selOffset);
@@ -7355,43 +7288,39 @@ HTMLEditRules::AdjustSelection(Selection
   // do we need to insert a special mozBR?  We do if we are:
   // 1) prior node is in same block where selection is AND
   // 2) prior node is a br AND
   // 3) that br is not visible
 
   NS_ENSURE_STATE(mHTMLEditor);
   nsCOMPtr<nsIContent> nearNode =
     mHTMLEditor->GetPriorHTMLNode(selNode, selOffset);
-  if (nearNode)
-  {
+  if (nearNode) {
     // is nearNode also a descendant of same block?
     NS_ENSURE_STATE(mHTMLEditor);
     nsCOMPtr<Element> block = mHTMLEditor->GetBlock(*selNode);
     nsCOMPtr<Element> nearBlock = mHTMLEditor->GetBlockNodeParent(nearNode);
     if (block && block == nearBlock) {
       if (nearNode && TextEditUtils::IsBreak(nearNode)) {
         NS_ENSURE_STATE(mHTMLEditor);
-        if (!mHTMLEditor->IsVisBreak(nearNode))
-        {
+        if (!mHTMLEditor->IsVisBreak(nearNode)) {
           // need to insert special moz BR. Why?  Because if we don't
           // the user will see no new line for the break.  Also, things
           // like table cells won't grow in height.
           nsCOMPtr<nsIDOMNode> brNode;
           rv = CreateMozBR(GetAsDOMNode(selNode), selOffset,
                            getter_AddRefs(brNode));
           NS_ENSURE_SUCCESS(rv, rv);
           nsCOMPtr<nsIDOMNode> brParent =
             EditorBase::GetNodeLocation(brNode, &selOffset);
           // selection stays *before* moz-br, sticking to it
           aSelection->SetInterlinePosition(true);
           rv = aSelection->Collapse(brParent, selOffset);
           NS_ENSURE_SUCCESS(rv, rv);
-        }
-        else
-        {
+        } else {
           NS_ENSURE_STATE(mHTMLEditor);
           nsCOMPtr<nsIContent> nextNode =
             mHTMLEditor->GetNextHTMLNode(nearNode, true);
           if (nextNode && TextEditUtils::IsMozBR(nextNode)) {
             // selection between br and mozbr.  make it stick to mozbr
             // so that it will be on blank line.
             aSelection->SetInterlinePosition(true);
           }
@@ -7460,22 +7389,23 @@ HTMLEditRules::FindNearSelectableNode(ns
     NS_ENSURE_STATE(mHTMLEditor);
     nsresult rv =
       mHTMLEditor->GetNextHTMLNode(aSelNode, aSelOffset, address_of(nearNode));
     if (NS_WARN_IF(NS_FAILED(rv))) {
       return rv;
     }
   }
 
-  if (!nearNode) // try the other direction then
-  {
-    if (aDirection == nsIEditor::ePrevious)
+  // Try the other direction then.
+  if (!nearNode) {
+    if (aDirection == nsIEditor::ePrevious) {
       aDirection = nsIEditor::eNext;
-    else
+    } else {
       aDirection = nsIEditor::ePrevious;
+    }
 
     if (aDirection == nsIEditor::ePrevious) {
       NS_ENSURE_STATE(mHTMLEditor);
       nsresult rv = mHTMLEditor->GetPriorHTMLNode(aSelNode, aSelOffset,
                                                   address_of(nearNode));
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
@@ -7487,20 +7417,19 @@ HTMLEditRules::FindNearSelectableNode(ns
         return rv;
       }
     }
   }
 
   // scan in the right direction until we find an eligible text node,
   // but don't cross any breaks, images, or table elements.
   NS_ENSURE_STATE(mHTMLEditor);
-  while (nearNode && !(mHTMLEditor->IsTextNode(nearNode)
-                       || TextEditUtils::IsBreak(nearNode)
-                       || HTMLEditUtils::IsImage(nearNode)))
-  {
+  while (nearNode && !(mHTMLEditor->IsTextNode(nearNode) ||
+                       TextEditUtils::IsBreak(nearNode) ||
+                       HTMLEditUtils::IsImage(nearNode))) {
     curNode = nearNode;
     if (aDirection == nsIEditor::ePrevious) {
       NS_ENSURE_STATE(mHTMLEditor);
       nsresult rv =
         mHTMLEditor->GetPriorHTMLNode(curNode, address_of(nearNode));
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
@@ -7509,18 +7438,17 @@ HTMLEditRules::FindNearSelectableNode(ns
       nsresult rv = mHTMLEditor->GetNextHTMLNode(curNode, address_of(nearNode));
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
     }
     NS_ENSURE_STATE(mHTMLEditor);
   }
 
-  if (nearNode)
-  {
+  if (nearNode) {
     // don't cross any table elements
     if (InDifferentTableElements(nearNode, aSelNode)) {
       return NS_OK;
     }
 
     // otherwise, ok, we have found a good spot to put the selection
     *outSelectableNode = do_QueryInterface(nearNode);
   }
@@ -7703,31 +7631,31 @@ HTMLEditRules::SelectionEndpointInNode(n
   RefPtr<Selection> selection = mHTMLEditor->GetSelection();
   NS_ENSURE_STATE(selection);
 
   uint32_t rangeCount = selection->RangeCount();
   for (uint32_t rangeIdx = 0; rangeIdx < rangeCount; ++rangeIdx) {
     RefPtr<nsRange> range = selection->GetRangeAt(rangeIdx);
     nsCOMPtr<nsIDOMNode> startParent, endParent;
     range->GetStartContainer(getter_AddRefs(startParent));
-    if (startParent)
-    {
+    if (startParent) {
       if (node == startParent) {
         *aResult = true;
         return NS_OK;
       }
       if (EditorUtils::IsDescendantOf(startParent, node)) {
         *aResult = true;
         return NS_OK;
       }
     }
     range->GetEndContainer(getter_AddRefs(endParent));
-    if (startParent == endParent) continue;
-    if (endParent)
-    {
+    if (startParent == endParent) {
+      continue;
+    }
+    if (endParent) {
       if (node == endParent) {
         *aResult = true;
         return NS_OK;
       }
       if (EditorUtils::IsDescendantOf(endParent, node)) {
         *aResult = true;
         return NS_OK;
       }
@@ -7816,27 +7744,28 @@ HTMLEditRules::PopListItem(nsIDOMNode* a
     mHTMLEditor->IsFirstEditableChild(aListItem, &bIsFirstListItem);
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool bIsLastListItem;
   NS_ENSURE_STATE(mHTMLEditor);
   rv = mHTMLEditor->IsLastEditableChild(aListItem, &bIsLastListItem);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (!bIsFirstListItem && !bIsLastListItem)
-  {
+  if (!bIsFirstListItem && !bIsLastListItem) {
     // split the list
     nsCOMPtr<nsIDOMNode> newBlock;
     NS_ENSURE_STATE(mHTMLEditor);
     rv = mHTMLEditor->SplitNode(GetAsDOMNode(curParent), offset,
                                 getter_AddRefs(newBlock));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  if (!bIsFirstListItem) parOffset++;
+  if (!bIsFirstListItem) {
+    parOffset++;
+  }
 
   NS_ENSURE_STATE(mHTMLEditor);
   rv = mHTMLEditor->MoveNode(listItem, curParPar, parOffset);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // unwrap list item contents if they are no longer in a list
   if (!HTMLEditUtils::IsList(curParPar) &&
       HTMLEditUtils::IsListItem(listItem)) {
@@ -7908,18 +7837,17 @@ HTMLEditRules::ConfirmSelectionInBody()
 
   // check that selNode is inside body
   while (temp && !TextEditUtils::IsBody(temp)) {
     temp->GetParentNode(getter_AddRefs(parent));
     temp = parent;
   }
 
   // if we aren't in the body, force the issue
-  if (!temp)
-  {
+  if (!temp) {
 //    uncomment this to see when we get bad selections
 //    NS_NOTREACHED("selection not in body");
     selection->Collapse(rootElement, 0);
   }
 
   // get the selection end location
   NS_ENSURE_STATE(mHTMLEditor);
   rv = mHTMLEditor->GetEndNodeAndOffset(selection,
@@ -7929,18 +7857,17 @@ HTMLEditRules::ConfirmSelectionInBody()
 
   // check that selNode is inside body
   while (temp && !TextEditUtils::IsBody(temp)) {
     rv = temp->GetParentNode(getter_AddRefs(parent));
     temp = parent;
   }
 
   // if we aren't in the body, force the issue
-  if (!temp)
-  {
+  if (!temp) {
 //    uncomment this to see when we get bad selections
 //    NS_NOTREACHED("selection not in body");
     selection->Collapse(rootElement, 0);
   }
 
   // XXX This is the result of the last call of GetParentNode(), it doesn't
   //     make sense...
   return rv;
@@ -7957,52 +7884,49 @@ HTMLEditRules::UpdateDocChangeRange(nsRa
   nsresult rv = aRange->GetStartContainer(getter_AddRefs(startNode));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_STATE(mHTMLEditor);
   if (!mHTMLEditor->IsDescendantOfRoot(startNode)) {
     // just return - we don't need to adjust mDocChangeRange in this case
     return NS_OK;
   }
 
-  if (!mDocChangeRange)
-  {
+  if (!mDocChangeRange) {
     // clone aRange.
     mDocChangeRange = aRange->CloneRange();
-  }
-  else
-  {
+  } else {
     int16_t result;
 
     // compare starts of ranges
     rv = mDocChangeRange->CompareBoundaryPoints(nsIDOMRange::START_TO_START,
                                                 aRange, &result);
     if (rv == NS_ERROR_NOT_INITIALIZED) {
       // This will happen is mDocChangeRange is non-null, but the range is
       // uninitialized. In this case we'll set the start to aRange start.
       // The same test won't be needed further down since after we've set
       // the start the range will be collapsed to that point.
       result = 1;
       rv = NS_OK;
     }
     NS_ENSURE_SUCCESS(rv, rv);
-    if (result > 0)  // positive result means mDocChangeRange start is after aRange start
-    {
+    // Positive result means mDocChangeRange start is after aRange start.
+    if (result > 0) {
       int32_t startOffset;
       rv = aRange->GetStartOffset(&startOffset);
       NS_ENSURE_SUCCESS(rv, rv);
       rv = mDocChangeRange->SetStart(startNode, startOffset);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     // compare ends of ranges
     rv = mDocChangeRange->CompareBoundaryPoints(nsIDOMRange::END_TO_END,
                                                 aRange, &result);
     NS_ENSURE_SUCCESS(rv, rv);
-    if (result < 0)  // negative result means mDocChangeRange end is before aRange end
-    {
+    // Negative result means mDocChangeRange end is before aRange end.
+    if (result < 0) {
       nsCOMPtr<nsIDOMNode> endNode;
       int32_t endOffset;
       rv = aRange->GetEndContainer(getter_AddRefs(endNode));
       NS_ENSURE_SUCCESS(rv, rv);
       rv = aRange->GetEndOffset(&endOffset);
       NS_ENSURE_SUCCESS(rv, rv);
       rv = mDocChangeRange->SetEnd(endNode, endOffset);
       NS_ENSURE_SUCCESS(rv, rv);
@@ -8244,31 +8168,27 @@ HTMLEditRules::RemoveAlignment(nsIDOMNod
   NS_ENSURE_TRUE(aNode, NS_ERROR_NULL_POINTER);
 
   NS_ENSURE_STATE(mHTMLEditor);
   if (mHTMLEditor->IsTextNode(aNode) || HTMLEditUtils::IsTable(aNode)) {
     return NS_OK;
   }
 
   nsCOMPtr<nsIDOMNode> child = aNode,tmp;
-  if (aChildrenOnly)
-  {
+  if (aChildrenOnly) {
     aNode->GetFirstChild(getter_AddRefs(child));
   }
   NS_ENSURE_STATE(mHTMLEditor);
   bool useCSS = mHTMLEditor->IsCSSEnabled();
 
-  while (child)
-  {
+  while (child) {
     if (aChildrenOnly) {
       // get the next sibling right now because we could have to remove child
       child->GetNextSibling(getter_AddRefs(tmp));
-    }
-    else
-    {
+    } else {
       tmp = nullptr;
     }
     bool isBlock;
     NS_ENSURE_STATE(mHTMLEditor);
     nsresult rv = mHTMLEditor->NodeIsBlockStatic(child, &isBlock);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (EditorBase::NodeIsType(child, nsGkAtoms::center)) {
@@ -8292,18 +8212,17 @@ HTMLEditRules::RemoveAlignment(nsIDOMNod
       // the current node is a block element
       nsCOMPtr<nsIDOMElement> curElem = do_QueryInterface(child);
       if (HTMLEditUtils::SupportsAlignAttr(child)) {
         // remove the ALIGN attribute if this element can have it
         NS_ENSURE_STATE(mHTMLEditor);
         rv = mHTMLEditor->RemoveAttribute(curElem, NS_LITERAL_STRING("align"));
         NS_ENSURE_SUCCESS(rv, rv);
       }
-      if (useCSS)
-      {
+      if (useCSS) {
         if (HTMLEditUtils::IsTable(child) || HTMLEditUtils::IsHR(child)) {
           NS_ENSURE_STATE(mHTMLEditor);
           rv = mHTMLEditor->SetAttributeOrEquivalent(curElem,
                                                      NS_LITERAL_STRING("align"),
                                                      aAlignType, false);
           if (NS_WARN_IF(NS_FAILED(rv))) {
             return rv;
           }
@@ -8336,69 +8255,59 @@ HTMLEditRules::RemoveAlignment(nsIDOMNod
 nsresult
 HTMLEditRules::MakeSureElemStartsOrEndsOnCR(nsIDOMNode* aNode,
                                             bool aStarts)
 {
   nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
   NS_ENSURE_TRUE(node, NS_ERROR_NULL_POINTER);
 
   nsCOMPtr<nsIDOMNode> child;
-  if (aStarts)
-  {
+  if (aStarts) {
     NS_ENSURE_STATE(mHTMLEditor);
     child = GetAsDOMNode(mHTMLEditor->GetFirstEditableChild(*node));
-  }
-  else
-  {
+  } else {
     NS_ENSURE_STATE(mHTMLEditor);
     child = GetAsDOMNode(mHTMLEditor->GetLastEditableChild(*node));
   }
   NS_ENSURE_TRUE(child, NS_OK);
   bool isChildBlock;
   NS_ENSURE_STATE(mHTMLEditor);
   nsresult rv = mHTMLEditor->NodeIsBlockStatic(child, &isChildBlock);
   NS_ENSURE_SUCCESS(rv, rv);
   bool foundCR = false;
   if (isChildBlock || TextEditUtils::IsBreak(child)) {
     foundCR = true;
   } else {
     nsCOMPtr<nsIDOMNode> sibling;
-    if (aStarts)
-    {
+    if (aStarts) {
       NS_ENSURE_STATE(mHTMLEditor);
       rv = mHTMLEditor->GetPriorHTMLSibling(aNode, address_of(sibling));
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
-    }
-    else
-    {
+    } else {
       NS_ENSURE_STATE(mHTMLEditor);
       rv = mHTMLEditor->GetNextHTMLSibling(aNode, address_of(sibling));
       if (NS_WARN_IF(NS_FAILED(rv))) {
         return rv;
       }
     }
-    if (sibling)
-    {
+    if (sibling) {
       bool isBlock;
       NS_ENSURE_STATE(mHTMLEditor);
       rv = mHTMLEditor->NodeIsBlockStatic(sibling, &isBlock);
       NS_ENSURE_SUCCESS(rv, rv);
       if (isBlock || TextEditUtils::IsBreak(sibling)) {
         foundCR = true;
       }
-    }
-    else
-    {
+    } else {
       foundCR = true;
     }
   }
-  if (!foundCR)
-  {
+  if (!foundCR) {
     int32_t offset = 0;
     if (!aStarts) {
       nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
       NS_ENSURE_STATE(node);
       offset = node->GetChildCount();
     }
     nsCOMPtr<nsIDOMNode> brNode;
     NS_ENSURE_STATE(mHTMLEditor);
@@ -8463,40 +8372,40 @@ HTMLEditRules::ChangeIndentation(Element
   nsIAtom& marginProperty =
     MarginPropertyAtomForIndent(*htmlEditor->mCSSEditUtils, aElement);
   nsAutoString value;
   htmlEditor->mCSSEditUtils->GetSpecifiedProperty(aElement, marginProperty,
                                                   value);
   float f;
   nsCOMPtr<nsIAtom> unit;
   htmlEditor->mCSSEditUtils->ParseLength(value, &f, getter_AddRefs(unit));
-  if (0 == f) {
+  if (!f) {
     nsAutoString defaultLengthUnit;
     htmlEditor->mCSSEditUtils->GetDefaultLengthUnit(defaultLengthUnit);
     unit = NS_Atomize(defaultLengthUnit);
   }
   int8_t multiplier = aChange == Change::plus ? +1 : -1;
-  if        (nsGkAtoms::in == unit) {
-            f += NS_EDITOR_INDENT_INCREMENT_IN * multiplier;
+  if (nsGkAtoms::in == unit) {
+    f += NS_EDITOR_INDENT_INCREMENT_IN * multiplier;
   } else if (nsGkAtoms::cm == unit) {
-            f += NS_EDITOR_INDENT_INCREMENT_CM * multiplier;
+    f += NS_EDITOR_INDENT_INCREMENT_CM * multiplier;
   } else if (nsGkAtoms::mm == unit) {
-            f += NS_EDITOR_INDENT_INCREMENT_MM * multiplier;
+    f += NS_EDITOR_INDENT_INCREMENT_MM * multiplier;
   } else if (nsGkAtoms::pt == unit) {
-            f += NS_EDITOR_INDENT_INCREMENT_PT * multiplier;
+    f += NS_EDITOR_INDENT_INCREMENT_PT * multiplier;
   } else if (nsGkAtoms::pc == unit) {
-            f += NS_EDITOR_INDENT_INCREMENT_PC * multiplier;
+    f += NS_EDITOR_INDENT_INCREMENT_PC * multiplier;
   } else if (nsGkAtoms::em == unit) {
-            f += NS_EDITOR_INDENT_INCREMENT_EM * multiplier;
+    f += NS_EDITOR_INDENT_INCREMENT_EM * multiplier;
   } else if (nsGkAtoms::ex == unit) {
-            f += NS_EDITOR_INDENT_INCREMENT_EX * multiplier;
+    f += NS_EDITOR_INDENT_INCREMENT_EX * multiplier;
   } else if (nsGkAtoms::px == unit) {
-            f += NS_EDITOR_INDENT_INCREMENT_PX * multiplier;
+    f += NS_EDITOR_INDENT_INCREMENT_PX * multiplier;
   } else if (nsGkAtoms::percentage == unit) {
-            f += NS_EDITOR_INDENT_INCREMENT_PERCENT * multiplier;
+    f += NS_EDITOR_INDENT_INCREMENT_PERCENT * multiplier;
   }
 
   if (0 < f) {
     nsAutoString newValue;
     newValue.AppendFloat(f);
     newValue.Append(nsDependentAtomString(unit));
     htmlEditor->mCSSEditUtils->SetCSSProperty(aElement, marginProperty,
                                               newValue);
@@ -8724,17 +8633,19 @@ HTMLEditRules::DidAbsolutePosition()
     static_cast<nsIDOMElement*>(GetAsDOMNode(mNewBlock));
   return absPosHTMLEditor->AbsolutelyPositionElement(elt, true);
 }
 
 nsresult
 HTMLEditRules::WillRemoveAbsolutePosition(Selection* aSelection,
                                           bool* aCancel,
                                           bool* aHandled) {
-  if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
   WillInsert(*aSelection, aCancel);
 
   // initialize out param
   // we want to ignore aCancel from WillInsert()
   *aCancel = false;
   *aHandled = true;
 
   nsCOMPtr<nsIDOMElement>  elt;
@@ -8752,17 +8663,19 @@ HTMLEditRules::WillRemoveAbsolutePositio
 }
 
 nsresult
 HTMLEditRules::WillRelativeChangeZIndex(Selection* aSelection,
                                         int32_t aChange,
                                         bool* aCancel,
                                         bool* aHandled)
 {
-  if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
   WillInsert(*aSelection, aCancel);
 
   // initialize out param
   // we want to ignore aCancel from WillInsert()
   *aCancel = false;
   *aHandled = true;
 
   nsCOMPtr<nsIDOMElement>  elt;
--- a/editor/libeditor/HTMLEditUtils.cpp
+++ b/editor/libeditor/HTMLEditUtils.cpp
@@ -341,18 +341,17 @@ HTMLEditUtils::IsLink(nsIDOMNode *aNode)
 }
 
 bool
 HTMLEditUtils::IsLink(nsINode* aNode)
 {
   MOZ_ASSERT(aNode);
 
   nsCOMPtr<nsIDOMHTMLAnchorElement> anchor = do_QueryInterface(aNode);
-  if (anchor)
-  {
+  if (anchor) {
     nsAutoString tmpText;
     if (NS_SUCCEEDED(anchor->GetHref(tmpText)) && !tmpText.IsEmpty()) {
       return true;
     }
   }
   return false;
 }
 
--- a/editor/libeditor/HTMLEditor.cpp
+++ b/editor/libeditor/HTMLEditor.cpp
@@ -145,55 +145,54 @@ HTMLEditor::~HTMLEditor()
 
   //the autopointers will clear themselves up.
   //but we need to also remove the listeners or we have a leak
   RefPtr<Selection> selection = GetSelection();
   // if we don't get the selection, just skip this
   if (selection) {
     nsCOMPtr<nsISelectionListener>listener;
     listener = do_QueryInterface(mTypeInState);
-    if (listener)
-    {
+    if (listener) {
       selection->RemoveSelectionListener(listener);
     }
     listener = do_QueryInterface(mSelectionListenerP);
-    if (listener)
-    {
+    if (listener) {
       selection->RemoveSelectionListener(listener);
     }
   }
 
   mTypeInState = nullptr;
   mSelectionListenerP = nullptr;
 
   // free any default style propItems
   RemoveAllDefaultProperties();
 
-  if (mLinkHandler && mDocWeak)
-  {
+  if (mLinkHandler && mDocWeak) {
     nsCOMPtr<nsIPresShell> ps = GetPresShell();
 
-    if (ps && ps->GetPresContext())
-    {
+    if (ps && ps->GetPresContext()) {
       ps->GetPresContext()->SetLinkHandler(mLinkHandler);
     }
   }
 
   RemoveEventListeners();
 }
 
 void
 HTMLEditor::HideAnonymousEditingUIs()
 {
-  if (mAbsolutelyPositionedObject)
+  if (mAbsolutelyPositionedObject) {
     HideGrabber();
-  if (mInlineEditedCell)
+  }
+  if (mInlineEditedCell) {
     HideInlineTableEditingUI();
-  if (mResizedObject)
+  }
+  if (mResizedObject) {
     HideResizers();
+  }
 }
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(HTMLEditor)
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(HTMLEditor, TextEditor)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mTypeInState)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mStyleSheets)
 
@@ -256,64 +255,62 @@ HTMLEditor::Init(nsIDOMDocument* aDoc,
                  const nsAString& aInitialValue)
 {
   NS_PRECONDITION(aDoc && !aSelCon, "bad arg");
   NS_ENSURE_TRUE(aDoc, NS_ERROR_NULL_POINTER);
   MOZ_ASSERT(aInitialValue.IsEmpty(), "Non-empty initial values not supported");
 
   nsresult result = NS_OK, rulesRes = NS_OK;
 
-  if (1)
   {
     // block to scope AutoEditInitRulesTrigger
     AutoEditInitRulesTrigger rulesTrigger(this, rulesRes);
 
     // Init the plaintext editor
     result = TextEditor::Init(aDoc, aRoot, nullptr, aFlags, aInitialValue);
-    if (NS_FAILED(result)) { return result; }
+    if (NS_FAILED(result)) {
+      return result;
+    }
 
     // Init mutation observer
     nsCOMPtr<nsINode> document = do_QueryInterface(aDoc);
     document->AddMutationObserverUnlessExists(this);
 
     // disable Composer-only features
-    if (IsMailEditor())
-    {
+    if (IsMailEditor()) {
       SetAbsolutePositioningEnabled(false);
       SetSnapToGridEnabled(false);
     }
 
     // Init the HTML-CSS utils
     mCSSEditUtils = new CSSEditUtils(this);
 
     // disable links
     nsCOMPtr<nsIPresShell> presShell = GetPresShell();
     NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE);
     nsPresContext *context = presShell->GetPresContext();
     NS_ENSURE_TRUE(context, NS_ERROR_NULL_POINTER);
     if (!IsPlaintextEditor() && !IsInteractionAllowed()) {
       mLinkHandler = context->GetLinkHandler();
-
       context->SetLinkHandler(nullptr);
     }
 
     // init the type-in state
     mTypeInState = new TypeInState();
 
     // init the selection listener for image resizing
     mSelectionListenerP = new ResizerSelectionListener(this);
 
     if (!IsInteractionAllowed()) {
       // ignore any errors from this in case the file is missing
       AddOverrideStyleSheet(NS_LITERAL_STRING("resource://gre/res/EditorOverride.css"));
     }
 
     RefPtr<Selection> selection = GetSelection();
-    if (selection)
-    {
+    if (selection) {
       nsCOMPtr<nsISelectionListener>listener;
       listener = do_QueryInterface(mTypeInState);
       if (listener) {
         selection->AddSelectionListener(listener);
       }
       listener = do_QueryInterface(mSelectionListenerP);
       if (listener) {
         selection->AddSelectionListener(listener);
@@ -332,18 +329,17 @@ HTMLEditor::PreDestroy(bool aDestroyingF
     return NS_OK;
   }
 
   nsCOMPtr<nsINode> document = do_QueryReferent(mDocWeak);
   if (document) {
     document->RemoveMutationObserver(this);
   }
 
-  while (mStyleSheetURLs.Length())
-  {
+  while (!mStyleSheetURLs.IsEmpty()) {
     RemoveOverrideStyleSheet(mStyleSheetURLs[0]);
   }
 
   // Clean up after our anonymous content -- we don't want these nodes to
   // stay around (which they would, since the frames have an owning reference).
   HideAnonymousEditingUIs();
 
   return TextEditor::PreDestroy(aDestroyingFrames);
@@ -455,44 +451,40 @@ HTMLEditor::InstallEventListeners()
   HTMLEditorEventListener* listener =
     reinterpret_cast<HTMLEditorEventListener*>(mEventListener.get());
   return listener->Connect(this);
 }
 
 void
 HTMLEditor::RemoveEventListeners()
 {
-  if (!mDocWeak)
-  {
+  if (!mDocWeak) {
     return;
   }
 
   nsCOMPtr<nsIDOMEventTarget> target = GetDOMEventTarget();
 
-  if (target)
-  {
+  if (target) {
     // Both mMouseMotionListenerP and mResizeEventListenerP can be
     // registerd with other targets than the DOM event receiver that
     // we can reach from here. But nonetheless, unregister the event
     // listeners with the DOM event reveiver (if it's registerd with
     // other targets, it'll get unregisterd once the target goes
     // away).
 
-    if (mMouseMotionListenerP)
-    {
+    if (mMouseMotionListenerP) {
       // mMouseMotionListenerP might be registerd either as bubbling or
       // capturing, unregister by both.
       target->RemoveEventListener(NS_LITERAL_STRING("mousemove"),
                                   mMouseMotionListenerP, false);
       target->RemoveEventListener(NS_LITERAL_STRING("mousemove"),
                                   mMouseMotionListenerP, true);
     }
 
-    if (mResizeEventListenerP)
-    {
+    if (mResizeEventListenerP) {
       target->RemoveEventListener(NS_LITERAL_STRING("resize"),
                                   mResizeEventListenerP, false);
     }
   }
 
   mMouseMotionListenerP = nullptr;
   mResizeEventListenerP = nullptr;
 
@@ -792,17 +784,19 @@ HTMLEditor::NodeIsBlockStatic(const nsIN
 
   return isBlock;
 }
 
 nsresult
 HTMLEditor::NodeIsBlockStatic(nsIDOMNode* aNode,
                               bool* aIsBlock)
 {
-  if (!aNode || !aIsBlock) { return NS_ERROR_NULL_POINTER; }
+  if (!aNode || !aIsBlock) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   nsCOMPtr<dom::Element> element = do_QueryInterface(aNode);
   *aIsBlock = element && NodeIsBlockStatic(element);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditor::NodeIsBlock(nsIDOMNode* aNode,
@@ -1471,38 +1465,41 @@ HTMLEditor::NormalizeEOLInsertPosition(n
        see an offset > 0, if there were a prior node.
 
     3) We do not want to skip, if both the next and the previous visible things are breaks.
 
     4) We do not want to skip if the previous visible thing is in a different block
        than the insertion position.
   */
 
-  if (!IsBlockNode(firstNodeToInsert))
+  if (!IsBlockNode(firstNodeToInsert)) {
     return;
+  }
 
   WSRunObject wsObj(this, *insertParentNode, *insertOffset);
   nsCOMPtr<nsINode> nextVisNode, prevVisNode;
   int32_t nextVisOffset=0;
   WSType nextVisType;
   int32_t prevVisOffset=0;
   WSType prevVisType;
 
   nsCOMPtr<nsINode> parent(do_QueryInterface(*insertParentNode));
   wsObj.NextVisibleNode(parent, *insertOffset, address_of(nextVisNode), &nextVisOffset, &nextVisType);
-  if (!nextVisNode)
+  if (!nextVisNode) {
     return;
+  }
 
   if (!(nextVisType & WSType::br)) {
     return;
   }
 
   wsObj.PriorVisibleNode(parent, *insertOffset, address_of(prevVisNode), &prevVisOffset, &prevVisType);
-  if (!prevVisNode)
+  if (!prevVisNode) {
     return;
+  }
 
   if (prevVisType & WSType::br) {
     return;
   }
 
   if (prevVisType & WSType::thisBlock) {
     return;
   }
@@ -1540,37 +1537,34 @@ HTMLEditor::InsertElementAtSelection(nsI
   bool cancel, handled;
   TextRulesInfo ruleInfo(EditAction::insertElement);
   ruleInfo.insertElement = aElement;
   nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   if (cancel || NS_FAILED(rv)) {
     return rv;
   }
 
-  if (!handled)
-  {
-    if (aDeleteSelection)
-    {
+  if (!handled) {
+    if (aDeleteSelection) {
       if (!IsBlockNode(element)) {
         // E.g., inserting an image.  In this case we don't need to delete any
         // inline wrappers before we do the insertion.  Otherwise we let
         // DeleteSelectionAndPrepareToCreateNode do the deletion for us, which
         // calls DeleteSelection with aStripWrappers = eStrip.
         rv = DeleteSelection(nsIEditor::eNone, nsIEditor::eNoStrip);
         NS_ENSURE_SUCCESS(rv, rv);
       }
 
       nsresult result = DeleteSelectionAndPrepareToCreateNode();
       NS_ENSURE_SUCCESS(result, result);
     }
 
     // If deleting, selection will be collapsed.
     // so if not, we collapse it
-    if (!aDeleteSelection)
-    {
+    if (!aDeleteSelection) {
       // Named Anchor is a special case,
       // We collapse to insert element BEFORE the selection
       // For all other tags, we insert AFTER the selection
       if (HTMLEditUtils::IsNamedAnchor(node)) {
         selection->CollapseToStart();
       } else {
         selection->CollapseToEnd();
       }
@@ -1587,28 +1581,26 @@ HTMLEditor::InsertElementAtSelection(nsI
       NormalizeEOLInsertPosition(element, address_of(parentSelectedNode),
                                  &offsetForInsert);
 
       rv = InsertNodeAtPoint(node, address_of(parentSelectedNode),
                              &offsetForInsert, false);
       NS_ENSURE_SUCCESS(rv, rv);
       // Set caret after element, but check for special case
       //  of inserting table-related elements: set in first cell instead
-      if (!SetCaretInTableCell(aElement))
-      {
+      if (!SetCaretInTableCell(aElement)) {
         rv = SetCaretAfterElement(aElement);
         NS_ENSURE_SUCCESS(rv, rv);
       }
       // check for inserting a whole table at the end of a block. If so insert a br after it.
       if (HTMLEditUtils::IsTable(node)) {
         bool isLast;
         rv = IsLastEditableChild(node, &isLast);
         NS_ENSURE_SUCCESS(rv, rv);
-        if (isLast)
-        {
+        if (isLast) {
           nsCOMPtr<nsIDOMNode> brNode;
           rv = CreateBR(parentSelectedNode, offsetForInsert + 1,
                         address_of(brNode));
           NS_ENSURE_SUCCESS(rv, rv);
           selection->Collapse(parentSelectedNode, offsetForInsert+1);
         }
       }
     }
@@ -1666,18 +1658,17 @@ HTMLEditor::InsertNodeAtPoint(nsIDOMNode
       // someone is trying to put block content in a span.  So just put it
       // where we were originally asked.
       parent = topChild = origParent;
       break;
     }
     topChild = parent;
     parent = parent->GetParent();
   }
-  if (parent != topChild)
-  {
+  if (parent != topChild) {
     // we need to split some levels above the original selection parent
     int32_t offset = SplitNodeDeep(*topChild, *origParent, *ioOffset,
                                    aNoEmptyNodes ? EmptyContainers::no
                                                  : EmptyContainers::yes);
     NS_ENSURE_STATE(offset != -1);
     *ioParent = GetAsDOMNode(parent);
     *ioOffset = offset;
   }
@@ -1735,27 +1726,29 @@ HTMLEditor::SetCaretAfterElement(nsIDOME
   return selection->Collapse(parent, offsetInParent + 1);
 }
 
 NS_IMETHODIMP
 HTMLEditor::SetParagraphFormat(const nsAString& aParagraphFormat)
 {
   nsAutoString tag; tag.Assign(aParagraphFormat);
   ToLowerCase(tag);
-  if (tag.EqualsLiteral("dd") || tag.EqualsLiteral("dt"))
+  if (tag.EqualsLiteral("dd") || tag.EqualsLiteral("dt")) {
     return MakeDefinitionItem(tag);
-  else
-    return InsertBasicBlock(tag);
+  }
+  return InsertBasicBlock(tag);
 }
 
 NS_IMETHODIMP
 HTMLEditor::GetParagraphState(bool* aMixed,
                               nsAString& outFormat)
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
   NS_ENSURE_TRUE(aMixed, NS_ERROR_NULL_POINTER);
   RefPtr<HTMLEditRules> htmlRules =
     static_cast<HTMLEditRules*>(mRules.get());
 
   return htmlRules->GetParagraphState(aMixed, outFormat);
 }
 
 NS_IMETHODIMP
@@ -1850,18 +1843,17 @@ HTMLEditor::GetCSSBackgroundColorState(b
       nodeToExamine = nodeToExamine->GetParentNode();
     }
     do {
       // is the node to examine a block ?
       if (NodeIsBlockStatic(nodeToExamine)) {
         // yes it is a block; in that case, the text background color is transparent
         aOutColor.AssignLiteral("transparent");
         break;
-      }
-      else {
+      } else {
         // no, it's not; let's retrieve the computed style of background-color for the
         // node to examine
         mCSSEditUtils->GetComputedProperty(*nodeToExamine,
                                            *nsGkAtoms::backgroundColor,
                                            aOutColor);
         if (!aOutColor.EqualsLiteral("transparent")) {
           break;
         }
@@ -1919,70 +1911,80 @@ HTMLEditor::GetHTMLBackgroundColorState(
 }
 
 NS_IMETHODIMP
 HTMLEditor::GetListState(bool* aMixed,
                          bool* aOL,
                          bool* aUL,
                          bool* aDL)
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
   NS_ENSURE_TRUE(aMixed && aOL && aUL && aDL, NS_ERROR_NULL_POINTER);
   RefPtr<HTMLEditRules> htmlRules =
     static_cast<HTMLEditRules*>(mRules.get());
 
   return htmlRules->GetListState(aMixed, aOL, aUL, aDL);
 }
 
 NS_IMETHODIMP
 HTMLEditor::GetListItemState(bool* aMixed,
                              bool* aLI,
                              bool* aDT,
                              bool* aDD)
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
   NS_ENSURE_TRUE(aMixed && aLI && aDT && aDD, NS_ERROR_NULL_POINTER);
 
   RefPtr<HTMLEditRules> htmlRules =
     static_cast<HTMLEditRules*>(mRules.get());
 
   return htmlRules->GetListItemState(aMixed, aLI, aDT, aDD);
 }
 
 NS_IMETHODIMP
 HTMLEditor::GetAlignment(bool* aMixed,
                          nsIHTMLEditor::EAlignment* aAlign)
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
   NS_ENSURE_TRUE(aMixed && aAlign, NS_ERROR_NULL_POINTER);
   RefPtr<HTMLEditRules> htmlRules =
     static_cast<HTMLEditRules*>(mRules.get());
 
   return htmlRules->GetAlignment(aMixed, aAlign);
 }
 
 NS_IMETHODIMP
 HTMLEditor::GetIndentState(bool* aCanIndent,
                            bool* aCanOutdent)
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
   NS_ENSURE_TRUE(aCanIndent && aCanOutdent, NS_ERROR_NULL_POINTER);
 
   RefPtr<HTMLEditRules> htmlRules =
     static_cast<HTMLEditRules*>(mRules.get());
 
   return htmlRules->GetIndentState(aCanIndent, aCanOutdent);
 }
 
 NS_IMETHODIMP
 HTMLEditor::MakeOrChangeList(const nsAString& aListType,
                              bool entireList,
                              const nsAString& aBulletType)
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
 
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> rules(mRules);
 
   bool cancel, handled;
 
   AutoEditBatch beginBatching(this);
   AutoRules beginRulesSniffing(this, EditAction::makeList, nsIEditor::eNext);
@@ -1995,43 +1997,40 @@ HTMLEditor::MakeOrChangeList(const nsASt
   ruleInfo.blockType = &aListType;
   ruleInfo.entireList = entireList;
   ruleInfo.bulletType = &aBulletType;
   nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   if (cancel || NS_FAILED(rv)) {
     return rv;
   }
 
-  if (!handled)
-  {
+  if (!handled) {
     // Find out if the selection is collapsed:
     bool isCollapsed = selection->Collapsed();
 
     NS_ENSURE_TRUE(selection->GetRangeAt(0) &&
                    selection->GetRangeAt(0)->GetStartParent() &&
                    selection->GetRangeAt(0)->GetStartParent()->IsContent(),
                    NS_ERROR_FAILURE);
     OwningNonNull<nsIContent> node =
       *selection->GetRangeAt(0)->GetStartParent()->AsContent();
     int32_t offset = selection->GetRangeAt(0)->StartOffset();
 
-    if (isCollapsed)
-    {
+    if (isCollapsed) {
       // have to find a place to put the list
       nsCOMPtr<nsIContent> parent = node;
       nsCOMPtr<nsIContent> topChild = node;
 
       nsCOMPtr<nsIAtom> listAtom = NS_Atomize(aListType);
       while (!CanContainTag(*parent, *listAtom)) {
         topChild = parent;
         parent = parent->GetParent();
       }
 
-      if (parent != node)
-      {
+      if (parent != node) {
         // we need to split up to the child of parent
         offset = SplitNodeDeep(*topChild, *node, offset);
         NS_ENSURE_STATE(offset != -1);
       }
 
       // make a list
       nsCOMPtr<Element> newList = CreateNode(listAtom, parent, offset);
       NS_ENSURE_STATE(newList);
@@ -2044,48 +2043,54 @@ HTMLEditor::MakeOrChangeList(const nsASt
   }
 
   return rules->DidDoAction(selection, &ruleInfo, rv);
 }
 
 NS_IMETHODIMP
 HTMLEditor::RemoveList(const nsAString& aListType)
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
 
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> rules(mRules);
 
   bool cancel, handled;
 
   AutoEditBatch beginBatching(this);
   AutoRules beginRulesSniffing(this, EditAction::removeList, nsIEditor::eNext);
 
   // pre-process
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
 
   TextRulesInfo ruleInfo(EditAction::removeList);
-  if (aListType.LowerCaseEqualsLiteral("ol"))
+  if (aListType.LowerCaseEqualsLiteral("ol")) {
     ruleInfo.bOrdered = true;
-  else  ruleInfo.bOrdered = false;
+  } else {
+    ruleInfo.bOrdered = false;
+  }
   nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   if (cancel || NS_FAILED(rv)) {
     return rv;
   }
 
   // no default behavior for this yet.  what would it mean?
 
   return rules->DidDoAction(selection, &ruleInfo, rv);
 }
 
 nsresult
 HTMLEditor::MakeDefinitionItem(const nsAString& aItemType)
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
 
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> rules(mRules);
 
   bool cancel, handled;
 
   AutoEditBatch beginBatching(this);
   AutoRules beginRulesSniffing(this, EditAction::makeDefListItem,
@@ -2096,28 +2101,29 @@ HTMLEditor::MakeDefinitionItem(const nsA
   NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
   TextRulesInfo ruleInfo(EditAction::makeDefListItem);
   ruleInfo.blockType = &aItemType;
   nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   if (cancel || NS_FAILED(rv)) {
     return rv;
   }
 
-  if (!handled)
-  {
+  if (!handled) {
     // todo: no default for now.  we count on rules to handle it.
   }
 
   return rules->DidDoAction(selection, &ruleInfo, rv);
 }
 
 nsresult
 HTMLEditor::InsertBasicBlock(const nsAString& aBlockType)
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
 
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> rules(mRules);
 
   bool cancel, handled;
 
   AutoEditBatch beginBatching(this);
   AutoRules beginRulesSniffing(this, EditAction::makeBasicBlock,
@@ -2128,44 +2134,41 @@ HTMLEditor::InsertBasicBlock(const nsASt
   NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
   TextRulesInfo ruleInfo(EditAction::makeBasicBlock);
   ruleInfo.blockType = &aBlockType;
   nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   if (cancel || NS_FAILED(rv)) {
     return rv;
   }
 
-  if (!handled)
-  {
+  if (!handled) {
     // Find out if the selection is collapsed:
     bool isCollapsed = selection->Collapsed();
 
     NS_ENSURE_TRUE(selection->GetRangeAt(0) &&
                    selection->GetRangeAt(0)->GetStartParent() &&
                    selection->GetRangeAt(0)->GetStartParent()->IsContent(),
                    NS_ERROR_FAILURE);
     OwningNonNull<nsIContent> node =
       *selection->GetRangeAt(0)->GetStartParent()->AsContent();
     int32_t offset = selection->GetRangeAt(0)->StartOffset();
 
-    if (isCollapsed)
-    {
+    if (isCollapsed) {
       // have to find a place to put the block
       nsCOMPtr<nsIContent> parent = node;
       nsCOMPtr<nsIContent> topChild = node;
 
       nsCOMPtr<nsIAtom> blockAtom = NS_Atomize(aBlockType);
       while (!CanContainTag(*parent, *blockAtom)) {
         NS_ENSURE_TRUE(parent->GetParent(), NS_ERROR_FAILURE);
         topChild = parent;
         parent = parent->GetParent();
       }
 
-      if (parent != node)
-      {
+      if (parent != node) {
         // we need to split up to the child of parent
         offset = SplitNodeDeep(*topChild, *node, offset);
         NS_ENSURE_STATE(offset != -1);
       }
 
       // make a block
       nsCOMPtr<Element> newBlock = CreateNode(blockAtom, parent, offset);
       NS_ENSURE_STATE(newBlock);
@@ -2177,68 +2180,65 @@ HTMLEditor::InsertBasicBlock(const nsASt
   }
 
   return rules->DidDoAction(selection, &ruleInfo, rv);
 }
 
 NS_IMETHODIMP
 HTMLEditor::Indent(const nsAString& aIndent)
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
 
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> rules(mRules);
 
   bool cancel, handled;
   EditAction opID = EditAction::indent;
-  if (aIndent.LowerCaseEqualsLiteral("outdent"))
-  {
+  if (aIndent.LowerCaseEqualsLiteral("outdent")) {
     opID = EditAction::outdent;
   }
   AutoEditBatch beginBatching(this);
   AutoRules beginRulesSniffing(this, opID, nsIEditor::eNext);
 
   // pre-process
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
 
   TextRulesInfo ruleInfo(opID);
   nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   if (cancel || NS_FAILED(rv)) {
     return rv;
   }
 
-  if (!handled)
-  {
+  if (!handled) {
     // Do default - insert a blockquote node if selection collapsed
     bool isCollapsed = selection->Collapsed();
 
     NS_ENSURE_TRUE(selection->GetRangeAt(0) &&
                    selection->GetRangeAt(0)->GetStartParent() &&
                    selection->GetRangeAt(0)->GetStartParent()->IsContent(),
                    NS_ERROR_FAILURE);
     OwningNonNull<nsIContent> node =
       *selection->GetRangeAt(0)->GetStartParent()->AsContent();
     int32_t offset = selection->GetRangeAt(0)->StartOffset();
 
-    if (aIndent.EqualsLiteral("indent"))
-    {
-      if (isCollapsed)
-      {
+    if (aIndent.EqualsLiteral("indent")) {
+      if (isCollapsed) {
         // have to find a place to put the blockquote
         nsCOMPtr<nsIContent> parent = node;
         nsCOMPtr<nsIContent> topChild = node;
         while (!CanContainTag(*parent, *nsGkAtoms::blockquote)) {
           NS_ENSURE_TRUE(parent->GetParent(), NS_ERROR_FAILURE);
           topChild = parent;
           parent = parent->GetParent();
         }
 
-        if (parent != node)
-        {
+        if (parent != node) {
           // we need to split up to the child of parent
           offset = SplitNodeDeep(*topChild, *node, offset);
           NS_ENSURE_STATE(offset != -1);
         }
 
         // make a blockquote
         nsCOMPtr<Element> newBQ = CreateNode(nsGkAtoms::blockquote, parent, offset);
         NS_ENSURE_STATE(newBQ);
@@ -2421,133 +2421,123 @@ HTMLEditor::GetSelectedElement(const nsA
 
   nsCOMPtr<nsIDOMNode> endParent;
   rv = range->GetEndContainer(getter_AddRefs(endParent));
   NS_ENSURE_SUCCESS(rv, rv);
   rv = range->GetEndOffset(&endOffset);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Optimization for a single selected element
-  if (startParent && startParent == endParent && (endOffset-startOffset) == 1)
-  {
+  if (startParent && startParent == endParent && endOffset - startOffset == 1) {
     nsCOMPtr<nsIDOMNode> selectedNode = GetChildAt(startParent, startOffset);
     NS_ENSURE_SUCCESS(rv, NS_OK);
-    if (selectedNode)
-    {
+    if (selectedNode) {
       selectedNode->GetNodeName(domTagName);
       ToLowerCase(domTagName);
 
       // Test for appropriate node type requested
       if (anyTag || (TagName == domTagName) ||
           (isLinkTag && HTMLEditUtils::IsLink(selectedNode)) ||
           (isNamedAnchorTag && HTMLEditUtils::IsNamedAnchor(selectedNode))) {
         bNodeFound = true;
         selectedElement = do_QueryInterface(selectedNode);
       }
     }
   }
 
-  if (!bNodeFound)
-  {
-    if (isLinkTag)
-    {
+  if (!bNodeFound) {
+    if (isLinkTag) {
       // Link tag is a special case - we return the anchor node
       //  found for any selection that is totally within a link,
       //  included a collapsed selection (just a caret in a link)
       nsCOMPtr<nsIDOMNode> anchorNode;
       rv = selection->GetAnchorNode(getter_AddRefs(anchorNode));
       NS_ENSURE_SUCCESS(rv, rv);
       int32_t anchorOffset = -1;
-      if (anchorNode)
+      if (anchorNode) {
         selection->GetAnchorOffset(&anchorOffset);
+      }
 
       nsCOMPtr<nsIDOMNode> focusNode;
       rv = selection->GetFocusNode(getter_AddRefs(focusNode));
       NS_ENSURE_SUCCESS(rv, rv);
       int32_t focusOffset = -1;
-      if (focusNode)
+      if (focusNode) {
         selection->GetFocusOffset(&focusOffset);
+      }
 
       // Link node must be the same for both ends of selection
       if (NS_SUCCEEDED(rv) && anchorNode) {
         nsCOMPtr<nsIDOMElement> parentLinkOfAnchor;
         rv = GetElementOrParentByTagName(NS_LITERAL_STRING("href"),
                                          anchorNode,
                                          getter_AddRefs(parentLinkOfAnchor));
         // XXX: ERROR_HANDLING  can parentLinkOfAnchor be null?
         if (NS_SUCCEEDED(rv) && parentLinkOfAnchor) {
-          if (isCollapsed)
-          {
+          if (isCollapsed) {
             // We have just a caret in the link
             bNodeFound = true;
-          } else if(focusNode)
-          {  // Link node must be the same for both ends of selection
+          } else if (focusNode) {
+            // Link node must be the same for both ends of selection.
             nsCOMPtr<nsIDOMElement> parentLinkOfFocus;
             rv = GetElementOrParentByTagName(NS_LITERAL_STRING("href"),
                                              focusNode,
                                              getter_AddRefs(parentLinkOfFocus));
             if (NS_SUCCEEDED(rv) && parentLinkOfFocus == parentLinkOfAnchor) {
               bNodeFound = true;
             }
           }
 
           // We found a link node parent
           if (bNodeFound) {
             // GetElementOrParentByTagName addref'd this, so we don't need to do it here
             *aReturn = parentLinkOfAnchor;
             NS_IF_ADDREF(*aReturn);
             return NS_OK;
           }
-        }
-        else if (anchorOffset >= 0)  // Check if link node is the only thing selected
-        {
+        } else if (anchorOffset >= 0) {
+          // Check if link node is the only thing selected
           nsCOMPtr<nsIDOMNode> anchorChild;
           anchorChild = GetChildAt(anchorNode,anchorOffset);
           if (anchorChild && HTMLEditUtils::IsLink(anchorChild) &&
-              (anchorNode == focusNode) && focusOffset == (anchorOffset+1))
-          {
+              anchorNode == focusNode && focusOffset == anchorOffset + 1) {
             selectedElement = do_QueryInterface(anchorChild);
             bNodeFound = true;
           }
         }
       }
     }
 
-    if (!isCollapsed)   // Don't bother to examine selection if it is collapsed
-    {
+    if (!isCollapsed) {
       RefPtr<nsRange> currange = selection->GetRangeAt(0);
       if (currange) {
         nsCOMPtr<nsIContentIterator> iter =
           do_CreateInstance("@mozilla.org/content/post-content-iterator;1",
                             &rv);
         NS_ENSURE_SUCCESS(rv, rv);
 
         iter->Init(currange);
         // loop through the content iterator for each content node
-        while (!iter->IsDone())
-        {
+        while (!iter->IsDone()) {
           // Query interface to cast nsIContent to nsIDOMNode
           //  then get tagType to compare to  aTagName
           // Clone node of each desired type and append it to the aDomFrag
           selectedElement = do_QueryInterface(iter->GetCurrentNode());
-          if (selectedElement)
-          {
+          if (selectedElement) {
             // If we already found a node, then we have another element,
             //  thus there's not just one element selected
-            if (bNodeFound)
-            {
+            if (bNodeFound) {
               bNodeFound = false;
               break;
             }
 
             selectedElement->GetNodeName(domTagName);
             ToLowerCase(domTagName);
 
-            if (anyTag)
-            {
+            if (anyTag) {
               // Get name of first selected element
               selectedElement->GetTagName(TagName);
               ToLowerCase(TagName);
               anyTag = false;
             }
 
             // The "A" tag is a pain,
             //  used for both link(href is set) and "Named Anchor"
@@ -2555,18 +2545,17 @@ HTMLEditor::GetSelectedElement(const nsA
             if ((isLinkTag &&
                  HTMLEditUtils::IsLink(selectedNode)) ||
                 (isNamedAnchorTag &&
                  HTMLEditUtils::IsNamedAnchor(selectedNode))) {
               bNodeFound = true;
             } else if (TagName == domTagName) { // All other tag names are handled here
               bNodeFound = true;
             }
-            if (!bNodeFound)
-            {
+            if (!bNodeFound) {
               // Check if node we have is really part of the selection???
               break;
             }
           }
           iter->Next();
         }
       } else {
         // Should never get here?
@@ -2736,26 +2725,23 @@ HTMLEditor::SetHTMLBackgroundColor(const
   nsAutoString tagName;
   nsresult rv = GetSelectedOrParentTableElement(tagName, &selectedCount,
                                                 getter_AddRefs(element));
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool setColor = !aColor.IsEmpty();
 
   NS_NAMED_LITERAL_STRING(bgcolor, "bgcolor");
-  if (element)
-  {
-    if (selectedCount > 0)
-    {
+  if (element) {
+    if (selectedCount > 0) {
       // Traverse all selected cells
       nsCOMPtr<nsIDOMElement> cell;
       rv = GetFirstSelectedCell(nullptr, getter_AddRefs(cell));
       if (NS_SUCCEEDED(rv) && cell) {
-        while(cell)
-        {
+        while (cell) {
           rv = setColor ? SetAttribute(cell, bgcolor, aColor) :
                           RemoveAttribute(cell, bgcolor);
           if (NS_FAILED(rv)) {
             return rv;
           }
 
           GetNextSelectedCell(nullptr, getter_AddRefs(cell));
         }
@@ -2805,21 +2791,19 @@ HTMLEditor::GetLinkedObjects(nsIArray** 
   NS_ENSURE_TRUE(iter, NS_ERROR_NULL_POINTER);
   if (NS_SUCCEEDED(rv)) {
     nsCOMPtr<nsIDocument> doc = GetDocument();
     NS_ENSURE_TRUE(doc, NS_ERROR_UNEXPECTED);
 
     iter->Init(doc->GetRootElement());
 
     // loop through the content iterator for each content node
-    while (!iter->IsDone())
-    {
+    while (!iter->IsDone()) {
       nsCOMPtr<nsIDOMNode> node (do_QueryInterface(iter->GetCurrentNode()));
-      if (node)
-      {
+      if (node) {
         // Let nsURIRefObject make the hard decisions:
         nsCOMPtr<nsIURIRefObject> refObject;
         rv = NS_NewHTMLURIRefObject(getter_AddRefs(refObject), node);
         if (NS_SUCCEEDED(rv)) {
           nodes->AppendElement(refObject, false);
         }
       }
       iter->Next();
@@ -2830,37 +2814,37 @@ HTMLEditor::GetLinkedObjects(nsIArray** 
   return NS_OK;
 }
 
 
 NS_IMETHODIMP
 HTMLEditor::AddStyleSheet(const nsAString& aURL)
 {
   // Enable existing sheet if already loaded.
-  if (EnableExistingStyleSheet(aURL))
+  if (EnableExistingStyleSheet(aURL)) {
     return NS_OK;
+  }
 
   // Lose the previously-loaded sheet so there's nothing to replace
   // This pattern is different from Override methods because
   //  we must wait to remove mLastStyleSheetURL and add new sheet
   //  at the same time (in StyleSheetLoaded callback) so they are undoable together
   mLastStyleSheetURL.Truncate();
   return ReplaceStyleSheet(aURL);
 }
 
 NS_IMETHODIMP
 HTMLEditor::ReplaceStyleSheet(const nsAString& aURL)
 {
   // Enable existing sheet if already loaded.
-  if (EnableExistingStyleSheet(aURL))
-  {
+  if (EnableExistingStyleSheet(aURL)) {
     // Disable last sheet if not the same as new one
-    if (!mLastStyleSheetURL.IsEmpty() && !mLastStyleSheetURL.Equals(aURL))
+    if (!mLastStyleSheetURL.IsEmpty() && !mLastStyleSheetURL.Equals(aURL)) {
       return EnableStyleSheet(mLastStyleSheetURL, false);
-
+    }
     return NS_OK;
   }
 
   // Make sure the pres shell doesn't disappear during the load.
   NS_ENSURE_TRUE(mDocWeak, NS_ERROR_NOT_INITIALIZED);
   nsCOMPtr<nsIPresShell> ps = GetPresShell();
   NS_ENSURE_TRUE(ps, NS_ERROR_NOT_INITIALIZED);
 
@@ -2896,18 +2880,19 @@ HTMLEditor::RemoveStyleSheet(const nsASt
   return rv;
 }
 
 
 NS_IMETHODIMP
 HTMLEditor::AddOverrideStyleSheet(const nsAString& aURL)
 {
   // Enable existing sheet if already loaded.
-  if (EnableExistingStyleSheet(aURL))
+  if (EnableExistingStyleSheet(aURL)) {
     return NS_OK;
+  }
 
   // Make sure the pres shell doesn't disappear during the load.
   nsCOMPtr<nsIPresShell> ps = GetPresShell();
   NS_ENSURE_TRUE(ps, NS_ERROR_NOT_INITIALIZED);
 
   nsCOMPtr<nsIURI> uaURI;
   nsresult rv = NS_NewURI(getter_AddRefs(uaURI), aURL);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -2936,28 +2921,28 @@ HTMLEditor::AddOverrideStyleSheet(const 
   //Add URL and style sheet to our lists
   return AddNewStyleSheetToList(aURL, sheet);
 }
 
 NS_IMETHODIMP
 HTMLEditor::ReplaceOverrideStyleSheet(const nsAString& aURL)
 {
   // Enable existing sheet if already loaded.
-  if (EnableExistingStyleSheet(aURL))
-  {
+  if (EnableExistingStyleSheet(aURL)) {
     // Disable last sheet if not the same as new one
-    if (!mLastOverrideStyleSheetURL.IsEmpty() && !mLastOverrideStyleSheetURL.Equals(aURL))
+    if (!mLastOverrideStyleSheetURL.IsEmpty() &&
+        !mLastOverrideStyleSheetURL.Equals(aURL)) {
       return EnableStyleSheet(mLastOverrideStyleSheetURL, false);
-
+    }
     return NS_OK;
   }
   // Remove the previous sheet
-  if (!mLastOverrideStyleSheetURL.IsEmpty())
+  if (!mLastOverrideStyleSheetURL.IsEmpty()) {
     RemoveOverrideStyleSheet(mLastOverrideStyleSheetURL);
-
+  }
   return AddOverrideStyleSheet(aURL);
 }
 
 // Do NOT use transaction system for override style sheets
 NS_IMETHODIMP
 HTMLEditor::RemoveOverrideStyleSheet(const nsAString& aURL)
 {
   RefPtr<StyleSheet> sheet = GetStyleSheetForURL(aURL);
@@ -2999,57 +2984,60 @@ HTMLEditor::EnableStyleSheet(const nsASt
 }
 
 bool
 HTMLEditor::EnableExistingStyleSheet(const nsAString& aURL)
 {
   RefPtr<StyleSheet> sheet = GetStyleSheetForURL(aURL);
 
   // Enable sheet if already loaded.
-  if (sheet)
-  {
-    // Ensure the style sheet is owned by our document.
-    nsCOMPtr<nsIDocument> doc = do_QueryReferent(mDocWeak);
-    sheet->SetOwningDocument(doc);
-
-    if (sheet->IsServo()) {
-      // XXXheycam ServoStyleSheets don't support being enabled/disabled yet.
-      NS_ERROR("stylo: ServoStyleSheets can't be disabled yet");
-      return true;
-    }
-    sheet->AsGecko()->SetDisabled(false);
+  if (!sheet) {
+    return false;
+  }
+
+  // Ensure the style sheet is owned by our document.
+  nsCOMPtr<nsIDocument> doc = do_QueryReferent(mDocWeak);
+  sheet->SetOwningDocument(doc);
+
+  if (sheet->IsServo()) {
+    // XXXheycam ServoStyleSheets don't support being enabled/disabled yet.
+    NS_ERROR("stylo: ServoStyleSheets can't be disabled yet");
     return true;
   }
-  return false;
+  sheet->AsGecko()->SetDisabled(false);
+  return true;
 }
 
 nsresult
 HTMLEditor::AddNewStyleSheetToList(const nsAString& aURL,
                                    StyleSheet* aStyleSheet)
 {
   uint32_t countSS = mStyleSheets.Length();
   uint32_t countU = mStyleSheetURLs.Length();
 
-  if (countSS != countU)
+  if (countSS != countU) {
     return NS_ERROR_UNEXPECTED;
-
-  if (!mStyleSheetURLs.AppendElement(aURL))
+  }
+
+  if (!mStyleSheetURLs.AppendElement(aURL)) {
     return NS_ERROR_UNEXPECTED;
+  }
 
   return mStyleSheets.AppendElement(aStyleSheet) ? NS_OK : NS_ERROR_UNEXPECTED;
 }
 
 nsresult
 HTMLEditor::RemoveStyleSheetFromList(const nsAString& aURL)
 {
   // is it already in the list?
   size_t foundIndex;
   foundIndex = mStyleSheetURLs.IndexOf(aURL);
-  if (foundIndex == mStyleSheetURLs.NoIndex)
+  if (foundIndex == mStyleSheetURLs.NoIndex) {
     return NS_ERROR_FAILURE;
+  }
 
   // Attempt both removals; if one fails there's not much we can do.
   mStyleSheets.RemoveElementAt(foundIndex);
   mStyleSheetURLs.RemoveElementAt(foundIndex);
 
   return NS_OK;
 }
 
@@ -3070,18 +3058,19 @@ HTMLEditor::GetStyleSheetForURL(const ns
 void
 HTMLEditor::GetURLForStyleSheet(StyleSheet* aStyleSheet,
                                 nsAString& aURL)
 {
   // is it already in the list?
   int32_t foundIndex = mStyleSheets.IndexOf(aStyleSheet);
 
   // Don't fail if we don't find it in our list
-  if (foundIndex == -1)
+  if (foundIndex == -1) {
     return;
+  }
 
   // Found it in the list!
   aURL = mStyleSheetURLs[foundIndex];
 }
 
 NS_IMETHODIMP
 HTMLEditor::GetEmbeddedObjects(nsIArray** aNodeList)
 {
@@ -3403,29 +3392,27 @@ HTMLEditor::GetHeadContentsAsHTML(nsAStr
 
   // Selection always includes <body></body>,
   //  so terminate there
   nsReadingIterator<char16_t> findIter,endFindIter;
   aOutputString.BeginReading(findIter);
   aOutputString.EndReading(endFindIter);
   //counting on our parser to always lower case!!!
   if (CaseInsensitiveFindInReadable(NS_LITERAL_STRING("<body"),
-                                    findIter, endFindIter))
-  {
+                                    findIter, endFindIter)) {
     nsReadingIterator<char16_t> beginIter;
     aOutputString.BeginReading(beginIter);
     int32_t offset = Distance(beginIter, findIter);//get the distance
 
     nsWritingIterator<char16_t> writeIter;
     aOutputString.BeginWriting(writeIter);
     // Ensure the string ends in a newline
     char16_t newline ('\n');
     findIter.advance(-1);
-    if (offset ==0 || (offset >0 &&  (*findIter) != newline)) //check for 0
-    {
+    if (!offset || (offset > 0 && (*findIter) != newline)) {
       writeIter.advance(offset);
       *writeIter = newline;
       aOutputString.Truncate(offset+1);
     }
   }
   return NS_OK;
 }
 
@@ -3561,31 +3548,32 @@ HTMLEditor::IsContainer(nsIDOMNode* aNod
   }
   return IsContainer(node);
 }
 
 
 nsresult
 HTMLEditor::SelectEntireDocument(Selection* aSelection)
 {
-  if (!aSelection || !mRules) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !mRules) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> rules(mRules);
 
   // get editor root node
   nsCOMPtr<nsIDOMElement> rootElement = do_QueryInterface(GetRoot());
 
   // is doc empty?
   bool bDocIsEmpty;
   nsresult rv = rules->DocumentIsEmpty(&bDocIsEmpty);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (bDocIsEmpty)
-  {
+  if (bDocIsEmpty) {
     // if its empty dont select entire doc - that would select the bogus node
     return aSelection->Collapse(rootElement, 0);
   }
 
   return EditorBase::SelectEntireDocument(aSelection);
 }
 
 NS_IMETHODIMP
@@ -3650,64 +3638,57 @@ HTMLEditor::IsTextPropertySetByContent(n
                                        nsAString* outValue)
 {
   nsresult result;
   aIsSet = false;  // must be initialized to false for code below to work
   nsAutoString propName;
   aProperty->ToString(propName);
   nsCOMPtr<nsIDOMNode>node = aNode;
 
-  while (node)
-  {
+  while (node) {
     nsCOMPtr<nsIDOMElement>element;
     element = do_QueryInterface(node);
-    if (element)
-    {
+    if (element) {
       nsAutoString tag, value;
       element->GetTagName(tag);
-      if (propName.Equals(tag, nsCaseInsensitiveStringComparator()))
-      {
+      if (propName.Equals(tag, nsCaseInsensitiveStringComparator())) {
         bool found = false;
-        if (aAttribute && 0!=aAttribute->Length())
-        {
+        if (aAttribute && !aAttribute->IsEmpty()) {
           element->GetAttribute(*aAttribute, value);
-          if (outValue) *outValue = value;
-          if (!value.IsEmpty())
-          {
+          if (outValue) {
+            *outValue = value;
+          }
+          if (!value.IsEmpty()) {
             if (!aValue) {
               found = true;
-            }
-            else
-            {
+            } else {
               nsString tString(*aValue);
               if (tString.Equals(value, nsCaseInsensitiveStringComparator())) {
                 found = true;
-              }
-              else {  // we found the prop with the attribute, but the value doesn't match
+              } else {
+                // We found the prop with the attribute, but the value doesn't
+                // match.
                 break;
               }
             }
           }
-        }
-        else {
+        } else {
           found = true;
         }
-        if (found)
-        {
+        if (found) {
           aIsSet = true;
           break;
         }
       }
     }
     nsCOMPtr<nsIDOMNode>temp;
     result = node->GetParentNode(getter_AddRefs(temp));
     if (NS_SUCCEEDED(result) && temp) {
       node = temp;
-    }
-    else {
+    } else {
       node = nullptr;
     }
   }
 }
 
 bool
 HTMLEditor::SetCaretInTableCell(nsIDOMElement* aElement)
 {
@@ -3781,44 +3762,41 @@ HTMLEditor::CollapseAdjacentTextNodes(ns
   // build a list of editable text nodes
   nsresult result;
   nsCOMPtr<nsIContentIterator> iter =
     do_CreateInstance("@mozilla.org/content/subtree-content-iterator;1", &result);
   NS_ENSURE_SUCCESS(result, result);
 
   iter->Init(aInRange);
 
-  while (!iter->IsDone())
-  {
+  while (!iter->IsDone()) {
     nsINode* node = iter->GetCurrentNode();
     if (node->NodeType() == nsIDOMNode::TEXT_NODE &&
         IsEditable(static_cast<nsIContent*>(node))) {
       nsCOMPtr<nsIDOMNode> domNode = do_QueryInterface(node);
       textNodes.AppendElement(domNode);
     }
 
     iter->Next();
   }
 
   // now that I have a list of text nodes, collapse adjacent text nodes
   // NOTE: assumption that JoinNodes keeps the righthand node
-  while (textNodes.Length() > 1)
-  {
+  while (textNodes.Length() > 1) {
     // we assume a textNodes entry can't be nullptr
     nsIDOMNode *leftTextNode = textNodes[0];
     nsIDOMNode *rightTextNode = textNodes[1];
     NS_ASSERTION(leftTextNode && rightTextNode,"left or rightTextNode null in CollapseAdjacentTextNodes");
 
     // get the prev sibling of the right node, and see if its leftTextNode
     nsCOMPtr<nsIDOMNode> prevSibOfRightNode;
     result =
       rightTextNode->GetPreviousSibling(getter_AddRefs(prevSibOfRightNode));
     NS_ENSURE_SUCCESS(result, result);
-    if (prevSibOfRightNode && (prevSibOfRightNode == leftTextNode))
-    {
+    if (prevSibOfRightNode && prevSibOfRightNode == leftTextNode) {
       nsCOMPtr<nsIDOMNode> parent;
       result = rightTextNode->GetParentNode(getter_AddRefs(parent));
       NS_ENSURE_SUCCESS(result, result);
       NS_ENSURE_TRUE(parent, NS_ERROR_NULL_POINTER);
       result = JoinNodes(leftTextNode, rightTextNode, parent);
       NS_ENSURE_SUCCESS(result, result);
     }
 
@@ -4273,52 +4251,45 @@ HTMLEditor::IsVisTextNode(nsIContent* aN
 {
   MOZ_ASSERT(aNode);
   MOZ_ASSERT(aNode->NodeType() == nsIDOMNode::TEXT_NODE);
   MOZ_ASSERT(outIsEmptyNode);
 
   *outIsEmptyNode = true;
 
   uint32_t length = aNode->TextLength();
-  if (aSafeToAskFrames)
-  {
+  if (aSafeToAskFrames) {
     nsCOMPtr<nsISelectionController> selCon;
     nsresult rv = GetSelectionController(getter_AddRefs(selCon));
     NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(selCon, NS_ERROR_FAILURE);
     bool isVisible = false;
     // ask the selection controller for information about whether any
     // of the data in the node is really rendered.  This is really
     // something that frames know about, but we aren't supposed to talk to frames.
     // So we put a call in the selection controller interface, since it's already
     // in bed with frames anyway.  (this is a fix for bug 22227, and a
     // partial fix for bug 46209)
     rv = selCon->CheckVisibilityContent(aNode, 0, length, &isVisible);
     NS_ENSURE_SUCCESS(rv, rv);
-    if (isVisible)
-    {
+    if (isVisible) {
       *outIsEmptyNode = false;
     }
-  }
-  else if (length)
-  {
-    if (aNode->TextIsOnlyWhitespace())
-    {
+  } else if (length) {
+    if (aNode->TextIsOnlyWhitespace()) {
       WSRunObject wsRunObj(this, aNode, 0);
       nsCOMPtr<nsINode> visNode;
       int32_t outVisOffset=0;
       WSType visType;
       wsRunObj.NextVisibleNode(aNode, 0, address_of(visNode),
                                &outVisOffset, &visType);
       if (visType == WSType::normalWS || visType == WSType::text) {
         *outIsEmptyNode = (aNode != visNode);
       }
-    }
-    else
-    {
+    } else {
       *outIsEmptyNode = false;
     }
   }
   return NS_OK;
 }
 
 /**
  * IsEmptyNode() figures out if aNode is an empty node.  A block can have
@@ -4369,17 +4340,17 @@ HTMLEditor::IsEmptyNodeImpl(nsINode* aNo
   }
 
   // if it's not a text node (handled above) and it's not a container,
   // then we don't call it empty (it's an <hr>, or <br>, etc.).
   // Also, if it's an anchor then don't treat it as empty - even though
   // anchors are containers, named anchors are "empty" but we don't
   // want to treat them as such.  Also, don't call ListItems or table
   // cells empty if caller desires.  Form Widgets not empty.
-  if (!IsContainer(aNode->AsDOMNode())                      ||
+  if (!IsContainer(aNode->AsDOMNode()) ||
       (HTMLEditUtils::IsNamedAnchor(aNode) ||
        HTMLEditUtils::IsFormWidget(aNode) ||
        (aListOrCellNotEmpty &&
         (HTMLEditUtils::IsListItem(aNode) ||
          HTMLEditUtils::IsTableCell(aNode))))) {
     *outIsEmptyNode = false;
     return NS_OK;
   }
--- a/editor/libeditor/HTMLEditorDataTransfer.cpp
+++ b/editor/libeditor/HTMLEditorDataTransfer.cpp
@@ -121,47 +121,43 @@ HTMLEditor::LoadHTML(const nsAString& aI
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> rules(mRules);
   nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   NS_ENSURE_SUCCESS(rv, rv);
   if (cancel) {
     return NS_OK; // rules canceled the operation
   }
 
-  if (!handled)
-  {
+  if (!handled) {
     // Delete Selection, but only if it isn't collapsed, see bug #106269
     if (!selection->Collapsed()) {
       rv = DeleteSelection(eNone, eStrip);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     // Get the first range in the selection, for context:
     RefPtr<nsRange> range = selection->GetRangeAt(0);
     NS_ENSURE_TRUE(range, NS_ERROR_NULL_POINTER);
 
     // create fragment for pasted html
     nsCOMPtr<nsIDOMDocumentFragment> docfrag;
-    {
-      rv = range->CreateContextualFragment(aInputString, getter_AddRefs(docfrag));
-      NS_ENSURE_SUCCESS(rv, rv);
-    }
+    rv = range->CreateContextualFragment(aInputString, getter_AddRefs(docfrag));
+    NS_ENSURE_SUCCESS(rv, rv);
     // put the fragment into the document
     nsCOMPtr<nsIDOMNode> parent;
     rv = range->GetStartContainer(getter_AddRefs(parent));
     NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(parent, NS_ERROR_NULL_POINTER);
     int32_t childOffset;
     rv = range->GetStartOffset(&childOffset);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsCOMPtr<nsIDOMNode> nodeToInsert;
     docfrag->GetFirstChild(getter_AddRefs(nodeToInsert));
-    while (nodeToInsert)
-    {
+    while (nodeToInsert) {
       rv = InsertNode(nodeToInsert, parent, childOffset++);
       NS_ENSURE_SUCCESS(rv, rv);
       docfrag->GetFirstChild(getter_AddRefs(nodeToInsert));
     }
   }
 
   return rules->DidDoAction(selection, &ruleInfo, rv);
 }
@@ -227,28 +223,25 @@ HTMLEditor::DoInsertHTMLWithContext(cons
                                            &streamStartOffset,
                                            &streamEndOffset,
                                            aTrustedInput);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIDOMNode> targetNode;
   int32_t targetOffset=0;
 
-  if (!aDestNode)
-  {
+  if (!aDestNode) {
     // if caller didn't provide the destination/target node,
     // fetch the paste insertion point from our selection
     rv = GetStartNodeAndOffset(selection, getter_AddRefs(targetNode), &targetOffset);
     NS_ENSURE_SUCCESS(rv, rv);
     if (!targetNode || !IsEditable(targetNode)) {
       return NS_ERROR_FAILURE;
     }
-  }
-  else
-  {
+  } else {
     targetNode = aDestNode;
     targetOffset = aDestOffset;
   }
 
   bool doContinue = true;
 
   rv = DoContentFilterCallback(aFlavor, aSourceDoc, aDeleteSelection,
                                (nsIDOMNode **)address_of(fragmentAsNode),
@@ -263,20 +256,18 @@ HTMLEditor::DoInsertHTMLWithContext(cons
   NS_ENSURE_TRUE(doContinue, NS_OK);
 
   // if we have a destination / target node, we want to insert there
   // rather than in place of the selection
   // ignore aDeleteSelection here if no aDestNode since deletion will
   // also occur later; this block is intended to cover the various
   // scenarios where we are dropping in an editor (and may want to delete
   // the selection before collapsing the selection in the new destination)
-  if (aDestNode)
-  {
-    if (aDeleteSelection)
-    {
+  if (aDestNode) {
+    if (aDeleteSelection) {
       // Use an auto tracker so that our drop point is correctly
       // positioned after the delete.
       AutoTrackDOMPoint tracker(mRangeUpdater, &targetNode, &targetOffset);
       rv = DeleteSelection(eNone, eStrip);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     rv = selection->Collapse(targetNode, targetOffset);
@@ -296,17 +287,17 @@ HTMLEditor::DoInsertHTMLWithContext(cons
   nsCOMPtr<nsINode> streamEndParentNode =
     do_QueryInterface(streamEndParent);
   NS_ENSURE_STATE(streamEndParentNode || !streamEndParent);
   CreateListOfNodesToPaste(*static_cast<DocumentFragment*>(fragmentAsNodeNode.get()),
                            nodeList,
                            streamStartParentNode, streamStartOffset,
                            streamEndParentNode, streamEndOffset);
 
-  if (nodeList.Length() == 0) {
+  if (nodeList.IsEmpty()) {
     // We aren't inserting anything, but if aDeleteSelection is set, we do want
     // to delete everything.
     if (aDeleteSelection) {
       return DeleteSelection(eNone, eStrip);
     }
     return NS_OK;
   }
 
@@ -314,48 +305,43 @@ HTMLEditor::DoInsertHTMLWithContext(cons
   // node and offset for insertion
   nsCOMPtr<nsIDOMNode> parentNode;
   int32_t offsetOfNewNode;
 
   // check for table cell selection mode
   bool cellSelectionMode = false;
   nsCOMPtr<nsIDOMElement> cell;
   rv = GetFirstSelectedCell(nullptr, getter_AddRefs(cell));
-  if (NS_SUCCEEDED(rv) && cell)
-  {
+  if (NS_SUCCEEDED(rv) && cell) {
     cellSelectionMode = true;
   }
 
-  if (cellSelectionMode)
-  {
+  if (cellSelectionMode) {
     // do we have table content to paste?  If so, we want to delete
     // the selected table cells and replace with new table elements;
     // but if not we want to delete _contents_ of cells and replace
     // with non-table elements.  Use cellSelectionMode bool to
     // indicate results.
     if (!HTMLEditUtils::IsTableElement(nodeList[0])) {
       cellSelectionMode = false;
     }
   }
 
-  if (!cellSelectionMode)
-  {
+  if (!cellSelectionMode) {
     rv = DeleteSelectionAndPrepareToCreateNode();
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (aClearStyle) {
       // pasting does not inherit local inline styles
       nsCOMPtr<nsINode> tmpNode = selection->GetAnchorNode();
       int32_t tmpOffset = static_cast<int32_t>(selection->AnchorOffset());
       rv = ClearStyle(address_of(tmpNode), &tmpOffset, nullptr, nullptr);
       NS_ENSURE_SUCCESS(rv, rv);
     }
-  }
-  else
-  {
+  } else {
     // Delete whole cells: we will replace with new table content.
 
     // Braces for artificial block to scope AutoSelectionRestorer.
     // Save current selection since DeleteTableCell() perturbs it.
     {
       AutoSelectionRestorer selectionRestorer(selection, this);
       rv = DeleteTableCell(1);
       NS_ENSURE_SUCCESS(rv, rv);
@@ -368,18 +354,17 @@ HTMLEditor::DoInsertHTMLWithContext(cons
   TextRulesInfo ruleInfo(EditAction::insertElement);
   bool cancel, handled;
   rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   NS_ENSURE_SUCCESS(rv, rv);
   if (cancel) {
     return NS_OK; // rules canceled the operation
   }
 
-  if (!handled)
-  {
+  if (!handled) {
     // The rules code (WillDoAction above) might have changed the selection.
     // refresh our memory...
     rv = GetStartNodeAndOffset(selection, getter_AddRefs(parentNode), &offsetOfNewNode);
     NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(parentNode, NS_ERROR_FAILURE);
 
     // Adjust position based on the first node we are going to insert.
     NormalizeEOLInsertPosition(nodeList[0], address_of(parentNode),
@@ -395,18 +380,17 @@ HTMLEditor::DoInsertHTMLWithContext(cons
       rv = DeleteNode(wsObj.mEndReasonNode);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     // Remember if we are in a link.
     bool bStartedInLink = IsInLink(parentNode);
 
     // Are we in a text node? If so, split it.
-    if (IsTextNode(parentNode))
-    {
+    if (IsTextNode(parentNode)) {
       nsCOMPtr<nsIContent> parentContent = do_QueryInterface(parentNode);
       NS_ENSURE_STATE(parentContent || !parentNode);
       offsetOfNewNode = SplitNodeDeep(*parentContent, *parentContent,
                                       offsetOfNewNode);
       NS_ENSURE_STATE(offsetOfNewNode != -1);
       nsCOMPtr<nsIDOMNode> temp;
       rv = parentNode->GetParentNode(getter_AddRefs(temp));
       NS_ENSURE_SUCCESS(rv, rv);
@@ -416,91 +400,87 @@ HTMLEditor::DoInsertHTMLWithContext(cons
     // build up list of parents of first node in list that are either
     // lists or tables.  First examine front of paste node list.
     nsTArray<OwningNonNull<Element>> startListAndTableArray;
     GetListAndTableParents(StartOrEnd::start, nodeList,
                            startListAndTableArray);
 
     // remember number of lists and tables above us
     int32_t highWaterMark = -1;
-    if (startListAndTableArray.Length() > 0) {
+    if (!startListAndTableArray.IsEmpty()) {
       highWaterMark = DiscoverPartialListsAndTables(nodeList,
                                                     startListAndTableArray);
     }
 
     // if we have pieces of tables or lists to be inserted, let's force the paste
     // to deal with table elements right away, so that it doesn't orphan some
     // table or list contents outside the table or list.
-    if (highWaterMark >= 0)
-    {
+    if (highWaterMark >= 0) {
       ReplaceOrphanedStructure(StartOrEnd::start, nodeList,
                                startListAndTableArray, highWaterMark);
     }
 
     // Now go through the same process again for the end of the paste node list.
     nsTArray<OwningNonNull<Element>> endListAndTableArray;
     GetListAndTableParents(StartOrEnd::end, nodeList, endListAndTableArray);
     highWaterMark = -1;
 
     // remember number of lists and tables above us
-    if (endListAndTableArray.Length() > 0) {
+    if (!endListAndTableArray.IsEmpty()) {
       highWaterMark = DiscoverPartialListsAndTables(nodeList,
                                                     endListAndTableArray);
     }
 
     // don't orphan partial list or table structure
-    if (highWaterMark >= 0)
-    {
+    if (highWaterMark >= 0) {
       ReplaceOrphanedStructure(StartOrEnd::end, nodeList,
                                endListAndTableArray, highWaterMark);
     }
 
     // Loop over the node list and paste the nodes:
     nsCOMPtr<nsIDOMNode> parentBlock, lastInsertNode, insertedContextParent;
-    int32_t listCount = nodeList.Length();
-    int32_t j;
     nsCOMPtr<nsINode> parentNodeNode = do_QueryInterface(parentNode);
     NS_ENSURE_STATE(parentNodeNode || !parentNode);
-    if (IsBlockNode(parentNodeNode))
+    if (IsBlockNode(parentNodeNode)) {
       parentBlock = parentNode;
-    else
+    } else {
       parentBlock = GetBlockNodeParent(parentNode);
+    }
 
-    for (j=0; j<listCount; j++)
-    {
+    int32_t listCount = nodeList.Length();
+    for (int32_t j = 0; j < listCount; j++) {
       bool bDidInsert = false;
       nsCOMPtr<nsIDOMNode> curNode = nodeList[j]->AsDOMNode();
 
       NS_ENSURE_TRUE(curNode, NS_ERROR_FAILURE);
       NS_ENSURE_TRUE(curNode != fragmentAsNode, NS_ERROR_FAILURE);
       NS_ENSURE_TRUE(!TextEditUtils::IsBody(curNode), NS_ERROR_FAILURE);
 
-      if (insertedContextParent)
-      {
+      if (insertedContextParent) {
         // if we had to insert something higher up in the paste hierarchy, we want to
         // skip any further paste nodes that descend from that.  Else we will paste twice.
         if (EditorUtils::IsDescendantOf(curNode, insertedContextParent)) {
           continue;
         }
       }
 
       // give the user a hand on table element insertion.  if they have
       // a table or table row on the clipboard, and are trying to insert
       // into a table or table row, insert the appropriate children instead.
       if (HTMLEditUtils::IsTableRow(curNode) &&
           HTMLEditUtils::IsTableRow(parentNode) &&
           (HTMLEditUtils::IsTable(curNode) ||
            HTMLEditUtils::IsTable(parentNode))) {
         nsCOMPtr<nsIDOMNode> child;
         curNode->GetFirstChild(getter_AddRefs(child));
-        while (child)
-        {
+        while (child) {
           rv = InsertNodeAtPoint(child, address_of(parentNode), &offsetOfNewNode, true);
-          if (NS_FAILED(rv))
+          if (NS_FAILED(rv)) {
             break;
+          }
 
           bDidInsert = true;
           lastInsertNode = child;
           offsetOfNewNode++;
 
           curNode->GetFirstChild(getter_AddRefs(child));
         }
       }
@@ -508,140 +488,129 @@ HTMLEditor::DoInsertHTMLWithContext(cons
       // a list on the clipboard, and are trying to insert
       // into a list or list item, insert the appropriate children instead,
       // ie, merge the lists instead of pasting in a sublist.
       else if (HTMLEditUtils::IsList(curNode) &&
                (HTMLEditUtils::IsList(parentNode) ||
                 HTMLEditUtils::IsListItem(parentNode))) {
         nsCOMPtr<nsIDOMNode> child, tmp;
         curNode->GetFirstChild(getter_AddRefs(child));
-        while (child)
-        {
+        while (child) {
           if (HTMLEditUtils::IsListItem(child) ||
               HTMLEditUtils::IsList(child)) {
             // Check if we are pasting into empty list item. If so
             // delete it and paste into parent list instead.
             if (HTMLEditUtils::IsListItem(parentNode)) {
               bool isEmpty;
               rv = IsEmptyNode(parentNode, &isEmpty, true);
-              if (NS_SUCCEEDED(rv) && isEmpty)
-              {
+              if (NS_SUCCEEDED(rv) && isEmpty) {
                 int32_t newOffset;
                 nsCOMPtr<nsIDOMNode> listNode = GetNodeLocation(parentNode, &newOffset);
-                if (listNode)
-                {
+                if (listNode) {
                   DeleteNode(parentNode);
                   parentNode = listNode;
                   offsetOfNewNode = newOffset;
                 }
               }
             }
             rv = InsertNodeAtPoint(child, address_of(parentNode), &offsetOfNewNode, true);
-            if (NS_FAILED(rv))
+            if (NS_FAILED(rv)) {
               break;
+            }
 
             bDidInsert = true;
             lastInsertNode = child;
             offsetOfNewNode++;
-          }
-          else
-          {
+          } else {
             curNode->RemoveChild(child, getter_AddRefs(tmp));
           }
           curNode->GetFirstChild(getter_AddRefs(child));
         }
-
       } else if (parentBlock && HTMLEditUtils::IsPre(parentBlock) &&
                  HTMLEditUtils::IsPre(curNode)) {
         // Check for pre's going into pre's.
         nsCOMPtr<nsIDOMNode> child;
         curNode->GetFirstChild(getter_AddRefs(child));
-        while (child)
-        {
+        while (child) {
           rv = InsertNodeAtPoint(child, address_of(parentNode), &offsetOfNewNode, true);
-          if (NS_FAILED(rv))
+          if (NS_FAILED(rv)) {
             break;
+          }
 
           bDidInsert = true;
           lastInsertNode = child;
           offsetOfNewNode++;
 
           curNode->GetFirstChild(getter_AddRefs(child));
         }
       }
 
-      if (!bDidInsert || NS_FAILED(rv))
-      {
+      if (!bDidInsert || NS_FAILED(rv)) {
         // try to insert
         rv = InsertNodeAtPoint(curNode, address_of(parentNode), &offsetOfNewNode, true);
-        if (NS_SUCCEEDED(rv))
-        {
+        if (NS_SUCCEEDED(rv)) {
           bDidInsert = true;
           lastInsertNode = curNode;
         }
 
         // Assume failure means no legal parent in the document hierarchy,
         // try again with the parent of curNode in the paste hierarchy.
         nsCOMPtr<nsIDOMNode> parent;
-        while (NS_FAILED(rv) && curNode)
-        {
+        while (NS_FAILED(rv) && curNode) {
           curNode->GetParentNode(getter_AddRefs(parent));
           if (parent && !TextEditUtils::IsBody(parent)) {
             rv = InsertNodeAtPoint(parent, address_of(parentNode), &offsetOfNewNode, true);
-            if (NS_SUCCEEDED(rv))
-            {
+            if (NS_SUCCEEDED(rv)) {
               bDidInsert = true;
               insertedContextParent = parent;
               lastInsertNode = GetChildAt(parentNode, offsetOfNewNode);
             }
           }
           curNode = parent;
         }
       }
-      if (lastInsertNode)
-      {
+      if (lastInsertNode) {
         parentNode = GetNodeLocation(lastInsertNode, &offsetOfNewNode);
         offsetOfNewNode++;
       }
     }
 
     // Now collapse the selection to the end of what we just inserted:
-    if (lastInsertNode)
-    {
+    if (lastInsertNode) {
       // set selection to the end of what we just pasted.
       nsCOMPtr<nsIDOMNode> selNode, tmp, highTable;
       int32_t selOffset;
 
       // but don't cross tables
       if (!HTMLEditUtils::IsTable(lastInsertNode)) {
         nsCOMPtr<nsINode> lastInsertNode_ = do_QueryInterface(lastInsertNode);
         NS_ENSURE_STATE(lastInsertNode_ || !lastInsertNode);
         selNode = GetAsDOMNode(GetLastEditableLeaf(*lastInsertNode_));
         tmp = selNode;
-        while (tmp && (tmp != lastInsertNode))
-        {
+        while (tmp && tmp != lastInsertNode) {
           if (HTMLEditUtils::IsTable(tmp)) {
             highTable = tmp;
           }
           nsCOMPtr<nsIDOMNode> parent = tmp;
           tmp->GetParentNode(getter_AddRefs(parent));
           tmp = parent;
         }
-        if (highTable)
+        if (highTable) {
           selNode = highTable;
+        }
       }
-      if (!selNode)
+      if (!selNode) {
         selNode = lastInsertNode;
+      }
       if (IsTextNode(selNode) ||
           (IsContainer(selNode) && !HTMLEditUtils::IsTable(selNode))) {
         rv = GetLengthOfDOMNode(selNode, (uint32_t&)selOffset);
         NS_ENSURE_SUCCESS(rv, rv);
-      }
-      else // we need to find a container for selection.  Look up.
-      {
+      } else {
+        // We need to find a container for selection.  Look up.
         tmp = selNode;
         selNode = GetNodeLocation(tmp, &selOffset);
         // selNode might be null in case a mutation listener removed
         // the stuff we just inserted from the DOM.
         NS_ENSURE_STATE(selNode);
         ++selOffset;  // want to be *after* last leaf node in paste
       }
 
@@ -653,18 +622,17 @@ HTMLEditor::DoInsertHTMLWithContext(cons
       nsCOMPtr<nsINode> selNode_(do_QueryInterface(selNode));
       wsRunObj.PriorVisibleNode(selNode_, selOffset, address_of(visNode),
                                 &outVisOffset, &visType);
       if (visType == WSType::br) {
         // we are after a break.  Is it visible?  Despite the name,
         // PriorVisibleNode does not make that determination for breaks.
         // It also may not return the break in visNode.  We have to pull it
         // out of the WSRunObject's state.
-        if (!IsVisBreak(wsRunObj.mStartReasonNode))
-        {
+        if (!IsVisBreak(wsRunObj.mStartReasonNode)) {
           // don't leave selection past an invisible break;
           // reset {selNode,selOffset} to point before break
           selNode = GetNodeLocation(GetAsDOMNode(wsRunObj.mStartReasonNode), &selOffset);
           // we want to be inside any inline style prior to break
           WSRunObject wsRunObj(this, selNode, selOffset);
           selNode_ = do_QueryInterface(selNode);
           wsRunObj.PriorVisibleNode(selNode_, selOffset, address_of(visNode),
                                     &outVisOffset, &visType);
@@ -678,18 +646,17 @@ HTMLEditor::DoInsertHTMLWithContext(cons
             ++selOffset;
           }
         }
       }
       selection->Collapse(selNode, selOffset);
 
       // if we just pasted a link, discontinue link style
       nsCOMPtr<nsIDOMNode> link;
-      if (!bStartedInLink && IsInLink(selNode, address_of(link)))
-      {
+      if (!bStartedInLink && IsInLink(selNode, address_of(link))) {
         // so, if we just pasted a link, I split it.  Why do that instead of just
         // nudging selection point beyond it?  Because it might have ended in a BR
         // that is not visible.  If so, the code above just placed selection
         // inside that.  So I split it instead.
         nsCOMPtr<nsIContent> linkContent = do_QueryInterface(link);
         NS_ENSURE_STATE(linkContent || !link);
         nsCOMPtr<nsIContent> selContent = do_QueryInterface(selNode);
         NS_ENSURE_STATE(selContent || !selNode);
@@ -759,24 +726,25 @@ HTMLEditor::DoContentFilterCallback(cons
   return NS_OK;
 }
 
 bool
 HTMLEditor::IsInLink(nsIDOMNode* aNode,
                      nsCOMPtr<nsIDOMNode>* outLink)
 {
   NS_ENSURE_TRUE(aNode, false);
-  if (outLink)
+  if (outLink) {
     *outLink = nullptr;
+  }
   nsCOMPtr<nsIDOMNode> tmp, node = aNode;
-  while (node)
-  {
+  while (node) {
     if (HTMLEditUtils::IsLink(node)) {
-      if (outLink)
+      if (outLink) {
         *outLink = node;
+      }
       return true;
     }
     tmp = node;
     tmp->GetParentNode(getter_AddRefs(node));
   }
   return false;
 }
 
@@ -817,33 +785,30 @@ HTMLEditor::PrepareTransferable(nsITrans
 nsresult
 HTMLEditor::PrepareHTMLTransferable(nsITransferable** aTransferable)
 {
   // Create generic Transferable for getting the data
   nsresult rv = CallCreateInstance("@mozilla.org/widget/transferable;1", aTransferable);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Get the nsITransferable interface for getting the data from the clipboard
-  if (aTransferable)
-  {
+  if (aTransferable) {
     nsCOMPtr<nsIDocument> destdoc = GetDocument();
     nsILoadContext* loadContext = destdoc ? destdoc->GetLoadContext() : nullptr;
     (*aTransferable)->Init(loadContext);
 
     // Create the desired DataFlavor for the type of data
     // we want to get out of the transferable
     // This should only happen in html editors, not plaintext
-    if (!IsPlaintextEditor())
-    {
+    if (!IsPlaintextEditor()) {
       (*aTransferable)->AddDataFlavor(kNativeHTMLMime);
       (*aTransferable)->AddDataFlavor(kHTMLMime);
       (*aTransferable)->AddDataFlavor(kFileMime);
 
-      switch (Preferences::GetInt("clipboard.paste_image_type", 1))
-      {
+      switch (Preferences::GetInt("clipboard.paste_image_type", 1)) {
         case 0:  // prefer JPEG over PNG over GIF encoding
           (*aTransferable)->AddDataFlavor(kJPEGImageMime);
           (*aTransferable)->AddDataFlavor(kJPGImageMime);
           (*aTransferable)->AddDataFlavor(kPNGImageMime);
           (*aTransferable)->AddDataFlavor(kGIFImageMime);
           break;
         case 1:  // prefer PNG over JPEG over GIF encoding (default)
         default:
@@ -869,120 +834,121 @@ HTMLEditor::PrepareHTMLTransferable(nsIT
 
 bool
 FindIntegerAfterString(const char* aLeadingString,
                        nsCString& aCStr,
                        int32_t& foundNumber)
 {
   // first obtain offsets from cfhtml str
   int32_t numFront = aCStr.Find(aLeadingString);
-  if (numFront == -1)
+  if (numFront == -1) {
     return false;
+  }
   numFront += strlen(aLeadingString);
 
   int32_t numBack = aCStr.FindCharInSet(CRLF, numFront);
-  if (numBack == -1)
+  if (numBack == -1) {
     return false;
+  }
 
   nsAutoCString numStr(Substring(aCStr, numFront, numBack-numFront));
   nsresult errorCode;
   foundNumber = numStr.ToInteger(&errorCode);
   return true;
 }
 
 nsresult
 RemoveFragComments(nsCString& aStr)
 {
   // remove the StartFragment/EndFragment comments from the str, if present
   int32_t startCommentIndx = aStr.Find("<!--StartFragment");
-  if (startCommentIndx >= 0)
-  {
+  if (startCommentIndx >= 0) {
     int32_t startCommentEnd = aStr.Find("-->", false, startCommentIndx);
-    if (startCommentEnd > startCommentIndx)
-      aStr.Cut(startCommentIndx, (startCommentEnd+3)-startCommentIndx);
+    if (startCommentEnd > startCommentIndx) {
+      aStr.Cut(startCommentIndx, (startCommentEnd + 3) - startCommentIndx);
+    }
   }
   int32_t endCommentIndx = aStr.Find("<!--EndFragment");
-  if (endCommentIndx >= 0)
-  {
+  if (endCommentIndx >= 0) {
     int32_t endCommentEnd = aStr.Find("-->", false, endCommentIndx);
-    if (endCommentEnd > endCommentIndx)
-      aStr.Cut(endCommentIndx, (endCommentEnd+3)-endCommentIndx);
+    if (endCommentEnd > endCommentIndx) {
+      aStr.Cut(endCommentIndx, (endCommentEnd + 3) - endCommentIndx);
+    }
   }
   return NS_OK;
 }
 
 nsresult
 HTMLEditor::ParseCFHTML(nsCString& aCfhtml,
                         char16_t** aStuffToPaste,
                         char16_t** aCfcontext)
 {
   // First obtain offsets from cfhtml str.
   int32_t startHTML, endHTML, startFragment, endFragment;
   if (!FindIntegerAfterString("StartHTML:", aCfhtml, startHTML) ||
-      startHTML < -1)
+      startHTML < -1) {
     return NS_ERROR_FAILURE;
+  }
   if (!FindIntegerAfterString("EndHTML:", aCfhtml, endHTML) ||
-      endHTML < -1)
+      endHTML < -1) {
     return NS_ERROR_FAILURE;
+  }
   if (!FindIntegerAfterString("StartFragment:", aCfhtml, startFragment) ||
-      startFragment < 0)
+      startFragment < 0) {
     return NS_ERROR_FAILURE;
+  }
   if (!FindIntegerAfterString("EndFragment:", aCfhtml, endFragment) ||
-      startFragment < 0)
+      startFragment < 0) {
     return NS_ERROR_FAILURE;
+  }
 
   // The StartHTML and EndHTML markers are allowed to be -1 to include everything.
   //   See Reference: MSDN doc entitled "HTML Clipboard Format"
   //   http://msdn.microsoft.com/en-us/library/aa767917(VS.85).aspx#unknown_854
   if (startHTML == -1) {
     startHTML = aCfhtml.Find("<!--StartFragment-->");
-    if (startHTML == -1)
+    if (startHTML == -1) {
       return NS_OK;
+    }
   }
   if (endHTML == -1) {
     const char endFragmentMarker[] = "<!--EndFragment-->";
     endHTML = aCfhtml.Find(endFragmentMarker);
-    if (endHTML == -1)
+    if (endHTML == -1) {
       return NS_OK;
+    }
     endHTML += ArrayLength(endFragmentMarker) - 1;
   }
 
   // create context string
   nsAutoCString contextUTF8(Substring(aCfhtml, startHTML, startFragment - startHTML) +
                             NS_LITERAL_CSTRING("<!--" kInsertCookie "-->") +
                             Substring(aCfhtml, endFragment, endHTML - endFragment));
 
   // validate startFragment
   // make sure it's not in the middle of a HTML tag
   // see bug #228879 for more details
   int32_t curPos = startFragment;
-  while (curPos > startHTML)
-  {
-      if (aCfhtml[curPos] == '>')
-      {
-          // working backwards, the first thing we see is the end of a tag
-          // so StartFragment is good, so do nothing.
-          break;
+  while (curPos > startHTML) {
+    if (aCfhtml[curPos] == '>') {
+      // working backwards, the first thing we see is the end of a tag
+      // so StartFragment is good, so do nothing.
+      break;
+    }
+    if (aCfhtml[curPos] == '<') {
+      // if we are at the start, then we want to see the '<'
+      if (curPos != startFragment) {
+        // working backwards, the first thing we see is the start of a tag
+        // so StartFragment is bad, so we need to update it.
+        NS_ERROR("StartFragment byte count in the clipboard looks bad, see bug #228879");
+        startFragment = curPos - 1;
       }
-      else if (aCfhtml[curPos] == '<')
-      {
-          // if we are at the start, then we want to see the '<'
-          if (curPos != startFragment)
-          {
-              // working backwards, the first thing we see is the start of a tag
-              // so StartFragment is bad, so we need to update it.
-              NS_ERROR("StartFragment byte count in the clipboard looks bad, see bug #228879");
-              startFragment = curPos - 1;
-          }
-          break;
-      }
-      else
-      {
-          curPos--;
-      }
+      break;
+    }
+    curPos--;
   }
 
   // create fragment string
   nsAutoCString fragmentUTF8(Substring(aCfhtml, startFragment, endFragment-startFragment));
 
   // remove the StartFragment/EndFragment comments from the fragment, if present
   RemoveFragComments(fragmentUTF8);
 
@@ -1119,48 +1085,39 @@ HTMLEditor::InsertObject(const char* aTy
     return utils->SlurpBlob(domBlob, node->OwnerDoc()->GetWindow(), br);
   }
 
   nsAutoCString type(aType);
 
   // Check to see if we can insert an image file
   bool insertAsImage = false;
   nsCOMPtr<nsIFile> fileObj;
-  if (type.EqualsLiteral(kFileMime))
-  {
+  if (type.EqualsLiteral(kFileMime)) {
     fileObj = do_QueryInterface(aObject);
-    if (fileObj)
-    {
+    if (fileObj) {
       // Accept any image type fed to us
-      if (nsContentUtils::IsFileImage(fileObj, type))
-      {
+      if (nsContentUtils::IsFileImage(fileObj, type)) {
         insertAsImage = true;
-      }
-      else
-      {
+      } else {
         // Reset type.
         type.AssignLiteral(kFileMime);
       }
     }
   }
 
   if (type.EqualsLiteral(kJPEGImageMime) ||
       type.EqualsLiteral(kJPGImageMime) ||
       type.EqualsLiteral(kPNGImageMime) ||
       type.EqualsLiteral(kGIFImageMime) ||
-      insertAsImage)
-  {
+      insertAsImage) {
     nsCString imageData;
-    if (insertAsImage)
-    {
+    if (insertAsImage) {
       rv = nsContentUtils::SlurpFileToString(fileObj, imageData);
       NS_ENSURE_SUCCESS(rv, rv);
-    }
-    else
-    {
+    } else {
       nsCOMPtr<nsIInputStream> imageStream = do_QueryInterface(aObject);
       NS_ENSURE_TRUE(imageStream, NS_ERROR_FAILURE);
 
       rv = NS_ConsumeStream(imageStream, UINT32_MAX, imageData);
       NS_ENSURE_SUCCESS(rv, rv);
 
       rv = imageStream->Close();
       NS_ENSURE_SUCCESS(rv, rv);
@@ -1191,46 +1148,44 @@ HTMLEditor::InsertFromTransferable(nsITr
                                    nsIDOMNode* aDestinationNode,
                                    int32_t aDestOffset,
                                    bool aDoDeleteSelection)
 {
   nsresult rv = NS_OK;
   nsXPIDLCString bestFlavor;
   nsCOMPtr<nsISupports> genericDataObj;
   uint32_t len = 0;
-  if (NS_SUCCEEDED(transferable->GetAnyTransferData(getter_Copies(bestFlavor), getter_AddRefs(genericDataObj), &len)))
-  {
+  if (NS_SUCCEEDED(
+        transferable->GetAnyTransferData(getter_Copies(bestFlavor),
+                                         getter_AddRefs(genericDataObj),
+                                         &len))) {
     AutoTransactionsConserveSelection dontSpazMySelection(this);
     nsAutoString flavor;
     flavor.AssignWithConversion(bestFlavor);
     nsAutoString stuffToPaste;
     bool isSafe = IsSafeToInsertData(aSourceDoc);
 
-    if (0 == nsCRT::strcmp(bestFlavor, kFileMime) ||
-        0 == nsCRT::strcmp(bestFlavor, kJPEGImageMime) ||
-        0 == nsCRT::strcmp(bestFlavor, kJPGImageMime) ||
-        0 == nsCRT::strcmp(bestFlavor, kPNGImageMime) ||
-        0 == nsCRT::strcmp(bestFlavor, kGIFImageMime)) {
+    if (!nsCRT::strcmp(bestFlavor, kFileMime) ||
+        !nsCRT::strcmp(bestFlavor, kJPEGImageMime) ||
+        !nsCRT::strcmp(bestFlavor, kJPGImageMime) ||
+        !nsCRT::strcmp(bestFlavor, kPNGImageMime) ||
+        !nsCRT::strcmp(bestFlavor, kGIFImageMime)) {
       rv = InsertObject(bestFlavor, genericDataObj, isSafe,
                         aSourceDoc, aDestinationNode, aDestOffset, aDoDeleteSelection);
-    }
-    else if (0 == nsCRT::strcmp(bestFlavor, kNativeHTMLMime))
-    {
+    } else if (!nsCRT::strcmp(bestFlavor, kNativeHTMLMime)) {
       // note cf_html uses utf8, hence use length = len, not len/2 as in flavors below
       nsCOMPtr<nsISupportsCString> textDataObj = do_QueryInterface(genericDataObj);
-      if (textDataObj && len > 0)
-      {
+      if (textDataObj && len > 0) {
         nsAutoCString cfhtml;
         textDataObj->GetData(cfhtml);
         NS_ASSERTION(cfhtml.Length() <= (len), "Invalid length!");
         nsXPIDLString cfcontext, cffragment, cfselection; // cfselection left emtpy for now
 
         rv = ParseCFHTML(cfhtml, getter_Copies(cffragment), getter_Copies(cfcontext));
-        if (NS_SUCCEEDED(rv) && !cffragment.IsEmpty())
-        {
+        if (NS_SUCCEEDED(rv) && !cffragment.IsEmpty()) {
           AutoEditBatch beginBatching(this);
           // If we have our private HTML flavor, we will only use the fragment
           // from the CF_HTML. The rest comes from the clipboard.
           if (havePrivateHTMLFlavor) {
             rv = DoInsertHTMLWithContext(cffragment,
                                          aContextStr, aInfoStr, flavor,
                                          aSourceDoc,
                                          aDestinationNode, aDestOffset,
@@ -1251,19 +1206,19 @@ HTMLEditor::InsertFromTransferable(nsITr
           // application/x-moz-nativehtml).  In this case, treat the data
           // to be pasted as mere HTML to get the best chance of pasting it
           // correctly.
           bestFlavor.AssignLiteral(kHTMLMime);
           // Fall through the next case
         }
       }
     }
-    if (0 == nsCRT::strcmp(bestFlavor, kHTMLMime) ||
-        0 == nsCRT::strcmp(bestFlavor, kUnicodeMime) ||
-        0 == nsCRT::strcmp(bestFlavor, kMozTextInternal)) {
+    if (!nsCRT::strcmp(bestFlavor, kHTMLMime) ||
+        !nsCRT::strcmp(bestFlavor, kUnicodeMime) ||
+        !nsCRT::strcmp(bestFlavor, kMozTextInternal)) {
       nsCOMPtr<nsISupportsString> textDataObj = do_QueryInterface(genericDataObj);
       if (textDataObj && len > 0) {
         nsAutoString text;
         textDataObj->GetData(text);
         NS_ASSERTION(text.Length() <= (len/2), "Invalid length!");
         stuffToPaste.Assign(text.get(), len / 2);
       } else {
         nsCOMPtr<nsISupportsCString> textDataObj(do_QueryInterface(genericDataObj));
@@ -1272,47 +1227,48 @@ HTMLEditor::InsertFromTransferable(nsITr
           textDataObj->GetData(text);
           NS_ASSERTION(text.Length() <= len, "Invalid length!");
           stuffToPaste.Assign(NS_ConvertUTF8toUTF16(Substring(text, 0, len)));
         }
       }
 
       if (!stuffToPaste.IsEmpty()) {
         AutoEditBatch beginBatching(this);
-        if (0 == nsCRT::strcmp(bestFlavor, kHTMLMime)) {
+        if (!nsCRT::strcmp(bestFlavor, kHTMLMime)) {
           rv = DoInsertHTMLWithContext(stuffToPaste,
                                        aContextStr, aInfoStr, flavor,
                                        aSourceDoc,
                                        aDestinationNode, aDestOffset,
                                        aDoDeleteSelection,
                                        isSafe);
         } else {
           rv = InsertTextAt(stuffToPaste, aDestinationNode, aDestOffset, aDoDeleteSelection);
         }
       }
     }
   }
 
   // Try to scroll the selection into view if the paste succeeded
-  if (NS_SUCCEEDED(rv))
+  if (NS_SUCCEEDED(rv)) {
     ScrollSelectionIntoView(false);
-
+  }
   return rv;
 }
 
 static void
 GetStringFromDataTransfer(nsIDOMDataTransfer* aDataTransfer,
                           const nsAString& aType,
                           int32_t aIndex,
                           nsAString& aOutputString)
 {
   nsCOMPtr<nsIVariant> variant;
   DataTransfer::Cast(aDataTransfer)->GetDataAtNoSecurityCheck(aType, aIndex, getter_AddRefs(variant));
-  if (variant)
+  if (variant) {
     variant->GetAsAString(aOutputString);
+  }
 }
 
 nsresult
 HTMLEditor::InsertFromDataTransfer(DataTransfer* aDataTransfer,
                                    int32_t aIndex,
                                    nsIDOMDocument* aSourceDoc,
                                    nsIDOMNode* aDestinationNode,
                                    int32_t aDestOffset,
@@ -1343,54 +1299,50 @@ HTMLEditor::InsertFromDataTransfer(DataT
         nsCOMPtr<nsIVariant> variant;
         DataTransfer::Cast(aDataTransfer)->GetDataAtNoSecurityCheck(type, aIndex, getter_AddRefs(variant));
         if (variant) {
           nsCOMPtr<nsISupports> object;
           variant->GetAsISupports(getter_AddRefs(object));
           return InsertObject(NS_ConvertUTF16toUTF8(type).get(), object, isSafe,
                               aSourceDoc, aDestinationNode, aDestOffset, aDoDeleteSelection);
         }
-      }
-      else if (type.EqualsLiteral(kNativeHTMLMime)) {
+      } else if (type.EqualsLiteral(kNativeHTMLMime)) {
         // Windows only clipboard parsing.
         nsAutoString text;
         GetStringFromDataTransfer(aDataTransfer, type, aIndex, text);
         NS_ConvertUTF16toUTF8 cfhtml(text);
 
         nsXPIDLString cfcontext, cffragment, cfselection; // cfselection left emtpy for now
 
         nsresult rv = ParseCFHTML(cfhtml, getter_Copies(cffragment), getter_Copies(cfcontext));
-        if (NS_SUCCEEDED(rv) && !cffragment.IsEmpty())
-        {
+        if (NS_SUCCEEDED(rv) && !cffragment.IsEmpty()) {
           AutoEditBatch beginBatching(this);
 
           if (hasPrivateHTMLFlavor) {
             // If we have our private HTML flavor, we will only use the fragment
             // from the CF_HTML. The rest comes from the clipboard.
             nsAutoString contextString, infoString;
             GetStringFromDataTransfer(aDataTransfer, NS_LITERAL_STRING(kHTMLContext), aIndex, contextString);
             GetStringFromDataTransfer(aDataTransfer, NS_LITERAL_STRING(kHTMLInfo), aIndex, infoString);
             return DoInsertHTMLWithContext(cffragment,
                                            contextString, infoString, type,
                                            aSourceDoc,
                                            aDestinationNode, aDestOffset,
                                            aDoDeleteSelection,
                                            isSafe);
-          }
-          else {
+          } else {
             return DoInsertHTMLWithContext(cffragment,
                                            cfcontext, cfselection, type,
                                            aSourceDoc,
                                            aDestinationNode, aDestOffset,
                                            aDoDeleteSelection,
                                            isSafe);
           }
         }
-      }
-      else if (type.EqualsLiteral(kHTMLMime)) {
+      } else if (type.EqualsLiteral(kHTMLMime)) {
         nsAutoString text, contextString, infoString;
         GetStringFromDataTransfer(aDataTransfer, type, aIndex, text);
         GetStringFromDataTransfer(aDataTransfer, NS_LITERAL_STRING(kHTMLContext), aIndex, contextString);
         GetStringFromDataTransfer(aDataTransfer, NS_LITERAL_STRING(kHTMLInfo), aIndex, infoString);
 
         AutoEditBatch beginBatching(this);
         if (type.EqualsLiteral(kHTMLMime)) {
           return DoInsertHTMLWithContext(text,
@@ -1422,20 +1374,23 @@ HTMLEditor::HavePrivateHTMLFlavor(nsICli
   // check the clipboard for our special kHTMLContext flavor.  If that is there, we know
   // we have our own internal html format on clipboard.
 
   NS_ENSURE_TRUE(aClipboard, false);
   bool bHavePrivateHTMLFlavor = false;
 
   const char* flavArray[] = { kHTMLContext };
 
-  if (NS_SUCCEEDED(aClipboard->HasDataMatchingFlavors(flavArray,
-    ArrayLength(flavArray), nsIClipboard::kGlobalClipboard,
-    &bHavePrivateHTMLFlavor)))
+  if (NS_SUCCEEDED(
+        aClipboard->HasDataMatchingFlavors(flavArray,
+                                           ArrayLength(flavArray),
+                                           nsIClipboard::kGlobalClipboard,
+                                           &bHavePrivateHTMLFlavor))) {
     return bHavePrivateHTMLFlavor;
+  }
 
   return false;
 }
 
 
 NS_IMETHODIMP
 HTMLEditor::Paste(int32_t aSelectionType)
 {
@@ -1461,18 +1416,17 @@ HTMLEditor::Paste(int32_t aSelectionType
   }
 
   // also get additional html copy hints, if present
   nsAutoString contextStr, infoStr;
 
   // If we have our internal html flavor on the clipboard, there is special
   // context to use instead of cfhtml context.
   bool bHavePrivateHTMLFlavor = HavePrivateHTMLFlavor(clipboard);
-  if (bHavePrivateHTMLFlavor)
-  {
+  if (bHavePrivateHTMLFlavor) {
     nsCOMPtr<nsISupports> contextDataObj, infoDataObj;
     uint32_t contextLen, infoLen;
     nsCOMPtr<nsISupportsString> textDataObj;
 
     nsCOMPtr<nsITransferable> contextTrans =
                   do_CreateInstance("@mozilla.org/widget/transferable;1");
     NS_ENSURE_TRUE(contextTrans, NS_ERROR_NULL_POINTER);
     contextTrans->Init(nullptr);
@@ -1483,27 +1437,25 @@ HTMLEditor::Paste(int32_t aSelectionType
     nsCOMPtr<nsITransferable> infoTrans =
                   do_CreateInstance("@mozilla.org/widget/transferable;1");
     NS_ENSURE_TRUE(infoTrans, NS_ERROR_NULL_POINTER);
     infoTrans->Init(nullptr);
     infoTrans->AddDataFlavor(kHTMLInfo);
     clipboard->GetData(infoTrans, aSelectionType);
     infoTrans->GetTransferData(kHTMLInfo, getter_AddRefs(infoDataObj), &infoLen);
 
-    if (contextDataObj)
-    {
+    if (contextDataObj) {
       nsAutoString text;
       textDataObj = do_QueryInterface(contextDataObj);
       textDataObj->GetData(text);
       NS_ASSERTION(text.Length() <= (contextLen/2), "Invalid length!");
       contextStr.Assign(text.get(), contextLen / 2);
     }
 
-    if (infoDataObj)
-    {
+    if (infoDataObj) {
       nsAutoString text;
       textDataObj = do_QueryInterface(infoDataObj);
       textDataObj->GetData(text);
       NS_ASSERTION(text.Length() <= (infoLen/2), "Invalid length!");
       infoStr.Assign(text.get(), infoLen / 2);
     }
   }
 
@@ -1554,21 +1506,20 @@ HTMLEditor::PasteNoFormatting(int32_t aS
   nsresult rv;
   nsCOMPtr<nsIClipboard> clipboard(do_GetService("@mozilla.org/widget/clipboard;1", &rv));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Get the nsITransferable interface for getting the data from the clipboard.
   // use TextEditor::PrepareTransferable() to force unicode plaintext data.
   nsCOMPtr<nsITransferable> trans;
   rv = TextEditor::PrepareTransferable(getter_AddRefs(trans));
-  if (NS_SUCCEEDED(rv) && trans)
-  {
+  if (NS_SUCCEEDED(rv) && trans) {
     // Get the Data from the clipboard
-    if (NS_SUCCEEDED(clipboard->GetData(trans, aSelectionType)) && IsModifiable())
-    {
+    if (NS_SUCCEEDED(clipboard->GetData(trans, aSelectionType)) &&
+        IsModifiable()) {
       const nsAFlatString& empty = EmptyString();
       rv = InsertFromTransferable(trans, nullptr, empty, empty, false, nullptr, 0,
                                   true);
     }
   }
 
   return rv;
 }
@@ -1595,25 +1546,25 @@ HTMLEditor::CanPaste(int32_t aSelectionT
 
   nsresult rv;
   nsCOMPtr<nsIClipboard> clipboard(do_GetService("@mozilla.org/widget/clipboard;1", &rv));
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool haveFlavors;
 
   // Use the flavors depending on the current editor mask
-  if (IsPlaintextEditor())
+  if (IsPlaintextEditor()) {
     rv = clipboard->HasDataMatchingFlavors(textEditorFlavors,
                                            ArrayLength(textEditorFlavors),
                                            aSelectionType, &haveFlavors);
-  else
+  } else {
     rv = clipboard->HasDataMatchingFlavors(textHtmlEditorFlavors,
                                            ArrayLength(textHtmlEditorFlavors),
                                            aSelectionType, &haveFlavors);
-
+  }
   NS_ENSURE_SUCCESS(rv, rv);
 
   *aCanPaste = haveFlavors;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditor::CanPasteTransferable(nsITransferable* aTransferable,
@@ -1663,18 +1614,19 @@ HTMLEditor::CanPasteTransferable(nsITran
 }
 
 /**
  * HTML PasteAsQuotation: Paste in a blockquote type=cite.
  */
 NS_IMETHODIMP
 HTMLEditor::PasteAsQuotation(int32_t aSelectionType)
 {
-  if (IsPlaintextEditor())
+  if (IsPlaintextEditor()) {
     return PasteAsPlaintextQuotation(aSelectionType);
+  }
 
   nsAutoString citation;
   return PasteAsCitedQuotation(citation, aSelectionType);
 }
 
 NS_IMETHODIMP
 HTMLEditor::PasteAsCitedQuotation(const nsAString& aCitation,
                                   int32_t aSelectionType)
@@ -1744,21 +1696,19 @@ HTMLEditor::PasteAsPlaintextQuotation(in
   // it still owns the data, we just have a pointer to it.
   // If it can't support a "text" output of the data the call will fail
   nsCOMPtr<nsISupports> genericDataObj;
   uint32_t len = 0;
   char* flav = 0;
   rv = trans->GetAnyTransferData(&flav, getter_AddRefs(genericDataObj), &len);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (flav && 0 == nsCRT::strcmp(flav, kUnicodeMime))
-  {
+  if (flav && !nsCRT::strcmp(flav, kUnicodeMime)) {
     nsCOMPtr<nsISupportsString> textDataObj = do_QueryInterface(genericDataObj);
-    if (textDataObj && len > 0)
-    {
+    if (textDataObj && len > 0) {
       nsAutoString stuffToPaste;
       textDataObj->GetData(stuffToPaste);
       NS_ASSERTION(stuffToPaste.Length() <= (len/2), "Invalid length!");
       AutoEditBatch beginBatching(this);
       rv = InsertAsPlaintextQuotation(stuffToPaste, true, 0);
     }
   }
   free(flav);
@@ -1786,80 +1736,84 @@ HTMLEditor::InsertTextWithQuotations(con
 
   // In the loop below, we only look for DOM newlines (\n),
   // because we don't have a FindChars method that can look
   // for both \r and \n.  \r is illegal in the dom anyway,
   // but in debug builds, let's take the time to verify that
   // there aren't any there:
 #ifdef DEBUG
   nsAString::const_iterator dbgStart (hunkStart);
-  if (FindCharInReadable('\r', dbgStart, strEnd))
+  if (FindCharInReadable('\r', dbgStart, strEnd)) {
     NS_ASSERTION(false,
             "Return characters in DOM! InsertTextWithQuotations may be wrong");
+  }
 #endif /* DEBUG */
 
   // Loop over lines:
   nsresult rv = NS_OK;
   nsAString::const_iterator lineStart (hunkStart);
-  while (1)   // we will break from inside when we run out of newlines
-  {
+  // We will break from inside when we run out of newlines.
+  for (;;) {
     // Search for the end of this line (dom newlines, see above):
     bool found = FindCharInReadable('\n', lineStart, strEnd);
     bool quoted = false;
-    if (found)
-    {
+    if (found) {
       // if there's another newline, lineStart now points there.
       // Loop over any consecutive newline chars:
       nsAString::const_iterator firstNewline (lineStart);
-      while (*lineStart == '\n')
+      while (*lineStart == '\n') {
         ++lineStart;
+      }
       quoted = (*lineStart == cite);
-      if (quoted == curHunkIsQuoted)
+      if (quoted == curHunkIsQuoted) {
         continue;
+      }
       // else we're changing state, so we need to insert
       // from curHunk to lineStart then loop around.
 
       // But if the current hunk is quoted, then we want to make sure
       // that any extra newlines on the end do not get included in
       // the quoted section: blank lines flaking a quoted section
       // should be considered unquoted, so that if the user clicks
       // there and starts typing, the new text will be outside of
       // the quoted block.
-      if (curHunkIsQuoted)
+      if (curHunkIsQuoted) {
         lineStart = firstNewline;
+      }
     }
 
     // If no newline found, lineStart is now strEnd and we can finish up,
     // inserting from curHunk to lineStart then returning.
     const nsAString &curHunk = Substring(hunkStart, lineStart);
     nsCOMPtr<nsIDOMNode> dummyNode;
-    if (curHunkIsQuoted)
+    if (curHunkIsQuoted) {
       rv = InsertAsPlaintextQuotation(curHunk, false,
                                       getter_AddRefs(dummyNode));
-    else
+    } else {
       rv = InsertText(curHunk);
-
-    if (!found)
+    }
+    if (!found) {
       break;
-
+    }
     curHunkIsQuoted = quoted;
     hunkStart = lineStart;
   }
 
   EndTransaction();
 
   return rv;
 }
 
 NS_IMETHODIMP
 HTMLEditor::InsertAsQuotation(const nsAString& aQuotedText,
                               nsIDOMNode** aNodeInserted)
 {
-  if (IsPlaintextEditor())
+  if (IsPlaintextEditor()) {
     return InsertAsPlaintextQuotation(aQuotedText, true, aNodeInserted);
+  }
 
   nsAutoString citation;
   return InsertAsCitedQuotation(aQuotedText, citation, false,
                                 aNodeInserted);
 }
 
 // Insert plaintext as a quotation, with cite marks (e.g. "> ").
 // This differs from its corresponding method in TextEditor
@@ -1904,33 +1858,32 @@ HTMLEditor::InsertAsPlaintextQuotation(c
     // Allow wrapping on spans so long lines get wrapped to the screen.
     newNode->SetAttr(kNameSpaceID_None, nsGkAtoms::style,
                      NS_LITERAL_STRING("white-space: pre-wrap;"), true);
 
     // and set the selection inside it:
     selection->Collapse(newNode, 0);
   }
 
-  if (aAddCites)
+  if (aAddCites) {
     rv = TextEditor::InsertAsQuotation(aQuotedText, aNodeInserted);
-  else
+  } else {
     rv = TextEditor::InsertText(aQuotedText);
+  }
   // Note that if !aAddCites, aNodeInserted isn't set.
   // That's okay because the routines that use aAddCites
   // don't need to know the inserted node.
 
-  if (aNodeInserted && NS_SUCCEEDED(rv))
-  {
+  if (aNodeInserted && NS_SUCCEEDED(rv)) {
     *aNodeInserted = GetAsDOMNode(newNode);
     NS_IF_ADDREF(*aNodeInserted);
   }
 
   // Set the selection to just after the inserted node:
-  if (NS_SUCCEEDED(rv) && newNode)
-  {
+  if (NS_SUCCEEDED(rv) && newNode) {
     nsCOMPtr<nsINode> parent = newNode->GetParentNode();
     int32_t offset = parent ? parent->IndexOf(newNode) : -1;
     if (parent) {
       selection->Collapse(parent, offset + 1);
     }
   }
   return rv;
 }
@@ -1949,18 +1902,17 @@ HTMLEditor::Rewrap(bool aRespectNewlines
 
 NS_IMETHODIMP
 HTMLEditor::InsertAsCitedQuotation(const nsAString& aQuotedText,
                                    const nsAString& aCitation,
                                    bool aInsertHTML,
                                    nsIDOMNode** aNodeInserted)
 {
   // Don't let anyone insert html into a "plaintext" editor:
-  if (IsPlaintextEditor())
-  {
+  if (IsPlaintextEditor()) {
     NS_ASSERTION(!aInsertHTML, "InsertAsCitedQuotation: trying to insert html into plaintext editor");
     return InsertAsPlaintextQuotation(aQuotedText, true, aNodeInserted);
   }
 
   // get selection
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
 
@@ -1989,30 +1941,29 @@ HTMLEditor::InsertAsCitedQuotation(const
 
   if (!aCitation.IsEmpty()) {
     newNode->SetAttr(kNameSpaceID_None, nsGkAtoms::cite, aCitation, true);
   }
 
   // Set the selection inside the blockquote so aQuotedText will go there:
   selection->Collapse(newNode, 0);
 
-  if (aInsertHTML)
+  if (aInsertHTML) {
     rv = LoadHTML(aQuotedText);
-  else
+  } else {
     rv = InsertText(aQuotedText);  // XXX ignore charset
+  }
 
-  if (aNodeInserted && NS_SUCCEEDED(rv))
-  {
+  if (aNodeInserted && NS_SUCCEEDED(rv)) {
     *aNodeInserted = GetAsDOMNode(newNode);
     NS_IF_ADDREF(*aNodeInserted);
   }
 
   // Set the selection to just after the inserted node:
-  if (NS_SUCCEEDED(rv) && newNode)
-  {
+  if (NS_SUCCEEDED(rv) && newNode) {
     nsCOMPtr<nsINode> parent = newNode->GetParentNode();
     int32_t offset = parent ? parent->IndexOf(newNode) : -1;
     if (parent) {
       selection->Collapse(parent, offset + 1);
     }
   }
   return rv;
 }
@@ -2062,38 +2013,34 @@ nsresult FindTargetNode(nsIDOMNode *aSta
 {
   NS_ENSURE_TRUE(aStart, NS_OK);
 
   nsCOMPtr<nsIDOMNode> child, tmp;
 
   nsresult rv = aStart->GetFirstChild(getter_AddRefs(child));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (!child)
-  {
+  if (!child) {
     // If the current result is nullptr, then aStart is a leaf, and is the
     // fallback result.
-    if (!aResult)
+    if (!aResult) {
       aResult = aStart;
-
+    }
     return NS_OK;
   }
 
-  do
-  {
+  do {
     // Is this child the magical cookie?
     nsCOMPtr<nsIDOMComment> comment = do_QueryInterface(child);
-    if (comment)
-    {
+    if (comment) {
       nsAutoString data;
       rv = comment->GetData(data);
       NS_ENSURE_SUCCESS(rv, rv);
 
-      if (data.EqualsLiteral(kInsertCookie))
-      {
+      if (data.EqualsLiteral(kInsertCookie)) {
         // Yes it is! Return an error so we bubble out and short-circuit the
         // search.
         aResult = aStart;
 
         // Note: it doesn't matter if this fails.
         aStart->RemoveChild(child, getter_AddRefs(tmp));
 
         return NS_SUCCESS_EDITOR_FOUND_TARGET;
--- a/editor/libeditor/HTMLEditorObjectResizer.cpp
+++ b/editor/libeditor/HTMLEditorObjectResizer.cpp
@@ -59,18 +59,19 @@ DocumentResizeEventListener::DocumentRes
 {
   mEditor = do_GetWeakReference(aEditor);
 }
 
 NS_IMETHODIMP
 DocumentResizeEventListener::HandleEvent(nsIDOMEvent* aMouseEvent)
 {
   nsCOMPtr<nsIHTMLObjectResizer> objectResizer = do_QueryReferent(mEditor);
-  if (objectResizer)
+  if (objectResizer) {
     return objectResizer->RefreshResizers();
+  }
   return NS_OK;
 }
 
 /******************************************************************************
  * mozilla::ResizerSelectionListener
  ******************************************************************************/
 
 NS_IMPL_ISUPPORTS(ResizerSelectionListener, nsISelectionListener)
@@ -82,23 +83,23 @@ ResizerSelectionListener::ResizerSelecti
 
 NS_IMETHODIMP
 ResizerSelectionListener::NotifySelectionChanged(nsIDOMDocument* aDOMDocument,
                                                  nsISelection* aSelection,
                                                  int16_t aReason)
 {
   if ((aReason & (nsISelectionListener::MOUSEDOWN_REASON |
                   nsISelectionListener::KEYPRESS_REASON |
-                  nsISelectionListener::SELECTALL_REASON)) && aSelection)
-  {
+                  nsISelectionListener::SELECTALL_REASON)) && aSelection) {
     // the selection changed and we need to check if we have to
     // hide and/or redisplay resizing handles
     nsCOMPtr<nsIHTMLEditor> editor = do_QueryReferent(mEditor);
-    if (editor)
+    if (editor) {
       editor->CheckSelectionStateForAnonymousButtons(aSelection);
+    }
   }
 
   return NS_OK;
 }
 
 /******************************************************************************
  * mozilla::ResizerMouseMotionListener
  ******************************************************************************/
@@ -116,18 +117,17 @@ ResizerMouseMotionListener::HandleEvent(
   nsCOMPtr<nsIDOMMouseEvent> mouseEvent ( do_QueryInterface(aMouseEvent) );
   if (!mouseEvent) {
     //non-ui event passed in.  bad things.
     return NS_OK;
   }
 
   // Don't do anything special if not an HTML object resizer editor
   nsCOMPtr<nsIHTMLObjectResizer> objectResizer = do_QueryReferent(mEditor);
-  if (objectResizer)
-  {
+  if (objectResizer) {
     // check if we have to redisplay a resizing shadow
     objectResizer->MouseMove(aMouseEvent);
   }
 
   return NS_OK;
 }
 
 /******************************************************************************
@@ -364,20 +364,24 @@ HTMLEditor::ShowResizersInner(nsIDOMElem
   NS_ENSURE_TRUE(mResizingInfo, NS_ERROR_FAILURE);
 
   // and listen to the "resize" event on the window first, get the
   // window from the document...
   nsCOMPtr<nsIDocument> doc = GetDocument();
   NS_ENSURE_TRUE(doc, NS_ERROR_NULL_POINTER);
 
   nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(doc->GetWindow());
-  if (!target) { return NS_ERROR_NULL_POINTER; }
+  if (!target) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   mResizeEventListenerP = new DocumentResizeEventListener(this);
-  if (!mResizeEventListenerP) { return NS_ERROR_OUT_OF_MEMORY; }
+  if (!mResizeEventListenerP) {
+    return NS_ERROR_OUT_OF_MEMORY;
+  }
   rv = target->AddEventListener(NS_LITERAL_STRING("resize"),
                                 mResizeEventListenerP, false);
   // XXX Even when it failed to add event listener, should we need to set
   //     _moz_resizing attribute?
   aResizedElement->SetAttribute(NS_LITERAL_STRING("_moz_resizing"), NS_LITERAL_STRING("true"));
   return rv;
 }
 
@@ -445,29 +449,32 @@ HTMLEditor::HideResizers()
                                 true);
     mActivatedHandle = nullptr;
   }
 
   // don't forget to remove the listeners !
 
   nsCOMPtr<nsIDOMEventTarget> target = GetDOMEventTarget();
 
-  if (target && mMouseMotionListenerP)
-  {
+  if (target && mMouseMotionListenerP) {
     DebugOnly<nsresult> rv =
       target->RemoveEventListener(NS_LITERAL_STRING("mousemove"),
                                   mMouseMotionListenerP, true);
     NS_ASSERTION(NS_SUCCEEDED(rv), "failed to remove mouse motion listener");
   }
   mMouseMotionListenerP = nullptr;
 
   nsCOMPtr<nsIDocument> doc = GetDocument();
-  if (!doc) { return NS_ERROR_NULL_POINTER; }
+  if (!doc) {
+    return NS_ERROR_NULL_POINTER;
+  }
   target = do_QueryInterface(doc->GetWindow());
-  if (!target) { return NS_ERROR_NULL_POINTER; }
+  if (!target) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   if (mResizeEventListenerP) {
     DebugOnly<nsresult> rv =
       target->RemoveEventListener(NS_LITERAL_STRING("resize"),
                                   mResizeEventListenerP, false);
     NS_ASSERTION(NS_SUCCEEDED(rv), "failed to remove resize event listener");
   }
   mResizeEventListenerP = nullptr;
@@ -476,22 +483,24 @@ HTMLEditor::HideResizers()
   mResizedObject = nullptr;
 
   return NS_OK;
 }
 
 void
 HTMLEditor::HideShadowAndInfo()
 {
-  if (mResizingShadow)
+  if (mResizingShadow) {
     mResizingShadow->SetAttr(kNameSpaceID_None, nsGkAtoms::_class,
                              NS_LITERAL_STRING("hidden"), true);
-  if (mResizingInfo)
+  }
+  if (mResizingInfo) {
     mResizingInfo->SetAttr(kNameSpaceID_None, nsGkAtoms::_class,
                            NS_LITERAL_STRING("hidden"), true);
+  }
 }
 
 nsresult
 HTMLEditor::StartResizing(nsIDOMElement* aHandle)
 {
   // First notify the listeners if any
   for (auto& listener : mObjectResizeEventListeners) {
     listener->OnStartResizing(static_cast<nsIDOMElement*>(GetAsDOMNode(mResizedObject)));
@@ -508,36 +517,29 @@ HTMLEditor::StartResizing(nsIDOMElement*
     Preferences::GetBool("editor.resizing.preserve_ratio", true);
 
   // the way we change the position/size of the shadow depends on
   // the handle
   nsAutoString locationStr;
   aHandle->GetAttribute(NS_LITERAL_STRING("anonlocation"), locationStr);
   if (locationStr.Equals(kTopLeft)) {
     SetResizeIncrements(1, 1, -1, -1, preserveRatio);
-  }
-  else if (locationStr.Equals(kTop)) {
+  } else if (locationStr.Equals(kTop)) {
     SetResizeIncrements(0, 1, 0, -1, false);
-  }
-  else if (locationStr.Equals(kTopRight)) {
+  } else if (locationStr.Equals(kTopRight)) {
     SetResizeIncrements(0, 1, 1, -1, preserveRatio);
-  }
-  else if (locationStr.Equals(kLeft)) {
+  } else if (locationStr.Equals(kLeft)) {
     SetResizeIncrements(1, 0, -1, 0, false);
-  }
-  else if (locationStr.Equals(kRight)) {
+  } else if (locationStr.Equals(kRight)) {
     SetResizeIncrements(0, 0, 1, 0, false);
-  }
-  else if (locationStr.Equals(kBottomLeft)) {
+  } else if (locationStr.Equals(kBottomLeft)) {
     SetResizeIncrements(1, 0, -1, 1, preserveRatio);
-  }
-  else if (locationStr.Equals(kBottom)) {
+  } else if (locationStr.Equals(kBottom)) {
     SetResizeIncrements(0, 0, 0, 1, false);
-  }
-  else if (locationStr.Equals(kBottomRight)) {
+  } else if (locationStr.Equals(kBottomRight)) {
     SetResizeIncrements(0, 0, 1, 1, preserveRatio);
   }
 
   // make the shadow appear
   mResizingShadow->UnsetAttr(kNameSpaceID_None, nsGkAtoms::_class, true);
 
   // position it
   mCSSEditUtils->SetCSSPropertyPixels(*mResizingShadow, *nsGkAtoms::width,
@@ -602,18 +604,17 @@ HTMLEditor::MouseUp(int32_t aClientX,
                     nsIDOMElement* aTarget)
 {
   if (mIsResizing) {
     // we are resizing and release the mouse button, so let's
     // end the resizing process
     mIsResizing = false;
     HideShadowAndInfo();
     SetFinalSize(aClientX, aClientY);
-  }
-  else if (mIsMoving || mGrabberClicked) {
+  } else if (mIsMoving || mGrabberClicked) {
     if (mIsMoving) {
       mPositioningShadow->SetAttr(kNameSpaceID_None, nsGkAtoms::_class,
                                   NS_LITERAL_STRING("hidden"), true);
       SetFinalPosition(aClientX, aClientY);
     }
     if (mGrabberClicked) {
       EndMoving();
     }
@@ -648,37 +649,39 @@ HTMLEditor::SetResizingInfoPosition(int3
   // resizer is the "activated handle".  For example, place the resizing
   // info box at the bottom-right corner of the new element, if the element
   // is being resized by the bottom-right resizer.
   int32_t infoXPosition;
   int32_t infoYPosition;
 
   if (mActivatedHandle == mTopLeftHandle ||
       mActivatedHandle == mLeftHandle ||
-      mActivatedHandle == mBottomLeftHandle)
+      mActivatedHandle == mBottomLeftHandle) {
     infoXPosition = aX;
-  else if (mActivatedHandle == mTopHandle ||
-             mActivatedHandle == mBottomHandle)
+  } else if (mActivatedHandle == mTopHandle ||
+             mActivatedHandle == mBottomHandle) {
     infoXPosition = aX + (aW / 2);
-  else
+  } else {
     // should only occur when mActivatedHandle is one of the 3 right-side
     // handles, but this is a reasonable default if it isn't any of them (?)
     infoXPosition = aX + aW;
+  }
 
   if (mActivatedHandle == mTopLeftHandle ||
       mActivatedHandle == mTopHandle ||
-      mActivatedHandle == mTopRightHandle)
+      mActivatedHandle == mTopRightHandle) {
     infoYPosition = aY;
-  else if (mActivatedHandle == mLeftHandle ||
-           mActivatedHandle == mRightHandle)
+  } else if (mActivatedHandle == mLeftHandle ||
+             mActivatedHandle == mRightHandle) {
     infoYPosition = aY + (aH / 2);
-  else
+  } else {
     // should only occur when mActivatedHandle is one of the 3 bottom-side
     // handles, but this is a reasonable default if it isn't any of them (?)
     infoYPosition = aY + aH;
+  }
 
   // Offset info box by 20 so it's not directly under the mouse cursor.
   const int mouseCursorOffset = 20;
   mCSSEditUtils->SetCSSPropertyPixels(*mResizingInfo, *nsGkAtoms::left,
                                       infoXPosition + mouseCursorOffset);
   mCSSEditUtils->SetCSSPropertyPixels(*mResizingInfo, *nsGkAtoms::top,
                                       infoYPosition + mouseCursorOffset);
 
@@ -690,20 +693,22 @@ HTMLEditor::SetResizingInfoPosition(int3
     textInfo = nullptr;
   }
 
   nsAutoString widthStr, heightStr, diffWidthStr, diffHeightStr;
   widthStr.AppendInt(aW);
   heightStr.AppendInt(aH);
   int32_t diffWidth  = aW - mResizedObjectWidth;
   int32_t diffHeight = aH - mResizedObjectHeight;
-  if (diffWidth > 0)
+  if (diffWidth > 0) {
     diffWidthStr.Assign('+');
-  if (diffHeight > 0)
+  }
+  if (diffHeight > 0) {
     diffHeightStr.Assign('+');
+  }
   diffWidthStr.AppendInt(diffWidth);
   diffHeightStr.AppendInt(diffHeight);
 
   nsAutoString info(widthStr + NS_LITERAL_STRING(" x ") + heightStr +
                     NS_LITERAL_STRING(" (") + diffWidthStr +
                     NS_LITERAL_STRING(", ") + diffHeightStr +
                     NS_LITERAL_STRING(")"));
 
@@ -916,68 +921,74 @@ HTMLEditor::SetFinalSize(int32_t aX,
   AutoEditBatch batchIt(this);
 
   NS_NAMED_LITERAL_STRING(widthStr,  "width");
   NS_NAMED_LITERAL_STRING(heightStr, "height");
 
   nsCOMPtr<Element> resizedObject = do_QueryInterface(mResizedObject);
   NS_ENSURE_TRUE(resizedObject, );
   if (mResizedObjectIsAbsolutelyPositioned) {
-    if (setHeight)
+    if (setHeight) {
       mCSSEditUtils->SetCSSPropertyPixels(*resizedObject, *nsGkAtoms::top, y);
-    if (setWidth)
+    }
+    if (setWidth) {
       mCSSEditUtils->SetCSSPropertyPixels(*resizedObject, *nsGkAtoms::left, x);
+    }
   }
   if (IsCSSEnabled() || mResizedObjectIsAbsolutelyPositioned) {
     if (setWidth && mResizedObject->HasAttr(kNameSpaceID_None, nsGkAtoms::width)) {
       RemoveAttribute(static_cast<nsIDOMElement*>(GetAsDOMNode(mResizedObject)), widthStr);
     }
 
     if (setHeight && mResizedObject->HasAttr(kNameSpaceID_None,
                                              nsGkAtoms::height)) {
       RemoveAttribute(static_cast<nsIDOMElement*>(GetAsDOMNode(mResizedObject)), heightStr);
     }
 
-    if (setWidth)
+    if (setWidth) {
       mCSSEditUtils->SetCSSPropertyPixels(*resizedObject, *nsGkAtoms::width,
                                           width);
-    if (setHeight)
+    }
+    if (setHeight) {
       mCSSEditUtils->SetCSSPropertyPixels(*resizedObject, *nsGkAtoms::height,
                                           height);
-  }
-  else {
+    }
+  } else {
     // we use HTML size and remove all equivalent CSS properties
 
     // we set the CSS width and height to remove it later,
     // triggering an immediate reflow; otherwise, we have problems
     // with asynchronous reflow
-    if (setWidth)
+    if (setWidth) {
       mCSSEditUtils->SetCSSPropertyPixels(*resizedObject, *nsGkAtoms::width,
                                           width);
-    if (setHeight)
+    }
+    if (setHeight) {
       mCSSEditUtils->SetCSSPropertyPixels(*resizedObject, *nsGkAtoms::height,
                                           height);
-
+    }
     if (setWidth) {
       nsAutoString w;
       w.AppendInt(width);
       SetAttribute(static_cast<nsIDOMElement*>(GetAsDOMNode(mResizedObject)), widthStr, w);
     }
     if (setHeight) {
       nsAutoString h;
       h.AppendInt(height);
       SetAttribute(static_cast<nsIDOMElement*>(GetAsDOMNode(mResizedObject)), heightStr, h);
     }
 
-    if (setWidth)
+    if (setWidth) {
       mCSSEditUtils->RemoveCSSProperty(*resizedObject, *nsGkAtoms::width,
                                        EmptyString());
-    if (setHeight)
+    }
+    if (setHeight) {
       mCSSEditUtils->RemoveCSSProperty(*resizedObject, *nsGkAtoms::height,
                                        EmptyString());
+    }
   }
   // finally notify the listeners if any
   for (auto& listener : mObjectResizeEventListeners) {
     listener->OnEndResizing(static_cast<nsIDOMElement*>(GetAsDOMNode(mResizedObject)),
                             mResizedObjectWidth, mResizedObjectHeight, width,
                             height);
   }
 
--- a/editor/libeditor/HTMLStyleEditor.cpp
+++ b/editor/libeditor/HTMLStyleEditor.cpp
@@ -59,52 +59,49 @@ IsEmptyTextNode(HTMLEditor* aThis, nsINo
 NS_IMETHODIMP
 HTMLEditor::AddDefaultProperty(nsIAtom* aProperty,
                                const nsAString& aAttribute,
                                const nsAString& aValue)
 {
   nsString outValue;
   int32_t index;
   nsString attr(aAttribute);
-  if (TypeInState::FindPropInList(aProperty, attr, &outValue, mDefaultStyles, index))
-  {
+  if (TypeInState::FindPropInList(aProperty, attr, &outValue,
+                                  mDefaultStyles, index)) {
     PropItem *item = mDefaultStyles[index];
     item->value = aValue;
-  }
-  else
-  {
+  } else {
     nsString value(aValue);
     PropItem *propItem = new PropItem(aProperty, attr, value);
     mDefaultStyles.AppendElement(propItem);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditor::RemoveDefaultProperty(nsIAtom* aProperty,
                                   const nsAString& aAttribute,
                                   const nsAString& aValue)
 {
   nsString outValue;
   int32_t index;
   nsString attr(aAttribute);
-  if (TypeInState::FindPropInList(aProperty, attr, &outValue, mDefaultStyles, index))
-  {
+  if (TypeInState::FindPropInList(aProperty, attr, &outValue,
+                                  mDefaultStyles, index)) {
     delete mDefaultStyles[index];
     mDefaultStyles.RemoveElementAt(index);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditor::RemoveAllDefaultProperties()
 {
-  uint32_t j, defcon = mDefaultStyles.Length();
-  for (j=0; j<defcon; j++)
-  {
+  size_t defcon = mDefaultStyles.Length();
+  for (size_t j = 0; j < defcon; j++) {
     delete mDefaultStyles[j];
   }
   mDefaultStyles.Clear();
   return NS_OK;
 }
 
 
 NS_IMETHODIMP
@@ -688,19 +685,18 @@ HTMLEditor::NodeIsProperty(nsINode& aNod
 {
   return IsContainer(&aNode) && IsEditable(&aNode) && !IsBlockNode(&aNode) &&
          !aNode.IsHTMLElement(nsGkAtoms::a);
 }
 
 nsresult
 HTMLEditor::ApplyDefaultProperties()
 {
-  uint32_t j, defcon = mDefaultStyles.Length();
-  for (j=0; j<defcon; j++)
-  {
+  size_t defcon = mDefaultStyles.Length();
+  for (size_t j = 0; j < defcon; j++) {
     PropItem *propItem = mDefaultStyles[j];
     NS_ENSURE_TRUE(propItem, NS_ERROR_NULL_POINTER);
     nsresult rv =
       SetInlineProperty(propItem->tag, propItem->attr, propItem->value);
     NS_ENSURE_SUCCESS(rv, rv);
   }
   return NS_OK;
 }
@@ -722,27 +718,24 @@ HTMLEditor::RemoveStyleInside(nsIContent
     nsCOMPtr<nsIContent> next = child->GetNextSibling();
     nsresult rv = RemoveStyleInside(*child, aProperty, aAttribute);
     NS_ENSURE_SUCCESS(rv, rv);
     child = next.forget();
   }
 
   // then process the node itself
   if (!aChildrenOnly &&
-    (
-      // node is prop we asked for
-      (aProperty && aNode.NodeInfo()->NameAtom() == aProperty) ||
-      // but check for link (<a href=...)
-      (aProperty == nsGkAtoms::href && HTMLEditUtils::IsLink(&aNode)) ||
-      // and for named anchors
-      (aProperty == nsGkAtoms::name && HTMLEditUtils::IsNamedAnchor(&aNode)) ||
-      // or node is any prop and we asked for that
-      (!aProperty && NodeIsProperty(aNode))
-    )
-  ) {
+       // node is prop we asked for
+      ((aProperty && aNode.NodeInfo()->NameAtom() == aProperty) ||
+       // but check for link (<a href=...)
+       (aProperty == nsGkAtoms::href && HTMLEditUtils::IsLink(&aNode)) ||
+       // and for named anchors
+       (aProperty == nsGkAtoms::name && HTMLEditUtils::IsNamedAnchor(&aNode)) ||
+       // or node is any prop and we asked for that
+       (!aProperty && NodeIsProperty(aNode)))) {
     // if we weren't passed an attribute, then we want to
     // remove any matching inlinestyles entirely
     if (!aAttribute || aAttribute->IsEmpty()) {
       NS_NAMED_LITERAL_STRING(styleAttr, "style");
       NS_NAMED_LITERAL_STRING(classAttr, "class");
 
       bool hasStyleAttr = aNode.HasAttr(kNameSpaceID_None, nsGkAtoms::style);
       bool hasClassAttr = aNode.HasAttr(kNameSpaceID_None, nsGkAtoms::_class);
@@ -803,24 +796,24 @@ HTMLEditor::RemoveStyleInside(nsIContent
                                                     &propertyValue,
                                                     false);
       // remove the node if it is a span or font, if its style attribute is
       // empty or absent, and if it does not have a class nor an id
       RemoveElementIfNoStyleOrIdOrClass(*aNode.AsElement());
     }
   }
 
-  if (!aChildrenOnly &&
-    (
-      // Or node is big or small and we are setting font size
-      aProperty == nsGkAtoms::font &&
-      (aNode.IsHTMLElement(nsGkAtoms::big) || aNode.IsHTMLElement(nsGkAtoms::small)) &&
-      (aAttribute && aAttribute->LowerCaseEqualsLiteral("size"))
-    )
-  ) {
+  // Or node is big or small and we are setting font size
+  if (aChildrenOnly) {
+    return NS_OK;
+  }
+  if (aProperty == nsGkAtoms::font &&
+      (aNode.IsHTMLElement(nsGkAtoms::big) ||
+       aNode.IsHTMLElement(nsGkAtoms::small)) &&
+      aAttribute && aAttribute->LowerCaseEqualsLiteral("size")) {
     // if we are setting font size, remove any nested bigs and smalls
     return RemoveContainer(&aNode);
   }
   return NS_OK;
 }
 
 bool
 HTMLEditor::IsOnlyAttribute(const nsIContent* aContent,
--- a/editor/libeditor/HTMLTableEditor.cpp
+++ b/editor/libeditor/HTMLTableEditor.cpp
@@ -90,17 +90,19 @@ NS_IMETHODIMP
 HTMLEditor::InsertCell(nsIDOMElement* aCell,
                        int32_t aRowSpan,
                        int32_t aColSpan,
                        bool aAfter,
                        bool aIsHeader,
                        nsIDOMElement** aNewCell)
 {
   NS_ENSURE_TRUE(aCell, NS_ERROR_NULL_POINTER);
-  if (aNewCell) *aNewCell = nullptr;
+  if (aNewCell) {
+    *aNewCell = nullptr;
+  }
 
   // And the parent and offsets needed to do an insert
   nsCOMPtr<nsIDOMNode> cellParent;
   nsresult rv = aCell->GetParentNode(getter_AddRefs(cellParent));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(cellParent, NS_ERROR_NULL_POINTER);
 
   int32_t cellOffset = GetChildOffset(aCell, cellParent);
@@ -112,37 +114,36 @@ HTMLEditor::InsertCell(nsIDOMElement* aC
   if (NS_FAILED(rv)) {
     return rv;
   }
   if (!newCell) {
     return NS_ERROR_FAILURE;
   }
 
   //Optional: return new cell created
-  if (aNewCell)
-  {
+  if (aNewCell) {
     *aNewCell = newCell.get();
     NS_ADDREF(*aNewCell);
   }
 
-  if( aRowSpan > 1)
-  {
+  if (aRowSpan > 1) {
     // Note: Do NOT use editor transaction for this
     nsAutoString newRowSpan;
     newRowSpan.AppendInt(aRowSpan, 10);
     newCell->SetAttribute(NS_LITERAL_STRING("rowspan"), newRowSpan);
   }
-  if( aColSpan > 1)
-  {
+  if (aColSpan > 1) {
     // Note: Do NOT use editor transaction for this
     nsAutoString newColSpan;
     newColSpan.AppendInt(aColSpan, 10);
     newCell->SetAttribute(NS_LITERAL_STRING("colspan"), newColSpan);
   }
-  if(aAfter) cellOffset++;
+  if (aAfter) {
+    cellOffset++;
+  }
 
   //Don't let Rules System change the selection
   AutoTransactionsConserveSelection dontChangeSelection(this);
   return InsertNode(newCell, cellParent, cellOffset);
 }
 
 NS_IMETHODIMP
 HTMLEditor::SetColSpan(nsIDOMElement* aCell,
@@ -193,19 +194,17 @@ HTMLEditor::InsertTableCell(int32_t aNum
   int32_t newCellIndex = aAfter ? (startColIndex+colSpan) : startColIndex;
   //We control selection resetting after the insert...
   AutoSelectionSetterAfterTableEdit setCaret(this, table, startRowIndex,
                                              newCellIndex, ePreviousColumn,
                                              false);
   //...so suppress Rules System selection munging
   AutoTransactionsConserveSelection dontChangeSelection(this);
 
-  int32_t i;
-  for (i = 0; i < aNumber; i++)
-  {
+  for (int32_t i = 0; i < aNumber; i++) {
     nsCOMPtr<nsIDOMElement> newCell;
     rv = CreateElementWithDefaults(NS_LITERAL_STRING("td"),
                                    getter_AddRefs(newCell));
     if (NS_SUCCEEDED(rv) && newCell) {
       if (aAfter) {
         cellOffset++;
       }
       rv = InsertNode(newCell, cellParent, cellOffset);
@@ -235,21 +234,19 @@ HTMLEditor::GetFirstRow(nsIDOMElement* a
                                             getter_AddRefs(tableElement));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(tableElement, NS_ERROR_NULL_POINTER);
 
   nsCOMPtr<nsIDOMNode> tableChild;
   rv = tableElement->GetFirstChild(getter_AddRefs(tableChild));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  while (tableChild)
-  {
+  while (tableChild) {
     nsCOMPtr<nsIContent> content = do_QueryInterface(tableChild);
-    if (content)
-    {
+    if (content) {
       if (content->IsHTMLElement(nsGkAtoms::tr)) {
         // Found a row directly under <table>
         *aRowNode = tableChild;
         NS_ADDREF(*aRowNode);
         return NS_OK;
       }
       // Look for row in one of the row container elements
       if (content->IsAnyOfHTMLElements(nsGkAtoms::tbody,
@@ -262,18 +259,17 @@ HTMLEditor::GetFirstRow(nsIDOMElement* a
         // We can encounter textnodes here -- must find a row
         while (rowNode && !HTMLEditUtils::IsTableRow(rowNode)) {
           nsCOMPtr<nsIDOMNode> nextNode;
           rv = rowNode->GetNextSibling(getter_AddRefs(nextNode));
           NS_ENSURE_SUCCESS(rv, rv);
 
           rowNode = nextNode;
         }
-        if(rowNode)
-        {
+        if (rowNode) {
           *aRowNode = rowNode.get();
           NS_ADDREF(*aRowNode);
           return NS_OK;
         }
       }
     }
     // Here if table child was a CAPTION or COLGROUP
     //  or child of a row parent wasn't a row (bad HTML?),
@@ -311,47 +307,44 @@ HTMLEditor::GetNextRow(nsIDOMNode* aCurr
 
   // Skip over any textnodes here
   while (nextRow && !HTMLEditUtils::IsTableRow(nextRow)) {
     rv = nextRow->GetNextSibling(getter_AddRefs(nextNode));
     NS_ENSURE_SUCCESS(rv, rv);
 
     nextRow = nextNode;
   }
-  if(nextRow)
-  {
+  if (nextRow) {
     *aRowNode = nextRow.get();
     NS_ADDREF(*aRowNode);
     return NS_OK;
   }
 
   // No row found, search for rows in other table sections
   nsCOMPtr<nsIDOMNode> rowParent;
   rv = aCurrentRowNode->GetParentNode(getter_AddRefs(rowParent));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(rowParent, NS_ERROR_NULL_POINTER);
 
   nsCOMPtr<nsIDOMNode> parentSibling;
   rv = rowParent->GetNextSibling(getter_AddRefs(parentSibling));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  while (parentSibling)
-  {
+  while (parentSibling) {
     rv = parentSibling->GetFirstChild(getter_AddRefs(nextRow));
     NS_ENSURE_SUCCESS(rv, rv);
 
     // We can encounter textnodes here -- must find a row
     while (nextRow && !HTMLEditUtils::IsTableRow(nextRow)) {
       rv = nextRow->GetNextSibling(getter_AddRefs(nextNode));
       NS_ENSURE_SUCCESS(rv, rv);
 
       nextRow = nextNode;
     }
-    if(nextRow)
-    {
+    if (nextRow) {
       *aRowNode = nextRow.get();
       NS_ADDREF(*aRowNode);
       return NS_OK;
     }
 
     // We arrive here only if a table section has no children
     //  or first child of section is not a row (bad HTML or more "_moz_text" nodes!)
     // So look for another section sibling
@@ -381,18 +374,17 @@ HTMLEditor::GetLastCellInRow(nsIDOMNode*
   while (rowChild && !HTMLEditUtils::IsTableCell(rowChild)) {
     // Skip over textnodes
     nsCOMPtr<nsIDOMNode> previousChild;
     rv = rowChild->GetPreviousSibling(getter_AddRefs(previousChild));
     NS_ENSURE_SUCCESS(rv, rv);
 
     rowChild = previousChild;
   }
-  if (rowChild)
-  {
+  if (rowChild) {
     *aCellNode = rowChild.get();
     NS_ADDREF(*aCellNode);
     return NS_OK;
   }
   // If here, cell was not found
   return NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND;
 }
 
@@ -424,69 +416,67 @@ HTMLEditor::InsertTableColumn(int32_t aN
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(curCell, NS_ERROR_FAILURE);
 
   AutoEditBatch beginBatching(this);
   // Prevent auto insertion of BR in new cell until we're done
   AutoRules beginRulesSniffing(this, EditAction::insertNode, nsIEditor::eNext);
 
   // Use column after current cell if requested
-  if (aAfter)
-  {
+  if (aAfter) {
     startColIndex += actualColSpan;
     //Detect when user is adding after a COLSPAN=0 case
     // Assume they want to stop the "0" behavior and
     // really add a new column. Thus we set the
     // colspan to its true value
-    if (colSpan == 0)
+    if (!colSpan) {
       SetColSpan(curCell, actualColSpan);
+    }
   }
 
   int32_t rowCount, colCount, rowIndex;
   rv = GetTableSize(table, &rowCount, &colCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
   //We reset caret in destructor...
   AutoSelectionSetterAfterTableEdit setCaret(this, table, startRowIndex,
                                              startColIndex, ePreviousRow,
                                              false);
   //.. so suppress Rules System selection munging
   AutoTransactionsConserveSelection dontChangeSelection(this);
 
   // If we are inserting after all existing columns
   // Make sure table is "well formed"
   //  before appending new column
-  if (startColIndex >= colCount)
+  if (startColIndex >= colCount) {
     NormalizeTable(table);
+  }
 
   nsCOMPtr<nsIDOMNode> rowNode;
-  for ( rowIndex = 0; rowIndex < rowCount; rowIndex++)
-  {
-    if (startColIndex < colCount)
-    {
+  for (rowIndex = 0; rowIndex < rowCount; rowIndex++) {
+    if (startColIndex < colCount) {
       // We are inserting before an existing column
       rv = GetCellDataAt(table, rowIndex, startColIndex,
                          getter_AddRefs(curCell),
                          &curStartRowIndex, &curStartColIndex,
                          &rowSpan, &colSpan,
                          &actualRowSpan, &actualColSpan, &isSelected);
       NS_ENSURE_SUCCESS(rv, rv);
 
       // Don't fail entire process if we fail to find a cell
       //  (may fail just in particular rows with < adequate cells per row)
-      if (curCell)
-      {
-        if (curStartColIndex < startColIndex)
-        {
+      if (curCell) {
+        if (curStartColIndex < startColIndex) {
           // We have a cell spanning this location
           // Simply increase its colspan to keep table rectangular
           // Note: we do nothing if colsSpan=0,
           //  since it should automatically span the new column
-          if (colSpan > 0)
+          if (colSpan > 0) {
             SetColSpan(curCell, colSpan+aNumber);
+          }
         } else {
           // Simply set selection to the current cell
           //  so we can let InsertTableCell() do the work
           // Insert a new cell before current one
           selection->Collapse(curCell, 0);
           rv = InsertTableCell(aNumber, false);
         }
       }
@@ -501,26 +491,24 @@ HTMLEditor::InsertTableColumn(int32_t aN
         nsCOMPtr<nsIDOMNode> nextRow;
         rv = GetNextRow(rowNode.get(), getter_AddRefs(nextRow));
         if (NS_WARN_IF(NS_FAILED(rv))) {
           return rv;
         }
         rowNode = nextRow;
       }
 
-      if (rowNode)
-      {
+      if (rowNode) {
         nsCOMPtr<nsIDOMNode> lastCell;
         rv = GetLastCellInRow(rowNode, getter_AddRefs(lastCell));
         NS_ENSURE_SUCCESS(rv, rv);
         NS_ENSURE_TRUE(lastCell, NS_ERROR_FAILURE);
 
         curCell = do_QueryInterface(lastCell);
-        if (curCell)
-        {
+        if (curCell) {
           // Simply add same number of cells to each row
           // Although tempted to check cell indexes for curCell,
           //  the effects of COLSPAN>1 in some cells makes this futile!
           // We must use NormalizeTable first to assure
           //  that there are cells in each cellmap location
           selection->Collapse(curCell, 0);
           rv = InsertTableCell(aNumber, true);
         }
@@ -562,144 +550,138 @@ HTMLEditor::InsertTableRow(int32_t aNumb
   int32_t rowCount, colCount;
   rv = GetTableSize(table, &rowCount, &colCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
   AutoEditBatch beginBatching(this);
   // Prevent auto insertion of BR in new cell until we're done
   AutoRules beginRulesSniffing(this, EditAction::insertNode, nsIEditor::eNext);
 
-  if (aAfter)
-  {
+  if (aAfter) {
     // Use row after current cell
     startRowIndex += actualRowSpan;
 
     //Detect when user is adding after a ROWSPAN=0 case
     // Assume they want to stop the "0" behavior and
     // really add a new row. Thus we set the
     // rowspan to its true value
-    if (rowSpan == 0)
+    if (!rowSpan) {
       SetRowSpan(curCell, actualRowSpan);
+    }
   }
 
   //We control selection resetting after the insert...
   AutoSelectionSetterAfterTableEdit setCaret(this, table, startRowIndex,
                                              startColIndex, ePreviousColumn,
                                              false);
   //...so suppress Rules System selection munging
   AutoTransactionsConserveSelection dontChangeSelection(this);
 
   nsCOMPtr<nsIDOMElement> cellForRowParent;
   int32_t cellsInRow = 0;
-  if (startRowIndex < rowCount)
-  {
+  if (startRowIndex < rowCount) {
     // We are inserting above an existing row
     // Get each cell in the insert row to adjust for COLSPAN effects while we
     //   count how many cells are needed
     int32_t colIndex = 0;
-    // This returns NS_TABLELAYOUT_CELL_NOT_FOUND when we run past end of row,
-    //   which passes the NS_SUCCEEDED macro
-    while ( NS_OK == GetCellDataAt(table, startRowIndex, colIndex,
-                                   getter_AddRefs(curCell),
-                                   &curStartRowIndex, &curStartColIndex,
-                                   &rowSpan, &colSpan,
-                                   &actualRowSpan, &actualColSpan,
-                                   &isSelected) )
-    {
-      if (curCell)
-      {
-        if (curStartRowIndex < startRowIndex)
-        {
+    while (NS_SUCCEEDED(GetCellDataAt(table, startRowIndex, colIndex,
+                                      getter_AddRefs(curCell),
+                                      &curStartRowIndex, &curStartColIndex,
+                                      &rowSpan, &colSpan,
+                                      &actualRowSpan, &actualColSpan,
+                                      &isSelected))) {
+      if (curCell) {
+        if (curStartRowIndex < startRowIndex) {
           // We have a cell spanning this location
           // Simply increase its rowspan
           //Note that if rowSpan == 0, we do nothing,
           //  since that cell should automatically extend into the new row
-          if (rowSpan > 0)
+          if (rowSpan > 0) {
             SetRowSpan(curCell, rowSpan+aNumber);
+          }
         } else {
           // We have a cell in the insert row
 
           // Count the number of cells we need to add to the new row
           cellsInRow += actualColSpan;
 
           // Save cell we will use below
-          if (!cellForRowParent)
+          if (!cellForRowParent) {
             cellForRowParent = curCell;
+          }
         }
         // Next cell in row
         colIndex += actualColSpan;
+      } else {
+        colIndex++;
       }
-      else
-        colIndex++;
     }
   } else {
     // We are adding a new row after all others
     // If it weren't for colspan=0 effect,
     // we could simply use colCount for number of new cells...
     // XXX colspan=0 support has now been removed in table layout so maybe this can be cleaned up now? (bug 1243183)
     cellsInRow = colCount;
 
     // ...but we must compensate for all cells with rowSpan = 0 in the last row
     int32_t lastRow = rowCount-1;
     int32_t tempColIndex = 0;
-    while ( NS_OK == GetCellDataAt(table, lastRow, tempColIndex,
-                                   getter_AddRefs(curCell),
-                                   &curStartRowIndex, &curStartColIndex,
-                                   &rowSpan, &colSpan,
-                                   &actualRowSpan, &actualColSpan,
-                                   &isSelected) )
-    {
-      if (rowSpan == 0)
+    while (NS_SUCCEEDED(GetCellDataAt(table, lastRow, tempColIndex,
+                                      getter_AddRefs(curCell),
+                                      &curStartRowIndex, &curStartColIndex,
+                                      &rowSpan, &colSpan,
+                                      &actualRowSpan, &actualColSpan,
+                                      &isSelected))) {
+      if (!rowSpan) {
         cellsInRow -= actualColSpan;
+      }
 
       tempColIndex += actualColSpan;
 
       // Save cell from the last row that we will use below
-      if (!cellForRowParent && curStartRowIndex == lastRow)
+      if (!cellForRowParent && curStartRowIndex == lastRow) {
         cellForRowParent = curCell;
+      }
     }
   }
 
-  if (cellsInRow > 0)
-  {
+  if (cellsInRow > 0) {
     // The row parent and offset where we will insert new row
     nsCOMPtr<nsIDOMNode> parentOfRow;
     int32_t newRowOffset;
 
     NS_NAMED_LITERAL_STRING(trStr, "tr");
-    if (cellForRowParent)
-    {
-      nsCOMPtr<nsIDOMElement> parentRow;
-      rv = GetElementOrParentByTagName(trStr, cellForRowParent,
-                                       getter_AddRefs(parentRow));
-      NS_ENSURE_SUCCESS(rv, rv);
-      NS_ENSURE_TRUE(parentRow, NS_ERROR_NULL_POINTER);
-
-      parentRow->GetParentNode(getter_AddRefs(parentOfRow));
-      NS_ENSURE_TRUE(parentOfRow, NS_ERROR_NULL_POINTER);
-
-      newRowOffset = GetChildOffset(parentRow, parentOfRow);
-
-      // Adjust for when adding past the end
-      if (aAfter && startRowIndex >= rowCount)
-        newRowOffset++;
+    if (!cellForRowParent) {
+      return NS_ERROR_FAILURE;
     }
-    else
-      return NS_ERROR_FAILURE;
-
-    for (int32_t row = 0; row < aNumber; row++)
-    {
+
+    nsCOMPtr<nsIDOMElement> parentRow;
+    rv = GetElementOrParentByTagName(trStr, cellForRowParent,
+                                     getter_AddRefs(parentRow));
+    NS_ENSURE_SUCCESS(rv, rv);
+    NS_ENSURE_TRUE(parentRow, NS_ERROR_NULL_POINTER);
+
+    parentRow->GetParentNode(getter_AddRefs(parentOfRow));
+    NS_ENSURE_TRUE(parentOfRow, NS_ERROR_NULL_POINTER);
+
+    newRowOffset = GetChildOffset(parentRow, parentOfRow);
+
+    // Adjust for when adding past the end
+    if (aAfter && startRowIndex >= rowCount) {
+      newRowOffset++;
+    }
+
+    for (int32_t row = 0; row < aNumber; row++) {
       // Create a new row
       nsCOMPtr<nsIDOMElement> newRow;
       rv = CreateElementWithDefaults(trStr, getter_AddRefs(newRow));
       if (NS_SUCCEEDED(rv)) {
         NS_ENSURE_TRUE(newRow, NS_ERROR_FAILURE);
 
-        for (int32_t i = 0; i < cellsInRow; i++)
-        {
+        for (int32_t i = 0; i < cellsInRow; i++) {
           nsCOMPtr<nsIDOMElement> newCell;
           rv = CreateElementWithDefaults(NS_LITERAL_STRING("td"),
                                          getter_AddRefs(newCell));
           NS_ENSURE_SUCCESS(rv, rv);
           NS_ENSURE_TRUE(newCell, NS_ERROR_FAILURE);
 
           // Don't use transaction system yet! (not until entire row is inserted)
           nsCOMPtr<nsIDOMNode>resultNode;
@@ -779,18 +761,17 @@ HTMLEditor::DeleteTableCell(int32_t aNum
   nsCOMPtr<nsIDOMRange> range;
   rv = GetFirstSelectedCell(getter_AddRefs(range), getter_AddRefs(firstCell));
   NS_ENSURE_SUCCESS(rv, rv);
 
   int32_t rangeCount;
   rv = selection->GetRangeCount(&rangeCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (firstCell && rangeCount > 1)
-  {
+  if (firstCell && rangeCount > 1) {
     // When > 1 selected cell,
     //  ignore aNumber and use selected cells
     cell = firstCell;
 
     int32_t rowCount, colCount;
     rv = GetTableSize(table, &rowCount, &colCount);
     NS_ENSURE_SUCCESS(rv, rv);
 
@@ -802,158 +783,148 @@ HTMLEditor::DeleteTableCell(int32_t aNum
     // destructor
     AutoSelectionSetterAfterTableEdit setCaret(this, table, startRowIndex,
                                                startColIndex, ePreviousColumn,
                                                false);
     AutoTransactionsConserveSelection dontChangeSelection(this);
 
     bool    checkToDeleteRow = true;
     bool    checkToDeleteColumn = true;
-    while (cell)
-    {
+    while (cell) {
       bool deleteRow = false;
       bool deleteCol = false;
 
-      if (checkToDeleteRow)
-      {
+      if (checkToDeleteRow) {
         // Optimize to delete an entire row
         // Clear so we don't repeat AllCellsInRowSelected within the same row
         checkToDeleteRow = false;
 
         deleteRow = AllCellsInRowSelected(table, startRowIndex, colCount);
-        if (deleteRow)
-        {
+        if (deleteRow) {
           // First, find the next cell in a different row
           //   to continue after we delete this row
           int32_t nextRow = startRowIndex;
-          while (nextRow == startRowIndex)
-          {
+          while (nextRow == startRowIndex) {
             rv = GetNextSelectedCell(nullptr, getter_AddRefs(cell));
             NS_ENSURE_SUCCESS(rv, rv);
-            if (!cell) break;
+            if (!cell) {
+              break;
+            }
             rv = GetCellIndexes(cell, &nextRow, &startColIndex);
             NS_ENSURE_SUCCESS(rv, rv);
           }
           // Delete entire row
           rv = DeleteRow(table, startRowIndex);
           NS_ENSURE_SUCCESS(rv, rv);
 
-          if (cell)
-          {
+          if (cell) {
             // For the next cell: Subtract 1 for row we deleted
             startRowIndex = nextRow - 1;
             // Set true since we know we will look at a new row next
             checkToDeleteRow = true;
           }
         }
       }
-      if (!deleteRow)
-      {
-        if (checkToDeleteColumn)
-        {
+      if (!deleteRow) {
+        if (checkToDeleteColumn) {
           // Optimize to delete an entire column
           // Clear this so we don't repeat AllCellsInColSelected within the same Col
           checkToDeleteColumn = false;
 
           deleteCol = AllCellsInColumnSelected(table, startColIndex, colCount);
-          if (deleteCol)
-          {
+          if (deleteCol) {
             // First, find the next cell in a different column
             //   to continue after we delete this column
             int32_t nextCol = startColIndex;
-            while (nextCol == startColIndex)
-            {
+            while (nextCol == startColIndex) {
               rv = GetNextSelectedCell(nullptr, getter_AddRefs(cell));
               NS_ENSURE_SUCCESS(rv, rv);
-              if (!cell) break;
+              if (!cell) {
+                break;
+              }
               rv = GetCellIndexes(cell, &startRowIndex, &nextCol);
               NS_ENSURE_SUCCESS(rv, rv);
             }
             // Delete entire Col
             rv = DeleteColumn(table, startColIndex);
             NS_ENSURE_SUCCESS(rv, rv);
-            if (cell)
-            {
+            if (cell) {
               // For the next cell, subtract 1 for col. deleted
               startColIndex = nextCol - 1;
               // Set true since we know we will look at a new column next
               checkToDeleteColumn = true;
             }
           }
         }
-        if (!deleteCol)
-        {
+        if (!deleteCol) {
           // First get the next cell to delete
           nsCOMPtr<nsIDOMElement> nextCell;
           rv = GetNextSelectedCell(getter_AddRefs(range),
                                    getter_AddRefs(nextCell));
           NS_ENSURE_SUCCESS(rv, rv);
 
           // Then delete the cell
           rv = DeleteNode(cell);
           NS_ENSURE_SUCCESS(rv, rv);
 
           // The next cell to delete
           cell = nextCell;
-          if (cell)
-          {
+          if (cell) {
             rv = GetCellIndexes(cell, &startRowIndex, &startColIndex);
             NS_ENSURE_SUCCESS(rv, rv);
           }
         }
       }
     }
-  }
-  else for (int32_t i = 0; i < aNumber; i++)
-  {
-    rv = GetCellContext(getter_AddRefs(selection),
-                        getter_AddRefs(table),
-                        getter_AddRefs(cell),
-                        nullptr, nullptr,
-                        &startRowIndex, &startColIndex);
-    NS_ENSURE_SUCCESS(rv, rv);
-    // Don't fail if no cell found
-    NS_ENSURE_TRUE(cell, NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND);
-
-    if (1 == GetNumberOfCellsInRow(table, startRowIndex))
-    {
-      nsCOMPtr<nsIDOMElement> parentRow;
-      rv = GetElementOrParentByTagName(NS_LITERAL_STRING("tr"), cell,
-                                       getter_AddRefs(parentRow));
+  } else {
+    for (int32_t i = 0; i < aNumber; i++) {
+      rv = GetCellContext(getter_AddRefs(selection),
+                          getter_AddRefs(table),
+                          getter_AddRefs(cell),
+                          nullptr, nullptr,
+                          &startRowIndex, &startColIndex);
       NS_ENSURE_SUCCESS(rv, rv);
-      NS_ENSURE_TRUE(parentRow, NS_ERROR_NULL_POINTER);
-
-      // We should delete the row instead,
-      //  but first check if its the only row left
-      //  so we can delete the entire table
-      int32_t rowCount, colCount;
-      rv = GetTableSize(table, &rowCount, &colCount);
-      NS_ENSURE_SUCCESS(rv, rv);
-
-      if (rowCount == 1)
-        return DeleteTable2(table, selection);
-
-      // We need to call DeleteTableRow to handle cells with rowspan
-      rv = DeleteTableRow(1);
-      NS_ENSURE_SUCCESS(rv, rv);
-    }
-    else
-    {
-      // More than 1 cell in the row
-
-      // The setCaret object will call AutoSelectionSetterAfterTableEdit in its
-      // destructor
-      AutoSelectionSetterAfterTableEdit setCaret(this, table, startRowIndex,
-                                                 startColIndex, ePreviousColumn,
-                                                 false);
-      AutoTransactionsConserveSelection dontChangeSelection(this);
-
-      rv = DeleteNode(cell);
-      // If we fail, don't try to delete any more cells???
-      NS_ENSURE_SUCCESS(rv, rv);
+      // Don't fail if no cell found
+      NS_ENSURE_TRUE(cell, NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND);
+
+      if (GetNumberOfCellsInRow(table, startRowIndex) == 1) {
+        nsCOMPtr<nsIDOMElement> parentRow;
+        rv = GetElementOrParentByTagName(NS_LITERAL_STRING("tr"), cell,
+                                         getter_AddRefs(parentRow));
+        NS_ENSURE_SUCCESS(rv, rv);
+        NS_ENSURE_TRUE(parentRow, NS_ERROR_NULL_POINTER);
+
+        // We should delete the row instead,
+        //  but first check if its the only row left
+        //  so we can delete the entire table
+        int32_t rowCount, colCount;
+        rv = GetTableSize(table, &rowCount, &colCount);
+        NS_ENSURE_SUCCESS(rv, rv);
+
+        if (rowCount == 1) {
+          return DeleteTable2(table, selection);
+        }
+
+        // We need to call DeleteTableRow to handle cells with rowspan
+        rv = DeleteTableRow(1);
+        NS_ENSURE_SUCCESS(rv, rv);
+      } else {
+        // More than 1 cell in the row
+
+        // The setCaret object will call AutoSelectionSetterAfterTableEdit in its
+        // destructor
+        AutoSelectionSetterAfterTableEdit setCaret(this, table, startRowIndex,
+                                                   startColIndex, ePreviousColumn,
+                                                   false);
+        AutoTransactionsConserveSelection dontChangeSelection(this);
+
+        rv = DeleteNode(cell);
+        // If we fail, don't try to delete any more cells???
+        NS_ENSURE_SUCCESS(rv, rv);
+      }
     }
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditor::DeleteTableCellContents()
 {
@@ -979,56 +950,52 @@ HTMLEditor::DeleteTableCellContents()
 
 
   nsCOMPtr<nsIDOMElement> firstCell;
   nsCOMPtr<nsIDOMRange> range;
   rv = GetFirstSelectedCell(getter_AddRefs(range), getter_AddRefs(firstCell));
   NS_ENSURE_SUCCESS(rv, rv);
 
 
-  if (firstCell)
-  {
+  if (firstCell) {
     cell = firstCell;
     rv = GetCellIndexes(cell, &startRowIndex, &startColIndex);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   AutoSelectionSetterAfterTableEdit setCaret(this, table, startRowIndex,
                                              startColIndex, ePreviousColumn,
                                              false);
 
-  while (cell)
-  {
+  while (cell) {
     DeleteCellContents(cell);
-    if (firstCell)
-    {
+    if (firstCell) {
       // We doing a selected cells, so do all of them
       rv = GetNextSelectedCell(nullptr, getter_AddRefs(cell));
       NS_ENSURE_SUCCESS(rv, rv);
+    } else {
+      cell = nullptr;
     }
-    else
-      cell = nullptr;
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditor::DeleteCellContents(nsIDOMElement* aCell)
 {
   NS_ENSURE_TRUE(aCell, NS_ERROR_NULL_POINTER);
 
   // Prevent rules testing until we're done
   AutoRules beginRulesSniffing(this, EditAction::deleteNode, nsIEditor::eNext);
 
   nsCOMPtr<nsIDOMNode> child;
   bool hasChild;
   aCell->HasChildNodes(&hasChild);
 
-  while (hasChild)
-  {
+  while (hasChild) {
     aCell->GetLastChild(getter_AddRefs(child));
     nsresult rv = DeleteNode(child);
     NS_ENSURE_SUCCESS(rv, rv);
     aCell->HasChildNodes(&hasChild);
   }
   return NS_OK;
 }
 
@@ -1047,18 +1014,19 @@ HTMLEditor::DeleteTableColumn(int32_t aN
   NS_ENSURE_SUCCESS(rv, rv);
   // Don't fail if no cell found
   NS_ENSURE_TRUE(table && cell, NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND);
 
   rv = GetTableSize(table, &rowCount, &colCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Shortcut the case of deleting all columns in table
-  if(startColIndex == 0 && aNumber >= colCount)
+  if (!startColIndex && aNumber >= colCount) {
     return DeleteTable2(table, selection);
+  }
 
   // Check for counts too high
   aNumber = std::min(aNumber,(colCount-startColIndex));
 
   AutoEditBatch beginBatching(this);
   // Prevent rules testing until we're done
   AutoRules beginRulesSniffing(this, EditAction::deleteNode, nsIEditor::eNext);
 
@@ -1067,58 +1035,55 @@ HTMLEditor::DeleteTableColumn(int32_t aN
   nsCOMPtr<nsIDOMRange> range;
   rv = GetFirstSelectedCell(getter_AddRefs(range), getter_AddRefs(firstCell));
   NS_ENSURE_SUCCESS(rv, rv);
 
   int32_t rangeCount;
   rv = selection->GetRangeCount(&rangeCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (firstCell && rangeCount > 1)
-  {
+  if (firstCell && rangeCount > 1) {
     // Fetch indexes again - may be different for selected cells
     rv = GetCellIndexes(firstCell, &startRowIndex, &startColIndex);
     NS_ENSURE_SUCCESS(rv, rv);
   }
   //We control selection resetting after the insert...
   AutoSelectionSetterAfterTableEdit setCaret(this, table, startRowIndex,
                                              startColIndex, ePreviousRow,
                                              false);
 
-  if (firstCell && rangeCount > 1)
-  {
+  if (firstCell && rangeCount > 1) {
     // Use selected cells to determine what rows to delete
     cell = firstCell;
 
-    while (cell)
-    {
-      if (cell != firstCell)
-      {
+    while (cell) {
+      if (cell != firstCell) {
         rv = GetCellIndexes(cell, &startRowIndex, &startColIndex);
         NS_ENSURE_SUCCESS(rv, rv);
       }
       // Find the next cell in a different column
       // to continue after we delete this column
       int32_t nextCol = startColIndex;
-      while (nextCol == startColIndex)
-      {
+      while (nextCol == startColIndex) {
         rv = GetNextSelectedCell(getter_AddRefs(range), getter_AddRefs(cell));
         NS_ENSURE_SUCCESS(rv, rv);
-        if (!cell) break;
+        if (!cell) {
+          break;
+        }
         rv = GetCellIndexes(cell, &startRowIndex, &nextCol);
         NS_ENSURE_SUCCESS(rv, rv);
       }
       rv = DeleteColumn(table, startColIndex);
       NS_ENSURE_SUCCESS(rv, rv);
     }
-  }
-  else for (int32_t i = 0; i < aNumber; i++)
-  {
-    rv = DeleteColumn(table, startColIndex);
-    NS_ENSURE_SUCCESS(rv, rv);
+  } else {
+    for (int32_t i = 0; i < aNumber; i++) {
+      rv = DeleteColumn(table, startColIndex);
+      NS_ENSURE_SUCCESS(rv, rv);
+    }
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditor::DeleteColumn(nsIDOMElement* aTable,
                          int32_t aColIndex)
 {
@@ -1131,78 +1096,68 @@ HTMLEditor::DeleteColumn(nsIDOMElement* 
 
   do {
     nsresult rv =
       GetCellDataAt(aTable, rowIndex, aColIndex, getter_AddRefs(cell),
                     &startRowIndex, &startColIndex, &rowSpan, &colSpan,
                     &actualRowSpan, &actualColSpan, &isSelected);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (cell)
-    {
+    if (cell) {
       // Find cells that don't start in column we are deleting
-      if (startColIndex < aColIndex || colSpan > 1 || colSpan == 0)
-      {
+      if (startColIndex < aColIndex || colSpan > 1 || !colSpan) {
         // We have a cell spanning this location
         // Decrease its colspan to keep table rectangular,
         // but if colSpan=0, it will adjust automatically
-        if (colSpan > 0)
-        {
+        if (colSpan > 0) {
           NS_ASSERTION((colSpan > 1),"Bad COLSPAN in DeleteTableColumn");
           SetColSpan(cell, colSpan-1);
         }
-        if (startColIndex == aColIndex)
-        {
+        if (startColIndex == aColIndex) {
           // Cell is in column to be deleted, but must have colspan > 1,
           // so delete contents of cell instead of cell itself
           // (We must have reset colspan above)
           DeleteCellContents(cell);
         }
         // To next cell in column
         rowIndex += actualRowSpan;
-      }
-      else
-      {
+      } else {
         // Delete the cell
-        if (1 == GetNumberOfCellsInRow(aTable, rowIndex))
-        {
+        if (GetNumberOfCellsInRow(aTable, rowIndex) == 1) {
           // Only 1 cell in row - delete the row
           nsCOMPtr<nsIDOMElement> parentRow;
           rv = GetElementOrParentByTagName(NS_LITERAL_STRING("tr"), cell,
                                            getter_AddRefs(parentRow));
           NS_ENSURE_SUCCESS(rv, rv);
           if (!parentRow) {
             return NS_ERROR_NULL_POINTER;
           }
 
           //  But first check if its the only row left
           //  so we can delete the entire table
           //  (This should never happen but it's the safe thing to do)
           int32_t rowCount, colCount;
           rv = GetTableSize(aTable, &rowCount, &colCount);
           NS_ENSURE_SUCCESS(rv, rv);
 
-          if (rowCount == 1)
-          {
+          if (rowCount == 1) {
             RefPtr<Selection> selection = GetSelection();
             NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);
             return DeleteTable2(aTable, selection);
           }
 
           // Delete the row by placing caret in cell we were to delete
           // We need to call DeleteTableRow to handle cells with rowspan
           rv = DeleteRow(aTable, startRowIndex);
           NS_ENSURE_SUCCESS(rv, rv);
 
           // Note that we don't incremenet rowIndex
           // since a row was deleted and "next"
           // row now has current rowIndex
-        }
-        else
-        {
+        } else {
           // A more "normal" deletion
           rv = DeleteNode(cell);
           NS_ENSURE_SUCCESS(rv, rv);
 
           //Skip over any rows spanned by this cell
           rowIndex += actualRowSpan;
         }
       }
@@ -1228,81 +1183,73 @@ HTMLEditor::DeleteTableRow(int32_t aNumb
   NS_ENSURE_SUCCESS(rv, rv);
   // Don't fail if no cell found
   NS_ENSURE_TRUE(cell, NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND);
 
   rv = GetTableSize(table, &rowCount, &colCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Shortcut the case of deleting all rows in table
-  if(startRowIndex == 0 && aNumber >= rowCount)
+  if (!startRowIndex && aNumber >= rowCount) {
     return DeleteTable2(table, selection);
+  }
 
   AutoEditBatch beginBatching(this);
   // Prevent rules testing until we're done
   AutoRules beginRulesSniffing(this, EditAction::deleteNode, nsIEditor::eNext);
 
   nsCOMPtr<nsIDOMElement> firstCell;
   nsCOMPtr<nsIDOMRange> range;
   rv = GetFirstSelectedCell(getter_AddRefs(range), getter_AddRefs(firstCell));
   NS_ENSURE_SUCCESS(rv, rv);
 
   int32_t rangeCount;
   rv = selection->GetRangeCount(&rangeCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (firstCell && rangeCount > 1)
-  {
+  if (firstCell && rangeCount > 1) {
     // Fetch indexes again - may be different for selected cells
     rv = GetCellIndexes(firstCell, &startRowIndex, &startColIndex);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   //We control selection resetting after the insert...
   AutoSelectionSetterAfterTableEdit setCaret(this, table, startRowIndex,
                                              startColIndex, ePreviousRow,
                                              false);
   // Don't change selection during deletions
   AutoTransactionsConserveSelection dontChangeSelection(this);
 
-  if (firstCell && rangeCount > 1)
-  {
+  if (firstCell && rangeCount > 1) {
     // Use selected cells to determine what rows to delete
     cell = firstCell;
 
-    while (cell)
-    {
-      if (cell != firstCell)
-      {
+    while (cell) {
+      if (cell != firstCell) {
         rv = GetCellIndexes(cell, &startRowIndex, &startColIndex);
         NS_ENSURE_SUCCESS(rv, rv);
       }
       // Find the next cell in a different row
       // to continue after we delete this row
       int32_t nextRow = startRowIndex;
-      while (nextRow == startRowIndex)
-      {
+      while (nextRow == startRowIndex) {
         rv = GetNextSelectedCell(getter_AddRefs(range), getter_AddRefs(cell));
         NS_ENSURE_SUCCESS(rv, rv);
         if (!cell) break;
         rv = GetCellIndexes(cell, &nextRow, &startColIndex);
         NS_ENSURE_SUCCESS(rv, rv);
       }
       // Delete entire row
       rv = DeleteRow(table, startRowIndex);
       NS_ENSURE_SUCCESS(rv, rv);
     }
-  }
-  else
-  {
+  } else {
     // Check for counts too high
     aNumber = std::min(aNumber,(rowCount-startRowIndex));
-
-    for (int32_t i = 0; i < aNumber; i++)
-    {
+    for (int32_t i = 0; i < aNumber; i++) {
       rv = DeleteRow(table, startRowIndex);
       // If failed in current row, try the next
       if (NS_FAILED(rv)) {
         startRowIndex++;
       }
 
       // Check if there's a cell in the "next" row
       rv = GetCellAt(table, startRowIndex, startColIndex, getter_AddRefs(cell));
@@ -1339,88 +1286,81 @@ HTMLEditor::DeleteRow(nsIDOMElement* aTa
   int32_t rowCount, colCount;
   nsresult rv = GetTableSize(aTable, &rowCount, &colCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Scan through cells in row to do rowspan adjustments
   // Note that after we delete row, startRowIndex will point to the
   //   cells in the next row to be deleted
   do {
-    if (aRowIndex >= rowCount || colIndex >= colCount)
+    if (aRowIndex >= rowCount || colIndex >= colCount) {
       break;
+    }
 
     rv = GetCellDataAt(aTable, aRowIndex, colIndex, getter_AddRefs(cell),
                        &startRowIndex, &startColIndex, &rowSpan, &colSpan,
                        &actualRowSpan, &actualColSpan, &isSelected);
     // We don't fail if we don't find a cell, so this must be real bad
     if (NS_FAILED(rv)) {
       return rv;
     }
 
     // Compensate for cells that don't start or extend below the row we are deleting
-    if (cell)
-    {
-      if (startRowIndex < aRowIndex)
-      {
+    if (cell) {
+      if (startRowIndex < aRowIndex) {
         // Cell starts in row above us
         // Decrease its rowspan to keep table rectangular
         //  but we don't need to do this if rowspan=0,
         //  since it will automatically adjust
-        if (rowSpan > 0)
-        {
+        if (rowSpan > 0) {
           // Build list of cells to change rowspan
           // We can't do it now since it upsets cell map,
           //  so we will do it after deleting the row
           spanCellList.AppendElement(cell);
           newSpanList.AppendElement(std::max((aRowIndex - startRowIndex), actualRowSpan-1));
         }
-      }
-      else
-      {
-        if (rowSpan > 1)
-        {
+      } else {
+        if (rowSpan > 1) {
           // Cell spans below row to delete, so we must insert new cells to
           // keep rows below.  Note that we test "rowSpan" so we don't do this
           // if rowSpan = 0 (automatic readjustment).
           int32_t aboveRowToInsertNewCellInto = aRowIndex - startRowIndex + 1;
           int32_t numOfRawSpanRemainingBelow = actualRowSpan - 1;
           rv = SplitCellIntoRows(aTable, startRowIndex, startColIndex,
                                  aboveRowToInsertNewCellInto,
                                  numOfRawSpanRemainingBelow, nullptr);
           NS_ENSURE_SUCCESS(rv, rv);
         }
-        if (!cellInDeleteRow)
+        if (!cellInDeleteRow) {
           cellInDeleteRow = cell; // Reference cell to find row to delete
+        }
       }
       // Skip over other columns spanned by this cell
       colIndex += actualColSpan;
     }
   } while (cell);
 
   // Things are messed up if we didn't find a cell in the row!
   NS_ENSURE_TRUE(cellInDeleteRow, NS_ERROR_FAILURE);
 
   // Delete the entire row
   nsCOMPtr<nsIDOMElement> parentRow;
   rv = GetElementOrParentByTagName(NS_LITERAL_STRING("tr"), cellInDeleteRow,
                                    getter_AddRefs(parentRow));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (parentRow)
-  {
+  if (parentRow) {
     rv = DeleteNode(parentRow);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Now we can set new rowspans for cells stored above
-  for (uint32_t i = 0, n = spanCellList.Length(); i < n; i++)
-  {
+  for (uint32_t i = 0, n = spanCellList.Length(); i < n; i++) {
     nsIDOMElement *cellPtr = spanCellList[i];
-    if (cellPtr)
-    {
+    if (cellPtr) {
       rv = SetRowSpan(cellPtr, newSpanList[i]);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
   return NS_OK;
 }
 
 
@@ -1476,17 +1416,19 @@ HTMLEditor::SelectBlockOfCells(nsIDOMEle
   nsCOMPtr<nsIDOMElement> endTable;
   rv = GetElementOrParentByTagName(tableStr, aEndCell,
                                    getter_AddRefs(endTable));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(endTable, NS_ERROR_FAILURE);
 
   // We can only select a block if within the same table,
   //  so do nothing if not within one table
-  if (table != endTable) return NS_OK;
+  if (table != endTable) {
+    return NS_OK;
+  }
 
   int32_t startRowIndex, startColIndex, endRowIndex, endColIndex;
 
   // Get starting and ending cells' location in the cellmap
   rv = GetCellIndexes(aStartCell, &startRowIndex, &startColIndex);
   if (NS_FAILED(rv)) {
     return rv;
   }
@@ -1511,48 +1453,45 @@ HTMLEditor::SelectBlockOfCells(nsIDOMEle
   int32_t currentRowIndex, currentColIndex;
   nsCOMPtr<nsIDOMRange> range;
   rv = GetFirstSelectedCell(getter_AddRefs(range), getter_AddRefs(cell));
   NS_ENSURE_SUCCESS(rv, rv);
   if (rv == NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND) {
     return NS_OK;
   }
 
-  while (cell)
-  {
+  while (cell) {
     rv = GetCellIndexes(cell, &currentRowIndex, &currentColIndex);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (currentRowIndex < maxRow || currentRowIndex > maxRow ||
-        currentColIndex < maxColumn || currentColIndex > maxColumn)
-    {
+        currentColIndex < maxColumn || currentColIndex > maxColumn) {
       selection->RemoveRange(range);
       // Since we've removed the range, decrement pointer to next range
       mSelectedCellIndex--;
     }
     rv = GetNextSelectedCell(getter_AddRefs(range), getter_AddRefs(cell));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   int32_t rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
-  for (int32_t row = minRow; row <= maxRow; row++)
-  {
-    for(int32_t col = minColumn; col <= maxColumn; col += std::max(actualColSpan, 1))
-    {
+  for (int32_t row = minRow; row <= maxRow; row++) {
+    for (int32_t col = minColumn; col <= maxColumn;
+        col += std::max(actualColSpan, 1)) {
       rv = GetCellDataAt(table, row, col, getter_AddRefs(cell),
                          &currentRowIndex, &currentColIndex,
                          &rowSpan, &colSpan,
                          &actualRowSpan, &actualColSpan, &isSelected);
       if (NS_FAILED(rv)) {
         break;
       }
       // Skip cells that already selected or are spanned from previous locations
-      if (!isSelected && cell && row == currentRowIndex && col == currentColIndex)
-      {
+      if (!isSelected && cell &&
+          row == currentRowIndex && col == currentColIndex) {
         rv = AppendNodeToSelectionAsRange(cell);
         if (NS_FAILED(rv)) {
           break;
         }
       }
     }
   }
   // NS_OK, otherwise, the last failure of GetCellDataAt() or
@@ -1596,41 +1535,37 @@ HTMLEditor::SelectAllTableCells()
   // It is now safe to clear the selection
   // BE SURE TO RESET IT BEFORE LEAVING!
   rv = ClearSelection();
 
   // Select all cells in the same column as current cell
   bool cellSelected = false;
   int32_t rowSpan, colSpan, actualRowSpan, actualColSpan, currentRowIndex, currentColIndex;
   bool    isSelected;
-  for(int32_t row = 0; row < rowCount; row++)
-  {
-    for(int32_t col = 0; col < colCount; col += std::max(actualColSpan, 1))
-    {
+  for (int32_t row = 0; row < rowCount; row++) {
+    for (int32_t col = 0; col < colCount; col += std::max(actualColSpan, 1)) {
       rv = GetCellDataAt(table, row, col, getter_AddRefs(cell),
                          &currentRowIndex, &currentColIndex,
                          &rowSpan, &colSpan,
                          &actualRowSpan, &actualColSpan, &isSelected);
       if (NS_FAILED(rv)) {
         break;
       }
       // Skip cells that are spanned from previous rows or columns
-      if (cell && row == currentRowIndex && col == currentColIndex)
-      {
+      if (cell && row == currentRowIndex && col == currentColIndex) {
         rv =  AppendNodeToSelectionAsRange(cell);
         if (NS_FAILED(rv)) {
           break;
         }
         cellSelected = true;
       }
     }
   }
   // Safety code to select starting cell if nothing else was selected
-  if (!cellSelected)
-  {
+  if (!cellSelected) {
     return AppendNodeToSelectionAsRange(startCell);
   }
   // NS_OK, otherwise, the error of ClearSelection() when there is no column or
   // the last failure of GetCellDataAt() or AppendNodeToSelectionAsRange().
   return rv;
 }
 
 NS_IMETHODIMP
@@ -1673,37 +1608,34 @@ HTMLEditor::SelectTableRow()
   // It is now safe to clear the selection
   // BE SURE TO RESET IT BEFORE LEAVING!
   rv = ClearSelection();
 
   // Select all cells in the same row as current cell
   bool cellSelected = false;
   int32_t rowSpan, colSpan, actualRowSpan, actualColSpan, currentRowIndex, currentColIndex;
   bool    isSelected;
-  for(int32_t col = 0; col < colCount; col += std::max(actualColSpan, 1))
-  {
+  for (int32_t col = 0; col < colCount; col += std::max(actualColSpan, 1)) {
     rv = GetCellDataAt(table, startRowIndex, col, getter_AddRefs(cell),
                        &currentRowIndex, &currentColIndex, &rowSpan, &colSpan,
                        &actualRowSpan, &actualColSpan, &isSelected);
     if (NS_FAILED(rv)) {
       break;
     }
     // Skip cells that are spanned from previous rows or columns
-    if (cell && currentRowIndex == startRowIndex && currentColIndex == col)
-    {
+    if (cell && currentRowIndex == startRowIndex && currentColIndex == col) {
       rv = AppendNodeToSelectionAsRange(cell);
       if (NS_FAILED(rv)) {
         break;
       }
       cellSelected = true;
     }
   }
   // Safety code to select starting cell if nothing else was selected
-  if (!cellSelected)
-  {
+  if (!cellSelected) {
     return AppendNodeToSelectionAsRange(startCell);
   }
   // NS_OK, otherwise, the error of ClearSelection() when there is no column or
   // the last failure of GetCellDataAt() or AppendNodeToSelectionAsRange().
   return rv;
 }
 
 NS_IMETHODIMP
@@ -1743,37 +1675,34 @@ HTMLEditor::SelectTableColumn()
   // It is now safe to clear the selection
   // BE SURE TO RESET IT BEFORE LEAVING!
   rv = ClearSelection();
 
   // Select all cells in the same column as current cell
   bool cellSelected = false;
   int32_t rowSpan, colSpan, actualRowSpan, actualColSpan, currentRowIndex, currentColIndex;
   bool    isSelected;
-  for(int32_t row = 0; row < rowCount; row += std::max(actualRowSpan, 1))
-  {
+  for (int32_t row = 0; row < rowCount; row += std::max(actualRowSpan, 1)) {
     rv = GetCellDataAt(table, row, startColIndex, getter_AddRefs(cell),
                        &currentRowIndex, &currentColIndex, &rowSpan, &colSpan,
                        &actualRowSpan, &actualColSpan, &isSelected);
     if (NS_FAILED(rv)) {
       break;
     }
     // Skip cells that are spanned from previous rows or columns
-    if (cell && currentRowIndex == row && currentColIndex == startColIndex)
-    {
+    if (cell && currentRowIndex == row && currentColIndex == startColIndex) {
       rv = AppendNodeToSelectionAsRange(cell);
       if (NS_FAILED(rv)) {
         break;
       }
       cellSelected = true;
     }
   }
   // Safety code to select starting cell if nothing else was selected
-  if (!cellSelected)
-  {
+  if (!cellSelected) {
     return AppendNodeToSelectionAsRange(startCell);
   }
   // NS_OK, otherwise, the error of ClearSelection() when there is no row or
   // the last failure of GetCellDataAt() or AppendNodeToSelectionAsRange().
   return rv;
 }
 
 NS_IMETHODIMP
@@ -1794,18 +1723,19 @@ HTMLEditor::SplitTableCell()
   }
 
   // We need rowspan and colspan data
   rv = GetCellSpansAt(table, startRowIndex, startColIndex,
                       actualRowSpan, actualColSpan);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Must have some span to split
-  if (actualRowSpan <= 1 && actualColSpan <= 1)
+  if (actualRowSpan <= 1 && actualColSpan <= 1) {
     return NS_OK;
+  }
 
   AutoEditBatch beginBatching(this);
   // Prevent auto insertion of BR in new cell until we're done
   AutoRules beginRulesSniffing(this, EditAction::insertNode, nsIEditor::eNext);
 
   // We reset selection
   AutoSelectionSetterAfterTableEdit setCaret(this, table, startRowIndex,
                                              startColIndex, ePreviousColumn,
@@ -1814,30 +1744,27 @@ HTMLEditor::SplitTableCell()
   AutoTransactionsConserveSelection dontChangeSelection(this);
 
   nsCOMPtr<nsIDOMElement> newCell;
   int32_t rowIndex = startRowIndex;
   int32_t rowSpanBelow, colSpanAfter;
 
   // Split up cell row-wise first into rowspan=1 above, and the rest below,
   //  whittling away at the cell below until no more extra span
-  for (rowSpanBelow = actualRowSpan-1; rowSpanBelow >= 0; rowSpanBelow--)
-  {
+  for (rowSpanBelow = actualRowSpan-1; rowSpanBelow >= 0; rowSpanBelow--) {
     // We really split row-wise only if we had rowspan > 1
-    if (rowSpanBelow > 0)
-    {
+    if (rowSpanBelow > 0) {
       rv = SplitCellIntoRows(table, rowIndex, startColIndex, 1, rowSpanBelow,
                              getter_AddRefs(newCell));
       NS_ENSURE_SUCCESS(rv, rv);
       CopyCellBackgroundColor(newCell, cell);
     }
     int32_t colIndex = startColIndex;
     // Now split the cell with rowspan = 1 into cells if it has colSpan > 1
-    for (colSpanAfter = actualColSpan-1; colSpanAfter > 0; colSpanAfter--)
-    {
+    for (colSpanAfter = actualColSpan-1; colSpanAfter > 0; colSpanAfter--) {
       rv = SplitCellIntoColumns(table, rowIndex, colIndex, 1, colSpanAfter,
                                 getter_AddRefs(newCell));
       NS_ENSURE_SUCCESS(rv, rv);
       CopyCellBackgroundColor(newCell, cell);
       colIndex++;
     }
     // Point to the new cell and repeat
     rowIndex++;
@@ -1869,32 +1796,35 @@ NS_IMETHODIMP
 HTMLEditor::SplitCellIntoColumns(nsIDOMElement* aTable,
                                  int32_t aRowIndex,
                                  int32_t aColIndex,
                                  int32_t aColSpanLeft,
                                  int32_t aColSpanRight,
                                  nsIDOMElement** aNewCell)
 {
   NS_ENSURE_TRUE(aTable, NS_ERROR_NULL_POINTER);
-  if (aNewCell) *aNewCell = nullptr;
+  if (aNewCell) {
+    *aNewCell = nullptr;
+  }
 
   nsCOMPtr<nsIDOMElement> cell;
   int32_t startRowIndex, startColIndex, rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
   nsresult rv =
     GetCellDataAt(aTable, aRowIndex, aColIndex, getter_AddRefs(cell),
                   &startRowIndex, &startColIndex,
                   &rowSpan, &colSpan,
                   &actualRowSpan, &actualColSpan, &isSelected);
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(cell, NS_ERROR_NULL_POINTER);
 
   // We can't split!
-  if (actualColSpan <= 1 || (aColSpanLeft + aColSpanRight) > actualColSpan)
+  if (actualColSpan <= 1 || (aColSpanLeft + aColSpanRight) > actualColSpan) {
     return NS_OK;
+  }
 
   // Reduce colspan of cell to split
   rv = SetColSpan(cell, aColSpanLeft);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Insert new cell after using the remaining span
   //  and always get the new cell so we can copy the background color;
   nsCOMPtr<nsIDOMElement> newCell;
@@ -1928,83 +1858,78 @@ HTMLEditor::SplitCellIntoRows(nsIDOMElem
     GetCellDataAt(aTable, aRowIndex, aColIndex, getter_AddRefs(cell),
                   &startRowIndex, &startColIndex,
                   &rowSpan, &colSpan,
                   &actualRowSpan, &actualColSpan, &isSelected);
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(cell, NS_ERROR_NULL_POINTER);
 
   // We can't split!
-  if (actualRowSpan <= 1 || (aRowSpanAbove + aRowSpanBelow) > actualRowSpan)
+  if (actualRowSpan <= 1 || (aRowSpanAbove + aRowSpanBelow) > actualRowSpan) {
     return NS_OK;
+  }
 
   int32_t rowCount, colCount;
   rv = GetTableSize(aTable, &rowCount, &colCount);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIDOMElement> cell2;
   nsCOMPtr<nsIDOMElement> lastCellFound;
   int32_t startRowIndex2, startColIndex2, rowSpan2, colSpan2, actualRowSpan2, actualColSpan2;
   bool    isSelected2;
   int32_t colIndex = 0;
   bool insertAfter = (startColIndex > 0);
   // This is the row we will insert new cell into
   int32_t rowBelowIndex = startRowIndex+aRowSpanAbove;
 
   // Find a cell to insert before or after
-  do
-  {
+  for (;;) {
     // Search for a cell to insert before
     rv = GetCellDataAt(aTable, rowBelowIndex,
                        colIndex, getter_AddRefs(cell2),
                        &startRowIndex2, &startColIndex2, &rowSpan2, &colSpan2,
                        &actualRowSpan2, &actualColSpan2, &isSelected2);
     // If we fail here, it could be because row has bad rowspan values,
     //   such as all cells having rowspan > 1 (Call FixRowSpan first!)
     if (NS_FAILED(rv) || !cell) {
       return NS_ERROR_FAILURE;
     }
 
     // Skip over cells spanned from above (like the one we are splitting!)
-    if (cell2 && startRowIndex2 == rowBelowIndex)
-    {
-      if (insertAfter)
-      {
-        // New cell isn't first in row,
-        // so stop after we find the cell just before new cell's column
-        if ((startColIndex2 + actualColSpan2) == startColIndex)
-          break;
-
-        // If cell found is AFTER desired new cell colum,
-        //  we have multiple cells with rowspan > 1 that
-        //  prevented us from finding a cell to insert after...
-        if (startColIndex2 > startColIndex)
-        {
-          // ... so instead insert before the cell we found
-          insertAfter = false;
-          break;
-        }
+    if (cell2 && startRowIndex2 == rowBelowIndex) {
+      if (!insertAfter) {
+        // Inserting before, so stop at first cell in row we want to insert
+        // into.
+        break;
       }
-      else
-      {
-        break; // Inserting before, so stop at first cell in row we want to insert into
+      // New cell isn't first in row,
+      // so stop after we find the cell just before new cell's column
+      if (startColIndex2 + actualColSpan2 == startColIndex) {
+        break;
+      }
+      // If cell found is AFTER desired new cell colum,
+      //  we have multiple cells with rowspan > 1 that
+      //  prevented us from finding a cell to insert after...
+      if (startColIndex2 > startColIndex) {
+        // ... so instead insert before the cell we found
+        insertAfter = false;
+        break;
       }
       lastCellFound = cell2;
     }
     // Skip to next available cellmap location
     colIndex += std::max(actualColSpan2, 1);
 
     // Done when past end of total number of columns
-    if (colIndex > colCount)
-        break;
-
-  } while(true);
-
-  if (!cell2 && lastCellFound)
-  {
+    if (colIndex > colCount) {
+      break;
+    }
+  }
+
+  if (!cell2 && lastCellFound) {
     // Edge case where we didn't find a cell to insert after
     //  or before because column(s) before desired column
     //  and all columns after it are spanned from above.
     //  We can insert after the last cell we found
     cell2 = lastCellFound;
     insertAfter = true; // Should always be true, but let's be sure
   }
 
@@ -2052,18 +1977,17 @@ HTMLEditor::SwitchTableCellHeaderType(ns
 
   // This creates new node, moves children, copies attributes (true)
   //   and manages the selection!
   nsCOMPtr<Element> newNode = ReplaceContainer(sourceCell, newCellType,
       nullptr, nullptr, EditorBase::eCloneAttributes);
   NS_ENSURE_TRUE(newNode, NS_ERROR_FAILURE);
 
   // Return the new cell
-  if (aNewCell)
-  {
+  if (aNewCell) {
     nsCOMPtr<nsIDOMElement> newElement = do_QueryInterface(newNode);
     *aNewCell = newElement.get();
     NS_ADDREF(*aNewCell);
   }
 
   return NS_OK;
 }
 
@@ -2099,28 +2023,26 @@ HTMLEditor::JoinTableCells(bool aMergeNo
 
   nsCOMPtr<nsIDOMElement> firstCell;
   int32_t firstRowIndex, firstColIndex;
   rv = GetFirstSelectedCellInTable(&firstRowIndex, &firstColIndex,
                                    getter_AddRefs(firstCell));
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool joinSelectedCells = false;
-  if (firstCell)
-  {
+  if (firstCell) {
     nsCOMPtr<nsIDOMElement> secondCell;
     rv = GetNextSelectedCell(nullptr, getter_AddRefs(secondCell));
     NS_ENSURE_SUCCESS(rv, rv);
 
     // If only one cell is selected, join with cell to the right
     joinSelectedCells = (secondCell != nullptr);
   }
 
-  if (joinSelectedCells)
-  {
+  if (joinSelectedCells) {
     // We have selected cells: Join just contiguous cells
     //  and just merge contents if not contiguous
 
     int32_t rowCount, colCount;
     rv = GetTableSize(table, &rowCount, &colCount);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Get spans for cell we will merge into
@@ -2136,223 +2058,195 @@ HTMLEditor::JoinTableCells(bool aMergeNo
     //  then expand as we find adjacent selected cells
     int32_t lastRowIndex = firstRowIndex;
     int32_t lastColIndex = firstColIndex;
     int32_t rowIndex, colIndex;
 
     // First pass: Determine boundaries of contiguous rectangular block
     //  that we will join into one cell,
     //  favoring adjacent cells in the same row
-    for (rowIndex = firstRowIndex; rowIndex <= lastRowIndex; rowIndex++)
-    {
+    for (rowIndex = firstRowIndex; rowIndex <= lastRowIndex; rowIndex++) {
       int32_t currentRowCount = rowCount;
       // Be sure each row doesn't have rowspan errors
       rv = FixBadRowSpan(table, rowIndex, rowCount);
       NS_ENSURE_SUCCESS(rv, rv);
       // Adjust rowcount by number of rows we removed
       lastRowIndex -= (currentRowCount-rowCount);
 
       bool cellFoundInRow = false;
       bool lastRowIsSet = false;
       int32_t lastColInRow = 0;
       int32_t firstColInRow = firstColIndex;
-      for (colIndex = firstColIndex; colIndex < colCount; colIndex += std::max(actualColSpan2, 1))
-      {
+      for (colIndex = firstColIndex; colIndex < colCount;
+           colIndex += std::max(actualColSpan2, 1)) {
         rv = GetCellDataAt(table, rowIndex, colIndex, getter_AddRefs(cell2),
                            &startRowIndex2, &startColIndex2,
                            &rowSpan2, &colSpan2,
                            &actualRowSpan2, &actualColSpan2, &isSelected2);
         NS_ENSURE_SUCCESS(rv, rv);
 
-        if (isSelected2)
-        {
-          if (!cellFoundInRow)
+        if (isSelected2) {
+          if (!cellFoundInRow) {
             // We've just found the first selected cell in this row
             firstColInRow = colIndex;
-
-          if (rowIndex > firstRowIndex && firstColInRow != firstColIndex)
-          {
+          }
+          if (rowIndex > firstRowIndex && firstColInRow != firstColIndex) {
             // We're in at least the second row,
             // but left boundary is "ragged" (not the same as 1st row's start)
             //Let's just end block on previous row
             // and keep previous lastColIndex
             //TODO: We could try to find the Maximum firstColInRow
             //      so our block can still extend down more rows?
             lastRowIndex = std::max(0,rowIndex - 1);
             lastRowIsSet = true;
             break;
           }
           // Save max selected column in this row, including extra colspan
           lastColInRow = colIndex + (actualColSpan2-1);
           cellFoundInRow = true;
-        }
-        else if (cellFoundInRow)
-        {
+        } else if (cellFoundInRow) {
           // No cell or not selected, but at least one cell in row was found
-
-          if (rowIndex > (firstRowIndex+1) && colIndex <= lastColIndex)
-          {
+          if (rowIndex > (firstRowIndex + 1) && colIndex <= lastColIndex) {
             // Cell is in a column less than current right border in
             //  the third or higher selected row, so stop block at the previous row
             lastRowIndex = std::max(0,rowIndex - 1);
             lastRowIsSet = true;
           }
           // We're done with this row
           break;
         }
       } // End of column loop
 
       // Done with this row
-      if (cellFoundInRow)
-      {
-        if (rowIndex == firstRowIndex)
-        {
+      if (cellFoundInRow) {
+        if (rowIndex == firstRowIndex) {
           // First row always initializes the right boundary
           lastColIndex = lastColInRow;
         }
 
         // If we didn't determine last row above...
-        if (!lastRowIsSet)
-        {
-          if (colIndex < lastColIndex)
-          {
+        if (!lastRowIsSet) {
+          if (colIndex < lastColIndex) {
             // (don't think we ever get here?)
             // Cell is in a column less than current right boundary,
             //  so stop block at the previous row
             lastRowIndex = std::max(0,rowIndex - 1);
-          }
-          else
-          {
+          } else {
             // Go on to examine next row
             lastRowIndex = rowIndex+1;
           }
         }
         // Use the minimum col we found so far for right boundary
         lastColIndex = std::min(lastColIndex, lastColInRow);
-      }
-      else
-      {
+      } else {
         // No selected cells in this row -- stop at row above
         //  and leave last column at its previous value
         lastRowIndex = std::max(0,rowIndex - 1);
       }
     }
 
     // The list of cells we will delete after joining
     nsTArray<nsCOMPtr<nsIDOMElement> > deleteList;
 
     // 2nd pass: Do the joining and merging
-    for (rowIndex = 0; rowIndex < rowCount; rowIndex++)
-    {
-      for (colIndex = 0; colIndex < colCount; colIndex += std::max(actualColSpan2, 1))
-      {
+    for (rowIndex = 0; rowIndex < rowCount; rowIndex++) {
+      for (colIndex = 0; colIndex < colCount;
+           colIndex += std::max(actualColSpan2, 1)) {
         rv = GetCellDataAt(table, rowIndex, colIndex, getter_AddRefs(cell2),
                            &startRowIndex2, &startColIndex2,
                            &rowSpan2, &colSpan2,
                            &actualRowSpan2, &actualColSpan2, &isSelected2);
         NS_ENSURE_SUCCESS(rv, rv);
 
         // If this is 0, we are past last cell in row, so exit the loop
-        if (actualColSpan2 == 0)
+        if (!actualColSpan2) {
           break;
+        }
 
         // Merge only selected cells (skip cell we're merging into, of course)
-        if (isSelected2 && cell2 != firstCell)
-        {
+        if (isSelected2 && cell2 != firstCell) {
           if (rowIndex >= firstRowIndex && rowIndex <= lastRowIndex &&
-              colIndex >= firstColIndex && colIndex <= lastColIndex)
-          {
+              colIndex >= firstColIndex && colIndex <= lastColIndex) {
             // We are within the join region
             // Problem: It is very tricky to delete cells as we merge,
             //  since that will upset the cellmap
             //  Instead, build a list of cells to delete and do it later
             NS_ASSERTION(startRowIndex2 == rowIndex, "JoinTableCells: StartRowIndex is in row above");
 
-            if (actualColSpan2 > 1)
-            {
+            if (actualColSpan2 > 1) {
               //Check if cell "hangs" off the boundary because of colspan > 1
               //  Use split methods to chop off excess
               int32_t extraColSpan = (startColIndex2 + actualColSpan2) - (lastColIndex+1);
-              if ( extraColSpan > 0)
-              {
+              if ( extraColSpan > 0) {
                 rv = SplitCellIntoColumns(table, startRowIndex2, startColIndex2,
                                           actualColSpan2 - extraColSpan,
                                           extraColSpan, nullptr);
                 NS_ENSURE_SUCCESS(rv, rv);
               }
             }
 
             rv = MergeCells(firstCell, cell2, false);
             NS_ENSURE_SUCCESS(rv, rv);
 
             // Add cell to list to delete
             deleteList.AppendElement(cell2.get());
-          }
-          else if (aMergeNonContiguousContents)
-          {
+          } else if (aMergeNonContiguousContents) {
             // Cell is outside join region -- just merge the contents
             rv = MergeCells(firstCell, cell2, false);
             NS_ENSURE_SUCCESS(rv, rv);
           }
         }
       }
     }
 
     // All cell contents are merged. Delete the empty cells we accumulated
     // Prevent rules testing until we're done
     AutoRules beginRulesSniffing(this, EditAction::deleteNode,
                                  nsIEditor::eNext);
 
-    for (uint32_t i = 0, n = deleteList.Length(); i < n; i++)
-    {
+    for (uint32_t i = 0, n = deleteList.Length(); i < n; i++) {
       nsIDOMElement *elementPtr = deleteList[i];
-      if (elementPtr)
-      {
+      if (elementPtr) {
         nsCOMPtr<nsIDOMNode> node = do_QueryInterface(elementPtr);
         rv = DeleteNode(node);
         NS_ENSURE_SUCCESS(rv, rv);
       }
     }
     // Cleanup selection: remove ranges where cells were deleted
     RefPtr<Selection> selection = GetSelection();
     NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);
 
     int32_t rangeCount;
     rv = selection->GetRangeCount(&rangeCount);
     NS_ENSURE_SUCCESS(rv, rv);
 
     RefPtr<nsRange> range;
-    int32_t i;
-    for (i = 0; i < rangeCount; i++)
-    {
+    for (int32_t i = 0; i < rangeCount; i++) {
       range = selection->GetRangeAt(i);
       NS_ENSURE_TRUE(range, NS_ERROR_FAILURE);
 
       nsCOMPtr<nsIDOMElement> deletedCell;
       GetCellFromRange(range, getter_AddRefs(deletedCell));
-      if (!deletedCell)
-      {
+      if (!deletedCell) {
         selection->RemoveRange(range);
         rangeCount--;
         i--;
       }
     }
 
     // Set spans for the cell everthing merged into
     rv = SetRowSpan(firstCell, lastRowIndex-firstRowIndex+1);
     NS_ENSURE_SUCCESS(rv, rv);
     rv = SetColSpan(firstCell, lastColIndex-firstColIndex+1);
     NS_ENSURE_SUCCESS(rv, rv);
 
 
     // Fixup disturbances in table layout
     NormalizeTable(table);
-  }
-  else
-  {
+  } else {
     // Joining with cell to the right -- get rowspan and colspan data of target cell
     rv = GetCellDataAt(table, startRowIndex, startColIndex,
                        getter_AddRefs(targetCell),
                        &startRowIndex, &startColIndex, &rowSpan, &colSpan,
                        &actualRowSpan, &actualColSpan, &isSelected);
     NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(targetCell, NS_ERROR_NULL_POINTER);
 
@@ -2369,45 +2263,42 @@ HTMLEditor::JoinTableCells(bool aMergeNo
     // sanity check
     NS_ASSERTION((startRowIndex >= startRowIndex2),"JoinCells: startRowIndex < startRowIndex2");
 
     // Figure out span of merged cell starting from target's starting row
     // to handle case of merged cell starting in a row above
     int32_t spanAboveMergedCell = startRowIndex - startRowIndex2;
     int32_t effectiveRowSpan2 = actualRowSpan2 - spanAboveMergedCell;
 
-    if (effectiveRowSpan2 > actualRowSpan)
-    {
+    if (effectiveRowSpan2 > actualRowSpan) {
       // Cell to the right spans into row below target
       // Split off portion below target cell's bottom-most row
       rv = SplitCellIntoRows(table, startRowIndex2, startColIndex2,
                              spanAboveMergedCell+actualRowSpan,
                              effectiveRowSpan2-actualRowSpan, nullptr);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     // Move contents from cell to the right
     // Delete the cell now only if it starts in the same row
     //   and has enough row "height"
     rv = MergeCells(targetCell, cell2,
                     (startRowIndex2 == startRowIndex) &&
                     (effectiveRowSpan2 >= actualRowSpan));
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (effectiveRowSpan2 < actualRowSpan)
-    {
+    if (effectiveRowSpan2 < actualRowSpan) {
       // Merged cell is "shorter"
       // (there are cells(s) below it that are row-spanned by target cell)
       // We could try splitting those cells, but that's REAL messy,
       //  so the safest thing to do is NOT really join the cells
       return NS_OK;
     }
 
-    if( spanAboveMergedCell > 0 )
-    {
+    if (spanAboveMergedCell > 0) {
       // Cell we merged started in a row above the target cell
       // Reduce rowspan to give room where target cell will extend its colspan
       rv = SetRowSpan(cell2, spanAboveMergedCell);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     // Reset target cell's colspan to encompass cell to the right
     rv = SetColSpan(targetCell, actualColSpan+actualColSpan2);
@@ -2454,18 +2345,19 @@ HTMLEditor::MergeCells(nsCOMPtr<nsIDOMEl
       NS_ENSURE_SUCCESS(rv, rv);
 
       rv = InsertNode(cellChild, aTargetCell, insertIndex);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
   // Delete cells whose contents were moved
-  if (aDeleteCellToMerge)
+  if (aDeleteCellToMerge) {
     return DeleteNode(aCellToMerge);
+  }
 
   return NS_OK;
 }
 
 
 NS_IMETHODIMP
 HTMLEditor::FixBadRowSpan(nsIDOMElement* aTable,
                           int32_t aRowIndex,
@@ -2479,55 +2371,52 @@ HTMLEditor::FixBadRowSpan(nsIDOMElement*
 
   nsCOMPtr<nsIDOMElement>cell;
   int32_t startRowIndex, startColIndex, rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
 
   int32_t minRowSpan = -1;
   int32_t colIndex;
 
-  for( colIndex = 0; colIndex < colCount; colIndex += std::max(actualColSpan, 1))
-  {
+  for (colIndex = 0; colIndex < colCount;
+       colIndex += std::max(actualColSpan, 1)) {
     rv = GetCellDataAt(aTable, aRowIndex, colIndex, getter_AddRefs(cell),
                        &startRowIndex, &startColIndex, &rowSpan, &colSpan,
                        &actualRowSpan, &actualColSpan, &isSelected);
     // NOTE: This is a *real* failure.
     // GetCellDataAt passes if cell is missing from cellmap
     if (NS_FAILED(rv)) {
       return rv;
     }
     if (!cell) {
       break;
     }
-    if(rowSpan > 0 &&
-       startRowIndex == aRowIndex &&
-       (rowSpan < minRowSpan || minRowSpan == -1))
-    {
+    if (rowSpan > 0 &&
+        startRowIndex == aRowIndex &&
+        (rowSpan < minRowSpan || minRowSpan == -1)) {
       minRowSpan = rowSpan;
     }
     NS_ASSERTION((actualColSpan > 0),"ActualColSpan = 0 in FixBadRowSpan");
   }
-  if(minRowSpan > 1)
-  {
+  if (minRowSpan > 1) {
     // The amount to reduce everyone's rowspan
     // so at least one cell has rowspan = 1
     int32_t rowsReduced = minRowSpan - 1;
-    for(colIndex = 0; colIndex < colCount; colIndex += std::max(actualColSpan, 1))
-    {
+    for (colIndex = 0; colIndex < colCount;
+         colIndex += std::max(actualColSpan, 1)) {
       rv = GetCellDataAt(aTable, aRowIndex, colIndex, getter_AddRefs(cell),
                          &startRowIndex, &startColIndex, &rowSpan, &colSpan,
                          &actualRowSpan, &actualColSpan, &isSelected);
       if (NS_FAILED(rv)) {
         return rv;
       }
       // Fixup rowspans only for cells starting in current row
-      if(cell && rowSpan > 0 &&
-         startRowIndex == aRowIndex &&
-         startColIndex ==  colIndex )
-      {
+      if (cell && rowSpan > 0 &&
+          startRowIndex == aRowIndex &&
+          startColIndex ==  colIndex ) {
         rv = SetRowSpan(cell, rowSpan-rowsReduced);
         if (NS_FAILED(rv)) {
           return rv;
         }
       }
       NS_ASSERTION((actualColSpan > 0),"ActualColSpan = 0 in FixBadRowSpan");
     }
   }
@@ -2547,55 +2436,52 @@ HTMLEditor::FixBadColSpan(nsIDOMElement*
 
   nsCOMPtr<nsIDOMElement> cell;
   int32_t startRowIndex, startColIndex, rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
 
   int32_t minColSpan = -1;
   int32_t rowIndex;
 
-  for( rowIndex = 0; rowIndex < rowCount; rowIndex += std::max(actualRowSpan, 1))
-  {
+  for (rowIndex = 0; rowIndex < rowCount;
+       rowIndex += std::max(actualRowSpan, 1)) {
     rv = GetCellDataAt(aTable, rowIndex, aColIndex, getter_AddRefs(cell),
                        &startRowIndex, &startColIndex, &rowSpan, &colSpan,
                        &actualRowSpan, &actualColSpan, &isSelected);
     // NOTE: This is a *real* failure.
     // GetCellDataAt passes if cell is missing from cellmap
     if (NS_FAILED(rv)) {
       return rv;
     }
     if (!cell) {
       break;
     }
-    if(colSpan > 0 &&
-       startColIndex == aColIndex &&
-       (colSpan < minColSpan || minColSpan == -1))
-    {
+    if (colSpan > 0 &&
+        startColIndex == aColIndex &&
+        (colSpan < minColSpan || minColSpan == -1)) {
       minColSpan = colSpan;
     }
     NS_ASSERTION((actualRowSpan > 0),"ActualRowSpan = 0 in FixBadColSpan");
   }
-  if(minColSpan > 1)
-  {
+  if (minColSpan > 1) {
     // The amount to reduce everyone's colspan
     // so at least one cell has colspan = 1
     int32_t colsReduced = minColSpan - 1;
-    for(rowIndex = 0; rowIndex < rowCount; rowIndex += std::max(actualRowSpan, 1))
-    {
+    for (rowIndex = 0; rowIndex < rowCount;
+         rowIndex += std::max(actualRowSpan, 1)) {
       rv = GetCellDataAt(aTable, rowIndex, aColIndex, getter_AddRefs(cell),
                          &startRowIndex, &startColIndex, &rowSpan, &colSpan,
                          &actualRowSpan, &actualColSpan, &isSelected);
       if (NS_FAILED(rv)) {
         return rv;
       }
       // Fixup colspans only for cells starting in current column
-      if(cell && colSpan > 0 &&
-         startColIndex == aColIndex &&
-         startRowIndex ==  rowIndex )
-      {
+      if (cell && colSpan > 0 &&
+          startColIndex == aColIndex &&
+          startRowIndex ==  rowIndex) {
         rv = SetColSpan(cell, colSpan-colsReduced);
         if (NS_FAILED(rv)) {
           return rv;
         }
       }
       NS_ASSERTION((actualRowSpan > 0),"ActualRowSpan = 0 in FixBadColSpan");
     }
   }
@@ -2626,89 +2512,83 @@ HTMLEditor::NormalizeTable(nsIDOMElement
   // Prevent auto insertion of BR in new cell until we're done
   AutoRules beginRulesSniffing(this, EditAction::insertNode, nsIEditor::eNext);
 
   nsCOMPtr<nsIDOMElement> cell;
   int32_t startRowIndex, startColIndex, rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
 
   // Scan all cells in each row to detect bad rowspan values
-  for(rowIndex = 0; rowIndex < rowCount; rowIndex++)
-  {
+  for (rowIndex = 0; rowIndex < rowCount; rowIndex++) {
     rv = FixBadRowSpan(table, rowIndex, rowCount);
     NS_ENSURE_SUCCESS(rv, rv);
   }
   // and same for colspans
-  for(colIndex = 0; colIndex < colCount; colIndex++)
-  {
+  for (colIndex = 0; colIndex < colCount; colIndex++) {
     rv = FixBadColSpan(table, colIndex, colCount);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Fill in missing cellmap locations with empty cells
-  for(rowIndex = 0; rowIndex < rowCount; rowIndex++)
-  {
+  for (rowIndex = 0; rowIndex < rowCount; rowIndex++) {
     nsCOMPtr<nsIDOMElement> previousCellInRow;
-
-    for(colIndex = 0; colIndex < colCount; colIndex++)
-    {
+    for (colIndex = 0; colIndex < colCount; colIndex++) {
       rv = GetCellDataAt(table, rowIndex, colIndex, getter_AddRefs(cell),
                          &startRowIndex, &startColIndex, &rowSpan, &colSpan,
                          &actualRowSpan, &actualColSpan, &isSelected);
       // NOTE: This is a *real* failure.
       // GetCellDataAt passes if cell is missing from cellmap
       if (NS_FAILED(rv)) {
         return rv;
       }
-      if (!cell)
-      {
+      if (!cell) {
         //We are missing a cell at a cellmap location
 #ifdef DEBUG
-        printf("NormalizeTable found missing cell at row=%d, col=%d\n", rowIndex, colIndex);
+        printf("NormalizeTable found missing cell at row=%d, col=%d\n",
+               rowIndex, colIndex);
 #endif
         // Add a cell after the previous Cell in the current row
-        if(previousCellInRow)
-        {
-          // Insert a new cell after (true), and return the new cell to us
-          rv = InsertCell(previousCellInRow, 1, 1, true, false,
-                          getter_AddRefs(cell));
-          NS_ENSURE_SUCCESS(rv, rv);
-
-          // Set this so we use returned new "cell" to set previousCellInRow below
-          if(cell)
-            startRowIndex = rowIndex;
-        } else {
+        if (!previousCellInRow) {
           // We don't have any cells in this row -- We are really messed up!
 #ifdef DEBUG
-          printf("NormalizeTable found no cells in row=%d, col=%d\n", rowIndex, colIndex);
+          printf("NormalizeTable found no cells in row=%d, col=%d\n",
+                 rowIndex, colIndex);
 #endif
           return NS_ERROR_FAILURE;
         }
+
+        // Insert a new cell after (true), and return the new cell to us
+        rv = InsertCell(previousCellInRow, 1, 1, true, false,
+                        getter_AddRefs(cell));
+        NS_ENSURE_SUCCESS(rv, rv);
+
+        // Set this so we use returned new "cell" to set previousCellInRow below
+        if (cell) {
+          startRowIndex = rowIndex;
+        }
       }
       // Save the last cell found in the same row we are scanning
-      if(startRowIndex == rowIndex)
-      {
+      if (startRowIndex == rowIndex) {
         previousCellInRow = cell;
       }
     }
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditor::GetCellIndexes(nsIDOMElement* aCell,
                            int32_t* aRowIndex,
                            int32_t* aColIndex)
 {
   NS_ENSURE_ARG_POINTER(aRowIndex);
   *aColIndex=0; // initialize out params
   NS_ENSURE_ARG_POINTER(aColIndex);
   *aRowIndex=0;
-  if (!aCell)
-  {
+  if (!aCell) {
     // Get the selected cell or the cell enclosing the selection anchor
     nsCOMPtr<nsIDOMElement> cell;
     nsresult rv = GetElementOrParentByTagName(NS_LITERAL_STRING("td"), nullptr,
                                               getter_AddRefs(cell));
     if (NS_FAILED(rv) || !cell) {
       return NS_ERROR_FAILURE;
     }
     aCell = cell;
@@ -2750,28 +2630,26 @@ HTMLEditor::GetNumberOfCellsInRow(nsIDOM
   do {
     int32_t startRowIndex, startColIndex, rowSpan, colSpan, actualRowSpan, actualColSpan;
     bool    isSelected;
     nsresult rv =
       GetCellDataAt(aTable, rowIndex, colIndex, getter_AddRefs(cell),
                     &startRowIndex, &startColIndex, &rowSpan, &colSpan,
                     &actualRowSpan, &actualColSpan, &isSelected);
     NS_ENSURE_SUCCESS(rv, 0);
-    if (cell)
-    {
+    if (cell) {
       // Only count cells that start in row we are working with
-      if (startRowIndex == rowIndex)
+      if (startRowIndex == rowIndex) {
         cellCount++;
-
+      }
       //Next possible location for a cell
       colIndex += actualColSpan;
+    } else {
+      colIndex++;
     }
-    else
-      colIndex++;
-
   } while (cell);
 
   return cellCount;
 }
 
 NS_IMETHODIMP
 HTMLEditor::GetTableSize(nsIDOMElement* aTable,
                          int32_t* aRowCount,
@@ -2824,37 +2702,37 @@ HTMLEditor::GetCellDataAt(nsIDOMElement*
   *aRowSpan = 0;
   *aColSpan = 0;
   *aActualRowSpan = 0;
   *aActualColSpan = 0;
   *aIsSelected = false;
 
   *aCell = nullptr;
 
-  if (!aTable)
-  {
+  if (!aTable) {
     // Get the selected table or the table enclosing the selection anchor
     nsCOMPtr<nsIDOMElement> table;
     nsresult rv =
       GetElementOrParentByTagName(NS_LITERAL_STRING("table"), nullptr,
                                   getter_AddRefs(table));
     NS_ENSURE_SUCCESS(rv, rv);
-    if (table)
-      aTable = table;
-    else
+    if (!table) {
       return NS_ERROR_FAILURE;
+    }
+    aTable = table;
   }
 
   nsTableWrapperFrame* tableFrame = GetTableFrame(aTable);
   NS_ENSURE_TRUE(tableFrame, NS_ERROR_FAILURE);
 
   nsTableCellFrame* cellFrame =
     tableFrame->GetCellFrameAt(aRowIndex, aColIndex);
-  if (!cellFrame)
+  if (!cellFrame) {
     return NS_ERROR_FAILURE;
+  }
 
   *aIsSelected = cellFrame->IsSelected();
   cellFrame->GetRowIndex(*aStartRowIndex);
   cellFrame->GetColIndex(*aStartColIndex);
   *aRowSpan = cellFrame->GetRowSpan();
   *aColSpan = cellFrame->GetColSpan();
   *aActualRowSpan = tableFrame->GetEffectiveRowSpanAt(aRowIndex, aColIndex);
   *aActualColSpan = tableFrame->GetEffectiveColSpanAt(aRowIndex, aColIndex);
@@ -2869,18 +2747,17 @@ NS_IMETHODIMP
 HTMLEditor::GetCellAt(nsIDOMElement* aTable,
                       int32_t aRowIndex,
                       int32_t aColIndex,
                       nsIDOMElement** aCell)
 {
   NS_ENSURE_ARG_POINTER(aCell);
   *aCell = nullptr;
 
-  if (!aTable)
-  {
+  if (!aTable) {
     // Get the selected table or the table enclosing the selection anchor
     nsCOMPtr<nsIDOMElement> table;
     nsresult rv =
       GetElementOrParentByTagName(NS_LITERAL_STRING("table"), nullptr,
                                   getter_AddRefs(table));
     NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(table, NS_ERROR_FAILURE);
     aTable = table;
@@ -2903,124 +2780,131 @@ HTMLEditor::GetCellAt(nsIDOMElement* aTa
 NS_IMETHODIMP
 HTMLEditor::GetCellSpansAt(nsIDOMElement* aTable,
                            int32_t aRowIndex,
                            int32_t aColIndex,
                            int32_t& aActualRowSpan,
                            int32_t& aActualColSpan)
 {
   nsTableWrapperFrame* tableFrame = GetTableFrame(aTable);
-  if (!tableFrame)
+  if (!tableFrame) {
     return NS_ERROR_FAILURE;
-
+  }
   aActualRowSpan = tableFrame->GetEffectiveRowSpanAt(aRowIndex, aColIndex);
   aActualColSpan = tableFrame->GetEffectiveColSpanAt(aRowIndex, aColIndex);
 
   return NS_OK;
 }
 
 nsresult
 HTMLEditor::GetCellContext(Selection** aSelection,
                            nsIDOMElement** aTable,
                            nsIDOMElement** aCell,
                            nsIDOMNode** aCellParent,
                            int32_t* aCellOffset,
                            int32_t* aRowIndex,
                            int32_t* aColIndex)
 {
   // Initialize return pointers
-  if (aSelection) *aSelection = nullptr;
-  if (aTable) *aTable = nullptr;
-  if (aCell) *aCell = nullptr;
-  if (aCellParent) *aCellParent = nullptr;
-  if (aCellOffset) *aCellOffset = 0;
-  if (aRowIndex) *aRowIndex = 0;
-  if (aColIndex) *aColIndex = 0;
+  if (aSelection) {
+    *aSelection = nullptr;
+  }
+  if (aTable) {
+    *aTable = nullptr;
+  }
+  if (aCell) {
+    *aCell = nullptr;
+  }
+  if (aCellParent) {
+    *aCellParent = nullptr;
+  }
+  if (aCellOffset) {
+    *aCellOffset = 0;
+  }
+  if (aRowIndex) {
+    *aRowIndex = 0;
+  }
+  if (aColIndex) {
+    *aColIndex = 0;
+  }
 
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);
 
-  if (aSelection)
-  {
+  if (aSelection) {
     *aSelection = selection.get();
     NS_ADDREF(*aSelection);
   }
   nsCOMPtr <nsIDOMElement> table;
   nsCOMPtr <nsIDOMElement> cell;
 
   // Caller may supply the cell...
-  if (aCell && *aCell)
+  if (aCell && *aCell) {
     cell = *aCell;
+  }
 
   // ...but if not supplied,
   //    get cell if it's the child of selection anchor node,
   //    or get the enclosing by a cell
-  if (!cell)
-  {
+  if (!cell) {
     // Find a selected or enclosing table element
     nsCOMPtr<nsIDOMElement> cellOrTableElement;
     int32_t selectedCount;
     nsAutoString tagName;
     nsresult rv =
       GetSelectedOrParentTableElement(tagName, &selectedCount,
                                       getter_AddRefs(cellOrTableElement));
     NS_ENSURE_SUCCESS(rv, rv);
-    if (tagName.EqualsLiteral("table"))
-    {
+    if (tagName.EqualsLiteral("table")) {
       // We have a selected table, not a cell
-      if (aTable)
-      {
+      if (aTable) {
         *aTable = cellOrTableElement.get();
         NS_ADDREF(*aTable);
       }
       return NS_OK;
     }
     if (!tagName.EqualsLiteral("td")) {
       return NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND;
     }
 
     // We found a cell
     cell = cellOrTableElement;
   }
-  if (aCell)
-  {
+  if (aCell) {
     *aCell = cell.get();
     NS_ADDREF(*aCell);
   }
 
   // Get containing table
   nsresult rv = GetElementOrParentByTagName(NS_LITERAL_STRING("table"), cell,
                                             getter_AddRefs(table));
   NS_ENSURE_SUCCESS(rv, rv);
   // Cell must be in a table, so fail if not found
   NS_ENSURE_TRUE(table, NS_ERROR_FAILURE);
-  if (aTable)
-  {
+  if (aTable) {
     *aTable = table.get();
     NS_ADDREF(*aTable);
   }
 
   // Get the rest of the related data only if requested
-  if (aRowIndex || aColIndex)
-  {
+  if (aRowIndex || aColIndex) {
     int32_t rowIndex, colIndex;
     // Get current cell location so we can put caret back there when done
     rv = GetCellIndexes(cell, &rowIndex, &colIndex);
     if (NS_FAILED(rv)) {
       return rv;
     }
     if (aRowIndex) {
       *aRowIndex = rowIndex;
     }
     if (aColIndex) {
       *aColIndex = colIndex;
     }
   }
-  if (aCellParent)
-  {
+  if (aCellParent) {
     nsCOMPtr <nsIDOMNode> cellParent;
     // Get the immediate parent of the cell
     rv = cell->GetParentNode(getter_AddRefs(cellParent));
     NS_ENSURE_SUCCESS(rv, rv);
     // Cell has to have a parent, so fail if not found
     NS_ENSURE_TRUE(cellParent, NS_ERROR_FAILURE);
 
     *aCellParent = cellParent.get();
@@ -3085,17 +2969,19 @@ HTMLEditor::GetCellFromRange(nsRange* aR
 }
 
 NS_IMETHODIMP
 HTMLEditor::GetFirstSelectedCell(nsIDOMRange** aRange,
                                  nsIDOMElement** aCell)
 {
   NS_ENSURE_TRUE(aCell, NS_ERROR_NULL_POINTER);
   *aCell = nullptr;
-  if (aRange) *aRange = nullptr;
+  if (aRange) {
+    *aRange = nullptr;
+  }
 
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);
 
   RefPtr<nsRange> range = selection->GetRangeAt(0);
   NS_ENSURE_TRUE(range, NS_ERROR_FAILURE);
 
   mSelectedCellIndex = 0;
@@ -3106,67 +2992,68 @@ HTMLEditor::GetFirstSelectedCell(nsIDOMR
   if (NS_FAILED(rv)) {
     return NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND;
   }
   // No cell means range was collapsed (cell was deleted)
   if (!*aCell) {
     return NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND;
   }
 
-  if (aRange)
-  {
+  if (aRange) {
     *aRange = range.get();
     NS_ADDREF(*aRange);
   }
 
   // Setup for next cell
   mSelectedCellIndex = 1;
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditor::GetNextSelectedCell(nsIDOMRange** aRange,
                                 nsIDOMElement** aCell)
 {
   NS_ENSURE_TRUE(aCell, NS_ERROR_NULL_POINTER);
   *aCell = nullptr;
-  if (aRange) *aRange = nullptr;
+  if (aRange) {
+    *aRange = nullptr;
+  }
 
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);
 
   int32_t rangeCount = selection->RangeCount();
 
   // Don't even try if index exceeds range count
   if (mSelectedCellIndex >= rangeCount) {
     return NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND;
   }
 
   // Scan through ranges to find next valid selected cell
   RefPtr<nsRange> range;
-  for (; mSelectedCellIndex < rangeCount; mSelectedCellIndex++)
-  {
+  for (; mSelectedCellIndex < rangeCount; mSelectedCellIndex++) {
     range = selection->GetRangeAt(mSelectedCellIndex);
     NS_ENSURE_TRUE(range, NS_ERROR_FAILURE);
 
     nsresult rv = GetCellFromRange(range, aCell);
     // Failure here means the range doesn't contain a cell
     NS_ENSURE_SUCCESS(rv, NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND);
 
     // We found a selected cell
-    if (*aCell) break;
+    if (*aCell) {
+      break;
+    }
 
     // If we didn't find a cell, continue to next range in selection
   }
   // No cell means all remaining ranges were collapsed (cells were deleted)
   NS_ENSURE_TRUE(*aCell, NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND);
 
-  if (aRange)
-  {
+  if (aRange) {
     *aRange = range.get();
     NS_ADDREF(*aRange);
   }
 
   // Setup for next cell
   mSelectedCellIndex++;
 
   return NS_OK;
@@ -3174,61 +3061,62 @@ HTMLEditor::GetNextSelectedCell(nsIDOMRa
 
 NS_IMETHODIMP
 HTMLEditor::GetFirstSelectedCellInTable(int32_t* aRowIndex,
                                         int32_t* aColIndex,
                                         nsIDOMElement** aCell)
 {
   NS_ENSURE_TRUE(aCell, NS_ERROR_NULL_POINTER);
   *aCell = nullptr;
-  if (aRowIndex)
+  if (aRowIndex) {
     *aRowIndex = 0;
-  if (aColIndex)
+  }
+  if (aColIndex) {
     *aColIndex = 0;
+  }
 
   nsCOMPtr<nsIDOMElement> cell;
   nsresult rv = GetFirstSelectedCell(nullptr, getter_AddRefs(cell));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(cell, NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND);
 
   *aCell = cell.get();
   NS_ADDREF(*aCell);
 
   // Also return the row and/or column if requested
-  if (aRowIndex || aColIndex)
-  {
+  if (aRowIndex || aColIndex) {
     int32_t startRowIndex, startColIndex;
     rv = GetCellIndexes(cell, &startRowIndex, &startColIndex);
     if (NS_FAILED(rv)) {
       return rv;
     }
 
-    if (aRowIndex)
+    if (aRowIndex) {
       *aRowIndex = startRowIndex;
-
-    if (aColIndex)
+    }
+    if (aColIndex) {
       *aColIndex = startColIndex;
+    }
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditor::SetSelectionAfterTableEdit(nsIDOMElement* aTable,
                                        int32_t aRow,
                                        int32_t aCol,
                                        int32_t aDirection,
                                        bool aSelected)
 {
   NS_ENSURE_TRUE(aTable, NS_ERROR_NOT_INITIALIZED);
 
   RefPtr<Selection> selection = GetSelection();
 
-  if (!selection)
-  {
+  if (!selection) {
     return NS_ERROR_FAILURE;
   }
 
   nsCOMPtr<nsIDOMElement> cell;
   bool done = false;
   do {
     nsresult rv = GetCellAt(aTable, aRow, aCol, getter_AddRefs(cell));
     if (NS_FAILED(rv)) {
@@ -3282,17 +3170,17 @@ HTMLEditor::SetSelectionAfterTableEdit(n
       }
     }
   } while (!done);
 
   // We didn't find a cell
   // Set selection to just before the table
   nsCOMPtr<nsIDOMNode> tableParent;
   nsresult rv = aTable->GetParentNode(getter_AddRefs(tableParent));
-  if(NS_SUCCEEDED(rv) && tableParent) {
+  if (NS_SUCCEEDED(rv) && tableParent) {
     int32_t tableOffset = GetChildOffset(aTable, tableParent);
     return selection->Collapse(tableParent, tableOffset);
   }
   // Last resort: Set selection to start of doc
   // (it's very bad to not have a valid selection!)
   return SetSelectionAtDocumentStart(selection);
 }
 
@@ -3313,53 +3201,46 @@ HTMLEditor::GetSelectedOrParentTableElem
   // Try to get the first selected cell
   nsCOMPtr<nsIDOMElement> tableOrCellElement;
   nsresult rv = GetFirstSelectedCell(nullptr,
                                      getter_AddRefs(tableOrCellElement));
   NS_ENSURE_SUCCESS(rv, rv);
 
   NS_NAMED_LITERAL_STRING(tdName, "td");
 
-  if (tableOrCellElement)
-  {
+  if (tableOrCellElement) {
       // Each cell is in its own selection range,
       //  so count signals multiple-cell selection
       rv = selection->GetRangeCount(aSelectedCount);
       NS_ENSURE_SUCCESS(rv, rv);
       aTagName = tdName;
-  }
-  else
-  {
+  } else {
     nsCOMPtr<nsIDOMNode> anchorNode;
     rv = selection->GetAnchorNode(getter_AddRefs(anchorNode));
     if (NS_FAILED(rv)) {
       return rv;
     }
     NS_ENSURE_TRUE(anchorNode, NS_ERROR_FAILURE);
 
     nsCOMPtr<nsIDOMNode> selectedNode;
 
     // Get child of anchor node, if exists
     bool hasChildren;
     anchorNode->HasChildNodes(&hasChildren);
 
-    if (hasChildren)
-    {
+    if (hasChildren) {
       int32_t anchorOffset;
       rv = selection->GetAnchorOffset(&anchorOffset);
       NS_ENSURE_SUCCESS(rv, rv);
       selectedNode = GetChildAt(anchorNode, anchorOffset);
-      if (!selectedNode)
-      {
+      if (!selectedNode) {
         selectedNode = anchorNode;
         // If anchor doesn't have a child, we can't be selecting a table element,
         //  so don't do the following:
-      }
-      else
-      {
+      } else {
         nsCOMPtr<nsIAtom> atom = EditorBase::GetTag(selectedNode);
 
         if (atom == nsGkAtoms::td) {
           tableOrCellElement = do_QueryInterface(selectedNode);
           aTagName = tdName;
           // Each cell is in its own selection range,
           //  so count signals multiple-cell selection
           rv = selection->GetRangeCount(aSelectedCount);
@@ -3370,31 +3251,29 @@ HTMLEditor::GetSelectedOrParentTableElem
           *aSelectedCount = 1;
         } else if (atom == nsGkAtoms::tr) {
           tableOrCellElement = do_QueryInterface(selectedNode);
           aTagName.AssignLiteral("tr");
           *aSelectedCount = 1;
         }
       }
     }
-    if (!tableOrCellElement)
-    {
+    if (!tableOrCellElement) {
       // Didn't find a table element -- find a cell parent
       rv = GetElementOrParentByTagName(tdName, anchorNode,
                                        getter_AddRefs(tableOrCellElement));
       if (NS_FAILED(rv)) {
         return rv;
       }
       if (tableOrCellElement) {
         aTagName = tdName;
       }
     }
   }
-  if (tableOrCellElement)
-  {
+  if (tableOrCellElement) {
     *aTableElement = tableOrCellElement.get();
     NS_ADDREF(*aTableElement);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLEditor::GetSelectedCellsType(nsIDOMElement* aElement,
@@ -3435,28 +3314,28 @@ HTMLEditor::GetSelectedCellsType(nsIDOME
   while (NS_SUCCEEDED(rv) && selectedCell) {
     // Get the cell's location in the cellmap
     int32_t startRowIndex, startColIndex;
     rv = GetCellIndexes(selectedCell, &startRowIndex, &startColIndex);
     if (NS_FAILED(rv)) {
       return rv;
     }
 
-    if (!indexArray.Contains(startColIndex))
-    {
+    if (!indexArray.Contains(startColIndex)) {
       indexArray.AppendElement(startColIndex);
       allCellsInRowAreSelected = AllCellsInRowSelected(table, startRowIndex, colCount);
       // We're done as soon as we fail for any row
-      if (!allCellsInRowAreSelected) break;
+      if (!allCellsInRowAreSelected) {
+        break;
+      }
     }
     rv = GetNextSelectedCell(nullptr, getter_AddRefs(selectedCell));
   }
 
-  if (allCellsInRowAreSelected)
-  {
+  if (allCellsInRowAreSelected) {
     *aSelectionType = nsISelectionPrivate::TABLESELECTION_ROW;
     return NS_OK;
   }
   // Test for columns
 
   // Empty the indexArray
   indexArray.Clear();
 
@@ -3465,43 +3344,45 @@ HTMLEditor::GetSelectedCellsType(nsIDOME
   while (NS_SUCCEEDED(rv) && selectedCell) {
     // Get the cell's location in the cellmap
     int32_t startRowIndex, startColIndex;
     rv = GetCellIndexes(selectedCell, &startRowIndex, &startColIndex);
     if (NS_FAILED(rv)) {
       return rv;
     }
 
-    if (!indexArray.Contains(startRowIndex))
-    {
+    if (!indexArray.Contains(startRowIndex)) {
       indexArray.AppendElement(startColIndex);
       allCellsInColAreSelected = AllCellsInColumnSelected(table, startColIndex, rowCount);
       // We're done as soon as we fail for any column
-      if (!allCellsInRowAreSelected) break;
+      if (!allCellsInRowAreSelected) {
+        break;
+      }
     }
     rv = GetNextSelectedCell(nullptr, getter_AddRefs(selectedCell));
   }
-  if (allCellsInColAreSelected)
+  if (allCellsInColAreSelected) {
     *aSelectionType = nsISelectionPrivate::TABLESELECTION_COLUMN;
+  }
 
   return NS_OK;
 }
 
 bool
 HTMLEditor::AllCellsInRowSelected(nsIDOMElement* aTable,
                                   int32_t aRowIndex,
                                   int32_t aNumberOfColumns)
 {
   NS_ENSURE_TRUE(aTable, false);
 
   int32_t curStartRowIndex, curStartColIndex, rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
 
-  for( int32_t col = 0; col < aNumberOfColumns; col += std::max(actualColSpan, 1))
-  {
+  for (int32_t col = 0; col < aNumberOfColumns;
+       col += std::max(actualColSpan, 1)) {
     nsCOMPtr<nsIDOMElement> cell;
     nsresult rv = GetCellDataAt(aTable, aRowIndex, col, getter_AddRefs(cell),
                                 &curStartRowIndex, &curStartColIndex,
                                 &rowSpan, &colSpan,
                                 &actualRowSpan, &actualColSpan, &isSelected);
 
     NS_ENSURE_SUCCESS(rv, false);
     // If no cell, we may have a "ragged" right edge,
@@ -3521,18 +3402,18 @@ HTMLEditor::AllCellsInColumnSelected(nsI
                                      int32_t aColIndex,
                                      int32_t aNumberOfRows)
 {
   NS_ENSURE_TRUE(aTable, false);
 
   int32_t curStartRowIndex, curStartColIndex, rowSpan, colSpan, actualRowSpan, actualColSpan;
   bool    isSelected;
 
-  for( int32_t row = 0; row < aNumberOfRows; row += std::max(actualRowSpan, 1))
-  {
+  for (int32_t row = 0; row < aNumberOfRows;
+       row += std::max(actualRowSpan, 1)) {
     nsCOMPtr<nsIDOMElement> cell;
     nsresult rv = GetCellDataAt(aTable, row, aColIndex, getter_AddRefs(cell),
                                 &curStartRowIndex, &curStartColIndex,
                                 &rowSpan, &colSpan,
                                 &actualRowSpan, &actualColSpan, &isSelected);
 
     NS_ENSURE_SUCCESS(rv, false);
     // If no cell, we must have a "ragged" right edge on the last column
--- a/editor/libeditor/HTMLURIRefObject.cpp
+++ b/editor/libeditor/HTMLURIRefObject.cpp
@@ -79,138 +79,138 @@ HTMLURIRefObject::Reset()
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLURIRefObject::GetNextURI(nsAString& aURI)
 {
   NS_ENSURE_TRUE(mNode, NS_ERROR_NOT_INITIALIZED);
 
+  // XXX Why don't you use nsIAtom for comparing the tag name a lot?
   nsAutoString tagName;
   nsresult rv = mNode->GetNodeName(tagName);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Loop over attribute list:
-  if (!mAttributes)
-  {
+  if (!mAttributes) {
     nsCOMPtr<nsIDOMElement> element (do_QueryInterface(mNode));
     NS_ENSURE_TRUE(element, NS_ERROR_INVALID_ARG);
 
     mCurAttrIndex = 0;
     element->GetAttributes(getter_AddRefs(mAttributes));
     NS_ENSURE_TRUE(mAttributes, NS_ERROR_NOT_INITIALIZED);
 
     rv = mAttributes->GetLength(&mAttributeCnt);
     NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(mAttributeCnt, NS_ERROR_FAILURE);
     mCurAttrIndex = 0;
   }
 
-  while (mCurAttrIndex < mAttributeCnt)
-  {
+  while (mCurAttrIndex < mAttributeCnt) {
     nsCOMPtr<nsIDOMAttr> attrNode;
     rv = mAttributes->Item(mCurAttrIndex++, getter_AddRefs(attrNode));
     NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_ARG_POINTER(attrNode);
     nsString curAttr;
     rv = attrNode->GetName(curAttr);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // href >> A, AREA, BASE, LINK
-    if (MATCHES(curAttr, "href"))
-    {
-      if (!MATCHES(tagName, "a") && !MATCHES(tagName, "area")
-          && !MATCHES(tagName, "base") && !MATCHES(tagName, "link"))
+    if (MATCHES(curAttr, "href")) {
+      if (!MATCHES(tagName, "a") && !MATCHES(tagName, "area") &&
+          !MATCHES(tagName, "base") && !MATCHES(tagName, "link")) {
         continue;
+      }
       rv = attrNode->GetValue(aURI);
       NS_ENSURE_SUCCESS(rv, rv);
       nsString uri (aURI);
       // href pointing to a named anchor doesn't count
-      if (aURI.First() != char16_t('#'))
+      if (aURI.First() != char16_t('#')) {
         return NS_OK;
+      }
       aURI.Truncate();
       return NS_ERROR_INVALID_ARG;
     }
     // src >> FRAME, IFRAME, IMG, INPUT, SCRIPT
-    else if (MATCHES(curAttr, "src"))
-    {
-      if (!MATCHES(tagName, "img")
-          && !MATCHES(tagName, "frame") && !MATCHES(tagName, "iframe")
-          && !MATCHES(tagName, "input") && !MATCHES(tagName, "script"))
+    else if (MATCHES(curAttr, "src")) {
+      if (!MATCHES(tagName, "img") &&
+          !MATCHES(tagName, "frame") && !MATCHES(tagName, "iframe") &&
+          !MATCHES(tagName, "input") && !MATCHES(tagName, "script")) {
         continue;
+      }
       return attrNode->GetValue(aURI);
     }
     //<META http-equiv="refresh" content="3,http://www.acme.com/intro.html">
-    else if (MATCHES(curAttr, "content"))
-    {
-      if (!MATCHES(tagName, "meta"))
+    else if (MATCHES(curAttr, "content")) {
+      if (!MATCHES(tagName, "meta")) {
         continue;
+      }
     }
     // longdesc >> FRAME, IFRAME, IMG
-    else if (MATCHES(curAttr, "longdesc"))
-    {
-      if (!MATCHES(tagName, "img")
-          && !MATCHES(tagName, "frame") && !MATCHES(tagName, "iframe"))
+    else if (MATCHES(curAttr, "longdesc")) {
+      if (!MATCHES(tagName, "img") &&
+          !MATCHES(tagName, "frame") && !MATCHES(tagName, "iframe")) {
         continue;
+      }
     }
     // usemap >> IMG, INPUT, OBJECT
-    else if (MATCHES(curAttr, "usemap"))
-    {
-      if (!MATCHES(tagName, "img")
-          && !MATCHES(tagName, "input") && !MATCHES(tagName, "object"))
+    else if (MATCHES(curAttr, "usemap")) {
+      if (!MATCHES(tagName, "img") &&
+          !MATCHES(tagName, "input") && !MATCHES(tagName, "object")) {
         continue;
+      }
     }
     // action >> FORM
-    else if (MATCHES(curAttr, "action"))
-    {
-      if (!MATCHES(tagName, "form"))
+    else if (MATCHES(curAttr, "action")) {
+      if (!MATCHES(tagName, "form")) {
         continue;
+      }
     }
     // background >> BODY
-    else if (MATCHES(curAttr, "background"))
-    {
-      if (!MATCHES(tagName, "body"))
+    else if (MATCHES(curAttr, "background")) {
+      if (!MATCHES(tagName, "body")) {
         continue;
+      }
     }
     // codebase >> OBJECT, APPLET
-    else if (MATCHES(curAttr, "codebase"))
-    {
-      if (!MATCHES(tagName, "meta"))
+    else if (MATCHES(curAttr, "codebase")) {
+      if (!MATCHES(tagName, "meta")) {
         continue;
+      }
     }
     // classid >> OBJECT
-    else if (MATCHES(curAttr, "classid"))
-    {
-      if (!MATCHES(tagName, "object"))
+    else if (MATCHES(curAttr, "classid")) {
+      if (!MATCHES(tagName, "object")) {
         continue;
+      }
     }
     // data >> OBJECT
-    else if (MATCHES(curAttr, "data"))
-    {
-      if (!MATCHES(tagName, "object"))
+    else if (MATCHES(curAttr, "data")) {
+      if (!MATCHES(tagName, "object")) {
         continue;
+      }
     }
     // cite >> BLOCKQUOTE, DEL, INS, Q
-    else if (MATCHES(curAttr, "cite"))
-    {
-      if (!MATCHES(tagName, "blockquote") && !MATCHES(tagName, "q")
-          && !MATCHES(tagName, "del") && !MATCHES(tagName, "ins"))
+    else if (MATCHES(curAttr, "cite")) {
+      if (!MATCHES(tagName, "blockquote") && !MATCHES(tagName, "q") &&
+          !MATCHES(tagName, "del") && !MATCHES(tagName, "ins")) {
         continue;
+      }
     }
     // profile >> HEAD
-    else if (MATCHES(curAttr, "profile"))
-    {
-      if (!MATCHES(tagName, "head"))
+    else if (MATCHES(curAttr, "profile")) {
+      if (!MATCHES(tagName, "head")) {
         continue;
+      }
     }
     // archive attribute on APPLET; warning, it contains a list of URIs.
-    else if (MATCHES(curAttr, "archive"))
-    {
-      if (!MATCHES(tagName, "applet"))
+    else if (MATCHES(curAttr, "archive")) {
+      if (!MATCHES(tagName, "applet")) {
         continue;
+      }
     }
   }
   // Return a code to indicate that there are no more,
   // to distinguish that case from real errors.
   return NS_ERROR_NOT_AVAILABLE;
 }
 
 NS_IMETHODIMP
@@ -231,18 +231,17 @@ HTMLURIRefObject::GetNode(nsIDOMNode** a
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HTMLURIRefObject::SetNode(nsIDOMNode* aNode)
 {
   mNode = aNode;
   nsAutoString dummyURI;
-  if (NS_SUCCEEDED(GetNextURI(dummyURI)))
-  {
+  if (NS_SUCCEEDED(GetNextURI(dummyURI))) {
     mCurAttrIndex = 0;    // Reset so we'll get the first node next time
     return NS_OK;
   }
 
   // If there weren't any URIs in the attributes,
   // then don't accept this node.
   mNode = 0;
   return NS_ERROR_INVALID_ARG;
--- a/editor/libeditor/InternetCiter.cpp
+++ b/editor/libeditor/InternetCiter.cpp
@@ -36,117 +36,117 @@ InternetCiter::GetCiteString(const nsASt
   char16_t uch = nl;
 
   // Strip trailing new lines which will otherwise turn up
   // as ugly quoted empty lines.
   nsReadingIterator <char16_t> beginIter,endIter;
   aInString.BeginReading(beginIter);
   aInString.EndReading(endIter);
   while(beginIter!= endIter &&
-        (*endIter == cr ||
-         *endIter == nl))
-  {
+        (*endIter == cr || *endIter == nl)) {
     --endIter;
   }
 
   // Loop over the string:
-  while (beginIter != endIter)
-  {
-    if (uch == nl)
-    {
+  while (beginIter != endIter) {
+    if (uch == nl) {
       aOutString.Append(gt);
       // No space between >: this is ">>> " style quoting, for
       // compatibility with RFC 2646 and format=flowed.
-      if (*beginIter != gt)
+      if (*beginIter != gt) {
         aOutString.Append(space);
+      }
     }
 
     uch = *beginIter;
     ++beginIter;
 
     aOutString += uch;
   }
 
-  if (uch != nl)
+  if (uch != nl) {
     aOutString += nl;
-
+  }
   return NS_OK;
 }
 
 nsresult
 InternetCiter::StripCitesAndLinebreaks(const nsAString& aInString,
                                        nsAString& aOutString,
                                        bool aLinebreaksToo,
                                        int32_t* aCiteLevel)
 {
-  if (aCiteLevel)
+  if (aCiteLevel) {
     *aCiteLevel = 0;
+  }
 
   aOutString.Truncate();
   nsReadingIterator <char16_t> beginIter,endIter;
   aInString.BeginReading(beginIter);
   aInString.EndReading(endIter);
-  while (beginIter!= endIter)  // loop over lines
-  {
+  while (beginIter!= endIter) { // loop over lines
     // Clear out cites first, at the beginning of the line:
     int32_t thisLineCiteLevel = 0;
-    while (beginIter!= endIter && (*beginIter == gt || nsCRT::IsAsciiSpace(*beginIter)))
-    {
-      if (*beginIter == gt) ++thisLineCiteLevel;
+    while (beginIter!= endIter &&
+           (*beginIter == gt || nsCRT::IsAsciiSpace(*beginIter))) {
+      if (*beginIter == gt) {
+        ++thisLineCiteLevel;
+      }
       ++beginIter;
     }
-
     // Now copy characters until line end:
-    while (beginIter != endIter && (*beginIter != '\r' && *beginIter != '\n'))
-    {
+    while (beginIter != endIter && (*beginIter != '\r' && *beginIter != '\n')) {
       aOutString.Append(*beginIter);
       ++beginIter;
     }
-    if (aLinebreaksToo)
+    if (aLinebreaksToo) {
       aOutString.Append(char16_t(' '));
-    else
+    } else {
       aOutString.Append(char16_t('\n'));    // DOM linebreaks, not NS_LINEBREAK
-      // Skip over any more consecutive linebreak-like characters:
-    while (beginIter != endIter && (*beginIter == '\r' || *beginIter == '\n'))
+    }
+    // Skip over any more consecutive linebreak-like characters:
+    while (beginIter != endIter && (*beginIter == '\r' || *beginIter == '\n')) {
       ++beginIter;
-
+    }
     // Done with this line -- update cite level
-    if (aCiteLevel && (thisLineCiteLevel > *aCiteLevel))
+    if (aCiteLevel && (thisLineCiteLevel > *aCiteLevel)) {
       *aCiteLevel = thisLineCiteLevel;
+    }
   }
   return NS_OK;
 }
 
 nsresult
 InternetCiter::StripCites(const nsAString& aInString,
                           nsAString& aOutString)
 {
   return StripCitesAndLinebreaks(aInString, aOutString, false, 0);
 }
 
 static void AddCite(nsAString& aOutString, int32_t citeLevel)
 {
-  for (int32_t i = 0; i < citeLevel; ++i)
+  for (int32_t i = 0; i < citeLevel; ++i) {
     aOutString.Append(gt);
-  if (citeLevel > 0)
+  }
+  if (citeLevel > 0) {
     aOutString.Append(space);
+  }
 }
 
 static inline void
 BreakLine(nsAString& aOutString, uint32_t& outStringCol,
           uint32_t citeLevel)
 {
   aOutString.Append(nl);
-  if (citeLevel > 0)
-  {
+  if (citeLevel > 0) {
     AddCite(aOutString, citeLevel);
     outStringCol = citeLevel + 1;
+  } else {
+    outStringCol = 0;
   }
-  else
-    outStringCol = 0;
 }
 
 static inline bool IsSpace(char16_t c)
 {
   const char16_t nbsp (0xa0);
   return (nsCRT::IsAsciiSpace(c) || (c == nl) || (c == cr) || (c == nbsp));
 }
 
@@ -172,199 +172,195 @@ InternetCiter::Rewrap(const nsAString& a
 
   // Loop over lines in the input string, rewrapping each one.
   uint32_t length;
   uint32_t posInString = 0;
   uint32_t outStringCol = 0;
   uint32_t citeLevel = 0;
   const nsPromiseFlatString &tString = PromiseFlatString(aInString);
   length = tString.Length();
-  while (posInString < length)
-  {
+  while (posInString < length) {
     // Get the new cite level here since we're at the beginning of a line
     uint32_t newCiteLevel = 0;
-    while (posInString < length && tString[posInString] == gt)
-    {
+    while (posInString < length && tString[posInString] == gt) {
       ++newCiteLevel;
       ++posInString;
-      while (posInString < length && tString[posInString] == space)
+      while (posInString < length && tString[posInString] == space) {
         ++posInString;
+      }
     }
-    if (posInString >= length)
+    if (posInString >= length) {
       break;
+    }
 
     // Special case: if this is a blank line, maintain a blank line
     // (retain the original paragraph breaks)
-    if (tString[posInString] == nl && !aOutString.IsEmpty())
-    {
-      if (aOutString.Last() != nl)
+    if (tString[posInString] == nl && !aOutString.IsEmpty()) {
+      if (aOutString.Last() != nl) {
         aOutString.Append(nl);
+      }
       AddCite(aOutString, newCiteLevel);
       aOutString.Append(nl);
 
       ++posInString;
       outStringCol = 0;
       continue;
     }
 
     // If the cite level has changed, then start a new line with the
     // new cite level (but if we're at the beginning of the string,
     // don't bother).
-    if (newCiteLevel != citeLevel && posInString > newCiteLevel+1
-        && outStringCol != 0)
-    {
+    if (newCiteLevel != citeLevel && posInString > newCiteLevel+1 &&
+        outStringCol) {
       BreakLine(aOutString, outStringCol, 0);
     }
     citeLevel = newCiteLevel;
 
     // Prepend the quote level to the out string if appropriate
-    if (outStringCol == 0)
-    {
+    if (!outStringCol) {
       AddCite(aOutString, citeLevel);
       outStringCol = citeLevel + (citeLevel ? 1 : 0);
     }
     // If it's not a cite, and we're not at the beginning of a line in
     // the output string, add a space to separate new text from the
     // previous text.
-    else if (outStringCol > citeLevel)
-    {
+    else if (outStringCol > citeLevel) {
       aOutString.Append(space);
       ++outStringCol;
     }
 
     // find the next newline -- don't want to go farther than that
     int32_t nextNewline = tString.FindChar(nl, posInString);
-    if (nextNewline < 0) nextNewline = length;
+    if (nextNewline < 0) {
+      nextNewline = length;
+    }
 
     // For now, don't wrap unquoted lines at all.
     // This is because the plaintext edit window has already wrapped them
     // by the time we get them for rewrap, yet when we call the line
     // breaker, it will refuse to break backwards, and we'll end up
     // with a line that's too long and gets displayed as a lone word
     // on a line by itself.  Need special logic to detect this case
     // and break it ourselves without resorting to the line breaker.
-    if (citeLevel == 0)
-    {
+    if (!citeLevel) {
       aOutString.Append(Substring(tString, posInString,
                                   nextNewline-posInString));
       outStringCol += nextNewline - posInString;
-      if (nextNewline != (int32_t)length)
-      {
+      if (nextNewline != (int32_t)length) {
         aOutString.Append(nl);
         outStringCol = 0;
       }
       posInString = nextNewline+1;
       continue;
     }
 
     // Otherwise we have to use the line breaker and loop
     // over this line of the input string to get all of it:
-    while ((int32_t)posInString < nextNewline)
-    {
+    while ((int32_t)posInString < nextNewline) {
       // Skip over initial spaces:
-      while ((int32_t)posInString < nextNewline
-             && nsCRT::IsAsciiSpace(tString[posInString]))
+      while ((int32_t)posInString < nextNewline &&
+             nsCRT::IsAsciiSpace(tString[posInString])) {
         ++posInString;
+      }
 
       // If this is a short line, just append it and continue:
-      if (outStringCol + nextNewline - posInString <= aWrapCol-citeLevel-1)
-      {
+      if (outStringCol + nextNewline - posInString <= aWrapCol-citeLevel-1) {
         // If this short line is the final one in the in string,
         // then we need to include the final newline, if any:
-        if (nextNewline+1 == (int32_t)length && tString[nextNewline-1] == nl)
+        if (nextNewline+1 == (int32_t)length && tString[nextNewline-1] == nl) {
           ++nextNewline;
-
+        }
         // Trim trailing spaces:
         int32_t lastRealChar = nextNewline;
-        while ((uint32_t)lastRealChar > posInString
-               && nsCRT::IsAsciiSpace(tString[lastRealChar-1]))
+        while ((uint32_t)lastRealChar > posInString &&
+               nsCRT::IsAsciiSpace(tString[lastRealChar-1])) {
           --lastRealChar;
+        }
 
         aOutString += Substring(tString,
                                 posInString, lastRealChar - posInString);
         outStringCol += lastRealChar - posInString;
         posInString = nextNewline + 1;
         continue;
       }
 
       int32_t eol = posInString + aWrapCol - citeLevel - outStringCol;
       // eol is the prospective end of line.
       // We'll first look backwards from there for a place to break.
       // If it's already less than our current position,
       // then our line is already too long, so break now.
-      if (eol <= (int32_t)posInString)
-      {
+      if (eol <= (int32_t)posInString) {
         BreakLine(aOutString, outStringCol, citeLevel);
         continue;    // continue inner loop, with outStringCol now at bol
       }
 
       int32_t breakPt = 0;
+      // XXX Why this uses NS_ERROR_"BASE"?
       rv = NS_ERROR_BASE;
-      if (lineBreaker)
-      {
+      if (lineBreaker) {
         breakPt = lineBreaker->Prev(tString.get() + posInString,
                                  length - posInString, eol + 1 - posInString);
-        if (breakPt == NS_LINEBREAKER_NEED_MORE_TEXT)
-        {
+        if (breakPt == NS_LINEBREAKER_NEED_MORE_TEXT) {
           // if we couldn't find a breakpoint looking backwards,
           // and we're not starting a new line, then end this line
           // and loop around again:
-          if (outStringCol > citeLevel + 1)
-          {
+          if (outStringCol > citeLevel + 1) {
             BreakLine(aOutString, outStringCol, citeLevel);
             continue;    // continue inner loop, with outStringCol now at bol
           }
 
           // Else try looking forwards:
           breakPt = lineBreaker->Next(tString.get() + posInString,
                                       length - posInString, eol - posInString);
-          if (breakPt == NS_LINEBREAKER_NEED_MORE_TEXT) rv = NS_ERROR_BASE;
-          else rv = NS_OK;
+
+          rv = breakPt == NS_LINEBREAKER_NEED_MORE_TEXT ? NS_ERROR_BASE :
+                                                          NS_OK;
+        } else {
+          rv = NS_OK;
         }
-        else rv = NS_OK;
       }
       // If rv is okay, then breakPt is the place to break.
       // If we get out here and rv is set, something went wrong with line
       // breaker.  Just break the line, hard.
-      if (NS_FAILED(rv))
-      {
+      if (NS_FAILED(rv)) {
         breakPt = eol;
       }
 
       // Special case: maybe we should have wrapped last time.
       // If the first breakpoint here makes the current line too long,
       // then if we already have text on the current line,
       // break and loop around again.
       // If we're at the beginning of the current line, though,
       // don't force a break since the long word might be a url
       // and breaking it would make it unclickable on the other end.
       const int SLOP = 6;
-      if (outStringCol + breakPt > aWrapCol + SLOP
-          && outStringCol > citeLevel+1)
-      {
+      if (outStringCol + breakPt > aWrapCol + SLOP &&
+          outStringCol > citeLevel+1) {
         BreakLine(aOutString, outStringCol, citeLevel);
         continue;
       }
 
       nsAutoString sub (Substring(tString, posInString, breakPt));
       // skip newlines or whitespace at the end of the string
       int32_t subend = sub.Length();
-      while (subend > 0 && IsSpace(sub[subend-1]))
+      while (subend > 0 && IsSpace(sub[subend-1])) {
         --subend;
+      }
       sub.Left(sub, subend);
       aOutString += sub;
       outStringCol += sub.Length();
       // Advance past the whitespace which caused the wrap:
       posInString += breakPt;
-      while (posInString < length && IsSpace(tString[posInString]))
+      while (posInString < length && IsSpace(tString[posInString])) {
         ++posInString;
+      }
 
       // Add a newline and the quote level to the out string
-      if (posInString < length)    // not for the last line, though
+      if (posInString < length) {  // not for the last line, though
         BreakLine(aOutString, outStringCol, citeLevel);
-
+      }
     } // end inner loop within one line of aInString
   } // end outer loop over lines of aInString
 
   return NS_OK;
 }
 
 } // namespace mozilla
--- a/editor/libeditor/PlaceholderTransaction.cpp
+++ b/editor/libeditor/PlaceholderTransaction.cpp
@@ -106,18 +106,17 @@ NS_IMETHODIMP
 PlaceholderTransaction::Merge(nsITransaction* aTransaction,
                               bool* aDidMerge)
 {
   NS_ENSURE_TRUE(aDidMerge && aTransaction, NS_ERROR_NULL_POINTER);
 
   // set out param default value
   *aDidMerge=false;
 
-  if (mForwarding)
-  {
+  if (mForwarding) {
     NS_NOTREACHED("tried to merge into a placeholder that was in forwarding mode!");
     return NS_ERROR_FAILURE;
   }
 
   // check to see if aTransaction is one of the editor's
   // private transactions. If not, we want to avoid merging
   // the foreign transaction into our placeholder since we
   // don't know what it does.
@@ -160,20 +159,19 @@ PlaceholderTransaction::Merge(nsITransac
     }
     *aDidMerge = true;
 //  RememberEndingSelection();
 //  efficiency hack: no need to remember selection here, as we haven't yet
 //  finished the initial batch and we know we will be told when the batch ends.
 //  we can remeber the selection then.
   } else {
     // merge typing or IME or deletion transactions if the selection matches
-    if (((mName.get() == nsGkAtoms::TypingTxnName) ||
-         (mName.get() == nsGkAtoms::IMETxnName)    ||
-         (mName.get() == nsGkAtoms::DeleteTxnName))
-         && !mCommitted) {
+    if ((mName.get() == nsGkAtoms::TypingTxnName ||
+         mName.get() == nsGkAtoms::IMETxnName    ||
+         mName.get() == nsGkAtoms::DeleteTxnName) && !mCommitted) {
       if (absorbingTransaction) {
         nsCOMPtr<nsIAtom> atom;
         absorbingTransaction->GetTxnName(getter_AddRefs(atom));
         if (atom && atom == mName) {
           // check if start selection of next placeholder matches
           // end selection of this placeholder
           bool isSame;
           absorbingTransaction->StartSelectionEquals(&mEndSel, &isSame);
@@ -195,18 +193,17 @@ PlaceholderTransaction::Merge(nsITransac
   return NS_OK;
 }
 
 NS_IMETHODIMP
 PlaceholderTransaction::GetTxnDescription(nsAString& aString)
 {
   aString.AssignLiteral("PlaceholderTransaction: ");
 
-  if (mName)
-  {
+  if (mName) {
     nsAutoString name;
     mName->ToString(name);
     aString += name;
   }
 
   return NS_OK;
 }
 
@@ -218,36 +215,35 @@ PlaceholderTransaction::GetTxnName(nsIAt
 
 NS_IMETHODIMP
 PlaceholderTransaction::StartSelectionEquals(SelectionState* aSelState,
                                              bool* aResult)
 {
   // determine if starting selection matches the given selection state.
   // note that we only care about collapsed selections.
   NS_ENSURE_TRUE(aResult && aSelState, NS_ERROR_NULL_POINTER);
-  if (!mStartSel->IsCollapsed() || !aSelState->IsCollapsed())
-  {
+  if (!mStartSel->IsCollapsed() || !aSelState->IsCollapsed()) {
     *aResult = false;
     return NS_OK;
   }
   *aResult = mStartSel->IsEqual(aSelState);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 PlaceholderTransaction::EndPlaceHolderBatch()
 {
   mAbsorb = false;
 
-  if (mForwarding)
-  {
+  if (mForwarding) {
     nsCOMPtr<nsIAbsorbingTransaction> plcTxn = do_QueryReferent(mForwarding);
-    if (plcTxn) plcTxn->EndPlaceHolderBatch();
+    if (plcTxn) {
+      plcTxn->EndPlaceHolderBatch();
+    }
   }
-
   // remember our selection state.
   return RememberEndingSelection();
 }
 
 NS_IMETHODIMP
 PlaceholderTransaction::ForwardEndBatchTo(
                           nsIAbsorbingTransaction* aForwardingAddress)
 {
--- a/editor/libeditor/SelectionState.cpp
+++ b/editor/libeditor/SelectionState.cpp
@@ -63,66 +63,74 @@ SelectionState::SaveSelection(Selection*
     mArray[i]->StoreRange(aSel->GetRangeAt(i));
   }
 }
 
 nsresult
 SelectionState::RestoreSelection(Selection* aSel)
 {
   NS_ENSURE_TRUE(aSel, NS_ERROR_NULL_POINTER);
-  uint32_t i, arrayCount = mArray.Length();
 
   // clear out selection
   aSel->RemoveAllRanges();
 
   // set the selection ranges anew
-  for (i=0; i<arrayCount; i++)
-  {
+  size_t arrayCount = mArray.Length();
+  for (size_t i = 0; i < arrayCount; i++) {
     RefPtr<nsRange> range = mArray[i]->GetRange();
     NS_ENSURE_TRUE(range, NS_ERROR_UNEXPECTED);
 
     nsresult rv = aSel->AddRange(range);
     if (NS_FAILED(rv)) {
       return rv;
     }
   }
   return NS_OK;
 }
 
 bool
 SelectionState::IsCollapsed()
 {
-  if (1 != mArray.Length()) return false;
+  if (mArray.Length() != 1) {
+    return false;
+  }
   RefPtr<nsRange> range = mArray[0]->GetRange();
   NS_ENSURE_TRUE(range, false);
   bool bIsCollapsed = false;
   range->GetCollapsed(&bIsCollapsed);
   return bIsCollapsed;
 }
 
 bool
 SelectionState::IsEqual(SelectionState* aSelState)
 {
   NS_ENSURE_TRUE(aSelState, false);
-  uint32_t i, myCount = mArray.Length(), itsCount = aSelState->mArray.Length();
-  if (myCount != itsCount) return false;
-  if (myCount < 1) return false;
+  size_t myCount = mArray.Length(), itsCount = aSelState->mArray.Length();
+  if (myCount != itsCount) {
+    return false;
+  }
+  if (!myCount) {
+    return false;
+  }
 
-  for (i=0; i<myCount; i++)
-  {
+  for (size_t i = 0; i < myCount; i++) {
     RefPtr<nsRange> myRange = mArray[i]->GetRange();
     RefPtr<nsRange> itsRange = aSelState->mArray[i]->GetRange();
     NS_ENSURE_TRUE(myRange && itsRange, false);
 
     int16_t compResult;
     nsresult rv;
     rv = myRange->CompareBoundaryPoints(nsIDOMRange::START_TO_START, itsRange, &compResult);
-    if (NS_FAILED(rv) || compResult) return false;
+    if (NS_FAILED(rv) || compResult) {
+      return false;
+    }
     rv = myRange->CompareBoundaryPoints(nsIDOMRange::END_TO_END, itsRange, &compResult);
-    if (NS_FAILED(rv) || compResult) return false;
+    if (NS_FAILED(rv) || compResult) {
+      return false;
+    }
   }
   // if we got here, they are equal
   return true;
 }
 
 void
 SelectionState::MakeEmpty()
 {
@@ -150,54 +158,59 @@ RangeUpdater::RangeUpdater()
 RangeUpdater::~RangeUpdater()
 {
   // nothing to do, we don't own the items in our array.
 }
 
 void
 RangeUpdater::RegisterRangeItem(RangeItem* aRangeItem)
 {
-  if (!aRangeItem) return;
-  if (mArray.Contains(aRangeItem))
-  {
+  if (!aRangeItem) {
+    return;
+  }
+  if (mArray.Contains(aRangeItem)) {
     NS_ERROR("tried to register an already registered range");
     return;  // don't register it again.  It would get doubly adjusted.
   }
   mArray.AppendElement(aRangeItem);
 }
 
 void
 RangeUpdater::DropRangeItem(RangeItem* aRangeItem)
 {
-  if (!aRangeItem) return;
+  if (!aRangeItem) {
+    return;
+  }
   mArray.RemoveElement(aRangeItem);
 }
 
 nsresult
 RangeUpdater::RegisterSelectionState(SelectionState& aSelState)
 {
-  uint32_t i, theCount = aSelState.mArray.Length();
-  if (theCount < 1) return NS_ERROR_FAILURE;
+  size_t theCount = aSelState.mArray.Length();
+  if (theCount < 1) {
+    return NS_ERROR_FAILURE;
+  }
 
-  for (i=0; i<theCount; i++)
-  {
+  for (size_t i = 0; i < theCount; i++) {
     RegisterRangeItem(aSelState.mArray[i]);
   }
 
   return NS_OK;
 }
 
 nsresult
 RangeUpdater::DropSelectionState(SelectionState& aSelState)
 {
-  uint32_t i, theCount = aSelState.mArray.Length();
-  if (theCount < 1) return NS_ERROR_FAILURE;
+  size_t theCount = aSelState.mArray.Length();
+  if (theCount < 1) {
+    return NS_ERROR_FAILURE;
+  }
 
-  for (i=0; i<theCount; i++)
-  {
+  for (size_t i = 0; i < theCount; i++) {
     DropRangeItem(aSelState.mArray[i]);
   }
 
   return NS_OK;
 }
 
 // gravity methods:
 
@@ -205,22 +218,22 @@ nsresult
 RangeUpdater::SelAdjCreateNode(nsINode* aParent,
                                int32_t aPosition)
 {
   if (mLock) {
     // lock set by Will/DidReplaceParent, etc...
     return NS_OK;
   }
   NS_ENSURE_TRUE(aParent, NS_ERROR_NULL_POINTER);
-  uint32_t count = mArray.Length();
+  size_t count = mArray.Length();
   if (!count) {
     return NS_OK;
   }
 
-  for (uint32_t i = 0; i < count; i++) {
+  for (size_t i = 0; i < count; i++) {
     RangeItem* item = mArray[i];
     NS_ENSURE_TRUE(item, NS_ERROR_NULL_POINTER);
 
     if (item->startNode == aParent && item->startOffset > aPosition) {
       item->startOffset++;
     }
     if (item->endNode == aParent && item->endOffset > aPosition) {
       item->endOffset++;
@@ -254,26 +267,26 @@ RangeUpdater::SelAdjInsertNode(nsIDOMNod
 void
 RangeUpdater::SelAdjDeleteNode(nsINode* aNode)
 {
   if (mLock) {
     // lock set by Will/DidReplaceParent, etc...
     return;
   }
   MOZ_ASSERT(aNode);
-  uint32_t count = mArray.Length();
+  size_t count = mArray.Length();
   if (!count) {
     return;
   }
 
   nsCOMPtr<nsINode> parent = aNode->GetParentNode();
   int32_t offset = parent ? parent->IndexOf(aNode) : -1;
 
   // check for range endpoints that are after aNode and in the same parent
-  for (uint32_t i = 0; i < count; i++) {
+  for (size_t i = 0; i < count; i++) {
     RangeItem* item = mArray[i];
     MOZ_ASSERT(item);
 
     if (item->startNode == parent && item->startOffset > offset) {
       item->startOffset--;
     }
     if (item->endNode == parent && item->endOffset > offset) {
       item->endOffset--;
@@ -294,56 +307,55 @@ RangeUpdater::SelAdjDeleteNode(nsINode* 
     if (EditorUtils::IsDescendantOf(item->startNode, aNode)) {
       oldStart = item->startNode;  // save for efficiency hack below.
       item->startNode   = parent;
       item->startOffset = offset;
     }
 
     // avoid having to call IsDescendantOf() for common case of range startnode == range endnode.
     if (item->endNode == oldStart ||
-        EditorUtils::IsDescendantOf(item->endNode, aNode))
-    {
+        EditorUtils::IsDescendantOf(item->endNode, aNode)) {
       item->endNode   = parent;
       item->endOffset = offset;
     }
   }
 }
 
 void
 RangeUpdater::SelAdjDeleteNode(nsIDOMNode* aNode)
 {
   nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
-  NS_ENSURE_TRUE(node, );
+  NS_ENSURE_TRUE_VOID(node);
   return SelAdjDeleteNode(node);
 }
 
 nsresult
 RangeUpdater::SelAdjSplitNode(nsIContent& aOldRightNode,
                               int32_t aOffset,
                               nsIContent* aNewLeftNode)
 {
   if (mLock) {
     // lock set by Will/DidReplaceParent, etc...
     return NS_OK;
   }
   NS_ENSURE_TRUE(aNewLeftNode, NS_ERROR_NULL_POINTER);
-  uint32_t count = mArray.Length();
+  size_t count = mArray.Length();
   if (!count) {
     return NS_OK;
   }
 
   nsCOMPtr<nsINode> parent = aOldRightNode.GetParentNode();
   int32_t offset = parent ? parent->IndexOf(&aOldRightNode) : -1;
 
   // first part is same as inserting aNewLeftnode
   nsresult result = SelAdjInsertNode(parent, offset - 1);
   NS_ENSURE_SUCCESS(result, result);
 
   // next step is to check for range enpoints inside aOldRightNode
-  for (uint32_t i = 0; i < count; i++) {
+  for (size_t i = 0; i < count; i++) {
     RangeItem* item = mArray[i];
     NS_ENSURE_TRUE(item, NS_ERROR_NULL_POINTER);
 
     if (item->startNode == &aOldRightNode) {
       if (item->startOffset > aOffset) {
         item->startOffset -= aOffset;
       } else {
         item->startNode = aNewLeftNode;
@@ -366,22 +378,22 @@ RangeUpdater::SelAdjJoinNodes(nsINode& a
                               nsINode& aParent,
                               int32_t aOffset,
                               int32_t aOldLeftNodeLength)
 {
   if (mLock) {
     // lock set by Will/DidReplaceParent, etc...
     return NS_OK;
   }
-  uint32_t count = mArray.Length();
+  size_t count = mArray.Length();
   if (!count) {
     return NS_OK;
   }
 
-  for (uint32_t i = 0; i < count; i++) {
+  for (size_t i = 0; i < count; i++) {
     RangeItem* item = mArray[i];
     NS_ENSURE_TRUE(item, NS_ERROR_NULL_POINTER);
 
     if (item->startNode == &aParent) {
       // adjust start point in aParent
       if (item->startOffset > aOffset) {
         item->startOffset--;
       } else if (item->startOffset == aOffset) {
@@ -423,23 +435,23 @@ RangeUpdater::SelAdjInsertText(Text& aTe
                                int32_t aOffset,
                                const nsAString& aString)
 {
   if (mLock) {
     // lock set by Will/DidReplaceParent, etc...
     return;
   }
 
-  uint32_t count = mArray.Length();
+  size_t count = mArray.Length();
   if (!count) {
     return;
   }
 
-  uint32_t len = aString.Length();
-  for (uint32_t i = 0; i < count; i++) {
+  size_t len = aString.Length();
+  for (size_t i = 0; i < count; i++) {
     RangeItem* item = mArray[i];
     MOZ_ASSERT(item);
 
     if (item->startNode == &aTextNode && item->startOffset > aOffset) {
       item->startOffset += len;
     }
     if (item->endNode == &aTextNode && item->endOffset > aOffset) {
       item->endOffset += len;
@@ -453,23 +465,23 @@ RangeUpdater::SelAdjDeleteText(nsIConten
                                int32_t aOffset,
                                int32_t aLength)
 {
   if (mLock) {
     // lock set by Will/DidReplaceParent, etc...
     return NS_OK;
   }
 
-  uint32_t count = mArray.Length();
+  size_t count = mArray.Length();
   if (!count) {
     return NS_OK;
   }
   NS_ENSURE_TRUE(aTextNode, NS_ERROR_NULL_POINTER);
 
-  for (uint32_t i = 0; i < count; i++) {
+  for (size_t i = 0; i < count; i++) {
     RangeItem* item = mArray[i];
     NS_ENSURE_TRUE(item, NS_ERROR_NULL_POINTER);
 
     if (item->startNode == aTextNode && item->startOffset > aOffset) {
       item->startOffset -= aLength;
       if (item->startOffset < 0) {
         item->startOffset = 0;
       }
@@ -491,72 +503,76 @@ RangeUpdater::SelAdjDeleteText(nsIDOMCha
 {
   nsCOMPtr<nsIContent> textNode = do_QueryInterface(aTextNode);
   return SelAdjDeleteText(textNode, aOffset, aLength);
 }
 
 nsresult
 RangeUpdater::WillReplaceContainer()
 {
-  if (mLock) return NS_ERROR_UNEXPECTED;
+  if (mLock) {
+    return NS_ERROR_UNEXPECTED;
+  }
   mLock = true;
   return NS_OK;
 }
 
 nsresult
 RangeUpdater::DidReplaceContainer(Element* aOriginalNode,
                                   Element* aNewNode)
 {
   NS_ENSURE_TRUE(mLock, NS_ERROR_UNEXPECTED);
   mLock = false;
 
   NS_ENSURE_TRUE(aOriginalNode && aNewNode, NS_ERROR_NULL_POINTER);
-  uint32_t count = mArray.Length();
+  size_t count = mArray.Length();
   if (!count) {
     return NS_OK;
   }
 
-  for (uint32_t i = 0; i < count; i++) {
+  for (size_t i = 0; i < count; i++) {
     RangeItem* item = mArray[i];
     NS_ENSURE_TRUE(item, NS_ERROR_NULL_POINTER);
 
     if (item->startNode == aOriginalNode) {
       item->startNode = aNewNode;
     }
     if (item->endNode == aOriginalNode) {
       item->endNode = aNewNode;
     }
   }
   return NS_OK;
 }
 
 nsresult
 RangeUpdater::WillRemoveContainer()
 {
-  if (mLock) return NS_ERROR_UNEXPECTED;
+  if (mLock) {
+    return NS_ERROR_UNEXPECTED;
+  }
   mLock = true;
   return NS_OK;
 }
 
 nsresult
 RangeUpdater::DidRemoveContainer(nsINode* aNode,
                                  nsINode* aParent,
                                  int32_t aOffset,
                                  uint32_t aNodeOrigLen)
 {
   NS_ENSURE_TRUE(mLock, NS_ERROR_UNEXPECTED);
   mLock = false;
 
   NS_ENSURE_TRUE(aNode && aParent, NS_ERROR_NULL_POINTER);
-  uint32_t count = mArray.Length();
+  size_t count = mArray.Length();
   if (!count) {
     return NS_OK;
   }
 
-  for (uint32_t i = 0; i < count; i++) {
+  for (size_t i = 0; i < count; i++) {
     RangeItem* item = mArray[i];
     NS_ENSURE_TRUE(item, NS_ERROR_NULL_POINTER);
 
     if (item->startNode == aNode) {
       item->startNode = aParent;
       item->startOffset += aOffset;
     } else if (item->startNode == aParent && item->startOffset > aOffset) {
       item->startOffset += (int32_t)aNodeOrigLen - 1;
@@ -581,17 +597,19 @@ RangeUpdater::DidRemoveContainer(nsIDOMN
   nsCOMPtr<nsINode> node = do_QueryInterface(aNode);
   nsCOMPtr<nsINode> parent = do_QueryInterface(aParent);
   return DidRemoveContainer(node, parent, aOffset, aNodeOrigLen);
 }
 
 nsresult
 RangeUpdater::WillInsertContainer()
 {
-  if (mLock) return NS_ERROR_UNEXPECTED;
+  if (mLock) {
+    return NS_ERROR_UNEXPECTED;
+  }
   mLock = true;
   return NS_OK;
 }
 
 nsresult
 RangeUpdater::DidInsertContainer()
 {
   NS_ENSURE_TRUE(mLock, NS_ERROR_UNEXPECTED);
@@ -609,17 +627,17 @@ void
 RangeUpdater::DidMoveNode(nsINode* aOldParent, int32_t aOldOffset,
                             nsINode* aNewParent, int32_t aNewOffset)
 {
   MOZ_ASSERT(aOldParent);
   MOZ_ASSERT(aNewParent);
   NS_ENSURE_TRUE_VOID(mLock);
   mLock = false;
 
-  for (uint32_t i = 0, count = mArray.Length(); i < count; ++i) {
+  for (size_t i = 0, count = mArray.Length(); i < count; ++i) {
     RangeItem* item = mArray[i];
     NS_ENSURE_TRUE_VOID(item);
 
     // like a delete in aOldParent
     if (item->startNode == aOldParent && item->startOffset > aOldOffset) {
       item->startOffset--;
     }
     if (item->endNode == aOldParent && item->endOffset > aOldOffset) {
--- a/editor/libeditor/TextEditRules.cpp
+++ b/editor/libeditor/TextEditRules.cpp
@@ -90,18 +90,19 @@ TextEditRules::InitFields()
   mLastLength = 0;
 }
 
 TextEditRules::~TextEditRules()
 {
    // do NOT delete mTextEditor here.  We do not hold a ref count to
    // mTextEditor.  mTextEditor owns our lifespan.
 
-  if (mTimer)
+  if (mTimer) {
     mTimer->Cancel();
+  }
 }
 
 NS_IMPL_CYCLE_COLLECTION(TextEditRules, mBogusNode, mCachedSelectionNode)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TextEditRules)
   NS_INTERFACE_MAP_ENTRY(nsIEditRules)
   NS_INTERFACE_MAP_ENTRY(nsITimerCallback)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIEditRules)
@@ -134,18 +135,17 @@ TextEditRules::Init(TextEditor* aTextEdi
   int32_t rangeCount;
   rv = selection->GetRangeCount(&rangeCount);
   NS_ENSURE_SUCCESS(rv, rv);
   if (!rangeCount) {
     rv = mTextEditor->EndOfDocument();
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  if (IsPlaintextEditor())
-  {
+  if (IsPlaintextEditor()) {
     // ensure trailing br node
     rv = CreateTrailingBRIfNeeded();
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   mDeleteBidiImmediately =
     Preferences::GetBool("bidi.edit.delete_immediately", false);
 
@@ -159,33 +159,34 @@ TextEditRules::SetInitialValue(const nsA
     mPasswordText = aValue;
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TextEditRules::DetachEditor()
 {
-  if (mTimer)
+  if (mTimer) {
     mTimer->Cancel();
-
+  }
   mTextEditor = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TextEditRules::BeforeEdit(EditAction action,
                           nsIEditor::EDirection aDirection)
 {
-  if (mLockRulesSniffing) return NS_OK;
+  if (mLockRulesSniffing) {
+    return NS_OK;
+  }
 
   AutoLockRulesSniffing lockIt(this);
   mDidExplicitlySetInterline = false;
-  if (!mActionNesting)
-  {
+  if (!mActionNesting) {
     // let rules remember the top level action
     mTheAction = action;
   }
   mActionNesting++;
 
   // get the selection and cache the position before editing
   NS_ENSURE_STATE(mTextEditor);
   RefPtr<Selection> selection = mTextEditor->GetSelection();
@@ -196,23 +197,24 @@ TextEditRules::BeforeEdit(EditAction act
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TextEditRules::AfterEdit(EditAction action,
                          nsIEditor::EDirection aDirection)
 {
-  if (mLockRulesSniffing) return NS_OK;
+  if (mLockRulesSniffing) {
+    return NS_OK;
+  }
 
   AutoLockRulesSniffing lockIt(this);
 
   NS_PRECONDITION(mActionNesting>0, "bad action nesting!");
-  if (!--mActionNesting)
-  {
+  if (!--mActionNesting) {
     NS_ENSURE_STATE(mTextEditor);
     RefPtr<Selection> selection = mTextEditor->GetSelection();
     NS_ENSURE_STATE(selection);
 
     NS_ENSURE_STATE(mTextEditor);
     nsresult rv =
       mTextEditor->HandleInlineSpellCheck(action, selection,
                                           mCachedSelectionNode,
@@ -298,18 +300,17 @@ TextEditRules::DidDoAction(Selection* aS
   // Note that this won't prevent explicit selection setting from working.
   AutoTransactionsConserveSelection dontSpazMySelection(mTextEditor);
 
   NS_ENSURE_TRUE(aSelection && aInfo, NS_ERROR_NULL_POINTER);
 
   // my kingdom for dynamic cast
   TextRulesInfo* info = static_cast<TextRulesInfo*>(aInfo);
 
-  switch (info->action)
-  {
+  switch (info->action) {
     case EditAction::insertBreak:
       return DidInsertBreak(aSelection, aResult);
     case EditAction::insertText:
     case EditAction::insertIMEText:
       return DidInsertText(aSelection, aResult);
     case EditAction::deleteSelection:
       return DidDeleteSelection(aSelection, info->collapsedAction, aResult);
     case EditAction::undo:
@@ -366,24 +367,24 @@ TextEditRules::DidInsert(Selection* aSel
 }
 
 nsresult
 TextEditRules::WillInsertBreak(Selection* aSelection,
                                bool* aCancel,
                                bool* aHandled,
                                int32_t aMaxLength)
 {
-  if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
   CANCEL_OPERATION_IF_READONLY_OR_DISABLED
   *aHandled = false;
   if (IsSingleLineEditor()) {
     *aCancel = true;
-  }
-  else
-  {
+  } else {
     // handle docs with a max length
     // NOTE, this function copies inString into outString for us.
     NS_NAMED_LITERAL_STRING(inString, "\n");
     nsAutoString outString;
     bool didTruncate;
     nsresult rv = TruncateInsertionIfNeeded(aSelection, &inString, &outString,
                                             aMaxLength, &didTruncate);
     NS_ENSURE_SUCCESS(rv, rv);
@@ -393,28 +394,26 @@ TextEditRules::WillInsertBreak(Selection
     }
 
     *aCancel = false;
 
     // if the selection isn't collapsed, delete it.
     bool bCollapsed;
     rv = aSelection->GetIsCollapsed(&bCollapsed);
     NS_ENSURE_SUCCESS(rv, rv);
-    if (!bCollapsed)
-    {
+    if (!bCollapsed) {
       NS_ENSURE_STATE(mTextEditor);
       rv = mTextEditor->DeleteSelection(nsIEditor::eNone, nsIEditor::eStrip);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     WillInsert(*aSelection, aCancel);
     // initialize out param
     // we want to ignore result of WillInsert()
     *aCancel = false;
-
   }
   return NS_OK;
 }
 
 nsresult
 TextEditRules::DidInsertBreak(Selection* aSelection,
                               nsresult aResult)
 {
@@ -445,34 +444,39 @@ TextEditRules::CollapseSelectionToTraili
   int32_t selOffset;
   nsCOMPtr<nsIDOMNode> selNode;
   nsresult rv =
     mTextEditor->GetStartNodeAndOffset(aSelection,
                                        getter_AddRefs(selNode), &selOffset);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIDOMText> nodeAsText = do_QueryInterface(selNode);
-  if (!nodeAsText) return NS_OK; // nothing to do if we're not at a text node
+  if (!nodeAsText) {
+    return NS_OK; // Nothing to do if we're not at a text node.
+  }
 
   uint32_t length;
   rv = nodeAsText->GetLength(&length);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // nothing to do if we're not at the end of the text node
-  if (selOffset != int32_t(length))
+  if (selOffset != int32_t(length)) {
     return NS_OK;
+  }
 
   int32_t parentOffset;
   nsCOMPtr<nsIDOMNode> parentNode =
     EditorBase::GetNodeLocation(selNode, &parentOffset);
 
   NS_ENSURE_STATE(mTextEditor);
   nsCOMPtr<nsIDOMNode> root = do_QueryInterface(mTextEditor->GetRoot());
   NS_ENSURE_TRUE(root, NS_ERROR_NULL_POINTER);
-  if (parentNode != root) return NS_OK;
+  if (parentNode != root) {
+    return NS_OK;
+  }
 
   nsCOMPtr<nsIDOMNode> nextNode = mTextEditor->GetChildAt(parentNode,
                                                           parentOffset + 1);
   if (nextNode && TextEditUtils::IsMozBR(nextNode)) {
     rv = aSelection->Collapse(parentNode, parentOffset + 1);
     NS_ENSURE_SUCCESS(rv, rv);
   }
   return NS_OK;
@@ -521,88 +525,89 @@ void
 TextEditRules::HandleNewLines(nsString& aString,
                               int32_t aNewlineHandling)
 {
   if (aNewlineHandling < 0) {
     int32_t caretStyle;
     TextEditor::GetDefaultEditorPrefs(aNewlineHandling, caretStyle);
   }
 
-  switch(aNewlineHandling)
-  {
-  case nsIPlaintextEditor::eNewlinesReplaceWithSpaces:
-    // Strip trailing newlines first so we don't wind up with trailing spaces
-    aString.Trim(CRLF, false, true);
-    aString.ReplaceChar(CRLF, ' ');
-    break;
-  case nsIPlaintextEditor::eNewlinesStrip:
-    aString.StripChars(CRLF);
-    break;
-  case nsIPlaintextEditor::eNewlinesPasteToFirst:
-  default:
-    {
+  switch(aNewlineHandling) {
+    case nsIPlaintextEditor::eNewlinesReplaceWithSpaces:
+      // Strip trailing newlines first so we don't wind up with trailing spaces
+      aString.Trim(CRLF, false, true);
+      aString.ReplaceChar(CRLF, ' ');
+      break;
+    case nsIPlaintextEditor::eNewlinesStrip:
+      aString.StripChars(CRLF);
+      break;
+    case nsIPlaintextEditor::eNewlinesPasteToFirst:
+    default: {
       int32_t firstCRLF = aString.FindCharInSet(CRLF);
 
       // we get first *non-empty* line.
       int32_t offset = 0;
-      while (firstCRLF == offset)
-      {
+      while (firstCRLF == offset) {
         offset++;
         firstCRLF = aString.FindCharInSet(CRLF, offset);
       }
-      if (firstCRLF > 0)
+      if (firstCRLF > 0) {
         aString.Truncate(firstCRLF);
-      if (offset > 0)
+      }
+      if (offset > 0) {
         aString.Cut(0, offset);
+      }
+      break;
     }
-    break;
-  case nsIPlaintextEditor::eNewlinesReplaceWithCommas:
-    aString.Trim(CRLF, true, true);
-    aString.ReplaceChar(CRLF, ',');
-    break;
-  case nsIPlaintextEditor::eNewlinesStripSurroundingWhitespace:
-    {
-      nsString result;
+    case nsIPlaintextEditor::eNewlinesReplaceWithCommas:
+      aString.Trim(CRLF, true, true);
+      aString.ReplaceChar(CRLF, ',');
+      break;
+    case nsIPlaintextEditor::eNewlinesStripSurroundingWhitespace: {
+      nsAutoString result;
       uint32_t offset = 0;
-      while (offset < aString.Length())
-      {
+      while (offset < aString.Length()) {
         int32_t nextCRLF = aString.FindCharInSet(CRLF, offset);
         if (nextCRLF < 0) {
           result.Append(nsDependentSubstring(aString, offset));
           break;
         }
         uint32_t wsBegin = nextCRLF;
         // look backwards for the first non-whitespace char
-        while (wsBegin > offset && NS_IS_SPACE(aString[wsBegin - 1]))
+        while (wsBegin > offset && NS_IS_SPACE(aString[wsBegin - 1])) {
           --wsBegin;
+        }
         result.Append(nsDependentSubstring(aString, offset, wsBegin - offset));
         offset = nextCRLF + 1;
-        while (offset < aString.Length() && NS_IS_SPACE(aString[offset]))
+        while (offset < aString.Length() && NS_IS_SPACE(aString[offset])) {
           ++offset;
+        }
       }
       aString = result;
+      break;
     }
-    break;
-  case nsIPlaintextEditor::eNewlinesPasteIntact:
-    // even if we're pasting newlines, don't paste leading/trailing ones
-    aString.Trim(CRLF, true, true);
-    break;
+    case nsIPlaintextEditor::eNewlinesPasteIntact:
+      // even if we're pasting newlines, don't paste leading/trailing ones
+      aString.Trim(CRLF, true, true);
+      break;
   }
 }
 
 nsresult
 TextEditRules::WillInsertText(EditAction aAction,
                               Selection* aSelection,
                               bool* aCancel,
                               bool* aHandled,
                               const nsAString* inString,
                               nsAString* outString,
                               int32_t aMaxLength)
 {
-  if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   if (inString->IsEmpty() && aAction != EditAction::insertIMEText) {
     // HACK: this is a fix for bug 19395
     // I can't outlaw all empty insertions
     // because IME transaction depend on them
     // There is more work to do to make the
     // world safe for IME.
     *aCancel = true;
@@ -638,81 +643,71 @@ TextEditRules::WillInsertText(EditAction
                                               mTextEditor->GetRoot(),
                                               start, end);
   }
 
   // if the selection isn't collapsed, delete it.
   bool bCollapsed;
   rv = aSelection->GetIsCollapsed(&bCollapsed);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (!bCollapsed)
-  {
+  if (!bCollapsed) {
     NS_ENSURE_STATE(mTextEditor);
     rv = mTextEditor->DeleteSelection(nsIEditor::eNone, nsIEditor::eStrip);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   WillInsert(*aSelection, aCancel);
   // initialize out param
   // we want to ignore result of WillInsert()
   *aCancel = false;
 
   // handle password field data
   // this has the side effect of changing all the characters in aOutString
   // to the replacement character
-  if (IsPasswordEditor())
-  {
-    if (aAction == EditAction::insertIMEText) {
-      RemoveIMETextFromPWBuf(start, outString);
-    }
+  if (IsPasswordEditor() &&
+      aAction == EditAction::insertIMEText) {
+    RemoveIMETextFromPWBuf(start, outString);
   }
 
   // People have lots of different ideas about what text fields
   // should do with multiline pastes.  See bugs 21032, 23485, 23485, 50935.
   // The six possible options are:
   // 0. paste newlines intact
   // 1. paste up to the first newline (default)
   // 2. replace newlines with spaces
   // 3. strip newlines
   // 4. replace with commas
   // 5. strip newlines and surrounding whitespace
   // So find out what we're expected to do:
-  if (IsSingleLineEditor())
-  {
+  if (IsSingleLineEditor()) {
     nsAutoString tString(*outString);
 
     NS_ENSURE_STATE(mTextEditor);
     HandleNewLines(tString, mTextEditor->mNewlineHandling);
 
     outString->Assign(tString);
   }
 
-  if (IsPasswordEditor())
-  {
+  if (IsPasswordEditor()) {
     // manage the password buffer
     mPasswordText.Insert(*outString, start);
 
     if (LookAndFeel::GetEchoPassword() && !DontEchoPassword()) {
       HideLastPWInput();
       mLastStart = start;
       mLastLength = outString->Length();
-      if (mTimer)
-      {
+      if (mTimer) {
         mTimer->Cancel();
-      }
-      else
-      {
+      } else {
         mTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
         NS_ENSURE_SUCCESS(rv, rv);
       }
       mTimer->InitWithCallback(this, LookAndFeel::GetPasswordMaskDelay(),
                                nsITimer::TYPE_ONE_SHOT);
-    }
-    else
-    {
+    } else {
       FillBufWithPWChars(outString, outString->Length());
     }
   }
 
   // get the (collapsed) selection location
   NS_ENSURE_STATE(aSelection->GetRangeAt(0));
   nsCOMPtr<nsINode> selNode = aSelection->GetRangeAt(0)->GetStartParent();
   int32_t selOffset = aSelection->GetRangeAt(0)->StartOffset();
@@ -752,18 +747,17 @@ TextEditRules::WillInsertText(EditAction
     // don't spaz my selection in subtransactions
     NS_ENSURE_STATE(mTextEditor);
     AutoTransactionsConserveSelection dontSpazMySelection(mTextEditor);
 
     rv = mTextEditor->InsertTextImpl(*outString, address_of(curNode),
                                      &curOffset, doc);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (curNode)
-    {
+    if (curNode) {
       // Make the caret attach to the inserted text, unless this text ends with a LF,
       // in which case make the caret attach to the next line.
       bool endsWithLF =
         !outString->IsEmpty() && outString->Last() == nsCRT::LF;
       aSelection->SetInterlinePosition(endsWithLF);
 
       aSelection->Collapse(curNode, curOffset);
     }
@@ -774,25 +768,24 @@ TextEditRules::WillInsertText(EditAction
 
 nsresult
 TextEditRules::DidInsertText(Selection* aSelection,
                              nsresult aResult)
 {
   return DidInsert(aSelection, aResult);
 }
 
-
-
 nsresult
 TextEditRules::WillSetTextProperty(Selection* aSelection,
                                    bool* aCancel,
                                    bool* aHandled)
 {
-  if (!aSelection || !aCancel || !aHandled)
-    { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   // XXX: should probably return a success value other than NS_OK that means "not allowed"
   if (IsPlaintextEditor()) {
     *aCancel = true;
   }
   return NS_OK;
 }
 
@@ -803,18 +796,19 @@ TextEditRules::DidSetTextProperty(Select
   return NS_OK;
 }
 
 nsresult
 TextEditRules::WillRemoveTextProperty(Selection* aSelection,
                                       bool* aCancel,
                                       bool* aHandled)
 {
-  if (!aSelection || !aCancel || !aHandled)
-    { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   // XXX: should probably return a success value other than NS_OK that means "not allowed"
   if (IsPlaintextEditor()) {
     *aCancel = true;
   }
   return NS_OK;
 }
 
@@ -826,17 +820,19 @@ TextEditRules::DidRemoveTextProperty(Sel
 }
 
 nsresult
 TextEditRules::WillDeleteSelection(Selection* aSelection,
                                    nsIEditor::EDirection aCollapsedAction,
                                    bool* aCancel,
                                    bool* aHandled)
 {
-  if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
   CANCEL_OPERATION_IF_READONLY_OR_DISABLED
 
   // initialize out param
   *aCancel = false;
   *aHandled = false;
 
   // if there is only bogus content, cancel the operation
   if (mBogusNode) {
@@ -849,76 +845,78 @@ TextEditRules::WillDeleteSelection(Selec
   // event to the user, so we hide selection changes. However, we still
   // want to send a single selectionchange event to the document, so we
   // batch the selectionchange events, such that a single event fires after
   // the AutoHideSelectionChanges destructor has been run.
   SelectionBatcher selectionBatcher(aSelection);
   AutoHideSelectionChanges hideSelection(aSelection);
   nsAutoScriptBlocker scriptBlocker;
 
-  if (IsPasswordEditor())
-  {
+  if (IsPasswordEditor()) {
     NS_ENSURE_STATE(mTextEditor);
     nsresult rv =
       mTextEditor->ExtendSelectionForDelete(aSelection, &aCollapsedAction);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // manage the password buffer
     int32_t start, end;
     nsContentUtils::GetSelectionInTextControl(aSelection,
                                               mTextEditor->GetRoot(),
                                               start, end);
 
     if (LookAndFeel::GetEchoPassword()) {
       HideLastPWInput();
       mLastStart = start;
       mLastLength = 0;
-      if (mTimer)
-      {
+      if (mTimer) {
         mTimer->Cancel();
       }
     }
 
-    if (end == start)
-    { // collapsed selection
-      if (nsIEditor::ePrevious==aCollapsedAction && 0<start) { // del back
+    // Collapsed selection.
+    if (end == start) {
+      // Deleting back.
+      if (nsIEditor::ePrevious == aCollapsedAction && 0<start) {
         mPasswordText.Cut(start-1, 1);
       }
-      else if (nsIEditor::eNext==aCollapsedAction) {      // del forward
+      // Deleting forward.
+      else if (nsIEditor::eNext == aCollapsedAction) {
         mPasswordText.Cut(start, 1);
       }
-      // otherwise nothing to do for this collapsed selection
+      // Otherwise nothing to do for this collapsed selection.
     }
-    else {  // extended selection
+    // Extended selection.
+    else {
       mPasswordText.Cut(start, end-start);
     }
-  }
-  else
-  {
+  } else {
     nsCOMPtr<nsIDOMNode> startNode;
     int32_t startOffset;
     NS_ENSURE_STATE(mTextEditor);
     nsresult rv =
       mTextEditor->GetStartNodeAndOffset(aSelection, getter_AddRefs(startNode),
                                          &startOffset);
     NS_ENSURE_SUCCESS(rv, rv);
     NS_ENSURE_TRUE(startNode, NS_ERROR_FAILURE);
 
     bool bCollapsed;
     rv = aSelection->GetIsCollapsed(&bCollapsed);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (!bCollapsed)
+    if (!bCollapsed) {
       return NS_OK;
+    }
 
     // Test for distance between caret and text that will be deleted
     rv = CheckBidiLevelForDeletion(aSelection, startNode, startOffset,
                                    aCollapsedAction, aCancel);
     NS_ENSURE_SUCCESS(rv, rv);
-    if (*aCancel) return NS_OK;
+    if (*aCancel) {
+      return NS_OK;
+    }
 
     NS_ENSURE_STATE(mTextEditor);
     rv = mTextEditor->ExtendSelectionForDelete(aSelection, &aCollapsedAction);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   NS_ENSURE_STATE(mTextEditor);
   nsresult rv =
@@ -947,18 +945,17 @@ TextEditRules::DidDeleteSelection(Select
   // delete empty text nodes at selection
   if (mTextEditor->IsTextNode(startNode)) {
     nsCOMPtr<nsIDOMText> textNode = do_QueryInterface(startNode);
     uint32_t strLength;
     rv = textNode->GetLength(&strLength);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // are we in an empty text node?
-    if (!strLength)
-    {
+    if (!strLength) {
       rv = mTextEditor->DeleteNode(startNode);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
   if (mDidExplicitlySetInterline) {
     return NS_OK;
   }
   // We prevent the caret from sticking on the left of prior BR
@@ -966,17 +963,19 @@ TextEditRules::DidDeleteSelection(Select
   return aSelection->SetInterlinePosition(true);
 }
 
 nsresult
 TextEditRules::WillUndo(Selection* aSelection,
                         bool* aCancel,
                         bool* aHandled)
 {
-  if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
   CANCEL_OPERATION_IF_READONLY_OR_DISABLED
   // initialize out param
   *aCancel = false;
   *aHandled = false;
   return NS_OK;
 }
 
 /**
@@ -1006,17 +1005,19 @@ TextEditRules::DidUndo(Selection* aSelec
   return aResult;
 }
 
 nsresult
 TextEditRules::WillRedo(Selection* aSelection,
                         bool* aCancel,
                         bool* aHandled)
 {
-  if (!aSelection || !aCancel || !aHandled) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
   CANCEL_OPERATION_IF_READONLY_OR_DISABLED
   // initialize out param
   *aCancel = false;
   *aHandled = false;
   return NS_OK;
 }
 
 nsresult
@@ -1064,34 +1065,33 @@ TextEditRules::DidRedo(Selection* aSelec
 nsresult
 TextEditRules::WillOutputText(Selection* aSelection,
                               const nsAString* aOutputFormat,
                               nsAString* aOutString,
                               bool* aCancel,
                               bool* aHandled)
 {
   // null selection ok
-  if (!aOutString || !aOutputFormat || !aCancel || !aHandled)
-    { return NS_ERROR_NULL_POINTER; }
+  if (!aOutString || !aOutputFormat || !aCancel || !aHandled) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   // initialize out param
   *aCancel = false;
   *aHandled = false;
 
   nsAutoString outputFormat(*aOutputFormat);
   ToLowerCase(outputFormat);
-  if (outputFormat.EqualsLiteral("text/plain"))
-  { // only use these rules for plain text output
-    if (IsPasswordEditor())
-    {
+  if (outputFormat.EqualsLiteral("text/plain")) {
+    // Only use these rules for plain text output.
+    if (IsPasswordEditor()) {
       *aOutString = mPasswordText;
       *aHandled = true;
-    }
-    else if (mBogusNode)
-    { // this means there's no content, so output null string
+    } else if (mBogusNode) {
+      // This means there's no content, so output null string.
       aOutString->Truncate();
       *aHandled = true;
     }
   }
   return NS_OK;
 }
 
 nsresult
@@ -1100,27 +1100,30 @@ TextEditRules::DidOutputText(Selection* 
 {
   return NS_OK;
 }
 
 nsresult
 TextEditRules::RemoveRedundantTrailingBR()
 {
   // If the bogus node exists, we have no work to do
-  if (mBogusNode)
+  if (mBogusNode) {
     return NS_OK;
+  }
 
   // Likewise, nothing to be done if we could never have inserted a trailing br
-  if (IsSingleLineEditor())
+  if (IsSingleLineEditor()) {
     return NS_OK;
+  }
 
   NS_ENSURE_STATE(mTextEditor);
   RefPtr<dom::Element> body = mTextEditor->GetRoot();
-  if (!body)
+  if (!body) {
     return NS_ERROR_NULL_POINTER;
+  }
 
   uint32_t childCount = body->GetChildCount();
   if (childCount > 1) {
     // The trailing br is redundant if it is the only remaining child node
     return NS_OK;
   }
 
   RefPtr<nsIContent> child = body->GetFirstChild();
@@ -1247,17 +1250,19 @@ TextEditRules::CreateBogusNodeIfNeeded(S
 
 nsresult
 TextEditRules::TruncateInsertionIfNeeded(Selection* aSelection,
                                          const nsAString* aInString,
                                          nsAString* aOutString,
                                          int32_t aMaxLength,
                                          bool* aTruncated)
 {
-  if (!aSelection || !aInString || !aOutString) {return NS_ERROR_NULL_POINTER;}
+  if (!aSelection || !aInString || !aOutString) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   if (!aOutString->Assign(*aInString, mozilla::fallible)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
   if (aTruncated) {
     *aTruncated = false;
   }
 
@@ -1287,27 +1292,24 @@ TextEditRules::TruncateInsertionIfNeeded
                                               mTextEditor->GetRoot(),
                                               start, end);
 
     TextComposition* composition = mTextEditor->GetComposition();
     int32_t oldCompStrLength = composition ? composition->String().Length() : 0;
 
     const int32_t selectionLength = end - start;
     const int32_t resultingDocLength = docLength - selectionLength - oldCompStrLength;
-    if (resultingDocLength >= aMaxLength)
-    {
+    if (resultingDocLength >= aMaxLength) {
       // This call is guaranteed to reduce the capacity of the string, so it
       // cannot cause an OOM.
       aOutString->Truncate();
       if (aTruncated) {
         *aTruncated = true;
       }
-    }
-    else
-    {
+    } else {
       int32_t oldLength = aOutString->Length();
       if (oldLength + resultingDocLength > aMaxLength) {
         int32_t newLength = aMaxLength - resultingDocLength;
         MOZ_ASSERT(newLength > 0);
         char16_t newLastChar = aOutString->CharAt(newLength - 1);
         char16_t removingFirstChar = aOutString->CharAt(newLength);
         // Don't separate the string between a surrogate pair.
         if (NS_IS_HIGH_SURROGATE(newLastChar) &&
@@ -1338,18 +1340,17 @@ void
 TextEditRules::RemoveIMETextFromPWBuf(int32_t& aStart,
                                       nsAString* aIMEString)
 {
   MOZ_ASSERT(aIMEString);
 
   // initialize PasswordIME
   if (mPasswordIMEText.IsEmpty()) {
     mPasswordIMEIndex = aStart;
-  }
-  else {
+  } else {
     // manage the password buffer
     mPasswordText.Cut(mPasswordIMEIndex, mPasswordIMEText.Length());
     aStart = mPasswordIMEIndex;
   }
 
   mPasswordIMEText.Assign(*aIMEString);
 }
 
@@ -1387,35 +1388,36 @@ TextEditRules::HideLastPWInput()
   nsCOMPtr<nsIDOMNode> selNode = GetTextNode(selection, mTextEditor);
   NS_ENSURE_TRUE(selNode, NS_OK);
 
   nsCOMPtr<nsIDOMCharacterData> nodeAsText(do_QueryInterface(selNode));
   NS_ENSURE_TRUE(nodeAsText, NS_OK);
 
   nodeAsText->ReplaceData(mLastStart, mLastLength, hiddenText);
   selection->Collapse(selNode, start);
-  if (start != end)
+  if (start != end) {
     selection->Extend(selNode, end);
+  }
   return NS_OK;
 }
 
 // static
 void
 TextEditRules::FillBufWithPWChars(nsAString* aOutString,
                                   int32_t aLength)
 {
   MOZ_ASSERT(aOutString);
 
   // change the output to the platform password character
   char16_t passwordChar = LookAndFeel::GetPasswordCharacter();
 
-  int32_t i;
   aOutString->Truncate();
-  for (i=0; i < aLength; i++)
+  for (int32_t i = 0; i < aLength; i++) {
     aOutString->Append(passwordChar);
+  }
 }
 
 /**
  * CreateMozBR() puts a BR node with moz attribute at {inParent, inOffset}.
  */
 nsresult
 TextEditRules::CreateMozBR(nsIDOMNode* inParent,
                            int32_t inOffset,
--- a/editor/libeditor/TextEditRulesBidi.cpp
+++ b/editor/libeditor/TextEditRulesBidi.cpp
@@ -35,18 +35,19 @@ TextEditRules::CheckBidiLevelForDeletion
   *aCancel = false;
 
   nsCOMPtr<nsIPresShell> shell = mTextEditor->GetPresShell();
   NS_ENSURE_TRUE(shell, NS_ERROR_NOT_INITIALIZED);
 
   nsPresContext *context = shell->GetPresContext();
   NS_ENSURE_TRUE(context, NS_ERROR_NULL_POINTER);
 
-  if (!context->BidiEnabled())
+  if (!context->BidiEnabled()) {
     return NS_OK;
+  }
 
   nsCOMPtr<nsIContent> content = do_QueryInterface(aSelNode);
   NS_ENSURE_TRUE(content, NS_ERROR_NULL_POINTER);
 
   nsBidiLevel levelBefore;
   nsBidiLevel levelAfter;
   RefPtr<nsFrameSelection> frameSelection =
     aSelection->AsSelection()->GetFrameSelection();
@@ -60,29 +61,27 @@ TextEditRules::CheckBidiLevelForDeletion
 
   nsBidiLevel currentCaretLevel = frameSelection->GetCaretBidiLevel();
 
   nsBidiLevel levelOfDeletion;
   levelOfDeletion =
     (nsIEditor::eNext==aAction || nsIEditor::eNextWord==aAction) ?
     levelAfter : levelBefore;
 
-  if (currentCaretLevel == levelOfDeletion)
-    ; // perform the deletion
-  else
-  {
-    if (mDeleteBidiImmediately || levelBefore == levelAfter)
-      ; // perform the deletion
-    else
-      *aCancel = true;
+  if (currentCaretLevel == levelOfDeletion) {
+    return NS_OK; // perform the deletion
+  }
 
-    // Set the bidi level of the caret to that of the
-    // character that will be (or would have been) deleted
-    frameSelection->SetCaretBidiLevel(levelOfDeletion);
+  if (!mDeleteBidiImmediately && levelBefore != levelAfter) {
+    *aCancel = true;
   }
+
+  // Set the bidi level of the caret to that of the
+  // character that will be (or would have been) deleted
+  frameSelection->SetCaretBidiLevel(levelOfDeletion);
   return NS_OK;
 }
 
 void
 TextEditRules::UndefineCaretBidiLevel(Selection* aSelection)
 {
   /**
    * After inserting text the caret Bidi level must be set to the level of the
--- a/editor/libeditor/TextEditor.cpp
+++ b/editor/libeditor/TextEditor.cpp
@@ -149,26 +149,27 @@ TextEditor::Init(nsIDOMDocument* aDoc,
 }
 
 static int32_t sNewlineHandlingPref = -1,
                sCaretStylePref = -1;
 
 static void
 EditorPrefsChangedCallback(const char* aPrefName, void *)
 {
-  if (nsCRT::strcmp(aPrefName, "editor.singleLine.pasteNewlines") == 0) {
+  if (!nsCRT::strcmp(aPrefName, "editor.singleLine.pasteNewlines")) {
     sNewlineHandlingPref =
       Preferences::GetInt("editor.singleLine.pasteNewlines",
                           nsIPlaintextEditor::eNewlinesPasteToFirst);
-  } else if (nsCRT::strcmp(aPrefName, "layout.selection.caret_style") == 0) {
+  } else if (!nsCRT::strcmp(aPrefName, "layout.selection.caret_style")) {
     sCaretStylePref = Preferences::GetInt("layout.selection.caret_style",
 #ifdef XP_WIN
                                                  1);
-    if (sCaretStylePref == 0)
+    if (!sCaretStylePref) {
       sCaretStylePref = 1;
+    }
 #else
                                                  0);
 #endif
   }
 }
 
 // static
 void
@@ -463,68 +464,56 @@ TextEditor::CreateBRImpl(nsCOMPtr<nsIDOM
   *outBRNode = nullptr;
 
   // we need to insert a br.  unfortunately, we may have to split a text node to do it.
   nsCOMPtr<nsIDOMNode> node = *aInOutParent;
   int32_t theOffset = *aInOutOffset;
   nsCOMPtr<nsIDOMCharacterData> nodeAsText = do_QueryInterface(node);
   NS_NAMED_LITERAL_STRING(brType, "br");
   nsCOMPtr<nsIDOMNode> brNode;
-  if (nodeAsText)
-  {
+  if (nodeAsText) {
     int32_t offset;
     uint32_t len;
     nodeAsText->GetLength(&len);
     nsCOMPtr<nsIDOMNode> tmp = GetNodeLocation(node, &offset);
     NS_ENSURE_TRUE(tmp, NS_ERROR_FAILURE);
-    if (!theOffset)
-    {
+    if (!theOffset) {
       // we are already set to go
-    }
-    else if (theOffset == (int32_t)len)
-    {
+    } else if (theOffset == (int32_t)len) {
       // update offset to point AFTER the text node
       offset++;
-    }
-    else
-    {
+    } else {
       // split the text node
       nsresult rv = SplitNode(node, theOffset, getter_AddRefs(tmp));
       NS_ENSURE_SUCCESS(rv, rv);
       tmp = GetNodeLocation(node, &offset);
     }
     // create br
     nsresult rv = CreateNode(brType, tmp, offset, getter_AddRefs(brNode));
     NS_ENSURE_SUCCESS(rv, rv);
     *aInOutParent = tmp;
     *aInOutOffset = offset+1;
-  }
-  else
-  {
+  } else {
     nsresult rv = CreateNode(brType, node, theOffset, getter_AddRefs(brNode));
     NS_ENSURE_SUCCESS(rv, rv);
     (*aInOutOffset)++;
   }
 
   *outBRNode = brNode;
-  if (*outBRNode && (aSelect != eNone))
-  {
+  if (*outBRNode && (aSelect != eNone)) {
     int32_t offset;
     nsCOMPtr<nsIDOMNode> parent = GetNodeLocation(*outBRNode, &offset);
 
     RefPtr<Selection> selection = GetSelection();
     NS_ENSURE_STATE(selection);
-    if (aSelect == eNext)
-    {
+    if (aSelect == eNext) {
       // position selection after br
       selection->SetInterlinePosition(true);
       selection->Collapse(parent, offset + 1);
-    }
-    else if (aSelect == ePrevious)
-    {
+    } else if (aSelect == ePrevious) {
       // position selection before br
       selection->SetInterlinePosition(true);
       selection->Collapse(parent, offset);
     }
   }
   return NS_OK;
 }
 
@@ -575,27 +564,27 @@ TextEditor::InsertBR(nsCOMPtr<nsIDOMNode
 nsresult
 TextEditor::ExtendSelectionForDelete(Selection* aSelection,
                                      nsIEditor::EDirection* aAction)
 {
   nsresult result = NS_OK;
 
   bool bCollapsed = aSelection->Collapsed();
 
-  if (*aAction == eNextWord || *aAction == ePreviousWord
-      || (*aAction == eNext && bCollapsed)
-      || (*aAction == ePrevious && bCollapsed)
-      || *aAction == eToBeginningOfLine || *aAction == eToEndOfLine)
-  {
+  if (*aAction == eNextWord ||
+      *aAction == ePreviousWord ||
+      (*aAction == eNext && bCollapsed) ||
+      (*aAction == ePrevious && bCollapsed) ||
+      *aAction == eToBeginningOfLine ||
+      *aAction == eToEndOfLine) {
     nsCOMPtr<nsISelectionController> selCont;
     GetSelectionController(getter_AddRefs(selCont));
     NS_ENSURE_TRUE(selCont, NS_ERROR_NO_INTERFACE);
 
-    switch (*aAction)
-    {
+    switch (*aAction) {
       case eNextWord:
         result = selCont->WordExtendForDelete(true);
         // DeleteSelectionImpl doesn't handle these actions
         // because it's inside batching, so don't confuse it:
         *aAction = eNone;
         break;
       case ePreviousWord:
         result = selCont->WordExtendForDelete(false);
@@ -656,17 +645,19 @@ TextEditor::ExtendSelectionForDelete(Sel
 }
 
 nsresult
 TextEditor::DeleteSelection(EDirection aAction,
                             EStripWrappers aStripWrappers)
 {
   MOZ_ASSERT(aStripWrappers == eStrip || aStripWrappers == eNoStrip);
 
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
 
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> rules(mRules);
 
   nsresult result;
 
   // delete placeholder txns merge.
   AutoPlaceHolderBatch batch(this, nsGkAtoms::DeleteTxnName);
@@ -678,52 +669,48 @@ TextEditor::DeleteSelection(EDirection a
 
   // If there is an existing selection when an extended delete is requested,
   //  platforms that use "caret-style" caret positioning collapse the
   //  selection to the  start and then create a new selection.
   //  Platforms that use "selection-style" caret positioning just delete the
   //  existing selection without extending it.
   if (!selection->Collapsed() &&
       (aAction == eNextWord || aAction == ePreviousWord ||
-       aAction == eToBeginningOfLine || aAction == eToEndOfLine))
-  {
-    if (mCaretStyle == 1)
-    {
+       aAction == eToBeginningOfLine || aAction == eToEndOfLine)) {
+    if (mCaretStyle == 1) {
       result = selection->CollapseToStart();
       NS_ENSURE_SUCCESS(result, result);
-    }
-    else
-    {
+    } else {
       aAction = eNone;
     }
   }
 
   TextRulesInfo ruleInfo(EditAction::deleteSelection);
   ruleInfo.collapsedAction = aAction;
   ruleInfo.stripWrappers = aStripWrappers;
   bool cancel, handled;
   result = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   NS_ENSURE_SUCCESS(result, result);
-  if (!cancel && !handled)
-  {
+  if (!cancel && !handled) {
     result = DeleteSelectionImpl(aAction, aStripWrappers);
   }
-  if (!cancel)
-  {
+  if (!cancel) {
     // post-process
     result = rules->DidDoAction(selection, &ruleInfo, result);
   }
 
   return result;
 }
 
 NS_IMETHODIMP
 TextEditor::InsertText(const nsAString& aStringToInsert)
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
 
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> rules(mRules);
 
   EditAction opID = EditAction::insertText;
   if (ShouldHandleIMEComposition()) {
     opID = EditAction::insertIMEText;
   }
@@ -740,49 +727,49 @@ TextEditor::InsertText(const nsAString& 
   TextRulesInfo ruleInfo(opID);
   ruleInfo.inString = &aStringToInsert;
   ruleInfo.outString = &resultString;
   ruleInfo.maxLength = mMaxTextLength;
 
   bool cancel, handled;
   nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (!cancel && !handled)
-  {
+  if (!cancel && !handled) {
     // we rely on rules code for now - no default implementation
   }
   if (cancel) {
     return NS_OK;
   }
   // post-process
   return rules->DidDoAction(selection, &ruleInfo, rv);
 }
 
 NS_IMETHODIMP
 TextEditor::InsertLineBreak()
 {
-  if (!mRules) { return NS_ERROR_NOT_INITIALIZED; }
+  if (!mRules) {
+    return NS_ERROR_NOT_INITIALIZED;
+  }
 
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> rules(mRules);
 
   AutoEditBatch beginBatching(this);
   AutoRules beginRulesSniffing(this, EditAction::insertBreak, nsIEditor::eNext);
 
   // pre-process
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
 
   TextRulesInfo ruleInfo(EditAction::insertBreak);
   ruleInfo.maxLength = mMaxTextLength;
   bool cancel, handled;
   nsresult rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (!cancel && !handled)
-  {
+  if (!cancel && !handled) {
     // get the (collapsed) selection location
     NS_ENSURE_STATE(selection->GetRangeAt(0));
     nsCOMPtr<nsINode> selNode = selection->GetRangeAt(0)->GetStartParent();
     int32_t selOffset = selection->GetRangeAt(0)->StartOffset();
     NS_ENSURE_STATE(selNode);
 
     // don't put text in places that can't have it
     if (!IsTextNode(selNode) && !CanContainTag(*selNode,
@@ -935,18 +922,19 @@ TextEditor::GetTextLength(int32_t* aCoun
 
   // initialize out params
   *aCount = 0;
 
   // special-case for empty document, to account for the bogus node
   bool docEmpty;
   nsresult rv = GetDocumentIsEmpty(&docEmpty);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (docEmpty)
+  if (docEmpty) {
     return NS_OK;
+  }
 
   dom::Element *rootElement = GetRoot();
   NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER);
 
   nsCOMPtr<nsIContentIterator> iter =
     do_CreateInstance("@mozilla.org/content/post-content-iterator;1", &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -993,35 +981,36 @@ TextEditor::GetWrapWidth(int32_t* aWrapC
 //
 // See if the style value includes this attribute, and if it does,
 // cut out everything from the attribute to the next semicolon.
 //
 static void CutStyle(const char* stylename, nsString& styleValue)
 {
   // Find the current wrapping type:
   int32_t styleStart = styleValue.Find(stylename, true);
-  if (styleStart >= 0)
-  {
+  if (styleStart >= 0) {
     int32_t styleEnd = styleValue.Find(";", false, styleStart);
-    if (styleEnd > styleStart)
+    if (styleEnd > styleStart) {
       styleValue.Cut(styleStart, styleEnd - styleStart + 1);
-    else
+    } else {
       styleValue.Cut(styleStart, styleValue.Length() - styleStart);
+    }
   }
 }
 
 NS_IMETHODIMP
 TextEditor::SetWrapWidth(int32_t aWrapColumn)
 {
   SetWrapColumn(aWrapColumn);
 
   // Make sure we're a plaintext editor, otherwise we shouldn't
   // do the rest of this.
-  if (!IsPlaintextEditor())
+  if (!IsPlaintextEditor()) {
     return NS_OK;
+  }
 
   // Ought to set a style sheet here ...
   // Probably should keep around an mPlaintextStyleSheet for this purpose.
   dom::Element *rootElement = GetRoot();
   NS_ENSURE_TRUE(rootElement, NS_ERROR_NULL_POINTER);
 
   // Get the current style for this root element:
   nsAutoString styleValue;
@@ -1029,35 +1018,35 @@ TextEditor::SetWrapWidth(int32_t aWrapCo
 
   // We'll replace styles for these values:
   CutStyle("white-space", styleValue);
   CutStyle("width", styleValue);
   CutStyle("font-family", styleValue);
 
   // If we have other style left, trim off any existing semicolons
   // or whitespace, then add a known semicolon-space:
-  if (!styleValue.IsEmpty())
-  {
+  if (!styleValue.IsEmpty()) {
     styleValue.Trim("; \t", false, true);
     styleValue.AppendLiteral("; ");
   }
 
   // Make sure we have fixed-width font.  This should be done for us,
   // but it isn't, see bug 22502, so we have to add "font: -moz-fixed;".
   // Only do this if we're wrapping.
-  if (IsWrapHackEnabled() && aWrapColumn >= 0)
+  if (IsWrapHackEnabled() && aWrapColumn >= 0) {
     styleValue.AppendLiteral("font-family: -moz-fixed; ");
+  }
 
   // and now we're ready to set the new whitespace/wrapping style.
   if (aWrapColumn > 0) {
     // Wrap to a fixed column.
     styleValue.AppendLiteral("white-space: pre-wrap; width: ");
     styleValue.AppendInt(aWrapColumn);
     styleValue.AppendLiteral("ch;");
-  } else if (aWrapColumn == 0) {
+  } else if (!aWrapColumn) {
     styleValue.AppendLiteral("white-space: pre-wrap;");
   } else {
     styleValue.AppendLiteral("white-space: pre;");
   }
 
   return rootElement->SetAttr(kNameSpaceID_None, nsGkAtoms::style, styleValue, true);
 }
 
@@ -1099,18 +1088,17 @@ TextEditor::Undo(uint32_t aCount)
 
   AutoRules beginRulesSniffing(this, EditAction::undo, nsIEditor::eNone);
 
   TextRulesInfo ruleInfo(EditAction::undo);
   RefPtr<Selection> selection = GetSelection();
   bool cancel, handled;
   nsresult result = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
 
-  if (!cancel && NS_SUCCEEDED(result))
-  {
+  if (!cancel && NS_SUCCEEDED(result)) {
     result = EditorBase::Undo(aCount);
     result = rules->DidDoAction(selection, &ruleInfo, result);
   }
 
   NotifyEditorObservers(eNotifyEditorObserversOfEnd);
   return result;
 }
 
@@ -1128,18 +1116,17 @@ TextEditor::Redo(uint32_t aCount)
 
   AutoRules beginRulesSniffing(this, EditAction::redo, nsIEditor::eNone);
 
   TextRulesInfo ruleInfo(EditAction::redo);
   RefPtr<Selection> selection = GetSelection();
   bool cancel, handled;
   nsresult result = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
 
-  if (!cancel && NS_SUCCEEDED(result))
-  {
+  if (!cancel && NS_SUCCEEDED(result)) {
     result = EditorBase::Redo(aCount);
     result = rules->DidDoAction(selection, &ruleInfo, result);
   }
 
   NotifyEditorObservers(eNotifyEditorObserversOfEnd);
   return result;
 }
 
@@ -1147,18 +1134,19 @@ bool
 TextEditor::CanCutOrCopy(PasswordFieldAllowed aPasswordFieldAllowed)
 {
   RefPtr<Selection> selection = GetSelection();
   if (!selection) {
     return false;
   }
 
   if (aPasswordFieldAllowed == ePasswordFieldNotAllowed &&
-      IsPasswordEditor())
+      IsPasswordEditor()) {
     return false;
+  }
 
   return !selection->Collapsed();
 }
 
 bool
 TextEditor::FireClipboardEvent(EventMessage aEventMessage,
                                int32_t aSelectionType,
                                bool* aActionTaken)
@@ -1255,33 +1243,32 @@ TextEditor::GetAndInitDocEncoder(const n
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!aCharset.IsEmpty() && !aCharset.EqualsLiteral("null")) {
     docEncoder->SetCharset(aCharset);
   }
 
   int32_t wc;
   (void) GetWrapWidth(&wc);
-  if (wc >= 0)
+  if (wc >= 0) {
     (void) docEncoder->SetWrapColumn(wc);
+  }
 
   // Set the selection, if appropriate.
   // We do this either if the OutputSelectionOnly flag is set,
   // in which case we use our existing selection ...
-  if (aFlags & nsIDocumentEncoder::OutputSelectionOnly)
-  {
+  if (aFlags & nsIDocumentEncoder::OutputSelectionOnly) {
     RefPtr<Selection> selection = GetSelection();
     NS_ENSURE_STATE(selection);
     rv = docEncoder->SetSelection(selection);
     NS_ENSURE_SUCCESS(rv, rv);
   }
   // ... or if the root element is not a body,
   // in which case we set the selection to encompass the root.
-  else
-  {
+  else {
     dom::Element* rootElement = GetRoot();
     NS_ENSURE_TRUE(rootElement, NS_ERROR_FAILURE);
     if (!rootElement->IsHTMLElement(nsGkAtoms::body)) {
       rv = docEncoder->SetNativeContainerNode(rootElement);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
@@ -1301,27 +1288,30 @@ TextEditor::OutputToString(const nsAStri
   nsString resultString;
   TextRulesInfo ruleInfo(EditAction::outputText);
   ruleInfo.outString = &resultString;
   // XXX Struct should store a nsAReadable*
   nsAutoString str(aFormatType);
   ruleInfo.outputFormat = &str;
   bool cancel, handled;
   nsresult rv = rules->WillDoAction(nullptr, &ruleInfo, &cancel, &handled);
-  if (cancel || NS_FAILED(rv)) { return rv; }
-  if (handled)
-  { // this case will get triggered by password fields
+  if (cancel || NS_FAILED(rv)) {
+    return rv;
+  }
+  if (handled) {
+    // This case will get triggered by password fields.
     aOutputString.Assign(*(ruleInfo.outString));
     return rv;
   }
 
   nsAutoCString charsetStr;
   rv = GetDocumentCharacterSet(charsetStr);
-  if(NS_FAILED(rv) || charsetStr.IsEmpty())
+  if (NS_FAILED(rv) || charsetStr.IsEmpty()) {
     charsetStr.AssignLiteral("ISO-8859-1");
+  }
 
   nsCOMPtr<nsIDocumentEncoder> encoder;
   rv = GetAndInitDocEncoder(aFormatType, aFlags, charsetStr, getter_AddRefs(encoder));
   NS_ENSURE_SUCCESS(rv, rv);
   return encoder->EncodeToString(aOutputString);
 }
 
 NS_IMETHODIMP
@@ -1330,24 +1320,24 @@ TextEditor::OutputToStream(nsIOutputStre
                            const nsACString& aCharset,
                            uint32_t aFlags)
 {
   nsresult rv;
 
   // special-case for empty document when requesting plain text,
   // to account for the bogus text node.
   // XXX Should there be a similar test in OutputToString?
-  if (aFormatType.EqualsLiteral("text/plain"))
-  {
+  if (aFormatType.EqualsLiteral("text/plain")) {
     bool docEmpty;
     rv = GetDocumentIsEmpty(&docEmpty);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (docEmpty)
-       return NS_OK;    // output nothing
+    if (docEmpty) {
+      return NS_OK; // Output nothing.
+    }
   }
 
   nsCOMPtr<nsIDocumentEncoder> encoder;
   rv = GetAndInitDocEncoder(aFormatType, aFlags, aCharset,
                             getter_AddRefs(encoder));
 
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -1366,40 +1356,36 @@ TextEditor::PasteAsQuotation(int32_t aSe
   // Get Clipboard Service
   nsresult rv;
   nsCOMPtr<nsIClipboard> clipboard(do_GetService("@mozilla.org/widget/clipboard;1", &rv));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Get the nsITransferable interface for getting the data from the clipboard
   nsCOMPtr<nsITransferable> trans;
   rv = PrepareTransferable(getter_AddRefs(trans));
-  if (NS_SUCCEEDED(rv) && trans)
-  {
+  if (NS_SUCCEEDED(rv) && trans) {
     // Get the Data from the clipboard
     clipboard->GetData(trans, aSelectionType);
 
     // Now we ask the transferable for the data
     // it still owns the data, we just have a pointer to it.
     // If it can't support a "text" output of the data the call will fail
     nsCOMPtr<nsISupports> genericDataObj;
     uint32_t len;
     char* flav = nullptr;
     rv = trans->GetAnyTransferData(&flav, getter_AddRefs(genericDataObj),
                                    &len);
-    if (NS_FAILED(rv) || !flav)
-    {
+    if (NS_FAILED(rv) || !flav) {
       return rv;
     }
 
-    if (0 == nsCRT::strcmp(flav, kUnicodeMime) ||
-        0 == nsCRT::strcmp(flav, kMozTextInternal))
-    {
+    if (!nsCRT::strcmp(flav, kUnicodeMime) ||
+        !nsCRT::strcmp(flav, kMozTextInternal)) {
       nsCOMPtr<nsISupportsString> textDataObj ( do_QueryInterface(genericDataObj) );
-      if (textDataObj && len > 0)
-      {
+      if (textDataObj && len > 0) {
         nsAutoString stuffToPaste;
         textDataObj->GetData ( stuffToPaste );
         AutoEditBatch beginBatching(this);
         rv = InsertAsQuotation(stuffToPaste, 0);
       }
     }
     free(flav);
   }
@@ -1416,41 +1402,41 @@ TextEditor::InsertAsQuotation(const nsAS
 
   // Let the citer quote it for us:
   nsString quotedStuff;
   nsresult rv = InternetCiter::GetCiteString(aQuotedText, quotedStuff);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // It's best to put a blank line after the quoted text so that mails
   // written without thinking won't be so ugly.
-  if (!aQuotedText.IsEmpty() && (aQuotedText.Last() != char16_t('\n')))
+  if (!aQuotedText.IsEmpty() && (aQuotedText.Last() != char16_t('\n'))) {
     quotedStuff.Append(char16_t('\n'));
+  }
 
   // get selection
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
 
   AutoEditBatch beginBatching(this);
   AutoRules beginRulesSniffing(this, EditAction::insertText, nsIEditor::eNext);
 
   // give rules a chance to handle or cancel
   TextRulesInfo ruleInfo(EditAction::insertElement);
   bool cancel, handled;
   rv = rules->WillDoAction(selection, &ruleInfo, &cancel, &handled);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (cancel) return NS_OK; // rules canceled the operation
-  if (!handled)
-  {
+  if (cancel) {
+    return NS_OK; // Rules canceled the operation.
+  }
+  if (!handled) {
     rv = InsertText(quotedStuff);
 
     // XXX Should set *aNodeInserted to the first node inserted
-    if (aNodeInserted && NS_SUCCEEDED(rv))
-    {
-      *aNodeInserted = 0;
-      //NS_IF_ADDREF(*aNodeInserted);
+    if (aNodeInserted && NS_SUCCEEDED(rv)) {
+      *aNodeInserted = nullptr;
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP
 TextEditor::PasteAsCitedQuotation(const nsAString& aCitation,
                                   int32_t aSelectionType)
@@ -1472,49 +1458,52 @@ TextEditor::SharedOutputString(uint32_t 
                                bool* aIsCollapsed,
                                nsAString& aResult)
 {
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_NOT_INITIALIZED);
 
   *aIsCollapsed = selection->Collapsed();
 
-  if (!*aIsCollapsed)
+  if (!*aIsCollapsed) {
     aFlags |= nsIDocumentEncoder::OutputSelectionOnly;
+  }
   // If the selection isn't collapsed, we'll use the whole document.
 
   return OutputToString(NS_LITERAL_STRING("text/plain"), aFlags, aResult);
 }
 
 NS_IMETHODIMP
 TextEditor::Rewrap(bool aRespectNewlines)
 {
   int32_t wrapCol;
   nsresult rv = GetWrapWidth(&wrapCol);
   NS_ENSURE_SUCCESS(rv, NS_OK);
 
   // Rewrap makes no sense if there's no wrap column; default to 72.
-  if (wrapCol <= 0)
+  if (wrapCol <= 0) {
     wrapCol = 72;
+  }
 
   nsAutoString current;
   bool isCollapsed;
   rv = SharedOutputString(nsIDocumentEncoder::OutputFormatted
                           | nsIDocumentEncoder::OutputLFLineBreak,
                           &isCollapsed, current);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsString wrapped;
   uint32_t firstLineOffset = 0;   // XXX need to reset this if there is a selection
   rv = InternetCiter::Rewrap(current, wrapCol, firstLineOffset,
                              aRespectNewlines, wrapped);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (isCollapsed)    // rewrap the whole document
+  if (isCollapsed) {
     SelectAll();
+  }
 
   return InsertTextWithQuotations(wrapped);
 }
 
 NS_IMETHODIMP
 TextEditor::StripCites()
 {
   nsAutoString current;
@@ -1522,28 +1511,27 @@ TextEditor::StripCites()
   nsresult rv = SharedOutputString(nsIDocumentEncoder::OutputFormatted,
                                    &isCollapsed, current);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsString stripped;
   rv = InternetCiter::StripCites(current, stripped);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (isCollapsed)    // rewrap the whole document
-  {
+  if (isCollapsed) {
     rv = SelectAll();
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return InsertText(stripped);
 }
 
 NS_IMETHODIMP
 TextEditor::GetEmbeddedObjects(nsIArray** aNodeList)
- {
+{
   if (NS_WARN_IF(!aNodeList)) {
     return NS_ERROR_INVALID_ARG;
   }
 
   *aNodeList = nullptr;
   return NS_OK;
 }
 
@@ -1579,17 +1567,19 @@ TextEditor::EndOperation()
   nsresult rv = rules ? rules->AfterEdit(mAction, mDirection) : NS_OK;
   EditorBase::EndOperation();  // will clear mAction, mDirection
   return rv;
 }
 
 nsresult
 TextEditor::SelectEntireDocument(Selection* aSelection)
 {
-  if (!aSelection || !mRules) { return NS_ERROR_NULL_POINTER; }
+  if (!aSelection || !mRules) {
+    return NS_ERROR_NULL_POINTER;
+  }
 
   // Protect the edit rules object from dying
   nsCOMPtr<nsIEditRules> rules(mRules);
 
   // is doc empty?
   bool bDocIsEmpty;
   if (NS_SUCCEEDED(rules->DocumentIsEmpty(&bDocIsEmpty)) && bDocIsEmpty) {
     // get root node
--- a/editor/libeditor/TextEditorDataTransfer.cpp
+++ b/editor/libeditor/TextEditorDataTransfer.cpp
@@ -72,26 +72,24 @@ TextEditor::PrepareTransferable(nsITrans
 }
 
 nsresult
 TextEditor::InsertTextAt(const nsAString& aStringToInsert,
                          nsIDOMNode* aDestinationNode,
                          int32_t aDestOffset,
                          bool aDoDeleteSelection)
 {
-  if (aDestinationNode)
-  {
+  if (aDestinationNode) {
     RefPtr<Selection> selection = GetSelection();
     NS_ENSURE_STATE(selection);
 
     nsCOMPtr<nsIDOMNode> targetNode = aDestinationNode;
     int32_t targetOffset = aDestOffset;
 
-    if (aDoDeleteSelection)
-    {
+    if (aDoDeleteSelection) {
       // Use an auto tracker so that our drop point is correctly
       // positioned after the delete.
       AutoTrackDOMPoint tracker(mRangeUpdater, &targetNode, &targetOffset);
       nsresult rv = DeleteSelection(eNone, eStrip);
       NS_ENSURE_SUCCESS(rv, rv);
     }
 
     nsresult rv = selection->Collapse(targetNode, targetOffset);
@@ -106,41 +104,43 @@ TextEditor::InsertTextFromTransferable(n
                                        nsIDOMNode* aDestinationNode,
                                        int32_t aDestOffset,
                                        bool aDoDeleteSelection)
 {
   nsresult rv = NS_OK;
   char* bestFlavor = nullptr;
   nsCOMPtr<nsISupports> genericDataObj;
   uint32_t len = 0;
-  if (NS_SUCCEEDED(aTransferable->GetAnyTransferData(&bestFlavor, getter_AddRefs(genericDataObj), &len))
-      && bestFlavor && (0 == nsCRT::strcmp(bestFlavor, kUnicodeMime) ||
-                        0 == nsCRT::strcmp(bestFlavor, kMozTextInternal)))
-  {
+  if (NS_SUCCEEDED(
+        aTransferable->GetAnyTransferData(&bestFlavor,
+                                          getter_AddRefs(genericDataObj),
+                                          &len)) &&
+      bestFlavor && (!nsCRT::strcmp(bestFlavor, kUnicodeMime) ||
+                     !nsCRT::strcmp(bestFlavor, kMozTextInternal))) {
     AutoTransactionsConserveSelection dontSpazMySelection(this);
     nsCOMPtr<nsISupportsString> textDataObj ( do_QueryInterface(genericDataObj) );
-    if (textDataObj && len > 0)
-    {
+    if (textDataObj && len > 0) {
       nsAutoString stuffToPaste;
       textDataObj->GetData(stuffToPaste);
       NS_ASSERTION(stuffToPaste.Length() <= (len/2), "Invalid length!");
 
       // Sanitize possible carriage returns in the string to be inserted
       nsContentUtils::PlatformToDOMLineBreaks(stuffToPaste);
 
       AutoEditBatch beginBatching(this);
       rv = InsertTextAt(stuffToPaste, aDestinationNode, aDestOffset, aDoDeleteSelection);
     }
   }
   free(bestFlavor);
 
   // Try to scroll the selection into view if the paste/drop succeeded
 
-  if (NS_SUCCEEDED(rv))
+  if (NS_SUCCEEDED(rv)) {
     ScrollSelectionIntoView(false);
+  }
 
   return rv;
 }
 
 nsresult
 TextEditor::InsertFromDataTransfer(DataTransfer* aDataTransfer,
                                    int32_t aIndex,
                                    nsIDOMDocument* aSourceDoc,
@@ -187,28 +187,31 @@ TextEditor::InsertFromDrop(nsIDOMEvent* 
     sourceNode->GetOwnerDocument(getter_AddRefs(srcdomdoc));
     NS_ENSURE_TRUE(sourceNode, NS_ERROR_FAILURE);
   }
 
   if (nsContentUtils::CheckForSubFrameDrop(dragSession,
         aDropEvent->WidgetEventPtr()->AsDragEvent())) {
     // Don't allow drags from subframe documents with different origins than
     // the drop destination.
-    if (srcdomdoc && !IsSafeToInsertData(srcdomdoc))
+    if (srcdomdoc && !IsSafeToInsertData(srcdomdoc)) {
       return NS_OK;
+    }
   }
 
   // Current doc is destination
   nsCOMPtr<nsIDOMDocument> destdomdoc = GetDOMDocument();
   NS_ENSURE_TRUE(destdomdoc, NS_ERROR_NOT_INITIALIZED);
 
   uint32_t numItems = 0;
   nsresult rv = dataTransfer->GetMozItemCount(&numItems);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (numItems < 1) return NS_ERROR_FAILURE;  // nothing to drop?
+  if (numItems < 1) {
+    return NS_ERROR_FAILURE;  // Nothing to drop?
+  }
 
   // Combine any deletion and drop insertion into one transaction
   AutoEditBatch beginBatching(this);
 
   bool deleteSelection = false;
 
   // We have to figure out whether to delete and relocate caret only once
   // Parent and offset are under the mouse cursor
@@ -226,18 +229,17 @@ TextEditor::InsertFromDrop(nsIDOMEvent* 
 
   RefPtr<Selection> selection = GetSelection();
   NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);
 
   bool isCollapsed = selection->Collapsed();
 
   // Only the HTMLEditor::FindUserSelectAllNode returns a node.
   nsCOMPtr<nsIDOMNode> userSelectNode = FindUserSelectAllNode(newSelectionParent);
-  if (userSelectNode)
-  {
+  if (userSelectNode) {
     // The drop is happening over a "-moz-user-select: all"
     // subtree so make sure the content we insert goes before
     // the root of the subtree.
     //
     // XXX: Note that inserting before the subtree matches the
     //      current behavior when dropping on top of an image.
     //      The decision for dropping before or after the
     //      subtree should really be done based on coordinates.
@@ -245,61 +247,55 @@ TextEditor::InsertFromDrop(nsIDOMEvent* 
     newSelectionParent = GetNodeLocation(userSelectNode, &newSelectionOffset);
 
     NS_ENSURE_TRUE(newSelectionParent, NS_ERROR_FAILURE);
   }
 
   // Check if mouse is in the selection
   // if so, jump through some hoops to determine if mouse is over selection (bail)
   // and whether user wants to copy selection or delete it
-  if (!isCollapsed)
-  {
+  if (!isCollapsed) {
     // We never have to delete if selection is already collapsed
     bool cursorIsInSelection = false;
 
     int32_t rangeCount;
     rv = selection->GetRangeCount(&rangeCount);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    for (int32_t j = 0; j < rangeCount; j++)
-    {
+    for (int32_t j = 0; j < rangeCount; j++) {
       RefPtr<nsRange> range = selection->GetRangeAt(j);
       if (!range) {
         // don't bail yet, iterate through them all
         continue;
       }
 
       rv = range->IsPointInRange(newSelectionParent, newSelectionOffset, &cursorIsInSelection);
-      if (cursorIsInSelection)
+      if (cursorIsInSelection) {
         break;
+      }
     }
 
-    if (cursorIsInSelection)
-    {
+    if (cursorIsInSelection) {
       // Dragging within same doc can't drop on itself -- leave!
-      if (srcdomdoc == destdomdoc)
+      if (srcdomdoc == destdomdoc) {
         return NS_OK;
+      }
 
       // Dragging from another window onto a selection
       // XXX Decision made to NOT do this,
       //     note that 4.x does replace if dropped on
       //deleteSelection = true;
-    }
-    else
-    {
+    } else {
       // We are NOT over the selection
-      if (srcdomdoc == destdomdoc)
-      {
+      if (srcdomdoc == destdomdoc) {
         // Within the same doc: delete if user doesn't want to copy
         uint32_t dropEffect;
         dataTransfer->GetDropEffectInt(&dropEffect);
         deleteSelection = !(dropEffect & nsIDragService::DRAGDROP_ACTION_COPY);
-      }
-      else
-      {
+      } else {
         // Different source doc: Don't delete
         deleteSelection = false;
       }
     }
   }
 
   if (IsPlaintextEditor()) {
     nsCOMPtr<nsIContent> content = do_QueryInterface(newSelectionParent);
@@ -314,43 +310,44 @@ TextEditor::InsertFromDrop(nsIDOMEvent* 
     }
   }
 
   for (uint32_t i = 0; i < numItems; ++i) {
     InsertFromDataTransfer(dataTransfer, i, srcdomdoc, newSelectionParent,
                            newSelectionOffset, deleteSelection);
   }
 
-  if (NS_SUCCEEDED(rv))
+  if (NS_SUCCEEDED(rv)) {
     ScrollSelectionIntoView(false);
+  }
 
   return rv;
 }
 
 NS_IMETHODIMP
 TextEditor::Paste(int32_t aSelectionType)
 {
   if (!FireClipboardEvent(ePaste, aSelectionType)) {
     return NS_OK;
   }
 
   // Get Clipboard Service
   nsresult rv;
   nsCOMPtr<nsIClipboard> clipboard(do_GetService("@mozilla.org/widget/clipboard;1", &rv));
-  if ( NS_FAILED(rv) )
+  if (NS_FAILED(rv)) {
     return rv;
+  }
 
   // Get the nsITransferable interface for getting the data from the clipboard
   nsCOMPtr<nsITransferable> trans;
   rv = PrepareTransferable(getter_AddRefs(trans));
-  if (NS_SUCCEEDED(rv) && trans)
-  {
+  if (NS_SUCCEEDED(rv) && trans) {
     // Get the Data from the clipboard
-    if (NS_SUCCEEDED(clipboard->GetData(trans, aSelectionType)) && IsModifiable())
-    {
+    if (NS_SUCCEEDED(clipboard->GetData(trans, aSelectionType)) &&
+        IsModifiable()) {
       // handle transferable hooks
       nsCOMPtr<nsIDOMDocument> domdoc = GetDOMDocument();
       if (!EditorHookUtils::DoInsertionHook(domdoc, nullptr, trans)) {
         return NS_OK;
       }
 
       rv = InsertTextFromTransferable(trans, nullptr, 0, true);
     }
@@ -363,18 +360,19 @@ NS_IMETHODIMP
 TextEditor::PasteTransferable(nsITransferable* aTransferable)
 {
   // Use an invalid value for the clipboard type as data comes from aTransferable
   // and we don't currently implement a way to put that in the data transfer yet.
   if (!FireClipboardEvent(ePaste, -1)) {
     return NS_OK;
   }
 
-  if (!IsModifiable())
+  if (!IsModifiable()) {
     return NS_OK;
+  }
 
   // handle transferable hooks
   nsCOMPtr<nsIDOMDocument> domdoc = GetDOMDocument();
   if (!EditorHookUtils::DoInsertionHook(domdoc, nullptr, aTransferable)) {
     return NS_OK;
   }
 
   return InsertTextFromTransferable(aTransferable, nullptr, 0, true);
@@ -383,18 +381,19 @@ TextEditor::PasteTransferable(nsITransfe
 NS_IMETHODIMP
 TextEditor::CanPaste(int32_t aSelectionType,
                      bool* aCanPaste)
 {
   NS_ENSURE_ARG_POINTER(aCanPaste);
   *aCanPaste = false;
 
   // can't paste if readonly
-  if (!IsModifiable())
+  if (!IsModifiable()) {
     return NS_OK;
+  }
 
   nsresult rv;
   nsCOMPtr<nsIClipboard> clipboard(do_GetService("@mozilla.org/widget/clipboard;1", &rv));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // the flavors that we can deal with
   const char* textEditorFlavors[] = { kUnicodeMime };
 
@@ -427,40 +426,43 @@ TextEditor::CanPasteTransferable(nsITran
     return NS_OK;
   }
 
   nsCOMPtr<nsISupports> data;
   uint32_t dataLen;
   nsresult rv = aTransferable->GetTransferData(kUnicodeMime,
                                                getter_AddRefs(data),
                                                &dataLen);
-  if (NS_SUCCEEDED(rv) && data)
+  if (NS_SUCCEEDED(rv) && data) {
     *aCanPaste = true;
-  else
+  } else {
     *aCanPaste = false;
+  }
 
   return NS_OK;
 }
 
 bool
 TextEditor::IsSafeToInsertData(nsIDOMDocument* aSourceDoc)
 {
   // Try to determine whether we should use a sanitizing fragment sink
   bool isSafe = false;
 
   nsCOMPtr<nsIDocument> destdoc = GetDocument();
   NS_ASSERTION(destdoc, "Where is our destination doc?");
   nsCOMPtr<nsIDocShellTreeItem> dsti = destdoc->GetDocShell();
   nsCOMPtr<nsIDocShellTreeItem> root;
-  if (dsti)
+  if (dsti) {
     dsti->GetRootTreeItem(getter_AddRefs(root));
+  }
   nsCOMPtr<nsIDocShell> docShell = do_QueryInterface(root);
   uint32_t appType;
-  if (docShell && NS_SUCCEEDED(docShell->GetAppType(&appType)))
+  if (docShell && NS_SUCCEEDED(docShell->GetAppType(&appType))) {
     isSafe = appType == nsIDocShell::APP_TYPE_EDITOR;
+  }
   if (!isSafe && aSourceDoc) {
     nsCOMPtr<nsIDocument> srcdoc = do_QueryInterface(aSourceDoc);
     NS_ASSERTION(srcdoc, "Where is our source doc?");
 
     nsIPrincipal* srcPrincipal = srcdoc->NodePrincipal();
     nsIPrincipal* destPrincipal = destdoc->NodePrincipal();
     NS_ASSERTION(srcPrincipal && destPrincipal, "How come we don't have a principal?");
     srcPrincipal->Subsumes(destPrincipal, &isSafe);
--- a/editor/libeditor/TypeInState.cpp
+++ b/editor/libeditor/TypeInState.cpp
@@ -94,44 +94,43 @@ TypeInState::NotifySelectionChanged(nsID
       int32_t selOffset = 0;
 
       nsresult result =
         EditorBase::GetStartNodeAndOffset(selection, getter_AddRefs(selNode),
                                           &selOffset);
 
       NS_ENSURE_SUCCESS(result, result);
 
-      if (selNode && selNode == mLastSelectionContainer && selOffset == mLastSelectionOffset)
-      {
+      if (selNode &&
+          selNode == mLastSelectionContainer &&
+          selOffset == mLastSelectionOffset) {
         // We got a bogus selection changed notification!
         return NS_OK;
       }
 
       mLastSelectionContainer = selNode;
       mLastSelectionOffset = selOffset;
-    }
-    else
-    {
+    } else {
       mLastSelectionContainer = nullptr;
       mLastSelectionOffset = 0;
     }
   }
 
   Reset();
   return NS_OK;
 }
 
 void
 TypeInState::Reset()
 {
-  for(uint32_t i = 0, n = mClearedArray.Length(); i < n; i++) {
+  for (size_t i = 0, n = mClearedArray.Length(); i < n; i++) {
     delete mClearedArray[i];
   }
   mClearedArray.Clear();
-  for(uint32_t i = 0, n = mSetArray.Length(); i < n; i++) {
+  for (size_t i = 0, n = mSetArray.Length(); i < n; i++) {
     delete mSetArray[i];
   }
   mSetArray.Clear();
 }
 
 
 void
 TypeInState::SetProp(nsIAtom* aProp,
@@ -192,17 +191,17 @@ TypeInState::ClearProp(nsIAtom* aProp,
 
 /**
  * TakeClearProperty() hands back next property item on the clear list.
  * Caller assumes ownership of PropItem and must delete it.
  */
 PropItem*
 TypeInState::TakeClearProperty()
 {
-  uint32_t count = mClearedArray.Length();
+  size_t count = mClearedArray.Length();
   if (!count) {
     return nullptr;
   }
 
   --count; // indices are zero based
   PropItem* propItem = mClearedArray[count];
   mClearedArray.RemoveElementAt(count);
   return propItem;
@@ -210,17 +209,17 @@ TypeInState::TakeClearProperty()
 
 /**
  * TakeSetProperty() hands back next poroperty item on the set list.
  * Caller assumes ownership of PropItem and must delete it.
  */
 PropItem*
 TypeInState::TakeSetProperty()
 {
-  uint32_t count = mSetArray.Length();
+  size_t count = mSetArray.Length();
   if (!count) {
     return nullptr;
   }
   count--; // indices are zero based
   PropItem* propItem = mSetArray[count];
   mSetArray.RemoveElementAt(count);
   return propItem;
 }
@@ -247,92 +246,79 @@ TypeInState::GetTypingState(bool& isSet,
 
 void
 TypeInState::GetTypingState(bool& isSet,
                             bool& theSetting,
                             nsIAtom* aProp,
                             const nsString& aAttr,
                             nsString* aValue)
 {
-  if (IsPropSet(aProp, aAttr, aValue))
-  {
+  if (IsPropSet(aProp, aAttr, aValue)) {
     isSet = true;
     theSetting = true;
-  }
-  else if (IsPropCleared(aProp, aAttr))
-  {
+  } else if (IsPropCleared(aProp, aAttr)) {
     isSet = true;
     theSetting = false;
-  }
-  else
-  {
+  } else {
     isSet = false;
   }
 }
 
 void
 TypeInState::RemovePropFromSetList(nsIAtom* aProp,
                                    const nsAString& aAttr)
 {
   int32_t index;
-  if (!aProp)
-  {
+  if (!aProp) {
     // clear _all_ props
-    for(uint32_t i = 0, n = mSetArray.Length(); i < n; i++) {
+    for (size_t i = 0, n = mSetArray.Length(); i < n; i++) {
       delete mSetArray[i];
     }
     mSetArray.Clear();
     mRelativeFontSize=0;
-  }
-  else if (FindPropInList(aProp, aAttr, nullptr, mSetArray, index))
-  {
+  } else if (FindPropInList(aProp, aAttr, nullptr, mSetArray, index)) {
     delete mSetArray[index];
     mSetArray.RemoveElementAt(index);
   }
 }
 
-
 void
 TypeInState::RemovePropFromClearedList(nsIAtom* aProp,
                                        const nsAString& aAttr)
 {
   int32_t index;
-  if (FindPropInList(aProp, aAttr, nullptr, mClearedArray, index))
-  {
+  if (FindPropInList(aProp, aAttr, nullptr, mClearedArray, index)) {
     delete mClearedArray[index];
     mClearedArray.RemoveElementAt(index);
   }
 }
 
-
 bool
 TypeInState::IsPropSet(nsIAtom* aProp,
                        const nsAString& aAttr,
                        nsAString* outValue)
 {
   int32_t i;
   return IsPropSet(aProp, aAttr, outValue, i);
 }
 
-
 bool
 TypeInState::IsPropSet(nsIAtom* aProp,
                        const nsAString& aAttr,
                        nsAString* outValue,
                        int32_t& outIndex)
 {
   // linear search.  list should be short.
-  uint32_t i, count = mSetArray.Length();
-  for (i=0; i<count; i++)
-  {
+  size_t count = mSetArray.Length();
+  for (size_t i = 0; i < count; i++) {
     PropItem *item = mSetArray[i];
-    if ( (item->tag == aProp) &&
-         (item->attr == aAttr) )
-    {
-      if (outValue) *outValue = item->value;
+    if (item->tag == aProp && item->attr == aAttr) {
+      if (outValue) {
+        *outValue = item->value;
+      }
       outIndex = i;
       return true;
     }
   }
   return false;
 }
 
 
@@ -345,43 +331,42 @@ TypeInState::IsPropCleared(nsIAtom* aPro
 }
 
 
 bool
 TypeInState::IsPropCleared(nsIAtom* aProp,
                            const nsAString& aAttr,
                            int32_t& outIndex)
 {
-  if (FindPropInList(aProp, aAttr, nullptr, mClearedArray, outIndex))
+  if (FindPropInList(aProp, aAttr, nullptr, mClearedArray, outIndex)) {
     return true;
-  if (FindPropInList(0, EmptyString(), nullptr, mClearedArray, outIndex))
-  {
+  }
+  if (FindPropInList(0, EmptyString(), nullptr, mClearedArray, outIndex)) {
     // special case for all props cleared
     outIndex = -1;
     return true;
   }
   return false;
 }
 
 bool
 TypeInState::FindPropInList(nsIAtom* aProp,
                             const nsAString& aAttr,
                             nsAString* outValue,
                             nsTArray<PropItem*>& aList,
                             int32_t& outIndex)
 {
   // linear search.  list should be short.
-  uint32_t i, count = aList.Length();
-  for (i=0; i<count; i++)
-  {
+  size_t count = aList.Length();
+  for (size_t i = 0; i < count; i++) {
     PropItem *item = aList[i];
-    if ( (item->tag == aProp) &&
-         (item->attr == aAttr) )
-    {
-      if (outValue) *outValue = item->value;
+    if (item->tag == aProp && item->attr == aAttr) {
+      if (outValue) {
+        *outValue = item->value;
+      }
       outIndex = i;
       return true;
     }
   }
   return false;
 }
 
 /********************************************************************
--- a/editor/libeditor/WSRunObject.cpp
+++ b/editor/libeditor/WSRunObject.cpp
@@ -362,22 +362,20 @@ WSRunObject::InsertText(const nsAString&
 }
 
 nsresult
 WSRunObject::DeleteWSBackward()
 {
   WSPoint point = GetCharBefore(mNode, mOffset);
   NS_ENSURE_TRUE(point.mTextNode, NS_OK);  // nothing to delete
 
-  if (mPRE) {
-    // easy case, preformatted ws
-    if (nsCRT::IsAsciiSpace(point.mChar) || point.mChar == nbsp) {
-      return DeleteChars(point.mTextNode, point.mOffset,
-                         point.mTextNode, point.mOffset + 1);
-    }
+  // Easy case, preformatted ws.
+  if (mPRE &&  (nsCRT::IsAsciiSpace(point.mChar) || point.mChar == nbsp)) {
+    return DeleteChars(point.mTextNode, point.mOffset,
+                       point.mTextNode, point.mOffset + 1);
   }
 
   // Caller's job to ensure that previous char is really ws.  If it is normal
   // ws, we need to delete the whole run.
   if (nsCRT::IsAsciiSpace(point.mChar)) {
     RefPtr<Text> startNodeText, endNodeText;
     int32_t startOffset, endOffset;
     GetAsciiWSBounds(eBoth, point.mTextNode, point.mOffset + 1,
@@ -390,45 +388,46 @@ WSRunObject::DeleteWSBackward()
     nsresult rv =
       WSRunObject::PrepareToDeleteRange(mHTMLEditor,
                                         address_of(startNode), &startOffset,
                                         address_of(endNode), &endOffset);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // finally, delete that ws
     return DeleteChars(startNode, startOffset, endNode, endOffset);
-  } else if (point.mChar == nbsp) {
+  }
+
+  if (point.mChar == nbsp) {
     nsCOMPtr<nsINode> node(point.mTextNode);
     // adjust surrounding ws
     int32_t startOffset = point.mOffset;
     int32_t endOffset = point.mOffset + 1;
     nsresult rv =
       WSRunObject::PrepareToDeleteRange(mHTMLEditor,
                                         address_of(node), &startOffset,
                                         address_of(node), &endOffset);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // finally, delete that ws
     return DeleteChars(node, startOffset, node, endOffset);
   }
+
   return NS_OK;
 }
 
 nsresult
 WSRunObject::DeleteWSForward()
 {
   WSPoint point = GetCharAfter(mNode, mOffset);
   NS_ENSURE_TRUE(point.mTextNode, NS_OK); // nothing to delete
 
-  if (mPRE) {
-    // easy case, preformatted ws
-    if (nsCRT::IsAsciiSpace(point.mChar) || point.mChar == nbsp) {
-      return DeleteChars(point.mTextNode, point.mOffset,
-                         point.mTextNode, point.mOffset + 1);
-    }
+  // Easy case, preformatted ws.
+  if (mPRE && (nsCRT::IsAsciiSpace(point.mChar) || point.mChar == nbsp)) {
+    return DeleteChars(point.mTextNode, point.mOffset,
+                       point.mTextNode, point.mOffset + 1);
   }
 
   // Caller's job to ensure that next char is really ws.  If it is normal ws,
   // we need to delete the whole run.
   if (nsCRT::IsAsciiSpace(point.mChar)) {
     RefPtr<Text> startNodeText, endNodeText;
     int32_t startOffset, endOffset;
     GetAsciiWSBounds(eBoth, point.mTextNode, point.mOffset + 1,
@@ -440,30 +439,33 @@ WSRunObject::DeleteWSForward()
     nsresult rv =
       WSRunObject::PrepareToDeleteRange(mHTMLEditor,
                                         address_of(startNode), &startOffset,
                                         address_of(endNode), &endOffset);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Finally, delete that ws
     return DeleteChars(startNode, startOffset, endNode, endOffset);
-  } else if (point.mChar == nbsp) {
+  }
+
+  if (point.mChar == nbsp) {
     nsCOMPtr<nsINode> node(point.mTextNode);
     // Adjust surrounding ws
     int32_t startOffset = point.mOffset;
     int32_t endOffset = point.mOffset+1;
     nsresult rv =
       WSRunObject::PrepareToDeleteRange(mHTMLEditor,
                                         address_of(node), &startOffset,
                                         address_of(node), &endOffset);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Finally, delete that ws
     return DeleteChars(node, startOffset, node, endOffset);
   }
+
   return NS_OK;
 }
 
 void
 WSRunObject::PriorVisibleNode(nsINode* aNode,
                               int32_t aOffset,
                               nsCOMPtr<nsINode>* outVisNode,
                               int32_t* outVisOffset,
@@ -555,18 +557,17 @@ WSRunObject::AdjustWhitespace()
   // this routine examines a run of ws and tries to get rid of some unneeded nbsp's,
   // replacing them with regualr ascii space if possible.  Keeping things simple
   // for now and just trying to fix up the trailing ws in the run.
   if (!mLastNBSPNode) {
     // nothing to do!
     return NS_OK;
   }
   WSFragment *curRun = mStartRun;
-  while (curRun)
-  {
+  while (curRun) {
     // look for normal ws run
     if (curRun->mType == WSType::normalWS) {
       nsresult rv = CheckTrailingNBSPOfRun(curRun);
       if (NS_FAILED(rv)) {
         return rv;
       }
     }
     curRun = curRun->mRight;
@@ -875,33 +876,28 @@ WSRunObject::GetRuns()
     normalRun->mLeftType = WSType::leadingWS;
     normalRun->mLeft = mStartRun;
     if (mEndReason != WSType::block) {
       // then no trailing ws.  this normal run ends the overall ws run.
       normalRun->mRightType = mEndReason;
       normalRun->mEndNode   = mEndNode;
       normalRun->mEndOffset = mEndOffset;
       mEndRun = normalRun;
-    }
-    else
-    {
+    } else {
       // we might have trailing ws.
       // it so happens that *if* there is an nbsp at end, {mEndNode,mEndOffset-1}
       // will point to it, even though in general start/end points not
       // guaranteed to be in text nodes.
-      if ((mLastNBSPNode == mEndNode) && (mLastNBSPOffset == (mEndOffset-1)))
-      {
+      if (mLastNBSPNode == mEndNode && mLastNBSPOffset == mEndOffset - 1) {
         // normal ws runs right up to adjacent block (nbsp next to block)
         normalRun->mRightType = mEndReason;
         normalRun->mEndNode   = mEndNode;
         normalRun->mEndOffset = mEndOffset;
         mEndRun = normalRun;
-      }
-      else
-      {
+      } else {
         normalRun->mEndNode = mLastNBSPNode;
         normalRun->mEndOffset = mLastNBSPOffset+1;
         normalRun->mRightType = WSType::trailingWS;
 
         // set up next run
         WSFragment *lastRun = new WSFragment();
         lastRun->mType = WSType::trailingWS;
         lastRun->mStartNode = mLastNBSPNode;
@@ -921,25 +917,22 @@ WSRunObject::GetRuns()
     mStartRun->mEndNode = mLastNBSPNode;
     mStartRun->mEndOffset = mLastNBSPOffset+1;
     mStartRun->mLeftType = mStartReason;
 
     // we might have trailing ws.
     // it so happens that *if* there is an nbsp at end, {mEndNode,mEndOffset-1}
     // will point to it, even though in general start/end points not
     // guaranteed to be in text nodes.
-    if ((mLastNBSPNode == mEndNode) && (mLastNBSPOffset == (mEndOffset-1)))
-    {
+    if (mLastNBSPNode == mEndNode && mLastNBSPOffset == (mEndOffset - 1)) {
       mStartRun->mRightType = mEndReason;
       mStartRun->mEndNode   = mEndNode;
       mStartRun->mEndOffset = mEndOffset;
       mEndRun = mStartRun;
-    }
-    else
-    {
+    } else {
       // set up next run
       WSFragment *lastRun = new WSFragment();
       lastRun->mType = WSType::trailingWS;
       lastRun->mStartNode = mLastNBSPNode;
       lastRun->mStartOffset = mLastNBSPOffset+1;
       lastRun->mLeftType = WSType::normalWS;
       lastRun->mLeft = mStartRun;
       lastRun->mRightType = mEndReason;
@@ -950,18 +943,17 @@ WSRunObject::GetRuns()
   }
 }
 
 void
 WSRunObject::ClearRuns()
 {
   WSFragment *tmp, *run;
   run = mStartRun;
-  while (run)
-  {
+  while (run) {
     tmp = run->mRight;
     delete run;
     run = tmp;
   }
   mStartRun = 0;
   mEndRun = 0;
 }
 
@@ -1177,36 +1169,34 @@ WSRunObject::PrepareToDeleteRangePriv(WS
   // adjust normal ws in afterRun if needed
   if (afterRun && afterRun->mType == WSType::normalWS && !aEndObject->mPRE) {
     if ((beforeRun && (beforeRun->mType & WSType::leadingWS)) ||
         (!beforeRun && ((mStartReason & WSType::block) ||
                         mStartReason == WSType::br))) {
       // make sure leading char of following ws is an nbsp, so that it will show up
       WSPoint point = aEndObject->GetCharAfter(aEndObject->mNode,
                                                aEndObject->mOffset);
-      if (point.mTextNode && nsCRT::IsAsciiSpace(point.mChar))
-      {
+      if (point.mTextNode && nsCRT::IsAsciiSpace(point.mChar)) {
         nsresult rv = aEndObject->ConvertToNBSP(point, eOutsideUserSelectAll);
         NS_ENSURE_SUCCESS(rv, rv);
       }
     }
   }
   // trim before run of any trailing ws
   if (beforeRun && (beforeRun->mType & WSType::trailingWS)) {
     nsresult rv = DeleteChars(beforeRun->mStartNode, beforeRun->mStartOffset,
                               mNode, mOffset, eOutsideUserSelectAll);
     NS_ENSURE_SUCCESS(rv, rv);
   } else if (beforeRun && beforeRun->mType == WSType::normalWS && !mPRE) {
     if ((afterRun && (afterRun->mType & WSType::trailingWS)) ||
         (afterRun && afterRun->mType == WSType::normalWS) ||
         (!afterRun && (aEndObject->mEndReason & WSType::block))) {
       // make sure trailing char of starting ws is an nbsp, so that it will show up
       WSPoint point = GetCharBefore(mNode, mOffset);
-      if (point.mTextNode && nsCRT::IsAsciiSpace(point.mChar))
-      {
+      if (point.mTextNode && nsCRT::IsAsciiSpace(point.mChar)) {
         RefPtr<Text> wsStartNode, wsEndNode;
         int32_t wsStartOffset, wsEndOffset;
         GetAsciiWSBounds(eBoth, mNode, mOffset,
                          getter_AddRefs(wsStartNode), &wsStartOffset,
                          getter_AddRefs(wsEndNode), &wsEndOffset);
         point.mTextNode = wsStartNode;
         point.mOffset = wsStartOffset;
         nsresult rv = ConvertToNBSP(point, eOutsideUserSelectAll);
@@ -1228,29 +1218,27 @@ WSRunObject::PrepareToSplitAcrossBlocksP
   WSFragment *beforeRun, *afterRun;
   FindRun(mNode, mOffset, &beforeRun, false);
   FindRun(mNode, mOffset, &afterRun, true);
 
   // adjust normal ws in afterRun if needed
   if (afterRun && afterRun->mType == WSType::normalWS) {
     // make sure leading char of following ws is an nbsp, so that it will show up
     WSPoint point = GetCharAfter(mNode, mOffset);
-    if (point.mTextNode && nsCRT::IsAsciiSpace(point.mChar))
-    {
+    if (point.mTextNode && nsCRT::IsAsciiSpace(point.mChar)) {
       nsresult rv = ConvertToNBSP(point);
       NS_ENSURE_SUCCESS(rv, rv);
     }
   }
 
   // adjust normal ws in beforeRun if needed
   if (beforeRun && beforeRun->mType == WSType::normalWS) {
     // make sure trailing char of starting ws is an nbsp, so that it will show up
     WSPoint point = GetCharBefore(mNode, mOffset);
-    if (point.mTextNode && nsCRT::IsAsciiSpace(point.mChar))
-    {
+    if (point.mTextNode && nsCRT::IsAsciiSpace(point.mChar)) {
       RefPtr<Text> wsStartNode, wsEndNode;
       int32_t wsStartOffset, wsEndOffset;
       GetAsciiWSBounds(eBoth, mNode, mOffset,
                        getter_AddRefs(wsStartNode), &wsStartOffset,
                        getter_AddRefs(wsEndNode), &wsEndOffset);
       point.mTextNode = wsStartNode;
       point.mOffset = wsStartOffset;
       nsresult rv = ConvertToNBSP(point);
@@ -1358,36 +1346,34 @@ WSRunObject::GetCharAfter(nsINode* aNode
                           int32_t aOffset)
 {
   MOZ_ASSERT(aNode);
 
   int32_t idx = mNodeArray.IndexOf(aNode);
   if (idx == -1) {
     // Use range comparisons to get right ws node
     return GetWSPointAfter(aNode, aOffset);
-  } else {
-    // Use WSPoint version of GetCharAfter()
-    return GetCharAfter(WSPoint(mNodeArray[idx], aOffset, 0));
   }
+  // Use WSPoint version of GetCharAfter()
+  return GetCharAfter(WSPoint(mNodeArray[idx], aOffset, 0));
 }
 
 WSRunObject::WSPoint
 WSRunObject::GetCharBefore(nsINode* aNode,
                            int32_t aOffset)
 {
   MOZ_ASSERT(aNode);
 
   int32_t idx = mNodeArray.IndexOf(aNode);
   if (idx == -1) {
     // Use range comparisons to get right ws node
     return GetWSPointBefore(aNode, aOffset);
-  } else {
-    // Use WSPoint version of GetCharBefore()
-    return GetCharBefore(WSPoint(mNodeArray[idx], aOffset, 0));
   }
+  // Use WSPoint version of GetCharBefore()
+  return GetCharBefore(WSPoint(mNodeArray[idx], aOffset, 0));
 }
 
 WSRunObject::WSPoint
 WSRunObject::GetCharAfter(const WSPoint &aPoint)
 {
   MOZ_ASSERT(aPoint.mTextNode);
 
   WSPoint outPoint;
@@ -1395,28 +1381,31 @@ WSRunObject::GetCharAfter(const WSPoint 
   outPoint.mOffset = 0;
   outPoint.mChar = 0;
 
   int32_t idx = mNodeArray.IndexOf(aPoint.mTextNode);
   if (idx == -1) {
     // Can't find point, but it's not an error
     return outPoint;
   }
-  int32_t numNodes = mNodeArray.Length();
 
-  if (uint16_t(aPoint.mOffset) < aPoint.mTextNode->TextLength()) {
+  if (static_cast<uint16_t>(aPoint.mOffset) < aPoint.mTextNode->TextLength()) {
     outPoint = aPoint;
     outPoint.mChar = GetCharAt(aPoint.mTextNode, aPoint.mOffset);
     return outPoint;
-  } else if (idx + 1 < numNodes) {
+  }
+
+  int32_t numNodes = mNodeArray.Length();
+  if (idx + 1 < numNodes) {
     outPoint.mTextNode = mNodeArray[idx + 1];
     MOZ_ASSERT(outPoint.mTextNode);
     outPoint.mOffset = 0;
     outPoint.mChar = GetCharAt(outPoint.mTextNode, 0);
   }
+
   return outPoint;
 }
 
 WSRunObject::WSPoint
 WSRunObject::GetCharBefore(const WSPoint &aPoint)
 {
   MOZ_ASSERT(aPoint.mTextNode);
 
@@ -1426,22 +1415,24 @@ WSRunObject::GetCharBefore(const WSPoint
   outPoint.mChar = 0;
 
   int32_t idx = mNodeArray.IndexOf(aPoint.mTextNode);
   if (idx == -1) {
     // Can't find point, but it's not an error
     return outPoint;
   }
 
-  if (aPoint.mOffset != 0) {
+  if (aPoint.mOffset) {
     outPoint = aPoint;
     outPoint.mOffset--;
     outPoint.mChar = GetCharAt(aPoint.mTextNode, aPoint.mOffset - 1);
     return outPoint;
-  } else if (idx) {
+  }
+
+  if (idx) {
     outPoint.mTextNode = mNodeArray[idx - 1];
 
     uint32_t len = outPoint.mTextNode->TextLength();
     if (len) {
       outPoint.mOffset = len - 1;
       outPoint.mChar = GetCharAt(outPoint.mTextNode, len - 1);
     }
   }
@@ -1572,17 +1563,17 @@ WSRunObject::FindRun(nsINode* aNode,
       }
       return;
     }
     comp = run->mEndNode ? nsContentUtils::ComparePoints(aNode, aOffset,
         run->mEndNode, run->mEndOffset) : -1;
     if (comp < 0) {
       *outRun = run;
       return;
-    } else if (comp == 0) {
+    } else if (!comp) {
       if (after) {
         *outRun = run->mRight;
       } else {
         // before
         *outRun = run;
       }
       return;
     }
@@ -1601,19 +1592,19 @@ WSRunObject::FindRun(nsINode* aNode,
 char16_t
 WSRunObject::GetCharAt(Text* aTextNode,
                        int32_t aOffset)
 {
   // return 0 if we can't get a char, for whatever reason
   NS_ENSURE_TRUE(aTextNode, 0);
 
   int32_t len = int32_t(aTextNode->TextLength());
-  if (aOffset < 0 || aOffset >= len)
+  if (aOffset < 0 || aOffset >= len) {
     return 0;
-
+  }
   return aTextNode->GetText()->CharAt(aOffset);
 }
 
 WSRunObject::WSPoint
 WSRunObject::GetWSPointAfter(nsINode* aNode,
                              int32_t aOffset)
 {
   // Note: only to be called if aNode is not a ws node.
@@ -1913,18 +1904,17 @@ WSRunObject::CheckLeadingNBSP(WSFragment
   return NS_OK;
 }
 
 
 nsresult
 WSRunObject::Scrub()
 {
   WSFragment *run = mStartRun;
-  while (run)
-  {
+  while (run) {
     if (run->mType & (WSType::leadingWS | WSType::trailingWS)) {
       nsresult rv = DeleteChars(run->mStartNode, run->mStartOffset,
                                 run->mEndNode, run->mEndOffset);
       NS_ENSURE_SUCCESS(rv, rv);
     }
     run = run->mRight;
   }
   return NS_OK;
--- a/editor/txmgr/nsTransactionManager.cpp
+++ b/editor/txmgr/nsTransactionManager.cpp
@@ -81,18 +81,19 @@ nsTransactionManager::DoTransaction(nsIT
     DidDoNotify(aTransaction, result);
     return result;
   }
 
   result = EndTransaction(false);
 
   nsresult result2 = DidDoNotify(aTransaction, result);
 
-  if (NS_SUCCEEDED(result))
+  if (NS_SUCCEEDED(result)) {
     result = result2;
+  }
 
   return result;
 }
 
 NS_IMETHODIMP
 nsTransactionManager::UndoTransaction()
 {
   nsresult result       = NS_OK;
@@ -132,18 +133,19 @@ nsTransactionManager::UndoTransaction()
 
   if (NS_SUCCEEDED(result)) {
     tx = mUndoStack.Pop();
     mRedoStack.Push(tx.forget());
   }
 
   nsresult result2 = DidUndoNotify(t, result);
 
-  if (NS_SUCCEEDED(result))
+  if (NS_SUCCEEDED(result)) {
     result = result2;
+  }
 
   return result;
 }
 
 NS_IMETHODIMP
 nsTransactionManager::RedoTransaction()
 {
   nsresult result       = NS_OK;
@@ -183,18 +185,19 @@ nsTransactionManager::RedoTransaction()
 
   if (NS_SUCCEEDED(result)) {
     tx = mRedoStack.Pop();
     mUndoStack.Push(tx.forget());
   }
 
   nsresult result2 = DidRedoNotify(t, result);
 
-  if (NS_SUCCEEDED(result))
+  if (NS_SUCCEEDED(result)) {
     result = result2;
+  }
 
   return result;
 }
 
 NS_IMETHODIMP
 nsTransactionManager::Clear()
 {
   nsresult result;
@@ -231,18 +234,19 @@ nsTransactionManager::BeginBatch(nsISupp
   if (doInterrupt) {
     return NS_OK;
   }
 
   result = BeginTransaction(0, aData);
 
   nsresult result2 = DidBeginBatchNotify(result);
 
-  if (NS_SUCCEEDED(result))
+  if (NS_SUCCEEDED(result)) {
     result = result2;
+  }
 
   return result;
 }
 
 NS_IMETHODIMP
 nsTransactionManager::EndBatch(bool aAllowEmpty)
 {
   nsCOMPtr<nsITransaction> ti;
@@ -280,18 +284,19 @@ nsTransactionManager::EndBatch(bool aAll
   if (doInterrupt) {
     return NS_OK;
   }
 
   result = EndTransaction(aAllowEmpty);
 
   nsresult result2 = DidEndBatchNotify(result);
 
-  if (NS_SUCCEEDED(result))
+  if (NS_SUCCEEDED(result)) {
     result = result2;
+  }
 
   return result;
 }
 
 NS_IMETHODIMP
 nsTransactionManager::GetNumberOfUndoItems(int32_t *aNumItems)
 {
   *aNumItems = mUndoStack.GetSize();
@@ -343,17 +348,17 @@ nsTransactionManager::SetMaxTransactionC
   numRedoItems = mRedoStack.GetSize();
 
   total = numUndoItems + numRedoItems;
 
   // If aMaxCount is greater than the number of transactions that currently
   // exist on the undo and redo stack, there is no need to prune the
   // undo or redo stacks!
 
-  if (aMaxCount > total ) {
+  if (aMaxCount > total) {
     mMaxTransactionCount = aMaxCount;
     return NS_OK;
   }
 
   // Try getting rid of some transactions on the undo stack! Start at
   // the bottom of the stack and pop towards the top.
 
   while (numUndoItems > 0 && (numRedoItems + numUndoItems) > aMaxCount) {
@@ -517,238 +522,238 @@ nsTransactionManager::ClearRedoStack()
   mRedoStack.Clear();
   return NS_OK;
 }
 
 nsresult
 nsTransactionManager::WillDoNotify(nsITransaction *aTransaction, bool *aInterrupt)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->WillDo(this, aTransaction, aInterrupt);
 
-    if (NS_FAILED(result) || *aInterrupt)
+    if (NS_FAILED(result) || *aInterrupt) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::DidDoNotify(nsITransaction *aTransaction, nsresult aDoResult)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->DidDo(this, aTransaction, aDoResult);
 
-    if (NS_FAILED(result))
+    if (NS_FAILED(result)) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::WillUndoNotify(nsITransaction *aTransaction, bool *aInterrupt)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->WillUndo(this, aTransaction, aInterrupt);
 
-    if (NS_FAILED(result) || *aInterrupt)
+    if (NS_FAILED(result) || *aInterrupt) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::DidUndoNotify(nsITransaction *aTransaction, nsresult aUndoResult)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->DidUndo(this, aTransaction, aUndoResult);
 
-    if (NS_FAILED(result))
+    if (NS_FAILED(result)) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::WillRedoNotify(nsITransaction *aTransaction, bool *aInterrupt)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->WillRedo(this, aTransaction, aInterrupt);
 
-    if (NS_FAILED(result) || *aInterrupt)
+    if (NS_FAILED(result) || *aInterrupt) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::DidRedoNotify(nsITransaction *aTransaction, nsresult aRedoResult)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->DidRedo(this, aTransaction, aRedoResult);
 
-    if (NS_FAILED(result))
+    if (NS_FAILED(result)) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::WillBeginBatchNotify(bool *aInterrupt)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->WillBeginBatch(this, aInterrupt);
 
-    if (NS_FAILED(result) || *aInterrupt)
+    if (NS_FAILED(result) || *aInterrupt) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::DidBeginBatchNotify(nsresult aResult)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->DidBeginBatch(this, aResult);
 
-    if (NS_FAILED(result))
+    if (NS_FAILED(result)) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::WillEndBatchNotify(bool *aInterrupt)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->WillEndBatch(this, aInterrupt);
 
-    if (NS_FAILED(result) || *aInterrupt)
+    if (NS_FAILED(result) || *aInterrupt) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::DidEndBatchNotify(nsresult aResult)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->DidEndBatch(this, aResult);
 
-    if (NS_FAILED(result))
+    if (NS_FAILED(result)) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::WillMergeNotify(nsITransaction *aTop, nsITransaction *aTransaction, bool *aInterrupt)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->WillMerge(this, aTop, aTransaction, aInterrupt);
 
-    if (NS_FAILED(result) || *aInterrupt)
+    if (NS_FAILED(result) || *aInterrupt) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::DidMergeNotify(nsITransaction *aTop,
                                      nsITransaction *aTransaction,
                                      bool aDidMerge,
                                      nsresult aMergeResult)
 {
   nsresult result = NS_OK;
-  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++)
-  {
+  for (int32_t i = 0, lcount = mListeners.Count(); i < lcount; i++) {
     nsITransactionListener *listener = mListeners[i];
 
     NS_ENSURE_TRUE(listener, NS_ERROR_FAILURE);
 
     result = listener->DidMerge(this, aTop, aTransaction, aDidMerge, aMergeResult);
 
-    if (NS_FAILED(result))
+    if (NS_FAILED(result)) {
       break;
+    }
   }
 
   return result;
 }
 
 nsresult
 nsTransactionManager::BeginTransaction(nsITransaction *aTransaction,
                                        nsISupports *aData)
@@ -782,18 +787,19 @@ nsTransactionManager::BeginTransaction(n
 
 nsresult
 nsTransactionManager::EndTransaction(bool aAllowEmpty)
 {
   nsresult result              = NS_OK;
 
   RefPtr<nsTransactionItem> tx = mDoStack.Pop();
 
-  if (!tx)
+  if (!tx) {
     return NS_ERROR_FAILURE;
+  }
 
   nsCOMPtr<nsITransaction> tint = tx->GetTransaction();
 
   if (!tint && !aAllowEmpty) {
     int32_t nc = 0;
 
     // If we get here, the transaction must be a dummy batch transaction
     // created by BeginBatch(). If it contains no children, get rid of it!
@@ -805,18 +811,19 @@ nsTransactionManager::EndTransaction(boo
     }
   }
 
   // Check if the transaction is transient. If it is, there's nothing
   // more to do, just return.
 
   bool isTransient = false;
 
-  if (tint)
+  if (tint) {
     result = tint->GetIsTransient(&isTransient);
+  }
 
   if (NS_FAILED(result) || isTransient || !mMaxTransactionCount) {
     // XXX: Should we be clearing the redo stack if the transaction
     //      is transient and there is nothing on the do stack?
     return result;
   }
 
   // Check if there is a transaction on the do stack. If there is,
@@ -857,18 +864,19 @@ nsTransactionManager::EndTransaction(boo
 
       NS_ENSURE_SUCCESS(result, result);
 
       if (!doInterrupt) {
         result = topTransaction->Merge(tint, &didMerge);
 
         nsresult result2 = DidMergeNotify(topTransaction, tint, didMerge, result);
 
-        if (NS_SUCCEEDED(result))
+        if (NS_SUCCEEDED(result)) {
           result = result2;
+        }
 
         if (NS_FAILED(result)) {
           // XXX: What do we do if this fails?
         }
 
         if (didMerge) {
           return result;
         }
--- a/editor/txmgr/tests/TestTXMgr.cpp
+++ b/editor/txmgr/tests/TestTXMgr.cpp
@@ -531,27 +531,27 @@ public:
     printf("\nSimpleTransaction.Redo: %d - 0x%.8x\n", mVal, (int32_t)this);
 #endif // ENABLE_DEBUG_PRINTFS
 
     return (mFlags & THROWS_REDO_ERROR_FLAG) ? NS_ERROR_FAILURE : NS_OK;
   }
 
   NS_IMETHOD GetIsTransient(bool *aIsTransient)
   {
-    if (aIsTransient)
+    if (aIsTransient) {
       *aIsTransient = (mFlags & TRANSIENT_FLAG) ? true : false;
-
+    }
     return NS_OK;
   }
 
   NS_IMETHOD Merge(nsITransaction *aTransaction, bool *aDidMerge)
   {
-    if (aDidMerge)
+    if (aDidMerge) {
       *aDidMerge = (mFlags & MERGE_FLAG) ? true : false;
-
+    }
     return NS_OK;
   }
 };
 
 class AggregateTransaction : public SimpleTransaction
 {
 private:
 
@@ -628,71 +628,70 @@ public:
 
     for (int i = 1; i <= mNumChildrenPerNode; i++) {
       int32_t flags = mErrorFlags & THROWS_DO_ERROR_FLAG;
 
       if ((mErrorFlags & THROWS_REDO_ERROR_FLAG) && i == mNumChildrenPerNode) {
         // Make the rightmost leaf transaction throw the error!
         flags = THROWS_REDO_ERROR_FLAG;
         mErrorFlags = mErrorFlags & (~THROWS_REDO_ERROR_FLAG);
-      }
-      else if ((mErrorFlags & THROWS_UNDO_ERROR_FLAG)
-               && i == 1) {
+      } else if ((mErrorFlags & THROWS_UNDO_ERROR_FLAG) && i == 1) {
         // Make the leftmost leaf transaction throw the error!
         flags = THROWS_UNDO_ERROR_FLAG;
         mErrorFlags = mErrorFlags & (~THROWS_UNDO_ERROR_FLAG);
       }
 
       flags |= mFlags & BATCH_FLAG;
 
       AggregateTransaction *tximpl =
               new AggregateTransaction(mTXMgr, cLevel, i, mMaxLevel,
                                        mNumChildrenPerNode, flags);
 
       if (!tximpl) {
         fail("Failed to allocate AggregateTransaction %d, level %d. (%d)\n",
              i, mLevel, result);
 
-        if (mFlags & BATCH_FLAG)
+        if (mFlags & BATCH_FLAG) {
           mTXMgr->EndBatch(false);
+        }
 
         return NS_ERROR_OUT_OF_MEMORY;
       }
 
       nsITransaction *tx = 0;
       result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx);
       if (NS_FAILED(result)) {
         fail("QueryInterface() failed for transaction %d, level %d. (%d)\n",
              i, mLevel, result);
 
-        if (mFlags & BATCH_FLAG)
+        if (mFlags & BATCH_FLAG) {
           mTXMgr->EndBatch(false);
-
+        }
         return result;
       }
 
       result = mTXMgr->DoTransaction(tx);
 
       if (NS_FAILED(result)) {
         // fail("Failed to execute transaction %d, level %d. (%d)\n",
         //      i, mLevel, result);
         tx->Release();
 
-        if (mFlags & BATCH_FLAG)
+        if (mFlags & BATCH_FLAG) {
           mTXMgr->EndBatch(false);
-
+        }
         return result;
       }
 
       tx->Release();
     }
 
-    if (mFlags & BATCH_FLAG)
+    if (mFlags & BATCH_FLAG) {
       mTXMgr->EndBatch(false);
-
+    }
     return result;
   }
 };
 
 class TestTransactionFactory
 {
 public:
   virtual TestTransaction *create(nsITransactionManager *txmgr, int32_t flags) = 0;
@@ -889,17 +888,17 @@ quick_test(TestTransactionFactory *facto
   result = mgr->GetNumberOfUndoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfUndoItems() on empty undo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Call GetNumberOfUndoItems() with empty undo stack");
 
   /*******************************************************************
@@ -911,17 +910,17 @@ quick_test(TestTransactionFactory *facto
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Call GetNumberOfRedoItems() with empty redo stack");
 
   nsITransaction *tx;
@@ -937,17 +936,17 @@ quick_test(TestTransactionFactory *facto
 
   TEST_TXMGR_IF_RELEASE(tx); // Don't hold onto any references!
 
   if (NS_FAILED(result)) {
     fail("PeekUndoStack() on empty undo stack failed. (%d)\n", result);
     return result;
   }
 
-  if (tx != 0) {
+  if (tx) {
     fail("PeekUndoStack() on empty undo stack failed. (%d)\n", result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Call PeekUndoStack() with empty undo stack");
 
   /*******************************************************************
    *
@@ -960,17 +959,17 @@ quick_test(TestTransactionFactory *facto
 
   TEST_TXMGR_IF_RELEASE(tx); // Don't hold onto any references!
 
   if (NS_FAILED(result)) {
     fail("PeekRedoStack() on empty redo stack failed. (%d)\n", result);
     return result;
   }
 
-  if (tx != 0) {
+  if (tx) {
     fail("PeekRedoStack() on empty redo stack failed. (%d)\n", result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Call PeekRedoStack() with empty undo stack");
 
   /*******************************************************************
    *
@@ -1145,17 +1144,17 @@ quick_test(TestTransactionFactory *facto
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   result = mgr->Clear();
   if (NS_FAILED(result)) {
     fail("Clear() failed. (%d)\n", result);
@@ -1213,17 +1212,17 @@ quick_test(TestTransactionFactory *facto
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Execute 20 transactions");
 
   /*******************************************************************
@@ -1323,17 +1322,17 @@ quick_test(TestTransactionFactory *facto
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Execute 20 transient transactions");
 
   /*******************************************************************
@@ -1473,17 +1472,17 @@ quick_test(TestTransactionFactory *facto
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Check if new transactions prune the redo stack");
 
   /*******************************************************************
@@ -1537,31 +1536,31 @@ quick_test(TestTransactionFactory *facto
   result = mgr->GetNumberOfUndoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfUndoItems() on cleared undo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on cleared redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Undo 4 transactions then clear the undo and redo stacks");
 
   /*******************************************************************
@@ -1612,17 +1611,17 @@ quick_test(TestTransactionFactory *facto
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Execute 5 transactions");
 
   /*******************************************************************
@@ -1721,17 +1720,17 @@ quick_test(TestTransactionFactory *facto
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Test transaction DoTransaction() error");
 
   /*******************************************************************
@@ -1837,17 +1836,17 @@ quick_test(TestTransactionFactory *facto
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Test transaction UndoTransaction() error");
 
   /*******************************************************************
@@ -2030,31 +2029,31 @@ quick_test(TestTransactionFactory *facto
   result = mgr->GetNumberOfUndoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfUndoItems() on empty undo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   for (i = 1; i <= 20; i++) {
     tximpl = factory->create(mgr, NONE_FLAG);
 
@@ -2082,31 +2081,31 @@ quick_test(TestTransactionFactory *facto
     result = mgr->GetNumberOfUndoItems(&numitems);
 
     if (NS_FAILED(result)) {
       fail("GetNumberOfUndoItems() on empty undo stack failed. (%d)\n",
            result);
       return result;
     }
 
-    if (numitems != 0) {
+    if (numitems) {
       fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
            numitems, result);
       return NS_ERROR_FAILURE;
     }
 
     result = mgr->GetNumberOfRedoItems(&numitems);
 
     if (NS_FAILED(result)) {
       fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
            result);
       return result;
     }
 
-    if (numitems != 0) {
+    if (numitems) {
       fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
            numitems, result);
       return NS_ERROR_FAILURE;
     }
   }
 
   passed("Test max transaction count of zero");
 
@@ -2168,17 +2167,17 @@ quick_test(TestTransactionFactory *facto
     result = mgr->GetNumberOfRedoItems(&numitems);
 
     if (NS_FAILED(result)) {
       fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
            result);
       return result;
     }
 
-    if (numitems != 0) {
+    if (numitems) {
       fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
            numitems, result);
       return NS_ERROR_FAILURE;
     }
   }
 
   for (i = 1; i <= 10; i++) {
 
@@ -2544,17 +2543,17 @@ quick_test(TestTransactionFactory *facto
     result = mgr->GetNumberOfRedoItems(&numitems);
 
     if (NS_FAILED(result)) {
       fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
            result);
       return result;
     }
 
-    if (numitems != 0) {
+    if (numitems) {
       fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
            numitems, result);
       return NS_ERROR_FAILURE;
     }
   }
 
   for (i = 1; i <= 10; i++) {
 
@@ -2715,17 +2714,17 @@ quick_batch_test(TestTransactionFactory 
   result = mgr->GetNumberOfUndoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfUndoItems() on empty undo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   result = mgr->EndBatch(false);
 
   if (result != NS_ERROR_FAILURE) {
@@ -2736,17 +2735,17 @@ quick_batch_test(TestTransactionFactory 
   result = mgr->GetNumberOfUndoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfUndoItems() on empty undo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Test unbalanced EndBatch(false) with empty undo stack");
 
   /*******************************************************************
@@ -2759,17 +2758,17 @@ quick_batch_test(TestTransactionFactory 
   result = mgr->GetNumberOfUndoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfUndoItems() on empty undo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   result = mgr->BeginBatch(nullptr);
 
   if (NS_FAILED(result)) {
@@ -2780,17 +2779,17 @@ quick_batch_test(TestTransactionFactory 
   result = mgr->GetNumberOfUndoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfUndoItems() on empty undo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   result = mgr->EndBatch(false);
 
   if (NS_FAILED(result)) {
@@ -2801,17 +2800,17 @@ quick_batch_test(TestTransactionFactory 
   result = mgr->GetNumberOfUndoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfUndoItems() on empty undo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Test empty batch");
 
   int32_t i;
@@ -3008,17 +3007,17 @@ quick_batch_test(TestTransactionFactory 
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Execute 20 batched transient transactions");
 
   /*******************************************************************
@@ -3212,17 +3211,17 @@ quick_batch_test(TestTransactionFactory 
   result = mgr->GetNumberOfUndoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfUndoItems() on empty undo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
@@ -3271,17 +3270,17 @@ quick_batch_test(TestTransactionFactory 
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Redo 2 batch transactions");
 
   /*******************************************************************
@@ -3542,17 +3541,17 @@ quick_batch_test(TestTransactionFactory 
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Check if new batched transactions prune the redo stack");
 
   /*******************************************************************
@@ -3841,17 +3840,17 @@ quick_batch_test(TestTransactionFactory 
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   passed("Test transaction UndoTransaction() error");
 
   /*******************************************************************
@@ -4048,31 +4047,31 @@ quick_batch_test(TestTransactionFactory 
   result = mgr->GetNumberOfUndoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfUndoItems() on empty undo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   result = mgr->GetNumberOfRedoItems(&numitems);
 
   if (NS_FAILED(result)) {
     fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
          result);
     return result;
   }
 
-  if (numitems != 0) {
+  if (numitems) {
     fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
          numitems, result);
     return NS_ERROR_FAILURE;
   }
 
   for (i = 1; i <= 20; i++) {
     tximpl = factory->create(mgr, NONE_FLAG);
 
@@ -4114,31 +4113,31 @@ quick_batch_test(TestTransactionFactory 
     result = mgr->GetNumberOfUndoItems(&numitems);
 
     if (NS_FAILED(result)) {
       fail("GetNumberOfUndoItems() on empty undo stack failed. (%d)\n",
            result);
       return result;
     }
 
-    if (numitems != 0) {
+    if (numitems) {
       fail("GetNumberOfUndoItems() expected 0 got %d. (%d)\n",
            numitems, result);
       return NS_ERROR_FAILURE;
     }
 
     result = mgr->GetNumberOfRedoItems(&numitems);
 
     if (NS_FAILED(result)) {
       fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
            result);
       return result;
     }
 
-    if (numitems != 0) {
+    if (numitems) {
       fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
            numitems, result);
       return NS_ERROR_FAILURE;
     }
   }
 
   passed("Test max transaction count of zero");
 
@@ -4213,17 +4212,17 @@ quick_batch_test(TestTransactionFactory 
     result = mgr->GetNumberOfRedoItems(&numitems);
 
     if (NS_FAILED(result)) {
       fail("GetNumberOfRedoItems() on empty redo stack failed. (%d)\n",
            result);
       return result;
     }
 
-    if (numitems != 0) {
+    if (numitems) {
       fail("GetNumberOfRedoItems() expected 0 got %d. (%d)\n",
            numitems, result);
       return NS_ERROR_FAILURE;
     }
   }
 
   for (i = 1; i <= 10; i++) {
 
@@ -4451,18 +4450,19 @@ stress_test(TestTransactionFactory *fact
       result = mgr->UndoTransaction();
       if (NS_FAILED(result)) {
         fail("Failed to undo transaction %d-%d. (%d)\n", i, j, result);
         return result;
       }
     }
 
     // Trivial feedback not to let the user think the test is stuck.
-    if (MOZ_UNLIKELY(j % 100 == 0))
+    if (MOZ_UNLIKELY(j % 100 == 0)) {
       printf("%i ", j);
+    }
   } // for, iterations.
 
   printf("passed\n");
 
   result = mgr->Clear();
   if (NS_FAILED(result)) {
     fail("Clear() failed. (%d)\n", result);
     return result;
@@ -4593,18 +4593,19 @@ aggregation_batch_stress_test()
   ;
   return stress_test(&factory, iterations);
 }
 
 int
 main (int argc, char *argv[])
 {
   ScopedXPCOM xpcom("nsITransactionManager");
-  if (xpcom.failed())
+  if (xpcom.failed()) {
     return 1;
+  }
 
   nsresult result;
 
   //
   // quick_test() part:
   //
 
   result = simple_test();
--- a/editor/txtsvc/nsTextServicesDocument.cpp
+++ b/editor/txtsvc/nsTextServicesDocument.cpp
@@ -46,21 +46,22 @@ using namespace mozilla::dom;
 
 class OffsetEntry
 {
 public:
   OffsetEntry(nsIDOMNode *aNode, int32_t aOffset, int32_t aLength)
     : mNode(aNode), mNodeOffset(0), mStrOffset(aOffset), mLength(aLength),
       mIsInsertedText(false), mIsValid(true)
   {
-    if (mStrOffset < 1)
+    if (mStrOffset < 1) {
       mStrOffset = 0;
-
-    if (mLength < 1)
+    }
+    if (mLength < 1) {
       mLength = 0;
+    }
   }
 
   virtual ~OffsetEntry()
   {
     mNode       = 0;
     mNodeOffset = 0;
     mStrOffset  = 0;
     mLength     = 0;
@@ -141,66 +142,60 @@ nsTextServicesDocument::InitWithEditor(n
 
   LOCK_DOC(this);
 
   // Check to see if we already have an mSelCon. If we do, it
   // better be the same one the editor uses!
 
   result = aEditor->GetSelectionController(getter_AddRefs(selCon));
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
-  if (!selCon || (mSelCon && selCon != mSelCon))
-  {
+  if (!selCon || (mSelCon && selCon != mSelCon)) {
     UNLOCK_DOC(this);
     return NS_ERROR_FAILURE;
   }
 
-  if (!mSelCon)
+  if (!mSelCon) {
     mSelCon = selCon;
+  }
 
   // Check to see if we already have an mDOMDocument. If we do, it
   // better be the same one the editor uses!
 
   result = aEditor->GetDocument(getter_AddRefs(doc));
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
-  if (!doc || (mDOMDocument && doc != mDOMDocument))
-  {
+  if (!doc || (mDOMDocument && doc != mDOMDocument)) {
     UNLOCK_DOC(this);
     return NS_ERROR_FAILURE;
   }
 
-  if (!mDOMDocument)
-  {
+  if (!mDOMDocument) {
     mDOMDocument = doc;
 
     result = CreateDocumentContentIterator(getter_AddRefs(mIterator));
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       UNLOCK_DOC(this);
       return result;
     }
 
     mIteratorStatus = nsTextServicesDocument::eIsDone;
 
     result = FirstBlock();
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       UNLOCK_DOC(this);
       return result;
     }
   }
 
   mEditor = do_GetWeakReference(aEditor);
 
   result = aEditor->AddEditActionListener(this);
@@ -236,18 +231,17 @@ nsTextServicesDocument::SetExtent(nsIDOM
   // know where it came from.
 
   mExtent = static_cast<nsRange*>(aDOMRange)->CloneRange();
 
   // Create a new iterator based on our new extent range.
 
   nsresult result = CreateContentIterator(mExtent, getter_AddRefs(mIterator));
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
   // Now position the iterator at the start of the first block
   // in the range.
 
   mIteratorStatus = nsTextServicesDocument::eIsDone;
@@ -286,58 +280,54 @@ nsTextServicesDocument::ExpandRangeToWor
 
   // Find the first text node in the range.
 
   TSDIteratorStatus iterStatus;
 
   result = FirstTextNode(iter, &iterStatus);
   NS_ENSURE_SUCCESS(result, result);
 
-  if (iterStatus == nsTextServicesDocument::eIsDone)
-  {
+  if (iterStatus == nsTextServicesDocument::eIsDone) {
     // No text was found so there's no adjustment necessary!
     return NS_OK;
   }
 
   nsINode *firstText = iter->GetCurrentNode();
   NS_ENSURE_TRUE(firstText, NS_ERROR_FAILURE);
 
   // Find the last text node in the range.
 
   result = LastTextNode(iter, &iterStatus);
   NS_ENSURE_SUCCESS(result, result);
 
-  if (iterStatus == nsTextServicesDocument::eIsDone)
-  {
+  if (iterStatus == nsTextServicesDocument::eIsDone) {
     // We should never get here because a first text block
     // was found above.
     NS_ASSERTION(false, "Found a first without a last!");
     return NS_ERROR_FAILURE;
   }
 
   nsINode *lastText = iter->GetCurrentNode();
   NS_ENSURE_TRUE(lastText, NS_ERROR_FAILURE);
 
   // Now make sure our end points are in terms of text nodes in the range!
 
   nsCOMPtr<nsIDOMNode> firstTextNode = do_QueryInterface(firstText);
   NS_ENSURE_TRUE(firstTextNode, NS_ERROR_FAILURE);
 
-  if (rngStartNode != firstTextNode)
-  {
+  if (rngStartNode != firstTextNode) {
     // The range includes the start of the first text node!
     rngStartNode = firstTextNode;
     rngStartOffset = 0;
   }
 
   nsCOMPtr<nsIDOMNode> lastTextNode = do_QueryInterface(lastText);
   NS_ENSURE_TRUE(lastTextNode, NS_ERROR_FAILURE);
 
-  if (rngEndNode != lastTextNode)
-  {
+  if (rngEndNode != lastTextNode) {
     // The range includes the end of the last text node!
     rngEndNode = lastTextNode;
     nsAutoString str;
     result = lastTextNode->GetNodeValue(str);
     rngEndOffset = str.Length();
   }
 
   // Create a doc iterator so that we can scan beyond
@@ -355,18 +345,17 @@ nsTextServicesDocument::ExpandRangeToWor
 
   iterStatus = nsTextServicesDocument::eValid;
 
   nsTArray<OffsetEntry*> offsetTable;
   nsAutoString blockStr;
 
   result = CreateOffsetTable(&offsetTable, docIter, &iterStatus,
                              nullptr, &blockStr);
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     ClearOffsetTable(&offsetTable);
     return result;
   }
 
   nsCOMPtr<nsIDOMNode> wordStartNode, wordEndNode;
   int32_t wordStartOffset, wordEndOffset;
 
   result = FindWordBounds(&offsetTable, &blockStr,
@@ -386,18 +375,17 @@ nsTextServicesDocument::ExpandRangeToWor
 
   result = docIter->PositionAt(lastText);
   NS_ENSURE_SUCCESS(result, result);
 
   iterStatus = nsTextServicesDocument::eValid;
 
   result = CreateOffsetTable(&offsetTable, docIter, &iterStatus,
                              nullptr, &blockStr);
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     ClearOffsetTable(&offsetTable);
     return result;
   }
 
   result = FindWordBounds(&offsetTable, &blockStr,
                           rngEndNode, rngEndOffset,
                           getter_AddRefs(wordStartNode), &wordStartOffset,
                           getter_AddRefs(wordEndNode), &wordEndOffset);
@@ -405,19 +393,19 @@ nsTextServicesDocument::ExpandRangeToWor
   ClearOffsetTable(&offsetTable);
 
   NS_ENSURE_SUCCESS(result, result);
 
   // To prevent expanding the range too much, we only change
   // rngEndNode and rngEndOffset if it isn't already at the start of the
   // word and isn't equivalent to rngStartNode and rngStartOffset.
 
-  if (rngEndNode != wordStartNode || rngEndOffset != wordStartOffset ||
-     (rngEndNode == rngStartNode  && rngEndOffset == rngStartOffset))
-  {
+  if (rngEndNode != wordStartNode ||
+      rngEndOffset != wordStartOffset ||
+      (rngEndNode == rngStartNode && rngEndOffset == rngStartOffset)) {
     rngEndNode = wordEndNode;
     rngEndOffset = wordEndOffset;
   }
 
   // Now adjust the range so that it uses our new
   // end points.
 
   result = range->SetEnd(rngEndNode, rngEndOffset);
@@ -460,32 +448,28 @@ NS_IMETHODIMP
 nsTextServicesDocument::FirstBlock()
 {
   NS_ENSURE_TRUE(mIterator, NS_ERROR_FAILURE);
 
   LOCK_DOC(this);
 
   nsresult result = FirstTextNode(mIterator, &mIteratorStatus);
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
   // Keep track of prev and next blocks, just in case
   // the text service blows away the current block.
 
-  if (mIteratorStatus == nsTextServicesDocument::eValid)
-  {
+  if (mIteratorStatus == nsTextServicesDocument::eValid) {
     mPrevTextBlock  = nullptr;
     result = GetFirstTextNodeInNextBlock(getter_AddRefs(mNextTextBlock));
-  }
-  else
-  {
+  } else {
     // There's no text block in the document!
 
     mPrevTextBlock  = nullptr;
     mNextTextBlock  = nullptr;
   }
 
   UNLOCK_DOC(this);
 
@@ -503,221 +487,197 @@ nsTextServicesDocument::LastSelectedBloc
 
   LOCK_DOC(this);
 
   mIteratorStatus = nsTextServicesDocument::eIsDone;
 
   *aSelStatus = nsITextServicesDocument::eBlockNotFound;
   *aSelOffset = *aSelLength = -1;
 
-  if (!mSelCon || !mIterator)
-  {
+  if (!mSelCon || !mIterator) {
     UNLOCK_DOC(this);
     return NS_ERROR_FAILURE;
   }
 
   nsCOMPtr<nsISelection> domSelection;
   result = mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
                                  getter_AddRefs(domSelection));
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
   RefPtr<Selection> selection = domSelection->AsSelection();
 
   bool isCollapsed = selection->IsCollapsed();
 
   nsCOMPtr<nsIContentIterator> iter;
   RefPtr<nsRange> range;
   nsCOMPtr<nsIDOMNode>         parent;
-  int32_t                      i, rangeCount, offset;
-
-  if (isCollapsed)
-  {
+  int32_t rangeCount, offset;
+
+  if (isCollapsed) {
     // We have a caret. Check if the caret is in a text node.
     // If it is, make the text node's block the current block.
     // If the caret isn't in a text node, search forwards in
     // the document, till we find a text node.
 
     range = selection->GetRangeAt(0);
 
-    if (!range)
-    {
+    if (!range) {
       UNLOCK_DOC(this);
       return NS_ERROR_FAILURE;
     }
 
     result = range->GetStartContainer(getter_AddRefs(parent));
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       UNLOCK_DOC(this);
       return result;
     }
 
-    if (!parent)
-    {
+    if (!parent) {
       UNLOCK_DOC(this);
       return NS_ERROR_FAILURE;
     }
 
     result = range->GetStartOffset(&offset);
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       UNLOCK_DOC(this);
       return result;
     }
 
-    if (IsTextNode(parent))
-    {
+    if (IsTextNode(parent)) {
       // The caret is in a text node. Find the beginning
       // of the text block containing this text node and
       // return.
 
       nsCOMPtr<nsIContent> content(do_QueryInterface(parent));
 
-      if (!content)
-      {
+      if (!content) {
         UNLOCK_DOC(this);
         return NS_ERROR_FAILURE;
       }
 
       result = mIterator->PositionAt(content);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       result = FirstTextNodeInCurrentBlock(mIterator);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       mIteratorStatus = nsTextServicesDocument::eValid;
 
       result = CreateOffsetTable(&mOffsetTable, mIterator, &mIteratorStatus,
                                  mExtent, nullptr);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       result = GetSelection(aSelStatus, aSelOffset, aSelLength);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       if (*aSelStatus == nsITextServicesDocument::eBlockContains)
         result = SetSelectionInternal(*aSelOffset, *aSelLength, false);
-    }
-    else
-    {
+    } else {
       // The caret isn't in a text node. Create an iterator
       // based on a range that extends from the current caret
       // position to the end of the document, then walk forwards
       // till you find a text node, then find the beginning of it's block.
 
       result = CreateDocumentContentRootToNodeOffsetRange(parent, offset, false, getter_AddRefs(range));
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       result = range->GetCollapsed(&isCollapsed);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
-      if (isCollapsed)
-      {
+      if (isCollapsed) {
         // If we get here, the range is collapsed because there is nothing after
         // the caret! Just return NS_OK;
 
         UNLOCK_DOC(this);
         return NS_OK;
       }
 
       result = CreateContentIterator(range, getter_AddRefs(iter));
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       iter->First();
 
       nsCOMPtr<nsIContent> content;
-      while (!iter->IsDone())
-      {
+      while (!iter->IsDone()) {
         content = do_QueryInterface(iter->GetCurrentNode());
 
-        if (IsTextNode(content))
+        if (IsTextNode(content)) {
           break;
+        }
 
         content = nullptr;
 
         iter->Next();
       }
 
-      if (!content)
-      {
+      if (!content) {
         UNLOCK_DOC(this);
         return NS_OK;
       }
 
       result = mIterator->PositionAt(content);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       result = FirstTextNodeInCurrentBlock(mIterator);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       mIteratorStatus = nsTextServicesDocument::eValid;
 
       result = CreateOffsetTable(&mOffsetTable, mIterator, &mIteratorStatus,
                                  mExtent, nullptr);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       result = GetSelection(aSelStatus, aSelOffset, aSelLength);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
     }
 
     UNLOCK_DOC(this);
 
     return result;
@@ -726,89 +686,81 @@ nsTextServicesDocument::LastSelectedBloc
   // If we get here, we have an uncollapsed selection!
   // Look backwards through each range in the selection till you
   // find the first text node. If you find one, find the
   // beginning of its text block, and make it the current
   // block.
 
   result = selection->GetRangeCount(&rangeCount);
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
   NS_ASSERTION(rangeCount > 0, "Unexpected range count!");
 
-  if (rangeCount <= 0)
-  {
+  if (rangeCount <= 0) {
     UNLOCK_DOC(this);
     return NS_OK;
   }
 
   // XXX: We may need to add some code here to make sure
   //      the ranges are sorted in document appearance order!
 
-  for (i = rangeCount - 1; i >= 0; i--)
-  {
+  for (int32_t i = rangeCount - 1; i >= 0; i--) {
     // Get the i'th range from the selection.
 
     range = selection->GetRangeAt(i);
 
     if (!range) {
       UNLOCK_DOC(this);
       return result;
     }
 
     // Create an iterator for the range.
 
     result = CreateContentIterator(range, getter_AddRefs(iter));
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       UNLOCK_DOC(this);
       return result;
     }
 
     iter->Last();
 
     // Now walk through the range till we find a text node.
 
-    while (!iter->IsDone())
-    {
+    while (!iter->IsDone()) {
       if (iter->GetCurrentNode()->NodeType() == nsIDOMNode::TEXT_NODE) {
         // We found a text node, so position the document's
         // iterator at the beginning of the block, then get
         // the selection in terms of the string offset.
         nsCOMPtr<nsIContent> content = iter->GetCurrentNode()->AsContent();
 
         result = mIterator->PositionAt(content);
 
-        if (NS_FAILED(result))
-        {
+        if (NS_FAILED(result)) {
           UNLOCK_DOC(this);
           return result;
         }
 
         result = FirstTextNodeInCurrentBlock(mIterator);
 
-        if (NS_FAILED(result))
-        {
+        if (NS_FAILED(result)) {
           UNLOCK_DOC(this);
           return result;
         }
 
         mIteratorStatus = nsTextServicesDocument::eValid;
 
         result = CreateOffsetTable(&mOffsetTable, mIterator, &mIteratorStatus,
                                    mExtent, nullptr);
 
-        if (NS_FAILED(result))
-        {
+        if (NS_FAILED(result)) {
           UNLOCK_DOC(this);
           return result;
         }
 
         result = GetSelection(aSelStatus, aSelOffset, aSelLength);
 
         UNLOCK_DOC(this);
 
@@ -822,110 +774,98 @@ nsTextServicesDocument::LastSelectedBloc
 
   // If we get here, we didn't find any text node in the selection!
   // Create a range that extends from the end of the selection,
   // to the end of the document, then iterate forwards through
   // it till you find a text node!
 
   range = selection->GetRangeAt(rangeCount - 1);
 
-  if (!range)
-  {
+  if (!range) {
     UNLOCK_DOC(this);
     return NS_ERROR_FAILURE;
   }
 
   result = range->GetEndContainer(getter_AddRefs(parent));
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
-  if (!parent)
-  {
+  if (!parent) {
     UNLOCK_DOC(this);
     return NS_ERROR_FAILURE;
   }
 
   result = range->GetEndOffset(&offset);
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
   result = CreateDocumentContentRootToNodeOffsetRange(parent, offset, false, getter_AddRefs(range));
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
   result = range->GetCollapsed(&isCollapsed);
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
-  if (isCollapsed)
-  {
+  if (isCollapsed) {
     // If we get here, the range is collapsed because there is nothing after
     // the current selection! Just return NS_OK;
 
     UNLOCK_DOC(this);
     return NS_OK;
   }
 
   result = CreateContentIterator(range, getter_AddRefs(iter));
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
   iter->First();
 
-  while (!iter->IsDone())
-  {
+  while (!iter->IsDone()) {
     if (iter->GetCurrentNode()->NodeType() == nsIDOMNode::TEXT_NODE) {
       // We found a text node! Adjust the document's iterator to point
       // to the beginning of its text block, then get the current selection.
       nsCOMPtr<nsIContent> content = iter->GetCurrentNode()->AsContent();
 
       result = mIterator->PositionAt(content);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       result = FirstTextNodeInCurrentBlock(mIterator);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
 
       mIteratorStatus = nsTextServicesDocument::eValid;
 
       result = CreateOffsetTable(&mOffsetTable, mIterator, &mIteratorStatus,
                                  mExtent, nullptr);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       result = GetSelection(aSelStatus, aSelOffset, aSelLength);
 
       UNLOCK_DOC(this);
 
@@ -947,35 +887,33 @@ NS_IMETHODIMP
 nsTextServicesDocument::PrevBlock()
 {
   nsresult result = NS_OK;
 
   NS_ENSURE_TRUE(mIterator, NS_ERROR_FAILURE);
 
   LOCK_DOC(this);
 
-  if (mIteratorStatus == nsTextServicesDocument::eIsDone)
+  if (mIteratorStatus == nsTextServicesDocument::eIsDone) {
     return NS_OK;
-
-  switch (mIteratorStatus)
-  {
+  }
+
+  switch (mIteratorStatus) {
     case nsTextServicesDocument::eValid:
     case nsTextServicesDocument::eNext:
 
       result = FirstTextNodeInPrevBlock(mIterator);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         mIteratorStatus = nsTextServicesDocument::eIsDone;
         UNLOCK_DOC(this);
         return result;
       }
 
-      if (mIterator->IsDone())
-      {
+      if (mIterator->IsDone()) {
         mIteratorStatus = nsTextServicesDocument::eIsDone;
         UNLOCK_DOC(this);
         return NS_OK;
       }
 
       mIteratorStatus = nsTextServicesDocument::eValid;
       break;
 
@@ -991,25 +929,21 @@ nsTextServicesDocument::PrevBlock()
 
       mIteratorStatus = nsTextServicesDocument::eIsDone;
       break;
   }
 
   // Keep track of prev and next blocks, just in case
   // the text service blows away the current block.
 
-  if (mIteratorStatus == nsTextServicesDocument::eValid)
-  {
+  if (mIteratorStatus == nsTextServicesDocument::eValid) {
     result = GetFirstTextNodeInPrevBlock(getter_AddRefs(mPrevTextBlock));
     result = GetFirstTextNodeInNextBlock(getter_AddRefs(mNextTextBlock));
-  }
-  else
-  {
+  } else {
     // We must be done!
-
     mPrevTextBlock = nullptr;
     mNextTextBlock = nullptr;
   }
 
   UNLOCK_DOC(this);
 
   return result;
 }
@@ -1018,36 +952,34 @@ NS_IMETHODIMP
 nsTextServicesDocument::NextBlock()
 {
   nsresult result = NS_OK;
 
   NS_ENSURE_TRUE(mIterator, NS_ERROR_FAILURE);
 
   LOCK_DOC(this);
 
-  if (mIteratorStatus == nsTextServicesDocument::eIsDone)
+  if (mIteratorStatus == nsTextServicesDocument::eIsDone) {
     return NS_OK;
-
-  switch (mIteratorStatus)
-  {
+  }
+
+  switch (mIteratorStatus) {
     case nsTextServicesDocument::eValid:
 
       // Advance the iterator to the next text block.
 
       result = FirstTextNodeInNextBlock(mIterator);
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         mIteratorStatus = nsTextServicesDocument::eIsDone;
         UNLOCK_DOC(this);
         return result;
       }
 
-      if (mIterator->IsDone())
-      {
+      if (mIterator->IsDone()) {
         mIteratorStatus = nsTextServicesDocument::eIsDone;
         UNLOCK_DOC(this);
         return NS_OK;
       }
 
       mIteratorStatus = nsTextServicesDocument::eValid;
       break;
 
@@ -1069,30 +1001,25 @@ nsTextServicesDocument::NextBlock()
 
       mIteratorStatus = nsTextServicesDocument::eIsDone;
       break;
   }
 
   // Keep track of prev and next blocks, just in case
   // the text service blows away the current block.
 
-  if (mIteratorStatus == nsTextServicesDocument::eValid)
-  {
+  if (mIteratorStatus == nsTextServicesDocument::eValid) {
     result = GetFirstTextNodeInPrevBlock(getter_AddRefs(mPrevTextBlock));
     result = GetFirstTextNodeInNextBlock(getter_AddRefs(mNextTextBlock));
-  }
-  else
-  {
+  } else {
     // We must be done.
-
     mPrevTextBlock = nullptr;
     mNextTextBlock = nullptr;
   }
 
-
   UNLOCK_DOC(this);
 
   return result;
 }
 
 NS_IMETHODIMP
 nsTextServicesDocument::IsDone(bool *aIsDone)
 {
@@ -1155,208 +1082,188 @@ nsTextServicesDocument::DeleteSelection(
 {
   nsresult result = NS_OK;
 
   // We don't allow deletion during a collapsed selection!
   nsCOMPtr<nsIEditor> editor (do_QueryReferent(mEditor));
   NS_ASSERTION(editor, "DeleteSelection called without an editor present!");
   NS_ASSERTION(SelectionIsValid(), "DeleteSelection called without a valid selection!");
 
-  if (!editor || !SelectionIsValid())
+  if (!editor || !SelectionIsValid()) {
     return NS_ERROR_FAILURE;
-
-  if (SelectionIsCollapsed())
+  }
+  if (SelectionIsCollapsed()) {
     return NS_OK;
+  }
 
   LOCK_DOC(this);
 
   //**** KDEBUG ****
   // printf("\n---- Before Delete\n");
   // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
   // PrintOffsetTable();
   //**** KDEBUG ****
 
   // If we have an mExtent, save off its current set of
   // end points so we can compare them against mExtent's
   // set after the deletion of the content.
 
   nsCOMPtr<nsIDOMNode> origStartNode, origEndNode;
   int32_t origStartOffset = 0, origEndOffset = 0;
 
-  if (mExtent)
-  {
+  if (mExtent) {
     result = GetRangeEndPoints(mExtent,
                                getter_AddRefs(origStartNode), &origStartOffset,
                                getter_AddRefs(origEndNode), &origEndOffset);
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       UNLOCK_DOC(this);
       return result;
     }
   }
 
-  int32_t i, selLength;
+  int32_t selLength;
   OffsetEntry *entry, *newEntry;
 
-  for (i = mSelStartIndex; i <= mSelEndIndex; i++)
-  {
+  for (int32_t i = mSelStartIndex; i <= mSelEndIndex; i++) {
     entry = mOffsetTable[i];
 
-    if (i == mSelStartIndex)
-    {
+    if (i == mSelStartIndex) {
       // Calculate the length of the selection. Note that the
       // selection length can be zero if the start of the selection
       // is at the very end of a text node entry.
 
-      if (entry->mIsInsertedText)
-      {
+      if (entry->mIsInsertedText) {
         // Inserted text offset entries have no width when
         // talking in terms of string offsets! If the beginning
         // of the selection is in an inserted text offset entry,
         // the caret is always at the end of the entry!
 
         selLength = 0;
-      }
-      else
+      } else {
         selLength = entry->mLength - (mSelStartOffset - entry->mStrOffset);
-
-      if (selLength > 0 && mSelStartOffset > entry->mStrOffset)
-      {
+      }
+
+      if (selLength > 0 && mSelStartOffset > entry->mStrOffset) {
         // Selection doesn't start at the beginning of the
         // text node entry. We need to split this entry into
         // two pieces, the piece before the selection, and
         // the piece inside the selection.
 
         result = SplitOffsetEntry(i, selLength);
 
-        if (NS_FAILED(result))
-        {
+        if (NS_FAILED(result)) {
           UNLOCK_DOC(this);
           return result;
         }
 
         // Adjust selection indexes to account for new entry:
 
         ++mSelStartIndex;
         ++mSelEndIndex;
         ++i;
 
         entry = mOffsetTable[i];
       }
 
 
-      if (selLength > 0 && mSelStartIndex < mSelEndIndex)
-      {
+      if (selLength > 0 && mSelStartIndex < mSelEndIndex) {
         // The entire entry is contained in the selection. Mark the
         // entry invalid.
-
         entry->mIsValid = false;
       }
     }
 
   //**** KDEBUG ****
   // printf("\n---- Middle Delete\n");
   // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
   // PrintOffsetTable();
   //**** KDEBUG ****
 
-    if (i == mSelEndIndex)
-    {
-      if (entry->mIsInsertedText)
-      {
+    if (i == mSelEndIndex) {
+      if (entry->mIsInsertedText) {
         // Inserted text offset entries have no width when
         // talking in terms of string offsets! If the end
         // of the selection is in an inserted text offset entry,
         // the selection includes the entire entry!
 
         entry->mIsValid = false;
-      }
-      else
-      {
+      } else {
         // Calculate the length of the selection. Note that the
         // selection length can be zero if the end of the selection
         // is at the very beginning of a text node entry.
 
         selLength = mSelEndOffset - entry->mStrOffset;
 
-        if (selLength > 0 && mSelEndOffset < entry->mStrOffset + entry->mLength)
-        {
+        if (selLength > 0 &&
+            mSelEndOffset < entry->mStrOffset + entry->mLength) {
           // mStrOffset is guaranteed to be inside the selection, even
           // when mSelStartIndex == mSelEndIndex.
 
           result = SplitOffsetEntry(i, entry->mLength - selLength);
 
-          if (NS_FAILED(result))
-          {
+          if (NS_FAILED(result)) {
             UNLOCK_DOC(this);
             return result;
           }
 
           // Update the entry fields:
 
           newEntry = mOffsetTable[i+1];
           newEntry->mNodeOffset = entry->mNodeOffset;
         }
 
 
-        if (selLength > 0 && mSelEndOffset == entry->mStrOffset + entry->mLength)
-        {
+        if (selLength > 0 &&
+            mSelEndOffset == entry->mStrOffset + entry->mLength) {
           // The entire entry is contained in the selection. Mark the
           // entry invalid.
-
           entry->mIsValid = false;
         }
       }
     }
 
-    if (i != mSelStartIndex && i != mSelEndIndex)
-    {
+    if (i != mSelStartIndex && i != mSelEndIndex) {
       // The entire entry is contained in the selection. Mark the
       // entry invalid.
-
       entry->mIsValid = false;
     }
   }
 
   // Make sure mIterator always points to something valid!
 
   AdjustContentIterator();
 
   // Now delete the actual content!
 
   result = editor->DeleteSelection(nsIEditor::ePrevious, nsIEditor::eStrip);
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
   // Now that we've actually deleted the selected content,
   // check to see if our mExtent has changed, if so, then
   // we have to create a new content iterator!
 
-  if (origStartNode && origEndNode)
-  {
+  if (origStartNode && origEndNode) {
     nsCOMPtr<nsIDOMNode> curStartNode, curEndNode;
     int32_t curStartOffset = 0, curEndOffset = 0;
 
     result = GetRangeEndPoints(mExtent,
                                getter_AddRefs(curStartNode), &curStartOffset,
                                getter_AddRefs(curEndNode), &curEndOffset);
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       UNLOCK_DOC(this);
       return result;
     }
 
-    if (origStartNode != curStartNode || origEndNode != curEndNode)
-    {
+    if (origStartNode != curStartNode || origEndNode != curEndNode) {
       // The range has changed, so we need to create a new content
       // iterator based on the new range.
 
       nsCOMPtr<nsIContent> curContent;
 
       if (mIteratorStatus != nsTextServicesDocument::eIsDone) {
         // The old iterator is still pointing to something valid,
         // so get its current node so we can restore it after we
@@ -1366,78 +1273,72 @@ nsTextServicesDocument::DeleteSelection(
                      ? mIterator->GetCurrentNode()->AsContent()
                      : nullptr;
       }
 
       // Create the new iterator.
 
       result = CreateContentIterator(mExtent, getter_AddRefs(mIterator));
 
-      if (NS_FAILED(result))
-      {
+      if (NS_FAILED(result)) {
         UNLOCK_DOC(this);
         return result;
       }
 
       // Now make the new iterator point to the content node
       // the old one was pointing at.
 
-      if (curContent)
-      {
+      if (curContent) {
         result = mIterator->PositionAt(curContent);
 
-        if (NS_FAILED(result))
+        if (NS_FAILED(result)) {
           mIteratorStatus = eIsDone;
-        else
+        } else {
           mIteratorStatus = eValid;
+        }
       }
     }
   }
 
   entry = 0;
 
   // Move the caret to the end of the first valid entry.
   // Start with mSelStartIndex since it may still be valid.
 
-  for (i = mSelStartIndex; !entry && i >= 0; i--)
-  {
+  for (int32_t i = mSelStartIndex; !entry && i >= 0; i--) {
     entry = mOffsetTable[i];
 
-    if (!entry->mIsValid)
+    if (!entry->mIsValid) {
       entry = 0;
-    else
-    {
+    } else {
       mSelStartIndex  = mSelEndIndex  = i;
       mSelStartOffset = mSelEndOffset = entry->mStrOffset + entry->mLength;
     }
   }
 
   // If we still don't have a valid entry, move the caret
   // to the next valid entry after the selection:
 
-  for (i = mSelEndIndex; !entry && i < int32_t(mOffsetTable.Length()); i++)
-  {
+  for (int32_t i = mSelEndIndex;
+       !entry && i < static_cast<int32_t>(mOffsetTable.Length()); i++) {
     entry = mOffsetTable[i];
 
-    if (!entry->mIsValid)
+    if (!entry->mIsValid) {
       entry = 0;
-    else
-    {
+    } else {
       mSelStartIndex = mSelEndIndex = i;
       mSelStartOffset = mSelEndOffset = entry->mStrOffset;
     }
   }
 
-  if (entry)
+  if (entry) {
     result = SetSelection(mSelStartOffset, 0);
-  else
-  {
+  } else {
     // Uuughh we have no valid offset entry to place our
     // caret ... just mark the selection invalid.
-
     mSelStartIndex  = mSelEndIndex  = -1;
     mSelStartOffset = mSelEndOffset = -1;
   }
 
   // Now remove any invalid entries from the offset table.
 
   result = RemoveInvalidOffsetEntries();
 
@@ -1455,269 +1356,244 @@ nsTextServicesDocument::DeleteSelection(
 NS_IMETHODIMP
 nsTextServicesDocument::InsertText(const nsString *aText)
 {
   nsresult result = NS_OK;
 
   nsCOMPtr<nsIEditor> editor (do_QueryReferent(mEditor));
   NS_ASSERTION(editor, "InsertText called without an editor present!");
 
-  if (!editor || !SelectionIsValid())
+  if (!editor || !SelectionIsValid()) {
     return NS_ERROR_FAILURE;
+  }
 
   NS_ENSURE_TRUE(aText, NS_ERROR_NULL_POINTER);
 
   // If the selection is not collapsed, we need to save
   // off the selection offsets so we can restore the
   // selection and delete the selected content after we've
   // inserted the new text. This is necessary to try and
   // retain as much of the original style of the content
   // being deleted.
 
   bool collapsedSelection = SelectionIsCollapsed();
   int32_t savedSelOffset = mSelStartOffset;
   int32_t savedSelLength = mSelEndOffset - mSelStartOffset;
 
-  if (!collapsedSelection)
-  {
+  if (!collapsedSelection) {
     // Collapse to the start of the current selection
     // for the insert!
 
     result = SetSelection(mSelStartOffset, 0);
 
     NS_ENSURE_SUCCESS(result, result);
   }
 
 
   LOCK_DOC(this);
 
   result = editor->BeginTransaction();
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
   nsCOMPtr<nsIPlaintextEditor> textEditor (do_QueryInterface(editor, &result));
-  if (textEditor)
+  if (textEditor) {
     result = textEditor->InsertText(*aText);
-
-  if (NS_FAILED(result))
-  {
+  }
+
+  if (NS_FAILED(result)) {
     editor->EndTransaction();
     UNLOCK_DOC(this);
     return result;
   }
 
   //**** KDEBUG ****
   // printf("\n---- Before Insert\n");
   // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
   // PrintOffsetTable();
   //**** KDEBUG ****
 
   int32_t strLength = aText->Length();
-  uint32_t i;
 
   nsCOMPtr<nsISelection> selection;
   OffsetEntry *itEntry;
   OffsetEntry *entry = mOffsetTable[mSelStartIndex];
   void *node         = entry->mNode;
 
   NS_ASSERTION((entry->mIsValid), "Invalid insertion point!");
 
-  if (entry->mStrOffset == mSelStartOffset)
-  {
-    if (entry->mIsInsertedText)
-    {
+  if (entry->mStrOffset == mSelStartOffset) {
+    if (entry->mIsInsertedText) {
       // If the caret is in an inserted text offset entry,
       // we simply insert the text at the end of the entry.
 
       entry->mLength += strLength;
-    }
-    else
-    {
+    } else {
       // Insert an inserted text offset entry before the current
       // entry!
 
       itEntry = new OffsetEntry(entry->mNode, entry->mStrOffset, strLength);
 
-      if (!itEntry)
-      {
+      if (!itEntry) {
         editor->EndTransaction();
         UNLOCK_DOC(this);
         return NS_ERROR_OUT_OF_MEMORY;
       }
 
       itEntry->mIsInsertedText = true;
       itEntry->mNodeOffset = entry->mNodeOffset;
 
-      if (!mOffsetTable.InsertElementAt(mSelStartIndex, itEntry))
-      {
+      if (!mOffsetTable.InsertElementAt(mSelStartIndex, itEntry)) {
         editor->EndTransaction();
         UNLOCK_DOC(this);
         return NS_ERROR_FAILURE;
       }
     }
-  }
-  else if ((entry->mStrOffset + entry->mLength) == mSelStartOffset)
-  {
+  } else if (entry->mStrOffset + entry->mLength == mSelStartOffset) {
     // We are inserting text at the end of the current offset entry.
     // Look at the next valid entry in the table. If it's an inserted
     // text entry, add to its length and adjust its node offset. If
     // it isn't, add a new inserted text entry.
 
-    i       = mSelStartIndex + 1;
+    // XXX Rename this!
+    uint32_t i = mSelStartIndex + 1;
     itEntry = 0;
 
-    if (mOffsetTable.Length() > i)
-    {
+    if (mOffsetTable.Length() > i) {
       itEntry = mOffsetTable[i];
 
-      if (!itEntry)
-      {
+      if (!itEntry) {
         editor->EndTransaction();
         UNLOCK_DOC(this);
         return NS_ERROR_FAILURE;
       }
 
       // Check if the entry is a match. If it isn't, set
       // iEntry to zero.
 
-      if (!itEntry->mIsInsertedText || itEntry->mStrOffset != mSelStartOffset)
+      if (!itEntry->mIsInsertedText || itEntry->mStrOffset != mSelStartOffset) {
         itEntry = 0;
+      }
     }
 
-    if (!itEntry)
-    {
+    if (!itEntry) {
       // We didn't find an inserted text offset entry, so
       // create one.
 
       itEntry = new OffsetEntry(entry->mNode, mSelStartOffset, 0);
 
-      if (!itEntry)
-      {
+      if (!itEntry) {
         editor->EndTransaction();
         UNLOCK_DOC(this);
         return NS_ERROR_OUT_OF_MEMORY;
       }
 
       itEntry->mNodeOffset = entry->mNodeOffset + entry->mLength;
       itEntry->mIsInsertedText = true;
 
-      if (!mOffsetTable.InsertElementAt(i, itEntry))
-      {
+      if (!mOffsetTable.InsertElementAt(i, itEntry)) {
         delete itEntry;
         return NS_ERROR_FAILURE;
       }
     }
 
     // We have a valid inserted text offset entry. Update its
     // length, adjust the selection indexes, and make sure the
     // caret is properly placed!
 
     itEntry->mLength += strLength;
 
     mSelStartIndex = mSelEndIndex = i;
 
     result = mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL, getter_AddRefs(selection));
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       editor->EndTransaction();
       UNLOCK_DOC(this);
       return result;
     }
 
     result = selection->Collapse(itEntry->mNode, itEntry->mNodeOffset + itEntry->mLength);
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       editor->EndTransaction();
       UNLOCK_DOC(this);
       return result;
     }
-  }
-  else if ((entry->mStrOffset + entry->mLength) > mSelStartOffset)
-  {
+  } else if (entry->mStrOffset + entry->mLength > mSelStartOffset) {
     // We are inserting text into the middle of the current offset entry.
     // split the current entry into two parts, then insert an inserted text
     // entry between them!
 
-    i = entry->mLength - (mSelStartOffset - entry->mStrOffset);
+    // XXX Rename this!
+    uint32_t i = entry->mLength - (mSelStartOffset - entry->mStrOffset);
 
     result = SplitOffsetEntry(mSelStartIndex, i);
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       editor->EndTransaction();
       UNLOCK_DOC(this);
       return result;
     }
 
     itEntry = new OffsetEntry(entry->mNode, mSelStartOffset, strLength);
 
-    if (!itEntry)
-    {
+    if (!itEntry) {
       editor->EndTransaction();
       UNLOCK_DOC(this);
       return NS_ERROR_OUT_OF_MEMORY;
     }
 
     itEntry->mIsInsertedText = true;
     itEntry->mNodeOffset     = entry->mNodeOffset + entry->mLength;
 
-    if (!mOffsetTable.InsertElementAt(mSelStartIndex + 1, itEntry))
-    {
+    if (!mOffsetTable.InsertElementAt(mSelStartIndex + 1, itEntry)) {
       editor->EndTransaction();
       UNLOCK_DOC(this);
       return NS_ERROR_FAILURE;
     }
 
     mSelEndIndex = ++mSelStartIndex;
   }
 
   // We've just finished inserting an inserted text offset entry.
   // update all entries with the same mNode pointer that follow
   // it in the table!
 
-  for (i = mSelStartIndex + 1; i < mOffsetTable.Length(); i++)
-  {
+  for (size_t i = mSelStartIndex + 1; i < mOffsetTable.Length(); i++) {
     entry = mOffsetTable[i];
-
-    if (entry->mNode == node)
-    {
-      if (entry->mIsValid)
-        entry->mNodeOffset += strLength;
+    if (entry->mNode != node) {
+      break;
     }
-    else
-      break;
+    if (entry->mIsValid) {
+      entry->mNodeOffset += strLength;
+    }
   }
 
   //**** KDEBUG ****
   // printf("\n---- After Insert\n");
   // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
   // PrintOffsetTable();
   //**** KDEBUG ****
 
-  if (!collapsedSelection)
-  {
+  if (!collapsedSelection) {
     result = SetSelection(savedSelOffset, savedSelLength);
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       editor->EndTransaction();
       UNLOCK_DOC(this);
       return result;
     }
 
     result = DeleteSelection();
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       editor->EndTransaction();
       UNLOCK_DOC(this);
       return result;
     }
   }
 
   result = editor->EndTransaction();
 
@@ -1750,59 +1626,52 @@ nsTextServicesDocument::DidDeleteNode(ns
   LOCK_DOC(this);
 
   int32_t nodeIndex = 0;
   bool hasEntry = false;
   OffsetEntry *entry;
 
   nsresult result = NodeHasOffsetEntry(&mOffsetTable, aChild, &hasEntry, &nodeIndex);
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     UNLOCK_DOC(this);
     return result;
   }
 
-  if (!hasEntry)
-  {
+  if (!hasEntry) {
     // It's okay if the node isn't in the offset table, the
     // editor could be cleaning house.
-
     UNLOCK_DOC(this);
     return NS_OK;
   }
 
   nsCOMPtr<nsIDOMNode> node = do_QueryInterface(mIterator->GetCurrentNode());
 
   if (node && node == aChild &&
-      mIteratorStatus != nsTextServicesDocument::eIsDone)
-  {
+      mIteratorStatus != nsTextServicesDocument::eIsDone) {
     // XXX: This should never really happen because
     // AdjustContentIterator() should have been called prior
     // to the delete to try and position the iterator on the
     // next valid text node in the offset table, and if there
     // wasn't a next, it would've set mIteratorStatus to eIsDone.
 
     NS_ERROR("DeleteNode called for current iterator node.");
   }
 
   int32_t tcount = mOffsetTable.Length();
 
-  while (nodeIndex < tcount)
-  {
+  while (nodeIndex < tcount) {
     entry = mOffsetTable[nodeIndex];
 
-    if (!entry)
-    {
+    if (!entry) {
       UNLOCK_DOC(this);
       return NS_ERROR_FAILURE;
     }
 
-    if (entry->mNode == aChild)
-    {
+    if (entry->mNode == aChild) {
       entry->mIsValid = false;
     }
 
     nodeIndex++;
   }
 
   UNLOCK_DOC(this);
 
@@ -1825,17 +1694,16 @@ nsTextServicesDocument::DidSplitNode(nsI
 NS_IMETHODIMP
 nsTextServicesDocument::DidJoinNodes(nsIDOMNode  *aLeftNode,
                                      nsIDOMNode  *aRightNode,
                                      nsIDOMNode  *aParent,
                                      nsresult     aResult)
 {
   NS_ENSURE_SUCCESS(aResult, NS_OK);
 
-  int32_t i;
   uint16_t type;
   nsresult result;
 
   //**** KDEBUG ****
   // printf("** JoinNodes: 0x%.8x  0x%.8x  0x%.8x\n", aLeftNode, aRightNode, aParent);
   // fflush(stdout);
   //**** KDEBUG ****
 
@@ -1860,97 +1728,89 @@ nsTextServicesDocument::DidJoinNodes(nsI
   int32_t rightIndex = 0;
   bool leftHasEntry = false;
   bool rightHasEntry = false;
 
   result = NodeHasOffsetEntry(&mOffsetTable, aLeftNode, &leftHasEntry, &leftIndex);
 
   NS_ENSURE_SUCCESS(result, result);
 
-  if (!leftHasEntry)
-  {
+  if (!leftHasEntry) {
     // It's okay if the node isn't in the offset table, the
     // editor could be cleaning house.
     return NS_OK;
   }
 
   result = NodeHasOffsetEntry(&mOffsetTable, aRightNode, &rightHasEntry, &rightIndex);
 
   NS_ENSURE_SUCCESS(result, result);
 
-  if (!rightHasEntry)
-  {
+  if (!rightHasEntry) {
     // It's okay if the node isn't in the offset table, the
     // editor could be cleaning house.
     return NS_OK;
   }
 
   NS_ASSERTION(leftIndex < rightIndex, "Indexes out of order.");
 
-  if (leftIndex > rightIndex)
-  {
+  if (leftIndex > rightIndex) {
     // Don't know how to handle this situation.
     return NS_ERROR_FAILURE;
   }
 
   LOCK_DOC(this);
 
   OffsetEntry *entry = mOffsetTable[rightIndex];
   NS_ASSERTION(entry->mNodeOffset == 0, "Unexpected offset value for rightIndex.");
 
   // Run through the table and change all entries referring to
   // the left node so that they now refer to the right node:
 
   nsAutoString str;
   result = aLeftNode->GetNodeValue(str);
   int32_t nodeLength = str.Length();
 
-  for (i = leftIndex; i < rightIndex; i++)
-  {
+  for (int32_t i = leftIndex; i < rightIndex; i++) {
     entry = mOffsetTable[i];
-
-    if (entry->mNode == aLeftNode)
-    {
-      if (entry->mIsValid)
-        entry->mNode = aRightNode;
+    if (entry->mNode != aLeftNode) {
+      break;
     }
-    else
-      break;
+    if (entry->mIsValid) {
+      entry->mNode = aRightNode;
+    }
   }
 
   // Run through the table and adjust the node offsets
   // for all entries referring to the right node.
 
-  for (i = rightIndex; i < int32_t(mOffsetTable.Length()); i++)
-  {
+  for (int32_t i = rightIndex;
+       i < static_cast<int32_t>(mOffsetTable.Length()); i++) {
     entry = mOffsetTable[i];
-
-    if (entry->mNode == aRightNode)
-    {
-      if (entry->mIsValid)
-        entry->mNodeOffset += nodeLength;
+    if (entry->mNode != aRightNode) {
+      break;
     }
-    else
-      break;
+    if (entry->mIsValid) {
+      entry->mNodeOffset += nodeLength;
+    }
   }
 
   // Now check to see if the iterator is pointing to the
   // left node. If it is, make it point to the right node!
 
   nsCOMPtr<nsIContent> leftContent = do_QueryInterface(aLeftNode);
   nsCOMPtr<nsIContent> rightContent = do_QueryInterface(aRightNode);
 
-  if (!leftContent || !rightContent)
-  {
+  if (!leftContent || !rightContent) {
     UNLOCK_DOC(this);
     return NS_ERROR_FAILURE;
   }
 
-  if (mIterator->GetCurrentNode() == leftContent)
+  if (mIterator->GetCurrentNode() == leftContent) {
     result = mIterator->PositionAt(rightContent);
+  }
 
   UNLOCK_DOC(this);
 
   return NS_OK;
 }
 
 nsresult
 nsTextServicesDocument::CreateContentIterator(nsRange* aRange,
@@ -1982,32 +1842,29 @@ nsTextServicesDocument::GetDocumentConte
   NS_ENSURE_TRUE(aNode, NS_ERROR_NULL_POINTER);
 
   *aNode = 0;
 
   NS_ENSURE_TRUE(mDOMDocument, NS_ERROR_FAILURE);
 
   nsCOMPtr<nsIDOMHTMLDocument> htmlDoc = do_QueryInterface(mDOMDocument);
 
-  if (htmlDoc)
-  {
+  if (htmlDoc) {
     // For HTML documents, the content root node is the body.
 
     nsCOMPtr<nsIDOMHTMLElement> bodyElement;
 
     result = htmlDoc->GetBody(getter_AddRefs(bodyElement));
 
     NS_ENSURE_SUCCESS(result, result);
 
     NS_ENSURE_TRUE(bodyElement, NS_ERROR_FAILURE);
 
     bodyElement.forget(aNode);
-  }
-  else
-  {
+  } else {
     // For non-HTML documents, the content root node will be the document element.
 
     nsCOMPtr<nsIDOMElement> docElement;
 
     result = mDOMDocument->GetDocumentElement(getter_AddRefs(docElement));
 
     NS_ENSURE_SUCCESS(result, result);
 
@@ -2046,18 +1903,19 @@ nsTextServicesDocument::CreateDocumentCo
     nsIDOMNode* aParent, int32_t aOffset, bool aToStart, nsRange** aRange)
 {
   NS_ENSURE_TRUE(aParent && aRange, NS_ERROR_NULL_POINTER);
 
   *aRange = 0;
 
   NS_ASSERTION(aOffset >= 0, "Invalid offset!");
 
-  if (aOffset < 0)
+  if (aOffset < 0) {
     return NS_ERROR_FAILURE;
+  }
 
   nsCOMPtr<nsIDOMNode> bodyNode;
   nsresult rv = GetDocumentContentRootNode(getter_AddRefs(bodyNode));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(bodyNode, NS_ERROR_NULL_POINTER);
 
   nsCOMPtr<nsIDOMNode> startNode;
   nsCOMPtr<nsIDOMNode> endNode;
@@ -2119,101 +1977,87 @@ nsTextServicesDocument::AdjustContentIte
   nsIDOMNode *nodePtr = node.get();
   int32_t tcount      = mOffsetTable.Length();
 
   nsIDOMNode *prevValidNode = 0;
   nsIDOMNode *nextValidNode = 0;
   bool foundEntry = false;
   OffsetEntry *entry;
 
-  for (int32_t i = 0; i < tcount && !nextValidNode; i++)
-  {
+  for (int32_t i = 0; i < tcount && !nextValidNode; i++) {
     entry = mOffsetTable[i];
 
     NS_ENSURE_TRUE(entry, NS_ERROR_FAILURE);
 
-    if (entry->mNode == nodePtr)
-    {
-      if (entry->mIsValid)
-      {
+    if (entry->mNode == nodePtr) {
+      if (entry->mIsValid) {
         // The iterator is still pointing to something valid!
         // Do nothing!
-
         return NS_OK;
       }
-      else
-      {
-        // We found an invalid entry that points to
-        // the current iterator node. Stop looking for
-        // a previous valid node!
-
-        foundEntry = true;
+      // We found an invalid entry that points to
+      // the current iterator node. Stop looking for
+      // a previous valid node!
+      foundEntry = true;
+    }
+
+    if (entry->mIsValid) {
+      if (!foundEntry) {
+        prevValidNode = entry->mNode;
+      } else {
+        nextValidNode = entry->mNode;
       }
     }
-
-    if (entry->mIsValid)
-    {
-      if (!foundEntry)
-        prevValidNode = entry->mNode;
-      else
-        nextValidNode = entry->mNode;
-    }
   }
 
   nsCOMPtr<nsIContent> content;
 
-  if (prevValidNode)
+  if (prevValidNode) {
     content = do_QueryInterface(prevValidNode);
-  else if (nextValidNode)
+  } else if (nextValidNode) {
     content = do_QueryInterface(nextValidNode);
-
-  if (content)
-  {
+  }
+
+  if (content) {
     result = mIterator->PositionAt(content);
 
-    if (NS_FAILED(result))
+    if (NS_FAILED(result)) {
       mIteratorStatus = eIsDone;
-    else
+    } else {
       mIteratorStatus = eValid;
-
+    }
     return result;
   }
 
   // If we get here, there aren't any valid entries
   // in the offset table! Try to position the iterator
   // on the next text block first, then previous if
   // one doesn't exist!
 
-  if (mNextTextBlock)
-  {
+  if (mNextTextBlock) {
     result = mIterator->PositionAt(mNextTextBlock);
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       mIteratorStatus = eIsDone;
       return result;
     }
 
     mIteratorStatus = eNext;
-  }
-  else if (mPrevTextBlock)
-  {
+  } else if (mPrevTextBlock) {
     result = mIterator->PositionAt(mPrevTextBlock);
 
-    if (NS_FAILED(result))
-    {
+    if (NS_FAILED(result)) {
       mIteratorStatus = eIsDone;
       return result;
     }
 
     mIteratorStatus = ePrev;
+  } else {
+    mIteratorStatus = eIsDone;
   }
-  else
-    mIteratorStatus = eIsDone;
-
   return NS_OK;
 }
 
 bool
 nsTextServicesDocument::DidSkip(nsIContentIterator* aFilteredIter)
 {
   // We can assume here that the Iterator is a nsFilteredContentIterator because
   // all the iterator are created in CreateContentIterator which create a
@@ -2280,28 +2124,27 @@ nsTextServicesDocument::IsBlockNode(nsIC
 bool
 nsTextServicesDocument::HasSameBlockNodeParent(nsIContent *aContent1, nsIContent *aContent2)
 {
   nsIContent* p1 = aContent1->GetParent();
   nsIContent* p2 = aContent2->GetParent();
 
   // Quick test:
 
-  if (p1 == p2)
+  if (p1 == p2) {
     return true;
+  }
 
   // Walk up the parent hierarchy looking for closest block boundary node:
 
-  while (p1 && !IsBlockNode(p1))
-  {
+  while (p1 && !IsBlockNode(p1)) {
     p1 = p1->GetParent();
   }
 
-  while (p2 && !IsBlockNode(p2))
-  {
+  while (p2 && !IsBlockNode(p2)) {
     p2 = p2->GetParent();
   }
 
   return p1 == p2;
 }
 
 bool
 nsTextServicesDocument::IsTextNode(nsIContent *aContent)
@@ -2322,149 +2165,127 @@ nsTextServicesDocument::IsTextNode(nsIDO
 nsresult
 nsTextServicesDocument::SetSelectionInternal(int32_t aOffset, int32_t aLength, bool aDoUpdate)
 {
   nsresult result = NS_OK;
 
   NS_ENSURE_TRUE(mSelCon && aOffset >= 0 && aLength >= 0, NS_ERROR_FAILURE);
 
   nsIDOMNode *sNode = 0, *eNode = 0;
-  int32_t i, sOffset = 0, eOffset = 0;
+  int32_t sOffset = 0, eOffset = 0;
   OffsetEntry *entry;
 
   // Find start of selection in node offset terms:
 
-  for (i = 0; !sNode && i < int32_t(mOffsetTable.Length()); i++)
-  {
+  for (size_t i = 0; !sNode && i < mOffsetTable.Length(); i++) {
     entry = mOffsetTable[i];
-    if (entry->mIsValid)
-    {
-      if (entry->mIsInsertedText)
-      {
+    if (entry->mIsValid) {
+      if (entry->mIsInsertedText) {
         // Caret can only be placed at the end of an
         // inserted text offset entry, if the offsets
         // match exactly!
 
-        if (entry->mStrOffset == aOffset)
-        {
+        if (entry->mStrOffset == aOffset) {
           sNode   = entry->mNode;
           sOffset = entry->mNodeOffset + entry->mLength;
         }
-      }
-      else if (aOffset >= entry->mStrOffset)
-      {
+      } else if (aOffset >= entry->mStrOffset) {
         bool foundEntry = false;
         int32_t strEndOffset = entry->mStrOffset + entry->mLength;
 
-        if (aOffset < strEndOffset)
+        if (aOffset < strEndOffset) {
           foundEntry = true;
-        else if (aOffset == strEndOffset)
-        {
+        } else if (aOffset == strEndOffset) {
           // Peek after this entry to see if we have any
           // inserted text entries belonging to the same
           // entry->mNode. If so, we have to place the selection
           // after it!
 
-          if ((i+1) < int32_t(mOffsetTable.Length()))
-          {
+          if (i + 1 < mOffsetTable.Length()) {
             OffsetEntry *nextEntry = mOffsetTable[i+1];
 
-            if (!nextEntry->mIsValid || nextEntry->mStrOffset != aOffset)
-            {
+            if (!nextEntry->mIsValid || nextEntry->mStrOffset != aOffset) {
               // Next offset entry isn't an exact match, so we'll
               // just use the current entry.
               foundEntry = true;
             }
           }
         }
 
-        if (foundEntry)
-        {
+        if (foundEntry) {
           sNode   = entry->mNode;
           sOffset = entry->mNodeOffset + aOffset - entry->mStrOffset;
         }
       }
 
-      if (sNode)
-      {
-        mSelStartIndex  = i;
+      if (sNode) {
+        mSelStartIndex = static_cast<int32_t>(i);
         mSelStartOffset = aOffset;
       }
     }
   }
 
   NS_ENSURE_TRUE(sNode, NS_ERROR_FAILURE);
 
   // XXX: If we ever get a SetSelection() method in nsIEditor, we should
   //      use it.
 
   nsCOMPtr<nsISelection> selection;
 
-  if (aDoUpdate)
-  {
+  if (aDoUpdate) {
     result = mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL, getter_AddRefs(selection));
 
     NS_ENSURE_SUCCESS(result, result);
 
     result = selection->Collapse(sNode, sOffset);
 
     NS_ENSURE_SUCCESS(result, result);
    }
 
-  if (aLength <= 0)
-  {
+  if (aLength <= 0) {
     // We have a collapsed selection. (Caret)
 
     mSelEndIndex  = mSelStartIndex;
     mSelEndOffset = mSelStartOffset;
 
    //**** KDEBUG ****
    // printf("\n* Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
    //**** KDEBUG ****
 
     return NS_OK;
   }
 
   // Find the end of the selection in node offset terms:
-
   int32_t endOffset = aOffset + aLength;
-
-  for (i = mOffsetTable.Length() - 1; !eNode && i >= 0; i--)
-  {
+  for (int32_t i = mOffsetTable.Length() - 1; !eNode && i >= 0; i--) {
     entry = mOffsetTable[i];
 
-    if (entry->mIsValid)
-    {
-      if (entry->mIsInsertedText)
-      {
-        if (entry->mStrOffset == eOffset)
-        {
+    if (entry->mIsValid) {
+      if (entry->mIsInsertedText) {
+        if (entry->mStrOffset == eOffset) {
           // If the selection ends on an inserted text offset entry,
           // the selection includes the entire entry!
 
           eNode   = entry->mNode;
           eOffset = entry->mNodeOffset + entry->mLength;
         }
-      }
-      else if (endOffset >= entry->mStrOffset && endOffset <= entry->mStrOffset + entry->mLength)
-      {
+      } else if (endOffset >= entry->mStrOffset &&
+                 endOffset <= entry->mStrOffset + entry->mLength) {
         eNode   = entry->mNode;
         eOffset = entry->mNodeOffset + endOffset - entry->mStrOffset;
       }
 
-      if (eNode)
-      {
-        mSelEndIndex  = i;
+      if (eNode) {
+        mSelEndIndex = i;
         mSelEndOffset = endOffset;
       }
     }
   }
 
-  if (aDoUpdate && eNode)
-  {
+  if (aDoUpdate && eNode) {
     result = selection->Extend(eNode, eOffset);
 
     NS_ENSURE_SUCCESS(result, result);
   }
 
   //**** KDEBUG ****
   // printf("\n * Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset);
   //**** KDEBUG ****
@@ -2480,18 +2301,19 @@ nsTextServicesDocument::GetSelection(nsI
   NS_ENSURE_TRUE(aSelStatus && aSelOffset && aSelLength, NS_ERROR_NULL_POINTER);
 
   *aSelStatus = nsITextServicesDocument::eBlockNotFound;
   *aSelOffset = -1;
   *aSelLength = -1;
 
   NS_ENSURE_TRUE(mDOMDocument && mSelCon, NS_ERROR_FAILURE);
 
-  if (mIteratorStatus == nsTextServicesDocument::eIsDone)
+  if (mIteratorStatus == nsTextServicesDocument::eIsDone) {
     return NS_OK;
+  }
 
   nsCOMPtr<nsISelection> selection;
   bool isCollapsed;
 
   result = mSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL, getter_AddRefs(selection));
 
   NS_ENSURE_SUCCESS(result, result);
 
@@ -2501,20 +2323,21 @@ nsTextServicesDocument::GetSelection(nsI
 
   NS_ENSURE_SUCCESS(result, result);
 
   // XXX: If we expose this method publicly, we need to
   //      add LOCK_DOC/UNLOCK_DOC calls!
 
   // LOCK_DOC(this);
 
-  if (isCollapsed)
+  if (isCollapsed) {
     result = GetCollapsedSelection(aSelStatus, aSelOffset, aSelLength);
-  else
+  } else {
     result = GetUncollapsedSelection(aSelStatus, aSelOffset, aSelLength);
+  }
 
   // UNLOCK_DOC(this);
 
   return result;
 }
 
 nsresult
 nsTextServicesDocument::GetCollapsedSelection(nsITextServicesDocument::TSDBlockSelectionStatus *aSelStatus, int32_t *aSelOffset, int32_t *aSelLength)
@@ -2530,28 +2353,30 @@ nsTextServicesDocument::GetCollapsedSele
 
   // The calling function should have done the GetIsCollapsed()
   // check already. Just assume it's collapsed!
   *aSelStatus = nsITextServicesDocument::eBlockOutside;
   *aSelOffset = *aSelLength = -1;
 
   int32_t tableCount = mOffsetTable.Length();
 
-  if (tableCount == 0)
+  if (!tableCount) {
     return NS_OK;
+  }
 
   // Get pointers to the first and last offset entries
   // in the table.
 
   OffsetEntry* eStart = mOffsetTable[0];
   OffsetEntry* eEnd;
-  if (tableCount > 1)
+  if (tableCount > 1) {
     eEnd = mOffsetTable[tableCount - 1];
-  else
+  } else {
     eEnd = eStart;
+  }
 
   int32_t eStartOffset = eStart->mNodeOffset;
   int32_t eEndOffset   = eEnd->mNodeOffset + eEnd->mLength;
 
   RefPtr<nsRange> range = selection->GetRangeAt(0);
   NS_ENSURE_STATE(range);
 
   nsCOMPtr<nsIDOMNode> domParent;
@@ -2580,18 +2405,18 @@ nsTextServicesDocument::GetCollapsedSele
     // through the offset table for the entry that
     // matches its parent and offset.
 
     for (int32_t i = 0; i < tableCount; i++) {
       OffsetEntry* entry = mOffsetTable[i];
       NS_ENSURE_TRUE(entry, NS_ERROR_FAILURE);
 
       if (entry->mNode == domParent.get() &&
-          entry->mNodeOffset <= offset && offset <= (entry->mNodeOffset + entry->mLength))
-      {
+          entry->mNodeOffset <= offset &&
+          offset <= entry->mNodeOffset + entry->mLength) {
         *aSelStatus = nsITextServicesDocument::eBlockContains;
         *aSelOffset = entry->mStrOffset + (offset - entry->mNodeOffset);
         *aSelLength = 0;
 
         return NS_OK;
       }
     }
 
@@ -2704,18 +2529,18 @@ nsTextServicesDocument::GetCollapsedSele
     offset = 0;
   }
 
   for (int32_t i = 0; i < tableCount; i++) {
     OffsetEntry* entry = mOffsetTable[i];
     NS_ENSURE_TRUE(entry, NS_ERROR_FAILURE);
 
     if (entry->mNode == node->AsDOMNode() &&
-        entry->mNodeOffset <= offset && offset <= (entry->mNodeOffset + entry->mLength))
-    {
+        entry->mNodeOffset <= offset &&
+        offset <= entry->mNodeOffset + entry->mLength) {
       *aSelStatus = nsITextServicesDocument::eBlockContains;
       *aSelOffset = entry->mStrOffset + (offset - entry->mNodeOffset);
       *aSelLength = 0;
 
       // Now move the caret so that it is actually in the text node.
       // We do this to keep things in sync.
       //
       // In most cases, the user shouldn't see any movement in the caret
@@ -2747,141 +2572,124 @@ nsTextServicesDocument::GetUncollapsedSe
   RefPtr<Selection> selection = domSelection->AsSelection();
 
   // It is assumed that the calling function has made sure that the
   // selection is not collapsed, and that the input params to this
   // method are initialized to some defaults.
 
   nsCOMPtr<nsIDOMNode> startParent, endParent;
   int32_t startOffset, endOffset;
-  int32_t rangeCount, tableCount, i;
+  int32_t rangeCount, tableCount;
   int32_t e1s1 = 0, e1s2 = 0, e2s1 = 0, e2s2 = 0;
 
   OffsetEntry *eStart, *eEnd;
   int32_t eStartOffset, eEndOffset;
 
   tableCount = mOffsetTable.Length();
 
   // Get pointers to the first and last offset entries
   // in the table.
 
   eStart = mOffsetTable[0];
 
-  if (tableCount > 1)
+  if (tableCount > 1) {
     eEnd = mOffsetTable[tableCount - 1];
-  else
+  } else {
     eEnd = eStart;
+  }
 
   eStartOffset = eStart->mNodeOffset;
   eEndOffset   = eEnd->mNodeOffset + eEnd->mLength;
 
   result = selection->GetRangeCount(&rangeCount);
 
   NS_ENSURE_SUCCESS(result, result);
 
   // Find the first range in the selection that intersects
   // the current text block.
 
-  for (i = 0; i < rangeCount; i++)
-  {
+  for (int32_t i = 0; i < rangeCount; i++) {
     range = selection->GetRangeAt(i);
     NS_ENSURE_STATE(range);
 
     result = GetRangeEndPoints(range,
                                getter_AddRefs(startParent), &startOffset,
                                getter_AddRefs(endParent), &endOffset);
 
     NS_ENSURE_SUCCESS(result, result);
 
     e1s2 = nsContentUtils::ComparePoints(eStart->mNode, eStartOffset,
                                          endParent, endOffset);
     e2s1 = nsContentUtils::ComparePoints(eEnd->mNode, eEndOffset,
                                          startParent, startOffset);
 
     // Break out of the loop if the text block intersects the current range.
 
-    if (e1s2 <= 0 && e2s1 >= 0)
+    if (e1s2 <= 0 && e2s1 >= 0) {
       break;
+    }
   }
 
   // We're done if we didn't find an intersecting range.
 
-  if (rangeCount < 1 || e1s2 > 0 || e2s1 < 0)
-  {
+  if (rangeCount < 1 || e1s2 > 0 || e2s1 < 0) {
     *aSelStatus = nsITextServicesDocument::eBlockOutside;
     *aSelOffset = *aSelLength = -1;
     return NS_OK;
   }
 
   // Now that we have an intersecting range, find out more info:
 
   e1s1 = nsContentUtils::ComparePoints(eStart->mNode, eStartOffset,
                                        startParent, startOffset);
   e2s2 = nsContentUtils::ComparePoints(eEnd->mNode, eEndOffset,
                                        endParent, endOffset);
 
-  if (rangeCount > 1)
-  {
+  if (rangeCount > 1) {
     // There are multiple selection ranges, we only deal
     // with the first one that intersects the current,
     // text block, so mark this a as a partial.
-
     *aSelStatus = nsITextServicesDocument::eBlockPartial;
-  }
-  else if (e1s1 > 0 && e2s2 < 0)
-  {
+  } else if (e1s1 > 0 && e2s2 < 0) {
     // The range extends beyond the start and
     // end of the current text block.
-
     *aSelStatus = nsITextServicesDocument::eBlockInside;
-  }
-  else if (e1s1 <= 0 && e2s2 >= 0)
-  {
+  } else if (e1s1 <= 0 && e2s2 >= 0) {
     // The current text block contains the entire
     // range.
-
     *aSelStatus = nsITextServicesDocument::eBlockContains;
-  }
-  else
-  {
+  } else {
     // The range partially intersects the block.
-
     *aSelStatus = nsITextServicesDocument::eBlockPartial;
   }
 
   // Now create a range based on the intersection of the
   // text block and range:
 
   nsCOMPtr<nsIDOMNode> p1, p2;
   int32_t     o1,  o2;
 
   // The start of the range will be the rightmost
   // start node.
 
-  if (e1s1 >= 0)
-  {
+  if (e1s1 >= 0) {
     p1 = do_QueryInterface(eStart->mNode);
     o1 = eStartOffset;
-  }
-  else
-  {
+  } else {
     p1 = startParent;
     o1 = startOffset;
   }
 
   // The end of the range will be the leftmost
   // end node.
 
-  if (e2s2 <= 0)
-  {
+  if (e2s2 <= 0) {
     p2 = do_QueryInterface(eEnd->mNode);
     o2 = eEndOffset;
-  }
-  else
-  {
+  } else {
     p2 = endParent;
     o2 = endOffset;
   }
 
   result = CreateRange(p1, o1, p2, o2, getter_AddRefs(range));
 
   NS_ENSURE_SUCCESS(result, result);
 
@@ -2896,26 +2704,23 @@ nsTextServicesDocument::GetUncollapsedSe
 
   // Find the first text node in the range.
 
   bool found;
   nsCOMPtr<nsIContent> content;
 
   iter->First();
 
-  if (!IsTextNode(p1))
-  {
+  if (!IsTextNode(p1)) {
     found = false;
 
-    while (!iter->IsDone())
-    {
+    while (!iter->IsDone()) {
       content = do_QueryInterface(iter->GetCurrentNode());
 
-      if (IsTextNode(content))
-      {
+      if (IsTextNode(content)) {
         p1 = do_QueryInterface(content);
 
         NS_ENSURE_TRUE(p1, NS_ERROR_FAILURE);
 
         o1 = 0;
         found = true;
 
         break;
@@ -2926,26 +2731,21 @@ nsTextServicesDocument::GetUncollapsedSe
 
     NS_ENSURE_TRUE(found, NS_ERROR_FAILURE);
   }
 
   // Find the last text node in the range.
 
   iter->Last();
 
-  if (! IsTextNode(p2))
-  {
+  if (!IsTextNode(p2)) {
     found = false;
-
-    while (!iter->IsDone())
-    {
+    while (!iter->IsDone()) {
       content = do_QueryInterface(iter->GetCurrentNode());
-
-      if (IsTextNode(content))
-      {
+      if (IsTextNode(content)) {
         p2 = do_QueryInterface(content);
 
         NS_ENSURE_TRUE(p2, NS_ERROR_FAILURE);
 
         nsString str;
 
         result = p2->GetNodeValue(str);
 
@@ -2961,66 +2761,48 @@ nsTextServicesDocument::GetUncollapsedSe
     }
 
     NS_ENSURE_TRUE(found, NS_ERROR_FAILURE);
   }
 
   found    = false;
   *aSelLength = 0;
 
-  for (i = 0; i < tableCount; i++)
-  {
+  for (int32_t i = 0; i < tableCount; i++) {
     entry = mOffsetTable[i];
-
     NS_ENSURE_TRUE(entry, NS_ERROR_FAILURE);
-
-    if (!found)
-    {
+    if (!found) {
       if (entry->mNode == p1.get() &&
-          entry->mNodeOffset <= o1 && o1 <= (entry->mNodeOffset + entry->mLength))
-      {
+          entry->mNodeOffset <= o1 &&
+          o1 <= entry->mNodeOffset + entry->mLength) {
         *aSelOffset = entry->mStrOffset + (o1 - entry->mNodeOffset);
-
         if (p1 == p2 &&
-            entry->mNodeOffset <= o2 && o2 <= (entry->mNodeOffset + entry->mLength))
-        {
+            entry->mNodeOffset <= o2 &&
+            o2 <= entry->mNodeOffset + entry->mLength) {
           // The start and end of the range are in the same offset
           // entry. Calculate the length of the range then we're done.
-
           *aSelLength = o2 - o1;
           break;
         }
-        else
-        {
-          // Add the length of the sub string in this offset entry
-          // that follows the start of the range.
-
-          *aSelLength = entry->mLength - (o1 - entry->mNodeOffset);
-        }
-
+        // Add the length of the sub string in this offset entry
+        // that follows the start of the range.
+        *aSelLength = entry->mLength - (o1 - entry->mNodeOffset);
         found = true;
       }
-    }
-    else // found
-    {
+    } else { // Found.
       if (entry->mNode == p2.get() &&
-          entry->mNodeOffset <= o2 && o2 <= (entry->mNodeOffset + entry->mLength))
-      {
+          entry->mNodeOffset <= o2 &&
+          o2 <= entry->mNodeOffset + entry->mLength) {
         // We found the end of the range. Calculate the length of the
         // sub string that is before the end of the range, then we're done.
-
         *aSelLength += o2 - entry->mNodeOffset;
         break;
       }
-      else
-      {
-        // The entire entry must be in the range.
-
-        *aSelLength += entry->mLength;
-      }
+      // The entire entry must be in the range.
+      *aSelLength += entry->mLength;
     }
   }
 
   return result;
 }
 
 bool
 nsTextServicesDocument::SelectionIsCollapsed()
@@ -3073,50 +2855,52 @@ nsTextServicesDocument::CreateRange(nsID
   return nsRange::CreateRange(aStartParent, aStartOffset, aEndParent,
                               aEndOffset, aRange);
 }
 
 nsresult
 nsTextServicesDocument::FirstTextNode(nsIContentIterator *aIterator,
                                       TSDIteratorStatus *aIteratorStatus)
 {
-  if (aIteratorStatus)
+  if (aIteratorStatus) {
     *aIteratorStatus = nsTextServicesDocument::eIsDone;
+  }
 
   aIterator->First();
 
   while (!aIterator->IsDone()) {
     if (aIterator->GetCurrentNode()->NodeType() == nsIDOMNode::TEXT_NODE) {
-      if (aIteratorStatus)
+      if (aIteratorStatus) {
         *aIteratorStatus = nsTextServicesDocument::eValid;
+      }
       break;
     }
-
     aIterator->Next();
   }
 
   return NS_OK;
 }
 
 nsresult
 nsTextServicesDocument::LastTextNode(nsIContentIterator *aIterator,
                                      TSDIteratorStatus *aIteratorStatus)
 {
-  if (aIteratorStatus)
+  if (aIteratorStatus) {
     *aIteratorStatus = nsTextServicesDocument::eIsDone;
+  }
 
   aIterator->Last();
 
   while (!aIterator->IsDone()) {
     if (aIterator->GetCurrentNode()->NodeType() == nsIDOMNode::TEXT_NODE) {
-      if (aIteratorStatus)
+      if (aIteratorStatus) {
         *aIteratorStatus = nsTextServicesDocument::eValid;
+      }
       break;
     }
-
     aIterator->Prev();
   }
 
   return NS_OK;
 }
 
 nsresult
 nsTextServicesDocument::FirstTextNodeInCurrentBlock(nsIContentIterator *iter)
@@ -3125,44 +2909,42 @@ nsTextServicesDocument::FirstTextNodeInC
 
   ClearDidSkip(iter);
 
   nsCOMPtr<nsIContent> last;
 
   // Walk backwards over adjacent text nodes until
   // we hit a block boundary:
 
-  while (!iter->IsDone())
-  {
+  while (!iter->IsDone()) {
     nsCOMPtr<nsIContent> content = iter->GetCurrentNode()->IsContent()
                                    ? iter->GetCurrentNode()->AsContent()
                                    : nullptr;
-
-    if (IsTextNode(content))
-    {
-      if (!last || HasSameBlockNodeParent(content, last))
-        last = content;
-      else
-      {
+    if (last && IsBlockNode(content)) {
+      break;
+    }
+    if (IsTextNode(content)) {
+      if (last && !HasSameBlockNodeParent(content, last)) {
         // We're done, the current text node is in a
         // different block.
         break;
       }
+      last = content;
     }
-    else if (last && IsBlockNode(content))
-      break;
 
     iter->Prev();
 
-    if (DidSkip(iter))
+    if (DidSkip(iter)) {
       break;
+    }
   }
 
-  if (last)
+  if (last) {
     iter->PositionAt(last);
+  }
 
   // XXX: What should we return if last is null?
 
   return NS_OK;
 }
 
 nsresult
 nsTextServicesDocument::FirstTextNodeInPrevBlock(nsIContentIterator *aIterator)
@@ -3179,54 +2961,55 @@ nsTextServicesDocument::FirstTextNodeInP
   result = FirstTextNodeInCurrentBlock(aIterator);
 
   NS_ENSURE_SUCCESS(result, NS_ERROR_FAILURE);
 
   // Point mIterator to the first node before the first text node:
 
   aIterator->Prev();
 
-  if (aIterator->IsDone())
+  if (aIterator->IsDone()) {
     return NS_ERROR_FAILURE;
+  }
 
   // Now find the first text node of the next block:
 
   return FirstTextNodeInCurrentBlock(aIterator);
 }
 
 nsresult
 nsTextServicesDocument::FirstTextNodeInNextBlock(nsIContentIterator *aIterator)
 {
   nsCOMPtr<nsIContent> prev;
   bool crossedBlockBoundary = false;
 
   NS_ENSURE_TRUE(aIterator, NS_ERROR_NULL_POINTER);
 
   ClearDidSkip(aIterator);
 
-  while (!aIterator->IsDone())
-  {
+  while (!aIterator->IsDone()) {
     nsCOMPtr<nsIContent> content = aIterator->GetCurrentNode()->IsContent()
                                    ? aIterator->GetCurrentNode()->AsContent()
                                    : nullptr;
 
-    if (IsTextNode(content))
-    {
-      if (!crossedBlockBoundary && (!prev || HasSameBlockNodeParent(prev, content)))
-        prev = content;
-      else
+    if (IsTextNode(content)) {
+      if (crossedBlockBoundary ||
+          (prev && !HasSameBlockNodeParent(prev, content))) {
         break;
+      }
+      prev = content;
+    } else if (!crossedBlockBoundary && IsBlockNode(content)) {
+      crossedBlockBoundary = true;
     }
-    else if (!crossedBlockBoundary && IsBlockNode(content))
-      crossedBlockBoundary = true;
 
     aIterator->Next();
 
-    if (!crossedBlockBoundary && DidSkip(aIterator))
+    if (!crossedBlockBoundary && DidSkip(aIterator)) {
       crossedBlockBoundary = true;
+    }
   }
 
   return NS_OK;
 }
 
 nsresult
 nsTextServicesDocument::GetFirstTextNodeInPrevBlock(nsIContent **aContent)
 {
@@ -3238,25 +3021,23 @@ nsTextServicesDocument::GetFirstTextNode
 
   // Save the iterator's current content node so we can restore
   // it when we are done:
 
   nsINode* node = mIterator->GetCurrentNode();
 
   result = FirstTextNodeInPrevBlock(mIterator);
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     // Try to restore the iterator before returning.
     mIterator->PositionAt(node);
     return result;
   }
 
-  if (!mIterator->IsDone())
-  {
+  if (!mIterator->IsDone()) {
     nsCOMPtr<nsIContent> current = mIterator->GetCurrentNode()->IsContent()
                                    ? mIterator->GetCurrentNode()->AsContent()
                                    : nullptr;
     current.forget(aContent);
   }
 
   // Restore the iterator:
 
@@ -3274,25 +3055,23 @@ nsTextServicesDocument::GetFirstTextNode
 
   // Save the iterator's current content node so we can restore
   // it when we are done:
 
   nsINode* node = mIterator->GetCurrentNode();
 
   result = FirstTextNodeInNextBlock(mIterator);
 
-  if (NS_FAILED(result))
-  {
+  if (NS_FAILED(result)) {
     // Try to restore the iterator before returning.
     mIterator->PositionAt(node);
     return result;
   }
 
-  if (!mIterator->IsDone())
-  {
+  if (!mIterator->IsDone()) {
     nsCOMPtr<nsIContent> current = mIterator->GetCurrentNode()->IsContent()
                                    ? mIterator->GetCurrentNode()->AsContent()
                                    : nullptr;
     current.forget(aContent);
   }
 
   // Restore the iterator:
   return mIterator->PositionAt(node);
@@ -3308,31 +3087,32 @@ nsTextServicesDocument::CreateOffsetTabl
 
   nsCOMPtr<nsIContent> first;
   nsCOMPtr<nsIContent> prev;
 
   NS_ENSURE_TRUE(aIterator, NS_ERROR_NULL_POINTER);
 
   ClearOffsetTable(aOffsetTable);
 
-  if (aStr)
+  if (aStr) {
     aStr->Truncate();
-
-  if (*aIteratorStatus == nsTextServicesDocument::eIsDone)
+  }
+
+  if (*aIteratorStatus == nsTextServicesDocument::eIsDone) {
     return NS_OK;
+  }
 
   // If we have an aIterRange, retrieve the endpoints so
   // they can be used in the while loop below to trim entries
   // for text nodes that are partially selected by aIterRange.
 
   nsCOMPtr<nsIDOMNode> rngStartNode, rngEndNode;
   int32_t rngStartOffset = 0, rngEndOffset = 0;
 
-  if (aIterRange)
-  {
+  if (aIterRange) {
     result = GetRangeEndPoints(aIterRange,
                                getter_AddRefs(rngStartNode), &rngStartOffset,
                                getter_AddRefs(rngEndNode), &rngEndOffset);
 
     NS_ENSURE_SUCCESS(result, result);
   }
 
   // The text service could have added text nodes to the beginning
@@ -3342,223 +3122,195 @@ nsTextServicesDocument::CreateOffsetTabl
   result = FirstTextNodeInCurrentBlock(aIterator);
 
   NS_ENSURE_SUCCESS(result, result);
 
   int32_t offset = 0;
 
   ClearDidSkip(aIterator);
 
-  while (!aIterator->IsDone())
-  {
+  while (!aIterator->IsDone()) {
     nsCOMPtr<nsIContent> content = aIterator->GetCurrentNode()->IsContent()
                                    ? aIterator->GetCurrentNode()->AsContent()
                                    : nullptr;
-
-    if (IsTextNode(content))
-    {
-      if (!prev || HasSameBlockNodeParent(prev, content))
-      {
-        nsCOMPtr<nsIDOMNode> node = do_QueryInterface(content);
-
-        if (node)
-        {
-          nsString str;
-
-          result = node->GetNodeValue(str);
-
-          NS_ENSURE_SUCCESS(result, result);
-
-          // Add an entry for this text node into the offset table:
-
-          OffsetEntry *entry = new OffsetEntry(node, offset, str.Length());
-          aOffsetTable->AppendElement(entry);
-
-          // If one or both of the endpoints of the iteration range
-          // are in the text node for this entry, make sure the entry
-          // only accounts for the portion of the text node that is
-          // in the range.
-
-          int32_t startOffset = 0;
-          int32_t endOffset   = str.Length();
-          bool adjustStr    = false;
-
-          if (entry->mNode == rngStartNode)
-          {
-            entry->mNodeOffset = startOffset = rngStartOffset;
-            adjustStr = true;
-          }
-
-          if (entry->mNode == rngEndNode)
-          {
-            endOffset = rngEndOffset;
-            adjustStr = true;
-          }
-
-          if (adjustStr)
-          {
-            entry->mLength = endOffset - startOffset;
-            str = Substring(str, startOffset, entry->mLength);
-          }
-
-          offset += str.Length();
-
-          if (aStr)
-          {
-            // Append the text node's string to the output string:
-
-            if (!first)
-              *aStr = str;
-            else
-              *aStr += str;
+    if (IsTextNode(content)) {
+      if (prev && !HasSameBlockNodeParent(prev, content)) {
+        break;
+      }
+
+      nsCOMPtr<nsIDOMNode> node = do_QueryInterface(content);
+      if (node) {
+        nsString str;
+
+        result = node->GetNodeValue(str);
+
+        NS_ENSURE_SUCCESS(result, result);
+
+        // Add an entry for this text node into the offset table:
+
+        OffsetEntry *entry = new OffsetEntry(node, offset, str.Length());
+        aOffsetTable->AppendElement(entry);
+
+        // If one or both of the endpoints of the iteration range
+        // are in the text node for this entry, make sure the entry
+        // only accounts for the portion of the text node that is
+        // in the range.
+
+        int32_t startOffset = 0;
+        int32_t endOffset   = str.Length();
+        bool adjustStr    = false;
+
+        if (entry->mNode == rngStartNode) {
+          entry->mNodeOffset = startOffset = rngStartOffset;
+          adjustStr = true;
+        }
+
+        if (entry->mNode == rngEndNode) {
+          endOffset = rngEndOffset;
+          adjustStr = true;
+        }
+
+        if (adjustStr) {
+          entry->mLength = endOffset - startOffset;
+          str = Substring(str, startOffset, entry->mLength);
+        }
+
+        offset += str.Length();
+
+        if (aStr) {
+          // Append the text node's string to the output string:
+          if (!first) {
+            *aStr = str;
+          } else {
+            *aStr += str;
           }
         }
-
-        prev = content;
-
-        if (!first)
-          first = content;
+      }
+
+      prev = content;
+
+      if (!first) {
+        first = content;
       }
-      else
-        break;
-
     }
-    else if (IsBlockNode(content))
+    // XXX This should be checked before IsTextNode(), but IsBlockNode() returns
+    //     true even if content is a text node.  See bug 1311934.
+    else if (IsBlockNode(content)) {
       break;
+    }
 
     aIterator->Next();
 
-    if (DidSkip(aIterator))
+    if (DidSkip(aIterator)) {
       break;
+    }
   }
 
-  if (first)
-  {
+  if (first) {
     // Always leave the iterator pointing at the first
     // text node of the current block!
-
     aIterator->PositionAt(first);
-  }
-  else
-  {
+  } else {
     // If we never ran across a text node, the iterator
     // might have been pointing to something invalid to
     // begin with.
-
     *aIteratorStatus = nsTextServicesDocument::eIsDone;
   }
 
   return result;
 }
 
 nsresult
 nsTextServicesDocument::RemoveInvalidOffsetEntries()
 {
-  OffsetEntry *entry;
-  int32_t i = 0;
-
-  while (uint32_t(i) < mOffsetTable.Length())
-  {
-    entry = mOffsetTable[i];
-
-    if (!entry->mIsValid)
-    {
+  for (size_t i = 0; i < mOffsetTable.Length(); ) {
+    OffsetEntry* entry = mOffsetTable[i];
+    if (!entry->mIsValid) {
       mOffsetTable.RemoveElementAt(i);
-
-      if (mSelStartIndex >= 0 && mSelStartIndex >= i)
-      {
+      if (mSelStartIndex >= 0 && static_cast<size_t>(mSelStartIndex) >= i) {
         // We are deleting an entry that comes before
         // mSelStartIndex, decrement mSelStartIndex so
         // that it points to the correct entry!
 
-        NS_ASSERTION(i != mSelStartIndex, "Invalid selection index.");
+        NS_ASSERTION(i != static_cast<size_t>(mSelStartIndex),
+                     "Invalid selection index.");
 
         --mSelStartIndex;
         --mSelEndIndex;
       }
+    } else {
+      i++;
     }
-    else
-      i++;
   }
 
   return NS_OK;
 }
 
 nsresult
 nsTextServicesDocument::ClearOffsetTable(nsTArray<OffsetEntry*> *aOffsetTable)
 {
-  uint32_t i;
-
-  for (i = 0; i < aOffsetTable->Length(); i++)
-  {
+  for (size_t i = 0; i < aOffsetTable->Length(); i++) {
     delete aOffsetTable->ElementAt(i);
   }
 
   aOffsetTable->Clear();
 
   return NS_OK;
 }
 
 nsresult
 nsTextServicesDocument::SplitOffsetEntry(int32_t aTableIndex, int32_t aNewEntryLength)
 {
   OffsetEntry *entry = mOffsetTable[aTableIndex];
 
   NS_ASSERTION((aNewEntryLength > 0), "aNewEntryLength <= 0");
   NS_ASSERTION((aNewEntryLength < entry->mLength), "aNewEntryLength >= mLength");
 
-  if (aNewEntryLength < 1 || aNewEntryLength >= entry->mLength)
+  if (aNewEntryLength < 1 || aNewEntryLength >= entry->mLength) {
     return NS_ERROR_FAILURE;
+  }
 
   int32_t oldLength = entry->mLength - aNewEntryLength;
 
   OffsetEntry *newEntry = new OffsetEntry(entry->mNode,
                                           entry->mStrOffset + oldLength,
                                           aNewEntryLength);
 
-  if (!mOffsetTable.InsertElementAt(aTableIndex + 1, newEntry))
-  {
+  if (!mOffsetTable.InsertElementAt(aTableIndex + 1, newEntry)) {
     delete newEntry;
     return NS_ERROR_FAILURE;
   }
 
    // Adjust entry fields:
 
    entry->mLength        = oldLength;
    newEntry->mNodeOffset = entry->mNodeOffset + oldLength;
 
   return NS_OK;
 }
 
 nsresult
 nsTextServicesDocument::NodeHasOffsetEntry(nsTArray<OffsetEntry*> *aOffsetTable, nsIDOMNode *aNode, bool *aHasEntry, int32_t *aEntryIndex)
 {
-  OffsetEntry *entry;
-  uint32_t i;
-
   NS_ENSURE_TRUE(aNode && aHasEntry && aEntryIndex, NS_ERROR_NULL_POINTER);
 
-  for (i = 0; i < aOffsetTable->Length(); i++)
-  {
-    entry = (*aOffsetTable)[i];
+  for (size_t i = 0; i < aOffsetTable->Length(); i++) {
+    OffsetEntry* entry = (*aOffsetTable)[i];
 
     NS_ENSURE_TRUE(entry, NS_ERROR_FAILURE);
 
-    if (entry->mNode == aNode)
-    {
+    if (entry->mNode == aNode) {
       *aHasEntry   = true;
       *aEntryIndex = i;
-
       return NS_OK;
     }
   }
 
   *aHasEntry   = false;
   *aEntryIndex = -1;
-
   return NS_OK;
 }
 
 // Spellchecker code has this. See bug 211343
 #define IS_NBSP_CHAR(c) (((unsigned char)0xa0)==(c))
 
 nsresult
 nsTextServicesDocument::FindWordBounds(nsTArray<OffsetEntry*> *aOffsetTable,
@@ -3567,24 +3319,28 @@ nsTextServicesDocument::FindWordBounds(n
                                        int32_t aNodeOffset,
                                        nsIDOMNode **aWordStartNode,
                                        int32_t *aWordStartOffset,
                                        nsIDOMNode **aWordEndNode,
                                        int32_t *aWordEndOffset)
 {
   // Initialize return values.
 
-  if (aWordStartNode)
+  if (aWordStartNode) {
     *aWordStartNode = nullptr;
-  if (aWordStartOffset)
+  }
+  if (aWordStartOffset) {
     *aWordStartOffset = 0;
-  if (aWordEndNode)
+  }
+  if (aWordEndNode) {
     *aWordEndNode = nullptr;
-  if (aWordEndOffset)
+  }
+  if (aWordEndOffset) {
     *aWordEndOffset = 0;
+  }
 
   int32_t entryIndex = 0;
   bool hasEntry = false;
 
   // It's assumed that aNode is a text node. The first thing
   // we do is get its index in the offset table so we can
   // calculate the dom point's string offset.
 
@@ -3605,88 +3361,85 @@ nsTextServicesDocument::FindWordBounds(n
 
   nsIWordBreaker* wordBreaker = nsContentUtils::WordBreaker();
   nsWordRange res = wordBreaker->FindWord(str, strLen, strOffset);
   if (res.mBegin > strLen) {
     return str ? NS_ERROR_ILLEGAL_VALUE : NS_ERROR_NULL_POINTER;
   }
 
   // Strip out the NBSPs at the ends
-  while ((res.mBegin <= res.mEnd) && (IS_NBSP_CHAR(str[res.mBegin])))
+  while (res.mBegin <= res.mEnd && IS_NBSP_CHAR(str[res.mBegin])) {
     res.mBegin++;
-  if (str[res.mEnd] == (unsigned char)0x20)
-  {
+  }
+  if (str[res.mEnd] == (unsigned char)0x20) {
     uint32_t realEndWord = res.mEnd - 1;
-    while ((realEndWord > res.mBegin) && (IS_NBSP_CHAR(str[realEndWord])))
+    while (realEndWord > res.mBegin && IS_NBSP_CHAR(str[realEndWord])) {
       realEndWord--;
-    if (realEndWord < res.mEnd - 1)
+    }
+    if (realEndWord < res.mEnd - 1) {
       res.mEnd = realEndWord + 1;
+    }
   }
 
   // Now that we have the string offsets for the beginning
   // and end of the word, run through the offset table and
   // convert them back into dom points.
 
-  int32_t i, lastIndex = aOffsetTable->Length() - 1;
-
-  for (i=0; i <= lastIndex; i++)
-  {
+  size_t lastIndex = aOffsetTable->Length() - 1;
+  for (size_t i = 0; i <= lastIndex; i++) {
     entry = (*aOffsetTable)[i];
 
     int32_t strEndOffset = entry->mStrOffset + entry->mLength;
 
     // Check to see if res.mBegin is within the range covered
     // by this entry. Note that if res.mBegin is after the last
     // character covered by this entry, we will use the next
     // entry if there is one.
 
     if (uint32_t(entry->mStrOffset) <= res.mBegin &&
-        (res.mBegin < uint32_t(strEndOffset) ||
-        (res.mBegin == uint32_t(strEndOffset) && i == lastIndex)))
-    {
-      if (aWordStartNode)
-      {
+        (res.mBegin < static_cast<uint32_t>(strEndOffset) ||
+         (res.mBegin == static_cast<uint32_t>(strEndOffset) &&
+          i == lastIndex))) {
+      if (aWordStartNode) {
         *aWordStartNode = entry->mNode;
         NS_IF_ADDREF(*aWordStartNode);
       }
 
-      if (aWordStartOffset)
+      if (aWordStartOffset) {
         *aWordStartOffset = entry->mNodeOffset + res.mBegin - entry->mStrOffset;
-
-      if (!aWordEndNode && !aWordEndOffset)
-      {
+      }
+
+      if (!aWordEndNode && !aWordEndOffset) {
         // We've found our start entry, but if we're not looking
         // for end entries, we're done.
-
         break;
       }
     }
 
     // Check to see if res.mEnd is within the range covered
     // by this entry.
 
-    if (uint32_t(entry->mStrOffset) <= res.mEnd && res.mEnd <= uint32_t(strEndOffset))
-    {
-      if (res.mBegin == res.mEnd && res.mEnd == uint32_t(strEndOffset) && i != lastIndex)
-      {
+    if (static_cast<uint32_t>(entry->mStrOffset) <= res.mEnd &&
+        res.mEnd <= static_cast<uint32_t>(strEndOffset)) {
+      if (res.mBegin == res.mEnd &&
+          res.mEnd == static_cast<uint32_t>(strEndOffset) &&
+          i != lastIndex) {
         // Wait for the next round so that we use the same entry
         // we did for aWordStartNode.
-
         continue;
       }
 
-      if (aWordEndNode)
-      {
+      if (aWordEndNode) {
         *aWordEndNode = entry->mNode;
         NS_IF_ADDREF(*aWordEndNode);
       }
 
-      if (aWordEndOffset)
+      if (aWordEndOffset) {
         *aWordEndOffset = entry->mNodeOffset + res.mEnd - entry->mStrOffset;
-
+      }
       break;
     }
   }
 
 
   return NS_OK;
 }
 
@@ -3714,17 +3467,16 @@ nsTextServicesDocument::WillSplitNode(ns
 NS_IMETHODIMP
 nsTextServicesDocument::WillJoinNodes(nsIDOMNode  *aLeftNode,
                              nsIDOMNode  *aRightNode,
                              nsIDOMNode  *aParent)
 {
   return NS_OK;
 }
 
-
 // -------------------------------
 // stubs for unused listen methods
 // -------------------------------
 
 NS_IMETHODIMP
 nsTextServicesDocument::WillCreateNode(const nsAString& aTag, nsIDOMNode *aParent, int32_t aPosition)
 {
   return NS_OK;
@@ -3766,9 +3518,8 @@ nsTextServicesDocument::WillDeleteSelect
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsTextServicesDocument::DidDeleteSelection(nsISelection *aSelection)
 {
   return NS_OK;
 }
-