Bug 1546364 - Reformat to Google coding style in mailnews/imap (part 3). rs=reformat
authorJorg K <jorgk@jorgk.com>
Mon, 06 May 2019 21:30:12 +0200
changeset 34422 c6597fe7374a29da54e54d1f0ba62cf7328cc970
parent 34421 d9e252049461c31a3dee652c91d3ff11b864e6a7
child 34423 fb9a0f3d6c42c57cb65e636e78228e0418850cab
push id2407
push userclokep@gmail.com
push dateMon, 20 May 2019 17:11:26 +0000
treeherdercomm-beta@193428fd6fd4 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersreformat
bugs1546364
Bug 1546364 - Reformat to Google coding style in mailnews/imap (part 3). rs=reformat # ignore-this-changeset
mailnews/imap/src/nsImapSearchResults.cpp
mailnews/imap/src/nsImapSearchResults.h
mailnews/imap/src/nsImapServerResponseParser.cpp
mailnews/imap/src/nsImapServerResponseParser.h
mailnews/imap/src/nsImapService.cpp
mailnews/imap/src/nsImapService.h
mailnews/imap/src/nsImapStringBundle.cpp
mailnews/imap/src/nsImapStringBundle.h
mailnews/imap/src/nsImapUndoTxn.cpp
mailnews/imap/src/nsImapUndoTxn.h
mailnews/imap/src/nsImapUrl.cpp
mailnews/imap/src/nsImapUrl.h
mailnews/imap/src/nsImapUtils.cpp
mailnews/imap/src/nsImapUtils.h
mailnews/imap/src/nsSyncRunnableHelpers.cpp
mailnews/imap/src/nsSyncRunnableHelpers.h
mailnews/imap/test/TestImapFlagAndUidState.cpp
mailnews/imap/test/TestImapHdrXferInfo.cpp
--- a/mailnews/imap/src/nsImapSearchResults.cpp
+++ b/mailnews/imap/src/nsImapSearchResults.cpp
@@ -4,88 +4,69 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "msgCore.h"  // for pre-compiled headers
 
 #include "nsImapSearchResults.h"
 #include "prmem.h"
 #include "nsCRT.h"
 
-nsImapSearchResultSequence::nsImapSearchResultSequence()
-{
-}
+nsImapSearchResultSequence::nsImapSearchResultSequence() {}
 
-nsImapSearchResultSequence *nsImapSearchResultSequence::CreateSearchResultSequence()
-{
+nsImapSearchResultSequence *
+nsImapSearchResultSequence::CreateSearchResultSequence() {
   return new nsImapSearchResultSequence;
 }
 
-void nsImapSearchResultSequence::Clear(void)
-{
-    int32_t i = Length();
-    while (0 <= --i)
-    {
-      char* string = ElementAt(i);
-      PR_Free(string);
-    }
-    nsTArray<char*>::Clear();
+void nsImapSearchResultSequence::Clear(void) {
+  int32_t i = Length();
+  while (0 <= --i) {
+    char *string = ElementAt(i);
+    PR_Free(string);
+  }
+  nsTArray<char *>::Clear();
 }
 
-nsImapSearchResultSequence::~nsImapSearchResultSequence()
-{
-  Clear();
-}
+nsImapSearchResultSequence::~nsImapSearchResultSequence() { Clear(); }
 
+void nsImapSearchResultSequence::ResetSequence() { Clear(); }
 
-void nsImapSearchResultSequence::ResetSequence()
-{
-  Clear();
-}
-
-void nsImapSearchResultSequence::AddSearchResultLine(const char *searchLine)
-{
+void nsImapSearchResultSequence::AddSearchResultLine(const char *searchLine) {
   // The first add becomes node 2.  Fix this.
-  char *copiedSequence = PL_strdup(searchLine + 9); // 9 == "* SEARCH "
+  char *copiedSequence = PL_strdup(searchLine + 9);  // 9 == "* SEARCH "
 
   if (copiedSequence)  // if we can't allocate this then the search won't hit
     AppendElement(copiedSequence);
 }
 
-
-nsImapSearchResultIterator::nsImapSearchResultIterator(nsImapSearchResultSequence &sequence) :
-fSequence(sequence)
-{
+nsImapSearchResultIterator::nsImapSearchResultIterator(
+    nsImapSearchResultSequence &sequence)
+    : fSequence(sequence) {
   ResetIterator();
 }
 
-nsImapSearchResultIterator::~nsImapSearchResultIterator()
-{
-}
+nsImapSearchResultIterator::~nsImapSearchResultIterator() {}
 
-void  nsImapSearchResultIterator::ResetIterator()
-{
+void nsImapSearchResultIterator::ResetIterator() {
   fSequenceIndex = 0;
-  fCurrentLine = (char *) fSequence.SafeElementAt(fSequenceIndex);
+  fCurrentLine = (char *)fSequence.SafeElementAt(fSequenceIndex);
   fPositionInCurrentLine = fCurrentLine;
 }
 
-int32_t nsImapSearchResultIterator::GetNextMessageNumber()
-{
+int32_t nsImapSearchResultIterator::GetNextMessageNumber() {
   int32_t returnValue = 0;
-  if (fPositionInCurrentLine)
-  {
+  if (fPositionInCurrentLine) {
     returnValue = atoi(fPositionInCurrentLine);
 
     // eat the current number
     while (isdigit(*++fPositionInCurrentLine))
       ;
 
     if (*fPositionInCurrentLine == 0xD)  // found CR, no more digits on line
     {
-      fCurrentLine = (char *) fSequence.SafeElementAt(++fSequenceIndex);
+      fCurrentLine = (char *)fSequence.SafeElementAt(++fSequenceIndex);
       fPositionInCurrentLine = fCurrentLine;
-    }
-    else  // eat the space
+    } else  // eat the space
       fPositionInCurrentLine++;
   }
 
   return returnValue;
 }
--- a/mailnews/imap/src/nsImapSearchResults.h
+++ b/mailnews/imap/src/nsImapSearchResults.h
@@ -3,40 +3,38 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef nsImapSearchResults_h___
 #define nsImapSearchResults_h___
 
 #include "nsTArray.h"
 
-class nsImapSearchResultSequence : public nsTArray<char*>
-{
-public:
-    virtual ~nsImapSearchResultSequence();
-    static nsImapSearchResultSequence *CreateSearchResultSequence();
+class nsImapSearchResultSequence : public nsTArray<char *> {
+ public:
+  virtual ~nsImapSearchResultSequence();
+  static nsImapSearchResultSequence *CreateSearchResultSequence();
 
-    virtual void AddSearchResultLine(const char *searchLine);
-    virtual void ResetSequence();
-    void  Clear();
+  virtual void AddSearchResultLine(const char *searchLine);
+  virtual void ResetSequence();
+  void Clear();
 
-    friend class nsImapSearchResultIterator;
-private:
-    nsImapSearchResultSequence();
+  friend class nsImapSearchResultIterator;
+
+ private:
+  nsImapSearchResultSequence();
 };
 
 class nsImapSearchResultIterator {
-public:
-    explicit nsImapSearchResultIterator(nsImapSearchResultSequence &sequence);
-    virtual ~nsImapSearchResultIterator();
+ public:
+  explicit nsImapSearchResultIterator(nsImapSearchResultSequence &sequence);
+  virtual ~nsImapSearchResultIterator();
 
-    void  ResetIterator();
-    int32_t GetNextMessageNumber();   // returns 0 at end of list
-private:
-    nsImapSearchResultSequence &fSequence;
-    int32_t fSequenceIndex;
-    char  *fCurrentLine;
-    char  *fPositionInCurrentLine;
+  void ResetIterator();
+  int32_t GetNextMessageNumber();  // returns 0 at end of list
+ private:
+  nsImapSearchResultSequence &fSequence;
+  int32_t fSequenceIndex;
+  char *fCurrentLine;
+  char *fPositionInCurrentLine;
 };
 
-
-
 #endif
--- a/mailnews/imap/src/nsImapServerResponseParser.cpp
+++ b/mailnews/imap/src/nsImapServerResponseParser.cpp
@@ -13,37 +13,37 @@
 #include "nsIMAPNamespace.h"
 #include "nsImapUtils.h"
 #include "nsCRT.h"
 #include "nsMsgUtils.h"
 #include "mozilla/Logging.h"
 
 ////////////////// nsImapServerResponseParser /////////////////////////
 
-extern mozilla::LazyLogModule IMAP; // defined in nsImapProtocol.cpp
+extern mozilla::LazyLogModule IMAP;  // defined in nsImapProtocol.cpp
 
-nsImapServerResponseParser::nsImapServerResponseParser(nsImapProtocol &imapProtocolConnection)
-                            : nsIMAPGenericParser(),
-    fReportingErrors(true),
-    fCurrentFolderReadOnly(false),
-    fCurrentLineContainedFlagInfo(false),
-    fServerIsNetscape3xServer(false),
-    fNumberOfUnseenMessages(0),
-    fNumberOfExistingMessages(0),
-    fNumberOfRecentMessages(0),
-    fSizeOfMostRecentMessage(0),
-    fTotalDownloadSize(0),
-    fCurrentCommandTag(nullptr),
-    fSelectedMailboxName(nullptr),
-    fIMAPstate(kNonAuthenticated),
-    fLastChunk(false),
-    fNextChunkStartsWithNewline(false),
-    fServerConnection(imapProtocolConnection),
-    fHostSessionList(nullptr)
-{
+nsImapServerResponseParser::nsImapServerResponseParser(
+    nsImapProtocol &imapProtocolConnection)
+    : nsIMAPGenericParser(),
+      fReportingErrors(true),
+      fCurrentFolderReadOnly(false),
+      fCurrentLineContainedFlagInfo(false),
+      fServerIsNetscape3xServer(false),
+      fNumberOfUnseenMessages(0),
+      fNumberOfExistingMessages(0),
+      fNumberOfRecentMessages(0),
+      fSizeOfMostRecentMessage(0),
+      fTotalDownloadSize(0),
+      fCurrentCommandTag(nullptr),
+      fSelectedMailboxName(nullptr),
+      fIMAPstate(kNonAuthenticated),
+      fLastChunk(false),
+      fNextChunkStartsWithNewline(false),
+      fServerConnection(imapProtocolConnection),
+      fHostSessionList(nullptr) {
   fSearchResults = nsImapSearchResultSequence::CreateSearchResultSequence();
   fFolderAdminUrl = nullptr;
   fNetscapeServerVersionString = nullptr;
   fXSenderInfo = nullptr;
   fSupportsUserDefinedFlags = 0;
   fSettablePermanentFlags = 0;
   fCapabilityFlag = kCapabilityUndefined;
   fLastAlert = nullptr;
@@ -56,711 +56,632 @@ nsImapServerResponseParser::nsImapServer
   fStatusRecentMessages = 0;
   fStatusNextUID = nsMsgKey_None;
   fStatusExistingMessages = 0;
   fReceivedHeaderOrSizeForUID = nsMsgKey_None;
   fCondStoreEnabled = false;
   fStdJunkNotJunkUseOk = false;
 }
 
-nsImapServerResponseParser::~nsImapServerResponseParser()
-{
-  PR_Free( fCurrentCommandTag );
+nsImapServerResponseParser::~nsImapServerResponseParser() {
+  PR_Free(fCurrentCommandTag);
   delete fSearchResults;
-  PR_Free( fFolderAdminUrl );
-  PR_Free( fNetscapeServerVersionString );
-  PR_Free( fXSenderInfo );
-  PR_Free( fLastAlert );
-  PR_Free( fSelectedMailboxName );
+  PR_Free(fFolderAdminUrl);
+  PR_Free(fNetscapeServerVersionString);
+  PR_Free(fXSenderInfo);
+  PR_Free(fLastAlert);
+  PR_Free(fSelectedMailboxName);
   PR_Free(fAuthChallenge);
 }
 
-bool nsImapServerResponseParser::LastCommandSuccessful()
-{
-  return (!CommandFailed() &&
-    !fServerConnection.DeathSignalReceived() &&
-    nsIMAPGenericParser::LastCommandSuccessful());
+bool nsImapServerResponseParser::LastCommandSuccessful() {
+  return (!CommandFailed() && !fServerConnection.DeathSignalReceived() &&
+          nsIMAPGenericParser::LastCommandSuccessful());
 }
 
 // returns true if things look ok to continue
-bool nsImapServerResponseParser::GetNextLineForParser(char **nextLine)
-{
+bool nsImapServerResponseParser::GetNextLineForParser(char **nextLine) {
   bool rv = true;
   *nextLine = fServerConnection.CreateNewLineFromSocket();
   if (fServerConnection.DeathSignalReceived() ||
       NS_FAILED(fServerConnection.GetConnectionStatus()))
     rv = false;
   // we'd really like to try to silently reconnect, but we shouldn't put this
   // message up just in the interrupt case
   if (NS_FAILED(fServerConnection.GetConnectionStatus()) &&
       !fServerConnection.DeathSignalReceived())
     fServerConnection.AlertUserEventUsingName("imapServerDisconnected");
   return rv;
 }
 
-bool nsImapServerResponseParser::CommandFailed()
-{
+bool nsImapServerResponseParser::CommandFailed() {
   return fCurrentCommandFailed;
 }
 
-void nsImapServerResponseParser::SetCommandFailed(bool failed)
-{
+void nsImapServerResponseParser::SetCommandFailed(bool failed) {
   fCurrentCommandFailed = failed;
 }
 
-void nsImapServerResponseParser::SetFlagState(nsIImapFlagAndUidState *state)
-{
+void nsImapServerResponseParser::SetFlagState(nsIImapFlagAndUidState *state) {
   fFlagState = state;
 }
 
-uint32_t nsImapServerResponseParser::SizeOfMostRecentMessage()
-{
+uint32_t nsImapServerResponseParser::SizeOfMostRecentMessage() {
   return fSizeOfMostRecentMessage;
 }
 
 // Call this when adding a pipelined command to the session
-void nsImapServerResponseParser::IncrementNumberOfTaggedResponsesExpected(const char *newExpectedTag)
-{
+void nsImapServerResponseParser::IncrementNumberOfTaggedResponsesExpected(
+    const char *newExpectedTag) {
   fNumberOfTaggedResponsesExpected++;
-  PR_Free( fCurrentCommandTag );
+  PR_Free(fCurrentCommandTag);
   fCurrentCommandTag = PL_strdup(newExpectedTag);
-  if (!fCurrentCommandTag)
-    HandleMemoryFailure();
+  if (!fCurrentCommandTag) HandleMemoryFailure();
 }
 
-void nsImapServerResponseParser::InitializeState()
-{
+void nsImapServerResponseParser::InitializeState() {
   fCurrentCommandFailed = false;
   fNumberOfRecentMessages = 0;
   fReceivedHeaderOrSizeForUID = nsMsgKey_None;
 }
 
 // RFC3501:  response = *(continue-req / response-data) response-done
 //           response-data = "*" SP (resp-cond-state / resp-cond-bye /
 //                           mailbox-data / message-data / capability-data) CRLF
 //           continue-req    = "+" SP (resp-text / base64) CRLF
-void nsImapServerResponseParser::ParseIMAPServerResponse(const char *aCurrentCommand,
-                                                         bool aIgnoreBadAndNOResponses,
-                                                         char *aGreetingWithCapability)
-{
-
+void nsImapServerResponseParser::ParseIMAPServerResponse(
+    const char *aCurrentCommand, bool aIgnoreBadAndNOResponses,
+    char *aGreetingWithCapability) {
   NS_ASSERTION(aCurrentCommand && *aCurrentCommand != '\r' &&
-    *aCurrentCommand != '\n' && *aCurrentCommand != ' ', "Invailid command string");
+                   *aCurrentCommand != '\n' && *aCurrentCommand != ' ',
+               "Invailid command string");
   bool sendingIdleDone = !strcmp(aCurrentCommand, "DONE" CRLF);
-  if (sendingIdleDone)
-    fWaitingForMoreClientInput = false;
+  if (sendingIdleDone) fWaitingForMoreClientInput = false;
 
   // Reinitialize the parser
   SetConnected(true);
   SetSyntaxError(false);
 
   // Reinitialize our state
   InitializeState();
 
   // the default is to not pipeline
   fNumberOfTaggedResponsesExpected = 1;
   int numberOfTaggedResponsesReceived = 0;
 
   nsCString copyCurrentCommand(aCurrentCommand);
-  if (!fServerConnection.DeathSignalReceived())
-  {
+  if (!fServerConnection.DeathSignalReceived()) {
     char *placeInTokenString = nullptr;
     char *tagToken = nullptr;
     const char *commandToken = nullptr;
     bool inIdle = false;
-    if (!sendingIdleDone)
-    {
+    if (!sendingIdleDone) {
       placeInTokenString = copyCurrentCommand.BeginWriting();
       tagToken = NS_strtok(WHITESPACE, &placeInTokenString);
       commandToken = NS_strtok(WHITESPACE, &placeInTokenString);
-    }
-    else
+    } else
       commandToken = "DONE";
-    if (tagToken)
-    {
-      PR_Free( fCurrentCommandTag );
+    if (tagToken) {
+      PR_Free(fCurrentCommandTag);
       fCurrentCommandTag = PL_strdup(tagToken);
-      if (!fCurrentCommandTag)
-        HandleMemoryFailure();
+      if (!fCurrentCommandTag) HandleMemoryFailure();
       inIdle = commandToken && !strcmp(commandToken, "IDLE");
     }
 
     if (commandToken && ContinueParse())
       PreProcessCommandToken(commandToken, aCurrentCommand);
 
     // For checking expected response to IDLE command below.
     bool untagged = false;
 
-    if (ContinueParse())
-    {
+    if (ContinueParse()) {
       ResetLexAnalyzer();
 
-      if (aGreetingWithCapability)
-      {
+      if (aGreetingWithCapability) {
         PR_FREEIF(fCurrentLine);
         fCurrentLine = aGreetingWithCapability;
       }
 
       do {
         AdvanceToNextToken();
 
         // untagged responses [RFC3501, Sec. 2.2.2]
-        while (ContinueParse() && fNextToken && *fNextToken == '*')
-        {
+        while (ContinueParse() && fNextToken && *fNextToken == '*') {
           response_data();
-          if (ContinueParse())
-          {
+          if (ContinueParse()) {
             if (!fAtEndOfLine)
               SetSyntaxError(true);
-            else if (!inIdle && !fCurrentCommandFailed && !aGreetingWithCapability)
+            else if (!inIdle && !fCurrentCommandFailed &&
+                     !aGreetingWithCapability)
               AdvanceToNextToken();
           }
           untagged = true;
         }
 
         // command continuation request [RFC3501, Sec. 7.5]
-        if (ContinueParse() && fNextToken && *fNextToken == '+')  // never pipeline APPEND or AUTHENTICATE
+        if (ContinueParse() && fNextToken &&
+            *fNextToken == '+')  // never pipeline APPEND or AUTHENTICATE
         {
-          NS_ASSERTION((fNumberOfTaggedResponsesExpected - numberOfTaggedResponsesReceived) == 1,
-            " didn't get the number of tagged responses we expected");
+          NS_ASSERTION(
+              (fNumberOfTaggedResponsesExpected -
+               numberOfTaggedResponsesReceived) == 1,
+              " didn't get the number of tagged responses we expected");
           numberOfTaggedResponsesReceived = fNumberOfTaggedResponsesExpected;
-          if (commandToken && !PL_strcasecmp(commandToken, "authenticate") && placeInTokenString &&
-            (!PL_strncasecmp(placeInTokenString, "CRAM-MD5", strlen("CRAM-MD5"))
-             || !PL_strncasecmp(placeInTokenString, "NTLM", strlen("NTLM"))
-             || !PL_strncasecmp(placeInTokenString, "GSSAPI", strlen("GSSAPI"))
-             || !PL_strncasecmp(placeInTokenString, "MSN", strlen("MSN"))))
-          {
-            // we need to store the challenge from the server if we are using CRAM-MD5 or NTLM.
+          if (commandToken && !PL_strcasecmp(commandToken, "authenticate") &&
+              placeInTokenString &&
+              (!PL_strncasecmp(placeInTokenString, "CRAM-MD5",
+                               strlen("CRAM-MD5")) ||
+               !PL_strncasecmp(placeInTokenString, "NTLM", strlen("NTLM")) ||
+               !PL_strncasecmp(placeInTokenString, "GSSAPI",
+                               strlen("GSSAPI")) ||
+               !PL_strncasecmp(placeInTokenString, "MSN", strlen("MSN")))) {
+            // we need to store the challenge from the server if we are using
+            // CRAM-MD5 or NTLM.
             authChallengeResponse_data();
           }
-        }
-        else
+        } else
           numberOfTaggedResponsesReceived++;
 
         if (numberOfTaggedResponsesReceived < fNumberOfTaggedResponsesExpected)
           response_tagged();
 
-      } while (ContinueParse() && !inIdle && (numberOfTaggedResponsesReceived < fNumberOfTaggedResponsesExpected));
+      } while (
+          ContinueParse() && !inIdle &&
+          (numberOfTaggedResponsesReceived < fNumberOfTaggedResponsesExpected));
 
       // check and see if the server is waiting for more input
-      // it's possible that we ate this + while parsing certain responses (like cram data),
-      // in these cases, the parsing routine for that specific command will manually set
-      // fWaitingForMoreClientInput so we don't lose that information....
-      if ((fNextToken && *fNextToken == '+') || inIdle)
-      {
-        if (inIdle && !((fNextToken && *fNextToken == '+') || untagged))
-        {
+      // it's possible that we ate this + while parsing certain responses (like
+      // cram data), in these cases, the parsing routine for that specific
+      // command will manually set fWaitingForMoreClientInput so we don't lose
+      // that information....
+      if ((fNextToken && *fNextToken == '+') || inIdle) {
+        if (inIdle && !((fNextToken && *fNextToken == '+') || untagged)) {
           // IDLE "response" + will not be "eaten" as described above since it
           // is not an authentication response. So if IDLE response does not
           // begin with '+' (continuation) or '*' (untagged and probably useful
           // response) then something is wrong and it is probably a tagged
-          // NO or BAD due to transient error or bad configuration of the server.
-          if (!PL_strcmp(fCurrentCommandTag, fNextToken))
-          {
+          // NO or BAD due to transient error or bad configuration of the
+          // server.
+          if (!PL_strcmp(fCurrentCommandTag, fNextToken)) {
             response_tagged();
-          }
-          else
-          {
-            // Expected tag doesn't match the received tag. Not good, start over.
+          } else {
+            // Expected tag doesn't match the received tag. Not good, start
+            // over.
             response_fatal();
           }
-          // Show an alert notification containing the server response to bad IDLE.
+          // Show an alert notification containing the server response to bad
+          // IDLE.
           fServerConnection.AlertUserEventFromServer(fCurrentLine, true);
-        }
-        else
-        {
+        } else {
           fWaitingForMoreClientInput = true;
         }
       }
       // if we aren't still waiting for more input....
-      else if (!fWaitingForMoreClientInput && !aGreetingWithCapability)
-      {
-        if (ContinueParse())
-          response_done();
+      else if (!fWaitingForMoreClientInput && !aGreetingWithCapability) {
+        if (ContinueParse()) response_done();
 
-        if (ContinueParse() && !CommandFailed())
-        {
+        if (ContinueParse() && !CommandFailed()) {
           // a successful command may change the eIMAPstate
           ProcessOkCommand(commandToken);
-        }
-        else if (CommandFailed())
-        {
+        } else if (CommandFailed()) {
           // a failed command may change the eIMAPstate
           ProcessBadCommand(commandToken);
           if (fReportingErrors && !aIgnoreBadAndNOResponses)
             fServerConnection.AlertUserEventFromServer(fCurrentLine, false);
         }
       }
     }
-  }
-  else
+  } else
     SetConnected(false);
 }
 
-void nsImapServerResponseParser::HandleMemoryFailure()
-{
+void nsImapServerResponseParser::HandleMemoryFailure() {
   fServerConnection.AlertUserEventUsingName("imapOutOfMemory");
   nsIMAPGenericParser::HandleMemoryFailure();
 }
 
-
 // SEARCH is the only command that requires pre-processing for now.
 // others will be added here.
-void nsImapServerResponseParser::PreProcessCommandToken(const char *commandToken,
-                                                        const char *currentCommand)
-{
+void nsImapServerResponseParser::PreProcessCommandToken(
+    const char *commandToken, const char *currentCommand) {
   fCurrentCommandIsSingleMessageFetch = false;
   fWaitingForMoreClientInput = false;
 
   if (!PL_strcasecmp(commandToken, "SEARCH"))
     fSearchResults->ResetSequence();
-  else if (!PL_strcasecmp(commandToken, "SELECT") && currentCommand)
-  {
+  else if (!PL_strcasecmp(commandToken, "SELECT") && currentCommand) {
     // the mailbox name must be quoted, so strip the quotes
     const char *openQuote = PL_strchr(currentCommand, '"');
     NS_ASSERTION(openQuote, "expected open quote in imap server response");
-    if (!openQuote)
-    { // ill formed select command
+    if (!openQuote) {  // ill formed select command
       openQuote = PL_strchr(currentCommand, ' ');
     }
-    PR_Free( fSelectedMailboxName);
+    PR_Free(fSelectedMailboxName);
     fSelectedMailboxName = PL_strdup(openQuote + 1);
-    if (fSelectedMailboxName)
-    {
+    if (fSelectedMailboxName) {
       // strip the escape chars and the ending quote
       char *currentChar = fSelectedMailboxName;
-      while (*currentChar)
-      {
-        if (*currentChar == '\\')
-        {
-          PL_strcpy(currentChar, currentChar+1);
+      while (*currentChar) {
+        if (*currentChar == '\\') {
+          PL_strcpy(currentChar, currentChar + 1);
           currentChar++;  // skip what we are escaping
-        }
-        else if (*currentChar == '\"')
+        } else if (*currentChar == '\"')
           *currentChar = 0;  // end quote
         else
           currentChar++;
       }
-    }
-    else
+    } else
       HandleMemoryFailure();
 
     // we don't want bogus info for this new box
-    //delete fFlagState;  // not our object
-    //fFlagState = nullptr;
-  }
-  else if (!PL_strcasecmp(commandToken, "CLOSE"))
-  {
+    // delete fFlagState;  // not our object
+    // fFlagState = nullptr;
+  } else if (!PL_strcasecmp(commandToken, "CLOSE")) {
     return;  // just for debugging
     // we don't want bogus info outside the selected state
-    //delete fFlagState;  // not our object
-    //fFlagState = nullptr;
-  }
-  else if (!PL_strcasecmp(commandToken, "UID"))
-  {
+    // delete fFlagState;  // not our object
+    // fFlagState = nullptr;
+  } else if (!PL_strcasecmp(commandToken, "UID")) {
     nsCString copyCurrentCommand(currentCommand);
-    if (!fServerConnection.DeathSignalReceived())
-    {
+    if (!fServerConnection.DeathSignalReceived()) {
       char *placeInTokenString = copyCurrentCommand.BeginWriting();
-      (void) NS_strtok(WHITESPACE, &placeInTokenString); // skip tag token
-      (void) NS_strtok(WHITESPACE, &placeInTokenString); // skip uid token
+      (void)NS_strtok(WHITESPACE, &placeInTokenString);  // skip tag token
+      (void)NS_strtok(WHITESPACE, &placeInTokenString);  // skip uid token
       char *fetchToken = NS_strtok(WHITESPACE, &placeInTokenString);
-      if (!PL_strcasecmp(fetchToken, "FETCH") )
-      {
+      if (!PL_strcasecmp(fetchToken, "FETCH")) {
         char *uidStringToken = NS_strtok(WHITESPACE, &placeInTokenString);
         // , and : are uid delimiters
         if (!PL_strchr(uidStringToken, ',') && !PL_strchr(uidStringToken, ':'))
           fCurrentCommandIsSingleMessageFetch = true;
       }
     }
   }
 }
 
-const char *nsImapServerResponseParser::GetSelectedMailboxName()
-{
+const char *nsImapServerResponseParser::GetSelectedMailboxName() {
   return fSelectedMailboxName;
 }
 
-nsImapSearchResultIterator *nsImapServerResponseParser::CreateSearchResultIterator()
-{
+nsImapSearchResultIterator *
+nsImapServerResponseParser::CreateSearchResultIterator() {
   return new nsImapSearchResultIterator(*fSearchResults);
 }
 
-nsImapServerResponseParser::eIMAPstate nsImapServerResponseParser::GetIMAPstate()
-{
+nsImapServerResponseParser::eIMAPstate
+nsImapServerResponseParser::GetIMAPstate() {
   return fIMAPstate;
 }
 
-void nsImapServerResponseParser::PreauthSetAuthenticatedState()
-{
+void nsImapServerResponseParser::PreauthSetAuthenticatedState() {
   fIMAPstate = kAuthenticated;
 }
 
-void nsImapServerResponseParser::ProcessOkCommand(const char *commandToken)
-{
+void nsImapServerResponseParser::ProcessOkCommand(const char *commandToken) {
   if (!PL_strcasecmp(commandToken, "LOGIN") ||
-    !PL_strcasecmp(commandToken, "AUTHENTICATE"))
+      !PL_strcasecmp(commandToken, "AUTHENTICATE"))
     fIMAPstate = kAuthenticated;
   else if (!PL_strcasecmp(commandToken, "LOGOUT"))
     fIMAPstate = kNonAuthenticated;
   else if (!PL_strcasecmp(commandToken, "SELECT") ||
-    !PL_strcasecmp(commandToken, "EXAMINE"))
+           !PL_strcasecmp(commandToken, "EXAMINE"))
     fIMAPstate = kFolderSelected;
-  else if (!PL_strcasecmp(commandToken, "CLOSE"))
-  {
+  else if (!PL_strcasecmp(commandToken, "CLOSE")) {
     fIMAPstate = kAuthenticated;
     // we no longer have a selected mailbox.
-    PR_FREEIF( fSelectedMailboxName );
-  }
-  else if ((!PL_strcasecmp(commandToken, "LIST")) ||
-          (!PL_strcasecmp(commandToken, "LSUB")) ||
-          (!PL_strcasecmp(commandToken, "XLIST")))
-  {
-    //fServerConnection.MailboxDiscoveryFinished();
+    PR_FREEIF(fSelectedMailboxName);
+  } else if ((!PL_strcasecmp(commandToken, "LIST")) ||
+             (!PL_strcasecmp(commandToken, "LSUB")) ||
+             (!PL_strcasecmp(commandToken, "XLIST"))) {
+    // fServerConnection.MailboxDiscoveryFinished();
     // This used to be reporting that we were finished
     // discovering folders for each time we issued a
     // LIST or LSUB.  So if we explicitly listed the
     // INBOX, or Trash, or namespaces, we would get multiple
     // "done" states, even though we hadn't finished.
     // Move this to be called from the connection object
     // itself.
-  }
-  else if (!PL_strcasecmp(commandToken, "FETCH"))
-  {
-    if (!fZeroLengthMessageUidString.IsEmpty())
-    {
+  } else if (!PL_strcasecmp(commandToken, "FETCH")) {
+    if (!fZeroLengthMessageUidString.IsEmpty()) {
       // "Deleting zero length message");
-      fServerConnection.Store(fZeroLengthMessageUidString, "+Flags (\\Deleted)", true);
-      if (LastCommandSuccessful())
-        fServerConnection.Expunge();
+      fServerConnection.Store(fZeroLengthMessageUidString, "+Flags (\\Deleted)",
+                              true);
+      if (LastCommandSuccessful()) fServerConnection.Expunge();
 
       fZeroLengthMessageUidString.Truncate();
     }
   }
-  if (GetFillingInShell())
-  {
+  if (GetFillingInShell()) {
     // There is a BODYSTRUCTURE response.  Now let's generate the stream...
     // that is, if we're not doing it already
-    if (!m_shell->IsBeingGenerated())
-    {
+    if (!m_shell->IsBeingGenerated()) {
       nsImapProtocol *navCon = &fServerConnection;
 
       char *imapPart = nullptr;
 
       fServerConnection.GetCurrentUrl()->GetImapPartToFetch(&imapPart);
       m_shell->Generate(imapPart);
       PR_Free(imapPart);
 
-      if ((navCon && navCon->GetPseudoInterrupted())
-        || fServerConnection.DeathSignalReceived())
-      {
+      if ((navCon && navCon->GetPseudoInterrupted()) ||
+          fServerConnection.DeathSignalReceived()) {
         // we were pseudointerrupted or interrupted
-        // if it's not in the cache, then we were (pseudo)interrupted while generating
-        // for the first time. Release it.
-        if (!m_shell->IsShellCached())
-          m_shell = nullptr;
+        // if it's not in the cache, then we were (pseudo)interrupted while
+        // generating for the first time. Release it.
+        if (!m_shell->IsShellCached()) m_shell = nullptr;
         navCon->PseudoInterrupt(false);
-      }
-      else if (m_shell->GetIsValid())
-      {
-        // If we have a valid shell that has not already been cached, then cache it.
-        if (!m_shell->IsShellCached() && fHostSessionList)  // cache is responsible for destroying it
+      } else if (m_shell->GetIsValid()) {
+        // If we have a valid shell that has not already been cached, then cache
+        // it.
+        if (!m_shell->IsShellCached() &&
+            fHostSessionList)  // cache is responsible for destroying it
         {
           MOZ_LOG(IMAP, mozilla::LogLevel::Info,
-            ("BODYSHELL:  Adding shell to cache."));
+                  ("BODYSHELL:  Adding shell to cache."));
           const char *serverKey = fServerConnection.GetImapServerKey();
-          fHostSessionList->AddShellToCacheForHost(
-            serverKey, m_shell);
+          fHostSessionList->AddShellToCacheForHost(serverKey, m_shell);
         }
       }
       m_shell = nullptr;
     }
   }
 }
 
-void nsImapServerResponseParser::ProcessBadCommand(const char *commandToken)
-{
+void nsImapServerResponseParser::ProcessBadCommand(const char *commandToken) {
   if (!PL_strcasecmp(commandToken, "LOGIN") ||
-    !PL_strcasecmp(commandToken, "AUTHENTICATE"))
+      !PL_strcasecmp(commandToken, "AUTHENTICATE"))
     fIMAPstate = kNonAuthenticated;
   else if (!PL_strcasecmp(commandToken, "LOGOUT"))
-    fIMAPstate = kNonAuthenticated; // ??
+    fIMAPstate = kNonAuthenticated;  // ??
   else if (!PL_strcasecmp(commandToken, "SELECT") ||
-    !PL_strcasecmp(commandToken, "EXAMINE"))
-    fIMAPstate = kAuthenticated; // nothing selected
+           !PL_strcasecmp(commandToken, "EXAMINE"))
+    fIMAPstate = kAuthenticated;  // nothing selected
   else if (!PL_strcasecmp(commandToken, "CLOSE"))
-    fIMAPstate = kAuthenticated; // nothing selected
-  if (GetFillingInShell() && !m_shell->IsBeingGenerated())
-    m_shell = nullptr;
+    fIMAPstate = kAuthenticated;  // nothing selected
+  if (GetFillingInShell() && !m_shell->IsBeingGenerated()) m_shell = nullptr;
 }
 
-
-
 // RFC3501:  response-data = "*" SP (resp-cond-state / resp-cond-bye /
 //                           mailbox-data / message-data / capability-data) CRLF
 // These are ``untagged'' responses [RFC3501, Sec. 2.2.2]
 /*
  The RFC1730 grammar spec did not allow one symbol look ahead to determine
  between mailbox_data / message_data so I combined the numeric possibilities
  of mailbox_data and all of message_data into numeric_mailbox_data.
 
  It is assumed that the initial "*" is already consumed before calling this
  method. The production implemented here is
          response_data   ::= (resp_cond_state / resp_cond_bye /
                               mailbox_data / numeric_mailbox_data /
                               capability_data)
                               CRLF
 */
-void nsImapServerResponseParser::response_data()
-{
+void nsImapServerResponseParser::response_data() {
   AdvanceToNextToken();
 
-  if (ContinueParse())
-  {
+  if (ContinueParse()) {
     // Instead of comparing lots of strings and make function calls, try to
     // pre-flight the possibilities based on the first letter of the token.
-    switch (NS_ToUpper(fNextToken[0]))
-    {
-    case 'O':   // OK
-      if (NS_ToUpper(fNextToken[1]) == 'K')
-        resp_cond_state(false);
-      else SetSyntaxError(true);
-      break;
-    case 'N':   // NO
-      if (NS_ToUpper(fNextToken[1]) == 'O')
-        resp_cond_state(false);
-      else if (!PL_strcasecmp(fNextToken, "NAMESPACE"))
-        namespace_data();
-      else SetSyntaxError(true);
-      break;
-    case 'B':   // BAD
-      if (!PL_strcasecmp(fNextToken, "BAD"))
-        resp_cond_state(false);
-      else if (!PL_strcasecmp(fNextToken, "BYE"))
-        resp_cond_bye();
-      else SetSyntaxError(true);
-      break;
-    case 'F':
-      if (!PL_strcasecmp(fNextToken, "FLAGS"))
-        mailbox_data();
-      else SetSyntaxError(true);
-      break;
-    case 'P':
-      if (PL_strcasecmp(fNextToken, "PERMANENTFLAGS"))
-        mailbox_data();
-      else SetSyntaxError(true);
-      break;
-    case 'L':
-      if (!PL_strcasecmp(fNextToken, "LIST") || !PL_strcasecmp(fNextToken, "LSUB"))
-        mailbox_data();
-      else if (!PL_strcasecmp(fNextToken, "LANGUAGE"))
-        language_data();
-      else
-        SetSyntaxError(true);
-      break;
-    case 'M':
-      if (!PL_strcasecmp(fNextToken, "MAILBOX"))
-        mailbox_data();
-      else if (!PL_strcasecmp(fNextToken, "MYRIGHTS"))
-        myrights_data(false);
-      else SetSyntaxError(true);
-      break;
-    case 'S':
-      if (!PL_strcasecmp(fNextToken, "SEARCH"))
-        mailbox_data();
-      else if (!PL_strcasecmp(fNextToken, "STATUS"))
-      {
-        AdvanceToNextToken();
-        if (fNextToken)
-        {
-          char *mailboxName = CreateAstring();
-          PL_strfree( mailboxName);
-        }
-        while (ContinueParse() && !fAtEndOfLine)
-        {
+    switch (NS_ToUpper(fNextToken[0])) {
+      case 'O':  // OK
+        if (NS_ToUpper(fNextToken[1]) == 'K')
+          resp_cond_state(false);
+        else
+          SetSyntaxError(true);
+        break;
+      case 'N':  // NO
+        if (NS_ToUpper(fNextToken[1]) == 'O')
+          resp_cond_state(false);
+        else if (!PL_strcasecmp(fNextToken, "NAMESPACE"))
+          namespace_data();
+        else
+          SetSyntaxError(true);
+        break;
+      case 'B':  // BAD
+        if (!PL_strcasecmp(fNextToken, "BAD"))
+          resp_cond_state(false);
+        else if (!PL_strcasecmp(fNextToken, "BYE"))
+          resp_cond_bye();
+        else
+          SetSyntaxError(true);
+        break;
+      case 'F':
+        if (!PL_strcasecmp(fNextToken, "FLAGS"))
+          mailbox_data();
+        else
+          SetSyntaxError(true);
+        break;
+      case 'P':
+        if (PL_strcasecmp(fNextToken, "PERMANENTFLAGS"))
+          mailbox_data();
+        else
+          SetSyntaxError(true);
+        break;
+      case 'L':
+        if (!PL_strcasecmp(fNextToken, "LIST") ||
+            !PL_strcasecmp(fNextToken, "LSUB"))
+          mailbox_data();
+        else if (!PL_strcasecmp(fNextToken, "LANGUAGE"))
+          language_data();
+        else
+          SetSyntaxError(true);
+        break;
+      case 'M':
+        if (!PL_strcasecmp(fNextToken, "MAILBOX"))
+          mailbox_data();
+        else if (!PL_strcasecmp(fNextToken, "MYRIGHTS"))
+          myrights_data(false);
+        else
+          SetSyntaxError(true);
+        break;
+      case 'S':
+        if (!PL_strcasecmp(fNextToken, "SEARCH"))
+          mailbox_data();
+        else if (!PL_strcasecmp(fNextToken, "STATUS")) {
+          AdvanceToNextToken();
+          if (fNextToken) {
+            char *mailboxName = CreateAstring();
+            PL_strfree(mailboxName);
+          }
+          while (ContinueParse() && !fAtEndOfLine) {
+            AdvanceToNextToken();
+            if (!fNextToken) break;
+
+            if (*fNextToken == '(') fNextToken++;
+            if (!PL_strcasecmp(fNextToken, "UIDNEXT")) {
+              AdvanceToNextToken();
+              if (fNextToken) {
+                fStatusNextUID = strtoul(fNextToken, nullptr, 10);
+                // if this token ends in ')', then it is the last token
+                // else we advance
+                if (*(fNextToken + strlen(fNextToken) - 1) == ')')
+                  fNextToken += strlen(fNextToken) - 1;
+              }
+            } else if (!PL_strcasecmp(fNextToken, "MESSAGES")) {
+              AdvanceToNextToken();
+              if (fNextToken) {
+                fStatusExistingMessages = strtoul(fNextToken, nullptr, 10);
+                // if this token ends in ')', then it is the last token
+                // else we advance
+                if (*(fNextToken + strlen(fNextToken) - 1) == ')')
+                  fNextToken += strlen(fNextToken) - 1;
+              }
+            } else if (!PL_strcasecmp(fNextToken, "UNSEEN")) {
+              AdvanceToNextToken();
+              if (fNextToken) {
+                fStatusUnseenMessages = strtoul(fNextToken, nullptr, 10);
+                // if this token ends in ')', then it is the last token
+                // else we advance
+                if (*(fNextToken + strlen(fNextToken) - 1) == ')')
+                  fNextToken += strlen(fNextToken) - 1;
+              }
+            } else if (!PL_strcasecmp(fNextToken, "RECENT")) {
+              AdvanceToNextToken();
+              if (fNextToken) {
+                fStatusRecentMessages = strtoul(fNextToken, nullptr, 10);
+                // if this token ends in ')', then it is the last token
+                // else we advance
+                if (*(fNextToken + strlen(fNextToken) - 1) == ')')
+                  fNextToken += strlen(fNextToken) - 1;
+              }
+            } else if (*fNextToken == ')')
+              break;
+            else if (!fAtEndOfLine)
+              SetSyntaxError(true);
+          }
+        } else
+          SetSyntaxError(true);
+        break;
+      case 'C':
+        if (!PL_strcasecmp(fNextToken, "CAPABILITY"))
+          capability_data();
+        else
+          SetSyntaxError(true);
+        break;
+      case 'V':
+        if (!PL_strcasecmp(fNextToken, "VERSION")) {
+          // figure out the version of the Netscape server here
+          PR_FREEIF(fNetscapeServerVersionString);
           AdvanceToNextToken();
           if (!fNextToken)
-            break;
-
-          if (*fNextToken == '(') fNextToken++;
-          if (!PL_strcasecmp(fNextToken, "UIDNEXT"))
-          {
-            AdvanceToNextToken();
-            if (fNextToken)
-            {
-              fStatusNextUID = strtoul(fNextToken, nullptr, 10);
-              // if this token ends in ')', then it is the last token
-              // else we advance
-              if ( *(fNextToken + strlen(fNextToken) - 1) == ')')
-                fNextToken += strlen(fNextToken) - 1;
-            }
-          }
-          else if (!PL_strcasecmp(fNextToken, "MESSAGES"))
-          {
+            SetSyntaxError(true);
+          else {
+            fNetscapeServerVersionString = CreateAstring();
             AdvanceToNextToken();
-            if (fNextToken)
-            {
-              fStatusExistingMessages = strtoul(fNextToken, nullptr, 10);
-              // if this token ends in ')', then it is the last token
-              // else we advance
-              if ( *(fNextToken + strlen(fNextToken) - 1) == ')')
-                fNextToken += strlen(fNextToken) - 1;
-            }
-          }
-          else if (!PL_strcasecmp(fNextToken, "UNSEEN"))
-          {
-            AdvanceToNextToken();
-            if (fNextToken)
-            {
-              fStatusUnseenMessages = strtoul(fNextToken, nullptr, 10);
-              // if this token ends in ')', then it is the last token
-              // else we advance
-              if ( *(fNextToken + strlen(fNextToken) - 1) == ')')
-                fNextToken += strlen(fNextToken) - 1;
+            if (fNetscapeServerVersionString) {
+              fServerIsNetscape3xServer =
+                  (*fNetscapeServerVersionString == '3');
             }
           }
-          else if (!PL_strcasecmp(fNextToken, "RECENT"))
-          {
+          skip_to_CRLF();
+        } else
+          SetSyntaxError(true);
+        break;
+      case 'A':
+        if (!PL_strcasecmp(fNextToken, "ACL")) {
+          acl_data();
+        } else if (!PL_strcasecmp(fNextToken, "ACCOUNT-URL")) {
+          fMailAccountUrl.Truncate();
+          AdvanceToNextToken();
+          if (!fNextToken)
+            SetSyntaxError(true);
+          else {
+            fMailAccountUrl.Adopt(CreateAstring());
             AdvanceToNextToken();
-            if (fNextToken)
-            {
-              fStatusRecentMessages = strtoul(fNextToken, nullptr, 10);
-              // if this token ends in ')', then it is the last token
-              // else we advance
-              if ( *(fNextToken + strlen(fNextToken) - 1) == ')')
-                fNextToken += strlen(fNextToken) - 1;
+          }
+        } else
+          SetSyntaxError(true);
+        break;
+      case 'E':
+        if (!PL_strcasecmp(fNextToken, "ENABLED")) enable_data();
+        break;
+      case 'X':
+        if (!PL_strcasecmp(fNextToken, "XSERVERINFO"))
+          xserverinfo_data();
+        else if (!PL_strcasecmp(fNextToken, "XMAILBOXINFO"))
+          xmailboxinfo_data();
+        else if (!PL_strcasecmp(fNextToken, "XAOL-OPTION"))
+          skip_to_CRLF();
+        else if (!PL_strcasecmp(fNextToken, "XLIST"))
+          mailbox_data();
+        else {
+          // check if custom command
+          nsAutoCString customCommand;
+          fServerConnection.GetCurrentUrl()->GetCommand(customCommand);
+          if (customCommand.Equals(fNextToken)) {
+            nsAutoCString customCommandResponse;
+            while (Connected() && !fAtEndOfLine) {
+              AdvanceToNextToken();
+              customCommandResponse.Append(fNextToken);
+              customCommandResponse.Append(' ');
             }
-          }
-          else if (*fNextToken == ')')
-            break;
-          else if (!fAtEndOfLine)
+            fServerConnection.GetCurrentUrl()->SetCustomCommandResult(
+                customCommandResponse);
+          } else
             SetSyntaxError(true);
         }
-      } else SetSyntaxError(true);
-      break;
-    case 'C':
-      if (!PL_strcasecmp(fNextToken, "CAPABILITY"))
-        capability_data();
-      else SetSyntaxError(true);
-      break;
-    case 'V':
-      if (!PL_strcasecmp(fNextToken, "VERSION"))
-      {
-        // figure out the version of the Netscape server here
-        PR_FREEIF(fNetscapeServerVersionString);
-        AdvanceToNextToken();
-        if (! fNextToken)
-          SetSyntaxError(true);
-        else
-        {
-          fNetscapeServerVersionString = CreateAstring();
-          AdvanceToNextToken();
-          if (fNetscapeServerVersionString)
-          {
-            fServerIsNetscape3xServer = (*fNetscapeServerVersionString == '3');
-          }
-        }
-        skip_to_CRLF();
-      }
-      else SetSyntaxError(true);
-      break;
-    case 'A':
-      if (!PL_strcasecmp(fNextToken, "ACL"))
-      {
-        acl_data();
-      }
-      else if (!PL_strcasecmp(fNextToken, "ACCOUNT-URL"))
-      {
-        fMailAccountUrl.Truncate();
-        AdvanceToNextToken();
-        if (! fNextToken)
-          SetSyntaxError(true);
-        else
-        {
-          fMailAccountUrl.Adopt(CreateAstring());
-          AdvanceToNextToken();
-        }
-      }
-      else SetSyntaxError(true);
-      break;
-    case 'E':
-      if (!PL_strcasecmp(fNextToken, "ENABLED"))
-        enable_data();
-      break;
-    case 'X':
-      if (!PL_strcasecmp(fNextToken, "XSERVERINFO"))
-        xserverinfo_data();
-      else if (!PL_strcasecmp(fNextToken, "XMAILBOXINFO"))
-        xmailboxinfo_data();
-      else if (!PL_strcasecmp(fNextToken, "XAOL-OPTION"))
-        skip_to_CRLF();
-      else if (!PL_strcasecmp(fNextToken, "XLIST"))
-        mailbox_data();
-      else
-      {
-        // check if custom command
-        nsAutoCString customCommand;
-        fServerConnection.GetCurrentUrl()->GetCommand(customCommand);
-        if (customCommand.Equals(fNextToken))
-        {
-          nsAutoCString customCommandResponse;
-          while (Connected() && !fAtEndOfLine)
-          {
-            AdvanceToNextToken();
-            customCommandResponse.Append(fNextToken);
-            customCommandResponse.Append(' ');
-          }
-          fServerConnection.GetCurrentUrl()->SetCustomCommandResult(customCommandResponse);
-        }
+        break;
+      case 'Q':
+        if (!PL_strcasecmp(fNextToken, "QUOTAROOT") ||
+            !PL_strcasecmp(fNextToken, "QUOTA"))
+          quota_data();
         else
           SetSyntaxError(true);
-      }
-      break;
-    case 'Q':
-      if (!PL_strcasecmp(fNextToken, "QUOTAROOT")  || !PL_strcasecmp(fNextToken, "QUOTA"))
-        quota_data();
-      else
-        SetSyntaxError(true);
-      break;
-    case 'I':
-      id_data();
-      break;
-    default:
-      if (IsNumericString(fNextToken))
-        numeric_mailbox_data();
-      else
-        SetSyntaxError(true);
-      break;
+        break;
+      case 'I':
+        id_data();
+        break;
+      default:
+        if (IsNumericString(fNextToken))
+          numeric_mailbox_data();
+        else
+          SetSyntaxError(true);
+        break;
     }
 
-    if (ContinueParse())
-      PostProcessEndOfLine();
+    if (ContinueParse()) PostProcessEndOfLine();
   }
 }
 
-
-void nsImapServerResponseParser::PostProcessEndOfLine()
-{
+void nsImapServerResponseParser::PostProcessEndOfLine() {
   // for now we only have to do one thing here
   // a fetch response to a 'uid store' command might return the flags
   // before it returns the uid of the message.  So we need both before
   // we report the new flag info to the front end
 
   // also check and be sure that there was a UID in the current response
-  if (fCurrentLineContainedFlagInfo && CurrentResponseUID())
-  {
+  if (fCurrentLineContainedFlagInfo && CurrentResponseUID()) {
     fCurrentLineContainedFlagInfo = false;
     nsCString customFlags;
-    fFlagState->GetCustomFlags(CurrentResponseUID(), getter_Copies(customFlags));
+    fFlagState->GetCustomFlags(CurrentResponseUID(),
+                               getter_Copies(customFlags));
     fServerConnection.NotifyMessageFlags(fSavedFlagInfo, customFlags,
                                          CurrentResponseUID(), fHighestModSeq);
   }
 }
 
-
 /*
  mailbox_data    ::=  "FLAGS" SPACE flag_list /
                                "LIST" SPACE mailbox_list /
                                "LSUB" SPACE mailbox_list /
                                "XLIST" SPACE mailbox_list /
                                "MAILBOX" SPACE text /
                                "SEARCH" [SPACE 1#nz_number] /
                                number SPACE "EXISTS" / number SPACE "RECENT"
@@ -769,84 +690,71 @@ This production was changed to accommoda
 
  mailbox_data    ::=  "FLAGS" SPACE flag_list /
                                "LIST" SPACE mailbox_list /
                                "LSUB" SPACE mailbox_list /
                                "XLIST" SPACE mailbox_list /
                                "MAILBOX" SPACE text /
                                "SEARCH" [SPACE 1#nz_number]
 */
-void nsImapServerResponseParser::mailbox_data()
-{
-  if (!PL_strcasecmp(fNextToken, "FLAGS"))
-  {
+void nsImapServerResponseParser::mailbox_data() {
+  if (!PL_strcasecmp(fNextToken, "FLAGS")) {
     // this handles the case where we got the permanent flags response
     // before the flags response, in which case, we want to ignore these flags.
     if (fGotPermanentFlags)
       skip_to_CRLF();
     else
       parse_folder_flags(true);
-  }
-  else if (!PL_strcasecmp(fNextToken, "LIST") ||
-           !PL_strcasecmp(fNextToken, "XLIST"))
-  {
+  } else if (!PL_strcasecmp(fNextToken, "LIST") ||
+             !PL_strcasecmp(fNextToken, "XLIST")) {
     AdvanceToNextToken();
-    if (ContinueParse())
-      mailbox_list(false);
-  }
-  else if (!PL_strcasecmp(fNextToken, "LSUB"))
-  {
+    if (ContinueParse()) mailbox_list(false);
+  } else if (!PL_strcasecmp(fNextToken, "LSUB")) {
     AdvanceToNextToken();
-    if (ContinueParse())
-      mailbox_list(true);
-  }
-  else if (!PL_strcasecmp(fNextToken, "MAILBOX"))
+    if (ContinueParse()) mailbox_list(true);
+  } else if (!PL_strcasecmp(fNextToken, "MAILBOX"))
     skip_to_CRLF();
-  else if (!PL_strcasecmp(fNextToken, "SEARCH"))
-  {
+  else if (!PL_strcasecmp(fNextToken, "SEARCH")) {
     fSearchResults->AddSearchResultLine(fCurrentLine);
     fServerConnection.NotifySearchHit(fCurrentLine);
     skip_to_CRLF();
   }
 }
 
 /*
  mailbox_list    ::= "(" #("\Marked" / "\Noinferiors" /
                               "\Noselect" / "\Unmarked" / flag_extension) ")"
                               SPACE (<"> QUOTED_CHAR <"> / nil) SPACE mailbox
 */
 
-void nsImapServerResponseParser::mailbox_list(bool discoveredFromLsub)
-{
+void nsImapServerResponseParser::mailbox_list(bool discoveredFromLsub) {
   RefPtr<nsImapMailboxSpec> boxSpec = new nsImapMailboxSpec;
   boxSpec->mFolderSelected = false;
   boxSpec->mBoxFlags = kNoFlags;
   boxSpec->mAllocatedPathName.Truncate();
   boxSpec->mHostName.Truncate();
   boxSpec->mConnection = &fServerConnection;
   boxSpec->mFlagState = nullptr;
   boxSpec->mDiscoveredFromLsub = discoveredFromLsub;
   boxSpec->mOnlineVerified = true;
   boxSpec->mBoxFlags &= ~kNameSpace;
 
   bool endOfFlags = false;
-  fNextToken++;// eat the first "("
+  fNextToken++;  // eat the first "("
   do {
     if (!PL_strncasecmp(fNextToken, "\\Marked", 7))
       boxSpec->mBoxFlags |= kMarked;
     else if (!PL_strncasecmp(fNextToken, "\\Unmarked", 9))
       boxSpec->mBoxFlags |= kUnmarked;
-    else if (!PL_strncasecmp(fNextToken, "\\Noinferiors", 12))
-    {
+    else if (!PL_strncasecmp(fNextToken, "\\Noinferiors", 12)) {
       boxSpec->mBoxFlags |= kNoinferiors;
       // RFC 5258 \Noinferiors implies \HasNoChildren
       if (fCapabilityFlag & kHasListExtendedCapability)
         boxSpec->mBoxFlags |= kHasNoChildren;
-    }
-    else if (!PL_strncasecmp(fNextToken, "\\Noselect", 9))
+    } else if (!PL_strncasecmp(fNextToken, "\\Noselect", 9))
       boxSpec->mBoxFlags |= kNoselect;
     else if (!PL_strncasecmp(fNextToken, "\\Drafts", 7))
       boxSpec->mBoxFlags |= kImapDrafts;
     else if (!PL_strncasecmp(fNextToken, "\\Trash", 6))
       boxSpec->mBoxFlags |= kImapXListTrash;
     else if (!PL_strncasecmp(fNextToken, "\\Sent", 5))
       boxSpec->mBoxFlags |= kImapSent;
     else if (!PL_strncasecmp(fNextToken, "\\Spam", 5) ||
@@ -854,180 +762,151 @@ void nsImapServerResponseParser::mailbox
       boxSpec->mBoxFlags |= kImapSpam;
     else if (!PL_strncasecmp(fNextToken, "\\Archive", 8))
       boxSpec->mBoxFlags |= kImapArchive;
     else if (!PL_strncasecmp(fNextToken, "\\All", 4) ||
              !PL_strncasecmp(fNextToken, "\\AllMail", 8))
       boxSpec->mBoxFlags |= kImapAllMail;
     else if (!PL_strncasecmp(fNextToken, "\\Inbox", 6))
       boxSpec->mBoxFlags |= kImapInbox;
-    else if (!PL_strncasecmp(fNextToken, "\\NonExistent", 11))
-    {
+    else if (!PL_strncasecmp(fNextToken, "\\NonExistent", 11)) {
       boxSpec->mBoxFlags |= kNonExistent;
       // RFC 5258 \NonExistent implies \Noselect
       boxSpec->mBoxFlags |= kNoselect;
-    }
-    else if (!PL_strncasecmp(fNextToken, "\\Subscribed", 10))
+    } else if (!PL_strncasecmp(fNextToken, "\\Subscribed", 10))
       boxSpec->mBoxFlags |= kSubscribed;
     else if (!PL_strncasecmp(fNextToken, "\\Remote", 6))
       boxSpec->mBoxFlags |= kRemote;
     else if (!PL_strncasecmp(fNextToken, "\\HasChildren", 11))
       boxSpec->mBoxFlags |= kHasChildren;
     else if (!PL_strncasecmp(fNextToken, "\\HasNoChildren", 13))
       boxSpec->mBoxFlags |= kHasNoChildren;
     // we ignore flag other extensions
 
     endOfFlags = *(fNextToken + strlen(fNextToken) - 1) == ')';
     AdvanceToNextToken();
   } while (!endOfFlags && ContinueParse());
 
-  if (ContinueParse())
-  {
-    if (*fNextToken == '"')
-    {
+  if (ContinueParse()) {
+    if (*fNextToken == '"') {
       fNextToken++;
-      if (*fNextToken == '\\') // handle escaped char
+      if (*fNextToken == '\\')  // handle escaped char
         boxSpec->mHierarchySeparator = *(fNextToken + 1);
       else
         boxSpec->mHierarchySeparator = *fNextToken;
-    }
-    else  // likely NIL.  Discovered late in 4.02 that we do not handle literals here (e.g. {10} <10 chars>), although this is almost impossibly unlikely
+    } else  // likely NIL.  Discovered late in 4.02 that we do not handle
+            // literals here (e.g. {10} <10 chars>), although this is almost
+            // impossibly unlikely
       boxSpec->mHierarchySeparator = kOnlineHierarchySeparatorNil;
     AdvanceToNextToken();
-    if (ContinueParse())
-      mailbox(boxSpec);
+    if (ContinueParse()) mailbox(boxSpec);
   }
 }
 
 /* mailbox         ::= "INBOX" / astring
-*/
-void nsImapServerResponseParser::mailbox(nsImapMailboxSpec *boxSpec)
-{
+ */
+void nsImapServerResponseParser::mailbox(nsImapMailboxSpec *boxSpec) {
   char *boxname = nullptr;
   const char *serverKey = fServerConnection.GetImapServerKey();
   bool xlistInbox = boxSpec->mBoxFlags & kImapInbox;
 
-  if (!PL_strcasecmp(fNextToken, "INBOX") || xlistInbox)
-  {
+  if (!PL_strcasecmp(fNextToken, "INBOX") || xlistInbox) {
     boxname = PL_strdup("INBOX");
-    if (xlistInbox)
-      PR_Free(CreateAstring());
+    if (xlistInbox) PR_Free(CreateAstring());
     AdvanceToNextToken();
-  }
-  else
-  {
+  } else {
     boxname = CreateAstring();
     AdvanceToNextToken();
   }
 
-  if (boxname && fHostSessionList)
-  {
+  if (boxname && fHostSessionList) {
     // should the namespace check go before or after the Utf7 conversion?
     fHostSessionList->SetNamespaceHierarchyDelimiterFromMailboxForHost(
-      serverKey, boxname, boxSpec->mHierarchySeparator);
-
+        serverKey, boxname, boxSpec->mHierarchySeparator);
 
     nsIMAPNamespace *ns = nullptr;
     fHostSessionList->GetNamespaceForMailboxForHost(serverKey, boxname, ns);
-    if (ns)
-    {
-      switch (ns->GetType())
-      {
-      case kPersonalNamespace:
-        boxSpec->mBoxFlags |= kPersonalMailbox;
-        break;
-      case kPublicNamespace:
-        boxSpec->mBoxFlags |= kPublicMailbox;
-        break;
-      case kOtherUsersNamespace:
-        boxSpec->mBoxFlags |= kOtherUsersMailbox;
-        break;
-      default:  // (kUnknownNamespace)
-        break;
+    if (ns) {
+      switch (ns->GetType()) {
+        case kPersonalNamespace:
+          boxSpec->mBoxFlags |= kPersonalMailbox;
+          break;
+        case kPublicNamespace:
+          boxSpec->mBoxFlags |= kPublicMailbox;
+          break;
+        case kOtherUsersNamespace:
+          boxSpec->mBoxFlags |= kOtherUsersMailbox;
+          break;
+        default:  // (kUnknownNamespace)
+          break;
       }
       boxSpec->mNamespaceForFolder = ns;
     }
 
-    // char *convertedName = fServerConnection.CreateUtf7ConvertedString(boxname, false);
-    // char16_t *unicharName = fServerConnection.CreatePRUnicharStringFromUTF7(boxname);
+    // char *convertedName =
+    // fServerConnection.CreateUtf7ConvertedString(boxname, false); char16_t
+    // *unicharName = fServerConnection.CreatePRUnicharStringFromUTF7(boxname);
     // PL_strfree(boxname);
     // boxname = convertedName;
   }
 
-  if (!boxname)
-  {
-    if (!fServerConnection.DeathSignalReceived())
-      HandleMemoryFailure();
-  }
-  else if (boxSpec->mConnection && boxSpec->mConnection->GetCurrentUrl())
-  {
-    boxSpec->mConnection->GetCurrentUrl()->AllocateCanonicalPath(boxname, boxSpec->mHierarchySeparator,
-                                                                 getter_Copies(boxSpec->mAllocatedPathName));
+  if (!boxname) {
+    if (!fServerConnection.DeathSignalReceived()) HandleMemoryFailure();
+  } else if (boxSpec->mConnection && boxSpec->mConnection->GetCurrentUrl()) {
+    boxSpec->mConnection->GetCurrentUrl()->AllocateCanonicalPath(
+        boxname, boxSpec->mHierarchySeparator,
+        getter_Copies(boxSpec->mAllocatedPathName));
     nsIURI *aURL = nullptr;
-    boxSpec->mConnection->GetCurrentUrl()->QueryInterface(NS_GET_IID(nsIURI), (void **) &aURL);
-    if (aURL)
-      aURL->GetHost(boxSpec->mHostName);
+    boxSpec->mConnection->GetCurrentUrl()->QueryInterface(NS_GET_IID(nsIURI),
+                                                          (void **)&aURL);
+    if (aURL) aURL->GetHost(boxSpec->mHostName);
 
     NS_IF_RELEASE(aURL);
     // storage for the boxSpec is now owned by server connection
     fServerConnection.DiscoverMailboxSpec(boxSpec);
 
     // if this was cancelled by the user,then we sure don't want to
     // send more mailboxes their way
-    if (NS_FAILED(fServerConnection.GetConnectionStatus()))
-      SetConnected(false);
+    if (NS_FAILED(fServerConnection.GetConnectionStatus())) SetConnected(false);
   }
 
-  if (boxname)
-    PL_strfree(boxname);
+  if (boxname) PL_strfree(boxname);
 }
 
-
 /*
  message_data    ::= nz_number SPACE ("EXPUNGE" /
                               ("FETCH" SPACE msg_fetch) / msg_obsolete)
 
 was changed to
 
 numeric_mailbox_data ::=  number SPACE "EXISTS" / number SPACE "RECENT"
  / nz_number SPACE ("EXPUNGE" /
                               ("FETCH" SPACE msg_fetch) / msg_obsolete)
 
 */
-void nsImapServerResponseParser::numeric_mailbox_data()
-{
+void nsImapServerResponseParser::numeric_mailbox_data() {
   int32_t tokenNumber = atoi(fNextToken);
   AdvanceToNextToken();
 
-  if (ContinueParse())
-  {
-    if (!PL_strcasecmp(fNextToken, "FETCH"))
-    {
+  if (ContinueParse()) {
+    if (!PL_strcasecmp(fNextToken, "FETCH")) {
       fFetchResponseIndex = tokenNumber;
       AdvanceToNextToken();
-      if (ContinueParse())
-        msg_fetch();
-    }
-    else if (!PL_strcasecmp(fNextToken, "EXISTS"))
-    {
+      if (ContinueParse()) msg_fetch();
+    } else if (!PL_strcasecmp(fNextToken, "EXISTS")) {
       fNumberOfExistingMessages = tokenNumber;
       AdvanceToNextToken();
-    }
-    else if (!PL_strcasecmp(fNextToken, "RECENT"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "RECENT")) {
       fNumberOfRecentMessages = tokenNumber;
       AdvanceToNextToken();
-    }
-    else if (!PL_strcasecmp(fNextToken, "EXPUNGE"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "EXPUNGE")) {
       if (!fServerConnection.GetIgnoreExpunges())
-        fFlagState->ExpungeByIndex((uint32_t) tokenNumber);
+        fFlagState->ExpungeByIndex((uint32_t)tokenNumber);
       skip_to_CRLF();
-    }
-    else
+    } else
       msg_obsolete();
   }
 }
 
 /*
 msg_fetch       ::= "(" 1#("BODY" SPACE body /
 "BODYSTRUCTURE" SPACE body /
 "BODY[" section "]" SPACE nstring /
@@ -1036,428 +915,361 @@ msg_fetch       ::= "(" 1#("BODY" SPACE 
 "INTERNALDATE" SPACE date_time /
 "MODSEQ" SPACE "(" nz_number ")" /
 "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
 "RFC822.SIZE" SPACE number /
 "UID" SPACE uniqueid) ")"
 
 */
 
-void nsImapServerResponseParser::msg_fetch()
-{
+void nsImapServerResponseParser::msg_fetch() {
   bool bNeedEndMessageDownload = false;
 
   // we have not seen a uid response or flags for this fetch, yet
   fCurrentResponseUID = 0;
   fCurrentLineContainedFlagInfo = false;
   fSizeOfMostRecentMessage = 0;
   // show any incremental progress, for instance, for header downloading
   fServerConnection.ShowProgress();
 
-  fNextToken++; // eat the '(' character
+  fNextToken++;  // eat the '(' character
 
   // some of these productions are ignored for now
-  while (ContinueParse() && (*fNextToken != ')') )
-  {
-    if (!PL_strcasecmp(fNextToken, "FLAGS"))
-    {
+  while (ContinueParse() && (*fNextToken != ')')) {
+    if (!PL_strcasecmp(fNextToken, "FLAGS")) {
       if (fCurrentResponseUID == 0)
-        fFlagState->GetUidOfMessage(fFetchResponseIndex - 1, &fCurrentResponseUID);
+        fFlagState->GetUidOfMessage(fFetchResponseIndex - 1,
+                                    &fCurrentResponseUID);
 
       AdvanceToNextToken();
-      if (ContinueParse())
-        flags();
+      if (ContinueParse()) flags();
 
-      if (ContinueParse())
-      { // eat the closing ')'
+      if (ContinueParse()) {  // eat the closing ')'
         fNextToken++;
         // there may be another ')' to close out
         // msg_fetch.  If there is then don't advance
-        if (*fNextToken != ')')
-          AdvanceToNextToken();
+        if (*fNextToken != ')') AdvanceToNextToken();
       }
-    }
-    else if (!PL_strcasecmp(fNextToken, "UID"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "UID")) {
       AdvanceToNextToken();
-      if (ContinueParse())
-      {
+      if (ContinueParse()) {
         fCurrentResponseUID = strtoul(fNextToken, nullptr, 10);
         if (fCurrentResponseUID > fHighestRecordedUID)
           fHighestRecordedUID = fCurrentResponseUID;
         // size came before UID
         if (fSizeOfMostRecentMessage)
           fReceivedHeaderOrSizeForUID = CurrentResponseUID();
         // if this token ends in ')', then it is the last token
         // else we advance
         char lastTokenChar = *(fNextToken + strlen(fNextToken) - 1);
         if (lastTokenChar == ')')
           fNextToken += strlen(fNextToken) - 1;
-        else if (lastTokenChar < '0' || lastTokenChar > '9')
-        {
+        else if (lastTokenChar < '0' || lastTokenChar > '9') {
           // GIANT HACK
           // this is a corrupt uid - see if it's pre 5.08 Zimbra omitting
           // a space between the UID and MODSEQ
           if (strlen(fNextToken) > 6 &&
               !strcmp("MODSEQ", fNextToken + strlen(fNextToken) - 6))
             fNextToken += strlen(fNextToken) - 6;
-        }
-        else
+        } else
           AdvanceToNextToken();
       }
-    }
-    else if (!PL_strcasecmp(fNextToken, "MODSEQ"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "MODSEQ")) {
       AdvanceToNextToken();
-      if (ContinueParse())
-      {
-        fNextToken++; // eat '('
-        uint64_t modSeq =  ParseUint64Str(fNextToken);
-        if (modSeq > fHighestModSeq)
-          fHighestModSeq = modSeq;
+      if (ContinueParse()) {
+        fNextToken++;  // eat '('
+        uint64_t modSeq = ParseUint64Str(fNextToken);
+        if (modSeq > fHighestModSeq) fHighestModSeq = modSeq;
 
-        if (PL_strcasestr(fNextToken, ")"))
-        {
+        if (PL_strcasestr(fNextToken, ")")) {
           // eat token chars until we get the ')'
           fNextToken = strchr(fNextToken, ')');
-          if (fNextToken)
-          {
+          if (fNextToken) {
             fNextToken++;
-            if (*fNextToken != ')')
-              AdvanceToNextToken();
-          }
-          else
+            if (*fNextToken != ')') AdvanceToNextToken();
+          } else
             SetSyntaxError(true);
-        }
-        else
-        {
+        } else {
           SetSyntaxError(true);
         }
       }
-    }
-    else if (!PL_strcasecmp(fNextToken, "RFC822") ||
-             !PL_strcasecmp(fNextToken, "RFC822.HEADER") ||
-             !PL_strncasecmp(fNextToken, "BODY[HEADER",11) ||
-             !PL_strncasecmp(fNextToken, "BODY[]", 6) ||
-             !PL_strcasecmp(fNextToken, "RFC822.TEXT") ||
-             (!PL_strncasecmp(fNextToken, "BODY[", 5) &&
-              PL_strstr(fNextToken, "HEADER")))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "RFC822") ||
+               !PL_strcasecmp(fNextToken, "RFC822.HEADER") ||
+               !PL_strncasecmp(fNextToken, "BODY[HEADER", 11) ||
+               !PL_strncasecmp(fNextToken, "BODY[]", 6) ||
+               !PL_strcasecmp(fNextToken, "RFC822.TEXT") ||
+               (!PL_strncasecmp(fNextToken, "BODY[", 5) &&
+                PL_strstr(fNextToken, "HEADER"))) {
       if (fCurrentResponseUID == 0)
-        fFlagState->GetUidOfMessage(fFetchResponseIndex - 1, &fCurrentResponseUID);
+        fFlagState->GetUidOfMessage(fFetchResponseIndex - 1,
+                                    &fCurrentResponseUID);
 
       if (!PL_strcasecmp(fNextToken, "RFC822.HEADER") ||
-        !PL_strcasecmp(fNextToken, "BODY[HEADER]"))
-      {
+          !PL_strcasecmp(fNextToken, "BODY[HEADER]")) {
         // all of this message's headers
         AdvanceToNextToken();
         fDownloadingHeaders = true;
-        BeginMessageDownload(MESSAGE_RFC822); // initialize header parser
+        BeginMessageDownload(MESSAGE_RFC822);  // initialize header parser
         bNeedEndMessageDownload = false;
-        if (ContinueParse())
-          msg_fetch_headers(nullptr);
-      }
-      else if (!PL_strncasecmp(fNextToken, "BODY[HEADER.FIELDS",19))
-      {
+        if (ContinueParse()) msg_fetch_headers(nullptr);
+      } else if (!PL_strncasecmp(fNextToken, "BODY[HEADER.FIELDS", 19)) {
         fDownloadingHeaders = true;
-        BeginMessageDownload(MESSAGE_RFC822); // initialize header parser
+        BeginMessageDownload(MESSAGE_RFC822);  // initialize header parser
         // specific message header fields
-        while (ContinueParse() && fNextToken[strlen(fNextToken)-1] != ']')
+        while (ContinueParse() && fNextToken[strlen(fNextToken) - 1] != ']')
           AdvanceToNextToken();
-        if (ContinueParse())
-        {
+        if (ContinueParse()) {
           bNeedEndMessageDownload = false;
           AdvanceToNextToken();
-          if (ContinueParse())
-            msg_fetch_headers(nullptr);
+          if (ContinueParse()) msg_fetch_headers(nullptr);
         }
-      }
-      else
-      {
+      } else {
         char *whereHeader = PL_strstr(fNextToken, "HEADER");
-        if (whereHeader)
-        {
+        if (whereHeader) {
           const char *startPartNum = fNextToken + 5;
-          if (whereHeader > startPartNum)
-          {
-            int32_t partLength = whereHeader - startPartNum - 1; //-1 for the dot!
-            char *partNum = (char *)PR_CALLOC((partLength + 1) * sizeof (char));
-            if (partNum)
-            {
+          if (whereHeader > startPartNum) {
+            int32_t partLength =
+                whereHeader - startPartNum - 1;  //-1 for the dot!
+            char *partNum = (char *)PR_CALLOC((partLength + 1) * sizeof(char));
+            if (partNum) {
               PL_strncpy(partNum, startPartNum, partLength);
-              if (ContinueParse())
-              {
-                if (PL_strstr(fNextToken, "FIELDS"))
-                {
-                  while (ContinueParse() && fNextToken[strlen(fNextToken)-1] != ']')
+              if (ContinueParse()) {
+                if (PL_strstr(fNextToken, "FIELDS")) {
+                  while (ContinueParse() &&
+                         fNextToken[strlen(fNextToken) - 1] != ']')
                     AdvanceToNextToken();
                 }
-                if (ContinueParse())
-                {
+                if (ContinueParse()) {
                   AdvanceToNextToken();
-                  if (ContinueParse())
-                    msg_fetch_headers(partNum);
+                  if (ContinueParse()) msg_fetch_headers(partNum);
                 }
               }
               PR_Free(partNum);
             }
-          }
-          else
+          } else
             SetSyntaxError(true);
-        }
-        else
-        {
+        } else {
           fDownloadingHeaders = false;
 
           bool chunk = false;
           int32_t origin = 0;
-          if (!PL_strncasecmp(fNextToken, "BODY[]<", 7))
-          {
+          if (!PL_strncasecmp(fNextToken, "BODY[]<", 7)) {
             char *tokenCopy = 0;
             tokenCopy = PL_strdup(fNextToken);
-            if (tokenCopy)
-            {
-              char *originString = tokenCopy + 7;  // where the byte number starts
-              char *closeBracket = PL_strchr(tokenCopy,'>');
-              if (closeBracket && originString && *originString)
-              {
+            if (tokenCopy) {
+              char *originString =
+                  tokenCopy + 7;  // where the byte number starts
+              char *closeBracket = PL_strchr(tokenCopy, '>');
+              if (closeBracket && originString && *originString) {
                 *closeBracket = 0;
                 origin = atoi(originString);
                 chunk = true;
               }
               PR_Free(tokenCopy);
             }
           }
 
           AdvanceToNextToken();
-          if (ContinueParse())
-          {
+          if (ContinueParse()) {
             msg_fetch_content(chunk, origin, MESSAGE_RFC822);
           }
         }
       }
-      }
-      else if (!PL_strcasecmp(fNextToken, "RFC822.SIZE") || !PL_strcasecmp(fNextToken, "XAOL.SIZE"))
-      {
-        AdvanceToNextToken();
-        if (ContinueParse())
-        {
-          bool sendEndMsgDownload = (GetDownloadingHeaders()
-                                        && fReceivedHeaderOrSizeForUID == CurrentResponseUID());
-          fSizeOfMostRecentMessage = strtoul(fNextToken, nullptr, 10);
-          fReceivedHeaderOrSizeForUID = CurrentResponseUID();
-          if (sendEndMsgDownload)
-          {
-            fServerConnection.NormalMessageEndDownload();
-            fReceivedHeaderOrSizeForUID = nsMsgKey_None;
-          }
+    } else if (!PL_strcasecmp(fNextToken, "RFC822.SIZE") ||
+               !PL_strcasecmp(fNextToken, "XAOL.SIZE")) {
+      AdvanceToNextToken();
+      if (ContinueParse()) {
+        bool sendEndMsgDownload =
+            (GetDownloadingHeaders() &&
+             fReceivedHeaderOrSizeForUID == CurrentResponseUID());
+        fSizeOfMostRecentMessage = strtoul(fNextToken, nullptr, 10);
+        fReceivedHeaderOrSizeForUID = CurrentResponseUID();
+        if (sendEndMsgDownload) {
+          fServerConnection.NormalMessageEndDownload();
+          fReceivedHeaderOrSizeForUID = nsMsgKey_None;
+        }
 
-          if (fSizeOfMostRecentMessage == 0 && CurrentResponseUID())
-          {
-            // on no, bogus Netscape 2.0 mail server bug
-            char uidString[100];
-            sprintf(uidString, "%ld", (long)CurrentResponseUID());
+        if (fSizeOfMostRecentMessage == 0 && CurrentResponseUID()) {
+          // on no, bogus Netscape 2.0 mail server bug
+          char uidString[100];
+          sprintf(uidString, "%ld", (long)CurrentResponseUID());
+
+          if (!fZeroLengthMessageUidString.IsEmpty())
+            fZeroLengthMessageUidString += ",";
+
+          fZeroLengthMessageUidString += uidString;
+        }
 
-            if (!fZeroLengthMessageUidString.IsEmpty())
-              fZeroLengthMessageUidString += ",";
-
-            fZeroLengthMessageUidString += uidString;
-          }
+        // if this token ends in ')', then it is the last token
+        // else we advance
+        if (*(fNextToken + strlen(fNextToken) - 1) == ')')
+          fNextToken += strlen(fNextToken) - 1;
+        else
+          AdvanceToNextToken();
+      }
+    } else if (!PL_strcasecmp(fNextToken, "XSENDER")) {
+      PR_FREEIF(fXSenderInfo);
+      AdvanceToNextToken();
+      if (!fNextToken)
+        SetSyntaxError(true);
+      else {
+        fXSenderInfo = CreateAstring();
+        AdvanceToNextToken();
+      }
+    } else if (!PL_strcasecmp(fNextToken, "X-GM-MSGID")) {
+      AdvanceToNextToken();
+      if (!fNextToken)
+        SetSyntaxError(true);
+      else {
+        fMsgID = CreateAtom();
+        AdvanceToNextToken();
+        nsCString msgIDValue;
+        msgIDValue.Assign(fMsgID);
+        if (fCurrentResponseUID == 0)
+          fFlagState->GetUidOfMessage(fFetchResponseIndex - 1,
+                                      &fCurrentResponseUID);
+        fFlagState->SetCustomAttribute(
+            fCurrentResponseUID, NS_LITERAL_CSTRING("X-GM-MSGID"), msgIDValue);
+        PR_FREEIF(fMsgID);
+      }
+    } else if (!PL_strcasecmp(fNextToken, "X-GM-THRID")) {
+      AdvanceToNextToken();
+      if (!fNextToken)
+        SetSyntaxError(true);
+      else {
+        fThreadID = CreateAtom();
+        AdvanceToNextToken();
+        nsCString threadIDValue;
+        threadIDValue.Assign(fThreadID);
+        if (fCurrentResponseUID == 0)
+          fFlagState->GetUidOfMessage(fFetchResponseIndex - 1,
+                                      &fCurrentResponseUID);
+        fFlagState->SetCustomAttribute(fCurrentResponseUID,
+                                       NS_LITERAL_CSTRING("X-GM-THRID"),
+                                       threadIDValue);
+        PR_FREEIF(fThreadID);
+      }
+    } else if (!PL_strcasecmp(fNextToken, "X-GM-LABELS")) {
+      AdvanceToNextToken();
+      if (!fNextToken)
+        SetSyntaxError(true);
+      else {
+        fLabels = CreateParenGroup();
+        nsCString labelsValue;
+        labelsValue.Assign(fLabels);
+        labelsValue.Cut(0, 1);
+        labelsValue.Cut(labelsValue.Length() - 1, 1);
+        if (fCurrentResponseUID == 0)
+          fFlagState->GetUidOfMessage(fFetchResponseIndex - 1,
+                                      &fCurrentResponseUID);
+        fFlagState->SetCustomAttribute(fCurrentResponseUID,
+                                       NS_LITERAL_CSTRING("X-GM-LABELS"),
+                                       labelsValue);
+        PR_FREEIF(fLabels);
+      }
+    }
 
-          // if this token ends in ')', then it is the last token
-          // else we advance
-          if ( *(fNextToken + strlen(fNextToken) - 1) == ')')
-            fNextToken += strlen(fNextToken) - 1;
-          else
-            AdvanceToNextToken();
-        }
-      }
-      else if (!PL_strcasecmp(fNextToken, "XSENDER"))
-      {
-        PR_FREEIF(fXSenderInfo);
+    // I only fetch RFC822 so I should never see these BODY responses
+    else if (!PL_strcasecmp(fNextToken, "BODY"))
+      skip_to_CRLF();  // I never ask for this
+    else if (!PL_strcasecmp(fNextToken, "BODYSTRUCTURE")) {
+      if (fCurrentResponseUID == 0)
+        fFlagState->GetUidOfMessage(fFetchResponseIndex - 1,
+                                    &fCurrentResponseUID);
+      bodystructure_data();
+    } else if (!PL_strncasecmp(fNextToken, "BODY[TEXT", 9)) {
+      mime_data();
+    } else if (!PL_strncasecmp(fNextToken, "BODY[", 5) &&
+               PL_strncasecmp(fNextToken, "BODY[]", 6)) {
+      fDownloadingHeaders = false;
+      // A specific MIME part, or MIME part header
+      mime_data();
+    } else if (!PL_strcasecmp(fNextToken, "ENVELOPE")) {
+      fDownloadingHeaders = true;
+      bNeedEndMessageDownload = true;
+      BeginMessageDownload(MESSAGE_RFC822);
+      envelope_data();
+    } else if (!PL_strcasecmp(fNextToken, "INTERNALDATE")) {
+      fDownloadingHeaders =
+          true;  // we only request internal date while downloading headers
+      if (!bNeedEndMessageDownload) BeginMessageDownload(MESSAGE_RFC822);
+      bNeedEndMessageDownload = true;
+      internal_date();
+    } else if (!PL_strcasecmp(fNextToken, "XAOL-ENVELOPE")) {
+      fDownloadingHeaders = true;
+      if (!bNeedEndMessageDownload) BeginMessageDownload(MESSAGE_RFC822);
+      bNeedEndMessageDownload = true;
+      xaolenvelope_data();
+    } else {
+      nsImapAction imapAction;
+      if (!fServerConnection.GetCurrentUrl()) return;
+      fServerConnection.GetCurrentUrl()->GetImapAction(&imapAction);
+      nsAutoCString userDefinedFetchAttribute;
+      fServerConnection.GetCurrentUrl()->GetCustomAttributeToFetch(
+          userDefinedFetchAttribute);
+      if ((imapAction == nsIImapUrl::nsImapUserDefinedFetchAttribute &&
+           !strcmp(userDefinedFetchAttribute.get(), fNextToken)) ||
+          imapAction == nsIImapUrl::nsImapUserDefinedMsgCommand) {
         AdvanceToNextToken();
-        if (! fNextToken)
-          SetSyntaxError(true);
-        else
-        {
-          fXSenderInfo = CreateAstring();
+        char *fetchResult;
+        if (fNextToken[0] == '(')
+          // look through the tokens until we find the closing ')'
+          // we can have a result like the following:
+          // ((A B) (C D) (E F))
+          fetchResult = CreateParenGroup();
+        else {
+          fetchResult = CreateAstring();
           AdvanceToNextToken();
         }
-      }
-      else if (!PL_strcasecmp(fNextToken, "X-GM-MSGID"))
-      {
-        AdvanceToNextToken();
-        if (!fNextToken)
-          SetSyntaxError(true);
-        else
-        {
-          fMsgID = CreateAtom();
-          AdvanceToNextToken();
-          nsCString msgIDValue;
-          msgIDValue.Assign(fMsgID);
-          if (fCurrentResponseUID == 0)
-            fFlagState->GetUidOfMessage(fFetchResponseIndex - 1, &fCurrentResponseUID);
-          fFlagState->SetCustomAttribute(fCurrentResponseUID,
-                                         NS_LITERAL_CSTRING("X-GM-MSGID"), msgIDValue);
-          PR_FREEIF(fMsgID);
-        }
-      }
-      else if (!PL_strcasecmp(fNextToken, "X-GM-THRID"))
-      {
-        AdvanceToNextToken();
-        if (!fNextToken)
-          SetSyntaxError(true);
-        else
-        {
-          fThreadID = CreateAtom();
-          AdvanceToNextToken();
-          nsCString threadIDValue;
-          threadIDValue.Assign(fThreadID);
-          if (fCurrentResponseUID == 0)
-            fFlagState->GetUidOfMessage(fFetchResponseIndex - 1, &fCurrentResponseUID);
-          fFlagState->SetCustomAttribute(fCurrentResponseUID,
-                                         NS_LITERAL_CSTRING("X-GM-THRID"), threadIDValue);
-          PR_FREEIF(fThreadID);
-        }
-      }
-      else if (!PL_strcasecmp(fNextToken, "X-GM-LABELS"))
-      {
-        AdvanceToNextToken();
-        if (!fNextToken)
-          SetSyntaxError(true);
-        else
-        {
-          fLabels = CreateParenGroup();
-          nsCString labelsValue;
-          labelsValue.Assign(fLabels);
-          labelsValue.Cut(0, 1);
-          labelsValue.Cut(labelsValue.Length()-1, 1);
-          if (fCurrentResponseUID == 0)
-            fFlagState->GetUidOfMessage(fFetchResponseIndex - 1, &fCurrentResponseUID);
-          fFlagState->SetCustomAttribute(fCurrentResponseUID,
-                                         NS_LITERAL_CSTRING("X-GM-LABELS"), labelsValue);
-          PR_FREEIF(fLabels);
-        }
-      }
+        if (imapAction == nsIImapUrl::nsImapUserDefinedFetchAttribute)
+          fServerConnection.GetCurrentUrl()->SetCustomAttributeResult(
+              nsDependentCString(fetchResult));
+        if (imapAction == nsIImapUrl::nsImapUserDefinedMsgCommand)
+          fServerConnection.GetCurrentUrl()->SetCustomCommandResult(
+              nsDependentCString(fetchResult));
+        PR_Free(fetchResult);
+      } else
+        SetSyntaxError(true);
+    }
+  }
 
-      // I only fetch RFC822 so I should never see these BODY responses
-      else if (!PL_strcasecmp(fNextToken, "BODY"))
-        skip_to_CRLF(); // I never ask for this
-      else if (!PL_strcasecmp(fNextToken, "BODYSTRUCTURE"))
-      {
-        if (fCurrentResponseUID == 0)
-          fFlagState->GetUidOfMessage(fFetchResponseIndex - 1, &fCurrentResponseUID);
-        bodystructure_data();
-      }
-      else if (!PL_strncasecmp(fNextToken, "BODY[TEXT", 9))
-      {
-        mime_data();
-      }
-      else if (!PL_strncasecmp(fNextToken, "BODY[", 5) && PL_strncasecmp(fNextToken, "BODY[]", 6))
-      {
-        fDownloadingHeaders = false;
-        // A specific MIME part, or MIME part header
-        mime_data();
-      }
-      else if (!PL_strcasecmp(fNextToken, "ENVELOPE"))
-      {
-        fDownloadingHeaders = true;
-        bNeedEndMessageDownload = true;
-        BeginMessageDownload(MESSAGE_RFC822);
-        envelope_data();
-      }
-      else if (!PL_strcasecmp(fNextToken, "INTERNALDATE"))
-      {
-        fDownloadingHeaders = true; // we only request internal date while downloading headers
-        if (!bNeedEndMessageDownload)
-          BeginMessageDownload(MESSAGE_RFC822);
-        bNeedEndMessageDownload = true;
-        internal_date();
-      }
-      else if (!PL_strcasecmp(fNextToken, "XAOL-ENVELOPE"))
-      {
-        fDownloadingHeaders = true;
-        if (!bNeedEndMessageDownload)
-          BeginMessageDownload(MESSAGE_RFC822);
-        bNeedEndMessageDownload = true;
-        xaolenvelope_data();
-      }
-      else
-      {
-        nsImapAction imapAction;
-        if (!fServerConnection.GetCurrentUrl())
-          return;
-        fServerConnection.GetCurrentUrl()->GetImapAction(&imapAction);
-        nsAutoCString userDefinedFetchAttribute;
-        fServerConnection.GetCurrentUrl()->GetCustomAttributeToFetch(userDefinedFetchAttribute);
-        if ((imapAction == nsIImapUrl::nsImapUserDefinedFetchAttribute && !strcmp(userDefinedFetchAttribute.get(), fNextToken)) ||
-            imapAction == nsIImapUrl::nsImapUserDefinedMsgCommand)
-        {
-          AdvanceToNextToken();
-          char *fetchResult;
-          if (fNextToken[0] == '(')
-            // look through the tokens until we find the closing ')'
-            // we can have a result like the following:
-            // ((A B) (C D) (E F))
-            fetchResult = CreateParenGroup();
-          else {
-            fetchResult = CreateAstring();
-            AdvanceToNextToken();
-          }
-          if (imapAction == nsIImapUrl::nsImapUserDefinedFetchAttribute)
-            fServerConnection.GetCurrentUrl()->SetCustomAttributeResult(nsDependentCString(fetchResult));
-          if (imapAction == nsIImapUrl::nsImapUserDefinedMsgCommand)
-            fServerConnection.GetCurrentUrl()->SetCustomCommandResult(nsDependentCString(fetchResult));
-          PR_Free(fetchResult);
-        }
-        else
-          SetSyntaxError(true);
-      }
+  if (ContinueParse()) {
+    if (CurrentResponseUID() && CurrentResponseUID() != nsMsgKey_None &&
+        fCurrentLineContainedFlagInfo && fFlagState) {
+      fFlagState->AddUidFlagPair(CurrentResponseUID(), fSavedFlagInfo,
+                                 fFetchResponseIndex - 1);
+      for (uint32_t i = 0; i < fCustomFlags.Length(); i++)
+        fFlagState->AddUidCustomFlagPair(CurrentResponseUID(),
+                                         fCustomFlags[i].get());
+      fCustomFlags.Clear();
+    }
 
-        }
-
-        if (ContinueParse())
-        {
-          if (CurrentResponseUID() && CurrentResponseUID() != nsMsgKey_None
-            && fCurrentLineContainedFlagInfo && fFlagState)
-          {
-            fFlagState->AddUidFlagPair(CurrentResponseUID(), fSavedFlagInfo, fFetchResponseIndex - 1);
-            for (uint32_t i = 0; i < fCustomFlags.Length(); i++)
-              fFlagState->AddUidCustomFlagPair(CurrentResponseUID(), fCustomFlags[i].get());
-            fCustomFlags.Clear();
-          }
+    if (fFetchingAllFlags)
+      fCurrentLineContainedFlagInfo =
+          false;  // do not fire if in PostProcessEndOfLine
 
-          if (fFetchingAllFlags)
-            fCurrentLineContainedFlagInfo = false;  // do not fire if in PostProcessEndOfLine
-
-          AdvanceToNextToken(); // eat the ')' ending token
-          // should be at end of line
-          if (bNeedEndMessageDownload)
-          {
-            if (ContinueParse())
-            {
-              // complete the message download
-              fServerConnection.NormalMessageEndDownload();
-            }
-            else
-              fServerConnection.AbortMessageDownLoad();
-          }
-
-        }
+    AdvanceToNextToken();  // eat the ')' ending token
+    // should be at end of line
+    if (bNeedEndMessageDownload) {
+      if (ContinueParse()) {
+        // complete the message download
+        fServerConnection.NormalMessageEndDownload();
+      } else
+        fServerConnection.AbortMessageDownLoad();
+    }
+  }
 }
 
-typedef enum _envelopeItemType
-{
+typedef enum _envelopeItemType {
   envelopeString,
   envelopeAddress
 } envelopeItemType;
 
-typedef struct
-{
-  const char * name;
+typedef struct {
+  const char *name;
   envelopeItemType type;
 } envelopeItem;
 
 // RFC3501:  envelope  = "(" env-date SP env-subject SP env-from SP
 //                       env-sender SP env-reply-to SP env-to SP env-cc SP
 //                       env-bcc SP env-in-reply-to SP env-message-id ")"
 //           env-date    = nstring
 //           env-subject = nstring
@@ -1465,430 +1277,354 @@ typedef struct
 //           env-sender  = "(" 1*address ")" / nil
 //           env-reply-to= "(" 1*address ")" / nil
 //           env-to      = "(" 1*address ")" / nil
 //           env-cc      = "(" 1*address ")" / nil
 //           env-bcc     = "(" 1*address ")" / nil
 //           env-in-reply-to = nstring
 //           env-message-id  = nstring
 
-static const envelopeItem EnvelopeTable[] =
-{
-  {"Date", envelopeString},
-  {"Subject", envelopeString},
-  {"From", envelopeAddress},
-  {"Sender", envelopeAddress},
-  {"Reply-to", envelopeAddress},
-  {"To", envelopeAddress},
-  {"Cc", envelopeAddress},
-  {"Bcc", envelopeAddress},
-  {"In-reply-to", envelopeString},
-  {"Message-id", envelopeString}
-};
+static const envelopeItem EnvelopeTable[] = {
+    {"Date", envelopeString},        {"Subject", envelopeString},
+    {"From", envelopeAddress},       {"Sender", envelopeAddress},
+    {"Reply-to", envelopeAddress},   {"To", envelopeAddress},
+    {"Cc", envelopeAddress},         {"Bcc", envelopeAddress},
+    {"In-reply-to", envelopeString}, {"Message-id", envelopeString}};
 
-void nsImapServerResponseParser::envelope_data()
-{
+void nsImapServerResponseParser::envelope_data() {
   AdvanceToNextToken();
-  fNextToken++; // eat '('
-  for (int tableIndex = 0; tableIndex < (int)(sizeof(EnvelopeTable) / sizeof(EnvelopeTable[0])); tableIndex++)
-  {
-    if (!ContinueParse())
-      break;
-    if (*fNextToken == ')')
-    {
-      SetSyntaxError(true); // envelope too short
+  fNextToken++;  // eat '('
+  for (int tableIndex = 0;
+       tableIndex < (int)(sizeof(EnvelopeTable) / sizeof(EnvelopeTable[0]));
+       tableIndex++) {
+    if (!ContinueParse()) break;
+    if (*fNextToken == ')') {
+      SetSyntaxError(true);  // envelope too short
       break;
     }
 
     nsAutoCString headerLine(EnvelopeTable[tableIndex].name);
     headerLine += ": ";
     bool headerNonNil = true;
-    if (EnvelopeTable[tableIndex].type == envelopeString)
-    {
+    if (EnvelopeTable[tableIndex].type == envelopeString) {
       nsAutoCString strValue;
       strValue.Adopt(CreateNilString());
       if (!strValue.IsEmpty())
         headerLine.Append(strValue);
       else
         headerNonNil = false;
-    }
-    else
-    {
+    } else {
       nsAutoCString address;
       parse_address(address);
       headerLine += address;
-      if (address.IsEmpty())
-        headerNonNil = false;
+      if (address.IsEmpty()) headerNonNil = false;
     }
     if (headerNonNil)
       fServerConnection.HandleMessageDownLoadLine(headerLine.get(), false);
 
-    if (ContinueParse())
-      AdvanceToNextToken();
+    if (ContinueParse()) AdvanceToNextToken();
   }
   // Now we should be at the end of the envelope and have *fToken == ')'.
   // Skip this last parenthesis.
   AdvanceToNextToken();
 }
 
-void nsImapServerResponseParser::xaolenvelope_data()
-{
+void nsImapServerResponseParser::xaolenvelope_data() {
   // eat the opening '('
   fNextToken++;
 
-  if (ContinueParse() && (*fNextToken != ')'))
-  {
+  if (ContinueParse() && (*fNextToken != ')')) {
     AdvanceToNextToken();
-    fNextToken++; // eat '('
+    fNextToken++;  // eat '('
     nsAutoCString subject;
     subject.Adopt(CreateNilString());
     nsAutoCString subjectLine("Subject: ");
     subjectLine += subject;
     fServerConnection.HandleMessageDownLoadLine(subjectLine.get(), false);
-    fNextToken++; // eat the next '('
-    if (ContinueParse())
-    {
+    fNextToken++;  // eat the next '('
+    if (ContinueParse()) {
       AdvanceToNextToken();
-      if (ContinueParse())
-      {
+      if (ContinueParse()) {
         nsAutoCString fromLine;
-        if (!strcmp(GetSelectedMailboxName(), "Sent Items"))
-        {
-          // xaol envelope switches the From with the To, so we switch them back and
-          // create a fake from line From: user@aol.com
+        if (!strcmp(GetSelectedMailboxName(), "Sent Items")) {
+          // xaol envelope switches the From with the To, so we switch them back
+          // and create a fake from line From: user@aol.com
           fromLine.AppendLiteral("To: ");
           nsAutoCString fakeFromLine(NS_LITERAL_CSTRING("From: "));
           fakeFromLine.Append(fServerConnection.GetImapUserName());
           fakeFromLine.AppendLiteral("@aol.com");
-          fServerConnection.HandleMessageDownLoadLine(fakeFromLine.get(), false);
-        }
-        else
-        {
+          fServerConnection.HandleMessageDownLoadLine(fakeFromLine.get(),
+                                                      false);
+        } else {
           fromLine.AppendLiteral("From: ");
         }
         parse_address(fromLine);
         fServerConnection.HandleMessageDownLoadLine(fromLine.get(), false);
-        if (ContinueParse())
-        {
+        if (ContinueParse()) {
           AdvanceToNextToken();  // ge attachment size
           int32_t attachmentSize = atoi(fNextToken);
-          if (attachmentSize != 0)
-          {
+          if (attachmentSize != 0) {
             nsAutoCString attachmentLine("X-attachment-size: ");
             attachmentLine.AppendInt(attachmentSize);
-            fServerConnection.HandleMessageDownLoadLine(attachmentLine.get(), false);
+            fServerConnection.HandleMessageDownLoadLine(attachmentLine.get(),
+                                                        false);
           }
         }
-        if (ContinueParse())
-        {
+        if (ContinueParse()) {
           AdvanceToNextToken();  // skip image size
           int32_t imageSize = atoi(fNextToken);
-          if (imageSize != 0)
-          {
+          if (imageSize != 0) {
             nsAutoCString imageLine("X-image-size: ");
             imageLine.AppendInt(imageSize);
             fServerConnection.HandleMessageDownLoadLine(imageLine.get(), false);
           }
         }
-        if (ContinueParse())
-          AdvanceToNextToken();  // skip )
+        if (ContinueParse()) AdvanceToNextToken();  // skip )
       }
     }
   }
 }
 
-void nsImapServerResponseParser::parse_address(nsAutoCString &addressLine)
-{
-  if (!strcmp(fNextToken, "NIL"))
-    return;
+void nsImapServerResponseParser::parse_address(nsAutoCString &addressLine) {
+  if (!strcmp(fNextToken, "NIL")) return;
   bool firstAddress = true;
   // should really look at chars here
   NS_ASSERTION(*fNextToken == '(', "address should start with '('");
-  fNextToken++; // eat the next '('
-  while (ContinueParse() && *fNextToken == '(')
-  {
+  fNextToken++;  // eat the next '('
+  while (ContinueParse() && *fNextToken == '(') {
     NS_ASSERTION(*fNextToken == '(', "address should start with '('");
-    fNextToken++; // eat the next '('
+    fNextToken++;  // eat the next '('
 
-    if (!firstAddress)
-      addressLine += ", ";
+    if (!firstAddress) addressLine += ", ";
 
     firstAddress = false;
     char *personalName = CreateNilString();
     AdvanceToNextToken();
     char *atDomainList = CreateNilString();
-    if (ContinueParse())
-    {
+    if (ContinueParse()) {
       AdvanceToNextToken();
       char *mailboxName = CreateNilString();
-      if (ContinueParse())
-      {
+      if (ContinueParse()) {
         AdvanceToNextToken();
         char *hostName = CreateNilString();
         AdvanceToNextToken();
         addressLine += mailboxName;
-        if (hostName)
-        {
+        if (hostName) {
           addressLine += '@';
           addressLine += hostName;
           free(hostName);
         }
-        if (personalName)
-        {
+        if (personalName) {
           addressLine += " (";
           addressLine += personalName;
           addressLine += ')';
         }
       }
     }
     PR_Free(personalName);
     PR_Free(atDomainList);
 
-    if (*fNextToken == ')')
-      fNextToken++;
+    if (*fNextToken == ')') fNextToken++;
     // if the next token isn't a ')' for the address term,
     // then we must have another address pair left....so get the next
     // token and continue parsing in this loop...
-    if ( *fNextToken == '\0' )
-      AdvanceToNextToken();
-
+    if (*fNextToken == '\0') AdvanceToNextToken();
   }
-  if (*fNextToken == ')')
-    fNextToken++;
+  if (*fNextToken == ')') fNextToken++;
   // AdvanceToNextToken();  // skip "))"
 }
 
-void nsImapServerResponseParser::internal_date()
-{
+void nsImapServerResponseParser::internal_date() {
   AdvanceToNextToken();
-  if (ContinueParse())
-  {
+  if (ContinueParse()) {
     nsAutoCString dateLine("Date: ");
     char *strValue = CreateNilString();
-    if (strValue)
-    {
+    if (strValue) {
       dateLine += strValue;
       free(strValue);
     }
     fServerConnection.HandleMessageDownLoadLine(dateLine.get(), false);
   }
   // advance the parser.
   AdvanceToNextToken();
 }
 
-void nsImapServerResponseParser::flags()
-{
+void nsImapServerResponseParser::flags() {
   imapMessageFlagsType messageFlags = kNoImapMsgFlag;
   fCustomFlags.Clear();
 
   // clear the custom flags for this message
   // otherwise the old custom flags will stay around
   // see bug #191042
   if (fFlagState && CurrentResponseUID() != nsMsgKey_None)
     fFlagState->ClearCustomFlags(CurrentResponseUID());
 
   // eat the opening '('
   fNextToken++;
-  while (ContinueParse() && (*fNextToken != ')'))
-  {
+  while (ContinueParse() && (*fNextToken != ')')) {
     bool knownFlag = false;
-    if (*fNextToken == '\\')
-    {
+    if (*fNextToken == '\\') {
       switch (NS_ToUpper(fNextToken[1])) {
-      case 'S':
-        if (!PL_strncasecmp(fNextToken, "\\Seen",5))
-        {
-          messageFlags |= kImapMsgSeenFlag;
-          knownFlag = true;
-        }
-        break;
-      case 'A':
-        if (!PL_strncasecmp(fNextToken, "\\Answered",9))
-        {
-          messageFlags |= kImapMsgAnsweredFlag;
-          knownFlag = true;
-        }
-        break;
-      case 'F':
-        if (!PL_strncasecmp(fNextToken, "\\Flagged",8))
-        {
-          messageFlags |= kImapMsgFlaggedFlag;
-          knownFlag = true;
-        }
-        break;
-      case 'D':
-        if (!PL_strncasecmp(fNextToken, "\\Deleted",8))
-        {
-          messageFlags |= kImapMsgDeletedFlag;
-          knownFlag = true;
-        }
-        else if (!PL_strncasecmp(fNextToken, "\\Draft",6))
-        {
-          messageFlags |= kImapMsgDraftFlag;
-          knownFlag = true;
-        }
-        break;
-      case 'R':
-        if (!PL_strncasecmp(fNextToken, "\\Recent",7))
-        {
-          messageFlags |= kImapMsgRecentFlag;
-          knownFlag = true;
-        }
-        break;
-      default:
-        break;
+        case 'S':
+          if (!PL_strncasecmp(fNextToken, "\\Seen", 5)) {
+            messageFlags |= kImapMsgSeenFlag;
+            knownFlag = true;
+          }
+          break;
+        case 'A':
+          if (!PL_strncasecmp(fNextToken, "\\Answered", 9)) {
+            messageFlags |= kImapMsgAnsweredFlag;
+            knownFlag = true;
+          }
+          break;
+        case 'F':
+          if (!PL_strncasecmp(fNextToken, "\\Flagged", 8)) {
+            messageFlags |= kImapMsgFlaggedFlag;
+            knownFlag = true;
+          }
+          break;
+        case 'D':
+          if (!PL_strncasecmp(fNextToken, "\\Deleted", 8)) {
+            messageFlags |= kImapMsgDeletedFlag;
+            knownFlag = true;
+          } else if (!PL_strncasecmp(fNextToken, "\\Draft", 6)) {
+            messageFlags |= kImapMsgDraftFlag;
+            knownFlag = true;
+          }
+          break;
+        case 'R':
+          if (!PL_strncasecmp(fNextToken, "\\Recent", 7)) {
+            messageFlags |= kImapMsgRecentFlag;
+            knownFlag = true;
+          }
+          break;
+        default:
+          break;
+      }
+    } else if (*fNextToken == '$') {
+      switch (NS_ToUpper(fNextToken[1])) {
+        case 'M':
+          if ((fSupportsUserDefinedFlags &
+               (kImapMsgSupportUserFlag | kImapMsgSupportMDNSentFlag)) &&
+              !PL_strncasecmp(fNextToken, "$MDNSent", 8)) {
+            messageFlags |= kImapMsgMDNSentFlag;
+            knownFlag = true;
+          }
+          break;
+        case 'F':
+          if ((fSupportsUserDefinedFlags &
+               (kImapMsgSupportUserFlag | kImapMsgSupportForwardedFlag)) &&
+              !PL_strncasecmp(fNextToken, "$Forwarded", 10)) {
+            messageFlags |= kImapMsgForwardedFlag;
+            knownFlag = true;
+          }
+          break;
+        default:
+          break;
       }
     }
-    else if (*fNextToken == '$')
-    {
-      switch (NS_ToUpper(fNextToken[1])) {
-      case 'M':
-        if ((fSupportsUserDefinedFlags & (kImapMsgSupportUserFlag |
-          kImapMsgSupportMDNSentFlag))
-          && !PL_strncasecmp(fNextToken, "$MDNSent",8))
-        {
-          messageFlags |= kImapMsgMDNSentFlag;
-          knownFlag = true;
-        }
-        break;
-      case 'F':
-        if ((fSupportsUserDefinedFlags & (kImapMsgSupportUserFlag |
-          kImapMsgSupportForwardedFlag))
-          && !PL_strncasecmp(fNextToken, "$Forwarded",10))
-        {
-          messageFlags |= kImapMsgForwardedFlag;
-          knownFlag = true;
-        }
-        break;
-      default:
-        break;
-      }
-    }
-    if (!knownFlag && fFlagState)
-    {
+    if (!knownFlag && fFlagState) {
       nsAutoCString flag(fNextToken);
       int32_t parenIndex = flag.FindChar(')');
-      if (parenIndex > 0)
-        flag.SetLength(parenIndex);
+      if (parenIndex > 0) flag.SetLength(parenIndex);
       messageFlags |= kImapMsgCustomKeywordFlag;
       if (CurrentResponseUID() != nsMsgKey_None && CurrentResponseUID() != 0)
         fFlagState->AddUidCustomFlagPair(CurrentResponseUID(), flag.get());
       else
         fCustomFlags.AppendElement(flag);
     }
-    if (PL_strcasestr(fNextToken, ")"))
-    {
+    if (PL_strcasestr(fNextToken, ")")) {
       // eat token chars until we get the ')'
-      while (*fNextToken != ')')
-        fNextToken++;
-    }
-    else
+      while (*fNextToken != ')') fNextToken++;
+    } else
       AdvanceToNextToken();
   }
 
   if (ContinueParse())
-    while(*fNextToken != ')')
-      fNextToken++;
+    while (*fNextToken != ')') fNextToken++;
 
   fCurrentLineContainedFlagInfo = true;  // handled in PostProcessEndOfLine
   fSavedFlagInfo = messageFlags;
 }
 
 // RFC3501:  resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
 //                             ; Status condition
-void nsImapServerResponseParser::resp_cond_state(bool isTagged)
-{
+void nsImapServerResponseParser::resp_cond_state(bool isTagged) {
   // According to RFC3501, Sec. 7.1, the untagged NO response "indicates a
   // warning; the command can still complete successfully."
   // However, the untagged BAD response "indicates a protocol-level error for
   // which the associated command can not be determined; it can also indicate an
   // internal server failure."
   // Thus, we flag an error for a tagged NO response and for any BAD response.
   if ((isTagged && !PL_strcasecmp(fNextToken, "NO")) ||
       !PL_strcasecmp(fNextToken, "BAD"))
     fCurrentCommandFailed = true;
 
   AdvanceToNextToken();
-  if (ContinueParse())
-    resp_text();
+  if (ContinueParse()) resp_text();
 }
 
 /*
 resp_text       ::= ["[" resp_text_code "]" SPACE] (text_mime2 / text)
 
   was changed to in order to enable a one symbol look ahead predictive
   parser.
 
     resp_text       ::= ["[" resp_text_code  SPACE] (text_mime2 / text)
 */
-void nsImapServerResponseParser::resp_text()
-{
-  if (ContinueParse() && (*fNextToken == '['))
-    resp_text_code();
+void nsImapServerResponseParser::resp_text() {
+  if (ContinueParse() && (*fNextToken == '[')) resp_text_code();
 
-  if (ContinueParse())
-  {
+  if (ContinueParse()) {
     if (!PL_strcmp(fNextToken, "=?"))
       text_mime2();
     else
       text();
   }
 }
 /*
  text_mime2       ::= "=?" <charset> "?" <encoding> "?"
                                <encoded-text> "?="
                                ;; Syntax defined in [MIME-2]
 */
-void nsImapServerResponseParser::text_mime2()
-{
-  skip_to_CRLF();
-}
+void nsImapServerResponseParser::text_mime2() { skip_to_CRLF(); }
 
 /*
  text            ::= 1*TEXT_CHAR
 
 */
-void nsImapServerResponseParser::text()
-{
-  skip_to_CRLF();
-}
+void nsImapServerResponseParser::text() { skip_to_CRLF(); }
 
-void nsImapServerResponseParser::parse_folder_flags(bool calledForFlags)
-{
+void nsImapServerResponseParser::parse_folder_flags(bool calledForFlags) {
   uint16_t labelFlags = 0;
   uint16_t junkNotJunkFlags = 0;
   bool storeUserFlags = calledForFlags && fFlagState;
   uint16_t numOtherKeywords = 0;
 
-  do
-  {
+  do {
     AdvanceToNextToken();
-    if (*fNextToken == '(')
-      fNextToken++;
+    if (*fNextToken == '(') fNextToken++;
     if (!PL_strncasecmp(fNextToken, "\\Seen", 5))
       fSettablePermanentFlags |= kImapMsgSeenFlag;
     else if (!PL_strncasecmp(fNextToken, "\\Answered", 9))
       fSettablePermanentFlags |= kImapMsgAnsweredFlag;
     else if (!PL_strncasecmp(fNextToken, "\\Flagged", 8))
       fSettablePermanentFlags |= kImapMsgFlaggedFlag;
     else if (!PL_strncasecmp(fNextToken, "\\Deleted", 8))
       fSettablePermanentFlags |= kImapMsgDeletedFlag;
     else if (!PL_strncasecmp(fNextToken, "\\Draft", 6))
       fSettablePermanentFlags |= kImapMsgDraftFlag;
-    else if (!PL_strncasecmp(fNextToken, "\\*", 2))
-    {
+    else if (!PL_strncasecmp(fNextToken, "\\*", 2)) {
       // User defined and special keywords (tags) can be defined and set for
       // mailbox. Should only occur in PERMANENTFLAGS response.
       fSupportsUserDefinedFlags |= kImapMsgSupportUserFlag;
       fSupportsUserDefinedFlags |= kImapMsgSupportForwardedFlag;
       fSupportsUserDefinedFlags |= kImapMsgSupportMDNSentFlag;
       fSupportsUserDefinedFlags |= kImapMsgLabelFlags;
-    }
-    else
-    {
+    } else {
       // Treat special and built-in $LabelX's as user defined if a
       // store occurs below. Include $Junk/$NotJunk in this too.
       if (!PL_strncasecmp(fNextToken, "$MDNSent", 8))
         fSupportsUserDefinedFlags |= kImapMsgSupportMDNSentFlag;
       else if (!PL_strncasecmp(fNextToken, "$Forwarded", 10))
         fSupportsUserDefinedFlags |= kImapMsgSupportForwardedFlag;
       else if (!PL_strncasecmp(fNextToken, "$Label1", 7))
         labelFlags |= 1;
@@ -1906,41 +1642,36 @@ void nsImapServerResponseParser::parse_f
         junkNotJunkFlags |= 2;
 
       // Store user keywords defined for mailbox, usually by other clients.
       // But only do this for FLAGS response, not PERMANENTFLAGS response.
       // This is only needed if '\*' does not appear in a PERMANENTFLAGS
       // response indicating the user defined keywords are not allowed. But this
       // is not known until this function is called for PERMANENTFLAGS which
       // typically occurs after FLAGS, so must store them regardless.
-      if (storeUserFlags && *fNextToken != '\r')
-      {
-        if (*(fNextToken + strlen(fNextToken) - 1) != ')')
-        {
+      if (storeUserFlags && *fNextToken != '\r') {
+        if (*(fNextToken + strlen(fNextToken) - 1) != ')') {
           // Token doesn't end in ')' so save it as is.
-          fFlagState->SetOtherKeywords(numOtherKeywords++, nsDependentCString(fNextToken));
-        }
-        else
-        {
+          fFlagState->SetOtherKeywords(numOtherKeywords++,
+                                       nsDependentCString(fNextToken));
+        } else {
           // Token ends in ')' so end of list. Save all but ending ')'.
-          fFlagState->SetOtherKeywords(numOtherKeywords++,
-                                       nsDependentCSubstring(fNextToken, strlen(fNextToken) - 1));
+          fFlagState->SetOtherKeywords(
+              numOtherKeywords++,
+              nsDependentCSubstring(fNextToken, strlen(fNextToken) - 1));
         }
       }
     }
   } while (!fAtEndOfLine && ContinueParse());
 
-  if (labelFlags == 31)
-    fSupportsUserDefinedFlags |= kImapMsgLabelFlags;
+  if (labelFlags == 31) fSupportsUserDefinedFlags |= kImapMsgLabelFlags;
 
-  if (fFlagState)
-    fFlagState->OrSupportedUserFlags(fSupportsUserDefinedFlags);
+  if (fFlagState) fFlagState->OrSupportedUserFlags(fSupportsUserDefinedFlags);
 
-  if (storeUserFlags)
-  {
+  if (storeUserFlags) {
     // Set true if both "$Junk" and "$NotJunk" appear in FLAGS.
     fStdJunkNotJunkUseOk = (junkNotJunkFlags == 3);
   }
 }
 /*
   resp_text_code  ::= ("ALERT" / "PARSE" /
                               "PERMANENTFLAGS" SPACE "(" #(flag / "\*") ")" /
                               "READ-ONLY" / "READ-WRITE" / "TRYCREATE" /
@@ -1948,976 +1679,812 @@ void nsImapServerResponseParser::parse_f
                               "UNSEEN" SPACE nz_number /
                               "HIGHESTMODSEQ" SPACE nz_number /
                               "NOMODSEQ" /
                               atom [SPACE 1*<any TEXT_CHAR except "]">] )
                       "]"
 
 
 */
-void nsImapServerResponseParser::resp_text_code()
-{
+void nsImapServerResponseParser::resp_text_code() {
   // this is a special case way of advancing the token
   // strtok won't break up "[ALERT]" into separate tokens
   if (strlen(fNextToken) > 1)
     fNextToken++;
   else
     AdvanceToNextToken();
 
-  if (ContinueParse())
-  {
-    if (!PL_strcasecmp(fNextToken,"ALERT]"))
-    {
+  if (ContinueParse()) {
+    if (!PL_strcasecmp(fNextToken, "ALERT]")) {
       char *alertMsg = fCurrentTokenPlaceHolder;  // advance past ALERT]
-      if (alertMsg && *alertMsg && (!fLastAlert || PL_strcmp(fNextToken, fLastAlert)))
-      {
+      if (alertMsg && *alertMsg &&
+          (!fLastAlert || PL_strcmp(fNextToken, fLastAlert))) {
         fServerConnection.AlertUserEvent(alertMsg);
         PR_Free(fLastAlert);
         fLastAlert = PL_strdup(alertMsg);
       }
       AdvanceToNextToken();
-    }
-    else if (!PL_strcasecmp(fNextToken,"PARSE]"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "PARSE]")) {
       // do nothing for now
       AdvanceToNextToken();
-    }
-    else if (!PL_strcasecmp(fNextToken,"NETSCAPE]"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "NETSCAPE]")) {
       skip_to_CRLF();
-    }
-    else if (!PL_strcasecmp(fNextToken,"PERMANENTFLAGS"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "PERMANENTFLAGS")) {
       uint32_t saveSettableFlags = fSettablePermanentFlags;
       fSupportsUserDefinedFlags = 0;  // assume no unless told
-      fSettablePermanentFlags = 0;            // assume none, unless told otherwise.
+      fSettablePermanentFlags = 0;    // assume none, unless told otherwise.
       parse_folder_flags(false);
       // if the server tells us there are no permanent flags, we're
       // just going to pretend that the FLAGS response flags, if any, are
       // permanent in case the server is broken. This will allow us
       // to store delete and seen flag changes - if they're not permanent,
       // they're not permanent, but at least we'll try to set them.
-      if (!fSettablePermanentFlags)
-        fSettablePermanentFlags = saveSettableFlags;
+      if (!fSettablePermanentFlags) fSettablePermanentFlags = saveSettableFlags;
       fGotPermanentFlags = true;
-    }
-    else if (!PL_strcasecmp(fNextToken,"READ-ONLY]"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "READ-ONLY]")) {
       fCurrentFolderReadOnly = true;
       AdvanceToNextToken();
-    }
-    else if (!PL_strcasecmp(fNextToken,"READ-WRITE]"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "READ-WRITE]")) {
       fCurrentFolderReadOnly = false;
       AdvanceToNextToken();
-    }
-    else if (!PL_strcasecmp(fNextToken,"TRYCREATE]"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "TRYCREATE]")) {
       // do nothing for now
       AdvanceToNextToken();
-    }
-    else if (!PL_strcasecmp(fNextToken,"UIDVALIDITY"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "UIDVALIDITY")) {
       AdvanceToNextToken();
-      if (ContinueParse())
-      {
+      if (ContinueParse()) {
         fFolderUIDValidity = strtoul(fNextToken, nullptr, 10);
         fHighestRecordedUID = 0;
         AdvanceToNextToken();
       }
-    }
-    else if (!PL_strcasecmp(fNextToken,"UNSEEN"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "UNSEEN")) {
       AdvanceToNextToken();
-      if (ContinueParse())
-      {
+      if (ContinueParse()) {
         fNumberOfUnseenMessages = strtoul(fNextToken, nullptr, 10);
         AdvanceToNextToken();
       }
-    }
-    else if (!PL_strcasecmp(fNextToken,"UIDNEXT"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "UIDNEXT")) {
       AdvanceToNextToken();
-      if (ContinueParse())
-      {
+      if (ContinueParse()) {
         fStatusNextUID = strtoul(fNextToken, nullptr, 10);
         AdvanceToNextToken();
       }
-    }
-    else if (!PL_strcasecmp(fNextToken, "APPENDUID"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "APPENDUID")) {
       AdvanceToNextToken();
-      if (ContinueParse())
-      {
+      if (ContinueParse()) {
         // ** jt -- the returned uidvalidity is the destination folder
         // uidvalidity; don't use it for current folder
         // fFolderUIDValidity = atoi(fNextToken);
         // fHighestRecordedUID = 0; ??? this should be wrong
         AdvanceToNextToken();
-        if (ContinueParse())
-        {
+        if (ContinueParse()) {
           fCurrentResponseUID = strtoul(fNextToken, nullptr, 10);
           AdvanceToNextToken();
         }
       }
-    }
-    else if (!PL_strcasecmp(fNextToken, "COPYUID"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "COPYUID")) {
       AdvanceToNextToken();
-      if (ContinueParse())
-      {
+      if (ContinueParse()) {
         // ** jt -- destination folder uidvalidity
         // fFolderUIDValidity = atoi(fNextToken);
         // original message set; ignore it
         AdvanceToNextToken();
-        if (ContinueParse())
-        {
+        if (ContinueParse()) {
           // the resulting message set; should be in the form of
           // either uid or uid1:uid2
           AdvanceToNextToken();
           // clear copy response uid
           fServerConnection.SetCopyResponseUid(fNextToken);
         }
-        if (ContinueParse())
-          AdvanceToNextToken();
+        if (ContinueParse()) AdvanceToNextToken();
       }
-    }
-    else if (!PL_strcasecmp(fNextToken, "HIGHESTMODSEQ"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "HIGHESTMODSEQ")) {
       AdvanceToNextToken();
-      if (ContinueParse())
-      {
+      if (ContinueParse()) {
         fHighestModSeq = ParseUint64Str(fNextToken);
         fUseModSeq = true;
         AdvanceToNextToken();
       }
-    }
-    else if (!PL_strcasecmp(fNextToken, "NOMODSEQ]"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "NOMODSEQ]")) {
       fHighestModSeq = 0;
       fUseModSeq = false;
       skip_to_CRLF();
-    }
-    else if (!PL_strcasecmp(fNextToken, "CAPABILITY"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "CAPABILITY")) {
       capability_data();
-    }
-    else if (!PL_strcasecmp(fNextToken, "MYRIGHTS"))
-    {
+    } else if (!PL_strcasecmp(fNextToken, "MYRIGHTS")) {
       myrights_data(true);
-    }
-    else // just text
+    } else  // just text
     {
       // do nothing but eat tokens until we see the ] or CRLF
       // we should see the ] but we don't want to go into an
       // endless loop if the CRLF is not there
-      do
-      {
+      do {
         AdvanceToNextToken();
-      } while (!PL_strcasestr(fNextToken, "]") && !fAtEndOfLine
-                && ContinueParse());
+      } while (!PL_strcasestr(fNextToken, "]") && !fAtEndOfLine &&
+               ContinueParse());
     }
   }
 }
 
 // RFC3501:  response-done = response-tagged / response-fatal
- void nsImapServerResponseParser::response_done()
- {
-   if (ContinueParse())
-   {
-     if (!PL_strcmp(fCurrentCommandTag, fNextToken))
-       response_tagged();
-     else
-       response_fatal();
-   }
- }
+void nsImapServerResponseParser::response_done() {
+  if (ContinueParse()) {
+    if (!PL_strcmp(fCurrentCommandTag, fNextToken))
+      response_tagged();
+    else
+      response_fatal();
+  }
+}
 
 // RFC3501:  response-tagged = tag SP resp-cond-state CRLF
- void nsImapServerResponseParser::response_tagged()
- {
-   // eat the tag
-   AdvanceToNextToken();
-   if (ContinueParse())
-   {
-     resp_cond_state(true);
-     if (ContinueParse())
-     {
-       if (!fAtEndOfLine)
-         SetSyntaxError(true);
-       else if (!fCurrentCommandFailed)
-         ResetLexAnalyzer();
-     }
-   }
- }
+void nsImapServerResponseParser::response_tagged() {
+  // eat the tag
+  AdvanceToNextToken();
+  if (ContinueParse()) {
+    resp_cond_state(true);
+    if (ContinueParse()) {
+      if (!fAtEndOfLine)
+        SetSyntaxError(true);
+      else if (!fCurrentCommandFailed)
+        ResetLexAnalyzer();
+    }
+  }
+}
 
 // RFC3501:  response-fatal = "*" SP resp-cond-bye CRLF
 //                              ; Server closes connection immediately
- void nsImapServerResponseParser::response_fatal()
- {
-   // eat the "*"
-   AdvanceToNextToken();
-   if (ContinueParse())
-     resp_cond_bye();
- }
+void nsImapServerResponseParser::response_fatal() {
+  // eat the "*"
+  AdvanceToNextToken();
+  if (ContinueParse()) resp_cond_bye();
+}
 
 // RFC3501:  resp-cond-bye = "BYE" SP resp-text
-void nsImapServerResponseParser::resp_cond_bye()
-{
+void nsImapServerResponseParser::resp_cond_bye() {
   SetConnected(false);
   fIMAPstate = kNonAuthenticated;
 }
 
-
-void nsImapServerResponseParser::msg_fetch_headers(const char *partNum)
-{
-  if (GetFillingInShell())
-  {
+void nsImapServerResponseParser::msg_fetch_headers(const char *partNum) {
+  if (GetFillingInShell()) {
     char *headerData = CreateAstring();
     AdvanceToNextToken();
     m_shell->AdoptMessageHeaders(headerData, partNum);
-  }
-  else
-  {
+  } else {
     msg_fetch_content(false, 0, MESSAGE_RFC822);
   }
 }
 
-
 /* nstring         ::= string / nil
 string          ::= quoted / literal
 nil             ::= "NIL"
 
 */
-void nsImapServerResponseParser::msg_fetch_content(bool chunk, int32_t origin, const char *content_type)
-{
+void nsImapServerResponseParser::msg_fetch_content(bool chunk, int32_t origin,
+                                                   const char *content_type) {
   // setup the stream for downloading this message.
   // Don't do it if we are filling in a shell or downloading a part.
   // DO do it if we are downloading a whole message as a result of
   // an invalid shell trying to generate.
   if ((!chunk || (origin == 0)) && !GetDownloadingHeaders() &&
-    (GetFillingInShell() ? m_shell->GetGeneratingWholeMessage() : true))
-  {
-    if (NS_FAILED(BeginMessageDownload(content_type)))
-      return;
+      (GetFillingInShell() ? m_shell->GetGeneratingWholeMessage() : true)) {
+    if (NS_FAILED(BeginMessageDownload(content_type))) return;
   }
 
-  if (PL_strcasecmp(fNextToken, "NIL"))
-  {
+  if (PL_strcasecmp(fNextToken, "NIL")) {
     if (*fNextToken == '"')
       fLastChunk = msg_fetch_quoted();
     else
       fLastChunk = msg_fetch_literal(chunk, origin);
-  }
-  else
+  } else
     AdvanceToNextToken();  // eat "NIL"
 
-  if (fLastChunk && (GetFillingInShell() ? m_shell->GetGeneratingWholeMessage() : true))
-  {
+  if (fLastChunk &&
+      (GetFillingInShell() ? m_shell->GetGeneratingWholeMessage() : true)) {
     // complete the message download
-    if (ContinueParse())
-    {
-      if (fReceivedHeaderOrSizeForUID == CurrentResponseUID())
-      {
+    if (ContinueParse()) {
+      if (fReceivedHeaderOrSizeForUID == CurrentResponseUID()) {
         fServerConnection.NormalMessageEndDownload();
         fReceivedHeaderOrSizeForUID = nsMsgKey_None;
-      }
-      else
-         fReceivedHeaderOrSizeForUID = CurrentResponseUID();
-    }
-    else
+      } else
+        fReceivedHeaderOrSizeForUID = CurrentResponseUID();
+    } else
       fServerConnection.AbortMessageDownLoad();
   }
 }
 
-
 /*
 quoted          ::= <"> *QUOTED_CHAR <">
 
   QUOTED_CHAR     ::= <any TEXT_CHAR except quoted_specials> /
   "\" quoted_specials
 
     quoted_specials ::= <"> / "\"
 */
 
-bool nsImapServerResponseParser::msg_fetch_quoted()
-{
+bool nsImapServerResponseParser::msg_fetch_quoted() {
   // *Should* never get a quoted string in response to a chunked download,
   // but the RFCs don't forbid it
   char *q = CreateQuoted();
-  if (q)
-  {
+  if (q) {
     numberOfCharsInThisChunk = PL_strlen(q);
     fServerConnection.HandleMessageDownLoadLine(q, false, q);
     PR_Free(q);
-  }
-  else
+  } else
     numberOfCharsInThisChunk = 0;
 
   AdvanceToNextToken();
-  bool lastChunk = ((fServerConnection.GetCurFetchSize() == 0) ||
-                    (numberOfCharsInThisChunk != fServerConnection.GetCurFetchSize()));
+  bool lastChunk =
+      ((fServerConnection.GetCurFetchSize() == 0) ||
+       (numberOfCharsInThisChunk != fServerConnection.GetCurFetchSize()));
   return lastChunk;
 }
 
 /* msg_obsolete    ::= "COPY" / ("STORE" SPACE msg_fetch)
 ;; OBSOLETE untagged data responses */
-void nsImapServerResponseParser::msg_obsolete()
-{
+void nsImapServerResponseParser::msg_obsolete() {
   if (!PL_strcasecmp(fNextToken, "COPY"))
     AdvanceToNextToken();
-  else if (!PL_strcasecmp(fNextToken, "STORE"))
-  {
+  else if (!PL_strcasecmp(fNextToken, "STORE")) {
     AdvanceToNextToken();
-    if (ContinueParse())
-      msg_fetch();
-  }
-  else
+    if (ContinueParse()) msg_fetch();
+  } else
     SetSyntaxError(true);
 }
 
-void nsImapServerResponseParser::capability_data()
-{
+void nsImapServerResponseParser::capability_data() {
   int32_t endToken = -1;
   fCapabilityFlag = kCapabilityDefined | kHasAuthOldLoginCapability;
   do {
     AdvanceToNextToken();
     if (fNextToken) {
       nsCString token(fNextToken);
       endToken = token.FindChar(']');
-      if (endToken >= 0)
-        token.SetLength(endToken);
+      if (endToken >= 0) token.SetLength(endToken);
 
-      if(token.Equals("AUTH=LOGIN", nsCaseInsensitiveCStringComparator()))
+      if (token.Equals("AUTH=LOGIN", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasAuthLoginCapability;
-      else if(token.Equals("AUTH=PLAIN", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("AUTH=PLAIN", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasAuthPlainCapability;
-      else if (token.Equals("AUTH=CRAM-MD5", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("AUTH=CRAM-MD5",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasCRAMCapability;
       else if (token.Equals("AUTH=NTLM", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasAuthNTLMCapability;
-      else if (token.Equals("AUTH=GSSAPI", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("AUTH=GSSAPI",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasAuthGssApiCapability;
       else if (token.Equals("AUTH=MSN", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasAuthMSNCapability;
-      else if (token.Equals("AUTH=EXTERNAL", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("AUTH=EXTERNAL",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasAuthExternalCapability;
-      else if (token.Equals("AUTH=XOAUTH2", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("AUTH=XOAUTH2",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasXOAuth2Capability;
       else if (token.Equals("STARTTLS", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasStartTLSCapability;
-      else if (token.Equals("LOGINDISABLED", nsCaseInsensitiveCStringComparator()))
-        fCapabilityFlag &= ~kHasAuthOldLoginCapability; // remove flag
+      else if (token.Equals("LOGINDISABLED",
+                            nsCaseInsensitiveCStringComparator()))
+        fCapabilityFlag &= ~kHasAuthOldLoginCapability;  // remove flag
       else if (token.Equals("XSENDER", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasXSenderCapability;
       else if (token.Equals("IMAP4", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kIMAP4Capability;
       else if (token.Equals("IMAP4rev1", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kIMAP4rev1Capability;
-      else if (Substring(token,0,5).Equals("IMAP4", nsCaseInsensitiveCStringComparator()))
+      else if (Substring(token, 0, 5)
+                   .Equals("IMAP4", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kIMAP4other;
-      else if (token.Equals("X-NO-ATOMIC-RENAME", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("X-NO-ATOMIC-RENAME",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kNoHierarchyRename;
-      else if (token.Equals("X-NON-HIERARCHICAL-RENAME", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("X-NON-HIERARCHICAL-RENAME",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kNoHierarchyRename;
       else if (token.Equals("NAMESPACE", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kNamespaceCapability;
       else if (token.Equals("ID", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasIDCapability;
       else if (token.Equals("ACL", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kACLCapability;
-      else if (token.Equals("XSERVERINFO", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("XSERVERINFO",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kXServerInfoCapability;
       else if (token.Equals("UIDPLUS", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kUidplusCapability;
       else if (token.Equals("LITERAL+", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kLiteralPlusCapability;
-      else if (token.Equals("XAOL-OPTION", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("XAOL-OPTION",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kAOLImapCapability;
       else if (token.Equals("X-GM-EXT-1", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kGmailImapCapability;
       else if (token.Equals("QUOTA", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kQuotaCapability;
       else if (token.Equals("LANGUAGE", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasLanguageCapability;
       else if (token.Equals("IDLE", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasIdleCapability;
       else if (token.Equals("CONDSTORE", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasCondStoreCapability;
       else if (token.Equals("ENABLE", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasEnableCapability;
-      else if (token.Equals("LIST-EXTENDED", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("LIST-EXTENDED",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasListExtendedCapability;
       else if (token.Equals("XLIST", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasXListCapability;
-      else if (token.Equals("SPECIAL-USE", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("SPECIAL-USE",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasSpecialUseCapability;
-      else if (token.Equals("COMPRESS=DEFLATE", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("COMPRESS=DEFLATE",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasCompressDeflateCapability;
       else if (token.Equals("MOVE", nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasMoveCapability;
-      else if (token.Equals("HIGHESTMODSEQ", nsCaseInsensitiveCStringComparator()))
+      else if (token.Equals("HIGHESTMODSEQ",
+                            nsCaseInsensitiveCStringComparator()))
         fCapabilityFlag |= kHasHighestModSeqCapability;
     }
   } while (fNextToken && endToken < 0 && !fAtEndOfLine && ContinueParse());
 
   nsImapProtocol *navCon = &fServerConnection;
-  NS_ASSERTION(navCon, "null imap protocol connection while parsing capability response");  // we should always have this
-  if (navCon)
-    navCon->CommitCapability();
+  NS_ASSERTION(navCon,
+               "null imap protocol connection while parsing capability "
+               "response");  // we should always have this
+  if (navCon) navCon->CommitCapability();
   skip_to_CRLF();
 }
 
-void nsImapServerResponseParser::xmailboxinfo_data()
-{
+void nsImapServerResponseParser::xmailboxinfo_data() {
   AdvanceToNextToken();
-  if (!fNextToken)
-    return;
+  if (!fNextToken) return;
 
-  char *mailboxName = CreateAstring(); // PL_strdup(fNextToken);
-  if (mailboxName)
-  {
-    do
-    {
+  char *mailboxName = CreateAstring();  // PL_strdup(fNextToken);
+  if (mailboxName) {
+    do {
       AdvanceToNextToken();
-      if (fNextToken)
-      {
-        if (!PL_strcmp("MANAGEURL", fNextToken))
-        {
+      if (fNextToken) {
+        if (!PL_strcmp("MANAGEURL", fNextToken)) {
           AdvanceToNextToken();
           fFolderAdminUrl = CreateAstring();
-        }
-        else if (!PL_strcmp("POSTURL", fNextToken))
-        {
+        } else if (!PL_strcmp("POSTURL", fNextToken)) {
           AdvanceToNextToken();
           // ignore this for now...
         }
       }
     } while (fNextToken && !fAtEndOfLine && ContinueParse());
   }
 }
 
-void nsImapServerResponseParser::xserverinfo_data()
-{
-  do
-  {
+void nsImapServerResponseParser::xserverinfo_data() {
+  do {
     AdvanceToNextToken();
-    if (!fNextToken)
-      break;
-    if (!PL_strcmp("MANAGEACCOUNTURL", fNextToken))
-    {
+    if (!fNextToken) break;
+    if (!PL_strcmp("MANAGEACCOUNTURL", fNextToken)) {
       AdvanceToNextToken();
       fMailAccountUrl.Adopt(CreateNilString());
-    }
-    else if (!PL_strcmp("MANAGELISTSURL", fNextToken))
-    {
+    } else if (!PL_strcmp("MANAGELISTSURL", fNextToken)) {
       AdvanceToNextToken();
       fManageListsUrl.Adopt(CreateNilString());
-    }
-    else if (!PL_strcmp("MANAGEFILTERSURL", fNextToken))
-    {
+    } else if (!PL_strcmp("MANAGEFILTERSURL", fNextToken)) {
       AdvanceToNextToken();
       fManageFiltersUrl.Adopt(CreateNilString());
     }
   } while (fNextToken && !fAtEndOfLine && ContinueParse());
 }
 
-void nsImapServerResponseParser::enable_data()
-{
-  do
-  {
+void nsImapServerResponseParser::enable_data() {
+  do {
     // eat each enable response;
-     AdvanceToNextToken();
-     if (!strcmp("CONDSTORE", fNextToken))
-       fCondStoreEnabled = true;
+    AdvanceToNextToken();
+    if (!strcmp("CONDSTORE", fNextToken)) fCondStoreEnabled = true;
   } while (fNextToken && !fAtEndOfLine && ContinueParse());
-
 }
 
-void nsImapServerResponseParser::language_data()
-{
+void nsImapServerResponseParser::language_data() {
   // we may want to go out and store the language returned to us
   // by the language command in the host info session stuff.
 
   // for now, just eat the language....
-  do
-  {
+  do {
     // eat each language returned to us
     AdvanceToNextToken();
   } while (fNextToken && !fAtEndOfLine && ContinueParse());
 }
 
 // cram/auth response data ::= "+" SPACE challenge CRLF
 // the server expects more client data after issuing its challenge
 
-void nsImapServerResponseParser::authChallengeResponse_data()
-{
+void nsImapServerResponseParser::authChallengeResponse_data() {
   AdvanceToNextToken();
   fAuthChallenge = strdup(fNextToken);
   fWaitingForMoreClientInput = true;
 
   skip_to_CRLF();
 }
 
-
-void nsImapServerResponseParser::namespace_data()
-{
+void nsImapServerResponseParser::namespace_data() {
   EIMAPNamespaceType namespaceType = kPersonalNamespace;
   bool namespacesCommitted = false;
-  const char* serverKey = fServerConnection.GetImapServerKey();
-  while ((namespaceType != kUnknownNamespace) && ContinueParse())
-  {
+  const char *serverKey = fServerConnection.GetImapServerKey();
+  while ((namespaceType != kUnknownNamespace) && ContinueParse()) {
     AdvanceToNextToken();
-    while (fAtEndOfLine && ContinueParse())
-      AdvanceToNextToken();
-    if (!PL_strcasecmp(fNextToken,"NIL"))
-    {
+    while (fAtEndOfLine && ContinueParse()) AdvanceToNextToken();
+    if (!PL_strcasecmp(fNextToken, "NIL")) {
       // No namespace for this type.
       // Don't add anything to the Namespace object.
-    }
-    else if (fNextToken[0] == '(')
-    {
+    } else if (fNextToken[0] == '(') {
       // There may be multiple namespaces of the same type.
       // Go through each of them and add them to our Namespace object.
 
       fNextToken++;
-      while (fNextToken[0] == '(' && ContinueParse())
-      {
+      while (fNextToken[0] == '(' && ContinueParse()) {
         // we have another namespace for this namespace type
         fNextToken++;
-        if (fNextToken[0] != '"')
-        {
+        if (fNextToken[0] != '"') {
           SetSyntaxError(true);
-        }
-        else
-        {
+        } else {
           char *namespacePrefix = CreateQuoted(false);
 
           AdvanceToNextToken();
           const char *quotedDelimiter = fNextToken;
           char namespaceDelimiter = '\0';
 
-          if (quotedDelimiter[0] == '"')
-          {
+          if (quotedDelimiter[0] == '"') {
             quotedDelimiter++;
             namespaceDelimiter = quotedDelimiter[0];
-          }
-          else if (!PL_strncasecmp(quotedDelimiter, "NIL", 3))
-          {
+          } else if (!PL_strncasecmp(quotedDelimiter, "NIL", 3)) {
             // NIL hierarchy delimiter.  Leave namespace delimiter nullptr.
-          }
-          else
-          {
+          } else {
             // not quoted or NIL.
             SetSyntaxError(true);
           }
-          if (ContinueParse())
-          {
+          if (ContinueParse()) {
             // add code to parse the TRANSLATE attribute if it is present....
-            // we'll also need to expand the name space code to take in the translated prefix name.
+            // we'll also need to expand the name space code to take in the
+            // translated prefix name.
 
-            nsIMAPNamespace *newNamespace = new nsIMAPNamespace(namespaceType, namespacePrefix, namespaceDelimiter, false);
+            nsIMAPNamespace *newNamespace = new nsIMAPNamespace(
+                namespaceType, namespacePrefix, namespaceDelimiter, false);
             // add it to a temporary list in the host
             if (newNamespace && fHostSessionList)
               fHostSessionList->AddNewNamespaceForHost(serverKey, newNamespace);
 
             skip_to_close_paren();  // Ignore any extension data
 
             bool endOfThisNamespaceType = (fNextToken[0] == ')');
-            if (!endOfThisNamespaceType && fNextToken[0] != '(')  // no space between namespaces of the same type
+            if (!endOfThisNamespaceType &&
+                fNextToken[0] !=
+                    '(')  // no space between namespaces of the same type
             {
               SetSyntaxError(true);
             }
           }
           PR_Free(namespacePrefix);
         }
       }
-    }
-    else
-    {
+    } else {
       SetSyntaxError(true);
     }
-    switch (namespaceType)
-    {
-    case kPersonalNamespace:
-      namespaceType = kOtherUsersNamespace;
-      break;
-    case kOtherUsersNamespace:
-      namespaceType = kPublicNamespace;
-      break;
-    default:
-      namespaceType = kUnknownNamespace;
-      break;
+    switch (namespaceType) {
+      case kPersonalNamespace:
+        namespaceType = kOtherUsersNamespace;
+        break;
+      case kOtherUsersNamespace:
+        namespaceType = kPublicNamespace;
+        break;
+      default:
+        namespaceType = kUnknownNamespace;
+        break;
     }
   }
-  if (ContinueParse())
-  {
+  if (ContinueParse()) {
     nsImapProtocol *navCon = &fServerConnection;
-    NS_ASSERTION(navCon, "null protocol connection while parsing namespace");  // we should always have this
-    if (navCon)
-    {
+    NS_ASSERTION(
+        navCon,
+        "null protocol connection while parsing namespace");  // we should
+                                                              // always have
+                                                              // this
+    if (navCon) {
       navCon->CommitNamespacesForHostEvent();
       namespacesCommitted = true;
     }
   }
   skip_to_CRLF();
 
-  if (!namespacesCommitted && fHostSessionList)
-  {
+  if (!namespacesCommitted && fHostSessionList) {
     bool success;
-    fHostSessionList->FlushUncommittedNamespacesForHost(serverKey,
-                                                            success);
+    fHostSessionList->FlushUncommittedNamespacesForHost(serverKey, success);
   }
 }
 
-void nsImapServerResponseParser::myrights_data(bool unsolicited)
-{
+void nsImapServerResponseParser::myrights_data(bool unsolicited) {
   AdvanceToNextToken();
-  if (ContinueParse() && !fAtEndOfLine)
-  {
+  if (ContinueParse() && !fAtEndOfLine) {
     char *mailboxName;
     // an unsolicited myrights response won't have the mailbox name in
     // the response, so we use the selected mailbox name.
-    if (unsolicited)
-    {
+    if (unsolicited) {
       mailboxName = strdup(fSelectedMailboxName);
-    }
-    else
-    {
+    } else {
       mailboxName = CreateAstring();
-      if (mailboxName)
-        AdvanceToNextToken();
+      if (mailboxName) AdvanceToNextToken();
     }
-    if (mailboxName)
-    {
-      if (ContinueParse())
-      {
+    if (mailboxName) {
+      if (ContinueParse()) {
         char *myrights = CreateAstring();
-        if (myrights)
-        {
+        if (myrights) {
           nsImapProtocol *navCon = &fServerConnection;
-          NS_ASSERTION(navCon, "null connection parsing my rights"); // we should always have this
+          NS_ASSERTION(
+              navCon, "null connection parsing my rights");  // we should always
+                                                             // have this
           if (navCon)
-            navCon->AddFolderRightsForUser(mailboxName, nullptr /* means "me" */, myrights);
+            navCon->AddFolderRightsForUser(mailboxName,
+                                           nullptr /* means "me" */, myrights);
           PR_Free(myrights);
-        }
-        else
-        {
+        } else {
           HandleMemoryFailure();
         }
-        if (ContinueParse())
-          AdvanceToNextToken();
+        if (ContinueParse()) AdvanceToNextToken();
       }
       PR_Free(mailboxName);
-    }
-    else
-    {
+    } else {
       HandleMemoryFailure();
     }
-  }
-  else
-  {
+  } else {
     SetSyntaxError(true);
   }
 }
 
-void nsImapServerResponseParser::acl_data()
-{
+void nsImapServerResponseParser::acl_data() {
   AdvanceToNextToken();
-  if (ContinueParse() && !fAtEndOfLine)
-  {
+  if (ContinueParse() && !fAtEndOfLine) {
     char *mailboxName = CreateAstring();  // PL_strdup(fNextToken);
-    if (mailboxName && ContinueParse())
-    {
+    if (mailboxName && ContinueParse()) {
       AdvanceToNextToken();
-      while (ContinueParse() && !fAtEndOfLine)
-      {
-        char *userName = CreateAstring(); // PL_strdup(fNextToken);
-        if (userName && ContinueParse())
-        {
+      while (ContinueParse() && !fAtEndOfLine) {
+        char *userName = CreateAstring();  // PL_strdup(fNextToken);
+        if (userName && ContinueParse()) {
           AdvanceToNextToken();
-          if (ContinueParse())
-          {
-            char *rights = CreateAstring(); // PL_strdup(fNextToken);
-            if (rights)
-            {
-              fServerConnection.AddFolderRightsForUser(mailboxName, userName, rights);
+          if (ContinueParse()) {
+            char *rights = CreateAstring();  // PL_strdup(fNextToken);
+            if (rights) {
+              fServerConnection.AddFolderRightsForUser(mailboxName, userName,
+                                                       rights);
               PR_Free(rights);
-            }
-            else
+            } else
               HandleMemoryFailure();
 
-            if (ContinueParse())
-              AdvanceToNextToken();
+            if (ContinueParse()) AdvanceToNextToken();
           }
           PR_Free(userName);
-        }
-        else
+        } else
           HandleMemoryFailure();
       }
       PR_Free(mailboxName);
-    }
-    else
+    } else
       HandleMemoryFailure();
   }
 }
 
-
-void nsImapServerResponseParser::mime_data()
-{
+void nsImapServerResponseParser::mime_data() {
   if (PL_strstr(fNextToken, "MIME"))
     mime_header_data();
   else
     mime_part_data();
 }
 
 // mime_header_data should not be streamed out;  rather, it should be
 // buffered in the nsIMAPBodyShell.
 // This is because we are still in the process of generating enough
 // information from the server (such as the MIME header's size) so that
 // we can construct the final output stream.
-void nsImapServerResponseParser::mime_header_data()
-{
+void nsImapServerResponseParser::mime_header_data() {
   char *partNumber = PL_strdup(fNextToken);
-  if (partNumber)
-  {
-    char *start = partNumber + 5, *end = partNumber + 5; // 5 == strlen("BODY[")
-    while (ContinueParse() && end && *end != 'M' && *end != 'm')
-    {
+  if (partNumber) {
+    char *start = partNumber + 5,
+         *end = partNumber + 5;  // 5 == strlen("BODY[")
+    while (ContinueParse() && end && *end != 'M' && *end != 'm') {
       end++;
     }
-    if (end && (*end == 'M' || *end == 'm'))
-    {
-      *(end-1) = 0;
+    if (end && (*end == 'M' || *end == 'm')) {
+      *(end - 1) = 0;
       AdvanceToNextToken();
       char *mimeHeaderData = CreateAstring();  // is it really this simple?
       AdvanceToNextToken();
-      if (m_shell)
-      {
+      if (m_shell) {
         m_shell->AdoptMimeHeader(start, mimeHeaderData);
       }
-    }
-    else
-    {
+    } else {
       SetSyntaxError(true);
     }
     PR_Free(partNumber);  // partNumber is not adopted by the body shell.
-  }
-  else
-  {
+  } else {
     HandleMemoryFailure();
   }
 }
 
 // Actual mime parts are filled in on demand (either from shell generation
 // or from explicit user download), so we need to stream these out.
-void nsImapServerResponseParser::mime_part_data()
-{
+void nsImapServerResponseParser::mime_part_data() {
   char *checkOriginToken = PL_strdup(fNextToken);
-  if (checkOriginToken)
-  {
+  if (checkOriginToken) {
     uint32_t origin = 0;
     bool originFound = false;
     char *whereStart = PL_strchr(checkOriginToken, '<');
-    if (whereStart)
-    {
+    if (whereStart) {
       char *whereEnd = PL_strchr(whereStart, '>');
-      if (whereEnd)
-      {
+      if (whereEnd) {
         *whereEnd = 0;
         whereStart++;
         origin = atoi(whereStart);
         originFound = true;
       }
     }
     PR_Free(checkOriginToken);
     AdvanceToNextToken();
-    msg_fetch_content(originFound, origin, MESSAGE_RFC822);  // keep content type as message/rfc822, even though the
+    msg_fetch_content(originFound, origin,
+                      MESSAGE_RFC822);  // keep content type as message/rfc822,
+                                        // even though the
     // MIME part might not be, because then libmime will
     // still handle and decode it.
-  }
-  else
+  } else
     HandleMemoryFailure();
 }
 
 // parse FETCH BODYSTRUCTURE response, "a parenthesized list that describes
 // the [MIME-IMB] body structure of a message" [RFC 3501].
-void nsImapServerResponseParser::bodystructure_data()
-{
+void nsImapServerResponseParser::bodystructure_data() {
   AdvanceToNextToken();
-  if (ContinueParse() && fNextToken && *fNextToken == '(')  // It has to start with an open paren.
+  if (ContinueParse() && fNextToken &&
+      *fNextToken == '(')  // It has to start with an open paren.
   {
-    // Turn the BODYSTRUCTURE response into a form that the nsIMAPBodypartMessage can be constructed from.
-    // FIXME: Follow up on bug 384210 to investigate why the caller has to duplicate the two in-param strings.
-    nsIMAPBodypartMessage *message =
-      new nsIMAPBodypartMessage(NULL, NULL, true, strdup("message"),
-                                strdup("rfc822"),
-                                NULL, NULL, NULL, 0,
-                                fServerConnection.GetPreferPlainText());
+    // Turn the BODYSTRUCTURE response into a form that the
+    // nsIMAPBodypartMessage can be constructed from.
+    // FIXME: Follow up on bug 384210 to investigate why the caller has to
+    // duplicate the two in-param strings.
+    nsIMAPBodypartMessage *message = new nsIMAPBodypartMessage(
+        NULL, NULL, true, strdup("message"), strdup("rfc822"), NULL, NULL, NULL,
+        0, fServerConnection.GetPreferPlainText());
     nsIMAPBodypart *body = bodystructure_part(PL_strdup("1"), message);
     if (body)
       message->SetBody(body);
-    else
-    {
+    else {
       delete message;
       message = nullptr;
     }
-    m_shell = new nsIMAPBodyShell(&fServerConnection, message, CurrentResponseUID(),
-                                  FolderUID(), GetSelectedMailboxName());
-    // ignore syntax errors in parsing the body structure response. If there's an error
-    // we'll just fall back to fetching the whole message.
+    m_shell =
+        new nsIMAPBodyShell(&fServerConnection, message, CurrentResponseUID(),
+                            FolderUID(), GetSelectedMailboxName());
+    // ignore syntax errors in parsing the body structure response. If there's
+    // an error we'll just fall back to fetching the whole message.
     SetSyntaxError(false);
-  }
-  else
+  } else
     SetSyntaxError(true);
 }
 
 // RFC3501:  body = "(" (body-type-1part / body-type-mpart) ")"
-nsIMAPBodypart *
-nsImapServerResponseParser::bodystructure_part(char *partNum, nsIMAPBodypart *parentPart)
-{
+nsIMAPBodypart *nsImapServerResponseParser::bodystructure_part(
+    char *partNum, nsIMAPBodypart *parentPart) {
   // Check to see if this buffer is a leaf or container
   // (Look at second character - if an open paren, then it is a container)
-  if (*fNextToken != '(')
-  {
+  if (*fNextToken != '(') {
     NS_ASSERTION(false, "bodystructure_part must begin with '('");
     return NULL;
   }
 
-  if (fNextToken[1] == '(')
-    return bodystructure_multipart(partNum, parentPart);
+  if (fNextToken[1] == '(') return bodystructure_multipart(partNum, parentPart);
   return bodystructure_leaf(partNum, parentPart);
 }
 
 // RFC3501: body-type-1part = (body-type-basic / body-type-msg / body-type-text)
 //                            [SP body-ext-1part]
-nsIMAPBodypart *
-nsImapServerResponseParser::bodystructure_leaf(char *partNum, nsIMAPBodypart *parentPart)
-{
-  // historical note: this code was originally in nsIMAPBodypartLeaf::ParseIntoObjects()
-  char *bodyType = nullptr, *bodySubType = nullptr, *bodyID = nullptr, *bodyDescription = nullptr, *bodyEncoding = nullptr;
+nsIMAPBodypart *nsImapServerResponseParser::bodystructure_leaf(
+    char *partNum, nsIMAPBodypart *parentPart) {
+  // historical note: this code was originally in
+  // nsIMAPBodypartLeaf::ParseIntoObjects()
+  char *bodyType = nullptr, *bodySubType = nullptr, *bodyID = nullptr,
+       *bodyDescription = nullptr, *bodyEncoding = nullptr;
   int32_t partLength = 0;
   bool isValid = true;
 
   // body type  ("application", "text", "image", etc.)
-  if (ContinueParse())
-  {
-    fNextToken++; // eat the first '('
+  if (ContinueParse()) {
+    fNextToken++;  // eat the first '('
     bodyType = CreateNilString();
-    if (ContinueParse())
-      AdvanceToNextToken();
+    if (ContinueParse()) AdvanceToNextToken();
   }
 
   // body subtype  ("gif", "html", etc.)
-  if (isValid && ContinueParse())
-  {
+  if (isValid && ContinueParse()) {
     bodySubType = CreateNilString();
-    if (ContinueParse())
-      AdvanceToNextToken();
+    if (ContinueParse()) AdvanceToNextToken();
   }
 
   // body parameter: parenthesized list
-  if (isValid && ContinueParse())
-  {
-    if (fNextToken[0] == '(')
-    {
+  if (isValid && ContinueParse()) {
+    if (fNextToken[0] == '(') {
       fNextToken++;
       skip_to_close_paren();
-    }
-    else if (!PL_strcasecmp(fNextToken, "NIL"))
+    } else if (!PL_strcasecmp(fNextToken, "NIL"))
       AdvanceToNextToken();
   }
 
   // body id
-  if (isValid && ContinueParse())
-  {
+  if (isValid && ContinueParse()) {
     bodyID = CreateNilString();
-    if (ContinueParse())
-      AdvanceToNextToken();
+    if (ContinueParse()) AdvanceToNextToken();
   }
 
   // body description
-  if (isValid && ContinueParse())
-  {
+  if (isValid && ContinueParse()) {
     bodyDescription = CreateNilString();
-    if (ContinueParse())
-      AdvanceToNextToken();
+    if (ContinueParse()) AdvanceToNextToken();
   }
 
   // body encoding
-  if (isValid && ContinueParse())
-  {
+  if (isValid && ContinueParse()) {
     bodyEncoding = CreateNilString();
-    if (ContinueParse())
-      AdvanceToNextToken();
+    if (ContinueParse()) AdvanceToNextToken();
   }
 
   // body size
-  if (isValid && ContinueParse())
-  {
+  if (isValid && ContinueParse()) {
     char *bodySizeString = CreateAtom();
     if (!bodySizeString)
       isValid = false;
-    else
-    {
+    else {
       partLength = atoi(bodySizeString);
       PR_Free(bodySizeString);
-      if (ContinueParse())
-        AdvanceToNextToken();
+      if (ContinueParse()) AdvanceToNextToken();
     }
   }
 
-  if (!isValid || !ContinueParse())
-  {
+  if (!isValid || !ContinueParse()) {
     PR_FREEIF(partNum);
     PR_FREEIF(bodyType);
     PR_FREEIF(bodySubType);
     PR_FREEIF(bodyID);
     PR_FREEIF(bodyDescription);
     PR_FREEIF(bodyEncoding);
-  }
-  else
-  {
-    if (PL_strcasecmp(bodyType, "message") || PL_strcasecmp(bodySubType, "rfc822"))
-    {
+  } else {
+    if (PL_strcasecmp(bodyType, "message") ||
+        PL_strcasecmp(bodySubType, "rfc822")) {
       skip_to_close_paren();
-      return new nsIMAPBodypartLeaf(partNum, parentPart, bodyType, bodySubType,
-                                    bodyID, bodyDescription, bodyEncoding,
-                                    partLength,
-                                    fServerConnection.GetPreferPlainText());
+      return new nsIMAPBodypartLeaf(
+          partNum, parentPart, bodyType, bodySubType, bodyID, bodyDescription,
+          bodyEncoding, partLength, fServerConnection.GetPreferPlainText());
     }
 
     // This part is of type "message/rfc822"  (probably a forwarded message)
-    nsIMAPBodypartMessage *message =
-      new nsIMAPBodypartMessage(partNum, parentPart, false,
-                                bodyType, bodySubType, bodyID, bodyDescription,
-                                bodyEncoding, partLength,
-                                fServerConnection.GetPreferPlainText());
+    nsIMAPBodypartMessage *message = new nsIMAPBodypartMessage(
+        partNum, parentPart, false, bodyType, bodySubType, bodyID,
+        bodyDescription, bodyEncoding, partLength,
+        fServerConnection.GetPreferPlainText());
 
-    // there are three additional fields: envelope structure, bodystructure, and size in lines
-    // historical note: this code was originally in nsIMAPBodypartMessage::ParseIntoObjects()
+    // there are three additional fields: envelope structure, bodystructure, and
+    // size in lines historical note: this code was originally in
+    // nsIMAPBodypartMessage::ParseIntoObjects()
 
     // envelope (ignored)
-    if (*fNextToken == '(')
-    {
+    if (*fNextToken == '(') {
       fNextToken++;
       skip_to_close_paren();
-    }
-    else
+    } else
       isValid = false;
 
     // bodystructure
-    if (isValid && ContinueParse())
-    {
+    if (isValid && ContinueParse()) {
       if (*fNextToken != '(')
         isValid = false;
-      else
-      {
+      else {
         char *bodyPartNum = PR_smprintf("%s.1", partNum);
-        if (bodyPartNum)
-        {
+        if (bodyPartNum) {
           nsIMAPBodypart *body = bodystructure_part(bodyPartNum, message);
           if (body)
             message->SetBody(body);
           else
             isValid = false;
         }
       }
     }
@@ -2927,551 +2494,480 @@ nsImapServerResponseParser::bodystructur
     if (isValid && ContinueParse()) {
       skip_to_close_paren();
       return message;
     }
     delete message;
   }
 
   // parsing failed, just move to the end of the parentheses group
-  if (ContinueParse())
-    skip_to_close_paren();
+  if (ContinueParse()) skip_to_close_paren();
   return nullptr;
 }
 
-
 // RFC3501:  body-type-mpart = 1*body SP media-subtype
 //                             [SP body-ext-mpart]
-nsIMAPBodypart *
-nsImapServerResponseParser::bodystructure_multipart(char *partNum, nsIMAPBodypart *parentPart)
-{
-  nsIMAPBodypartMultipart *multipart = new nsIMAPBodypartMultipart(partNum, parentPart);
+nsIMAPBodypart *nsImapServerResponseParser::bodystructure_multipart(
+    char *partNum, nsIMAPBodypart *parentPart) {
+  nsIMAPBodypartMultipart *multipart =
+      new nsIMAPBodypartMultipart(partNum, parentPart);
   bool isValid = multipart->GetIsValid();
-  // historical note: this code was originally in nsIMAPBodypartMultipart::ParseIntoObjects()
-  if (ContinueParse())
-  {
-    fNextToken++; // eat the first '('
+  // historical note: this code was originally in
+  // nsIMAPBodypartMultipart::ParseIntoObjects()
+  if (ContinueParse()) {
+    fNextToken++;  // eat the first '('
     // Parse list of children
     int childCount = 0;
-    while (isValid && fNextToken[0] == '(' && ContinueParse())
-    {
+    while (isValid && fNextToken[0] == '(' && ContinueParse()) {
       childCount++;
       char *childPartNum = NULL;
       // note: the multipart constructor does some magic on partNumber
-      if (PL_strcmp(multipart->GetPartNumberString(), "0")) // not top-level
-        childPartNum = PR_smprintf("%s.%d", multipart->GetPartNumberString(), childCount);
-      else // top-level
+      if (PL_strcmp(multipart->GetPartNumberString(), "0"))  // not top-level
+        childPartNum =
+            PR_smprintf("%s.%d", multipart->GetPartNumberString(), childCount);
+      else  // top-level
         childPartNum = PR_smprintf("%d", childCount);
       if (!childPartNum)
         isValid = false;
-      else
-      {
+      else {
         nsIMAPBodypart *child = bodystructure_part(childPartNum, multipart);
         if (child)
           multipart->AppendPart(child);
         else
           isValid = false;
       }
     }
 
     // RFC3501:  media-subtype   = string
     // (multipart subtype: mixed, alternative, etc.)
-    if (isValid && ContinueParse())
-    {
+    if (isValid && ContinueParse()) {
       char *bodySubType = CreateNilString();
       multipart->SetBodySubType(bodySubType);
-      if (ContinueParse())
-        AdvanceToNextToken();
+      if (ContinueParse()) AdvanceToNextToken();
     }
 
+    // clang-format off
     // extension data:
     // RFC3501:  body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
     //                            [SP body-fld-loc *(SP body-extension)]]]
 
     // body parameter parenthesized list (optional data), includes boundary parameter
     // RFC3501:  body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
+    // clang-format on
     char *boundaryData = nullptr;
-    if (isValid && ContinueParse() && *fNextToken == '(')
-    {
+    if (isValid && ContinueParse() && *fNextToken == '(') {
       fNextToken++;
-      while (ContinueParse() && *fNextToken != ')')
-      {
+      while (ContinueParse() && *fNextToken != ')') {
         char *attribute = CreateNilString();
-        if (ContinueParse())
-          AdvanceToNextToken();
-        if (ContinueParse() && !PL_strcasecmp(attribute, "BOUNDARY"))
-        {
+        if (ContinueParse()) AdvanceToNextToken();
+        if (ContinueParse() && !PL_strcasecmp(attribute, "BOUNDARY")) {
           char *boundary = CreateNilString();
-          if (boundary)
-            boundaryData = PR_smprintf("--%s", boundary);
+          if (boundary) boundaryData = PR_smprintf("--%s", boundary);
           PR_FREEIF(boundary);
-        }
-        else if (ContinueParse())
-        {
+        } else if (ContinueParse()) {
           char *value = CreateNilString();
           PR_FREEIF(value);
         }
         PR_FREEIF(attribute);
-        if (ContinueParse())
-          AdvanceToNextToken();
+        if (ContinueParse()) AdvanceToNextToken();
       }
-      if (ContinueParse())
-        fNextToken++;  // skip closing ')'
+      if (ContinueParse()) fNextToken++;  // skip closing ')'
     }
     if (boundaryData)
       multipart->SetBoundaryData(boundaryData);
     else
-      isValid = false;   // Actually, we should probably generate a boundary here.
+      isValid =
+          false;  // Actually, we should probably generate a boundary here.
   }
 
   // always move to closing ')', even if part was not successfully read
-  if (ContinueParse())
-    skip_to_close_paren();
+  if (ContinueParse()) skip_to_close_paren();
 
-  if (isValid)
-    return multipart;
+  if (isValid) return multipart;
   delete multipart;
   return nullptr;
 }
 
-
 // RFC2087:  quotaroot_response = "QUOTAROOT" SP astring *(SP astring)
 //           quota_response = "QUOTA" SP astring SP quota_list
 //           quota_list     = "(" [quota_resource *(SP quota_resource)] ")"
 //           quota_resource = atom SP number SP number
 // Only the STORAGE resource is considered.  The current implementation is
 // slightly broken because it assumes that STORAGE is the first resource;
 // a response   QUOTA (MESSAGE 5 100 STORAGE 10 512)   would be ignored.
-void nsImapServerResponseParser::quota_data()
-{
-  if (!PL_strcasecmp(fNextToken, "QUOTAROOT"))
-  {
+void nsImapServerResponseParser::quota_data() {
+  if (!PL_strcasecmp(fNextToken, "QUOTAROOT")) {
     // ignore QUOTAROOT response
     nsCString quotaroot;
     AdvanceToNextToken();
-    while (ContinueParse() && !fAtEndOfLine)
-    {
+    while (ContinueParse() && !fAtEndOfLine) {
       quotaroot.Adopt(CreateAstring());
       AdvanceToNextToken();
     }
-  }
-  else if(!PL_strcasecmp(fNextToken, "QUOTA"))
-  {
+  } else if (!PL_strcasecmp(fNextToken, "QUOTA")) {
     uint32_t used, max;
     char *parengroup;
 
     AdvanceToNextToken();
-    if (ContinueParse())
-    {
+    if (ContinueParse()) {
       nsCString quotaroot;
       quotaroot.Adopt(CreateAstring());
 
-      if(ContinueParse() && !fAtEndOfLine)
-      {
+      if (ContinueParse() && !fAtEndOfLine) {
         AdvanceToNextToken();
-        if(fNextToken)
-        {
-          if(!PL_strcasecmp(fNextToken, "(STORAGE"))
-          {
+        if (fNextToken) {
+          if (!PL_strcasecmp(fNextToken, "(STORAGE")) {
             parengroup = CreateParenGroup();
-            if(parengroup && (PR_sscanf(parengroup, "(STORAGE %lu %lu)", &used, &max) == 2) )
-            {
+            if (parengroup && (PR_sscanf(parengroup, "(STORAGE %lu %lu)", &used,
+                                         &max) == 2)) {
               fServerConnection.UpdateFolderQuotaData(quotaroot, used, max);
               skip_to_CRLF();
-            }
-            else
+            } else
               SetSyntaxError(true);
 
             PR_Free(parengroup);
-          }
-          else
+          } else
             // Ignore other limits, we just check STORAGE for now
             skip_to_CRLF();
-        }
-        else
+        } else
           SetSyntaxError(true);
-      }
-      else
+      } else
         HandleMemoryFailure();
     }
-  }
-  else
+  } else
     SetSyntaxError(true);
 }
 
-void nsImapServerResponseParser::id_data()
-{
+void nsImapServerResponseParser::id_data() {
   AdvanceToNextToken();
   if (!PL_strcasecmp(fNextToken, "NIL"))
     AdvanceToNextToken();
   else
     fServerIdResponse.Adopt(CreateParenGroup());
   skip_to_CRLF();
 }
 
-bool nsImapServerResponseParser::GetFillingInShell()
-{
+bool nsImapServerResponseParser::GetFillingInShell() {
   return (m_shell != nullptr);
 }
 
-bool nsImapServerResponseParser::GetDownloadingHeaders()
-{
+bool nsImapServerResponseParser::GetDownloadingHeaders() {
   return fDownloadingHeaders;
 }
 
 // Tells the server state parser to use a previously cached shell.
-void nsImapServerResponseParser::UseCachedShell(nsIMAPBodyShell *cachedShell)
-{
+void nsImapServerResponseParser::UseCachedShell(nsIMAPBodyShell *cachedShell) {
   // We shouldn't already have another shell we're dealing with.
-  if (m_shell && cachedShell)
-  {
+  if (m_shell && cachedShell) {
     MOZ_LOG(IMAP, mozilla::LogLevel::Info, ("PARSER: Shell Collision"));
     NS_ASSERTION(false, "shell collision");
   }
   m_shell = cachedShell;
 }
 
-
-void nsImapServerResponseParser::ResetCapabilityFlag()
-{
-}
+void nsImapServerResponseParser::ResetCapabilityFlag() {}
 
 /*
  literal         ::= "{" number "}" CRLF *CHAR8
                               ;; Number represents the number of CHAR8 octets
 */
 // returns true if this is the last chunk and we should close the stream
-bool nsImapServerResponseParser::msg_fetch_literal(bool chunk, int32_t origin)
-{
+bool nsImapServerResponseParser::msg_fetch_literal(bool chunk, int32_t origin) {
   numberOfCharsInThisChunk = atoi(fNextToken + 1);
   // If we didn't request a specific size, or the server isn't returning exactly
   // as many octets as we requested, this must be the last or only chunk
-  bool lastChunk = (!chunk ||
-                    (numberOfCharsInThisChunk != fServerConnection.GetCurFetchSize()));
+  bool lastChunk = (!chunk || (numberOfCharsInThisChunk !=
+                               fServerConnection.GetCurFetchSize()));
 
 #ifdef DEBUG
   if (lastChunk)
+    // clang-format off
     MOZ_LOG(IMAP, mozilla::LogLevel::Debug,
-                  ("PARSER: fetch_literal chunk = %d, requested %d, receiving %d",
-                    chunk, fServerConnection.GetCurFetchSize(),
-                    numberOfCharsInThisChunk));
+            ("PARSER: fetch_literal chunk = %d, requested %d, receiving %d", chunk,
+             fServerConnection.GetCurFetchSize(), numberOfCharsInThisChunk));
+    // clang-format on
 #endif
 
   charsReadSoFar = 0;
 
-  while (ContinueParse() && !fServerConnection.DeathSignalReceived() && (charsReadSoFar < numberOfCharsInThisChunk))
-  {
+  while (ContinueParse() && !fServerConnection.DeathSignalReceived() &&
+         (charsReadSoFar < numberOfCharsInThisChunk)) {
     AdvanceToNextLine();
-    if (ContinueParse())
-    {
-      // When "\r\n" (CRLF) is split across two chunks, the '\n' at the beginning of
-      // the next chunk might be set to an empty line consisting only of "\r\n".
-      // This is observed while running unit tests with the imap "fake" server.
-      // The unexpected '\r' is discarded here. However, with several real world
-      // servers tested, e.g., Dovecot, Gmail, Outlook, Yahoo etc., the leading
+    if (ContinueParse()) {
+      // When "\r\n" (CRLF) is split across two chunks, the '\n' at the
+      // beginning of the next chunk might be set to an empty line consisting
+      // only of "\r\n". This is observed while running unit tests with the imap
+      // "fake" server. The unexpected '\r' is discarded here. However, with
+      // several real world servers tested, e.g., Dovecot, Gmail, Outlook, Yahoo
+      // etc., the leading
       // '\r' is not inserted so the beginning line of the next chunk remains
       // just '\n' and no discard is required.
       // In any case, this "orphan" line is ignored and not processed below.
-      if (fNextChunkStartsWithNewline && (*fCurrentLine == '\r'))
-      {
+      if (fNextChunkStartsWithNewline && (*fCurrentLine == '\r')) {
         // Cause fCurrentLine to point to '\n' which discards the '\r'.
         char *usableCurrentLine = PL_strdup(fCurrentLine + 1);
         PR_Free(fCurrentLine);
         fCurrentLine = usableCurrentLine;
       }
 
-      // strlen() *would* fail on data containing \0, but the above AdvanceToNextLine() in
-      // nsMsgLineStreamBuffer::ReadNextLine() we replace '\0' with ' ' (blank) because
-      // who cares about binary transparency, and anyway \0 in this context violates RFCs.
+      // strlen() *would* fail on data containing \0, but the above
+      // AdvanceToNextLine() in nsMsgLineStreamBuffer::ReadNextLine() we replace
+      // '\0' with ' ' (blank) because who cares about binary transparency, and
+      // anyway \0 in this context violates RFCs.
       charsReadSoFar += strlen(fCurrentLine);
-      if (!fDownloadingHeaders && fCurrentCommandIsSingleMessageFetch)
-      {
-        fServerConnection.ProgressEventFunctionUsingName("imapDownloadingMessage");
+      if (!fDownloadingHeaders && fCurrentCommandIsSingleMessageFetch) {
+        fServerConnection.ProgressEventFunctionUsingName(
+            "imapDownloadingMessage");
         if (fTotalDownloadSize > 0)
-          fServerConnection.PercentProgressUpdateEvent(0, charsReadSoFar + origin, fTotalDownloadSize);
+          fServerConnection.PercentProgressUpdateEvent(
+              0, charsReadSoFar + origin, fTotalDownloadSize);
       }
-      if (charsReadSoFar > numberOfCharsInThisChunk)
-      {
-        // This is the last line of a chunk. "Literal" here means actual email data and
-        // its EOLs, without imap protocol elements and their EOLs. End of line is
-        // defined by two characters \r\n (i.e., CRLF, 0xd,0xa) specified by RFC822.
-        // Here is an example the most typical last good line of a chunk:
-        // "1s8AA5i4AAvF4QAG6+sAAD0bAPsAAAAA1OAAC)\r\n", where ")\r\n" are non-literals.
-        // This an example of the last "good" line of a chunk that terminates with \r\n
+      if (charsReadSoFar > numberOfCharsInThisChunk) {
+        // This is the last line of a chunk. "Literal" here means actual email
+        // data and its EOLs, without imap protocol elements and their EOLs. End
+        // of line is defined by two characters \r\n (i.e., CRLF, 0xd,0xa)
+        // specified by RFC822. Here is an example the most typical last good
+        // line of a chunk: "1s8AA5i4AAvF4QAG6+sAAD0bAPsAAAAA1OAAC)\r\n", where
+        // ")\r\n" are non-literals. This an example of the last "good" line of
+        // a chunk that terminates with \r\n
         // "FxcA/wAAAALN2gADu80ACS0nAPpVVAD1wNAABF5YAPhAJgD31+QABAAAAP8oMQD+HBwA/umj\r\n"
         // followed by another line of non-literal data:
-        // " UID 1004)\r\n". These two are concatenated into a single string pointed to
-        // by fCurrentLine.  The extra "non-literal data" on the last chunk line makes
-        // the charsReadSoFar greater than numberOfCharsInThisChunk (the configured
-        // chunk size).
-        // A problem occurs if the \r\n of the long line above is split between
-        // chunks and \n is contained in the next chunk. For example, if last
-        // lines of chunk X are:
+        // " UID 1004)\r\n". These two are concatenated into a single string
+        // pointed to by fCurrentLine.  The extra "non-literal data" on the last
+        // chunk line makes the charsReadSoFar greater than
+        // numberOfCharsInThisChunk (the configured chunk size). A problem
+        // occurs if the \r\n of the long line above is split between chunks and
+        // \n is contained in the next chunk. For example, if last lines of
+        // chunk X are:
         // "/gAOC/wA/QAAAAAAAAAA8wACCvz+AgIEAAD8/P4ABQUAAPoAAAD+AAEA/voHAAQGBQD/BAQA\r"
         // ")\r\n"
         // and the first two lines of chunk X+1 are:
         // "\n"
         // "APwAAAAAmZkA/wAAAAAREQD/AAAAAquVAAbk8QAHCBAAAPD0AAP5+wABRCoA+0BgAP0AAAAA\r\n"
-        // The missing '\n' on the last line of chunk X must be added back and the
-        // line consisting only of "\n" in chunk X+1 must be ignored in order to
-        // produce the the correct output. This is needed to insure that the signature
-        // verification of cryptographically signed emails does not fail due to missing
-        // or extra EOL characters. Otherwise, the extra or missing \n or \r  doesn't
-        // really matter.
+        // The missing '\n' on the last line of chunk X must be added back and
+        // the line consisting only of "\n" in chunk X+1 must be ignored in
+        // order to produce the the correct output. This is needed to insure
+        // that the signature verification of cryptographically signed emails
+        // does not fail due to missing or extra EOL characters. Otherwise, the
+        // extra or missing \n or \r  doesn't really matter.
         //
         // Special case observed only with the "fake" imap server used with TB
-        // unit test.  When the "\r\n" at the end of a chunk is split as described
-        // above, the \n at the beginning of the next chunk may actually be "\r\n"
-        // like this example:
-        // Last lines of chunk X
+        // unit test.  When the "\r\n" at the end of a chunk is split as
+        // described above, the \n at the beginning of the next chunk may
+        // actually be "\r\n" like this example: Last lines of chunk X
         // "/gAOC/wA/QAAAAAAAAAA8wACCvz+AgIEAAD8/P4ABQUAAPoAAAD+AAEA/voHAAQGBQD/BAQA\r"
         // ")\r\n"
         // and the first two lines of chunk X+1:
         // "\r\n"   <-- The code changes this to just "\n" like it should be.
         // "APwAAAAAmZkA/wAAAAAREQD/AAAAAquVAAbk8QAHCBAAAPD0AAP5+wABRCoA+0BgAP0AAAAA\r\n"
         //
         // Implementation:
-        // Obtain pointer to last literal in chunk X, e.g., 'C' in 1st example above,
-        // or to the \n or \r in the other examples.
+        // Obtain pointer to last literal in chunk X, e.g., 'C' in 1st example
+        // above, or to the \n or \r in the other examples.
         char *displayEndOfLine =
-          (fCurrentLine + strlen(fCurrentLine) - (charsReadSoFar - numberOfCharsInThisChunk + 1));
+            (fCurrentLine + strlen(fCurrentLine) -
+             (charsReadSoFar - numberOfCharsInThisChunk + 1));
         // Save so original unmodified fCurrentLine is restored below.
         char saveit1 = displayEndOfLine[1];
         char saveit2 = 0;  // Keep compiler happy.
         // Determine if EOL is split such that Chunk X has the \r and chunk
         // X+1 has the \n.
         fNextChunkStartsWithNewline = (displayEndOfLine[0] == '\r');
-        if (fNextChunkStartsWithNewline)
-        {
+        if (fNextChunkStartsWithNewline) {
           saveit2 = displayEndOfLine[2];
           // Add the missing newline and terminate the string.
           displayEndOfLine[1] = '\n';
           displayEndOfLine[2] = 0;
           // This is a good thing to log.
-          MOZ_LOG(IMAP, mozilla::LogLevel::Info, ("PARSER: CR/LF split at chunk boundary"));
-        }
-        else
-        {
+          MOZ_LOG(IMAP, mozilla::LogLevel::Info,
+                  ("PARSER: CR/LF split at chunk boundary"));
+        } else {
           // Typical case where EOLs are not split. Terminate the string.
           displayEndOfLine[1] = 0;
         }
         // Process this modified string pointed to by fCurrentLine.
         fServerConnection.HandleMessageDownLoadLine(fCurrentLine, !lastChunk);
         // Restore fCurrentLine's original content.
         displayEndOfLine[1] = saveit1;
-        if (fNextChunkStartsWithNewline)
-          displayEndOfLine[2] = saveit2;
-      }
-      else
-      {
+        if (fNextChunkStartsWithNewline) displayEndOfLine[2] = saveit2;
+      } else {
         // Not the last line of a chunk.
-        if (!fNextChunkStartsWithNewline)
-        {
+        if (!fNextChunkStartsWithNewline) {
           // Process unmodified fCurrentLine string.
-          fServerConnection.HandleMessageDownLoadLine(fCurrentLine,
-            !lastChunk && (charsReadSoFar == numberOfCharsInThisChunk),
-            fCurrentLine);
-        }
-        else
-        {
+          fServerConnection.HandleMessageDownLoadLine(
+              fCurrentLine,
+              !lastChunk && (charsReadSoFar == numberOfCharsInThisChunk),
+              fCurrentLine);
+        } else {
           // Ignore the orphan '\n' on a line by itself.
           MOZ_ASSERT(strlen(fCurrentLine) == 1 && fCurrentLine[0] == '\n',
                      "Expect '\\n' as only character in this line");
           fNextChunkStartsWithNewline = false;
         }
       }
     }
   }
 
-  if (ContinueParse())
-  {
-    if (charsReadSoFar > numberOfCharsInThisChunk)
-    {
-      // move the lexical analyzer state to the end of this message because this message
-      // fetch ends in the middle of this line.
-      AdvanceTokenizerStartingPoint(strlen(fCurrentLine) - (charsReadSoFar - numberOfCharsInThisChunk));
+  if (ContinueParse()) {
+    if (charsReadSoFar > numberOfCharsInThisChunk) {
+      // move the lexical analyzer state to the end of this message because this
+      // message fetch ends in the middle of this line.
+      AdvanceTokenizerStartingPoint(
+          strlen(fCurrentLine) - (charsReadSoFar - numberOfCharsInThisChunk));
       AdvanceToNextToken();
-    }
-    else
-    {
+    } else {
       skip_to_CRLF();
       AdvanceToNextToken();
     }
-  }
-  else
-  {
+  } else {
     fNextChunkStartsWithNewline = false;
   }
   return lastChunk;
 }
 
-bool nsImapServerResponseParser::CurrentFolderReadOnly()
-{
+bool nsImapServerResponseParser::CurrentFolderReadOnly() {
   return fCurrentFolderReadOnly;
 }
 
-int32_t nsImapServerResponseParser::NumberOfMessages()
-{
+int32_t nsImapServerResponseParser::NumberOfMessages() {
   return fNumberOfExistingMessages;
 }
 
-int32_t nsImapServerResponseParser::NumberOfRecentMessages()
-{
+int32_t nsImapServerResponseParser::NumberOfRecentMessages() {
   return fNumberOfRecentMessages;
 }
 
-int32_t nsImapServerResponseParser::NumberOfUnseenMessages()
-{
+int32_t nsImapServerResponseParser::NumberOfUnseenMessages() {
   return fNumberOfUnseenMessages;
 }
 
-int32_t nsImapServerResponseParser::FolderUID()
-{
-  return fFolderUIDValidity;
+int32_t nsImapServerResponseParser::FolderUID() { return fFolderUIDValidity; }
+
+void nsImapServerResponseParser::SetCurrentResponseUID(uint32_t uid) {
+  if (uid > 0) fCurrentResponseUID = uid;
 }
 
-void nsImapServerResponseParser::SetCurrentResponseUID(uint32_t uid)
-{
-  if (uid > 0)
-    fCurrentResponseUID = uid;
-}
-
-uint32_t nsImapServerResponseParser::CurrentResponseUID()
-{
+uint32_t nsImapServerResponseParser::CurrentResponseUID() {
   return fCurrentResponseUID;
 }
 
-uint32_t nsImapServerResponseParser::HighestRecordedUID()
-{
+uint32_t nsImapServerResponseParser::HighestRecordedUID() {
   return fHighestRecordedUID;
 }
 
-void nsImapServerResponseParser::ResetHighestRecordedUID()
-{
+void nsImapServerResponseParser::ResetHighestRecordedUID() {
   fHighestRecordedUID = 0;
 }
 
-bool nsImapServerResponseParser::IsNumericString(const char *string)
-{
+bool nsImapServerResponseParser::IsNumericString(const char *string) {
   int i;
-  for(i = 0; i < (int) PL_strlen(string); i++)
-  {
-    if (! isdigit(string[i]))
-    {
+  for (i = 0; i < (int)PL_strlen(string); i++) {
+    if (!isdigit(string[i])) {
       return false;
     }
   }
 
   return true;
 }
 
-
 already_AddRefed<nsImapMailboxSpec>
-nsImapServerResponseParser::CreateCurrentMailboxSpec(const char *mailboxName /* = nullptr */)
-{
+nsImapServerResponseParser::CreateCurrentMailboxSpec(
+    const char *mailboxName /* = nullptr */) {
   RefPtr<nsImapMailboxSpec> returnSpec = new nsImapMailboxSpec;
-  const char *mailboxNameToConvert = (mailboxName) ? mailboxName : fSelectedMailboxName;
-  if (mailboxNameToConvert)
-  {
+  const char *mailboxNameToConvert =
+      (mailboxName) ? mailboxName : fSelectedMailboxName;
+  if (mailboxNameToConvert) {
     const char *serverKey = fServerConnection.GetImapServerKey();
     nsIMAPNamespace *ns = nullptr;
     if (serverKey && fHostSessionList)
-      fHostSessionList->GetNamespaceForMailboxForHost(serverKey, mailboxNameToConvert, ns);  // for
-      // delimiter
-    returnSpec->mHierarchySeparator = (ns) ? ns->GetDelimiter(): '/';
-
+      fHostSessionList->GetNamespaceForMailboxForHost(
+          serverKey, mailboxNameToConvert, ns);  // for
+    // delimiter
+    returnSpec->mHierarchySeparator = (ns) ? ns->GetDelimiter() : '/';
   }
 
-  returnSpec->mFolderSelected = !mailboxName; // if mailboxName is null, we're doing a Status
+  returnSpec->mFolderSelected =
+      !mailboxName;  // if mailboxName is null, we're doing a Status
   returnSpec->mFolder_UIDVALIDITY = fFolderUIDValidity;
   returnSpec->mHighestModSeq = fHighestModSeq;
-  returnSpec->mNumOfMessages = (mailboxName) ? fStatusExistingMessages : fNumberOfExistingMessages;
-  returnSpec->mNumOfUnseenMessages = (mailboxName) ? fStatusUnseenMessages : fNumberOfUnseenMessages;
-  returnSpec->mNumOfRecentMessages = (mailboxName) ? fStatusRecentMessages : fNumberOfRecentMessages;
+  returnSpec->mNumOfMessages =
+      (mailboxName) ? fStatusExistingMessages : fNumberOfExistingMessages;
+  returnSpec->mNumOfUnseenMessages =
+      (mailboxName) ? fStatusUnseenMessages : fNumberOfUnseenMessages;
+  returnSpec->mNumOfRecentMessages =
+      (mailboxName) ? fStatusRecentMessages : fNumberOfRecentMessages;
   returnSpec->mNextUID = fStatusNextUID;
 
   returnSpec->mSupportedUserFlags = fSupportsUserDefinedFlags;
 
   returnSpec->mBoxFlags = kNoFlags;  // stub
-  returnSpec->mOnlineVerified = false;  // we're fabricating this.  The flags aren't verified.
+  returnSpec->mOnlineVerified =
+      false;  // we're fabricating this.  The flags aren't verified.
   returnSpec->mAllocatedPathName.Assign(mailboxNameToConvert);
   returnSpec->mConnection = &fServerConnection;
-  if (returnSpec->mConnection)
-  {
-    nsIURI * aUrl = nullptr;
+  if (returnSpec->mConnection) {
+    nsIURI *aUrl = nullptr;
     nsresult rv = NS_OK;
-    returnSpec->mConnection->GetCurrentUrl()->QueryInterface(NS_GET_IID(nsIURI), (void **) &aUrl);
-    if (NS_SUCCEEDED(rv) && aUrl)
-      aUrl->GetHost(returnSpec->mHostName);
+    returnSpec->mConnection->GetCurrentUrl()->QueryInterface(NS_GET_IID(nsIURI),
+                                                             (void **)&aUrl);
+    if (NS_SUCCEEDED(rv) && aUrl) aUrl->GetHost(returnSpec->mHostName);
 
     NS_IF_RELEASE(aUrl);
-  }
-  else
+  } else
     returnSpec->mHostName.Truncate();
 
   if (fFlagState)
-    returnSpec->mFlagState = fFlagState; //copies flag state
+    returnSpec->mFlagState = fFlagState;  // copies flag state
   else
     returnSpec->mFlagState = nullptr;
 
   return returnSpec.forget();
-
 }
 // Reset the flag state.
-void nsImapServerResponseParser::ResetFlagInfo()
-{
-  if (fFlagState)
-    fFlagState->Reset();
+void nsImapServerResponseParser::ResetFlagInfo() {
+  if (fFlagState) fFlagState->Reset();
 }
 
-
-bool nsImapServerResponseParser::GetLastFetchChunkReceived()
-{
+bool nsImapServerResponseParser::GetLastFetchChunkReceived() {
   return fLastChunk;
 }
 
-void nsImapServerResponseParser::ClearLastFetchChunkReceived()
-{
+void nsImapServerResponseParser::ClearLastFetchChunkReceived() {
   fLastChunk = false;
 }
 
-void nsImapServerResponseParser::SetHostSessionList(nsIImapHostSessionList*
-                                               aHostSessionList)
-{
-    fHostSessionList = aHostSessionList;
+void nsImapServerResponseParser::SetHostSessionList(
+    nsIImapHostSessionList *aHostSessionList) {
+  fHostSessionList = aHostSessionList;
 }
 
-void nsImapServerResponseParser::SetSyntaxError(bool error, const char *msg)
-{
+void nsImapServerResponseParser::SetSyntaxError(bool error, const char *msg) {
   nsIMAPGenericParser::SetSyntaxError(error, msg);
-  if (error)
-  {
-    if (!fCurrentLine)
-    {
+  if (error) {
+    if (!fCurrentLine) {
       HandleMemoryFailure();
-      fServerConnection.Log("PARSER", ("Internal Syntax Error: %s: <no line>"), msg);
-    }
-    else
-    {
+      fServerConnection.Log("PARSER", ("Internal Syntax Error: %s: <no line>"),
+                            msg);
+    } else {
       if (!strcmp(fCurrentLine, CRLF))
-        fServerConnection.Log("PARSER", "Internal Syntax Error: %s: <CRLF>", msg);
-      else
-      {
+        fServerConnection.Log("PARSER", "Internal Syntax Error: %s: <CRLF>",
+                              msg);
+      else {
         if (msg)
           fServerConnection.Log("PARSER", "Internal Syntax Error: %s:", msg);
-        fServerConnection.Log("PARSER", "Internal Syntax Error on line: %s", fCurrentLine);
+        fServerConnection.Log("PARSER", "Internal Syntax Error on line: %s",
+                              fCurrentLine);
       }
     }
   }
 }
 
-nsresult nsImapServerResponseParser::BeginMessageDownload(const char *content_type)
-{
+nsresult nsImapServerResponseParser::BeginMessageDownload(
+    const char *content_type) {
   nsresult rv = fServerConnection.BeginMessageDownLoad(fSizeOfMostRecentMessage,
-    content_type);
-  if (NS_FAILED(rv))
-  {
+                                                       content_type);
+  if (NS_FAILED(rv)) {
     skip_to_CRLF();
     fServerConnection.PseudoInterrupt(true);
     fServerConnection.AbortMessageDownLoad();
   }
   return rv;
 }
--- a/mailnews/imap/src/nsImapServerResponseParser.h
+++ b/mailnews/imap/src/nsImapServerResponseParser.h
@@ -17,242 +17,256 @@
 
 class nsIMAPBodyShell;
 class nsIMAPBodypart;
 class nsImapSearchResultIterator;
 class nsIImapFlagAndUidState;
 
 #include "nsIMAPGenericParser.h"
 
-class nsImapServerResponseParser : public nsIMAPGenericParser
-{
-public:
+class nsImapServerResponseParser : public nsIMAPGenericParser {
+ public:
   explicit nsImapServerResponseParser(nsImapProtocol &imapConnection);
   virtual ~nsImapServerResponseParser();
 
   // Overridden from the base parser class
-  virtual bool       LastCommandSuccessful() override;
+  virtual bool LastCommandSuccessful() override;
   virtual void HandleMemoryFailure() override;
 
-  // aignoreBadAndNOResponses --> don't throw a error dialog if this command results in a NO or Bad response
-  // from the server..in other words the command is "exploratory" and we don't really care if it succeeds or fails.
-  // This value is typically FALSE for almost all cases.
+  // aignoreBadAndNOResponses --> don't throw a error dialog if this command
+  // results in a NO or Bad response from the server..in other words the command
+  // is "exploratory" and we don't really care if it succeeds or fails. This
+  // value is typically FALSE for almost all cases.
   virtual void ParseIMAPServerResponse(const char *aCurrentCommand,
                                        bool aIgnoreBadAndNOResponses,
                                        char *aGreetingWithCapability = NULL);
   virtual void InitializeState();
-  bool    CommandFailed();
-  void    SetCommandFailed(bool failed);
+  bool CommandFailed();
+  void SetCommandFailed(bool failed);
 
-    enum eIMAPstate {
-        kNonAuthenticated,
-        kAuthenticated,
-        kFolderSelected
-    } ;
+  enum eIMAPstate { kNonAuthenticated, kAuthenticated, kFolderSelected };
 
   virtual eIMAPstate GetIMAPstate();
-  virtual bool WaitingForMoreClientInput() { return fWaitingForMoreClientInput; }
-  const char *GetSelectedMailboxName();   // can be NULL
+  virtual bool WaitingForMoreClientInput() {
+    return fWaitingForMoreClientInput;
+  }
+  const char *GetSelectedMailboxName();  // can be NULL
   bool IsStdJunkNotJunkUseOk() { return fStdJunkNotJunkUseOk; }
 
-  // if we get a PREAUTH greeting from the server, initialize the parser to begin in
-  // the kAuthenticated state
+  // if we get a PREAUTH greeting from the server, initialize the parser to
+  // begin in the kAuthenticated state
   void PreauthSetAuthenticatedState();
 
   // these functions represent the state of the currently selected
   // folder
-  bool       CurrentFolderReadOnly();
-  int32_t    NumberOfMessages();
-  int32_t    NumberOfRecentMessages();
-  int32_t    NumberOfUnseenMessages();
-  int32_t    FolderUID();
-  uint32_t   CurrentResponseUID();
-  uint32_t   HighestRecordedUID();
-  void       ResetHighestRecordedUID();
-  void       SetCurrentResponseUID(uint32_t uid);
-  bool       IsNumericString(const char *string);
-  uint32_t   SizeOfMostRecentMessage();
-  void       SetTotalDownloadSize(int32_t newSize) { fTotalDownloadSize = newSize; }
+  bool CurrentFolderReadOnly();
+  int32_t NumberOfMessages();
+  int32_t NumberOfRecentMessages();
+  int32_t NumberOfUnseenMessages();
+  int32_t FolderUID();
+  uint32_t CurrentResponseUID();
+  uint32_t HighestRecordedUID();
+  void ResetHighestRecordedUID();
+  void SetCurrentResponseUID(uint32_t uid);
+  bool IsNumericString(const char *string);
+  uint32_t SizeOfMostRecentMessage();
+  void SetTotalDownloadSize(int32_t newSize) { fTotalDownloadSize = newSize; }
 
   nsImapSearchResultIterator *CreateSearchResultIterator();
-  void ResetSearchResultSequence() {fSearchResults->ResetSequence();}
+  void ResetSearchResultSequence() { fSearchResults->ResetSequence(); }
 
   // create a struct mailbox_spec from our info, used in
   // libmsg c interface
-  already_AddRefed<nsImapMailboxSpec> CreateCurrentMailboxSpec(const char *mailboxName = nullptr);
+  already_AddRefed<nsImapMailboxSpec> CreateCurrentMailboxSpec(
+      const char *mailboxName = nullptr);
 
   // Resets the flags state.
   void ResetFlagInfo();
 
   // set this to false if you don't want to alert the user to server
   // error messages
-  void SetReportingErrors(bool reportThem) { fReportingErrors=reportThem;}
+  void SetReportingErrors(bool reportThem) { fReportingErrors = reportThem; }
   bool GetReportingErrors() { return fReportingErrors; }
 
   eIMAPCapabilityFlags GetCapabilityFlag() { return fCapabilityFlag; }
-  void   SetCapabilityFlag(eIMAPCapabilityFlags capability) {fCapabilityFlag = capability;}
-  bool ServerHasIMAP4Rev1Capability() { return ((fCapabilityFlag & kIMAP4rev1Capability) != 0); }
-  bool ServerHasACLCapability() { return ((fCapabilityFlag & kACLCapability) != 0); }
-  bool ServerHasNamespaceCapability() { return ((fCapabilityFlag & kNamespaceCapability) != 0); }
+  void SetCapabilityFlag(eIMAPCapabilityFlags capability) {
+    fCapabilityFlag = capability;
+  }
+  bool ServerHasIMAP4Rev1Capability() {
+    return ((fCapabilityFlag & kIMAP4rev1Capability) != 0);
+  }
+  bool ServerHasACLCapability() {
+    return ((fCapabilityFlag & kACLCapability) != 0);
+  }
+  bool ServerHasNamespaceCapability() {
+    return ((fCapabilityFlag & kNamespaceCapability) != 0);
+  }
   bool ServerIsNetscape3xServer() { return fServerIsNetscape3xServer; }
-  bool ServerHasServerInfo() {return ((fCapabilityFlag & kXServerInfoCapability) != 0); }
-  bool ServerIsAOLServer() {return ((fCapabilityFlag & kAOLImapCapability) != 0); }
-  void SetFetchingFlags(bool aFetchFlags) { fFetchingAllFlags = aFetchFlags;}
-  void ResetCapabilityFlag() ;
+  bool ServerHasServerInfo() {
+    return ((fCapabilityFlag & kXServerInfoCapability) != 0);
+  }
+  bool ServerIsAOLServer() {
+    return ((fCapabilityFlag & kAOLImapCapability) != 0);
+  }
+  void SetFetchingFlags(bool aFetchFlags) { fFetchingAllFlags = aFetchFlags; }
+  void ResetCapabilityFlag();
 
-  nsCString& GetMailAccountUrl() { return fMailAccountUrl; }
+  nsCString &GetMailAccountUrl() { return fMailAccountUrl; }
   const char *GetXSenderInfo() { return fXSenderInfo; }
   void FreeXSenderInfo() { PR_FREEIF(fXSenderInfo); }
-  nsCString& GetManageListsUrl() { return fManageListsUrl; }
-  nsCString& GetManageFiltersUrl() {return fManageFiltersUrl;}
-  const char *GetManageFolderUrl() {return fFolderAdminUrl;}
-  nsCString &GetServerID() {return fServerIdResponse;}
+  nsCString &GetManageListsUrl() { return fManageListsUrl; }
+  nsCString &GetManageFiltersUrl() { return fManageFiltersUrl; }
+  const char *GetManageFolderUrl() { return fFolderAdminUrl; }
+  nsCString &GetServerID() { return fServerIdResponse; }
 
   // Call this when adding a pipelined command to the session
   void IncrementNumberOfTaggedResponsesExpected(const char *newExpectedTag);
 
   // Interrupt a Fetch, without really Interrupting (through netlib)
   bool GetLastFetchChunkReceived();
   void ClearLastFetchChunkReceived();
   virtual uint16_t SupportsUserFlags() { return fSupportsUserDefinedFlags; }
-  virtual uint16_t  SettablePermanentFlags() { return fSettablePermanentFlags;}
+  virtual uint16_t SettablePermanentFlags() { return fSettablePermanentFlags; }
   void SetFlagState(nsIImapFlagAndUidState *state);
   bool GetDownloadingHeaders();
   bool GetFillingInShell();
   void UseCachedShell(nsIMAPBodyShell *cachedShell);
   void SetHostSessionList(nsIImapHostSessionList *aHostSession);
-  char  *fAuthChallenge;    // the challenge returned by the server in
-                            //response to authenticate using CRAM-MD5 or NTLM
-  bool            fCondStoreEnabled;
-  bool            fUseModSeq;  // can use mod seq for currently selected folder
-  uint64_t        fHighestModSeq;
+  char *fAuthChallenge;  // the challenge returned by the server in
+                         // response to authenticate using CRAM-MD5 or NTLM
+  bool fCondStoreEnabled;
+  bool fUseModSeq;  // can use mod seq for currently selected folder
+  uint64_t fHighestModSeq;
 
-protected:
-  virtual void    flags();
-  virtual void    envelope_data();
-  virtual void    xaolenvelope_data();
-  virtual void    parse_address(nsAutoCString &addressLine);
-  virtual void    internal_date();
+ protected:
+  virtual void flags();
+  virtual void envelope_data();
+  virtual void xaolenvelope_data();
+  virtual void parse_address(nsAutoCString &addressLine);
+  virtual void internal_date();
   virtual nsresult BeginMessageDownload(const char *content_type);
 
-  virtual void    response_data();
-  virtual void    resp_text();
-  virtual void    resp_cond_state(bool isTagged);
-  virtual void    text_mime2();
-  virtual void    text();
-  virtual void    parse_folder_flags(bool calledForFlags);
-  virtual void    enable_data();
-  virtual void    language_data();
-  virtual void    authChallengeResponse_data();
-  virtual void    resp_text_code();
-  virtual void    response_done();
-  virtual void    response_tagged();
-  virtual void    response_fatal();
-  virtual void    resp_cond_bye();
-  virtual void    id_data();
-  virtual void    mailbox_data();
-  virtual void    numeric_mailbox_data();
-  virtual void    capability_data();
-  virtual void    xserverinfo_data();
-  virtual void    xmailboxinfo_data();
-  virtual void    namespace_data();
-  virtual void    myrights_data(bool unsolicited);
-  virtual void    acl_data();
-  virtual void    bodystructure_data();
-  nsIMAPBodypart  *bodystructure_part(char *partNum, nsIMAPBodypart *parentPart);
-  nsIMAPBodypart  *bodystructure_leaf(char *partNum, nsIMAPBodypart *parentPart);
-  nsIMAPBodypart  *bodystructure_multipart(char *partNum, nsIMAPBodypart *parentPart);
-  virtual void    mime_data();
-  virtual void    mime_part_data();
-  virtual void    mime_header_data();
-  virtual void    quota_data();
-  virtual void    msg_fetch();
-  virtual void    msg_obsolete();
-  virtual void    msg_fetch_headers(const char *partNum);
-  virtual void    msg_fetch_content(bool chunk, int32_t origin, const char *content_type);
-  virtual bool    msg_fetch_quoted();
-  virtual bool    msg_fetch_literal(bool chunk, int32_t origin);
-  virtual void    mailbox_list(bool discoveredFromLsub);
-  virtual void    mailbox(nsImapMailboxSpec *boxSpec);
+  virtual void response_data();
+  virtual void resp_text();
+  virtual void resp_cond_state(bool isTagged);
+  virtual void text_mime2();
+  virtual void text();
+  virtual void parse_folder_flags(bool calledForFlags);
+  virtual void enable_data();
+  virtual void language_data();
+  virtual void authChallengeResponse_data();
+  virtual void resp_text_code();
+  virtual void response_done();
+  virtual void response_tagged();
+  virtual void response_fatal();
+  virtual void resp_cond_bye();
+  virtual void id_data();
+  virtual void mailbox_data();
+  virtual void numeric_mailbox_data();
+  virtual void capability_data();
+  virtual void xserverinfo_data();
+  virtual void xmailboxinfo_data();
+  virtual void namespace_data();
+  virtual void myrights_data(bool unsolicited);
+  virtual void acl_data();
+  virtual void bodystructure_data();
+  nsIMAPBodypart *bodystructure_part(char *partNum, nsIMAPBodypart *parentPart);
+  nsIMAPBodypart *bodystructure_leaf(char *partNum, nsIMAPBodypart *parentPart);
+  nsIMAPBodypart *bodystructure_multipart(char *partNum,
+                                          nsIMAPBodypart *parentPart);
+  virtual void mime_data();
+  virtual void mime_part_data();
+  virtual void mime_header_data();
+  virtual void quota_data();
+  virtual void msg_fetch();
+  virtual void msg_obsolete();
+  virtual void msg_fetch_headers(const char *partNum);
+  virtual void msg_fetch_content(bool chunk, int32_t origin,
+                                 const char *content_type);
+  virtual bool msg_fetch_quoted();
+  virtual bool msg_fetch_literal(bool chunk, int32_t origin);
+  virtual void mailbox_list(bool discoveredFromLsub);
+  virtual void mailbox(nsImapMailboxSpec *boxSpec);
 
-  virtual void    ProcessOkCommand(const char *commandToken);
-  virtual void    ProcessBadCommand(const char *commandToken);
-  virtual void    PreProcessCommandToken(const char *commandToken,
-                                             const char *currentCommand);
-  virtual void    PostProcessEndOfLine();
+  virtual void ProcessOkCommand(const char *commandToken);
+  virtual void ProcessBadCommand(const char *commandToken);
+  virtual void PreProcessCommandToken(const char *commandToken,
+                                      const char *currentCommand);
+  virtual void PostProcessEndOfLine();
 
   // Overridden from the nsIMAPGenericParser, to retrieve the next line
   // from the open socket.
-  virtual bool    GetNextLineForParser(char **nextLine) override;
+  virtual bool GetNextLineForParser(char **nextLine) override;
   // overridden to do logging
-  virtual void    SetSyntaxError(bool error, const char *msg = nullptr) override;
+  virtual void SetSyntaxError(bool error, const char *msg = nullptr) override;
 
-private:
-  bool            fCurrentCommandFailed;
-  bool            fReportingErrors;
-
+ private:
+  bool fCurrentCommandFailed;
+  bool fReportingErrors;
 
-  bool            fCurrentFolderReadOnly;
-  bool            fCurrentLineContainedFlagInfo;
-  bool            fFetchingAllFlags;
-  bool            fWaitingForMoreClientInput;
+  bool fCurrentFolderReadOnly;
+  bool fCurrentLineContainedFlagInfo;
+  bool fFetchingAllFlags;
+  bool fWaitingForMoreClientInput;
   // Is the server a Netscape 3.x Messaging Server?
-  bool            fServerIsNetscape3xServer;
-  bool            fDownloadingHeaders;
-  bool            fCurrentCommandIsSingleMessageFetch;
-  bool            fGotPermanentFlags;
-  bool            fStdJunkNotJunkUseOk;
-  imapMessageFlagsType   fSavedFlagInfo;
+  bool fServerIsNetscape3xServer;
+  bool fDownloadingHeaders;
+  bool fCurrentCommandIsSingleMessageFetch;
+  bool fGotPermanentFlags;
+  bool fStdJunkNotJunkUseOk;
+  imapMessageFlagsType fSavedFlagInfo;
   nsTArray<nsCString> fCustomFlags;
 
-  uint16_t  fSupportsUserDefinedFlags;
-  uint16_t  fSettablePermanentFlags;
+  uint16_t fSupportsUserDefinedFlags;
+  uint16_t fSettablePermanentFlags;
 
-  int32_t           fFolderUIDValidity;
-  int32_t           fNumberOfUnseenMessages;
-  int32_t           fNumberOfExistingMessages;
-  int32_t           fNumberOfRecentMessages;
-  uint32_t          fCurrentResponseUID;
-  uint32_t          fHighestRecordedUID;
+  int32_t fFolderUIDValidity;
+  int32_t fNumberOfUnseenMessages;
+  int32_t fNumberOfExistingMessages;
+  int32_t fNumberOfRecentMessages;
+  uint32_t fCurrentResponseUID;
+  uint32_t fHighestRecordedUID;
   // used to handle server that sends msg size after headers
-  uint32_t          fReceivedHeaderOrSizeForUID;
-  int32_t           fSizeOfMostRecentMessage;
-  int32_t           fTotalDownloadSize;
+  uint32_t fReceivedHeaderOrSizeForUID;
+  int32_t fSizeOfMostRecentMessage;
+  int32_t fTotalDownloadSize;
 
-  int32_t           fStatusUnseenMessages;
-  int32_t           fStatusRecentMessages;
-  uint32_t          fStatusNextUID;
-  uint32_t          fStatusExistingMessages;
+  int32_t fStatusUnseenMessages;
+  int32_t fStatusRecentMessages;
+  uint32_t fStatusNextUID;
+  uint32_t fStatusExistingMessages;
 
-  int               fNumberOfTaggedResponsesExpected;
+  int fNumberOfTaggedResponsesExpected;
 
-  char              *fCurrentCommandTag;
+  char *fCurrentCommandTag;
 
-  nsCString         fZeroLengthMessageUidString;
+  nsCString fZeroLengthMessageUidString;
 
-  char              *fSelectedMailboxName;
+  char *fSelectedMailboxName;
 
-  nsImapSearchResultSequence    *fSearchResults;
+  nsImapSearchResultSequence *fSearchResults;
 
-  nsCOMPtr <nsIImapFlagAndUidState> fFlagState;  // NOT owned by us, it's a copy, do not destroy
+  nsCOMPtr<nsIImapFlagAndUidState>
+      fFlagState;  // NOT owned by us, it's a copy, do not destroy
 
-  eIMAPstate               fIMAPstate;
+  eIMAPstate fIMAPstate;
 
-  eIMAPCapabilityFlags      fCapabilityFlag;
-  nsCString     fMailAccountUrl;
-  char          *fNetscapeServerVersionString;
-  char          *fXSenderInfo; /* changed per message download */
-  char          *fLastAlert; /* used to avoid displaying the same alert over and over */
-  char          *fMsgID; /* MessageID for Gmail only (X-GM-MSGID) */
-  char          *fThreadID; /* ThreadID for Gmail only (X-GM-THRID) */
-  char          *fLabels; /* Labels for Gmail only (X-GM-LABELS) [will include parens, removed while passing to hashTable ]*/
-  nsCString     fManageListsUrl;
-  nsCString    fManageFiltersUrl;
-  char          *fFolderAdminUrl;
-  nsCString    fServerIdResponse; // RFC
+  eIMAPCapabilityFlags fCapabilityFlag;
+  nsCString fMailAccountUrl;
+  char *fNetscapeServerVersionString;
+  char *fXSenderInfo; /* changed per message download */
+  char *fLastAlert; /* used to avoid displaying the same alert over and over */
+  char *fMsgID;     /* MessageID for Gmail only (X-GM-MSGID) */
+  char *fThreadID;  /* ThreadID for Gmail only (X-GM-THRID) */
+  char *fLabels;    /* Labels for Gmail only (X-GM-LABELS) [will include parens,
+                       removed while passing to hashTable ]*/
+  nsCString fManageListsUrl;
+  nsCString fManageFiltersUrl;
+  char *fFolderAdminUrl;
+  nsCString fServerIdResponse;  // RFC
 
   int32_t fFetchResponseIndex;
 
   // used for aborting a fetch stream when we're pseudo-Interrupted
   int32_t numberOfCharsInThisChunk;
   int32_t charsReadSoFar;
   bool fLastChunk;
 
--- a/mailnews/imap/src/nsImapService.cpp
+++ b/mailnews/imap/src/nsImapService.cpp
@@ -1,14 +1,14 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "msgCore.h"    // precompiled header...
+#include "msgCore.h"  // precompiled header...
 #include "nsImapService.h"
 #include "nsMsgImapCID.h"
 #include "nsImapCore.h"
 #include "netCore.h"
 
 #include "nsImapUrl.h"
 #include "nsCOMPtr.h"
 #include "nsIMsgFolder.h"
@@ -60,259 +60,237 @@
 #include "nsNetUtil.h"
 #include "nsMsgMessageFlags.h"
 #include "nsIMsgPluggableStore.h"
 #include "../../base/src/MailnewsLoadContextInfo.h"
 #include "nsDocShellLoadState.h"
 #include "nsContentUtils.h"
 #include "mozilla/LoadInfo.h"
 
-#define PREF_MAIL_ROOT_IMAP "mail.root.imap"            // old - for backward compatibility only
 #define PREF_MAIL_ROOT_IMAP_REL "mail.root.imap-rel"
+// old - for backward compatibility only
+#define PREF_MAIL_ROOT_IMAP "mail.root.imap"
 
 static NS_DEFINE_CID(kImapUrlCID, NS_IMAPURL_CID);
 static NS_DEFINE_CID(kCImapMockChannel, NS_IMAPMOCKCHANNEL_CID);
 
 static const char sequenceString[] = "SEQUENCE";
 static const char uidString[] = "UID";
 
 static bool gInitialized = false;
 static int32_t gMIMEOnDemandThreshold = 15000;
 static bool gMIMEOnDemand = false;
 
-NS_IMPL_ISUPPORTS(nsImapService,
-                   nsIImapService,
-                   nsIMsgMessageService,
-                   nsIProtocolHandler,
-                   nsIMsgProtocolInfo,
-                   nsIMsgMessageFetchPartService,
-                   nsIContentHandler)
-
-nsImapService::nsImapService()
-{
+NS_IMPL_ISUPPORTS(nsImapService, nsIImapService, nsIMsgMessageService,
+                  nsIProtocolHandler, nsIMsgProtocolInfo,
+                  nsIMsgMessageFetchPartService, nsIContentHandler)
+
+nsImapService::nsImapService() {
   mPrintingOperation = false;
-  if (!gInitialized)
-  {
+  if (!gInitialized) {
     nsresult rv;
-    nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
-    if (NS_SUCCEEDED(rv) && prefBranch)
-    {
+    nsCOMPtr<nsIPrefBranch> prefBranch(
+        do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
+    if (NS_SUCCEEDED(rv) && prefBranch) {
       prefBranch->GetBoolPref("mail.imap.mime_parts_on_demand", &gMIMEOnDemand);
-      prefBranch->GetIntPref("mail.imap.mime_parts_on_demand_threshold", &gMIMEOnDemandThreshold);
+      prefBranch->GetIntPref("mail.imap.mime_parts_on_demand_threshold",
+                             &gMIMEOnDemandThreshold);
     }
 
     // initialize auto-sync service
-    nsCOMPtr<nsIAutoSyncManager> autoSyncMgr = do_GetService(NS_AUTOSYNCMANAGER_CONTRACTID, &rv);
-    if (NS_SUCCEEDED(rv) && autoSyncMgr)
-    {
+    nsCOMPtr<nsIAutoSyncManager> autoSyncMgr =
+        do_GetService(NS_AUTOSYNCMANAGER_CONTRACTID, &rv);
+    if (NS_SUCCEEDED(rv) && autoSyncMgr) {
       // auto-sync manager initialization goes here
       // assign new strategy objects here...
     }
-    NS_ASSERTION(autoSyncMgr != nullptr, "*** Cannot initialize nsAutoSyncManager service.");
+    NS_ASSERTION(autoSyncMgr != nullptr,
+                 "*** Cannot initialize nsAutoSyncManager service.");
 
     gInitialized = true;
   }
 }
 
-nsImapService::~nsImapService()
-{
-}
-
-char nsImapService::GetHierarchyDelimiter(nsIMsgFolder *aMsgFolder)
-{
+nsImapService::~nsImapService() {}
+
+char nsImapService::GetHierarchyDelimiter(nsIMsgFolder *aMsgFolder) {
   char delimiter = '/';
-  if (aMsgFolder)
-  {
+  if (aMsgFolder) {
     nsCOMPtr<nsIMsgImapMailFolder> imapFolder = do_QueryInterface(aMsgFolder);
-    if (imapFolder)
-      imapFolder->GetHierarchyDelimiter(&delimiter);
+    if (imapFolder) imapFolder->GetHierarchyDelimiter(&delimiter);
   }
   return delimiter;
 }
 
 // N.B., this returns an escaped folder name, appropriate for putting in a url.
-nsresult nsImapService::GetFolderName(nsIMsgFolder *aImapFolder, nsACString &aFolderName)
-{
+nsresult nsImapService::GetFolderName(nsIMsgFolder *aImapFolder,
+                                      nsACString &aFolderName) {
   nsresult rv;
   nsCOMPtr<nsIMsgImapMailFolder> aFolder(do_QueryInterface(aImapFolder, &rv));
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCString onlineName;
   // online name is in imap utf-7 - leave it that way
   rv = aFolder->GetOnlineName(onlineName);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (onlineName.IsEmpty())
-  {
+  if (onlineName.IsEmpty()) {
     nsCString uri;
     rv = aImapFolder->GetURI(uri);
     NS_ENSURE_SUCCESS(rv, rv);
     nsCString hostname;
     rv = aImapFolder->GetHostname(hostname);
     NS_ENSURE_SUCCESS(rv, rv);
-    rv = nsImapURI2FullName(kImapRootURI, hostname.get(), uri.get(), getter_Copies(onlineName));
+    rv = nsImapURI2FullName(kImapRootURI, hostname.get(), uri.get(),
+                            getter_Copies(onlineName));
   }
   // if the hierarchy delimiter is not '/', then we want to escape slashes;
   // otherwise, we do want to escape slashes.
   // we want to escape slashes and '^' first, otherwise, nsEscape will lose them
   bool escapeSlashes = (GetHierarchyDelimiter(aImapFolder) != '/');
-  if (escapeSlashes && !onlineName.IsEmpty())
-  {
-    char* escapedOnlineName;
+  if (escapeSlashes && !onlineName.IsEmpty()) {
+    char *escapedOnlineName;
     rv = nsImapUrl::EscapeSlashes(onlineName.get(), &escapedOnlineName);
-    if (NS_SUCCEEDED(rv))
-      onlineName.Adopt(escapedOnlineName);
+    if (NS_SUCCEEDED(rv)) onlineName.Adopt(escapedOnlineName);
   }
   // need to escape everything else
   MsgEscapeString(onlineName, nsINetUtil::ESCAPE_URL_PATH, aFolderName);
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::SelectFolder(nsIMsgFolder *aImapMailFolder,
                                           nsIUrlListener *aUrlListener,
                                           nsIMsgWindow *aMsgWindow,
-                                          nsIURI **aURL)
-{
+                                          nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
-  if (WeAreOffline())
-    return NS_MSG_ERROR_OFFLINE;
+  if (WeAreOffline()) return NS_MSG_ERROR_OFFLINE;
 
   bool canOpenThisFolder = true;
-  nsCOMPtr<nsIMsgImapMailFolder> imapFolder = do_QueryInterface(aImapMailFolder);
-  if (imapFolder)
-    imapFolder->GetCanOpenFolder(&canOpenThisFolder);
-
-  if (!canOpenThisFolder)
-    return NS_OK;
+  nsCOMPtr<nsIMsgImapMailFolder> imapFolder =
+      do_QueryInterface(aImapMailFolder);
+  if (imapFolder) imapFolder->GetCanOpenFolder(&canOpenThisFolder);
+
+  if (!canOpenThisFolder) return NS_OK;
 
   nsresult rv;
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
   char hierarchyDelimiter = GetHierarchyDelimiter(aImapMailFolder);
   rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
-                            aImapMailFolder, aUrlListener, urlSpec, hierarchyDelimiter);
-
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+                            aImapMailFolder, aUrlListener, urlSpec,
+                            hierarchyDelimiter);
+
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     // nsImapUrl::SetSpec() will set the imap action properly
     rv = imapUrl->SetImapAction(nsIImapUrl::nsImapSelectFolder);
 
     nsCOMPtr<nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
-    // if no msg window, we won't put up error messages (this is almost certainly a biff-inspired get new msgs)
-    if (!aMsgWindow)
-      mailNewsUrl->SetSuppressErrorMsgs(true);
+    // if no msg window, we won't put up error messages (this is almost
+    // certainly a biff-inspired get new msgs)
+    if (!aMsgWindow) mailNewsUrl->SetSuppressErrorMsgs(true);
     mailNewsUrl->SetMsgWindow(aMsgWindow);
     mailNewsUrl->SetUpdatingFolder(true);
     rv = SetImapUrlSink(aImapMailFolder, imapUrl);
 
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsAutoCString folderName;
       GetFolderName(aImapMailFolder, folderName);
       urlSpec.AppendLiteral("/select>");
       urlSpec.Append(hierarchyDelimiter);
       urlSpec.Append(folderName);
       rv = mailNewsUrl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, aURL);
     }
-  } // if we have a url to run....
+  }  // if we have a url to run....
 
   return rv;
 }
 
 // lite select, used to verify UIDVALIDITY while going on/offline
 NS_IMETHODIMP nsImapService::LiteSelectFolder(nsIMsgFolder *aImapMailFolder,
                                               nsIUrlListener *aUrlListener,
                                               nsIMsgWindow *aMsgWindow,
-                                              nsIURI **aURL)
-{
+                                              nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
-  return FolderCommand(aImapMailFolder, aUrlListener,
-                       "/liteselect>", nsIImapUrl::nsImapLiteSelectFolder, aMsgWindow, aURL);
+  return FolderCommand(aImapMailFolder, aUrlListener, "/liteselect>",
+                       nsIImapUrl::nsImapLiteSelectFolder, aMsgWindow, aURL);
 }
 
 NS_IMETHODIMP nsImapService::GetUrlForUri(const char *aMessageURI,
                                           nsIURI **aURL,
-                                          nsIMsgWindow *aMsgWindow)
-{
+                                          nsIMsgWindow *aMsgWindow) {
   nsAutoCString messageURI(aMessageURI);
 
-  if (messageURI.Find(NS_LITERAL_CSTRING("&type=application/x-message-display")) != kNotFound)
+  if (messageURI.Find(NS_LITERAL_CSTRING(
+          "&type=application/x-message-display")) != kNotFound)
     return NS_NewURI(aURL, aMessageURI);
 
   nsCOMPtr<nsIMsgFolder> folder;
   nsAutoCString msgKey;
   nsresult rv = DecomposeImapURI(messageURI, getter_AddRefs(folder), msgKey);
-  if (NS_SUCCEEDED(rv))
-  {
+  if (NS_SUCCEEDED(rv)) {
     nsCOMPtr<nsIImapUrl> imapUrl;
     nsAutoCString urlSpec;
     char hierarchyDelimiter = GetHierarchyDelimiter(folder);
-    rv = CreateStartOfImapUrl(messageURI, getter_AddRefs(imapUrl), folder, nullptr, urlSpec, hierarchyDelimiter);
+    rv = CreateStartOfImapUrl(messageURI, getter_AddRefs(imapUrl), folder,
+                              nullptr, urlSpec, hierarchyDelimiter);
     NS_ENSURE_SUCCESS(rv, rv);
     rv = SetImapUrlSink(folder, imapUrl);
     NS_ENSURE_SUCCESS(rv, rv);
-    nsCOMPtr <nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(imapUrl);
+    nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(imapUrl);
     bool useLocalCache = false;
     folder->HasMsgOffline(strtoul(msgKey.get(), nullptr, 10), &useLocalCache);
     mailnewsUrl->SetMsgIsInLocalCache(useLocalCache);
 
     nsCOMPtr<nsIURI> url = do_QueryInterface(imapUrl);
     rv = url->GetSpec(urlSpec);
     NS_ENSURE_SUCCESS(rv, rv);
     urlSpec.AppendLiteral("fetch>UID>");
     urlSpec.Append(hierarchyDelimiter);
 
     nsAutoCString folderName;
     GetFolderName(folder, folderName);
     urlSpec.Append(folderName);
     urlSpec.Append('>');
     urlSpec.Append(msgKey);
     rv = mailnewsUrl->SetSpecInternal(urlSpec);
-    imapUrl->QueryInterface(NS_GET_IID(nsIURI), (void **) aURL);
+    imapUrl->QueryInterface(NS_GET_IID(nsIURI), (void **)aURL);
   }
 
   return rv;
 }
 
-NS_IMETHODIMP nsImapService::OpenAttachment(const char *aContentType,
-                                            const char *aFileName,
-                                            const char *aUrl,
-                                            const char *aMessageUri,
-                                            nsISupports *aDisplayConsumer,
-                                            nsIMsgWindow *aMsgWindow,
-                                            nsIUrlListener *aUrlListener)
-{
+NS_IMETHODIMP nsImapService::OpenAttachment(
+    const char *aContentType, const char *aFileName, const char *aUrl,
+    const char *aMessageUri, nsISupports *aDisplayConsumer,
+    nsIMsgWindow *aMsgWindow, nsIUrlListener *aUrlListener) {
   // okay this is a little tricky....we may have to fetch the mime part
   // or it may already be downloaded for us....the only way i can tell to
   // distinguish the two events is to search for ?section or ?part
 
   nsAutoCString uri(aMessageUri);
   nsAutoCString urlString(aUrl);
   MsgReplaceSubstring(urlString, "/;section", "?section");
 
   // more stuff i don't understand
   int32_t sectionPos = urlString.Find("?section");
-  // if we have a section field then we must be dealing with a mime part we need to fetchf
-  if (sectionPos > 0)
-  {
+  // if we have a section field then we must be dealing with a mime part we need
+  // to fetchf
+  if (sectionPos > 0) {
     uri.Append(Substring(urlString, sectionPos));
     uri += "&type=";
     uri += aContentType;
     uri += "&filename=";
     uri += aFileName;
-  }
-  else
-  {
+  } else {
     // try to extract the specific part number out from the url string
     const char *partStart = PL_strstr(aUrl, "part=");
-    if (!partStart)
-      return NS_ERROR_FAILURE;
+    if (!partStart) return NS_ERROR_FAILURE;
     nsDependentCString part(partStart);
     uri += "?";
     uri += Substring(part, 0, part.FindChar('&'));
     uri += "&type=";
     uri += aContentType;
     uri += "&filename=";
     uri += aFileName;
   }
@@ -320,640 +298,612 @@ NS_IMETHODIMP nsImapService::OpenAttachm
   nsCOMPtr<nsIMsgFolder> folder;
   nsAutoCString msgKey;
   nsAutoCString uriMimePart;
   nsAutoCString folderURI;
   nsMsgKey key;
 
   nsresult rv = DecomposeImapURI(uri, getter_AddRefs(folder), msgKey);
   NS_ENSURE_SUCCESS(rv, rv);
-  rv = nsParseImapMessageURI(uri.get(), folderURI, &key, getter_Copies(uriMimePart));
-  if (NS_SUCCEEDED(rv))
-  {
-    nsCOMPtr<nsIImapMessageSink> imapMessageSink(do_QueryInterface(folder, &rv));
-    if (NS_SUCCEEDED(rv))
-    {
+  rv = nsParseImapMessageURI(uri.get(), folderURI, &key,
+                             getter_Copies(uriMimePart));
+  if (NS_SUCCEEDED(rv)) {
+    nsCOMPtr<nsIImapMessageSink> imapMessageSink(
+        do_QueryInterface(folder, &rv));
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIImapUrl> imapUrl;
       nsAutoCString urlSpec;
       char hierarchyDelimiter = GetHierarchyDelimiter(folder);
-      rv = CreateStartOfImapUrl(uri, getter_AddRefs(imapUrl), folder, aUrlListener, urlSpec, hierarchyDelimiter);
+      rv = CreateStartOfImapUrl(uri, getter_AddRefs(imapUrl), folder,
+                                aUrlListener, urlSpec, hierarchyDelimiter);
       NS_ENSURE_SUCCESS(rv, rv);
 
       urlSpec.AppendLiteral("/fetch>UID>");
       urlSpec.Append(hierarchyDelimiter);
 
       nsCString folderName;
       GetFolderName(folder, folderName);
       urlSpec.Append(folderName);
       urlSpec.Append('>');
       urlSpec.Append(msgKey);
       urlSpec.Append(uriMimePart);
 
-      if (!uriMimePart.IsEmpty())
-      {
+      if (!uriMimePart.IsEmpty()) {
         nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl(do_QueryInterface(imapUrl));
-        if (mailnewsurl)
-        {
+        if (mailnewsurl) {
           rv = mailnewsurl->SetSpecInternal(urlSpec);
           NS_ENSURE_SUCCESS(rv, rv);
           if (aFileName)
             mailnewsurl->SetFileNameInternal(nsDependentCString(aFileName));
         }
-        rv =  FetchMimePart(imapUrl, nsIImapUrl::nsImapOpenMimePart, folder, imapMessageSink,
-                            nullptr, aDisplayConsumer, msgKey, uriMimePart);
+        rv = FetchMimePart(imapUrl, nsIImapUrl::nsImapOpenMimePart, folder,
+                           imapMessageSink, nullptr, aDisplayConsumer, msgKey,
+                           uriMimePart);
       }
-    } // if we got a message sink
-  } // if we parsed the message uri
+    }  // if we got a message sink
+  }    // if we parsed the message uri
 
   return rv;
 }
 
-NS_IMETHODIMP nsImapService::FetchMimePart(nsIURI *aURI,
-                                           const char *aMessageURI,
-                                           nsISupports *aDisplayConsumer,
-                                           nsIMsgWindow *aMsgWindow,
-                                           nsIUrlListener *aUrlListener,
-                                           nsIURI **aURL)
-{
+NS_IMETHODIMP nsImapService::FetchMimePart(
+    nsIURI *aURI, const char *aMessageURI, nsISupports *aDisplayConsumer,
+    nsIMsgWindow *aMsgWindow, nsIUrlListener *aUrlListener, nsIURI **aURL) {
   nsCOMPtr<nsIMsgFolder> folder;
   nsAutoCString messageURI(aMessageURI);
   nsAutoCString msgKey;
   nsAutoCString mimePart;
   nsAutoCString folderURI;
   nsMsgKey key;
 
   nsresult rv = DecomposeImapURI(messageURI, getter_AddRefs(folder), msgKey);
   NS_ENSURE_SUCCESS(rv, rv);
-  rv = nsParseImapMessageURI(aMessageURI, folderURI, &key, getter_Copies(mimePart));
-  if (NS_SUCCEEDED(rv))
-  {
-    nsCOMPtr<nsIImapMessageSink> imapMessageSink(do_QueryInterface(folder, &rv));
-    if (NS_SUCCEEDED(rv))
-    {
+  rv = nsParseImapMessageURI(aMessageURI, folderURI, &key,
+                             getter_Copies(mimePart));
+  if (NS_SUCCEEDED(rv)) {
+    nsCOMPtr<nsIImapMessageSink> imapMessageSink(
+        do_QueryInterface(folder, &rv));
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIImapUrl> imapUrl = do_QueryInterface(aURI);
-      nsCOMPtr<nsIMsgMailNewsUrl> msgurl (do_QueryInterface(aURI));
+      nsCOMPtr<nsIMsgMailNewsUrl> msgurl(do_QueryInterface(aURI));
 
       msgurl->SetMsgWindow(aMsgWindow);
       msgurl->RegisterListener(aUrlListener);
 
-      if (!mimePart.IsEmpty())
-      {
-        return FetchMimePart(imapUrl, nsIImapUrl::nsImapMsgFetch, folder, imapMessageSink,
-          aURL, aDisplayConsumer, msgKey, mimePart);
+      if (!mimePart.IsEmpty()) {
+        return FetchMimePart(imapUrl, nsIImapUrl::nsImapMsgFetch, folder,
+                             imapMessageSink, aURL, aDisplayConsumer, msgKey,
+                             mimePart);
       }
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::DisplayMessage(const char *aMessageURI,
                                             nsISupports *aDisplayConsumer,
                                             nsIMsgWindow *aMsgWindow,
                                             nsIUrlListener *aUrlListener,
                                             const char *aCharsetOverride,
-                                            nsIURI **aURL)
-{
+                                            nsIURI **aURL) {
   nsresult rv;
 
   nsCOMPtr<nsIMsgFolder> folder;
   nsAutoCString msgKey;
   nsAutoCString mimePart;
   nsAutoCString folderURI;
   nsMsgKey key;
   nsAutoCString messageURI(aMessageURI);
 
   int32_t typeIndex = messageURI.Find("&type=application/x-message-display");
-  if (typeIndex != kNotFound)
-  {
+  if (typeIndex != kNotFound) {
     // This happens with forward inline of a message/rfc822 attachment opened in
     // a standalone msg window.
     // So, just cut to the chase and call AsyncOpen on a channel.
     nsCOMPtr<nsIURI> uri;
-    messageURI.Cut(typeIndex, sizeof("&type=application/x-message-display") - 1);
+    messageURI.Cut(typeIndex,
+                   sizeof("&type=application/x-message-display") - 1);
     rv = NS_NewURI(getter_AddRefs(uri), messageURI.get());
     NS_ENSURE_SUCCESS(rv, rv);
-    if (aURL)
-      NS_IF_ADDREF(*aURL = uri);
-    nsCOMPtr<nsIStreamListener> aStreamListener = do_QueryInterface(aDisplayConsumer, &rv);
-    if (NS_SUCCEEDED(rv) && aStreamListener)
-    {
+    if (aURL) NS_IF_ADDREF(*aURL = uri);
+    nsCOMPtr<nsIStreamListener> aStreamListener =
+        do_QueryInterface(aDisplayConsumer, &rv);
+    if (NS_SUCCEEDED(rv) && aStreamListener) {
       nsCOMPtr<nsIChannel> aChannel;
       nsCOMPtr<nsILoadGroup> aLoadGroup;
       nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(uri, &rv);
       if (NS_SUCCEEDED(rv) && mailnewsUrl)
         mailnewsUrl->GetLoadGroup(getter_AddRefs(aLoadGroup));
 
       nsCOMPtr<nsILoadInfo> loadInfo = new mozilla::net::LoadInfo(
-        nsContentUtils::GetSystemPrincipal(),
-        nullptr,
-        nullptr,
-        nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
-        nsIContentPolicy::TYPE_OTHER);
+          nsContentUtils::GetSystemPrincipal(), nullptr, nullptr,
+          nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
+          nsIContentPolicy::TYPE_OTHER);
       rv = NewChannel(uri, loadInfo, getter_AddRefs(aChannel));
       NS_ENSURE_SUCCESS(rv, rv);
 
-      //  now try to open the channel passing in our display consumer as the listener
+      //  now try to open the channel passing in our display consumer as the
+      //  listener
       rv = aChannel->AsyncOpen(aStreamListener);
       return rv;
     }
   }
 
   rv = DecomposeImapURI(messageURI, getter_AddRefs(folder), msgKey);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (msgKey.IsEmpty())
-    return NS_MSG_MESSAGE_NOT_FOUND;
-
-  rv = nsParseImapMessageURI(aMessageURI, folderURI, &key, getter_Copies(mimePart));
-  if (NS_SUCCEEDED(rv))
-  {
-    nsCOMPtr<nsIImapMessageSink> imapMessageSink(do_QueryInterface(folder, &rv));
-    if (NS_SUCCEEDED(rv))
-    {
+  if (msgKey.IsEmpty()) return NS_MSG_MESSAGE_NOT_FOUND;
+
+  rv = nsParseImapMessageURI(aMessageURI, folderURI, &key,
+                             getter_Copies(mimePart));
+  if (NS_SUCCEEDED(rv)) {
+    nsCOMPtr<nsIImapMessageSink> imapMessageSink(
+        do_QueryInterface(folder, &rv));
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIImapUrl> imapUrl;
       nsAutoCString urlSpec;
       char hierarchyDelimiter = GetHierarchyDelimiter(folder);
-      rv = CreateStartOfImapUrl(messageURI, getter_AddRefs(imapUrl), folder, aUrlListener, urlSpec, hierarchyDelimiter);
+      rv = CreateStartOfImapUrl(messageURI, getter_AddRefs(imapUrl), folder,
+                                aUrlListener, urlSpec, hierarchyDelimiter);
       NS_ENSURE_SUCCESS(rv, rv);
-      if (!mimePart.IsEmpty())
-      {
+      if (!mimePart.IsEmpty()) {
         nsresult rv;
         nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(imapUrl);
 
-        rv = AddImapFetchToUrl(mailnewsurl, folder, msgKey + mimePart, EmptyCString());
+        rv = AddImapFetchToUrl(mailnewsurl, folder, msgKey + mimePart,
+                               EmptyCString());
         NS_ENSURE_SUCCESS(rv, rv);
 
-        return FetchMimePart(imapUrl, nsIImapUrl::nsImapMsgFetch, folder, imapMessageSink,
-                             aURL, aDisplayConsumer, msgKey, mimePart);
+        return FetchMimePart(imapUrl, nsIImapUrl::nsImapMsgFetch, folder,
+                             imapMessageSink, aURL, aDisplayConsumer, msgKey,
+                             mimePart);
       }
 
-      nsCOMPtr<nsIMsgMailNewsUrl> msgurl (do_QueryInterface(imapUrl));
-      nsCOMPtr<nsIMsgI18NUrl> i18nurl (do_QueryInterface(imapUrl));
+      nsCOMPtr<nsIMsgMailNewsUrl> msgurl(do_QueryInterface(imapUrl));
+      nsCOMPtr<nsIMsgI18NUrl> i18nurl(do_QueryInterface(imapUrl));
       i18nurl->SetCharsetOverRide(aCharsetOverride);
 
       uint32_t messageSize;
       bool useMimePartsOnDemand = gMIMEOnDemand;
       bool shouldStoreMsgOffline = false;
       bool hasMsgOffline = false;
 
       nsCOMPtr<nsIMsgIncomingServer> aMsgIncomingServer;
 
       if (imapMessageSink)
         imapMessageSink->GetMessageSizeFromDB(msgKey.get(), &messageSize);
 
       msgurl->SetMsgWindow(aMsgWindow);
 
       rv = msgurl->GetServer(getter_AddRefs(aMsgIncomingServer));
 
-      if (NS_SUCCEEDED(rv) && aMsgIncomingServer)
-      {
-        nsCOMPtr<nsIImapIncomingServer> aImapServer(do_QueryInterface(aMsgIncomingServer, &rv));
+      if (NS_SUCCEEDED(rv) && aMsgIncomingServer) {
+        nsCOMPtr<nsIImapIncomingServer> aImapServer(
+            do_QueryInterface(aMsgIncomingServer, &rv));
         if (NS_SUCCEEDED(rv) && aImapServer)
           aImapServer->GetMimePartsOnDemand(&useMimePartsOnDemand);
       }
 
       nsAutoCString uriStr(aMessageURI);
       int32_t keySeparator = uriStr.RFindChar('#');
-      if(keySeparator != -1)
-      {
+      if (keySeparator != -1) {
         int32_t keyEndSeparator = MsgFindCharInSet(uriStr, "/?&", keySeparator);
-        int32_t mpodFetchPos = MsgFind(uriStr, "fetchCompleteMessage=true", false, keyEndSeparator);
-        if (mpodFetchPos != -1)
-          useMimePartsOnDemand = false;
+        int32_t mpodFetchPos = MsgFind(uriStr, "fetchCompleteMessage=true",
+                                       false, keyEndSeparator);
+        if (mpodFetchPos != -1) useMimePartsOnDemand = false;
       }
 
-      if (folder)
-      {
+      if (folder) {
         folder->ShouldStoreMsgOffline(key, &shouldStoreMsgOffline);
         folder->HasMsgOffline(key, &hasMsgOffline);
       }
       imapUrl->SetStoreResultsOffline(shouldStoreMsgOffline);
-      imapUrl->SetFetchPartsOnDemand(
-        useMimePartsOnDemand && messageSize >= (uint32_t) gMIMEOnDemandThreshold);
-
-      if (hasMsgOffline)
-        msgurl->SetMsgIsInLocalCache(true);
-
-      nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
+      imapUrl->SetFetchPartsOnDemand(useMimePartsOnDemand &&
+                                     messageSize >=
+                                         (uint32_t)gMIMEOnDemandThreshold);
+
+      if (hasMsgOffline) msgurl->SetMsgIsInLocalCache(true);
+
+      nsCOMPtr<nsIPrefBranch> prefBranch(
+          do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
       // Should the message fetch force a peek or a traditional fetch?
-      // Force peek if there is a delay in marking read (or no auto-marking at all).
-      // This is because a FETCH (BODY[]) will implicitly set the \Seen flag on the msg,
-      // but a FETCH (BODY.PEEK[]) won't.
+      // Force peek if there is a delay in marking read (or no auto-marking at
+      // all). This is because a FETCH (BODY[]) will implicitly set the \Seen
+      // flag on the msg, but a FETCH (BODY.PEEK[]) won't.
       bool forcePeek = false;
-      if (NS_SUCCEEDED(rv) && prefBranch)
-      {
+      if (NS_SUCCEEDED(rv) && prefBranch) {
         int32_t dontMarkAsReadPos = uriStr.Find("&markRead=false");
         bool markReadAuto = true;
-        prefBranch->GetBoolPref("mailnews.mark_message_read.auto", &markReadAuto);
+        prefBranch->GetBoolPref("mailnews.mark_message_read.auto",
+                                &markReadAuto);
         bool markReadDelay = false;
-        prefBranch->GetBoolPref("mailnews.mark_message_read.delay", &markReadDelay);
-        forcePeek = (!markReadAuto || markReadDelay || (dontMarkAsReadPos != kNotFound));
+        prefBranch->GetBoolPref("mailnews.mark_message_read.delay",
+                                &markReadDelay);
+        forcePeek = (!markReadAuto || markReadDelay ||
+                     (dontMarkAsReadPos != kNotFound));
       }
 
-      rv = FetchMessage(imapUrl, forcePeek ? nsIImapUrl::nsImapMsgFetchPeek : nsIImapUrl::nsImapMsgFetch,
-                        folder, imapMessageSink, aMsgWindow, aDisplayConsumer, msgKey, false,
-                        (mPrintingOperation) ? NS_LITERAL_CSTRING("print") : NS_LITERAL_CSTRING(""), aURL);
+      rv = FetchMessage(imapUrl,
+                        forcePeek ? nsIImapUrl::nsImapMsgFetchPeek
+                                  : nsIImapUrl::nsImapMsgFetch,
+                        folder, imapMessageSink, aMsgWindow, aDisplayConsumer,
+                        msgKey, false,
+                        (mPrintingOperation) ? NS_LITERAL_CSTRING("print")
+                                             : NS_LITERAL_CSTRING(""),
+                        aURL);
     }
   }
   return rv;
 }
 
-
-nsresult nsImapService::FetchMimePart(nsIImapUrl *aImapUrl,
-                                      nsImapAction aImapAction,
-                                      nsIMsgFolder *aImapMailFolder,
-                                      nsIImapMessageSink *aImapMessage,
-                                      nsIURI **aURL,
-                                      nsISupports *aDisplayConsumer,
-                                      const nsACString &messageIdentifierList,
-                                      const nsACString &mimePart)
-{
+nsresult nsImapService::FetchMimePart(
+    nsIImapUrl *aImapUrl, nsImapAction aImapAction,
+    nsIMsgFolder *aImapMailFolder, nsIImapMessageSink *aImapMessage,
+    nsIURI **aURL, nsISupports *aDisplayConsumer,
+    const nsACString &messageIdentifierList, const nsACString &mimePart) {
   NS_ENSURE_ARG_POINTER(aImapUrl);
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
   NS_ENSURE_ARG_POINTER(aImapMessage);
 
   // create a protocol instance to handle the request.
-  // NOTE: once we start working with multiple connections, this step will be much more complicated...but for now
-  // just create a connection and process the request.
+  // NOTE: once we start working with multiple connections, this step will be
+  // much more complicated...but for now just create a connection and process
+  // the request.
   nsAutoCString urlSpec;
   nsresult rv = SetImapUrlSink(aImapMailFolder, aImapUrl);
   nsImapAction actionToUse = aImapAction;
   if (actionToUse == nsImapUrl::nsImapOpenMimePart)
     actionToUse = nsIImapUrl::nsImapMsgFetch;
 
-  nsCOMPtr<nsIMsgMailNewsUrl> msgurl (do_QueryInterface(aImapUrl));
-  if (aImapMailFolder && msgurl && !messageIdentifierList.IsEmpty())
-  {
+  nsCOMPtr<nsIMsgMailNewsUrl> msgurl(do_QueryInterface(aImapUrl));
+  if (aImapMailFolder && msgurl && !messageIdentifierList.IsEmpty()) {
     bool useLocalCache = false;
-    aImapMailFolder->HasMsgOffline(strtoul(nsCString(messageIdentifierList).get(), nullptr, 10),
-                                   &useLocalCache);
+    aImapMailFolder->HasMsgOffline(
+        strtoul(nsCString(messageIdentifierList).get(), nullptr, 10),
+        &useLocalCache);
     msgurl->SetMsgIsInLocalCache(useLocalCache);
   }
   rv = aImapUrl->SetImapMessageSink(aImapMessage);
-  if (NS_SUCCEEDED(rv))
-  {
+  if (NS_SUCCEEDED(rv)) {
     nsCOMPtr<nsIURI> url = do_QueryInterface(aImapUrl);
-    if (aURL)
-      NS_IF_ADDREF(*aURL = url);
+    if (aURL) NS_IF_ADDREF(*aURL = url);
 
     rv = url->GetSpec(urlSpec);
     NS_ENSURE_SUCCESS(rv, rv);
 
     // rhp: If we are displaying this message for the purpose of printing, we
     // need to append the header=print option.
     //
-    if (mPrintingOperation)
-      urlSpec.AppendLiteral("?header=print");
+    if (mPrintingOperation) urlSpec.AppendLiteral("?header=print");
 
     rv = msgurl->SetSpecInternal(urlSpec);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = aImapUrl->SetImapAction(actionToUse /* nsIImapUrl::nsImapMsgFetch */);
-    if (aImapMailFolder && aDisplayConsumer)
-    {
+    if (aImapMailFolder && aDisplayConsumer) {
       nsCOMPtr<nsIMsgIncomingServer> aMsgIncomingServer;
       rv = aImapMailFolder->GetServer(getter_AddRefs(aMsgIncomingServer));
-      if (NS_SUCCEEDED(rv) && aMsgIncomingServer)
-      {
+      if (NS_SUCCEEDED(rv) && aMsgIncomingServer) {
         bool interrupted;
-        nsCOMPtr<nsIImapIncomingServer>
-          aImapServer(do_QueryInterface(aMsgIncomingServer, &rv));
+        nsCOMPtr<nsIImapIncomingServer> aImapServer(
+            do_QueryInterface(aMsgIncomingServer, &rv));
         if (NS_SUCCEEDED(rv) && aImapServer)
-          aImapServer->PseudoInterruptMsgLoad(aImapMailFolder, nullptr, &interrupted);
+          aImapServer->PseudoInterruptMsgLoad(aImapMailFolder, nullptr,
+                                              &interrupted);
       }
     }
-    // if the display consumer is a docshell, then we should run the url in the docshell.
-    // otherwise, it should be a stream listener....so open a channel using AsyncRead
-    // and the provided stream listener....
+    // if the display consumer is a docshell, then we should run the url in the
+    // docshell. otherwise, it should be a stream listener....so open a channel
+    // using AsyncRead and the provided stream listener....
 
     nsCOMPtr<nsIDocShell> docShell(do_QueryInterface(aDisplayConsumer, &rv));
-    if (NS_SUCCEEDED(rv) && docShell)
-    {
-      // DIRTY LITTLE HACK --> if we are opening an attachment we want the docshell to
-      // treat this load as if it were a user click event. Then the dispatching stuff will be much
-      // happier.
+    if (NS_SUCCEEDED(rv) && docShell) {
+      // DIRTY LITTLE HACK --> if we are opening an attachment we want the
+      // docshell to treat this load as if it were a user click event. Then the
+      // dispatching stuff will be much happier.
       RefPtr<nsDocShellLoadState> loadState = new nsDocShellLoadState(url);
       loadState->SetLoadFlags(aImapAction == nsImapUrl::nsImapOpenMimePart
-                                ? nsIWebNavigation::LOAD_FLAGS_IS_LINK
-                                : nsIWebNavigation::LOAD_FLAGS_NONE);
+                                  ? nsIWebNavigation::LOAD_FLAGS_IS_LINK
+                                  : nsIWebNavigation::LOAD_FLAGS_NONE);
       if (aImapAction == nsImapUrl::nsImapOpenMimePart)
         loadState->SetLoadType(LOAD_LINK);
       loadState->SetFirstParty(false);
       loadState->SetTriggeringPrincipal(nsContentUtils::GetSystemPrincipal());
       rv = docShell->LoadURI(loadState);
-    }
-    else
-    {
-      nsCOMPtr<nsIStreamListener> aStreamListener = do_QueryInterface(aDisplayConsumer, &rv);
-      if (NS_SUCCEEDED(rv) && aStreamListener)
-      {
+    } else {
+      nsCOMPtr<nsIStreamListener> aStreamListener =
+          do_QueryInterface(aDisplayConsumer, &rv);
+      if (NS_SUCCEEDED(rv) && aStreamListener) {
         nsCOMPtr<nsIChannel> aChannel;
         nsCOMPtr<nsILoadGroup> loadGroup;
-        nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(aImapUrl, &rv);
+        nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl =
+            do_QueryInterface(aImapUrl, &rv);
         if (NS_SUCCEEDED(rv) && mailnewsUrl)
           mailnewsUrl->GetLoadGroup(getter_AddRefs(loadGroup));
 
         nsCOMPtr<nsILoadInfo> loadInfo = new mozilla::net::LoadInfo(
-          nsContentUtils::GetSystemPrincipal(),
-          nullptr,
-          nullptr,
-          nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
-          nsIContentPolicy::TYPE_OTHER);
+            nsContentUtils::GetSystemPrincipal(), nullptr, nullptr,
+            nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
+            nsIContentPolicy::TYPE_OTHER);
         rv = NewChannel(url, loadInfo, getter_AddRefs(aChannel));
         NS_ENSURE_SUCCESS(rv, rv);
 
-        // we need a load group to hold onto the channel. When the request is finished,
-        // it'll get removed from the load group, and the channel will go away,
-        // which will free the load group.
-        if (!loadGroup)
-          loadGroup = do_CreateInstance(NS_LOADGROUP_CONTRACTID);
+        // we need a load group to hold onto the channel. When the request is
+        // finished, it'll get removed from the load group, and the channel will
+        // go away, which will free the load group.
+        if (!loadGroup) loadGroup = do_CreateInstance(NS_LOADGROUP_CONTRACTID);
 
         aChannel->SetLoadGroup(loadGroup);
 
-        //  now try to open the channel passing in our display consumer as the listener
+        //  now try to open the channel passing in our display consumer as the
+        //  listener
         rv = aChannel->AsyncOpen(aStreamListener);
-      }
-      else // do what we used to do before
+      } else  // do what we used to do before
       {
-        // I'd like to get rid of this code as I believe that we always get a docshell
-        // or stream listener passed into us in this method but i'm not sure yet...
-        // I'm going to use an assert for now to figure out if this is ever getting called
+        // I'd like to get rid of this code as I believe that we always get a
+        // docshell or stream listener passed into us in this method but i'm not
+        // sure yet... I'm going to use an assert for now to figure out if this
+        // is ever getting called
 #if defined(DEBUG_mscott) || defined(DEBUG_bienvenu)
         NS_ERROR("oops...someone still is reaching this part of the code");
 #endif
         rv = GetImapConnectionAndLoadUrl(aImapUrl, aDisplayConsumer, aURL);
       }
     }
   }
   return rv;
 }
 
 //
 // rhp: Right now, this is the same as simple DisplayMessage, but it will change
 // to support print rendering.
 //
-NS_IMETHODIMP nsImapService::DisplayMessageForPrinting(const char *aMessageURI,
-                                                       nsISupports *aDisplayConsumer,
-                                                       nsIMsgWindow *aMsgWindow,
-                                                       nsIUrlListener *aUrlListener,
-                                                       nsIURI **aURL)
-{
+NS_IMETHODIMP nsImapService::DisplayMessageForPrinting(
+    const char *aMessageURI, nsISupports *aDisplayConsumer,
+    nsIMsgWindow *aMsgWindow, nsIUrlListener *aUrlListener, nsIURI **aURL) {
   mPrintingOperation = true;
-  nsresult rv = DisplayMessage(aMessageURI, aDisplayConsumer, aMsgWindow, aUrlListener, nullptr, aURL);
+  nsresult rv = DisplayMessage(aMessageURI, aDisplayConsumer, aMsgWindow,
+                               aUrlListener, nullptr, aURL);
   mPrintingOperation = false;
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::CopyMessage(const char *aSrcMailboxURI,
                                          nsIStreamListener *aMailboxCopy,
                                          bool moveMessage,
                                          nsIUrlListener *aUrlListener,
                                          nsIMsgWindow *aMsgWindow,
-                                         nsIURI **aURL)
-{
+                                         nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aSrcMailboxURI);
   NS_ENSURE_ARG_POINTER(aMailboxCopy);
 
   nsresult rv;
   nsCOMPtr<nsISupports> streamSupport;
   streamSupport = do_QueryInterface(aMailboxCopy, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIMsgFolder> folder;
   nsAutoCString msgKey;
-  rv = DecomposeImapURI(nsDependentCString(aSrcMailboxURI), getter_AddRefs(folder), msgKey);
-  if (NS_SUCCEEDED(rv))
-  {
-    nsCOMPtr<nsIImapMessageSink> imapMessageSink(do_QueryInterface(folder, &rv));
-    if (NS_SUCCEEDED(rv))
-    {
+  rv = DecomposeImapURI(nsDependentCString(aSrcMailboxURI),
+                        getter_AddRefs(folder), msgKey);
+  if (NS_SUCCEEDED(rv)) {
+    nsCOMPtr<nsIImapMessageSink> imapMessageSink(
+        do_QueryInterface(folder, &rv));
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIImapUrl> imapUrl;
       nsAutoCString urlSpec;
       char hierarchyDelimiter = GetHierarchyDelimiter(folder);
       bool hasMsgOffline = false;
       nsMsgKey key = strtoul(msgKey.get(), nullptr, 10);
 
-      rv = CreateStartOfImapUrl(nsDependentCString(aSrcMailboxURI), getter_AddRefs(imapUrl),
-                                folder, aUrlListener, urlSpec, hierarchyDelimiter);
-      if (folder)
-      {
-        nsCOMPtr<nsIMsgMailNewsUrl> msgurl (do_QueryInterface(imapUrl));
+      rv = CreateStartOfImapUrl(nsDependentCString(aSrcMailboxURI),
+                                getter_AddRefs(imapUrl), folder, aUrlListener,
+                                urlSpec, hierarchyDelimiter);
+      if (folder) {
+        nsCOMPtr<nsIMsgMailNewsUrl> msgurl(do_QueryInterface(imapUrl));
         folder->HasMsgOffline(key, &hasMsgOffline);
-        if (msgurl)
-          msgurl->SetMsgIsInLocalCache(hasMsgOffline);
+        if (msgurl) msgurl->SetMsgIsInLocalCache(hasMsgOffline);
       }
       // now try to download the message
       nsImapAction imapAction = nsIImapUrl::nsImapOnlineToOfflineCopy;
-      if (moveMessage)
-        imapAction = nsIImapUrl::nsImapOnlineToOfflineMove;
-      rv = FetchMessage(imapUrl,imapAction, folder, imapMessageSink,aMsgWindow,
-                        streamSupport, msgKey, false, EmptyCString(), aURL);
-    } // if we got an imap message sink
-  } // if we decomposed the imap message
+      if (moveMessage) imapAction = nsIImapUrl::nsImapOnlineToOfflineMove;
+      // clang-format off
+      rv = FetchMessage(imapUrl, imapAction, folder, imapMessageSink,
+                        aMsgWindow, streamSupport, msgKey, false,
+                        EmptyCString(), aURL);
+      // clang-format on
+    }  // if we got an imap message sink
+  }    // if we decomposed the imap message
   return rv;
 }
 
-NS_IMETHODIMP nsImapService::CopyMessages(uint32_t aNumKeys,
-                                          nsMsgKey*aKeys,
-                                          nsIMsgFolder *srcFolder,
-                                          nsIStreamListener *aMailboxCopy,
-                                          bool moveMessage,
-                                          nsIUrlListener *aUrlListener,
-                                          nsIMsgWindow *aMsgWindow,
-                                          nsIURI **aURL)
-{
+NS_IMETHODIMP nsImapService::CopyMessages(
+    uint32_t aNumKeys, nsMsgKey *aKeys, nsIMsgFolder *srcFolder,
+    nsIStreamListener *aMailboxCopy, bool moveMessage,
+    nsIUrlListener *aUrlListener, nsIMsgWindow *aMsgWindow, nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aMailboxCopy);
   NS_ENSURE_ARG_POINTER(aKeys);
 
   nsresult rv;
   nsCOMPtr<nsISupports> streamSupport = do_QueryInterface(aMailboxCopy, &rv);
-  if (!streamSupport || NS_FAILED(rv))
-    return rv;
+  if (!streamSupport || NS_FAILED(rv)) return rv;
 
   nsCOMPtr<nsIMsgFolder> folder = srcFolder;
-  if (NS_SUCCEEDED(rv))
-  {
-    nsCOMPtr<nsIImapMessageSink> imapMessageSink(do_QueryInterface(folder, &rv));
-    if (NS_SUCCEEDED(rv))
-    {
+  if (NS_SUCCEEDED(rv)) {
+    nsCOMPtr<nsIImapMessageSink> imapMessageSink(
+        do_QueryInterface(folder, &rv));
+    if (NS_SUCCEEDED(rv)) {
       // we generate the uri for the first message so that way on down the line,
-      // GetMessage in nsCopyMessageStreamListener will get an unescaped username
-      // and be able to find the msg hdr. See bug 259656 for details
+      // GetMessage in nsCopyMessageStreamListener will get an unescaped
+      // username and be able to find the msg hdr. See bug 259656 for details
       nsCString uri;
       srcFolder->GenerateMessageURI(aKeys[0], uri);
 
       nsCString messageIds;
       AllocateImapUidString(aKeys, aNumKeys, nullptr, messageIds);
       nsCOMPtr<nsIImapUrl> imapUrl;
       nsAutoCString urlSpec;
       char hierarchyDelimiter = GetHierarchyDelimiter(folder);
-      rv = CreateStartOfImapUrl(uri, getter_AddRefs(imapUrl), folder, aUrlListener, urlSpec, hierarchyDelimiter);
+      rv = CreateStartOfImapUrl(uri, getter_AddRefs(imapUrl), folder,
+                                aUrlListener, urlSpec, hierarchyDelimiter);
       nsImapAction action;
-      if (moveMessage) // don't use ?: syntax here, it seems to break the Mac.
+      if (moveMessage)  // don't use ?: syntax here, it seems to break the Mac.
         action = nsIImapUrl::nsImapOnlineToOfflineMove;
       else
         action = nsIImapUrl::nsImapOnlineToOfflineCopy;
       imapUrl->SetCopyState(aMailboxCopy);
       // now try to display the message
       rv = FetchMessage(imapUrl, action, folder, imapMessageSink, aMsgWindow,
                         streamSupport, messageIds, false, EmptyCString(), aURL);
-      // ### end of copy operation should know how to do the delete.if this is a move
-
-    } // if we got an imap message sink
-  } // if we decomposed the imap message
+      // ### end of copy operation should know how to do the delete.if this is a
+      // move
+
+    }  // if we got an imap message sink
+  }    // if we decomposed the imap message
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::Search(nsIMsgSearchSession *aSearchSession,
                                     nsIMsgWindow *aMsgWindow,
                                     nsIMsgFolder *aMsgFolder,
-                                    const char *aSearchUri)
-{
+                                    const char *aSearchUri) {
   NS_ENSURE_ARG_POINTER(aSearchUri);
   NS_ENSURE_ARG_POINTER(aMsgFolder);
   nsresult rv;
 
   nsCOMPtr<nsIImapUrl> imapUrl;
-  nsCOMPtr <nsIUrlListener> urlListener = do_QueryInterface(aSearchSession, &rv);
+  nsCOMPtr<nsIUrlListener> urlListener = do_QueryInterface(aSearchSession, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsAutoCString urlSpec;
   char hierarchyDelimiter = GetHierarchyDelimiter(aMsgFolder);
-  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
-                            aMsgFolder, urlListener, urlSpec,
-                            hierarchyDelimiter);
+  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aMsgFolder,
+                            urlListener, urlSpec, hierarchyDelimiter);
   NS_ENSURE_SUCCESS(rv, rv);
-  nsCOMPtr<nsIMsgMailNewsUrl> msgurl (do_QueryInterface(imapUrl));
+  nsCOMPtr<nsIMsgMailNewsUrl> msgurl(do_QueryInterface(imapUrl));
 
   msgurl->SetMsgWindow(aMsgWindow);
   msgurl->SetSearchSession(aSearchSession);
   rv = SetImapUrlSink(aMsgFolder, imapUrl);
 
-  if (NS_SUCCEEDED(rv))
-  {
+  if (NS_SUCCEEDED(rv)) {
     nsCString folderName;
     GetFolderName(aMsgFolder, folderName);
 
-    nsCOMPtr <nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
-    if (!aMsgWindow)
-      mailNewsUrl->SetSuppressErrorMsgs(true);
+    nsCOMPtr<nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
+    if (!aMsgWindow) mailNewsUrl->SetSuppressErrorMsgs(true);
 
     urlSpec.AppendLiteral("/search>UID>");
     urlSpec.Append(hierarchyDelimiter);
     urlSpec.Append(folderName);
     urlSpec.Append('>');
     // escape aSearchUri so that IMAP special characters (i.e. '\')
     // won't be replaced with '/' in NECKO.
     // it will be unescaped in nsImapUrl::ParseUrl().
     nsCString escapedSearchUri;
 
-    MsgEscapeString(nsDependentCString(aSearchUri), nsINetUtil::ESCAPE_XALPHAS, escapedSearchUri);
+    MsgEscapeString(nsDependentCString(aSearchUri), nsINetUtil::ESCAPE_XALPHAS,
+                    escapedSearchUri);
     urlSpec.Append(escapedSearchUri);
     rv = mailNewsUrl->SetSpecInternal(urlSpec);
     if (NS_SUCCEEDED(rv))
       rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, nullptr);
   }
   return rv;
 }
 
 // just a helper method to break down imap message URIs....
 nsresult nsImapService::DecomposeImapURI(const nsACString &aMessageURI,
                                          nsIMsgFolder **aFolder,
-                                         nsACString &aMsgKey)
-{
+                                         nsACString &aMsgKey) {
   nsMsgKey msgKey;
   nsresult rv = DecomposeImapURI(aMessageURI, aFolder, &msgKey);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (msgKey)
-  {
+  if (msgKey) {
     nsAutoCString messageIdString;
     messageIdString.AppendInt(msgKey);
     aMsgKey = messageIdString;
   }
 
   return rv;
 }
 
 // just a helper method to break down imap message URIs....
 nsresult nsImapService::DecomposeImapURI(const nsACString &aMessageURI,
                                          nsIMsgFolder **aFolder,
-                                         nsMsgKey *aMsgKey)
-{
+                                         nsMsgKey *aMsgKey) {
   NS_ENSURE_ARG_POINTER(aFolder);
   NS_ENSURE_ARG_POINTER(aMsgKey);
 
   nsAutoCString folderURI;
   nsresult rv = nsParseImapMessageURI(PromiseFlatCString(aMessageURI).get(),
                                       folderURI, aMsgKey, nullptr);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIMsgFolder> folder;
   rv = GetOrCreateFolder(folderURI, aFolder);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::SaveMessageToDisk(const char *aMessageURI,
-                                               nsIFile *aFile,
-                                               bool aAddDummyEnvelope,
-                                               nsIUrlListener *aUrlListener,
-                                               nsIURI **aURL,
-                                               bool canonicalLineEnding,
-                                               nsIMsgWindow *aMsgWindow)
-{
+NS_IMETHODIMP nsImapService::SaveMessageToDisk(
+    const char *aMessageURI, nsIFile *aFile, bool aAddDummyEnvelope,
+    nsIUrlListener *aUrlListener, nsIURI **aURL, bool canonicalLineEnding,
+    nsIMsgWindow *aMsgWindow) {
   nsCOMPtr<nsIMsgFolder> folder;
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString msgKey;
 
   nsresult rv = DecomposeImapURI(nsDependentCString(aMessageURI),
                                  getter_AddRefs(folder), msgKey);
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool hasMsgOffline = false;
 
   if (folder)
     folder->HasMsgOffline(strtoul(msgKey.get(), nullptr, 10), &hasMsgOffline);
 
   nsAutoCString urlSpec;
   char hierarchyDelimiter = GetHierarchyDelimiter(folder);
-  rv = CreateStartOfImapUrl(nsDependentCString(aMessageURI), getter_AddRefs(imapUrl),
-                            folder, aUrlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv))
-  {
-    nsCOMPtr<nsIImapMessageSink> imapMessageSink(do_QueryInterface(folder, &rv));
+  rv = CreateStartOfImapUrl(nsDependentCString(aMessageURI),
+                            getter_AddRefs(imapUrl), folder, aUrlListener,
+                            urlSpec, hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv)) {
+    nsCOMPtr<nsIImapMessageSink> imapMessageSink(
+        do_QueryInterface(folder, &rv));
     NS_ENSURE_SUCCESS(rv, rv);
     nsCOMPtr<nsIMsgMessageUrl> msgUrl = do_QueryInterface(imapUrl, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
     msgUrl->SetMessageFile(aFile);
     msgUrl->SetAddDummyEnvelope(aAddDummyEnvelope);
     msgUrl->SetCanonicalLineEnding(canonicalLineEnding);
 
-    nsCOMPtr <nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(msgUrl);
-    if (mailnewsUrl)
-      mailnewsUrl->SetMsgIsInLocalCache(hasMsgOffline);
-
-    nsCOMPtr <nsIStreamListener> saveAsListener;
-    mailnewsUrl->GetSaveAsListener(aAddDummyEnvelope, aFile, getter_AddRefs(saveAsListener));
-
-    return FetchMessage(imapUrl, nsIImapUrl::nsImapSaveMessageToDisk, folder, imapMessageSink,
-                        aMsgWindow, saveAsListener, msgKey, false, EmptyCString(), aURL);
+    nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(msgUrl);
+    if (mailnewsUrl) mailnewsUrl->SetMsgIsInLocalCache(hasMsgOffline);
+
+    nsCOMPtr<nsIStreamListener> saveAsListener;
+    mailnewsUrl->GetSaveAsListener(aAddDummyEnvelope, aFile,
+                                   getter_AddRefs(saveAsListener));
+
+    return FetchMessage(imapUrl, nsIImapUrl::nsImapSaveMessageToDisk, folder,
+                        imapMessageSink, aMsgWindow, saveAsListener, msgKey,
+                        false, EmptyCString(), aURL);
   }
   return rv;
 }
 
 /* fetching RFC822 messages */
 /* imap4://HOST>fetch><UID>>MAILBOXPATH>x */
 /*   'x' is the message UID */
 /* will set the 'SEEN' flag */
-NS_IMETHODIMP nsImapService::AddImapFetchToUrl(nsIMsgMailNewsUrl *aUrl,
-                                               nsIMsgFolder *aImapMailFolder,
-                                               const nsACString &aMessageIdentifierList,
-                                               const nsACString &aAdditionalHeader)
-{
+NS_IMETHODIMP nsImapService::AddImapFetchToUrl(
+    nsIMsgMailNewsUrl *aUrl, nsIMsgFolder *aImapMailFolder,
+    const nsACString &aMessageIdentifierList,
+    const nsACString &aAdditionalHeader) {
   NS_ENSURE_ARG_POINTER(aUrl);
 
   nsAutoCString urlSpec;
   nsresult rv = aUrl->GetSpec(urlSpec);
   NS_ENSURE_SUCCESS(rv, rv);
 
   char hierarchyDelimiter = GetHierarchyDelimiter(aImapMailFolder);
 
@@ -962,256 +912,234 @@ NS_IMETHODIMP nsImapService::AddImapFetc
 
   nsAutoCString folderName;
   GetFolderName(aImapMailFolder, folderName);
   urlSpec.Append(folderName);
 
   urlSpec.Append('>');
   urlSpec.Append(aMessageIdentifierList);
 
-  if (!aAdditionalHeader.IsEmpty())
-  {
+  if (!aAdditionalHeader.IsEmpty()) {
     urlSpec.AppendLiteral("?header=");
     urlSpec.Append(aAdditionalHeader);
   }
 
   return aUrl->SetSpecInternal(urlSpec);
 }
 
-NS_IMETHODIMP nsImapService::FetchMessage(nsIImapUrl *aImapUrl,
-                                          nsImapAction aImapAction,
-                                          nsIMsgFolder *aImapMailFolder,
-                                          nsIImapMessageSink *aImapMessage,
-                                          nsIMsgWindow *aMsgWindow,
-                                          nsISupports *aDisplayConsumer,
-                                          const nsACString &messageIdentifierList,
-                                          bool aConvertDataToText,
-                                          const nsACString &aAdditionalHeader,
-                                          nsIURI **aURL)
-{
+NS_IMETHODIMP nsImapService::FetchMessage(
+    nsIImapUrl *aImapUrl, nsImapAction aImapAction,
+    nsIMsgFolder *aImapMailFolder, nsIImapMessageSink *aImapMessage,
+    nsIMsgWindow *aMsgWindow, nsISupports *aDisplayConsumer,
+    const nsACString &messageIdentifierList, bool aConvertDataToText,
+    const nsACString &aAdditionalHeader, nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapUrl);
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
   NS_ENSURE_ARG_POINTER(aImapMessage);
 
   nsresult rv;
   nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(aImapUrl);
 
-  rv = AddImapFetchToUrl(mailnewsurl, aImapMailFolder, messageIdentifierList, aAdditionalHeader);
+  rv = AddImapFetchToUrl(mailnewsurl, aImapMailFolder, messageIdentifierList,
+                         aAdditionalHeader);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (WeAreOffline())
-  {
+  if (WeAreOffline()) {
     bool msgIsInCache = false;
     nsCOMPtr<nsIMsgMailNewsUrl> msgUrl(do_QueryInterface(aImapUrl));
     msgUrl->GetMsgIsInLocalCache(&msgIsInCache);
     if (!msgIsInCache)
       IsMsgInMemCache(mailnewsurl, aImapMailFolder, &msgIsInCache);
 
-    // Display the "offline" message if we didn't find it in the memory cache either
-    if (!msgIsInCache)
-    {
+    // Display the "offline" message if we didn't find it in the memory cache
+    // either
+    if (!msgIsInCache) {
       nsCOMPtr<nsIMsgIncomingServer> server;
       rv = aImapMailFolder->GetServer(getter_AddRefs(server));
       if (server && aDisplayConsumer)
         rv = server->DisplayOfflineMsg(aMsgWindow);
       return rv;
     }
   }
 
-  if (aURL)
-    mailnewsurl.forget(aURL);
+  if (aURL) mailnewsurl.forget(aURL);
 
   return GetMessageFromUrl(aImapUrl, aImapAction, aImapMailFolder, aImapMessage,
-                           aMsgWindow, aDisplayConsumer, aConvertDataToText, aURL);
+                           aMsgWindow, aDisplayConsumer, aConvertDataToText,
+                           aURL);
 }
 
-nsresult nsImapService::GetMessageFromUrl(nsIImapUrl *aImapUrl,
-                                          nsImapAction aImapAction,
-                                          nsIMsgFolder *aImapMailFolder,
-                                          nsIImapMessageSink *aImapMessage,
-                                          nsIMsgWindow *aMsgWindow,
-                                          nsISupports *aDisplayConsumer,
-                                          bool aConvertDataToText,
-                                          nsIURI **aURL)
-{
+nsresult nsImapService::GetMessageFromUrl(
+    nsIImapUrl *aImapUrl, nsImapAction aImapAction,
+    nsIMsgFolder *aImapMailFolder, nsIImapMessageSink *aImapMessage,
+    nsIMsgWindow *aMsgWindow, nsISupports *aDisplayConsumer,
+    bool aConvertDataToText, nsIURI **aURL) {
   nsresult rv = SetImapUrlSink(aImapMailFolder, aImapUrl);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = aImapUrl->SetImapMessageSink(aImapMessage);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = aImapUrl->SetImapAction(aImapAction);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIURI> url(do_QueryInterface(aImapUrl));
 
-  // if the display consumer is a docshell, then we should run the url in the docshell.
-  // otherwise, it should be a stream listener....so open a channel using AsyncRead
-  // and the provided stream listener....
+  // if the display consumer is a docshell, then we should run the url in the
+  // docshell. otherwise, it should be a stream listener....so open a channel
+  // using AsyncRead and the provided stream listener....
 
   nsCOMPtr<nsIDocShell> docShell(do_QueryInterface(aDisplayConsumer, &rv));
-  if (aImapMailFolder && docShell)
-  {
+  if (aImapMailFolder && docShell) {
     nsCOMPtr<nsIMsgIncomingServer> aMsgIncomingServer;
     rv = aImapMailFolder->GetServer(getter_AddRefs(aMsgIncomingServer));
-    if (NS_SUCCEEDED(rv) && aMsgIncomingServer)
-    {
+    if (NS_SUCCEEDED(rv) && aMsgIncomingServer) {
       bool interrupted;
-      nsCOMPtr<nsIImapIncomingServer>
-        aImapServer(do_QueryInterface(aMsgIncomingServer, &rv));
+      nsCOMPtr<nsIImapIncomingServer> aImapServer(
+          do_QueryInterface(aMsgIncomingServer, &rv));
       if (NS_SUCCEEDED(rv) && aImapServer)
-        aImapServer->PseudoInterruptMsgLoad(aImapMailFolder, aMsgWindow, &interrupted);
+        aImapServer->PseudoInterruptMsgLoad(aImapMailFolder, aMsgWindow,
+                                            &interrupted);
     }
   }
-  if (NS_SUCCEEDED(rv) && docShell)
-  {
-    NS_ASSERTION(!aConvertDataToText, "can't convert to text when using docshell");
+  if (NS_SUCCEEDED(rv) && docShell) {
+    NS_ASSERTION(!aConvertDataToText,
+                 "can't convert to text when using docshell");
     RefPtr<nsDocShellLoadState> loadState = new nsDocShellLoadState(url);
     loadState->SetLoadFlags(nsIWebNavigation::LOAD_FLAGS_NONE);
     loadState->SetFirstParty(false);
     loadState->SetTriggeringPrincipal(nsContentUtils::GetSystemPrincipal());
     rv = docShell->LoadURI(loadState);
-  }
-  else
-  {
-    nsCOMPtr<nsIStreamListener> streamListener = do_QueryInterface(aDisplayConsumer, &rv);
+  } else {
+    nsCOMPtr<nsIStreamListener> streamListener =
+        do_QueryInterface(aDisplayConsumer, &rv);
     nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(aImapUrl, &rv);
-    if (aMsgWindow && mailnewsUrl)
-      mailnewsUrl->SetMsgWindow(aMsgWindow);
-    if (NS_SUCCEEDED(rv) && streamListener)
-    {
+    if (aMsgWindow && mailnewsUrl) mailnewsUrl->SetMsgWindow(aMsgWindow);
+    if (NS_SUCCEEDED(rv) && streamListener) {
       nsCOMPtr<nsIChannel> channel;
       nsCOMPtr<nsILoadGroup> loadGroup;
       if (NS_SUCCEEDED(rv) && mailnewsUrl)
         mailnewsUrl->GetLoadGroup(getter_AddRefs(loadGroup));
 
       nsCOMPtr<nsILoadInfo> loadInfo = new mozilla::net::LoadInfo(
-        nsContentUtils::GetSystemPrincipal(),
-        nullptr,
-        nullptr,
-        nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
-        nsIContentPolicy::TYPE_OTHER);
+          nsContentUtils::GetSystemPrincipal(), nullptr, nullptr,
+          nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
+          nsIContentPolicy::TYPE_OTHER);
       rv = NewChannel(url, loadInfo, getter_AddRefs(channel));
       NS_ENSURE_SUCCESS(rv, rv);
 
-      // we need a load group to hold onto the channel. When the request is finished,
-      // it'll get removed from the load group, and the channel will go away,
-      // which will free the load group.
-      if (!loadGroup)
-        loadGroup = do_CreateInstance(NS_LOADGROUP_CONTRACTID);
+      // we need a load group to hold onto the channel. When the request is
+      // finished, it'll get removed from the load group, and the channel will
+      // go away, which will free the load group.
+      if (!loadGroup) loadGroup = do_CreateInstance(NS_LOADGROUP_CONTRACTID);
 
       rv = channel->SetLoadGroup(loadGroup);
       NS_ENSURE_SUCCESS(rv, rv);
 
-      if (aConvertDataToText)
-      {
+      if (aConvertDataToText) {
         nsCOMPtr<nsIStreamListener> conversionListener;
-        nsCOMPtr<nsIStreamConverterService> streamConverter = do_GetService("@mozilla.org/streamConverters;1", &rv);
+        nsCOMPtr<nsIStreamConverterService> streamConverter =
+            do_GetService("@mozilla.org/streamConverters;1", &rv);
         NS_ENSURE_SUCCESS(rv, rv);
-        rv = streamConverter->AsyncConvertData("message/rfc822",
-                                               "*/*", streamListener, channel, getter_AddRefs(conversionListener));
+        rv = streamConverter->AsyncConvertData(
+            "message/rfc822", "*/*", streamListener, channel,
+            getter_AddRefs(conversionListener));
         NS_ENSURE_SUCCESS(rv, rv);
-        streamListener = conversionListener; // this is our new listener.
+        streamListener = conversionListener;  // this is our new listener.
       }
 
-      //  now try to open the channel passing in our display consumer as the listener
+      //  now try to open the channel passing in our display consumer as the
+      //  listener
       rv = channel->AsyncOpen(streamListener);
-    }
-    else // do what we used to do before
+    } else  // do what we used to do before
     {
-      // I'd like to get rid of this code as I believe that we always get a docshell
-      // or stream listener passed into us in this method but i'm not sure yet...
-      // I'm going to use an assert for now to figure out if this is ever getting called
+      // I'd like to get rid of this code as I believe that we always get a
+      // docshell or stream listener passed into us in this method but i'm not
+      // sure yet... I'm going to use an assert for now to figure out if this is
+      // ever getting called
 #if defined(DEBUG_mscott) || defined(DEBUG_bienvenu)
       NS_ERROR("oops...someone still is reaching this part of the code");
 #endif
-      rv = GetImapConnectionAndLoadUrl(aImapUrl,
-                                       aDisplayConsumer, aURL);
+      rv = GetImapConnectionAndLoadUrl(aImapUrl, aDisplayConsumer, aURL);
     }
   }
   return rv;
 }
 
-// this method streams a message to the passed in consumer, with an optional stream converter
-// and additional header (e.g., "header=filter")
-NS_IMETHODIMP nsImapService::StreamMessage(const char *aMessageURI,
-                                           nsISupports *aConsumer,
-                                           nsIMsgWindow *aMsgWindow,
-                                           nsIUrlListener *aUrlListener,
-                                           bool aConvertData,
-                                           const nsACString &aAdditionalHeader,
-                                           bool aLocalOnly,
-                                           nsIURI **aURL)
-{
+// this method streams a message to the passed in consumer, with an optional
+// stream converter and additional header (e.g., "header=filter")
+NS_IMETHODIMP nsImapService::StreamMessage(
+    const char *aMessageURI, nsISupports *aConsumer, nsIMsgWindow *aMsgWindow,
+    nsIUrlListener *aUrlListener, bool aConvertData,
+    const nsACString &aAdditionalHeader, bool aLocalOnly, nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aMessageURI);
 
   nsCOMPtr<nsIMsgFolder> folder;
   nsAutoCString msgKey;
   nsAutoCString mimePart;
   nsAutoCString folderURI;
   nsMsgKey key;
 
-  nsresult rv = DecomposeImapURI(nsDependentCString(aMessageURI), getter_AddRefs(folder), msgKey);
+  nsresult rv = DecomposeImapURI(nsDependentCString(aMessageURI),
+                                 getter_AddRefs(folder), msgKey);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (msgKey.IsEmpty())
-    return NS_MSG_MESSAGE_NOT_FOUND;
-  rv = nsParseImapMessageURI(aMessageURI, folderURI, &key, getter_Copies(mimePart));
-  if (NS_SUCCEEDED(rv))
-  {
-    nsCOMPtr<nsIImapMessageSink> imapMessageSink(do_QueryInterface(folder, &rv));
-    if (NS_SUCCEEDED(rv))
-    {
+  if (msgKey.IsEmpty()) return NS_MSG_MESSAGE_NOT_FOUND;
+  rv = nsParseImapMessageURI(aMessageURI, folderURI, &key,
+                             getter_Copies(mimePart));
+  if (NS_SUCCEEDED(rv)) {
+    nsCOMPtr<nsIImapMessageSink> imapMessageSink(
+        do_QueryInterface(folder, &rv));
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIImapUrl> imapUrl;
       nsAutoCString urlSpec;
       char hierarchyDelimiter = GetHierarchyDelimiter(folder);
-      rv = CreateStartOfImapUrl(nsDependentCString(aMessageURI), getter_AddRefs(imapUrl),
-                                folder, aUrlListener, urlSpec, hierarchyDelimiter);
+      rv = CreateStartOfImapUrl(nsDependentCString(aMessageURI),
+                                getter_AddRefs(imapUrl), folder, aUrlListener,
+                                urlSpec, hierarchyDelimiter);
       NS_ENSURE_SUCCESS(rv, rv);
       nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl(do_QueryInterface(imapUrl));
 
       // This option is used by the JS Mime Emitter, in case we want a cheap
       // streaming, for example, if we just want a quick look at some header,
       // without having to download all the attachments...
 
       uint32_t messageSize = 0;
       imapMessageSink->GetMessageSizeFromDB(msgKey.get(), &messageSize);
       nsAutoCString additionalHeader(aAdditionalHeader);
       bool fetchOnDemand =
-        additionalHeader.Find("&fetchCompleteMessage=false") != kNotFound &&
-          messageSize > (uint32_t) gMIMEOnDemandThreshold;
+          additionalHeader.Find("&fetchCompleteMessage=false") != kNotFound &&
+          messageSize > (uint32_t)gMIMEOnDemandThreshold;
       imapUrl->SetFetchPartsOnDemand(fetchOnDemand);
 
-      // We need to add the fetch command here for the cache lookup to behave correctly
+      // We need to add the fetch command here for the cache lookup to behave
+      // correctly
       rv = AddImapFetchToUrl(mailnewsurl, folder, msgKey, additionalHeader);
       NS_ENSURE_SUCCESS(rv, rv);
 
       nsCOMPtr<nsIMsgIncomingServer> aMsgIncomingServer;
 
       mailnewsurl->SetMsgWindow(aMsgWindow);
       rv = mailnewsurl->GetServer(getter_AddRefs(aMsgIncomingServer));
 
       // Try to check if the message is offline
       bool hasMsgOffline = false;
       folder->HasMsgOffline(key, &hasMsgOffline);
       mailnewsurl->SetMsgIsInLocalCache(hasMsgOffline);
       imapUrl->SetLocalFetchOnly(aLocalOnly);
 
-      // If we don't have the message available locally, and we can't get it over
-      // the network, return with an error
-      if (aLocalOnly || WeAreOffline())
-      {
+      // If we don't have the message available locally, and we can't get it
+      // over the network, return with an error
+      if (aLocalOnly || WeAreOffline()) {
         bool isMsgInMemCache = false;
-        if (!hasMsgOffline)
-        {
+        if (!hasMsgOffline) {
           rv = IsMsgInMemCache(mailnewsurl, folder, &isMsgInMemCache);
           NS_ENSURE_SUCCESS(rv, rv);
 
-          if (!isMsgInMemCache)
-            return NS_ERROR_FAILURE;
+          if (!isMsgInMemCache) return NS_ERROR_FAILURE;
         }
       }
 
       bool shouldStoreMsgOffline = false;
       folder->ShouldStoreMsgOffline(key, &shouldStoreMsgOffline);
       imapUrl->SetStoreResultsOffline(shouldStoreMsgOffline);
       rv = GetMessageFromUrl(imapUrl, nsIImapUrl::nsImapMsgFetchPeek, folder,
                              imapMessageSink, aMsgWindow, aConsumer,
@@ -1220,64 +1148,58 @@ NS_IMETHODIMP nsImapService::StreamMessa
   }
   return rv;
 }
 
 // this method streams a message's headers to the passed in consumer.
 NS_IMETHODIMP nsImapService::StreamHeaders(const char *aMessageURI,
                                            nsIStreamListener *aConsumer,
                                            nsIUrlListener *aUrlListener,
-                                           bool aLocalOnly,
-                                           nsIURI **aURL)
-{
+                                           bool aLocalOnly, nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aMessageURI);
   NS_ENSURE_ARG_POINTER(aConsumer);
   nsCOMPtr<nsIMsgFolder> folder;
   nsAutoCString msgKey;
   nsAutoCString folderURI;
   nsCString mimePart;
   nsMsgKey key;
 
-  nsresult rv = DecomposeImapURI(nsDependentCString(aMessageURI), getter_AddRefs(folder), msgKey);
+  nsresult rv = DecomposeImapURI(nsDependentCString(aMessageURI),
+                                 getter_AddRefs(folder), msgKey);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (msgKey.IsEmpty())
-    return NS_MSG_MESSAGE_NOT_FOUND;
-  rv = nsParseImapMessageURI(aMessageURI, folderURI, &key, getter_Copies(mimePart));
-  if (NS_SUCCEEDED(rv))
-  {
+  if (msgKey.IsEmpty()) return NS_MSG_MESSAGE_NOT_FOUND;
+  rv = nsParseImapMessageURI(aMessageURI, folderURI, &key,
+                             getter_Copies(mimePart));
+  if (NS_SUCCEEDED(rv)) {
     nsCOMPtr<nsIInputStream> inputStream;
     bool hasMsgOffline = false;
     folder->HasMsgOffline(key, &hasMsgOffline);
-    if (hasMsgOffline)
-    {
+    if (hasMsgOffline) {
       int64_t messageOffset;
       uint32_t messageSize;
-      folder->GetOfflineFileStream(key, &messageOffset, &messageSize, getter_AddRefs(inputStream));
-      if (inputStream)
-        return MsgStreamMsgHeaders(inputStream, aConsumer);
+      folder->GetOfflineFileStream(key, &messageOffset, &messageSize,
+                                   getter_AddRefs(inputStream));
+      if (inputStream) return MsgStreamMsgHeaders(inputStream, aConsumer);
     }
   }
 
-  if (aLocalOnly)
-    return NS_ERROR_FAILURE;
+  if (aLocalOnly) return NS_ERROR_FAILURE;
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::IsMsgInMemCache(nsIURI *aUrl,
                                              nsIMsgFolder *aImapMailFolder,
-                                             bool *aResult)
-{
+                                             bool *aResult) {
   NS_ENSURE_ARG_POINTER(aUrl);
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
   *aResult = false;
 
   // Poke around in the memory cache
-  if (mCacheStorage)
-  {
+  if (mCacheStorage) {
     nsAutoCString urlSpec;
     aUrl->GetSpec(urlSpec);
 
     // Strip any query qualifiers.
     bool truncated = false;
     int32_t ind = urlSpec.FindChar('?');
     if (ind != kNotFound) {
       urlSpec.SetLength(ind);
@@ -1285,17 +1207,18 @@ NS_IMETHODIMP nsImapService::IsMsgInMemC
     }
     ind = urlSpec.Find("/;");
     if (ind != kNotFound) {
       urlSpec.SetLength(ind);
       truncated = true;
     }
 
     nsresult rv;
-    nsCOMPtr<nsIImapMailFolderSink> folderSink(do_QueryInterface(aImapMailFolder, &rv));
+    nsCOMPtr<nsIImapMailFolderSink> folderSink(
+        do_QueryInterface(aImapMailFolder, &rv));
     NS_ENSURE_SUCCESS(rv, rv);
 
     int32_t uidValidity = -1;
     folderSink->GetUidValidity(&uidValidity);
     // stick the uid validity in front of the url, so that if the uid validity
     // changes, we won't re-use the wrong cache entries.
     nsAutoCString extension;
     extension.AppendInt(uidValidity, 16);
@@ -1317,45 +1240,42 @@ NS_IMETHODIMP nsImapService::IsMsgInMemC
   return NS_OK;
 }
 
 nsresult nsImapService::CreateStartOfImapUrl(const nsACString &aImapURI,
                                              nsIImapUrl **imapUrl,
                                              nsIMsgFolder *aImapMailFolder,
                                              nsIUrlListener *aUrlListener,
                                              nsACString &urlSpec,
-                                             char &hierarchyDelimiter)
-{
+                                             char &hierarchyDelimiter) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   nsCString hostname;
   nsCString username;
   nsCString escapedUsername;
 
   nsresult rv = aImapMailFolder->GetHostname(hostname);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = aImapMailFolder->GetUsername(username);
   NS_ENSURE_SUCCESS(rv, rv);
   if (!username.IsEmpty())
     MsgEscapeString(username, nsINetUtil::ESCAPE_XALPHAS, escapedUsername);
 
   int32_t port = nsIImapUrl::DEFAULT_IMAP_PORT;
   nsCOMPtr<nsIMsgIncomingServer> server;
   rv = aImapMailFolder->GetServer(getter_AddRefs(server));
-  if (NS_SUCCEEDED(rv))
-  {
+  if (NS_SUCCEEDED(rv)) {
     server->GetPort(&port);
     if (port == -1 || port == 0) port = nsIImapUrl::DEFAULT_IMAP_PORT;
   }
 
   // now we need to create an imap url to load into the connection. The url
   // needs to represent a select folder action.
   rv = CallCreateInstance(kImapUrlCID, imapUrl);
-  if (NS_SUCCEEDED(rv) && *imapUrl)
-  {
+  if (NS_SUCCEEDED(rv) && *imapUrl) {
     nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(*imapUrl, &rv);
     if (NS_SUCCEEDED(rv) && mailnewsUrl && aUrlListener)
       mailnewsUrl->RegisterListener(aUrlListener);
     nsCOMPtr<nsIMsgMessageUrl> msgurl(do_QueryInterface(*imapUrl));
     (*imapUrl)->SetExternalLinkUrl(false);
     msgurl->SetUri(PromiseFlatCString(aImapURI).get());
 
     urlSpec = "imap://";
@@ -1369,101 +1289,95 @@ nsresult nsImapService::CreateStartOfIma
     urlSpec.Append(portStr);
 
     // *** jefft - force to parse the urlSpec in order to search for
     // the correct incoming server
     rv = mailnewsUrl->SetSpecInternal(urlSpec);
     NS_ENSURE_SUCCESS(rv, rv);
 
     hierarchyDelimiter = kOnlineHierarchySeparatorUnknown;
-    nsCOMPtr <nsIMsgImapMailFolder> imapFolder = do_QueryInterface(aImapMailFolder);
-    if (imapFolder)
-      imapFolder->GetHierarchyDelimiter(&hierarchyDelimiter);
+    nsCOMPtr<nsIMsgImapMailFolder> imapFolder =
+        do_QueryInterface(aImapMailFolder);
+    if (imapFolder) imapFolder->GetHierarchyDelimiter(&hierarchyDelimiter);
   }
   return rv;
 }
 
 /* fetching the headers of RFC822 messages */
 /* imap4://HOST>header><UID/SEQUENCE>>MAILBOXPATH>x */
 /*   'x' is the message UID or sequence number list */
 /* will not affect the 'SEEN' flag */
 NS_IMETHODIMP nsImapService::GetHeaders(nsIMsgFolder *aImapMailFolder,
                                         nsIUrlListener *aUrlListener,
                                         nsIURI **aURL,
                                         const nsACString &messageIdentifierList,
-                                        bool messageIdsAreUID)
-{
+                                        bool messageIdsAreUID) {
   // create a protocol instance to handle the request.
-  // NOTE: once we start working with multiple connections, this step will be much more complicated...but for now
-  // just create a connection and process the request.
+  // NOTE: once we start working with multiple connections, this step will be
+  // much more complicated...but for now just create a connection and process
+  // the request.
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
   char hierarchyDelimiter = GetHierarchyDelimiter(aImapMailFolder);
 
-  nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aImapMailFolder,
-                                     aUrlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
+                                     aImapMailFolder, aUrlListener, urlSpec,
+                                     hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(imapUrl);
 
     rv = imapUrl->SetImapAction(nsIImapUrl::nsImapMsgFetch);
     rv = SetImapUrlSink(aImapMailFolder, imapUrl);
 
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       urlSpec.AppendLiteral("/header>");
       urlSpec.Append(messageIdsAreUID ? uidString : sequenceString);
       urlSpec.Append('>');
-      urlSpec.Append(char (hierarchyDelimiter));
+      urlSpec.Append(char(hierarchyDelimiter));
 
       nsCString folderName;
 
       GetFolderName(aImapMailFolder, folderName);
       urlSpec.Append(folderName);
       urlSpec.Append('>');
       urlSpec.Append(messageIdentifierList);
       rv = mailnewsUrl->SetSpecInternal(urlSpec);
 
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, aURL);
     }
   }
   return rv;
 }
 
-
 /* peeking at the start of msg bodies */
 /* imap4://HOST>header><UID>>MAILBOXPATH>x>n */
 /*   'x' is the message UID */
 /*   'n' is the number of bytes to fetch */
 /* will not affect the 'SEEN' flag */
-NS_IMETHODIMP nsImapService::GetBodyStart(nsIMsgFolder *aImapMailFolder,
-                                          nsIUrlListener *aUrlListener,
-                                          const nsACString &messageIdentifierList,
-                                          int32_t numBytes,
-                                          nsIURI **aURL)
-{
+NS_IMETHODIMP nsImapService::GetBodyStart(
+    nsIMsgFolder *aImapMailFolder, nsIUrlListener *aUrlListener,
+    const nsACString &messageIdentifierList, int32_t numBytes, nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   nsresult rv;
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(aImapMailFolder);
-  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aImapMailFolder,
-    aUrlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
+                            aImapMailFolder, aUrlListener, urlSpec,
+                            hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     rv = imapUrl->SetImapAction(nsIImapUrl::nsImapMsgPreview);
     rv = SetImapUrlSink(aImapMailFolder, imapUrl);
 
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(imapUrl);
 
       urlSpec.AppendLiteral("/previewBody>");
       urlSpec.Append(uidString);
       urlSpec.Append('>');
       urlSpec.Append(hierarchyDelimiter);
 
       nsCString folderName;
@@ -1480,136 +1394,121 @@ NS_IMETHODIMP nsImapService::GetBodyStar
   }
   return rv;
 }
 
 nsresult nsImapService::FolderCommand(nsIMsgFolder *imapMailFolder,
                                       nsIUrlListener *urlListener,
                                       const char *aCommand,
                                       nsImapAction imapAction,
-                                      nsIMsgWindow *msgWindow,
-                                      nsIURI **url)
-{
+                                      nsIMsgWindow *msgWindow, nsIURI **url) {
   NS_ENSURE_ARG_POINTER(imapMailFolder);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(imapMailFolder);
   nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
-                                     imapMailFolder, urlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+                                     imapMailFolder, urlListener, urlSpec,
+                                     hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     rv = imapUrl->SetImapAction(imapAction);
     rv = SetImapUrlSink(imapMailFolder, imapUrl);
     nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(imapUrl);
-    if (mailnewsurl)
-      mailnewsurl->SetMsgWindow(msgWindow);
-
-    if (NS_SUCCEEDED(rv))
-    {
+    if (mailnewsurl) mailnewsurl->SetMsgWindow(msgWindow);
+
+    if (NS_SUCCEEDED(rv)) {
       urlSpec.Append(aCommand);
       urlSpec.Append(hierarchyDelimiter);
 
       nsCString folderName;
       GetFolderName(imapMailFolder, folderName);
       urlSpec.Append(folderName);
       rv = mailnewsurl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, url);
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP
 nsImapService::VerifyLogon(nsIMsgFolder *aFolder, nsIUrlListener *aUrlListener,
-                           nsIMsgWindow *aMsgWindow, nsIURI **aURL)
-{
+                           nsIMsgWindow *aMsgWindow, nsIURI **aURL) {
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
 
-  char delimiter = '/'; // shouldn't matter what is is.
-  nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aFolder,
-                                     aUrlListener, urlSpec, delimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  char delimiter = '/';  // shouldn't matter what is is.
+  nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
+                                     aFolder, aUrlListener, urlSpec, delimiter);
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(imapUrl);
 
     nsCOMPtr<nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
     mailNewsUrl->SetSuppressErrorMsgs(true);
     mailNewsUrl->SetMsgWindow(aMsgWindow);
     rv = SetImapUrlSink(aFolder, imapUrl);
     urlSpec.AppendLiteral("/verifyLogon");
     rv = mailnewsurl->SetSpecInternal(urlSpec);
     if (NS_SUCCEEDED(rv))
       rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, nullptr);
-    if (aURL)
-      mailnewsurl.forget(aURL);
+    if (aURL) mailnewsurl.forget(aURL);
   }
   return rv;
 }
 
 // Noop, used to update a folder (causes server to send changes).
 NS_IMETHODIMP nsImapService::Noop(nsIMsgFolder *aImapMailFolder,
-                                  nsIUrlListener *aUrlListener,
-                                  nsIURI **aURL)
-{
+                                  nsIUrlListener *aUrlListener, nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
-  return FolderCommand(aImapMailFolder, aUrlListener,
-                       "/selectnoop>", nsIImapUrl::nsImapSelectNoopFolder, nullptr, aURL);
+  return FolderCommand(aImapMailFolder, aUrlListener, "/selectnoop>",
+                       nsIImapUrl::nsImapSelectNoopFolder, nullptr, aURL);
 }
 
 // FolderStatus, used to update message counts
 NS_IMETHODIMP nsImapService::UpdateFolderStatus(nsIMsgFolder *aImapMailFolder,
                                                 nsIUrlListener *aUrlListener,
-                                                nsIURI **aURL)
-{
+                                                nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
-  return FolderCommand(aImapMailFolder, aUrlListener,
-                       "/folderstatus>", nsIImapUrl::nsImapFolderStatus, nullptr, aURL);
+  return FolderCommand(aImapMailFolder, aUrlListener, "/folderstatus>",
+                       nsIImapUrl::nsImapFolderStatus, nullptr, aURL);
 }
 
 // Expunge, used to "compress" an imap folder,removes deleted messages.
 NS_IMETHODIMP nsImapService::Expunge(nsIMsgFolder *aImapMailFolder,
                                      nsIUrlListener *aUrlListener,
-                                     nsIMsgWindow *aMsgWindow,
-                                     nsIURI **aURL)
-{
+                                     nsIMsgWindow *aMsgWindow, nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
-  return FolderCommand(aImapMailFolder, aUrlListener,
-                       "/Expunge>", nsIImapUrl::nsImapExpungeFolder, aMsgWindow, aURL);
+  return FolderCommand(aImapMailFolder, aUrlListener, "/Expunge>",
+                       nsIImapUrl::nsImapExpungeFolder, aMsgWindow, aURL);
 }
 
 /* old-stle biff that doesn't download headers */
 NS_IMETHODIMP nsImapService::Biff(nsIMsgFolder *aImapMailFolder,
-                                  nsIUrlListener *aUrlListener,
-                                  nsIURI **aURL,
-                                  uint32_t uidHighWater)
-{
+                                  nsIUrlListener *aUrlListener, nsIURI **aURL,
+                                  uint32_t uidHighWater) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   // static const char *formatString = "biff>%c%s>%ld";
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(aImapMailFolder);
   nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
-    aImapMailFolder, aUrlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+                                     aImapMailFolder, aUrlListener, urlSpec,
+                                     hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     rv = imapUrl->SetImapAction(nsIImapUrl::nsImapExpungeFolder);
     rv = SetImapUrlSink(aImapMailFolder, imapUrl);
 
     nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(imapUrl);
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       urlSpec.AppendLiteral("/Biff>");
       urlSpec.Append(hierarchyDelimiter);
 
       nsCString folderName;
       GetFolderName(aImapMailFolder, folderName);
       urlSpec.Append(folderName);
       urlSpec.Append('>');
       urlSpec.AppendInt(uidHighWater);
@@ -1619,61 +1518,56 @@ NS_IMETHODIMP nsImapService::Biff(nsIMsg
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::DeleteFolder(nsIMsgFolder *aImapMailFolder,
                                           nsIUrlListener *aUrlListener,
                                           nsIMsgWindow *aMsgWindow,
-                                          nsIURI **aURL)
-{
+                                          nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   // If it's an aol server then use 'deletefolder' url to
   // remove all msgs first and then remove the folder itself.
   bool removeFolderAndMsgs = false;
   nsCOMPtr<nsIMsgIncomingServer> server;
-  if (NS_SUCCEEDED(aImapMailFolder->GetServer(getter_AddRefs(server))) && server)
-  {
-    nsCOMPtr <nsIImapIncomingServer> imapServer = do_QueryInterface(server);
-    if (imapServer)
-      imapServer->GetIsAOLServer(&removeFolderAndMsgs);
+  if (NS_SUCCEEDED(aImapMailFolder->GetServer(getter_AddRefs(server))) &&
+      server) {
+    nsCOMPtr<nsIImapIncomingServer> imapServer = do_QueryInterface(server);
+    if (imapServer) imapServer->GetIsAOLServer(&removeFolderAndMsgs);
   }
 
   return FolderCommand(aImapMailFolder, aUrlListener,
                        removeFolderAndMsgs ? "/deletefolder>" : "/delete>",
                        nsIImapUrl::nsImapDeleteFolder, aMsgWindow, aURL);
 }
 
-NS_IMETHODIMP nsImapService::DeleteMessages(nsIMsgFolder *aImapMailFolder,
-                                            nsIUrlListener *aUrlListener,
-                                            nsIURI **aURL,
-                                            const nsACString &messageIdentifierList,
-                                            bool messageIdsAreUID)
-{
+NS_IMETHODIMP nsImapService::DeleteMessages(
+    nsIMsgFolder *aImapMailFolder, nsIUrlListener *aUrlListener, nsIURI **aURL,
+    const nsACString &messageIdentifierList, bool messageIdsAreUID) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   // create a protocol instance to handle the request.
-  // NOTE: once we start working with multiple connections, this step will be much more complicated...but for now
-  // just create a connection and process the request.
+  // NOTE: once we start working with multiple connections, this step will be
+  // much more complicated...but for now just create a connection and process
+  // the request.
   nsresult rv;
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(aImapMailFolder);
-  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aImapMailFolder,
-    aUrlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
+                            aImapMailFolder, aUrlListener, urlSpec,
+                            hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     rv = imapUrl->SetImapAction(nsIImapUrl::nsImapMsgFetch);
     rv = SetImapUrlSink(aImapMailFolder, imapUrl);
 
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(imapUrl);
 
       urlSpec.AppendLiteral("/deletemsg>");
       urlSpec.Append(messageIdsAreUID ? uidString : sequenceString);
       urlSpec.Append('>');
       urlSpec.Append(hierarchyDelimiter);
 
       nsCString folderName;
@@ -1687,90 +1581,77 @@ NS_IMETHODIMP nsImapService::DeleteMessa
     }
   }
   return rv;
 }
 
 // Delete all messages in a folder, used to empty trash
 NS_IMETHODIMP nsImapService::DeleteAllMessages(nsIMsgFolder *aImapMailFolder,
                                                nsIUrlListener *aUrlListener,
-                                               nsIURI **aURL)
-{
+                                               nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
-  return FolderCommand(aImapMailFolder, aUrlListener,
-                      "/deleteallmsgs>", nsIImapUrl::nsImapSelectNoopFolder, nullptr, aURL);
+  return FolderCommand(aImapMailFolder, aUrlListener, "/deleteallmsgs>",
+                       nsIImapUrl::nsImapSelectNoopFolder, nullptr, aURL);
 }
 
-NS_IMETHODIMP nsImapService::AddMessageFlags(nsIMsgFolder *aImapMailFolder,
-                                             nsIUrlListener *aUrlListener,
-                                             nsIURI **aURL,
-                                             const nsACString &messageIdentifierList,
-                                             imapMessageFlagsType flags,
-                                             bool messageIdsAreUID)
-{
+NS_IMETHODIMP nsImapService::AddMessageFlags(
+    nsIMsgFolder *aImapMailFolder, nsIUrlListener *aUrlListener, nsIURI **aURL,
+    const nsACString &messageIdentifierList, imapMessageFlagsType flags,
+    bool messageIdsAreUID) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   return DiddleFlags(aImapMailFolder, aUrlListener, aURL, messageIdentifierList,
                      "addmsgflags", flags, messageIdsAreUID);
 }
 
-NS_IMETHODIMP nsImapService::SubtractMessageFlags(nsIMsgFolder *aImapMailFolder,
-                                                  nsIUrlListener *aUrlListener,
-                                                  nsIURI **aURL,
-                                                  const nsACString &messageIdentifierList,
-                                                  imapMessageFlagsType flags,
-                                                  bool messageIdsAreUID)
-{
+NS_IMETHODIMP nsImapService::SubtractMessageFlags(
+    nsIMsgFolder *aImapMailFolder, nsIUrlListener *aUrlListener, nsIURI **aURL,
+    const nsACString &messageIdentifierList, imapMessageFlagsType flags,
+    bool messageIdsAreUID) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   return DiddleFlags(aImapMailFolder, aUrlListener, aURL, messageIdentifierList,
                      "subtractmsgflags", flags, messageIdsAreUID);
 }
 
-NS_IMETHODIMP nsImapService::SetMessageFlags(nsIMsgFolder *aImapMailFolder,
-                                             nsIUrlListener *aUrlListener,
-                                             nsIURI **aURL,
-                                             const nsACString &messageIdentifierList,
-                                             imapMessageFlagsType flags,
-                                             bool messageIdsAreUID)
-{
+NS_IMETHODIMP nsImapService::SetMessageFlags(
+    nsIMsgFolder *aImapMailFolder, nsIUrlListener *aUrlListener, nsIURI **aURL,
+    const nsACString &messageIdentifierList, imapMessageFlagsType flags,
+    bool messageIdsAreUID) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   return DiddleFlags(aImapMailFolder, aUrlListener, aURL, messageIdentifierList,
                      "setmsgflags", flags, messageIdsAreUID);
 }
 
 nsresult nsImapService::DiddleFlags(nsIMsgFolder *aImapMailFolder,
-                                    nsIUrlListener *aUrlListener,
-                                    nsIURI **aURL,
+                                    nsIUrlListener *aUrlListener, nsIURI **aURL,
                                     const nsACString &messageIdentifierList,
                                     const char *howToDiddle,
                                     imapMessageFlagsType flags,
-                                    bool messageIdsAreUID)
-{
+                                    bool messageIdsAreUID) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   // create a protocol instance to handle the request.
   // NOTE: once we start working with multiple connections,
   //       this step will be much more complicated...but for now
   // just create a connection and process the request.
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(aImapMailFolder);
   nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
-                                     aImapMailFolder, aUrlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+                                     aImapMailFolder, aUrlListener, urlSpec,
+                                     hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     rv = imapUrl->SetImapAction(nsIImapUrl::nsImapMsgFetch);
     rv = SetImapUrlSink(aImapMailFolder, imapUrl);
 
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(imapUrl);
 
       urlSpec.Append('/');
       urlSpec.Append(howToDiddle);
       urlSpec.Append('>');
       urlSpec.Append(messageIdsAreUID ? uidString : sequenceString);
       urlSpec.Append('>');
       urlSpec.Append(hierarchyDelimiter);
@@ -1784,158 +1665,145 @@ nsresult nsImapService::DiddleFlags(nsIM
       rv = mailnewsurl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, aURL);
     }
   }
   return rv;
 }
 
-nsresult nsImapService::SetImapUrlSink(nsIMsgFolder *aMsgFolder, nsIImapUrl *aImapUrl)
-{
+nsresult nsImapService::SetImapUrlSink(nsIMsgFolder *aMsgFolder,
+                                       nsIImapUrl *aImapUrl) {
   NS_ENSURE_ARG_POINTER(aMsgFolder);
   NS_ENSURE_ARG_POINTER(aImapUrl);
 
   nsresult rv;
   nsCOMPtr<nsIMsgIncomingServer> incomingServer;
   nsCOMPtr<nsIImapServerSink> imapServerSink;
 
   rv = aMsgFolder->GetServer(getter_AddRefs(incomingServer));
-  if (NS_SUCCEEDED(rv) && incomingServer)
-  {
+  if (NS_SUCCEEDED(rv) && incomingServer) {
     imapServerSink = do_QueryInterface(incomingServer);
-    if (imapServerSink)
-      aImapUrl->SetImapServerSink(imapServerSink);
+    if (imapServerSink) aImapUrl->SetImapServerSink(imapServerSink);
   }
 
-  nsCOMPtr<nsIImapMailFolderSink> imapMailFolderSink = do_QueryInterface(aMsgFolder);
+  nsCOMPtr<nsIImapMailFolderSink> imapMailFolderSink =
+      do_QueryInterface(aMsgFolder);
   if (NS_SUCCEEDED(rv) && imapMailFolderSink)
     aImapUrl->SetImapMailFolderSink(imapMailFolderSink);
 
   nsCOMPtr<nsIImapMessageSink> imapMessageSink = do_QueryInterface(aMsgFolder);
   if (NS_SUCCEEDED(rv) && imapMessageSink)
     aImapUrl->SetImapMessageSink(imapMessageSink);
 
-  nsCOMPtr <nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(aImapUrl);
+  nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(aImapUrl);
   mailnewsUrl->SetFolder(aMsgFolder);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP nsImapService::DiscoverAllFolders(nsIMsgFolder *aImapMailFolder,
                                                 nsIUrlListener *aUrlListener,
                                                 nsIMsgWindow *aMsgWindow,
-                                                nsIURI **aURL)
-{
+                                                nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(aImapMailFolder);
-  nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aImapMailFolder,
-                                     aUrlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED (rv))
-  {
+  nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
+                                     aImapMailFolder, aUrlListener, urlSpec,
+                                     hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv)) {
     rv = SetImapUrlSink(aImapMailFolder, imapUrl);
 
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(imapUrl);
       mailnewsurl->SetMsgWindow(aMsgWindow);
       urlSpec.AppendLiteral("/discoverallboxes");
       rv = mailnewsurl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, aURL);
     }
   }
   return rv;
 }
 
-NS_IMETHODIMP nsImapService::DiscoverAllAndSubscribedFolders(nsIMsgFolder *aImapMailFolder,
-                                                             nsIUrlListener *aUrlListener,
-                                                             nsIURI **aURL)
-{
+NS_IMETHODIMP nsImapService::DiscoverAllAndSubscribedFolders(
+    nsIMsgFolder *aImapMailFolder, nsIUrlListener *aUrlListener,
+    nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   nsCOMPtr<nsIImapUrl> aImapUrl;
   nsAutoCString urlSpec;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(aImapMailFolder);
-  nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(aImapUrl), aImapMailFolder,
-                                     aUrlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && aImapUrl)
-  {
+  nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(aImapUrl),
+                                     aImapMailFolder, aUrlListener, urlSpec,
+                                     hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv) && aImapUrl) {
     rv = SetImapUrlSink(aImapMailFolder, aImapUrl);
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(aImapUrl);
       urlSpec.AppendLiteral("/discoverallandsubscribedboxes");
       rv = mailnewsurl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(aImapUrl, nullptr, aURL);
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::DiscoverChildren(nsIMsgFolder *aImapMailFolder,
                                               nsIUrlListener *aUrlListener,
                                               const nsACString &folderPath,
-                                              nsIURI **aURL)
-{
+                                              nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
   nsCOMPtr<nsIImapUrl> aImapUrl;
   nsAutoCString urlSpec;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(aImapMailFolder);
-  nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(aImapUrl), aImapMailFolder,
-                                     aUrlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED (rv))
-  {
+  nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(aImapUrl),
+                                     aImapMailFolder, aUrlListener, urlSpec,
+                                     hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv)) {
     rv = SetImapUrlSink(aImapMailFolder, aImapUrl);
-    if (NS_SUCCEEDED(rv))
-    {
-      if (!folderPath.IsEmpty())
-      {
+    if (NS_SUCCEEDED(rv)) {
+      if (!folderPath.IsEmpty()) {
         nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(aImapUrl);
         urlSpec.AppendLiteral("/discoverchildren>");
         urlSpec.Append(hierarchyDelimiter);
         urlSpec.Append(folderPath);
         rv = mailnewsurl->SetSpecInternal(urlSpec);
 
-        // Make sure the uri has the same hierarchy separator as the one in msg folder
-        // obj if it's not kOnlineHierarchySeparatorUnknown (ie, '^').
+        // Make sure the uri has the same hierarchy separator as the one in msg
+        // folder obj if it's not kOnlineHierarchySeparatorUnknown (ie, '^').
         char uriDelimiter;
         nsresult rv1 = aImapUrl->GetOnlineSubDirSeparator(&uriDelimiter);
-        if (NS_SUCCEEDED (rv1) && hierarchyDelimiter != kOnlineHierarchySeparatorUnknown &&
+        if (NS_SUCCEEDED(rv1) &&
+            hierarchyDelimiter != kOnlineHierarchySeparatorUnknown &&
             uriDelimiter != hierarchyDelimiter)
           aImapUrl->SetOnlineSubDirSeparator(hierarchyDelimiter);
 
         if (NS_SUCCEEDED(rv))
           rv = GetImapConnectionAndLoadUrl(aImapUrl, nullptr, aURL);
-      }
-      else
+      } else
         rv = NS_ERROR_FAILURE;
     }
   }
   return rv;
 }
 
-NS_IMETHODIMP nsImapService::OnlineMessageCopy(nsIMsgFolder *aSrcFolder,
-                                               const nsACString &messageIds,
-                                               nsIMsgFolder *aDstFolder,
-                                               bool idsAreUids,
-                                               bool isMove,
-                                               nsIUrlListener *aUrlListener,
-                                               nsIURI **aURL,
-                                               nsISupports *copyState,
-                                               nsIMsgWindow *aMsgWindow)
-{
+NS_IMETHODIMP nsImapService::OnlineMessageCopy(
+    nsIMsgFolder *aSrcFolder, const nsACString &messageIds,
+    nsIMsgFolder *aDstFolder, bool idsAreUids, bool isMove,
+    nsIUrlListener *aUrlListener, nsIURI **aURL, nsISupports *copyState,
+    nsIMsgWindow *aMsgWindow) {
   NS_ENSURE_ARG_POINTER(aSrcFolder);
   NS_ENSURE_ARG_POINTER(aDstFolder);
 
   nsresult rv;
   nsCOMPtr<nsIMsgIncomingServer> srcServer;
   nsCOMPtr<nsIMsgIncomingServer> dstServer;
 
   rv = aSrcFolder->GetServer(getter_AddRefs(srcServer));
@@ -1943,34 +1811,33 @@ NS_IMETHODIMP nsImapService::OnlineMessa
 
   rv = aDstFolder->GetServer(getter_AddRefs(dstServer));
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool sameServer;
   rv = dstServer->Equals(srcServer, &sameServer);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (!sameServer)
-  {
+  if (!sameServer) {
     NS_ASSERTION(false, "can't use this method to copy across servers");
     // *** can only take message from the same imap host and user accnt
     return NS_ERROR_FAILURE;
   }
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(aSrcFolder);
-  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aSrcFolder, aUrlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv))
-  {
+  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aSrcFolder,
+                            aUrlListener, urlSpec, hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv)) {
     SetImapUrlSink(aSrcFolder, imapUrl);
     imapUrl->SetCopyState(copyState);
 
-    nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl (do_QueryInterface(imapUrl));
+    nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl(do_QueryInterface(imapUrl));
     mailnewsurl->SetMsgWindow(aMsgWindow);
 
     if (isMove)
       urlSpec.AppendLiteral("/onlinemove>");
     else
       urlSpec.AppendLiteral("/onlinecopy>");
     if (idsAreUids)
       urlSpec.Append(uidString);
@@ -1992,166 +1859,154 @@ NS_IMETHODIMP nsImapService::OnlineMessa
 
     rv = mailnewsurl->SetSpecInternal(urlSpec);
     if (NS_SUCCEEDED(rv))
       rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, aURL);
   }
   return rv;
 }
 
-nsresult nsImapService::OfflineAppendFromFile(nsIFile *aFile,
-                                              nsIURI *aUrl,
-                                              nsIMsgFolder* aDstFolder,
-                                              const nsACString &messageId,  // to be replaced
-                                              bool inSelectedState, // needs to be in
-                                              nsIUrlListener *aListener,
-                                              nsIURI **aURL,
-                                              nsISupports *aCopyState)
-{
+nsresult nsImapService::OfflineAppendFromFile(
+    nsIFile *aFile, nsIURI *aUrl, nsIMsgFolder *aDstFolder,
+    const nsACString &messageId,  // to be replaced
+    bool inSelectedState,         // needs to be in
+    nsIUrlListener *aListener, nsIURI **aURL, nsISupports *aCopyState) {
   nsCOMPtr<nsIMsgDatabase> destDB;
   nsresult rv = aDstFolder->GetMsgDatabase(getter_AddRefs(destDB));
   // ### might need to send some notifications instead of just returning
 
   bool isLocked;
   aDstFolder->GetLocked(&isLocked);
-  if (isLocked)
-    return NS_MSG_FOLDER_BUSY;
-
-  if (NS_SUCCEEDED(rv) && destDB)
-  {
+  if (isLocked) return NS_MSG_FOLDER_BUSY;
+
+  if (NS_SUCCEEDED(rv) && destDB) {
     nsMsgKey fakeKey;
     destDB->GetNextFakeOfflineMsgKey(&fakeKey);
 
-    nsCOMPtr <nsIMsgOfflineImapOperation> op;
+    nsCOMPtr<nsIMsgOfflineImapOperation> op;
     rv = destDB->GetOfflineOpForKey(fakeKey, true, getter_AddRefs(op));
-    if (NS_SUCCEEDED(rv) && op)
-    {
+    if (NS_SUCCEEDED(rv) && op) {
       nsCString destFolderUri;
       aDstFolder->GetURI(destFolderUri);
-      op->SetOperation(nsIMsgOfflineImapOperation::kAppendDraft); // ### do we care if it's a template?
+      op->SetOperation(
+          nsIMsgOfflineImapOperation::kAppendDraft);  // ### do we care if it's
+                                                      // a template?
       op->SetDestinationFolderURI(destFolderUri.get());
-      nsCOMPtr <nsIOutputStream> offlineStore;
+      nsCOMPtr<nsIOutputStream> offlineStore;
       nsCOMPtr<nsIMsgPluggableStore> msgStore;
       nsCOMPtr<nsIMsgIncomingServer> dstServer;
       nsCOMPtr<nsIMsgDBHdr> newMsgHdr;
 
       aDstFolder->GetServer(getter_AddRefs(dstServer));
       rv = dstServer->GetMsgStore(getter_AddRefs(msgStore));
       NS_ENSURE_SUCCESS(rv, rv);
       rv = destDB->CreateNewHdr(fakeKey, getter_AddRefs(newMsgHdr));
       NS_ENSURE_SUCCESS(rv, rv);
-      rv = aDstFolder->GetOfflineStoreOutputStream(newMsgHdr, getter_AddRefs(offlineStore));
-
-      if (NS_SUCCEEDED(rv) && offlineStore)
-      {
+      rv = aDstFolder->GetOfflineStoreOutputStream(
+          newMsgHdr, getter_AddRefs(offlineStore));
+
+      if (NS_SUCCEEDED(rv) && offlineStore) {
         int64_t curOfflineStorePos = 0;
-        nsCOMPtr <nsISeekableStream> seekable = do_QueryInterface(offlineStore);
+        nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(offlineStore);
         if (seekable)
           seekable->Tell(&curOfflineStorePos);
-        else
-        {
+        else {
           NS_ERROR("needs to be a random store!");
           return NS_ERROR_FAILURE;
         }
 
-        nsCOMPtr <nsIInputStream> inputStream;
-        nsCOMPtr <nsIMsgParseMailMsgState> msgParser = do_CreateInstance(NS_PARSEMAILMSGSTATE_CONTRACTID, &rv);
+        nsCOMPtr<nsIInputStream> inputStream;
+        nsCOMPtr<nsIMsgParseMailMsgState> msgParser =
+            do_CreateInstance(NS_PARSEMAILMSGSTATE_CONTRACTID, &rv);
         msgParser->SetMailDB(destDB);
 
         rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream), aFile);
-        if (NS_SUCCEEDED(rv) && inputStream)
-        {
+        if (NS_SUCCEEDED(rv) && inputStream) {
           // now, copy the temp file to the offline store for the dest folder.
           RefPtr<nsMsgLineStreamBuffer> inputStreamBuffer =
-            new nsMsgLineStreamBuffer(FILE_IO_BUFFER_SIZE,
-                                      true,    // allocate new lines
-                                      false);  // leave CRLFs on the returned string
+              new nsMsgLineStreamBuffer(
+                  FILE_IO_BUFFER_SIZE,
+                  true,    // allocate new lines
+                  false);  // leave CRLFs on the returned string
           int64_t fileSize;
           aFile->GetFileSize(&fileSize);
           uint32_t bytesWritten;
           rv = NS_OK;
-//        rv = inputStream->Read(inputBuffer, inputBufferSize, &bytesRead);
-//        if (NS_SUCCEEDED(rv) && bytesRead > 0)
+          // rv = inputStream->Read(inputBuffer, inputBufferSize, &bytesRead);
+          // if (NS_SUCCEEDED(rv) && bytesRead > 0)
           msgParser->SetState(nsIMsgParseMailMsgState::ParseHeadersState);
           msgParser->SetNewMsgHdr(newMsgHdr);
           // set the new key to fake key so the msg hdr will have that for a key
           msgParser->SetNewKey(fakeKey);
           bool needMoreData = false;
-          char * newLine = nullptr;
+          char *newLine = nullptr;
           uint32_t numBytesInLine = 0;
-          do
-          {
-            newLine = inputStreamBuffer->ReadNextLine(inputStream, numBytesInLine, needMoreData);
-            if (newLine)
-            {
+          do {
+            newLine = inputStreamBuffer->ReadNextLine(
+                inputStream, numBytesInLine, needMoreData);
+            if (newLine) {
               msgParser->ParseAFolderLine(newLine, numBytesInLine);
               rv = offlineStore->Write(newLine, numBytesInLine, &bytesWritten);
               free(newLine);
             }
           } while (newLine);
           msgParser->FinishHeader();
 
           nsCOMPtr<nsIMsgDBHdr> fakeHdr;
           msgParser->GetNewMsgHdr(getter_AddRefs(fakeHdr));
-          if (fakeHdr)
-          {
-            if (NS_SUCCEEDED(rv) && fakeHdr)
-            {
+          if (fakeHdr) {
+            if (NS_SUCCEEDED(rv) && fakeHdr) {
               uint32_t resultFlags;
               fakeHdr->SetMessageOffset(curOfflineStorePos);
-              fakeHdr->OrFlags(nsMsgMessageFlags::Offline | nsMsgMessageFlags::Read, &resultFlags);
+              fakeHdr->OrFlags(
+                  nsMsgMessageFlags::Offline | nsMsgMessageFlags::Read,
+                  &resultFlags);
               fakeHdr->SetOfflineMessageSize(fileSize);
               destDB->AddNewHdrToDB(fakeHdr, true /* notify */);
               aDstFolder->SetFlag(nsMsgFolderFlags::OfflineEvents);
-              if (msgStore)
-                msgStore->FinishNewMessage(offlineStore, fakeHdr);
+              if (msgStore) msgStore->FinishNewMessage(offlineStore, fakeHdr);
             }
           }
           // tell the listener we're done.
           inputStream->Close();
           inputStream = nullptr;
           aListener->OnStopRunningUrl(aUrl, NS_OK);
         }
         offlineStore->Close();
       }
     }
   }
 
-  if (destDB)
-    destDB->Close(true);
+  if (destDB) destDB->Close(true);
   return rv;
 }
 
 /* append message from file url */
 /* imap://HOST>appendmsgfromfile>DESTINATIONMAILBOXPATH */
 /* imap://HOST>appenddraftfromfile>DESTINATIONMAILBOXPATH>UID>messageId */
-NS_IMETHODIMP nsImapService::AppendMessageFromFile(nsIFile *aFile,
-                                                   nsIMsgFolder *aDstFolder,
-                                                   const nsACString &messageId,  // to be replaced
-                                                   bool idsAreUids,
-                                                   bool inSelectedState,       // needs to be in
-                                                   nsIUrlListener *aListener,
-                                                   nsIURI **aURL,
-                                                   nsISupports *aCopyState,
-                                                   nsIMsgWindow *aMsgWindow)
-{
+NS_IMETHODIMP nsImapService::AppendMessageFromFile(
+    nsIFile *aFile, nsIMsgFolder *aDstFolder,
+    const nsACString &messageId,  // to be replaced
+    bool idsAreUids,
+    bool inSelectedState,  // needs to be in
+    nsIUrlListener *aListener, nsIURI **aURL, nsISupports *aCopyState,
+    nsIMsgWindow *aMsgWindow) {
   NS_ENSURE_ARG_POINTER(aFile);
   NS_ENSURE_ARG_POINTER(aDstFolder);
 
   nsresult rv;
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(aDstFolder);
-  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aDstFolder, aListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv))
-  {
+  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aDstFolder,
+                            aListener, urlSpec, hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv)) {
     nsCOMPtr<nsIMsgMailNewsUrl> msgUrl = do_QueryInterface(imapUrl);
-    if (msgUrl && aMsgWindow)
-    {
+    if (msgUrl && aMsgWindow) {
       // we get the loadGroup from msgWindow
       msgUrl->SetMsgWindow(aMsgWindow);
     }
 
     SetImapUrlSink(aDstFolder, imapUrl);
     imapUrl->SetMsgFile(aFile);
     imapUrl->SetCopyState(aCopyState);
 
@@ -2163,1227 +2018,1129 @@ NS_IMETHODIMP nsImapService::AppendMessa
       urlSpec.AppendLiteral("/appendmsgfromfile>");
 
     urlSpec.Append(hierarchyDelimiter);
 
     nsCString folderName;
     GetFolderName(aDstFolder, folderName);
     urlSpec.Append(folderName);
 
-    if (inSelectedState)
-    {
+    if (inSelectedState) {
       urlSpec.Append('>');
       if (idsAreUids)
         urlSpec.Append(uidString);
       else
         urlSpec.Append(sequenceString);
       urlSpec.Append('>');
-      if (!messageId.IsEmpty())
-        urlSpec.Append(messageId);
+      if (!messageId.IsEmpty()) urlSpec.Append(messageId);
     }
 
     rv = mailnewsurl->SetSpecInternal(urlSpec);
-    if (WeAreOffline())
-    {
+    if (WeAreOffline()) {
       // handle offline append to drafts or templates folder here.
-      return OfflineAppendFromFile(aFile, mailnewsurl, aDstFolder, messageId, inSelectedState, aListener, aURL, aCopyState);
+      return OfflineAppendFromFile(aFile, mailnewsurl, aDstFolder, messageId,
+                                   inSelectedState, aListener, aURL,
+                                   aCopyState);
     }
     if (NS_SUCCEEDED(rv))
       rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, aURL);
   }
   return rv;
 }
 
 nsresult nsImapService::GetImapConnectionAndLoadUrl(nsIImapUrl *aImapUrl,
                                                     nsISupports *aConsumer,
-                                                    nsIURI **aURL)
-{
+                                                    nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapUrl);
 
   bool isValidUrl;
   aImapUrl->GetValidUrl(&isValidUrl);
-  if (!isValidUrl)
-    return NS_ERROR_FAILURE;
-
-  if (WeAreOffline())
-  {
+  if (!isValidUrl) return NS_ERROR_FAILURE;
+
+  if (WeAreOffline()) {
     nsImapAction imapAction;
 
     // the only thing we can do offline is fetch messages.
     // ### TODO - need to look at msg copy, save attachment, etc. when we
     // have offline message bodies.
     aImapUrl->GetImapAction(&imapAction);
-    if (imapAction != nsIImapUrl::nsImapMsgFetch && imapAction != nsIImapUrl::nsImapSaveMessageToDisk)
+    if (imapAction != nsIImapUrl::nsImapMsgFetch &&
+        imapAction != nsIImapUrl::nsImapSaveMessageToDisk)
       return NS_MSG_ERROR_OFFLINE;
   }
 
   nsCOMPtr<nsIMsgIncomingServer> aMsgIncomingServer;
   nsCOMPtr<nsIMsgMailNewsUrl> msgUrl = do_QueryInterface(aImapUrl);
   nsresult rv = msgUrl->GetServer(getter_AddRefs(aMsgIncomingServer));
 
-  if (aURL)
-  {
+  if (aURL) {
     msgUrl.forget(aURL);
   }
 
-  if (NS_SUCCEEDED(rv) && aMsgIncomingServer)
-  {
-    nsCOMPtr<nsIImapIncomingServer> aImapServer(do_QueryInterface(aMsgIncomingServer, &rv));
+  if (NS_SUCCEEDED(rv) && aMsgIncomingServer) {
+    nsCOMPtr<nsIImapIncomingServer> aImapServer(
+        do_QueryInterface(aMsgIncomingServer, &rv));
     if (NS_SUCCEEDED(rv) && aImapServer)
       rv = aImapServer->GetImapConnectionAndLoadUrl(aImapUrl, aConsumer);
   }
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::MoveFolder(nsIMsgFolder *srcFolder,
                                         nsIMsgFolder *dstFolder,
                                         nsIUrlListener *urlListener,
-                                        nsIMsgWindow *msgWindow,
-                                        nsIURI **url)
-{
+                                        nsIMsgWindow *msgWindow, nsIURI **url) {
   NS_ENSURE_ARG_POINTER(srcFolder);
   NS_ENSURE_ARG_POINTER(dstFolder);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
   nsresult rv;
 
   char default_hierarchyDelimiter = GetHierarchyDelimiter(dstFolder);
   rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), dstFolder,
                             urlListener, urlSpec, default_hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     rv = SetImapUrlSink(dstFolder, imapUrl);
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
-      if (mailNewsUrl)
-        mailNewsUrl->SetMsgWindow(msgWindow);
+      if (mailNewsUrl) mailNewsUrl->SetMsgWindow(msgWindow);
       char hierarchyDelimiter = kOnlineHierarchySeparatorUnknown;
       nsCString folderName;
 
       nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(imapUrl);
       GetFolderName(srcFolder, folderName);
       urlSpec.AppendLiteral("/movefolderhierarchy>");
       urlSpec.Append(hierarchyDelimiter);
       urlSpec.Append(folderName);
       urlSpec.Append('>');
       GetFolderName(dstFolder, folderName);
-      if (!folderName.IsEmpty())
-      {
+      if (!folderName.IsEmpty()) {
         urlSpec.Append(hierarchyDelimiter);
         urlSpec.Append(folderName);
       }
       rv = mailnewsurl->SetSpecInternal(urlSpec);
-      if (NS_SUCCEEDED(rv))
-      {
+      if (NS_SUCCEEDED(rv)) {
         GetFolderName(srcFolder, folderName);
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, url);
       }
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::RenameLeaf(nsIMsgFolder *srcFolder,
                                         const nsAString &newLeafName,
                                         nsIUrlListener *urlListener,
-                                        nsIMsgWindow *msgWindow,
-                                        nsIURI **url)
-{
+                                        nsIMsgWindow *msgWindow, nsIURI **url) {
   NS_ENSURE_ARG_POINTER(srcFolder);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(srcFolder);
-  nsresult rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), srcFolder,
-                            urlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv))
-  {
+  nsresult rv =
+      CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), srcFolder,
+                           urlListener, urlSpec, hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv)) {
     rv = SetImapUrlSink(srcFolder, imapUrl);
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
       mailNewsUrl->SetMsgWindow(msgWindow);
       nsCString folderName;
       GetFolderName(srcFolder, folderName);
       urlSpec.AppendLiteral("/rename>");
       urlSpec.Append(hierarchyDelimiter);
       urlSpec.Append(folderName);
       urlSpec.Append('>');
       urlSpec.Append(hierarchyDelimiter);
       nsAutoCString cStrFolderName;
       // Unescape the name before looking for parent path
       MsgUnescapeString(folderName, 0, cStrFolderName);
       int32_t leafNameStart = cStrFolderName.RFindChar(hierarchyDelimiter);
-      if (leafNameStart != -1)
-      {
-        cStrFolderName.SetLength(leafNameStart+1);
+      if (leafNameStart != -1) {
+        cStrFolderName.SetLength(leafNameStart + 1);
         urlSpec.Append(cStrFolderName);
       }
 
       nsAutoCString utfNewName;
       CopyUTF16toMUTF7(PromiseFlatString(newLeafName), utfNewName);
       nsCString escapedNewName;
       MsgEscapeString(utfNewName, nsINetUtil::ESCAPE_URL_PATH, escapedNewName);
       nsCString escapedSlashName;
-      rv = nsImapUrl::EscapeSlashes(escapedNewName.get(), getter_Copies(escapedSlashName));
+      rv = nsImapUrl::EscapeSlashes(escapedNewName.get(),
+                                    getter_Copies(escapedSlashName));
       NS_ENSURE_SUCCESS(rv, rv);
       urlSpec.Append(escapedSlashName);
 
       rv = mailNewsUrl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, url);
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::CreateFolder(nsIMsgFolder *parent,
                                           const nsAString &newFolderName,
                                           nsIUrlListener *urlListener,
-                                          nsIURI **url)
-{
+                                          nsIURI **url) {
   NS_ENSURE_ARG_POINTER(parent);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
   nsresult rv;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(parent);
   rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), parent,
                             urlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     rv = SetImapUrlSink(parent, imapUrl);
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(imapUrl);
 
       nsCString folderName;
       GetFolderName(parent, folderName);
       urlSpec.AppendLiteral("/create>");
       urlSpec.Append(hierarchyDelimiter);
-      if (!folderName.IsEmpty())
-      {
+      if (!folderName.IsEmpty()) {
         nsCString canonicalName;
-        nsImapUrl::ConvertToCanonicalFormat(folderName.get(),
-                                            hierarchyDelimiter,
-                                            getter_Copies(canonicalName));
+        nsImapUrl::ConvertToCanonicalFormat(
+            folderName.get(), hierarchyDelimiter, getter_Copies(canonicalName));
         urlSpec.Append(canonicalName);
         urlSpec.Append(hierarchyDelimiter);
       }
 
       nsAutoCString utfNewName;
       rv = CopyUTF16toMUTF7(PromiseFlatString(newFolderName), utfNewName);
       NS_ENSURE_SUCCESS(rv, rv);
       nsCString escapedFolderName;
-      MsgEscapeString(utfNewName, nsINetUtil::ESCAPE_URL_PATH, escapedFolderName);
+      MsgEscapeString(utfNewName, nsINetUtil::ESCAPE_URL_PATH,
+                      escapedFolderName);
       urlSpec.Append(escapedFolderName);
 
       rv = mailnewsurl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, url);
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::EnsureFolderExists(nsIMsgFolder *parent,
                                                 const nsAString &newFolderName,
                                                 nsIUrlListener *urlListener,
-                                                nsIURI **url)
-{
+                                                nsIURI **url) {
   NS_ENSURE_ARG_POINTER(parent);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
   nsresult rv;
 
   char hierarchyDelimiter = GetHierarchyDelimiter(parent);
-  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), parent, urlListener, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), parent,
+                            urlListener, urlSpec, hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     rv = SetImapUrlSink(parent, imapUrl);
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(imapUrl);
 
       nsCString folderName;
       GetFolderName(parent, folderName);
       urlSpec.AppendLiteral("/ensureExists>");
       urlSpec.Append(hierarchyDelimiter);
-      if (!folderName.IsEmpty())
-      {
+      if (!folderName.IsEmpty()) {
         urlSpec.Append(folderName);
         urlSpec.Append(hierarchyDelimiter);
       }
       nsAutoCString utfNewName;
       CopyUTF16toMUTF7(PromiseFlatString(newFolderName), utfNewName);
       nsCString escapedFolderName;
-      MsgEscapeString(utfNewName, nsINetUtil::ESCAPE_URL_PATH, escapedFolderName);
+      MsgEscapeString(utfNewName, nsINetUtil::ESCAPE_URL_PATH,
+                      escapedFolderName);
       urlSpec.Append(escapedFolderName);
 
       rv = mailnewsurl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, url);
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::ListFolder(nsIMsgFolder *aImapMailFolder,
                                         nsIUrlListener *aUrlListener,
-                                        nsIURI **aURL)
-{
+                                        nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
-  return FolderCommand(aImapMailFolder, aUrlListener,
-                       "/listfolder>", nsIImapUrl::nsImapListFolder, nullptr, aURL);
+  return FolderCommand(aImapMailFolder, aUrlListener, "/listfolder>",
+                       nsIImapUrl::nsImapListFolder, nullptr, aURL);
 }
 
-NS_IMETHODIMP nsImapService::GetScheme(nsACString &aScheme)
-{
+NS_IMETHODIMP nsImapService::GetScheme(nsACString &aScheme) {
   aScheme.AssignLiteral("imap");
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetDefaultPort(int32_t *aDefaultPort)
-{
+NS_IMETHODIMP nsImapService::GetDefaultPort(int32_t *aDefaultPort) {
   NS_ENSURE_ARG_POINTER(aDefaultPort);
   *aDefaultPort = nsIImapUrl::DEFAULT_IMAP_PORT;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetProtocolFlags(uint32_t *result)
-{
+NS_IMETHODIMP nsImapService::GetProtocolFlags(uint32_t *result) {
   *result = URI_NORELATIVE | URI_FORBIDS_AUTOMATIC_DOCUMENT_REPLACEMENT |
-    URI_DANGEROUS_TO_LOAD | ALLOWS_PROXY | URI_FORBIDS_COOKIE_ACCESS
+            URI_DANGEROUS_TO_LOAD | ALLOWS_PROXY | URI_FORBIDS_COOKIE_ACCESS
 #ifdef IS_ORIGIN_IS_FULL_SPEC_DEFINED
-    | ORIGIN_IS_FULL_SPEC
+            | ORIGIN_IS_FULL_SPEC
 #endif
-  ;
+      ;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::AllowPort(int32_t port, const char *scheme, bool *aRetVal)
-{
+NS_IMETHODIMP nsImapService::AllowPort(int32_t port, const char *scheme,
+                                       bool *aRetVal) {
   // allow imap to run on any port
   *aRetVal = true;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetDefaultDoBiff(bool *aDoBiff)
-{
+NS_IMETHODIMP nsImapService::GetDefaultDoBiff(bool *aDoBiff) {
   NS_ENSURE_ARG_POINTER(aDoBiff);
   // by default, do biff for IMAP servers
   *aDoBiff = true;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetDefaultServerPort(bool isSecure, int32_t *aDefaultPort)
-{
+NS_IMETHODIMP nsImapService::GetDefaultServerPort(bool isSecure,
+                                                  int32_t *aDefaultPort) {
   nsresult rv = NS_OK;
 
   // Return Secure IMAP Port if secure option chosen i.e., if isSecure is TRUE
   if (isSecure)
     *aDefaultPort = nsIImapUrl::DEFAULT_IMAPS_PORT;
   else
     rv = GetDefaultPort(aDefaultPort);
 
   return rv;
 }
 
-// this method first tries to find an exact username and hostname match with the given url
-// then, tries to find any account on the passed in imap host in case this is a url to
-// a shared imap folder.
-nsresult nsImapService::GetServerFromUrl(nsIImapUrl *aImapUrl, nsIMsgIncomingServer **aServer)
-{
+// this method first tries to find an exact username and hostname match with the
+// given url then, tries to find any account on the passed in imap host in case
+// this is a url to a shared imap folder.
+nsresult nsImapService::GetServerFromUrl(nsIImapUrl *aImapUrl,
+                                         nsIMsgIncomingServer **aServer) {
   nsresult rv;
   nsCString folderName;
   nsAutoCString userPass;
   nsAutoCString hostName;
   nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(aImapUrl);
 
   // if we can't get a folder name out of the url then I think this is an error
   aImapUrl->CreateCanonicalSourceFolderPathString(getter_Copies(folderName));
-  if (folderName.IsEmpty())
-  {
+  if (folderName.IsEmpty()) {
     rv = mailnewsUrl->GetFileName(folderName);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  nsCOMPtr<nsIMsgAccountManager> accountManager = do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
+  nsCOMPtr<nsIMsgAccountManager> accountManager =
+      do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = accountManager->FindServerByURI(mailnewsUrl, false, aServer);
 
   // look for server with any user name, in case we're trying to subscribe
   // to a folder with some one else's user name like the following
   // "IMAP://userSharingFolder@server1/SharedFolderName"
-  if (NS_FAILED(rv) || !aServer)
-  {
+  if (NS_FAILED(rv) || !aServer) {
     nsAutoCString turl;
     rv = mailnewsUrl->GetSpec(turl);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsCOMPtr<nsIURL> url;
     rv = NS_MutateURI(NS_STANDARDURLMUTATOR_CONTRACTID)
-           .SetSpec(turl)
-           .SetUserPass(EmptyCString())
-           .Finalize(url);
+             .SetSpec(turl)
+             .SetUserPass(EmptyCString())
+             .Finalize(url);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = accountManager->FindServerByURI(url, false, aServer);
-    if (*aServer)
-      aImapUrl->SetExternalLinkUrl(true);
+    if (*aServer) aImapUrl->SetExternalLinkUrl(true);
   }
 
-    // if we can't extract the imap server from this url then give up!!!
+  // if we can't extract the imap server from this url then give up!!!
   NS_ENSURE_TRUE(*aServer, NS_ERROR_FAILURE);
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::NewURI(const nsACString &aSpec,
                                     const char *aOriginCharset,  // ignored
-                                    nsIURI *aBaseURI,
-                                    nsIURI **aRetVal)
-{
+                                    nsIURI *aBaseURI, nsIURI **aRetVal) {
   NS_ENSURE_ARG_POINTER(aRetVal);
 
   nsresult rv;
   nsCOMPtr<nsIImapUrl> aImapUrl = do_CreateInstance(kImapUrlCID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // now extract lots of fun information...
   nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(aImapUrl);
   // nsAutoCString unescapedSpec(aSpec);
   // nsUnescape(unescapedSpec.BeginWriting());
 
   // set the spec
-  if (aBaseURI)
-  {
+  if (aBaseURI) {
     nsAutoCString newSpec;
     aBaseURI->Resolve(aSpec, newSpec);
     rv = mailnewsUrl->SetSpecInternal(newSpec);
-  }
-  else
-  {
+  } else {
     rv = mailnewsUrl->SetSpecInternal(aSpec);
   }
 
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCString folderName;
   // if we can't get a folder name out of the url then I think this is an error
   aImapUrl->CreateCanonicalSourceFolderPathString(getter_Copies(folderName));
-  if (folderName.IsEmpty())
-  {
+  if (folderName.IsEmpty()) {
     rv = mailnewsUrl->GetFileName(folderName);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   nsCOMPtr<nsIMsgIncomingServer> server;
   rv = GetServerFromUrl(aImapUrl, getter_AddRefs(server));
   // if we can't extract the imap server from this url then give up!!!
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(server, NS_ERROR_FAILURE);
 
   // now try to get the folder in question...
   nsCOMPtr<nsIMsgFolder> rootFolder;
   server->GetRootFolder(getter_AddRefs(rootFolder));
-  if (rootFolder && !folderName.IsEmpty())
-  {
+  if (rootFolder && !folderName.IsEmpty()) {
     nsCOMPtr<nsIMsgFolder> folder;
     nsCOMPtr<nsIMsgImapMailFolder> imapRoot = do_QueryInterface(rootFolder);
     nsCOMPtr<nsIMsgImapMailFolder> subFolder;
-    if (imapRoot)
-    {
+    if (imapRoot) {
       imapRoot->FindOnlineSubFolder(folderName, getter_AddRefs(subFolder));
       folder = do_QueryInterface(subFolder);
     }
 
     // If we can't find the folder, we can still create the URI
     // in this low-level service. Cloning URIs where the folder
     // isn't found is common when folders are renamed or moved.
     // We also ignore return statuses here.
-    if (folder)
-    {
+    if (folder) {
       nsCOMPtr<nsIImapMessageSink> msgSink = do_QueryInterface(folder);
-      (void) aImapUrl->SetImapMessageSink(msgSink);
-
-      (void) SetImapUrlSink(folder, aImapUrl);
+      (void)aImapUrl->SetImapMessageSink(msgSink);
+
+      (void)SetImapUrlSink(folder, aImapUrl);
 
       nsCString messageIdString;
       aImapUrl->GetListOfMessageIds(messageIdString);
-      if (!messageIdString.IsEmpty())
-      {
+      if (!messageIdString.IsEmpty()) {
         bool useLocalCache = false;
         folder->HasMsgOffline(strtoul(messageIdString.get(), nullptr, 10),
                               &useLocalCache);
         mailnewsUrl->SetMsgIsInLocalCache(useLocalCache);
       }
     }
   }
 
   // if we are fetching a part, be sure to enable fetch parts on demand
   bool mimePartSelectorDetected = false;
   aImapUrl->GetMimePartSelectorDetected(&mimePartSelectorDetected);
-  if (mimePartSelectorDetected)
-    aImapUrl->SetFetchPartsOnDemand(true);
+  if (mimePartSelectorDetected) aImapUrl->SetFetchPartsOnDemand(true);
 
   // we got an imap url, so be sure to return it...
   nsCOMPtr<nsIURI> imapUri = do_QueryInterface(aImapUrl);
 
   imapUri.forget(aRetVal);
 
   return rv;
 }
 
-NS_IMETHODIMP nsImapService::NewChannel(nsIURI *aURI,
-                                        nsILoadInfo* aLoadInfo,
-                                        nsIChannel **aRetVal)
-{
+NS_IMETHODIMP nsImapService::NewChannel(nsIURI *aURI, nsILoadInfo *aLoadInfo,
+                                        nsIChannel **aRetVal) {
   NS_ENSURE_ARG_POINTER(aURI);
   NS_ENSURE_ARG_POINTER(aRetVal);
   *aRetVal = nullptr;
 
   nsresult rv;
   nsCOMPtr<nsIImapUrl> imapUrl = do_QueryInterface(aURI, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
-  nsCOMPtr <nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(imapUrl, &rv);
+  nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(imapUrl, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  // imap can't open and return a channel right away...the url needs to go in the imap url queue
-  // until we find a connection which can run the url..in order to satisfy necko, we're going to return
-  // a mock imap channel....
-  nsCOMPtr<nsIImapMockChannel> channel = do_CreateInstance(kCImapMockChannel, &rv);
+  // imap can't open and return a channel right away...the url needs to go in
+  // the imap url queue until we find a connection which can run the url..in
+  // order to satisfy necko, we're going to return a mock imap channel....
+  nsCOMPtr<nsIImapMockChannel> channel =
+      do_CreateInstance(kCImapMockChannel, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
   channel->SetURI(aURI);
 
   rv = channel->SetLoadInfo(aLoadInfo);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIMsgWindow> msgWindow;
   mailnewsUrl->GetMsgWindow(getter_AddRefs(msgWindow));
-  if (msgWindow)
-  {
+  if (msgWindow) {
     nsCOMPtr<nsIDocShell> msgDocShell;
     msgWindow->GetRootDocShell(getter_AddRefs(msgDocShell));
-    if (msgDocShell)
-    {
-      nsCOMPtr <nsIProgressEventSink> prevEventSink;
+    if (msgDocShell) {
+      nsCOMPtr<nsIProgressEventSink> prevEventSink;
       channel->GetProgressEventSink(getter_AddRefs(prevEventSink));
       nsCOMPtr<nsIInterfaceRequestor> docIR(do_QueryInterface(msgDocShell));
       channel->SetNotificationCallbacks(docIR);
       // we want to use our existing event sink.
-      if (prevEventSink)
-        channel->SetProgressEventSink(prevEventSink);
+      if (prevEventSink) channel->SetProgressEventSink(prevEventSink);
     }
   }
-  imapUrl->SetMockChannel(channel); // the imap url holds a weak reference so we can pass the channel into the imap protocol when we actually run the url
+  // the imap url holds a weak reference so we can pass the channel into the
+  // imap protocol when we actually run the url.
+  imapUrl->SetMockChannel(channel);
 
   bool externalLinkUrl;
   imapUrl->GetExternalLinkUrl(&externalLinkUrl);
-  if (externalLinkUrl)
-  {
-    // everything after here is to handle clicking on an external link. We only want
-    // to do this if we didn't run the url through the various nsImapService methods,
-    // which we can tell by seeing if the sinks have been setup on the url or not.
-    nsCOMPtr <nsIMsgIncomingServer> server;
+  if (externalLinkUrl) {
+    // everything after here is to handle clicking on an external link. We only
+    // want to do this if we didn't run the url through the various
+    // nsImapService methods, which we can tell by seeing if the sinks have been
+    // setup on the url or not.
+    nsCOMPtr<nsIMsgIncomingServer> server;
     rv = GetServerFromUrl(imapUrl, getter_AddRefs(server));
     NS_ENSURE_SUCCESS(rv, rv);
     nsCString folderName;
     imapUrl->CreateCanonicalSourceFolderPathString(getter_Copies(folderName));
-    if (folderName.IsEmpty())
-    {
+    if (folderName.IsEmpty()) {
       nsCString escapedFolderName;
       rv = mailnewsUrl->GetFileName(escapedFolderName);
       if (!escapedFolderName.IsEmpty()) {
         MsgUnescapeString(escapedFolderName, 0, folderName);
       }
     }
-    // if the parent is null, then the folder doesn't really exist, so see if the user
-    // wants to subscribe to it./
+    // if the parent is null, then the folder doesn't really exist, so see if
+    // the user wants to subscribe to it./
     nsCOMPtr<nsIMsgFolder> aFolder;
     // now try to get the folder in question...
     nsCOMPtr<nsIMsgFolder> rootFolder;
     server->GetRootFolder(getter_AddRefs(rootFolder));
-    nsCOMPtr <nsIMsgImapMailFolder> imapRoot = do_QueryInterface(rootFolder);
-    nsCOMPtr <nsIMsgImapMailFolder> subFolder;
-    if (imapRoot)
-    {
+    nsCOMPtr<nsIMsgImapMailFolder> imapRoot = do_QueryInterface(rootFolder);
+    nsCOMPtr<nsIMsgImapMailFolder> subFolder;
+    if (imapRoot) {
       imapRoot->FindOnlineSubFolder(folderName, getter_AddRefs(subFolder));
       aFolder = do_QueryInterface(subFolder);
     }
-    nsCOMPtr <nsIMsgFolder> parent;
-    if (aFolder)
-      aFolder->GetParent(getter_AddRefs(parent));
+    nsCOMPtr<nsIMsgFolder> parent;
+    if (aFolder) aFolder->GetParent(getter_AddRefs(parent));
     nsCString serverKey;
     nsAutoCString userPass;
     rv = mailnewsUrl->GetUserPass(userPass);
     server->GetKey(serverKey);
     nsCString fullFolderName;
-    if (parent)
-      fullFolderName = folderName;
-    if (!parent && !folderName.IsEmpty())  // check if this folder is another user's folder
+    if (parent) fullFolderName = folderName;
+    if (!parent &&
+        !folderName.IsEmpty())  // check if this folder is another user's folder
     {
-      fullFolderName = nsIMAPNamespaceList::GenerateFullFolderNameWithDefaultNamespace(serverKey.get(),
-                                                                                       folderName.get(),
-                                                                                       userPass.get(),
-                                                                                       kOtherUsersNamespace,
-                                                                                       nullptr);
-      // if this is another user's folder, let's see if we're already subscribed to it.
-      rv = imapRoot->FindOnlineSubFolder(fullFolderName, getter_AddRefs(subFolder));
+      fullFolderName =
+          nsIMAPNamespaceList::GenerateFullFolderNameWithDefaultNamespace(
+              serverKey.get(), folderName.get(), userPass.get(),
+              kOtherUsersNamespace, nullptr);
+      // if this is another user's folder, let's see if we're already subscribed
+      // to it.
+      rv = imapRoot->FindOnlineSubFolder(fullFolderName,
+                                         getter_AddRefs(subFolder));
       aFolder = do_QueryInterface(subFolder);
-      if (aFolder)
-        aFolder->GetParent(getter_AddRefs(parent));
+      if (aFolder) aFolder->GetParent(getter_AddRefs(parent));
     }
     // if we couldn't get the fullFolderName, then we probably couldn't find
-    // the other user's namespace, in which case, we shouldn't try to subscribe to it.
-    if (!parent && !folderName.IsEmpty() && !fullFolderName.IsEmpty())
-    {
-      // this folder doesn't exist - check if the user wants to subscribe to this folder.
+    // the other user's namespace, in which case, we shouldn't try to subscribe
+    // to it.
+    if (!parent && !folderName.IsEmpty() && !fullFolderName.IsEmpty()) {
+      // this folder doesn't exist - check if the user wants to subscribe to
+      // this folder.
       nsCOMPtr<nsIPrompt> dialog;
-      nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv));
+      nsCOMPtr<nsIWindowWatcher> wwatch(
+          do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv));
       NS_ENSURE_SUCCESS(rv, rv);
       wwatch->GetNewPrompter(nullptr, getter_AddRefs(dialog));
 
       nsString statusString, confirmText;
       nsCOMPtr<nsIStringBundle> bundle;
       rv = IMAPGetStringBundle(getter_AddRefs(bundle));
       NS_ENSURE_SUCCESS(rv, rv);
-        // need to convert folder name from mod-utf7 to unicode
+      // need to convert folder name from mod-utf7 to unicode
       nsAutoString unescapedName;
       if (NS_FAILED(CopyMUTF7toUTF16(fullFolderName, unescapedName)))
         CopyASCIItoUTF16(fullFolderName, unescapedName);
-      const char16_t *formatStrings[1] = { unescapedName.get() };
-
-      rv = bundle->FormatStringFromName(
-        "imapSubscribePrompt",
-        formatStrings, 1, confirmText);
-      NS_ENSURE_SUCCESS(rv,rv);
+      const char16_t *formatStrings[1] = {unescapedName.get()};
+
+      rv = bundle->FormatStringFromName("imapSubscribePrompt", formatStrings, 1,
+                                        confirmText);
+      NS_ENSURE_SUCCESS(rv, rv);
 
       bool confirmResult = false;
       rv = dialog->Confirm(nullptr, confirmText.get(), &confirmResult);
       NS_ENSURE_SUCCESS(rv, rv);
 
-      if (confirmResult)
-      {
-        nsCOMPtr <nsIImapIncomingServer> imapServer = do_QueryInterface(server);
-        if (imapServer)
-        {
-          nsCOMPtr <nsIURI> subscribeURI;
-          // now we have the real folder name to try to subscribe to. Let's try running
-          // a subscribe url and returning that as the uri we've created.
-          // We need to convert this to unicode because that's what subscribe wants :-(
-          // It's already in mod-utf7.
+      if (confirmResult) {
+        nsCOMPtr<nsIImapIncomingServer> imapServer = do_QueryInterface(server);
+        if (imapServer) {
+          nsCOMPtr<nsIURI> subscribeURI;
+          // now we have the real folder name to try to subscribe to. Let's try
+          // running a subscribe url and returning that as the uri we've
+          // created. We need to convert this to unicode because that's what
+          // subscribe wants :-( It's already in mod-utf7.
           nsAutoString unicodeName;
           CopyASCIItoUTF16(fullFolderName, unicodeName);
-          rv = imapServer->SubscribeToFolder(unicodeName, true, getter_AddRefs(subscribeURI));
-          if (NS_SUCCEEDED(rv) && subscribeURI)
-          {
-            nsCOMPtr <nsIImapUrl> imapSubscribeUrl = do_QueryInterface(subscribeURI);
-            if (imapSubscribeUrl)
-              imapSubscribeUrl->SetExternalLinkUrl(true);
-            nsCOMPtr <nsIMsgMailNewsUrl> mailnewsUrl = do_QueryInterface(subscribeURI);
-            if (mailnewsUrl)
-            {
-              nsCOMPtr<nsIMsgMailSession> mailSession = do_GetService(NS_MSGMAILSESSION_CONTRACTID, &rv);
+          rv = imapServer->SubscribeToFolder(unicodeName, true,
+                                             getter_AddRefs(subscribeURI));
+          if (NS_SUCCEEDED(rv) && subscribeURI) {
+            nsCOMPtr<nsIImapUrl> imapSubscribeUrl =
+                do_QueryInterface(subscribeURI);
+            if (imapSubscribeUrl) imapSubscribeUrl->SetExternalLinkUrl(true);
+            nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl =
+                do_QueryInterface(subscribeURI);
+            if (mailnewsUrl) {
+              nsCOMPtr<nsIMsgMailSession> mailSession =
+                  do_GetService(NS_MSGMAILSESSION_CONTRACTID, &rv);
               NS_ENSURE_SUCCESS(rv, rv);
-              nsCOMPtr <nsIMsgWindow> msgWindow;
+              nsCOMPtr<nsIMsgWindow> msgWindow;
               rv = mailSession->GetTopmostMsgWindow(getter_AddRefs(msgWindow));
-              if (NS_SUCCEEDED(rv) && msgWindow)
-              {
+              if (NS_SUCCEEDED(rv) && msgWindow) {
                 mailnewsUrl->SetMsgWindow(msgWindow);
-                nsCOMPtr <nsIUrlListener> listener = do_QueryInterface(rootFolder);
-                if (listener)
-                  mailnewsUrl->RegisterListener(listener);
+                nsCOMPtr<nsIUrlListener> listener =
+                    do_QueryInterface(rootFolder);
+                if (listener) mailnewsUrl->RegisterListener(listener);
               }
             }
           }
         }
       }
       // error out this channel, so it'll stop trying to run the url.
       rv = NS_ERROR_FAILURE;
       *aRetVal = nullptr;
     }
     // this folder exists - check if this is a click on a link to the folder
     // in which case, we'll select it.
-    else if (!fullFolderName.IsEmpty())
-    {
+    else if (!fullFolderName.IsEmpty()) {
       nsCOMPtr<nsIMsgFolder> imapFolder;
       nsCOMPtr<nsIImapServerSink> serverSink;
 
       mailnewsUrl->GetFolder(getter_AddRefs(imapFolder));
       imapUrl->GetImapServerSink(getter_AddRefs(serverSink));
-      // need to see if this is a link click - one way is to check if the url is set up correctly
-      // if not, it's probably a url click. We need a better way of doing this.
-      if (!imapFolder)
-      {
-        nsCOMPtr<nsIMsgMailSession> mailSession = do_GetService(NS_MSGMAILSESSION_CONTRACTID, &rv);
+      // need to see if this is a link click - one way is to check if the url is
+      // set up correctly if not, it's probably a url click. We need a better
+      // way of doing this.
+      if (!imapFolder) {
+        nsCOMPtr<nsIMsgMailSession> mailSession =
+            do_GetService(NS_MSGMAILSESSION_CONTRACTID, &rv);
         NS_ENSURE_SUCCESS(rv, rv);
-        nsCOMPtr <nsIMsgWindow> msgWindow;
+        nsCOMPtr<nsIMsgWindow> msgWindow;
         rv = mailSession->GetTopmostMsgWindow(getter_AddRefs(msgWindow));
-        if (NS_SUCCEEDED(rv) && msgWindow)
-        {
+        if (NS_SUCCEEDED(rv) && msgWindow) {
           nsCString uri;
           rootFolder->GetURI(uri);
           uri.Append('/');
           uri.Append(fullFolderName);
           nsCOMPtr<nsIMsgWindowCommands> windowCommands;
           msgWindow->GetWindowCommands(getter_AddRefs(windowCommands));
-          if (windowCommands)
-            windowCommands->SelectFolder(uri);
-            // error out this channel, so it'll stop trying to run the url.
+          if (windowCommands) windowCommands->SelectFolder(uri);
+          // error out this channel, so it'll stop trying to run the url.
           *aRetVal = nullptr;
           rv = NS_ERROR_FAILURE;
-        }
-        else
-        {
+        } else {
           // make sure the imap action is selectFolder, so the content type
           // will be x-application-imapfolder, so ::HandleContent will
           // know to open a new 3 pane window.
           imapUrl->SetImapAction(nsIImapUrl::nsImapSelectFolder);
         }
       }
     }
   }
-  if (NS_SUCCEEDED(rv))
-    channel.forget(aRetVal);
+  if (NS_SUCCEEDED(rv)) channel.forget(aRetVal);
   return rv;
 }
 
-NS_IMETHODIMP nsImapService::SetDefaultLocalPath(nsIFile *aPath)
-{
+NS_IMETHODIMP nsImapService::SetDefaultLocalPath(nsIFile *aPath) {
   NS_ENSURE_ARG_POINTER(aPath);
 
-  return NS_SetPersistentFile(PREF_MAIL_ROOT_IMAP_REL, PREF_MAIL_ROOT_IMAP, aPath);
+  return NS_SetPersistentFile(PREF_MAIL_ROOT_IMAP_REL, PREF_MAIL_ROOT_IMAP,
+                              aPath);
 }
 
-NS_IMETHODIMP nsImapService::GetDefaultLocalPath(nsIFile **aResult)
-{
+NS_IMETHODIMP nsImapService::GetDefaultLocalPath(nsIFile **aResult) {
   NS_ENSURE_ARG_POINTER(aResult);
   *aResult = nullptr;
 
   bool havePref;
   nsCOMPtr<nsIFile> localFile;
-  nsresult rv = NS_GetPersistentFile(PREF_MAIL_ROOT_IMAP_REL,
-                                     PREF_MAIL_ROOT_IMAP,
-                                     NS_APP_IMAP_MAIL_50_DIR,
-                                     havePref,
-                                     getter_AddRefs(localFile));
+  nsresult rv = NS_GetPersistentFile(
+      PREF_MAIL_ROOT_IMAP_REL, PREF_MAIL_ROOT_IMAP, NS_APP_IMAP_MAIL_50_DIR,
+      havePref, getter_AddRefs(localFile));
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_TRUE(localFile, NS_ERROR_FAILURE);
 
   bool exists;
   rv = localFile->Exists(&exists);
   if (NS_SUCCEEDED(rv) && !exists)
     rv = localFile->Create(nsIFile::DIRECTORY_TYPE, 0775);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (!havePref || !exists)
-  {
-    rv = NS_SetPersistentFile(PREF_MAIL_ROOT_IMAP_REL, PREF_MAIL_ROOT_IMAP, localFile);
+  if (!havePref || !exists) {
+    rv = NS_SetPersistentFile(PREF_MAIL_ROOT_IMAP_REL, PREF_MAIL_ROOT_IMAP,
+                              localFile);
     NS_ASSERTION(NS_SUCCEEDED(rv), "Failed to set root dir pref.");
   }
 
   localFile.forget(aResult);
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetServerIID(nsIID **aServerIID)
-{
+NS_IMETHODIMP nsImapService::GetServerIID(nsIID **aServerIID) {
   *aServerIID = new nsIID(NS_GET_IID(nsIImapIncomingServer));
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetRequiresUsername(bool *aRequiresUsername)
-{
+NS_IMETHODIMP nsImapService::GetRequiresUsername(bool *aRequiresUsername) {
   NS_ENSURE_ARG_POINTER(aRequiresUsername);
 
   *aRequiresUsername = true;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetPreflightPrettyNameWithEmailAddress(bool *aPreflightPrettyNameWithEmailAddress)
-{
+NS_IMETHODIMP nsImapService::GetPreflightPrettyNameWithEmailAddress(
+    bool *aPreflightPrettyNameWithEmailAddress) {
   NS_ENSURE_ARG_POINTER(aPreflightPrettyNameWithEmailAddress);
 
   *aPreflightPrettyNameWithEmailAddress = true;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetCanLoginAtStartUp(bool *aCanLoginAtStartUp)
-{
+NS_IMETHODIMP nsImapService::GetCanLoginAtStartUp(bool *aCanLoginAtStartUp) {
   NS_ENSURE_ARG_POINTER(aCanLoginAtStartUp);
   *aCanLoginAtStartUp = true;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetCanDelete(bool *aCanDelete)
-{
+NS_IMETHODIMP nsImapService::GetCanDelete(bool *aCanDelete) {
   NS_ENSURE_ARG_POINTER(aCanDelete);
   *aCanDelete = true;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetCanDuplicate(bool *aCanDuplicate)
-{
+NS_IMETHODIMP nsImapService::GetCanDuplicate(bool *aCanDuplicate) {
   NS_ENSURE_ARG_POINTER(aCanDuplicate);
   *aCanDuplicate = true;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetCanGetMessages(bool *aCanGetMessages)
-{
+NS_IMETHODIMP nsImapService::GetCanGetMessages(bool *aCanGetMessages) {
   NS_ENSURE_ARG_POINTER(aCanGetMessages);
   *aCanGetMessages = true;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetCanGetIncomingMessages(bool *aCanGetIncomingMessages)
-{
+NS_IMETHODIMP nsImapService::GetCanGetIncomingMessages(
+    bool *aCanGetIncomingMessages) {
   NS_ENSURE_ARG_POINTER(aCanGetIncomingMessages);
   *aCanGetIncomingMessages = true;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetShowComposeMsgLink(bool *showComposeMsgLink)
-{
+NS_IMETHODIMP nsImapService::GetShowComposeMsgLink(bool *showComposeMsgLink) {
   NS_ENSURE_ARG_POINTER(showComposeMsgLink);
   *showComposeMsgLink = true;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetFoldersCreatedAsync(bool *aAsyncCreation)
-{
+NS_IMETHODIMP nsImapService::GetFoldersCreatedAsync(bool *aAsyncCreation) {
   NS_ENSURE_ARG_POINTER(aAsyncCreation);
   *aAsyncCreation = true;
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::GetListOfFoldersWithPath(nsIImapIncomingServer *aServer,
-                                                      nsIMsgWindow *aMsgWindow,
-                                                      const nsACString &folderPath)
-{
+NS_IMETHODIMP nsImapService::GetListOfFoldersWithPath(
+    nsIImapIncomingServer *aServer, nsIMsgWindow *aMsgWindow,
+    const nsACString &folderPath) {
   nsresult rv;
   nsCOMPtr<nsIMsgIncomingServer> server = do_QueryInterface(aServer);
-  if (!server)
-    return NS_ERROR_FAILURE;
+  if (!server) return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIMsgFolder> rootMsgFolder;
   rv = server->GetRootMsgFolder(getter_AddRefs(rootMsgFolder));
 
   NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && rootMsgFolder, NS_ERROR_FAILURE);
 
   nsCOMPtr<nsIUrlListener> listener = do_QueryInterface(aServer, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (!listener)
-    return NS_ERROR_FAILURE;
-
-  // Locate the folder so that the correct hierarchical delimiter is used in the folder
-  // pathnames, otherwise root's (ie, '^') is used and this is wrong.
+  if (!listener) return NS_ERROR_FAILURE;
+
+  // Locate the folder so that the correct hierarchical delimiter is used in the
+  // folder pathnames, otherwise root's (ie, '^') is used and this is wrong.
   nsCOMPtr<nsIMsgFolder> msgFolder;
-  if (rootMsgFolder && !folderPath.IsEmpty())
-  {
-    // If the folder path contains 'INBOX' of any forms, we need to convert it to uppercase
-    // before finding it under the root folder. We do the same in PossibleImapMailbox().
+  if (rootMsgFolder && !folderPath.IsEmpty()) {
+    // If the folder path contains 'INBOX' of any forms, we need to convert it
+    // to uppercase before finding it under the root folder. We do the same in
+    // PossibleImapMailbox().
     nsAutoCString tempFolderName(folderPath);
     nsAutoCString tokenStr, remStr, changedStr;
     int32_t slashPos = tempFolderName.FindChar('/');
-    if (slashPos > 0)
-    {
+    if (slashPos > 0) {
       tokenStr = StringHead(tempFolderName, slashPos);
       remStr = Substring(tempFolderName, slashPos);
-    }
-    else
+    } else
       tokenStr.Assign(tempFolderName);
 
     if (tokenStr.LowerCaseEqualsLiteral("inbox") &&
         !tokenStr.EqualsLiteral("INBOX"))
       changedStr.AppendLiteral("INBOX");
     else
       changedStr.Append(tokenStr);
 
-    if (slashPos > 0 )
-      changedStr.Append(remStr);
+    if (slashPos > 0) changedStr.Append(remStr);
 
     rv = rootMsgFolder->FindSubFolder(changedStr, getter_AddRefs(msgFolder));
   }
   return DiscoverChildren(msgFolder, listener, folderPath, nullptr);
 }
 
-NS_IMETHODIMP nsImapService::GetListOfFoldersOnServer(nsIImapIncomingServer *aServer,
-                                                      nsIMsgWindow *aMsgWindow)
-{
+NS_IMETHODIMP nsImapService::GetListOfFoldersOnServer(
+    nsIImapIncomingServer *aServer, nsIMsgWindow *aMsgWindow) {
   nsresult rv;
 
   nsCOMPtr<nsIMsgIncomingServer> server = do_QueryInterface(aServer);
-  if (!server)
-    return NS_ERROR_FAILURE;
+  if (!server) return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIMsgFolder> rootMsgFolder;
   rv = server->GetRootMsgFolder(getter_AddRefs(rootMsgFolder));
 
   NS_ENSURE_SUCCESS(rv, rv);
-  if (!rootMsgFolder)
-    return NS_ERROR_FAILURE;
+  if (!rootMsgFolder) return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIUrlListener> listener = do_QueryInterface(aServer, &rv);
   NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && listener, NS_ERROR_FAILURE);
 
   return DiscoverAllAndSubscribedFolders(rootMsgFolder, listener, nullptr);
 }
 
 NS_IMETHODIMP nsImapService::SubscribeFolder(nsIMsgFolder *aFolder,
                                              const nsAString &aFolderName,
                                              nsIUrlListener *urlListener,
-                                             nsIURI **url)
-{
-
-  return ChangeFolderSubscription(aFolder, aFolderName,
-                                  "/subscribe>", urlListener, url);
+                                             nsIURI **url) {
+  return ChangeFolderSubscription(aFolder, aFolderName, "/subscribe>",
+                                  urlListener, url);
 }
 
 nsresult nsImapService::ChangeFolderSubscription(nsIMsgFolder *folder,
                                                  const nsAString &folderName,
                                                  const char *command,
                                                  nsIUrlListener *urlListener,
-                                                 nsIURI **url)
-{
+                                                 nsIURI **url) {
   NS_ENSURE_ARG_POINTER(folder);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
   nsresult rv;
   char hierarchyDelimiter = GetHierarchyDelimiter(folder);
-  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), folder, urlListener,
-                            urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), folder,
+                            urlListener, urlSpec, hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     rv = SetImapUrlSink(folder, imapUrl);
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCOMPtr<nsIMsgMailNewsUrl> mailnewsurl = do_QueryInterface(imapUrl);
       urlSpec.Append(command);
       urlSpec.Append(hierarchyDelimiter);
       nsAutoCString utfFolderName;
       rv = CopyUTF16toMUTF7(PromiseFlatString(folderName), utfFolderName);
       NS_ENSURE_SUCCESS(rv, rv);
       nsCString escapedFolderName;
-      MsgEscapeString(utfFolderName, nsINetUtil::ESCAPE_URL_PATH, escapedFolderName);
+      MsgEscapeString(utfFolderName, nsINetUtil::ESCAPE_URL_PATH,
+                      escapedFolderName);
       urlSpec.Append(escapedFolderName);
       rv = mailnewsurl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, url);
     }
   }
   return rv;
 }
 
 NS_IMETHODIMP nsImapService::UnsubscribeFolder(nsIMsgFolder *aFolder,
                                                const nsAString &aFolderName,
                                                nsIUrlListener *aUrlListener,
-                                               nsIURI **aUrl)
-{
-
-  return ChangeFolderSubscription(aFolder, aFolderName,
-                                  "/unsubscribe>", aUrlListener, aUrl);
+                                               nsIURI **aUrl) {
+  return ChangeFolderSubscription(aFolder, aFolderName, "/unsubscribe>",
+                                  aUrlListener, aUrl);
 }
 
 NS_IMETHODIMP nsImapService::GetFolderAdminUrl(nsIMsgFolder *aImapMailFolder,
                                                nsIMsgWindow *aMsgWindow,
                                                nsIUrlListener *aUrlListener,
-                                               nsIURI **aURL)
-{
+                                               nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(aImapMailFolder);
 
-  return FolderCommand(aImapMailFolder, aUrlListener,
-                       "/refreshfolderurls>", nsIImapUrl::nsImapRefreshFolderUrls, aMsgWindow, aURL);
+  return FolderCommand(aImapMailFolder, aUrlListener, "/refreshfolderurls>",
+                       nsIImapUrl::nsImapRefreshFolderUrls, aMsgWindow, aURL);
 }
 
 NS_IMETHODIMP nsImapService::IssueCommandOnMsgs(nsIMsgFolder *anImapFolder,
                                                 nsIMsgWindow *aMsgWindow,
                                                 const nsACString &aCommand,
                                                 const nsACString &uids,
-                                                nsIURI **aURL)
-{
+                                                nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(anImapFolder);
   NS_ENSURE_ARG_POINTER(aMsgWindow);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
   nsresult rv;
   char hierarchyDelimiter = GetHierarchyDelimiter(anImapFolder);
-  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), anImapFolder, nullptr, urlSpec, hierarchyDelimiter);
-
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
+                            anImapFolder, nullptr, urlSpec, hierarchyDelimiter);
+
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     // nsImapUrl::SetSpec() will set the imap action properly
     rv = imapUrl->SetImapAction(nsIImapUrl::nsImapUserDefinedMsgCommand);
 
-    nsCOMPtr <nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
+    nsCOMPtr<nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
     mailNewsUrl->SetMsgWindow(aMsgWindow);
     mailNewsUrl->SetUpdatingFolder(true);
     rv = SetImapUrlSink(anImapFolder, imapUrl);
 
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCString folderName;
       GetFolderName(anImapFolder, folderName);
       urlSpec.Append('/');
       urlSpec.Append(aCommand);
       urlSpec.Append('>');
       urlSpec.Append(uidString);
       urlSpec.Append('>');
       urlSpec.Append(hierarchyDelimiter);
       urlSpec.Append(folderName);
       urlSpec.Append('>');
       urlSpec.Append(uids);
       rv = mailNewsUrl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, aURL);
     }
-  } // if we have a url to run....
+  }  // if we have a url to run....
 
   return rv;
 }
 
-NS_IMETHODIMP nsImapService::FetchCustomMsgAttribute(nsIMsgFolder *anImapFolder,
-                                                     nsIMsgWindow *aMsgWindow,
-                                                     const nsACString &aAttribute,
-                                                     const nsACString &uids,
-                                                     nsIURI **aURL)
-{
+NS_IMETHODIMP nsImapService::FetchCustomMsgAttribute(
+    nsIMsgFolder *anImapFolder, nsIMsgWindow *aMsgWindow,
+    const nsACString &aAttribute, const nsACString &uids, nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(anImapFolder);
   NS_ENSURE_ARG_POINTER(aMsgWindow);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
   nsresult rv;
   char hierarchyDelimiter = GetHierarchyDelimiter(anImapFolder);
-  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), anImapFolder,
-                            nullptr, urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
+                            anImapFolder, nullptr, urlSpec, hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     // nsImapUrl::SetSpec() will set the imap action properly
     rv = imapUrl->SetImapAction(nsIImapUrl::nsImapUserDefinedFetchAttribute);
 
-    nsCOMPtr <nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
+    nsCOMPtr<nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
     mailNewsUrl->SetMsgWindow(aMsgWindow);
     mailNewsUrl->SetUpdatingFolder(true);
     rv = SetImapUrlSink(anImapFolder, imapUrl);
 
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCString folderName;
       GetFolderName(anImapFolder, folderName);
       urlSpec.AppendLiteral("/customFetch>UID>");
       urlSpec.Append(hierarchyDelimiter);
       urlSpec.Append(folderName);
       urlSpec.Append('>');
       urlSpec.Append(uids);
       urlSpec.Append('>');
       urlSpec.Append(aAttribute);
       rv = mailNewsUrl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, aURL);
     }
-  } // if we have a url to run....
+  }  // if we have a url to run....
 
   return rv;
 }
 
-NS_IMETHODIMP nsImapService::StoreCustomKeywords(nsIMsgFolder *anImapFolder,
-                                                 nsIMsgWindow *aMsgWindow,
-                                                 const nsACString &flagsToAdd,
-                                                 const nsACString &flagsToSubtract,
-                                                 const nsACString &uids,
-                                                 nsIURI **aURL)
-{
+NS_IMETHODIMP nsImapService::StoreCustomKeywords(
+    nsIMsgFolder *anImapFolder, nsIMsgWindow *aMsgWindow,
+    const nsACString &flagsToAdd, const nsACString &flagsToSubtract,
+    const nsACString &uids, nsIURI **aURL) {
   NS_ENSURE_ARG_POINTER(anImapFolder);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
   nsresult rv;
   char hierarchyDelimiter = GetHierarchyDelimiter(anImapFolder);
-  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), anImapFolder, nullptr, urlSpec, hierarchyDelimiter);
-
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl),
+                            anImapFolder, nullptr, urlSpec, hierarchyDelimiter);
+
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     // nsImapUrl::SetSpec() will set the imap action properly
     rv = imapUrl->SetImapAction(nsIImapUrl::nsImapMsgStoreCustomKeywords);
 
-    nsCOMPtr <nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
+    nsCOMPtr<nsIMsgMailNewsUrl> mailNewsUrl = do_QueryInterface(imapUrl);
     mailNewsUrl->SetMsgWindow(aMsgWindow);
     mailNewsUrl->SetUpdatingFolder(true);
     rv = SetImapUrlSink(anImapFolder, imapUrl);
 
-    if (NS_SUCCEEDED(rv))
-    {
+    if (NS_SUCCEEDED(rv)) {
       nsCString folderName;
       GetFolderName(anImapFolder, folderName);
       urlSpec.AppendLiteral("/customKeywords>UID>");
       urlSpec.Append(hierarchyDelimiter);
       urlSpec.Append(folderName);
       urlSpec.Append('>');
       urlSpec.Append(uids);
       urlSpec.Append('>');
       urlSpec.Append(flagsToAdd);
       urlSpec.Append('>');
       urlSpec.Append(flagsToSubtract);
       rv = mailNewsUrl->SetSpecInternal(urlSpec);
       if (NS_SUCCEEDED(rv))
         rv = GetImapConnectionAndLoadUrl(imapUrl, nullptr, aURL);
     }
-  } // if we have a url to run....
+  }  // if we have a url to run....
 
   return rv;
 }
 
-
-NS_IMETHODIMP nsImapService::DownloadMessagesForOffline(const nsACString &messageIds,
-                                                        nsIMsgFolder *aFolder,
-                                                        nsIUrlListener *aUrlListener,
-                                                        nsIMsgWindow *aMsgWindow)
-{
+NS_IMETHODIMP nsImapService::DownloadMessagesForOffline(
+    const nsACString &messageIds, nsIMsgFolder *aFolder,
+    nsIUrlListener *aUrlListener, nsIMsgWindow *aMsgWindow) {
   NS_ENSURE_ARG_POINTER(aFolder);
 
   nsCOMPtr<nsIImapUrl> imapUrl;
   nsAutoCString urlSpec;
   nsresult rv;
   char hierarchyDelimiter = GetHierarchyDelimiter(aFolder);
-  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aFolder, nullptr,
-                            urlSpec, hierarchyDelimiter);
-  if (NS_SUCCEEDED(rv) && imapUrl)
-  {
+  rv = CreateStartOfImapUrl(EmptyCString(), getter_AddRefs(imapUrl), aFolder,
+                            nullptr, urlSpec, hierarchyDelimiter);
+  if (NS_SUCCEEDED(rv) && imapUrl) {
     nsCOMPtr<nsIURI> runningURI;
-    // need to pass in stream listener in order to get the channel created correctly
-    nsCOMPtr<nsIImapMessageSink> imapMessageSink(do_QueryInterface(aFolder, &rv));
-    rv = FetchMessage(imapUrl, nsImapUrl::nsImapMsgDownloadForOffline,aFolder,
-                      imapMessageSink, aMsgWindow, nullptr, messageIds,
-                      false, EmptyCString(), getter_AddRefs(runningURI));
-    if (runningURI && aUrlListener)
-    {
-      nsCOMPtr<nsIMsgMailNewsUrl> msgurl (do_QueryInterface(runningURI));
+    // need to pass in stream listener in order to get the channel created
+    // correctly
+    nsCOMPtr<nsIImapMessageSink> imapMessageSink(
+        do_QueryInterface(aFolder, &rv));
+    rv = FetchMessage(imapUrl, nsImapUrl::nsImapMsgDownloadForOffline, aFolder,
+                      imapMessageSink, aMsgWindow, nullptr, messageIds, false,
+                      EmptyCString(), getter_AddRefs(runningURI));
+    if (runningURI && aUrlListener) {
+      nsCOMPtr<nsIMsgMailNewsUrl> msgurl(do_QueryInterface(runningURI));
       nsCOMPtr<nsIImapUrl> imapUrl(do_QueryInterface(runningURI));
-      if (msgurl)
-        msgurl->RegisterListener(aUrlListener);
-      if (imapUrl)
-        imapUrl->SetStoreResultsOffline(true);
+      if (msgurl) msgurl->RegisterListener(aUrlListener);
+      if (imapUrl) imapUrl->SetStoreResultsOffline(true);
     }
   }
   return rv;
 }
 
-NS_IMETHODIMP nsImapService::MessageURIToMsgHdr(const char *uri, nsIMsgDBHdr **aRetVal)
-{
+NS_IMETHODIMP nsImapService::MessageURIToMsgHdr(const char *uri,
+                                                nsIMsgDBHdr **aRetVal) {
   NS_ENSURE_ARG_POINTER(uri);
   NS_ENSURE_ARG_POINTER(aRetVal);
 
   nsCOMPtr<nsIMsgFolder> folder;
   nsMsgKey msgKey;
   nsresult rv = DecomposeImapURI(nsDependentCString(uri),
                                  getter_AddRefs(folder), &msgKey);
-  NS_ENSURE_SUCCESS(rv,rv);
+  NS_ENSURE_SUCCESS(rv, rv);
   rv = folder->GetMessageHeader(msgKey, aRetVal);
-  NS_ENSURE_SUCCESS(rv,rv);
+  NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
-NS_IMETHODIMP nsImapService::PlaybackAllOfflineOperations(nsIMsgWindow *aMsgWindow,
-                                                          nsIUrlListener *aListener,
-                                                          nsISupports **aResult)
-{
+NS_IMETHODIMP nsImapService::PlaybackAllOfflineOperations(
+    nsIMsgWindow *aMsgWindow, nsIUrlListener *aListener,
+    nsISupports **aResult) {
   NS_ENSURE_ARG_POINTER(aResult);
 
   nsresult rv;
-  nsImapOfflineSync *goOnline = new nsImapOfflineSync(aMsgWindow, aListener, nullptr);
-  if (goOnline)
-  {
-    rv = goOnline->QueryInterface(NS_GET_IID(nsISupports), (void **) aResult);
+  nsImapOfflineSync *goOnline =
+      new nsImapOfflineSync(aMsgWindow, aListener, nullptr);
+  if (goOnline) {
+    rv = goOnline->QueryInterface(NS_GET_IID(nsISupports), (void **)aResult);
     NS_ENSURE_SUCCESS(rv, rv);
-    if (NS_SUCCEEDED(rv) && *aResult)
-      return goOnline->ProcessNextOperation();
+    if (NS_SUCCEEDED(rv) && *aResult) return goOnline->ProcessNextOperation();
   }
   return NS_ERROR_OUT_OF_MEMORY;
 }
 
-NS_IMETHODIMP nsImapService::DownloadAllOffineImapFolders(nsIMsgWindow *aMsgWindow,
-                                                          nsIUrlListener *aListener)
-{
-  RefPtr<nsImapOfflineDownloader> downloadForOffline = new nsImapOfflineDownloader(aMsgWindow, aListener);
-  if (downloadForOffline)
-  {
+NS_IMETHODIMP nsImapService::DownloadAllOffineImapFolders(
+    nsIMsgWindow *aMsgWindow, nsIUrlListener *aListener) {
+  RefPtr<nsImapOfflineDownloader> downloadForOffline =
+      new nsImapOfflineDownloader(aMsgWindow, aListener);
+  if (downloadForOffline) {
     // hold reference to this so it won't get deleted out from under itself.
     nsresult rv = downloadForOffline->ProcessNextOperation();
     return rv;
   }
   return NS_ERROR_OUT_OF_MEMORY;
 }
 
-NS_IMETHODIMP nsImapService::GetCacheStorage(nsICacheStorage **result)
-{
+NS_IMETHODIMP nsImapService::GetCacheStorage(nsICacheStorage **result) {
   nsresult rv = NS_OK;
-  if (!mCacheStorage)
-  {
+  if (!mCacheStorage) {
     nsCOMPtr<nsICacheStorageService> cacheStorageService =
-      do_GetService("@mozilla.org/netwerk/cache-storage-service;1", &rv);
+        do_GetService("@mozilla.org/netwerk/cache-storage-service;1", &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
     RefPtr<MailnewsLoadContextInfo> lci =
-      new MailnewsLoadContextInfo(false, false, mozilla::OriginAttributes());
-
-    rv = cacheStorageService->MemoryCacheStorage(lci, getter_AddRefs(mCacheStorage));
+        new MailnewsLoadContextInfo(false, false, mozilla::OriginAttributes());
+
+    rv = cacheStorageService->MemoryCacheStorage(lci,
+                                                 getter_AddRefs(mCacheStorage));
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   NS_IF_ADDREF(*result = mCacheStorage);
   return rv;
 }
 
-NS_IMETHODIMP nsImapService::HandleContent(const char *aContentType,
-                                           nsIInterfaceRequestor *aWindowContext,
-                                           nsIRequest *request)
-{
+NS_IMETHODIMP nsImapService::HandleContent(
+    const char *aContentType, nsIInterfaceRequestor *aWindowContext,
+    nsIRequest *request) {
   NS_ENSURE_ARG_POINTER(request);
 
   nsresult rv;
   nsCOMPtr<nsIChannel> aChannel = do_QueryInterface(request, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (PL_strcasecmp(aContentType, "x-application-imapfolder") == 0)
-  {
+  if (PL_strcasecmp(aContentType, "x-application-imapfolder") == 0) {
     nsCOMPtr<nsIURI> uri;
     rv = aChannel->GetURI(getter_AddRefs(uri));
     NS_ENSURE_SUCCESS(rv, rv);
 
-    if (uri)
-    {
+    if (uri) {
       request->Cancel(NS_BINDING_ABORTED);
-      nsCOMPtr<nsIWindowMediator> mediator(do_GetService(NS_WINDOWMEDIATOR_CONTRACTID, &rv));
+      nsCOMPtr<nsIWindowMediator> mediator(
+          do_GetService(NS_WINDOWMEDIATOR_CONTRACTID, &rv));
       NS_ENSURE_SUCCESS(rv, rv);
 
       nsAutoCString uriStr;
       rv = uri->GetSpec(uriStr);
       NS_ENSURE_SUCCESS(rv, rv);
 
       // imap uri's are unescaped, so unescape the url.
       nsCString unescapedUriStr;
       MsgUnescapeString(uriStr, 0, unescapedUriStr);
-      nsCOMPtr <nsIMessengerWindowService> messengerWindowService = do_GetService(NS_MESSENGERWINDOWSERVICE_CONTRACTID,&rv);
+      nsCOMPtr<nsIMessengerWindowService> messengerWindowService =
+          do_GetService(NS_MESSENGERWINDOWSERVICE_CONTRACTID, &rv);
       NS_ENSURE_SUCCESS(rv, rv);
 
-      rv = messengerWindowService->OpenMessengerWindowWithUri("mail:3pane", unescapedUriStr.get(), nsMsgKey_None);
+      rv = messengerWindowService->OpenMessengerWindowWithUri(
+          "mail:3pane", unescapedUriStr.get(), nsMsgKey_None);
       NS_ENSURE_SUCCESS(rv, rv);
     }
-  }
-  else
-  {
+  } else {
     // The content-type was not x-application-imapfolder
     return NS_ERROR_WONT_HANDLE_CONTENT;
   }
 
   return rv;
 }
--- a/mailnews/imap/src/nsImapService.h
+++ b/mailnews/imap/src/nsImapService.h
@@ -20,102 +20,91 @@ class nsIImapUrl;
 class nsIMsgFolder;
 class nsIMsgIncomingServer;
 
 class nsImapService : public nsIImapService,
                       public nsIMsgMessageService,
                       public nsIMsgMessageFetchPartService,
                       public nsIProtocolHandler,
                       public nsIMsgProtocolInfo,
-                      public nsIContentHandler
-{
-public:
+                      public nsIContentHandler {
+ public:
   nsImapService();
 
   NS_DECL_THREADSAFE_ISUPPORTS
   NS_DECL_NSIMSGPROTOCOLINFO
   NS_DECL_NSIIMAPSERVICE
   NS_DECL_NSIMSGMESSAGESERVICE
   NS_DECL_NSIPROTOCOLHANDLER
   NS_DECL_NSIMSGMESSAGEFETCHPARTSERVICE
   NS_DECL_NSICONTENTHANDLER
 
-protected:
+ protected:
   virtual ~nsImapService();
   char GetHierarchyDelimiter(nsIMsgFolder *aMsgFolder);
 
   nsresult GetFolderName(nsIMsgFolder *aImapFolder, nsACString &aFolderName);
 
   // This is called by both FetchMessage and StreamMessage
-  nsresult GetMessageFromUrl(nsIImapUrl *aImapUrl,
-                             nsImapAction aImapAction,
+  nsresult GetMessageFromUrl(nsIImapUrl *aImapUrl, nsImapAction aImapAction,
                              nsIMsgFolder *aImapMailFolder,
                              nsIImapMessageSink *aImapMessage,
                              nsIMsgWindow *aMsgWindow,
                              nsISupports *aDisplayConsumer,
-                             bool aConvertDataToText,
-                             nsIURI **aURL);
+                             bool aConvertDataToText, nsIURI **aURL);
 
-  nsresult CreateStartOfImapUrl(const nsACString &aImapURI,  // a RDF URI for the current message/folder, can be empty
-                                nsIImapUrl  **imapUrl,
-                                nsIMsgFolder *aImapFolder,
-                                nsIUrlListener *aUrlListener,
-                                nsACString &urlSpec,
-                                char &hierarchyDelimiter);
+  nsresult CreateStartOfImapUrl(
+      const nsACString
+          &aImapURI,  // a RDF URI for the current message/folder, can be empty
+      nsIImapUrl **imapUrl, nsIMsgFolder *aImapFolder,
+      nsIUrlListener *aUrlListener, nsACString &urlSpec,
+      char &hierarchyDelimiter);
 
   nsresult GetImapConnectionAndLoadUrl(nsIImapUrl *aImapUrl,
-                                       nsISupports *aConsumer,
-                                       nsIURI **aURL);
+                                       nsISupports *aConsumer, nsIURI **aURL);
 
   nsresult SetImapUrlSink(nsIMsgFolder *aMsgFolder, nsIImapUrl *aImapUrl);
 
-  nsresult FetchMimePart(nsIImapUrl *aImapUrl,
-                         nsImapAction aImapAction,
+  nsresult FetchMimePart(nsIImapUrl *aImapUrl, nsImapAction aImapAction,
                          nsIMsgFolder *aImapMailFolder,
-                         nsIImapMessageSink *aImapMessage,
-                         nsIURI **aURL,
+                         nsIImapMessageSink *aImapMessage, nsIURI **aURL,
                          nsISupports *aDisplayConsumer,
                          const nsACString &messageIdentifierList,
                          const nsACString &mimePart);
 
   nsresult FolderCommand(nsIMsgFolder *imapMailFolder,
-                         nsIUrlListener *urlListener,
-                         const char *aCommand,
-                         nsImapAction imapAction,
-                         nsIMsgWindow *msgWindow,
+                         nsIUrlListener *urlListener, const char *aCommand,
+                         nsImapAction imapAction, nsIMsgWindow *msgWindow,
                          nsIURI **url);
 
   nsresult ChangeFolderSubscription(nsIMsgFolder *folder,
                                     const nsAString &folderName,
                                     const char *aCommand,
-                                    nsIUrlListener *urlListener,
-                                    nsIURI **url);
+                                    nsIUrlListener *urlListener, nsIURI **url);
 
   nsresult DiddleFlags(nsIMsgFolder *aImapMailFolder,
-                       nsIUrlListener *aUrlListener,
-                       nsIURI **aURL,
+                       nsIUrlListener *aUrlListener, nsIURI **aURL,
                        const nsACString &messageIdentifierList,
-                       const char *howToDiddle,
-                       imapMessageFlagsType flags,
+                       const char *howToDiddle, imapMessageFlagsType flags,
                        bool messageIdsAreUID);
 
-  nsresult OfflineAppendFromFile(nsIFile *aFile,
-                                 nsIURI *aUrl,
+  nsresult OfflineAppendFromFile(nsIFile *aFile, nsIURI *aUrl,
                                  nsIMsgFolder *aDstFolder,
                                  const nsACString &messageId,  // to be replaced
-                                 bool inSelectedState, // needs to be in
-                                 nsIUrlListener *aListener,
-                                 nsIURI **aURL,
+                                 bool inSelectedState,         // needs to be in
+                                 nsIUrlListener *aListener, nsIURI **aURL,
                                  nsISupports *aCopyState);
 
-  nsresult GetServerFromUrl(nsIImapUrl *aImapUrl, nsIMsgIncomingServer **aServer);
+  nsresult GetServerFromUrl(nsIImapUrl *aImapUrl,
+                            nsIMsgIncomingServer **aServer);
 
-  // just a little helper method...maybe it should be a macro? which helps break down a imap message uri
-  // into the folder and message key equivalents
-  nsresult DecomposeImapURI(const nsACString &aMessageURI, nsIMsgFolder **aFolder, nsACString &msgKey);
-  nsresult DecomposeImapURI(const nsACString &aMessageURI, nsIMsgFolder **aFolder, nsMsgKey *msgKey);
-
+  // just a little helper method...maybe it should be a macro? which helps break
+  // down a imap message uri into the folder and message key equivalents
+  nsresult DecomposeImapURI(const nsACString &aMessageURI,
+                            nsIMsgFolder **aFolder, nsACString &msgKey);
+  nsresult DecomposeImapURI(const nsACString &aMessageURI,
+                            nsIMsgFolder **aFolder, nsMsgKey *msgKey);
 
   nsCOMPtr<nsICacheStorage> mCacheStorage;
-  bool mPrintingOperation;                // Flag for printing operations
+  bool mPrintingOperation;  // Flag for printing operations
 };
 
 #endif /* nsImapService_h___ */
--- a/mailnews/imap/src/nsImapStringBundle.cpp
+++ b/mailnews/imap/src/nsImapStringBundle.cpp
@@ -6,36 +6,32 @@
 #include "prmem.h"
 #include "nsCOMPtr.h"
 #include "nsString.h"
 #include "nsIStringBundle.h"
 #include "nsImapStringBundle.h"
 #include "nsServiceManagerUtils.h"
 #include "mozilla/Services.h"
 
-#define IMAP_MSGS_URL       "chrome://messenger/locale/imapMsgs.properties"
+#define IMAP_MSGS_URL "chrome://messenger/locale/imapMsgs.properties"
 
-extern "C"
-nsresult
-IMAPGetStringByName(const char* stringName, char16_t **aString)
-{
-  nsCOMPtr <nsIStringBundle> sBundle;
+extern "C" nsresult IMAPGetStringByName(const char *stringName,
+                                        char16_t **aString) {
+  nsCOMPtr<nsIStringBundle> sBundle;
   nsresult rv = IMAPGetStringBundle(getter_AddRefs(sBundle));
   if (NS_SUCCEEDED(rv) && sBundle) {
     nsAutoString string;
     rv = sBundle->GetStringFromName(stringName, string);
     *aString = ToNewUnicode(string);
   }
   return rv;
 }
 
-nsresult
-IMAPGetStringBundle(nsIStringBundle **aBundle)
-{
-  nsresult rv=NS_OK;
+nsresult IMAPGetStringBundle(nsIStringBundle **aBundle) {
+  nsresult rv = NS_OK;
   nsCOMPtr<nsIStringBundleService> stringService =
-    mozilla::services::GetStringBundleService();
+      mozilla::services::GetStringBundleService();
   if (!stringService) return NS_ERROR_NULL_POINTER;
   nsCOMPtr<nsIStringBundle> stringBundle;
   rv = stringService->CreateBundle(IMAP_MSGS_URL, getter_AddRefs(stringBundle));
   stringBundle.forget(aBundle);
   return rv;
 }
--- a/mailnews/imap/src/nsImapStringBundle.h
+++ b/mailnews/imap/src/nsImapStringBundle.h
@@ -4,14 +4,14 @@
 
 #ifndef _nsImapStringBundle_H__
 #define _nsImapStringBundle_H__
 
 #include "nsIStringBundle.h"
 
 PR_BEGIN_EXTERN_C
 
-nsresult      IMAPGetStringByName(const char* stringName, char16_t **aString);
-nsresult      IMAPGetStringBundle(nsIStringBundle **aBundle);
+nsresult IMAPGetStringByName(const char *stringName, char16_t **aString);
+nsresult IMAPGetStringBundle(nsIStringBundle **aBundle);
 
 PR_END_EXTERN_C
 
 #endif /* _nsImapStringBundle_H__ */
--- a/mailnews/imap/src/nsImapUndoTxn.cpp
+++ b/mailnews/imap/src/nsImapUndoTxn.cpp
@@ -1,37 +1,35 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "msgCore.h" // for precompiled headers
+#include "msgCore.h"  // for precompiled headers
 #include "nsMsgImapCID.h"
 #include "nsIMsgHdr.h"
 #include "nsImapUndoTxn.h"
 #include "nsIMsgIncomingServer.h"
 #include "nsImapMailFolder.h"
 #include "nsIImapService.h"
 #include "nsIDBFolderInfo.h"
 #include "nsIMsgDatabase.h"
 #include "nsMsgUtils.h"
 #include "nsThreadUtils.h"
 #include "nsServiceManagerUtils.h"
 #include "nsComponentManagerUtils.h"
 
-nsImapMoveCopyMsgTxn::nsImapMoveCopyMsgTxn() :
-    m_idsAreUids(false), m_isMove(false), m_srcIsPop3(false)
-{
-}
+nsImapMoveCopyMsgTxn::nsImapMoveCopyMsgTxn()
+    : m_idsAreUids(false), m_isMove(false), m_srcIsPop3(false) {}
 
-nsresult
-nsImapMoveCopyMsgTxn::Init(nsIMsgFolder* srcFolder, nsTArray<nsMsgKey>* srcKeyArray,
-                           const char* srcMsgIdString, nsIMsgFolder* dstFolder,
-                           bool idsAreUids, bool isMove)
-{
+nsresult nsImapMoveCopyMsgTxn::Init(nsIMsgFolder* srcFolder,
+                                    nsTArray<nsMsgKey>* srcKeyArray,
+                                    const char* srcMsgIdString,
+                                    nsIMsgFolder* dstFolder, bool idsAreUids,
+                                    bool isMove) {
   m_srcMsgIdString = srcMsgIdString;
   m_idsAreUids = idsAreUids;
   m_isMove = isMove;
   m_srcFolder = do_GetWeakReference(srcFolder);
   m_dstFolder = do_GetWeakReference(dstFolder);
   m_srcKeyArray = *srcKeyArray;
   m_dupKeyArray = *srcKeyArray;
   nsCString uri;
@@ -41,703 +39,596 @@ nsImapMoveCopyMsgTxn::Init(nsIMsgFolder*
   nsCOMPtr<nsIMsgDatabase> srcDB;
   rv = srcFolder->GetMsgDatabase(getter_AddRefs(srcDB));
   NS_ENSURE_SUCCESS(rv, rv);
   uint32_t i, count = m_srcKeyArray.Length();
   nsCOMPtr<nsIMsgDBHdr> srcHdr;
   nsCOMPtr<nsIMsgDBHdr> copySrcHdr;
   nsCString messageId;
 
-  for (i = 0; i < count; i++)
-  {
-    rv = srcDB->GetMsgHdrForKey(m_srcKeyArray[i],
-      getter_AddRefs(srcHdr));
-    if (NS_SUCCEEDED(rv))
-    {
+  for (i = 0; i < count; i++) {
+    rv = srcDB->GetMsgHdrForKey(m_srcKeyArray[i], getter_AddRefs(srcHdr));
+    if (NS_SUCCEEDED(rv)) {
       // ** jt -- only do this for mailbox protocol
-      if (MsgLowerCaseEqualsLiteral(protocolType, "mailbox"))
-      {
+      if (MsgLowerCaseEqualsLiteral(protocolType, "mailbox")) {
         m_srcIsPop3 = true;
         uint32_t msgSize;
         rv = srcHdr->GetMessageSize(&msgSize);
-        if (NS_SUCCEEDED(rv))
-          m_srcSizeArray.AppendElement(msgSize);
-        if (isMove)
-        {
+        if (NS_SUCCEEDED(rv)) m_srcSizeArray.AppendElement(msgSize);
+        if (isMove) {
           rv = srcDB->CopyHdrFromExistingHdr(nsMsgKey_None, srcHdr, false,
                                              getter_AddRefs(copySrcHdr));
           nsMsgKey pseudoKey = nsMsgKey_None;
-          if (NS_SUCCEEDED(rv))
-          {
+          if (NS_SUCCEEDED(rv)) {
             copySrcHdr->GetMessageKey(&pseudoKey);
             m_srcHdrs.AppendObject(copySrcHdr);
           }
           m_dupKeyArray[i] = pseudoKey;
         }
       }
       srcHdr->GetMessageId(getter_Copies(messageId));
       m_srcMessageIds.AppendElement(messageId);
     }
   }
   return nsMsgTxn::Init();
 }
 
-nsImapMoveCopyMsgTxn::~nsImapMoveCopyMsgTxn()
-{
-}
+nsImapMoveCopyMsgTxn::~nsImapMoveCopyMsgTxn() {}
 
 NS_IMPL_ISUPPORTS_INHERITED(nsImapMoveCopyMsgTxn, nsMsgTxn, nsIUrlListener)
 
 NS_IMETHODIMP
-nsImapMoveCopyMsgTxn::UndoTransaction(void)
-{
+nsImapMoveCopyMsgTxn::UndoTransaction(void) {
   nsresult rv;
-  nsCOMPtr<nsIImapService> imapService = do_GetService(NS_IMAPSERVICE_CONTRACTID, &rv);
+  nsCOMPtr<nsIImapService> imapService =
+      do_GetService(NS_IMAPSERVICE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool finishInOnStopRunningUrl = false;
 
-  if (m_isMove || !m_dstFolder)
-  {
-    if (m_srcIsPop3)
-    {
+  if (m_isMove || !m_dstFolder) {
+    if (m_srcIsPop3) {
       rv = UndoMailboxDelete();
       NS_ENSURE_SUCCESS(rv, rv);
-    }
-    else
-    {
+    } else {
       nsCOMPtr<nsIMsgFolder> srcFolder = do_QueryReferent(m_srcFolder, &rv);
-      if (NS_FAILED(rv) || !srcFolder)
-        return rv;
+      if (NS_FAILED(rv) || !srcFolder) return rv;
       nsCOMPtr<nsIUrlListener> srcListener = do_QueryInterface(srcFolder, &rv);
-      if (NS_FAILED(rv))
-        return rv;
-      m_onStopListener =   do_GetWeakReference(srcListener);
+      if (NS_FAILED(rv)) return rv;
+      m_onStopListener = do_GetWeakReference(srcListener);
 
       // ** make sure we are in the selected state; use lite select
       // folder so we won't hit performance hard
-      rv = imapService->LiteSelectFolder(srcFolder, srcListener, nullptr, nullptr);
-      if (NS_FAILED(rv))
-        return rv;
-      bool deletedMsgs = true; //default is true unless imapDelete model
+      rv = imapService->LiteSelectFolder(srcFolder, srcListener, nullptr,
+                                         nullptr);
+      if (NS_FAILED(rv)) return rv;
+      bool deletedMsgs = true;  // default is true unless imapDelete model
       nsMsgImapDeleteModel deleteModel;
       rv = GetImapDeleteModel(srcFolder, &deleteModel);
 
       // protect against a bogus undo txn without any source keys
       // see bug #179856 for details
       NS_ASSERTION(!m_srcKeyArray.IsEmpty(), "no source keys");
-      if (m_srcKeyArray.IsEmpty())
-        return NS_ERROR_UNEXPECTED;
+      if (m_srcKeyArray.IsEmpty()) return NS_ERROR_UNEXPECTED;
 
-      if (!m_srcMsgIdString.IsEmpty())
-      {
-        if (NS_SUCCEEDED(rv) && deleteModel == nsMsgImapDeleteModels::IMAPDelete)
+      if (!m_srcMsgIdString.IsEmpty()) {
+        if (NS_SUCCEEDED(rv) &&
+            deleteModel == nsMsgImapDeleteModels::IMAPDelete)
           CheckForToggleDelete(srcFolder, m_srcKeyArray[0], &deletedMsgs);
 
         if (deletedMsgs)
-          rv = imapService->SubtractMessageFlags(srcFolder,
-                                                 this, nullptr,
-                                                 m_srcMsgIdString,
-                                                 kImapMsgDeletedFlag,
-                                                 m_idsAreUids);
+          rv = imapService->SubtractMessageFlags(
+              srcFolder, this, nullptr, m_srcMsgIdString, kImapMsgDeletedFlag,
+              m_idsAreUids);
         else
-          rv = imapService->AddMessageFlags(srcFolder,
-                                            srcListener, nullptr,
+          rv = imapService->AddMessageFlags(srcFolder, srcListener, nullptr,
                                             m_srcMsgIdString,
-                                            kImapMsgDeletedFlag,
-                                            m_idsAreUids);
-        if (NS_FAILED(rv))
-          return rv;
+                                            kImapMsgDeletedFlag, m_idsAreUids);
+        if (NS_FAILED(rv)) return rv;
 
         finishInOnStopRunningUrl = true;
         if (deleteModel != nsMsgImapDeleteModels::IMAPDelete)
           rv = imapService->GetHeaders(srcFolder, srcListener, nullptr,
                                        m_srcMsgIdString, true);
       }
     }
   }
-  if (!finishInOnStopRunningUrl && !m_dstMsgIdString.IsEmpty())
-  {
+  if (!finishInOnStopRunningUrl && !m_dstMsgIdString.IsEmpty()) {
     nsCOMPtr<nsIMsgFolder> dstFolder = do_QueryReferent(m_dstFolder, &rv);
-    if (NS_FAILED(rv) || !dstFolder)
-      return rv;
+    if (NS_FAILED(rv) || !dstFolder) return rv;
 
     nsCOMPtr<nsIUrlListener> dstListener;
 
     dstListener = do_QueryInterface(dstFolder, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
     // ** make sure we are in the selected state; use lite select folder
     // so we won't potentially download a bunch of headers.
-    rv = imapService->LiteSelectFolder(dstFolder,
-      dstListener, nullptr, nullptr);
+    rv =
+        imapService->LiteSelectFolder(dstFolder, dstListener, nullptr, nullptr);
     NS_ENSURE_SUCCESS(rv, rv);
-    rv = imapService->AddMessageFlags(dstFolder, dstListener,
-                                      nullptr, m_dstMsgIdString,
-                                      kImapMsgDeletedFlag, m_idsAreUids);
+    rv = imapService->AddMessageFlags(dstFolder, dstListener, nullptr,
+                                      m_dstMsgIdString, kImapMsgDeletedFlag,
+                                      m_idsAreUids);
   }
   return rv;
 }
 
 NS_IMETHODIMP
-nsImapMoveCopyMsgTxn::RedoTransaction(void)
-{
+nsImapMoveCopyMsgTxn::RedoTransaction(void) {
   nsresult rv;
-  nsCOMPtr<nsIImapService> imapService = do_GetService(NS_IMAPSERVICE_CONTRACTID, &rv);
+  nsCOMPtr<nsIImapService> imapService =
+      do_GetService(NS_IMAPSERVICE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (m_isMove || !m_dstFolder)
-  {
-    if (m_srcIsPop3)
-    {
+  if (m_isMove || !m_dstFolder) {
+    if (m_srcIsPop3) {
       rv = RedoMailboxDelete();
       if (NS_FAILED(rv)) return rv;
-    }
-    else if (!m_srcMsgIdString.IsEmpty())
-    {
+    } else if (!m_srcMsgIdString.IsEmpty()) {
       nsCOMPtr<nsIMsgFolder> srcFolder = do_QueryReferent(m_srcFolder, &rv);
-      if (NS_FAILED(rv) || !srcFolder)
-        return rv;
+      if (NS_FAILED(rv) || !srcFolder) return rv;
       nsCOMPtr<nsIUrlListener> srcListener = do_QueryInterface(srcFolder, &rv);
       NS_ENSURE_SUCCESS(rv, rv);
 
-      bool deletedMsgs = false;  //default will be false unless imapDeleteModel;
+      bool deletedMsgs = false;  // default will be false unless
+                                 // imapDeleteModel;
       nsMsgImapDeleteModel deleteModel;
       rv = GetImapDeleteModel(srcFolder, &deleteModel);
 
       // protect against a bogus undo txn without any source keys
       // see bug #179856 for details
       NS_ASSERTION(!m_srcKeyArray.IsEmpty(), "no source keys");
-      if (m_srcKeyArray.IsEmpty())
-        return NS_ERROR_UNEXPECTED;
+      if (m_srcKeyArray.IsEmpty()) return NS_ERROR_UNEXPECTED;
 
       if (NS_SUCCEEDED(rv) && deleteModel == nsMsgImapDeleteModels::IMAPDelete)
         rv = CheckForToggleDelete(srcFolder, m_srcKeyArray[0], &deletedMsgs);
 
       // Make sure we are in the selected state; use lite select
       // folder so performance won't suffer.
-      rv = imapService->LiteSelectFolder(srcFolder, srcListener, nullptr, nullptr);
+      rv = imapService->LiteSelectFolder(srcFolder, srcListener, nullptr,
+                                         nullptr);
       NS_ENSURE_SUCCESS(rv, rv);
-      if (deletedMsgs)
-      {
-        rv = imapService->SubtractMessageFlags(srcFolder,
-                                               srcListener, nullptr,
-                                               m_srcMsgIdString,
-                                               kImapMsgDeletedFlag,
-                                               m_idsAreUids);
-      }
-      else
-      {
-        rv = imapService->AddMessageFlags(srcFolder,
-                                          srcListener, nullptr, m_srcMsgIdString,
-                                          kImapMsgDeletedFlag, m_idsAreUids);
+      if (deletedMsgs) {
+        rv = imapService->SubtractMessageFlags(
+            srcFolder, srcListener, nullptr, m_srcMsgIdString,
+            kImapMsgDeletedFlag, m_idsAreUids);
+      } else {
+        rv = imapService->AddMessageFlags(srcFolder, srcListener, nullptr,
+                                          m_srcMsgIdString, kImapMsgDeletedFlag,
+                                          m_idsAreUids);
       }
     }
   }
-  if (!m_dstMsgIdString.IsEmpty())
-  {
+  if (!m_dstMsgIdString.IsEmpty()) {
     nsCOMPtr<nsIMsgFolder> dstFolder = do_QueryReferent(m_dstFolder, &rv);
     if (NS_FAILED(rv) || !dstFolder) return rv;
 
     nsCOMPtr<nsIUrlListener> dstListener;
 
     dstListener = do_QueryInterface(dstFolder, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
     // ** make sure we are in the selected state; use lite select
     // folder so we won't hit performance hard
-    rv = imapService->LiteSelectFolder(dstFolder, dstListener, nullptr, nullptr);
+    rv =
+        imapService->LiteSelectFolder(dstFolder, dstListener, nullptr, nullptr);
     NS_ENSURE_SUCCESS(rv, rv);
-    rv = imapService->SubtractMessageFlags(dstFolder,
-                                           dstListener, nullptr,
+    rv = imapService->SubtractMessageFlags(dstFolder, dstListener, nullptr,
                                            m_dstMsgIdString,
-                                           kImapMsgDeletedFlag,
-                                           m_idsAreUids);
+                                           kImapMsgDeletedFlag, m_idsAreUids);
     NS_ENSURE_SUCCESS(rv, rv);
     nsMsgImapDeleteModel deleteModel;
     rv = GetImapDeleteModel(dstFolder, &deleteModel);
-    if (NS_FAILED(rv) || deleteModel == nsMsgImapDeleteModels::MoveToTrash)
-    {
-      rv = imapService->GetHeaders(dstFolder, dstListener,
-                                   nullptr, m_dstMsgIdString, true);
+    if (NS_FAILED(rv) || deleteModel == nsMsgImapDeleteModels::MoveToTrash) {
+      rv = imapService->GetHeaders(dstFolder, dstListener, nullptr,
+                                   m_dstMsgIdString, true);
     }
   }
   return rv;
 }
 
-nsresult
-nsImapMoveCopyMsgTxn::SetCopyResponseUid(const char* aMsgIdString)
-{
+nsresult nsImapMoveCopyMsgTxn::SetCopyResponseUid(const char* aMsgIdString) {
   if (!aMsgIdString) return NS_ERROR_NULL_POINTER;
   m_dstMsgIdString = aMsgIdString;
-  if (m_dstMsgIdString.Last() == ']')
-  {
+  if (m_dstMsgIdString.Last() == ']') {
     int32_t len = m_dstMsgIdString.Length();
     m_dstMsgIdString.SetLength(len - 1);
   }
   return NS_OK;
 }
 
-nsresult
-nsImapMoveCopyMsgTxn::GetSrcKeyArray(nsTArray<nsMsgKey>& srcKeyArray)
-{
-    srcKeyArray = m_srcKeyArray;
-    return NS_OK;
+nsresult nsImapMoveCopyMsgTxn::GetSrcKeyArray(nsTArray<nsMsgKey>& srcKeyArray) {
+  srcKeyArray = m_srcKeyArray;
+  return NS_OK;
 }
 
-nsresult
-nsImapMoveCopyMsgTxn::AddDstKey(nsMsgKey aKey)
-{
-    if (!m_dstMsgIdString.IsEmpty())
-        m_dstMsgIdString.Append(',');
-    m_dstMsgIdString.AppendInt((int32_t) aKey);
-    return NS_OK;
+nsresult nsImapMoveCopyMsgTxn::AddDstKey(nsMsgKey aKey) {
+  if (!m_dstMsgIdString.IsEmpty()) m_dstMsgIdString.Append(',');
+  m_dstMsgIdString.AppendInt((int32_t)aKey);
+  return NS_OK;
 }
 
-nsresult
-nsImapMoveCopyMsgTxn::UndoMailboxDelete()
-{
-    nsresult rv = NS_ERROR_FAILURE;
-    // ** jt -- only do this for mailbox protocol
-    if (m_srcIsPop3)
-    {
-        nsCOMPtr<nsIMsgFolder> srcFolder = do_QueryReferent(m_srcFolder, &rv);
-        if (NS_FAILED(rv) || !srcFolder) return rv;
+nsresult nsImapMoveCopyMsgTxn::UndoMailboxDelete() {
+  nsresult rv = NS_ERROR_FAILURE;
+  // ** jt -- only do this for mailbox protocol
+  if (m_srcIsPop3) {
+    nsCOMPtr<nsIMsgFolder> srcFolder = do_QueryReferent(m_srcFolder, &rv);