private void FormatDocument(EnvDTE.ProjectItem item) { Contract.Requires(item != null); try { var fileName = item.FileNames[0]; Contract.Assume(Dte.ItemOperations != null); var shouldClose = fileName == null || !Dte.ItemOperations.IsFileOpen(fileName, VSConstants.LOGVIEWID.Code_string); var window = item.Open(VSConstants.LOGVIEWID.Code_string); if (window != null) { window.Activate(); Contract.Assume(Dte.Commands != null); Dte.Commands.Raise(Guids.vsStd2kCmdIdString, (int)VSConstants.VSStd2KCmdID.FORMATDOCUMENT, null, null); if (shouldClose) { window.Close(EnvDTE.vsSaveChanges.vsSaveChangesYes); } else { item.Save(); } } } catch (Exception ex) { Debug.WriteLine("Failed to format item. Error: " + ex, packageTitle); } }