public void FormatSqlInTextDoc(DTE2 dte) { //TODO: Add check for no active doc (with translation, etc) string fileExtension = System.IO.Path.GetExtension(dte.ActiveDocument.FullName); bool isSqlFile = fileExtension.ToUpper().Equals(".SQL"); if (isSqlFile || MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes) { string fullText = SelectAllCodeFromDocument(dte.ActiveDocument); TextSelection selection = (TextSelection)dte.ActiveDocument.Selection; if (!selection.IsActiveEndGreater) { selection.SwapAnchor(); } string selectionText = selection.Text; bool formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length; int cursorPoint = selection.ActivePoint.AbsoluteCharOffset; string textToFormat = formatSelectionOnly ? selectionText : fullText; bool errorsFound = false; string formattedText = _formattingManager.Format(textToFormat, ref errorsFound); bool abortFormatting = false; if (errorsFound) { abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes; } if (!abortFormatting) { if (formatSelectionOnly) { selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText); } else { //if whole doc then replace all text, and put the cursor approximately where it was (using proportion of text total length before and after) int newPosition = (int)Math.Round(1.0 * cursorPoint * formattedText.Length / textToFormat.Length, 0, MidpointRounding.AwayFromZero); ReplaceAllCodeInDocument(dte.ActiveDocument, formattedText); SafelySetCursorAt(dte.ActiveDocument, newPosition); } } } }
/// <summary> /// Get and position EditPoint objects to include all of original text that is selected, plus surrounding text for complete lines of text /// </summary> /// <param name="document"></param> /// <param name="earlierPoint"></param> /// <param name="laterPoint"></param> public void GetEditPointsForLinesToCheck(TextDocument document, out EditPoint earlierPoint, out EditPoint laterPoint) { TextSelection selection = document.Selection; // Reorder selection points as needed if (selection.IsActiveEndGreater) { selection.SwapAnchor(); } // Get and position EditPoint objects to include all of original text that is selected, plus surrounding text for complete lines of text earlierPoint = selection.ActivePoint.CreateEditPoint(); laterPoint = selection.AnchorPoint.CreateEditPoint(); earlierPoint.StartOfLine(); laterPoint.LineDown(1); laterPoint.StartOfLine(); }
/// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary> /// <param term='commandName'>The name of the command to execute.</param> /// <param term='executeOption'>Describes how the command should be run.</param> /// <param term='varIn'>Parameters passed from the caller to the command handler.</param> /// <param term='varOut'>Parameters passed from the command handler to the caller.</param> /// <param term='handled'>Informs the caller if the command was handled or not.</param> /// <seealso class='Exec' /> public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled) { handled = false; if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault) { if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow")) { string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName); bool isSqlFile = fileExtension.ToUpper().Equals(".SQL"); if (isSqlFile || MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes) { string fullText = SelectAllCodeFromDocument(_applicationObject.ActiveDocument); TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection; if (!selection.IsActiveEndGreater) { selection.SwapAnchor(); } if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" ")) { selection.CharLeft(true, 1); //newline counts as a distance of one. } string selectionText = selection.Text; bool formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length; int cursorPoint = selection.ActivePoint.AbsoluteCharOffset; string textToFormat = formatSelectionOnly ? selectionText : fullText; bool errorsFound = false; string formattedText = _formattingManager.Format(textToFormat, ref errorsFound); bool abortFormatting = false; if (errorsFound) { abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes; } if (!abortFormatting) { if (formatSelectionOnly) { //if selection just delete/insert, so the active point is at the end of the selection selection.Delete(1); selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText); } else { //if whole doc then replace all text, and put the cursor approximately where it was (using proportion of text total length before and after) int newPosition = (int)Math.Round(1.0 * cursorPoint * formattedText.Length / textToFormat.Length, 0, MidpointRounding.AwayFromZero); ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText); ((TextSelection)(_applicationObject.ActiveDocument.Selection)).MoveToAbsoluteOffset(newPosition, false); } } } handled = true; return; } if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions")) { GetFormatHotkey(); SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"), new SettingsForm.GetTextEditorKeyBindingScopeName(GetTextEditorKeyBindingScopeName)); if (settings.ShowDialog() == DialogResult.OK) { SetFormatHotkey(); _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default); } settings.Dispose(); } } }
/// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary> /// <param term='commandName'>The name of the command to execute.</param> /// <param term='executeOption'>Describes how the command should be run.</param> /// <param term='varIn'>Parameters passed from the caller to the command handler.</param> /// <param term='varOut'>Parameters passed from the command handler to the caller.</param> /// <param term='handled'>Informs the caller if the command was handled or not.</param> /// <seealso class='Exec' /> public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled) { handled = false; if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault) { if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow")) { string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName); bool isSqlFile = fileExtension.ToUpper().Equals(".SQL"); if (isSqlFile || MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes) { string fullText = SelectAllCodeFromDocument(_applicationObject.ActiveDocument); TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection; if (!selection.IsActiveEndGreater) { selection.SwapAnchor(); } if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" ")) { selection.CharLeft(true, 1); //newline counts as a distance of one. } string selectionText = selection.Text; bool formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length; string textToFormat = formatSelectionOnly ? selectionText : fullText; var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter( Properties.Settings.Default.IndentString.Replace("\\t", "\t"), Properties.Settings.Default.SpacesPerTab, Properties.Settings.Default.MaxLineWidth, Properties.Settings.Default.ExpandCommaLists, Properties.Settings.Default.TrailingCommas, Properties.Settings.Default.SpaceAfterExpandedComma, Properties.Settings.Default.ExpandBooleanExpressions, Properties.Settings.Default.ExpandCaseStatements, Properties.Settings.Default.ExpandBetweenConditions, Properties.Settings.Default.BreakJoinOnSections, Properties.Settings.Default.UppercaseKeywords, false, Properties.Settings.Default.KeywordStandardization ); formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix"); var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter); bool errorsFound = false; string formattedText = formattingManager.Format(textToFormat, ref errorsFound); bool abortFormatting = false; if (errorsFound) { abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes; } if (!abortFormatting) { if (formatSelectionOnly) { selection.Delete(1); selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText); } else { ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText); } } } handled = true; return; } if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions")) { SettingsForm settings = new SettingsForm(); if (settings.ShowDialog() == DialogResult.OK) { SetFormatHotkey(); } settings.Dispose(); } } }
/// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary> /// <param term='commandName'>The name of the command to execute.</param> /// <param term='executeOption'>Describes how the command should be run.</param> /// <param term='varIn'>Parameters passed from the caller to the command handler.</param> /// <param term='varOut'>Parameters passed from the command handler to the caller.</param> /// <param term='handled'>Informs the caller if the command was handled or not.</param> /// <seealso class='Exec' /> public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled) { handled = false; if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault) { if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormatSelectionOrActiveWindow")) { string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName); bool isSqlFile = fileExtension.ToUpper().Equals(".SQL"); if (isSqlFile || MessageBox.Show(_generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), MessageBoxButtons.YesNo) == DialogResult.Yes) { string fullText = SelectAllCodeFromDocument(_applicationObject.ActiveDocument); TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection; if (!selection.IsActiveEndGreater) { selection.SwapAnchor(); } if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" ")) { selection.CharLeft(true, 1); //newline counts as a distance of one. } string selectionText = selection.Text; bool formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length; string textToFormat = formatSelectionOnly ? selectionText : fullText; bool errorsFound = false; string formattedText = _formattingManager.Format(textToFormat, ref errorsFound); bool abortFormatting = false; if (errorsFound) { abortFormatting = MessageBox.Show(_generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), MessageBoxButtons.YesNo) != DialogResult.Yes; } if (!abortFormatting) { if (formatSelectionOnly) { selection.Delete(1); selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText); } else { ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText); } } } handled = true; return; } if (commandName.Equals("PoorMansTSqlFormatterSSMSAddIn.AddinConnector.FormattingOptions")) { SettingsForm settings = new SettingsForm(Properties.Settings.Default, Assembly.GetExecutingAssembly(), _generalResourceManager.GetString("ProjectAboutDescription"), new SettingsForm.GetTextEditorKeyBindingScopeName(GetTextEditorKeyBindingScopeName)); if (settings.ShowDialog() == DialogResult.OK) { SetFormatHotkey(); _formattingManager = Utils.GetFormattingManager(Properties.Settings.Default); } settings.Dispose(); } } }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void MenuFormatCallback(object sender, EventArgs e) { if (_applicationObject.ActiveDocument == null) { return; } string fileExtension = System.IO.Path.GetExtension(_applicationObject.ActiveDocument.FullName); bool isSqlFile = fileExtension.ToUpper().Equals(".SQL"); if (isSqlFile || VsShellUtilities.ShowMessageBox( this.ServiceProvider, _generalResourceManager.GetString("FileTypeWarningMessage"), _generalResourceManager.GetString("FileTypeWarningMessageTitle"), OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST ) == OLEMSGRESULT_YES) { string fullText = SelectAllCodeFromDocument(_applicationObject.ActiveDocument); TextSelection selection = (TextSelection)_applicationObject.ActiveDocument.Selection; if (!selection.IsActiveEndGreater) { selection.SwapAnchor(); } if (selection.Text.EndsWith(Environment.NewLine) || selection.Text.EndsWith(" ")) { selection.CharLeft(true, 1); //newline counts as a distance of one. } string selectionText = selection.Text; bool formatSelectionOnly = selectionText.Length > 0 && selectionText.Length != fullText.Length; int cursorPoint = selection.ActivePoint.AbsoluteCharOffset; string textToFormat = formatSelectionOnly ? selectionText : fullText; bool errorsFound = false; string formattedText = _formattingManager.Format(textToFormat, ref errorsFound); bool abortFormatting = false; if (errorsFound) { abortFormatting = VsShellUtilities.ShowMessageBox( this.ServiceProvider, _generalResourceManager.GetString("ParseErrorWarningMessage"), _generalResourceManager.GetString("ParseErrorWarningMessageTitle"), OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST ) != OLEMSGRESULT_YES; } if (!abortFormatting) { if (formatSelectionOnly) { //if selection just delete/insert, so the active point is at the end of the selection selection.Delete(1); selection.Insert(formattedText, (int)EnvDTE.vsInsertFlags.vsInsertFlagsContainNewText); } else { //if whole doc then replace all text, and put the cursor approximately where it was (using proportion of text total length before and after) //int newPosition = (int)Math.Round(1.0 * cursorPoint * formattedText.Length / textToFormat.Length, 0, MidpointRounding.AwayFromZero); ReplaceAllCodeInDocument(_applicationObject.ActiveDocument, formattedText); //((TextSelection)(_applicationObject.ActiveDocument.Selection)).MoveToAbsoluteOffset(newPosition, false); } } } }
void BeforeKeyPress(string Keypress, TextSelection Selection, bool InStatementCompletion, ref bool CancelKeypress) { if (isOn) { bool isAlpha = (Keypress[0] >= 'A' && Keypress[0] <= 'Z') || (Keypress[0] >= 'a' && Keypress[0] <= 'z'); bool swap = Selection.IsActiveEndGreater; if (isAlpha) { if (!nextShouldBeCaps) { if (swap) Selection.SwapAnchor(); Selection.CharLeft(true); if (Selection.Text[0] == '_') nextShouldBeCaps = true; Selection.CharRight(true); if (swap) Selection.SwapAnchor(); } if (nextShouldBeCaps) { CancelKeypress = true; if (!Selection.IsEmpty) { Selection.Delete(); } Selection.Insert(Keypress.ToUpper()); } } else if (Keypress == " ") { CancelKeypress = true; if (!Selection.IsEmpty) { Selection.Delete(); } Selection.Insert("_"); } else if (Keypress == "(") { CancelKeypress = false; ToggleIsOn(); } nextShouldBeCaps = false; } }