public bool BeforeKeyPress(string key, TextSelection selection, bool inStatementCompletion, ref bool cancelKeyPress) { if (!selection.IsEmpty || key != _key) { return(false); } cancelKeyPress = true; var closeUndoContext = !DTE.UndoContext.IsOpen; if (closeUndoContext) { selection.BeginUpdate("insert " + _template); } selection.Insert(_template); if (_caret != 0) { selection.CharLeft(false, -_caret); } if (closeUndoContext) { selection.EndUpdate(); } return(true); }
private void BeforeKeyPress(string keypress, TextSelection selection, bool inStatementCompletion, ref bool cancelKeypress) { if (!ConvertTabsToSpaces || !selection.IsEmpty || inStatementCompletion) return; switch (keypress) { case BACKSPACE_KEY: do { selection.CharLeft(true); if (selection.Text == " ") { cancelKeypress = true; selection.Delete(); continue; } selection.CharRight(true); return; } while (selection.CurrentColumn%IndentSize != 1); return; case DELETE_KEY: for (var i = 0; i < IndentSize; i++) { selection.CharRight(true); if (selection.Text == " ") { cancelKeypress = true; selection.Delete(); continue; } selection.CharLeft(true); return; } return; } }
private bool Apply(TextSelection selection, string value) { selection.CharLeft(true, _match.Length); if (selection.Text != _match) { selection.CharRight(false); return(false); } selection.Insert(value, (int)vsInsertFlags.vsInsertFlagsContainNewText); selection.CharRight(false); return(true); }
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { try { if (VsShellUtilities.IsInAutomationFunction(m_provider.ServiceProvider)) { return(m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut)); } // make a copy of this so we can look at it after forwarding some commands uint commandID = nCmdID; char typedChar = char.MinValue; // make sure the input is a char before getting it if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR) { typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn); } // check for the triple slash if (typedChar == '/' && m_dte != null) { string currentLine = m_textView.TextSnapshot.GetLineFromPosition( m_textView.Caret.Position.BufferPosition.Position).GetText(); if ((currentLine + "/").Trim() == "///") { // Calculate how many spaces string spaces = currentLine.Replace(currentLine.TrimStart(), ""); TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection; int oldLine = ts.ActivePoint.Line; int oldOffset = ts.ActivePoint.LineCharOffset; ts.LineDown(); ts.EndOfLine(); CodeElement codeElement = null; FileCodeModel fcm = m_dte.ActiveDocument.ProjectItem.FileCodeModel; if (fcm != null) { codeElement = fcm.CodeElementFromPoint(ts.ActivePoint, vsCMElement.vsCMElementFunction); } if (codeElement != null && codeElement is CodeFunction) { CodeFunction function = codeElement as CodeFunction; StringBuilder sb = new StringBuilder("/ <summary>\r\n" + spaces + "/// \r\n" + spaces + "/// </summary>"); foreach (CodeElement child in codeElement.Children) { CodeParameter parameter = child as CodeParameter; if (parameter != null) { sb.AppendFormat("\r\n" + spaces + "/// <param name=\"{0}\"></param>", parameter.Name); } } if (function.Type.AsString != "void") { sb.AppendFormat("\r\n" + spaces + "/// <returns></returns>"); } ts.MoveToLineAndOffset(oldLine, oldOffset); ts.Insert(sb.ToString()); ts.MoveToLineAndOffset(oldLine, oldOffset); ts.LineDown(); ts.EndOfLine(); return(VSConstants.S_OK); } else { ts.MoveToLineAndOffset(oldLine, oldOffset); ts.Insert("/ <summary>\r\n" + spaces + "/// \r\n" + spaces + "/// </summary>"); ts.MoveToLineAndOffset(oldLine, oldOffset); ts.LineDown(); ts.EndOfLine(); return(VSConstants.S_OK); } } } if (m_session != null && !m_session.IsDismissed) { // check for a commit character if (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN || nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB || typedChar == '>') { // check for a selection // if the selection is fully selected, commit the current session if (m_session.SelectedCompletionSet.SelectionStatus.IsSelected) { string selectedCompletion = m_session.SelectedCompletionSet.SelectionStatus.Completion.DisplayText; m_session.Commit(); TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection; switch (selectedCompletion) { case "<!-->": ts.CharLeft(false, 3); break; case "<![CDATA[>": ts.CharLeft(false, 3); break; case "<c>": ts.CharLeft(false, 4); break; case "<code>": ts.CharLeft(false, 7); break; case "<example>": ts.CharLeft(false, 10); break; case "<exception>": ts.CharLeft(false, 14); break; case "<include>": ts.CharLeft(false, 21); break; case "<list>": ts.CharLeft(false, 7); break; case "<para>": ts.CharLeft(false, 7); break; case "<param>": ts.CharLeft(false, 10); break; case "<paramref>": ts.CharLeft(false, 13); break; case "<permission>": ts.CharLeft(false, 15); break; case "<remarks>": ts.CharLeft(false, 10); break; case "<returns>": ts.CharLeft(false, 10); break; case "<see>": ts.CharLeft(false, 3); break; case "<seealso>": ts.CharLeft(false, 3); break; case "<typeparam>": ts.CharLeft(false, 14); break; case "<typeparamref>": ts.CharLeft(false, 3); break; case "<value>": ts.CharLeft(false, 8); break; default: break; } // also, don't add the character to the buffer return(VSConstants.S_OK); } else { // if there is no selection, dismiss the session m_session.Dismiss(); } } } else { if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN) { string currentLine = m_textView.TextSnapshot.GetLineFromPosition( m_textView.Caret.Position.BufferPosition.Position).GetText(); if (currentLine.TrimStart().StartsWith("///")) { TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection; string spaces = currentLine.Replace(currentLine.TrimStart(), ""); ts.Insert("\r\n" + spaces + "/// "); return(VSConstants.S_OK); } } } // pass along the command so the char is added to the buffer int retVal = m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); if (typedChar == '<') { string currentLine = m_textView.TextSnapshot.GetLineFromPosition( m_textView.Caret.Position.BufferPosition.Position).GetText(); if (currentLine.TrimStart().StartsWith("///")) { if (m_session == null || m_session.IsDismissed) // If there is no active session, bring up completion { if (this.TriggerCompletion()) { m_session.SelectedCompletionSet.SelectBestMatch(); m_session.SelectedCompletionSet.Recalculate(); return(VSConstants.S_OK); } } } } else if ( commandID == (uint)VSConstants.VSStd2KCmdID.BACKSPACE || commandID == (uint)VSConstants.VSStd2KCmdID.DELETE || char.IsLetter(typedChar)) { if (m_session != null && !m_session.IsDismissed) // the completion session is already active, so just filter { m_session.SelectedCompletionSet.SelectBestMatch(); m_session.SelectedCompletionSet.Recalculate(); return(VSConstants.S_OK); } } return(retVal); } catch { } return(VSConstants.E_FAIL); }
/// <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> /// Inserts the method header. /// </summary> /// ------------------------------------------------------------------------------------ public void InsertMethodHeader() { TextSelection sel = (TextSelection)m_applicationObject.ActiveDocument.Selection; CodeElement codeElement = GetMethodOrProperty(sel); if (codeElement == null) { codeElement = sel.ActivePoint.get_CodeElement(vsCMElement.vsCMElementClass); if (codeElement == null) { codeElement = sel.ActivePoint.get_CodeElement(vsCMElement.vsCMElementInterface); } if (codeElement == null || codeElement.StartPoint.Line != sel.ActivePoint.Line) { // not a function or property, so just insert /// <summary/> sel.LineUp(false, 1); if (!IsXmlCommentLine) { sel.EndOfLine(false); sel.NewLine(1); sel.Text = "///"; sel.LineDown(true, 1); sel.Delete(1); sel.LineUp(false, 1); sel.EndOfLine(false); sel.WordRight(true, 2); sel.Delete(1); } else { sel.LineDown(false, 1); } return; } } sel.MoveToPoint(codeElement.StartPoint, false); // Figure out indentation and build dashed line sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, false); sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, true); string indent = sel.Text; sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false); string dashedLine = indent + "/// " + new string('-', kLineLen - sel.ActivePoint.VirtualDisplayColumn - 4); bool fGhostDoc = true; try { // Use GhostDoc if available string addinName = string.Empty; foreach (AddIn addin in m_applicationObject.AddIns) { if (addin.Name == "GhostDoc") { addinName = (addin.ProgID == "SubMain.GhostDoc.Connect") ? "Tools.SubMain.GhostDoc.DocumentThis" : "Weigelt.GhostDoc.AddIn.DocumentThis"; break; } } if (addinName != string.Empty) { m_applicationObject.ExecuteCommand(addinName, string.Empty); } else { fGhostDoc = false; } } catch { fGhostDoc = false; } if (fGhostDoc) { int nLine = sel.ActivePoint.Line; int nLineOffset = sel.ActivePoint.LineCharOffset; // Check to see if we're in the middle of the comment or at the beginning of // the method. sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false); if (GetMethodOrProperty(sel) == null) { // we're in the middle of the comment - move to the end of the comment MoveDownAfterComment(sel); // we're inserting one line (//---) above nLine++; } else { // We are at the beginning of the method. // Check to see if the line above the current line is an attribute. If it is we want to // start there, otherwise we start at the current line. sel.LineUp(false, 1); sel.CharRight(false, 1); if (sel.ActivePoint.get_CodeElement(vsCMElement.vsCMElementAttribute) == null) { sel.MoveToLineAndOffset(nLine, 1, false); } // we're inserting two lines above nLine += 2; } // In case the line is wrapped, we want to go to the real beginning of the line sel.MoveToLineAndOffset(sel.ActivePoint.Line, 1, false); sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, false); // Insert a new line and then insert our dashed line. sel.Insert(dashedLine + Environment.NewLine, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd); sel.LineUp(false, 1); sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false); MoveUpBeforeComment(sel); sel.Insert(Environment.NewLine + dashedLine, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd); sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false); // put IP at previous location sel.MoveToLineAndOffset(nLine, nLineOffset, false); } else { // check if we already have a comment sel.LineUp(false, 1); if (!IsXmlCommentLine) { // Insert comment sel.EndOfLine(false); sel.NewLine(1); sel.Text = "///"; } // Insert line above MoveUpBeforeComment(sel); sel.EndOfLine(false); sel.NewLine(1); sel.Text = dashedLine; int upperLine = sel.ActivePoint.Line; sel.LineDown(false, 1); // reformat text for (; IsXmlCommentLine;) { int curLine = sel.CurrentLine; // go through all words in this line for (; sel.CurrentLine == curLine; sel.WordRight(false, 1)) { if (sel.ActivePoint.VirtualDisplayColumn > kLineLen) { // we have to break before this word sel.WordLeft(true, 1); // skip all punctuation characters for (; sel.Text.Length == 1 && char.IsPunctuation(sel.Text[0]);) { sel.CharLeft(false, 1); // removes selection sel.WordLeft(true, 1); } sel.CharLeft(false, 1); // removes selection // break the line sel.NewLine(1); // join next line with remainder of current line sel.EndOfLine(false); sel.LineDown(true, 1); sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, true); sel.WordRight(true, 1); sel.Delete(1); // insert a space between the two lines sel.Text = " "; } } } // Insert line below sel.GotoLine(upperLine + 1, false); MoveDownAfterComment(sel); sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false); sel.NewLine(1); sel.LineUp(false, 1); sel.Text = dashedLine; sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false); sel.LineDown(false, 1); } }
/// <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; } }