/// <summary> /// Inserts text at current cursor location or replaces the one that is currently selected. /// Undo will be used to name the action in Visual Studio's UndoRedo editor. /// </summary> public void InsertTextOrReplaceSelection(string undoContextName, string newText, bool detectStringCharsInSelection) { try { // open the undo-context to combine all the modifications of the source code into one: application.UndoContext.Open(undoContextName, true); if (IsSelected) { // paste into selected text: if (detectStringCharsInSelection) { InsertAsSelectionWithStringChars(newText); } else { selection.Insert(newText, (int)vsInsertFlags.vsInsertFlagsContainNewText); } } else { // just insert text: EditPoint.Insert(newText); } } finally { // close the undo-context, so all the changes will be threated as one: application.UndoContext.Close(); } }
/// <summary>实现 IDTCommandTarget 接口的 Exec 方法。此方法在调用该命令时调用。</summary> /// <param term='CmdName'>要执行的命令的名称。</param> /// <param term='ExecuteOption'>描述该命令应如何运行。</param> /// <param term='VariantIn'>从调用方传递到命令处理程序的参数。</param> /// <param term='VariantOut'>从命令处理程序传递到调用方的参数。</param> /// <param term='Handled'>通知调用方此命令是否已被处理。</param> /// <seealso class='Exec' /> public void Exec(string CmdName, vsCommandExecOption ExecuteOption, ref object VariantIn, ref object VariantOut, ref bool Handled) { Handled = false; if (ExecuteOption == vsCommandExecOption.vsCommandExecOptionDoDefault) { if (CmdName == "PasteXmlAsLinq.Connect.PasteXmlAsLinq") { Document doc = applicationObject.ActiveDocument; if (doc != null) { string xml = (string)Clipboard.GetDataObject().GetData(typeof(string)); if (xml != null) { try { string code = Converter.Convert(xml); TextSelection s = (TextSelection)doc.Selection; s.Insert(code, (int)vsInsertFlags.vsInsertFlagsContainNewText); applicationObject.ExecuteCommand("Edit.FormatSelection", ""); } catch (Exception e) { MessageBox.Show("Clipboard does not contain valid XML.\r\n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } Handled = true; return; } } }
/// <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 == "FormatVariableDefine.Connect.FormatVariableDefine" || commandName == "FormatVariableDefine.Connect.FormatVariableDefineRightClick") { TextSelection select = ((TextSelection)_applicationObject.ActiveDocument.Selection); int nTopLine = select.TopLine; int nBottomLine = select.BottomLine; bool bLastLineEmpty = select.BottomPoint.AtStartOfLine; select.GotoLine(nTopLine, true); select.LineDown(true, nBottomLine - nTopLine); select.EndOfLine(true); if (bLastLineEmpty) { select.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, true); } string selectedCode = select.Text; string outCode = CodeSmart.AlignText(selectedCode); //对齐选中文本 select.Insert(outCode, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd); handled = true; return; } } }
internal void CreateNewcshtmlFile(string title, string fileContents) { DTE2 provider = Package.GetGlobalService(typeof(SDTE)) as DTE2; if (provider == null || provider.ActiveDocument == null) { return; } var x = provider.ActiveDocument.Path.ToString() + title + ".cshtml"; using (var stream = new FileStream(x, FileMode.OpenOrCreate)) { } var file = provider.ItemOperations.AddExistingItem(x).Open(); if (file?.Document == null) { return; } file?.Document?.Activate(); if (!String.IsNullOrEmpty(fileContents)) { TextSelection selection = (TextSelection)file?.Document?.Selection; selection.SelectAll(); selection.Text = ""; selection.Insert(fileContents); } }
/// <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) { DTE2 dte = ServiceCache.ExtensibilityModel.DTE as DTE2; if (commandName == "MyAddin1.Connect.MyAddin1") { Document activeDocument = null; IScriptFactory scriptFactory = ServiceCache.ScriptFactory; if (scriptFactory != null) { scriptFactory.CreateNewBlankScript(ScriptType.Sql); activeDocument = dte.ActiveDocument; } if (activeDocument != null) { TextSelection ts = activeDocument.Selection as TextSelection; ts.Insert("This Query Window was created with our TestAddin.", (int)vsInsertFlags.vsInsertFlagsInsertAtStart); } handled = true; } if (commandName == "MyAddin1.Connect.MyAddin1ToolWindowForm") { Windows2 MyWindow = (Windows2)dte.Windows; Assembly asm = System.Reflection.Assembly.GetExecutingAssembly(); object MyControl = null; Window toolWindow = MyWindow.CreateToolWindow2(_addInInstance, asm.Location, "MyAddin1.MyAddinWindow", "MyAddin1.MyAddin1ToolWindowForm", "{5B7F8C1C-65B9-2aca-1Ac3-12AcBbAF21d5}", MyControl); toolWindow.Visible = true; handled = true; /*Assembly a = Assembly.GetExecutingAssembly(); * object controlObject = null; * * Windows2 toolWindows = dte.Windows as Windows2; * Window2 toolWindow; * * * toolWindow = (Window2)toolWindows.CreateToolWindow2(_addInInstance,a.Location, "MyAddin1.MyAddin1ToolWindowForm ", "", Guid.NewGuid().ToString(), ref controlObject); * * toolWindow.WindowState = vsWindowState.vsWindowStateNormal; * toolWindow.IsFloating = false; * toolWindow.Visible = true; * * handled = true;*/ } else { String s = varIn.ToString(); string s2 = varOut.ToString(); } } }
/// <summary> /// Tries to do smart indentation based on the current position of the caret. /// </summary> /// <returns>If smart indentation was performed. Otherwise false.</returns> private bool TrySmartIndent() { ThreadHelper.ThrowIfNotOnUIThread(); // Try to indent intelligently to correct location based on the previous line. TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection; string prevLine = ts.ActivePoint.CreateEditPoint().GetLines(ts.ActivePoint.Line - 1, ts.ActivePoint.Line); bool success = m_generator.GenerateIndentation(ts.ActivePoint.LineCharOffset, prevLine, out int newOffset); if (success) { // If we're at the end of the line, we should just move the caret. This ensures that the editor doesn't // commit any trailing spaces unless user writes something after the indentation. if (ts.ActivePoint.LineCharOffset > ts.ActivePoint.LineLength) { ts.MoveToLineAndOffset(ts.ActivePoint.Line, newOffset); } else { // Otherwise add indentation in the middle of the line. ts.Insert(new string(' ', newOffset - ts.ActivePoint.LineCharOffset)); } } return(success); }
/// <summary> /// Creates a new comment line based on the position of the caret and Doxygen configuration. /// </summary> /// <param name="currentLine">Current line for reference.</param> private void NewCommentLine(string currentLine) { ThreadHelper.ThrowIfNotOnUIThread(); string startSpaces = currentLine.Replace(currentLine.TrimStart(), ""); string endSpaces = currentLine.Replace(currentLine.TrimEnd(), ""); TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection; // Try to also guess proper indentation level based on the current line. int oldLine = ts.ActivePoint.Line; int oldOffset = ts.ActivePoint.LineCharOffset; int extraIndent = 0; while (!currentLine.StartsWith("/*!")) { if (m_regexTagSection.IsMatch(currentLine)) { extraIndent = m_configService.Config.TagIndentation; break; } ts.LineUp(); currentLine = ts.ActivePoint.CreateEditPoint().GetLines(ts.ActivePoint.Line, ts.ActivePoint.Line + 1); currentLine = currentLine.TrimStart(); } // Remove extra spaces from the previous line and add tag start line. ts.MoveToLineAndOffset(oldLine, oldOffset); ts.DeleteLeft(endSpaces.Length); // TODO: This adds trailing space. Get rid of it similarly to SmartIndent(). ts.Insert(m_generator.GenerateTagStartLine(startSpaces) + new string(' ', extraIndent)); }
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 btnGenerateScript_Click(object sender, EventArgs e) { try { Cursor.Current = Cursors.WaitCursor; if (_bismNormalizerPackage.Dte != null) { _bismNormalizerPackage.Dte.StatusBar.Text = "BISM Normalizer - creating script ..."; } string script = _comparison.ScriptDatabase(); //doing this here in case errors before opening file in VS Document file = NewXmlaFile(_comparison.CompatibilityLevel >= 1200, (_comparisonInfo.ConnectionInfoTarget.UseProject ? _comparisonInfo.ConnectionInfoTarget.ProjectName : _comparisonInfo.ConnectionInfoTarget.DatabaseName)); if (file != null) { TextSelection selection = (TextSelection)file.Selection; selection.SelectAll(); selection.Insert(script); selection.GotoLine(1); return; } //If we get here, there was a problem generating the xmla file (maybe file item templates not installed), so offer saving to a file instead SaveFileDialog saveFile = new SaveFileDialog(); saveFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); if (_comparison.CompatibilityLevel >= 1200) { saveFile.Filter = "JSON Files|*.json|Text Files|*.txt|All files|*.*"; } else { saveFile.Filter = "XMLA Files|*.xmla|Text Files|*.txt|All files|*.*"; } saveFile.CheckFileExists = false; if (saveFile.ShowDialog() == DialogResult.OK) { File.WriteAllText(saveFile.FileName, _comparison.ScriptDatabase()); if (_bismNormalizerPackage.Dte != null) { _bismNormalizerPackage.Dte.StatusBar.Text = "BISM Normalizer - finished generating script"; } MessageBox.Show("Created script\n" + saveFile.FileName, _bismNormalizerCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception exc) { MessageBox.Show(exc.Message, _bismNormalizerCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); SetNotComparedState(); } finally { Cursor.Current = Cursors.Default; _bismNormalizerPackage.Dte.StatusBar.Text = ""; } }
public static void CreateNewFile(string fileType, string title, string fileContents) { Document document = DteService.DTE.ItemOperations.NewFile(fileType, title, "{00000000-0000-0000-0000-000000000000}").Document; TextSelection textSelection = document.Selection as TextSelection; textSelection.SelectAll(); textSelection.Text = ""; textSelection.Insert(fileContents, 1); textSelection.StartOfDocument(false); }
/// <summary> /// Creates a new comment line based on the position of the caret and Doxygen configuration. /// </summary> /// <param name="currentLine">Current line for reference.</param> private void NewCommentLine() { ThreadHelper.ThrowIfNotOnUIThread(); int lineNumber = m_textView.Caret.Position.BufferPosition.GetContainingLine().LineNumber; string currentLine = m_textView.TextSnapshot.GetLineFromLineNumber(lineNumber).GetText(); string startSpaces = currentLine.Replace(currentLine.TrimStart(), ""); string endSpaces = currentLine.Replace(currentLine.TrimEnd(), ""); // Try to also guess proper indentation level based on the current line. int extraIndent = 0; int i = lineNumber; string loopLine = currentLine; while (!loopLine.StartsWith("/*!") || !loopLine.StartsWith("/**")) { if (m_regexTagSection.IsMatch(loopLine)) { extraIndent = m_config.TagIndentation; break; } --i; if (i < 0 || i > m_textView.TextSnapshot.LineCount - 1) { break; } loopLine = m_textView.TextSnapshot.GetLineFromLineNumber(i).GetText().TrimStart(); } TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection; ts.DeleteLeft(endSpaces.Length); if (currentLine.EndsWith("*/")) { ts.MoveToLineAndOffset(ts.CurrentLine, currentLine.Length - 1); } else { ts.MoveToLineAndOffset(ts.CurrentLine, currentLine.Length + 1); } // TODO: This adds trailing space. Get rid of it similarly to SmartIndent(). ts.Insert(m_generator.GenerateTagStartLine(startSpaces) + new string(' ', extraIndent)); }
/// <summary> /// Creates the new file. /// </summary> /// <param name="fileType">Type of the file.</param> /// <param name="title">The title.</param> /// <param name="fileContents">The file contents.</param> public static void CreateNewFile( string fileType, string title, string fileContents) { Document file = DTE.ItemOperations.NewFile(fileType, title).Document; TextSelection selection = file.Selection as TextSelection; selection.SelectAll(); selection.Text = ""; selection.Insert(fileContents); selection.StartOfDocument(); }
public static void CreateClass(this Project pro, string directory, string name, string content) { if (pro == null) { return; } var add = false; foreach (ProjectItem projectItem in pro.ProjectItems) { var dname = projectItem.Name; if (dname == directory) { var item = projectItem.GetItem(name + ".cs"); if (item == null) { string templatePath = GetSolution3().GetProjectItemTemplate("Class.zip", "CSharp"); projectItem.ProjectItems.AddFromTemplate(templatePath, name + ".cs"); TextSelection txtSel = (TextSelection)Application.ActiveDocument.Selection; txtSel.SelectAll(); txtSel.Delete(); txtSel.Insert(content); add = true; } else { item.Open(); TextSelection txtSel = (TextSelection)Application.ActiveDocument.Selection; txtSel.SelectAll(); txtSel.Delete(); txtSel.Insert(content); add = true; } } } if (!add) { pro.ProjectItems.AddFolder(directory); var projectItem = pro.GetItem(directory); string templatePath = GetSolution3().GetProjectItemTemplate("Class.zip", "CSharp"); projectItem.ProjectItems.AddFromTemplate(templatePath, name + ".cs"); TextSelection txtSel = (TextSelection)Application.ActiveDocument.Selection; txtSel.SelectAll(); txtSel.Delete(); txtSel.Insert(content); add = true; } }
/// <summary> /// Adds new file to the current Solution/Project and inserts the contents /// </summary> /// <param name="fileType">File type, eg. General\XML File</param> /// <param name="title">File title</param> /// <param name="fileContents">File contents</param> internal static void CreateNewFile(string fileType, string title, string fileContents) { DTE2 dte = Package.GetGlobalService(typeof(SDTE)) as DTE2; Document file = dte.ItemOperations.NewFile(fileType, title).Document; if (!String.IsNullOrEmpty(fileContents)) { TextSelection selection = file.Selection; selection.SelectAll(); selection.Text = ""; selection.Insert(fileContents); } }
public void Execute(TextSelection textSelection, Func <string, string> seletionCallback) { ThreadHelper.ThrowIfNotOnUIThread(); textSelection.GotoLine(1, true); textSelection.SelectAll(); var contents = textSelection.Text; var changedTxt = seletionCallback.Invoke(contents); textSelection.Insert(changedTxt); textSelection.SmartFormat(); textSelection.GotoLine(1, false); }
private void writeOutputToEditorBuffer(TextSelection sel, Document tdToSave) { if (m_td.Type == "Text") { if (m_CfSuccessful) { sel.Insert(cfOutput, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd); if (m_sSaveOnFormat) { tdToSave.Save(m_fullFileName); } } } }
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); }
internal void CreateFile(string fileName, string content) { DTE dte = (DTE)GetService(typeof(DTE)); dte.ItemOperations.NewFile("General\\Text File", fileName); TextSelection textSel = (TextSelection)dte.ActiveDocument.Selection; TextDocument textDoc = (TextDocument)dte.ActiveDocument.Object(); textSel.SelectAll(); textSel.Delete(); textSel.Insert(content); textSel.GotoLine(1); }
/// <summary> /// Appends a new line to an existing comment block with indenting and a triple slash /// already added. /// </summary> /// <returns>True if the addition worked, false if it failed.</returns> private bool HandleNewlineInCommentBlock() { ThreadHelper.ThrowIfNotOnUIThread(); TextSelection ts = Dte.ActiveDocument.Selection as TextSelection; string currentLine = TextView.TextSnapshot.GetLineFromPosition( TextView.Caret.Position.BufferPosition.Position).GetText(); if (currentLine.TrimStart().StartsWith("///")) { string leadingSpaces = currentLine.Replace(currentLine.TrimStart(), ""); ts.Insert(Environment.NewLine + leadingSpaces + "/// "); return(true); } return(false); }
private static void AddToExisting(ProjectItem extObject, string code) { // TODO: Need to handle failure here. var window = extObject.Open(); window.Activate(); TextSelection selection = (TextSelection)extObject.Document.Selection; selection.SelectAll(); var text = selection.Text; selection.EndOfDocument(); selection.NewLine(); selection.Insert(code); }
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); } } } }
private void CreateNewFile(string filename, string content) { DTE dte = (DTE)GetService(typeof(DTE)); dte.ItemOperations.NewFile(@"General\Visual C# Class", filename, EnvDTE.Constants.vsViewKindTextView); TextSelection txtSel = (TextSelection)dte.ActiveDocument.Selection; TextDocument txtDoc = (TextDocument)dte.ActiveDocument.Object(""); txtSel.SelectAll(); txtSel.Delete(); txtSel.Insert(content); // //var dte = (EnvDTE.DTE)ServiceProvider.GlobalProvider.GetService(typeof(EnvDTE.DTE)); // // https://social.msdn.microsoft.com/Forums/vstudio/en-US/a7da9e48-7282-4e22-a07a-36e66426316e/add-in-trying-to-add-class-fails-with-template-invalid-for-that-project?forum=vsx // EnvDTE80.DTE2 dte = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2; // if (dte == null) // { // //Alert("Could not create new file."); // System.Diagnostics.Debug.WriteLine("Could not get EnvDTE.DTE service."); // return; // } // var solution = dte.Solution as EnvDTE80.Solution2; // if (solution == null) // { // //Alert("Could not create new file."); // System.Diagnostics.Debug.WriteLine("Could not get DTE solution."); // return; // } // var x = solution.GetProjectItemTemplate(filename, "CSharp"); // //dte.ActiveDocument.ProjectItem.ContainingProject; // //dte.ItemOperations.AddNewItem(@"Visual C# Project Items\Class", name); // // http://stackoverflow.com/questions/11049758/selected-project-from-solution-explorer // var txtSel = (EnvDTE.TextSelection)dte.ActiveDocument.Selection; // var txtDoc = (EnvDTE.TextDocument)dte.ActiveDocument.Object(); // txtSel.SelectAll(); // txtSel.Delete(); // txtSel.Insert(content); }
protected override void OnExecute(Microsoft.VisualStudio.Shell.OleMenuCommand command) { TextSelection selection = VSTextView.ActiveTextSelection; if (selection != null) { string selectedText = selection.Text; if (string.IsNullOrEmpty(selectedText)) { VSTextView view = new VSTextView(VSTextView.ActiveTextView); if (view != null) { selectedText = view.GetOneLineText(selection.TopPoint.Line - 1); view.InsertText(selectedText, selection.TopPoint.Line, 0); } } else { selection.Insert(selectedText + "\n" + selectedText); } } }
/// <summary> /// takes a project item file contents and re-saves through IDE editor window, hopefully this triggers /// other extensions like bundlers, minifiers, linters etc to update themselves /// </summary> /// <param name="outputFile"></param> public static void SaveOutputFileThroughEditorWindow(string outputFile) { string jsSource = System.IO.File.ReadAllText(outputFile); var dte = TsWspPackage.DTE; var item = dte.Solution.FindProjectItem(outputFile); if (item != null) { // open it var w = item.Open(EnvDTE.Constants.vsViewKindCode); if (w != null) { TextSelection ts = w.Document.Selection as TextSelection; if (ts != null) { // replace all text with new source ts.SelectAll(); ts.Insert(jsSource); item.Save(); // move to top ts.StartOfDocument(); } else { Logger.Log("Could not update text in " + outputFile); } } else { Logger.Log("Could not open code window for " + outputFile); } } else { Logger.Log("Could not locate project item = " + outputFile); } }
private static void MoveUsingsInsideNameSpace(ProjectItem projectItem, TextSelection txtSel, CodeNamespace nameSpace) { var usingsOutsideNameSpace = SearchService.FindUsings(projectItem.FileCodeModel.CodeElements); if (usingsOutsideNameSpace.Any()) { List <string> linesToMove = new List <string>(); for (int i = 0; i < usingsOutsideNameSpace.Count(); i++) { linesToMove.Add(usingsOutsideNameSpace[i].InnerText()); usingsOutsideNameSpace[i].Delete(); } var editPoint = nameSpace.GetStartPoint().CreateEditPoint(); editPoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsNone, ref editPoint); txtSel.MoveToPoint(editPoint); txtSel.NewLine(); foreach (var line in linesToMove) { txtSel.Insert(line); txtSel.NewLine(); } } }
private void ApplyInline(TextSelection selection) { var closeUndoContext = false; if (!selection.DTE.UndoContext.IsOpen) { selection.BeginUpdate("Surround With " + Name); closeUndoContext = true; } var sb = new StringBuilder(); sb.Append(_preText[0]); sb.Append(selection.Text); sb.Append(_postText[0]); var line = selection.TopLine; var col = selection.TopPoint.DisplayColumn; selection.Delete(); selection.Insert(sb.ToString()); if (_caretLine >= 0) { selection.MoveToDisplayColumn(line, col + _caretCol - 1); } else { selection.MoveToDisplayColumn(line, col, true); } if (closeUndoContext) { selection.EndUpdate(); } }
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); }
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); } if (m_dte != null) { string currentLine = m_textView.TextSnapshot.GetLineFromPosition( m_textView.Caret.Position.BufferPosition.Position).GetText(); // check for the Javadoc slash and two asterisk pattern while compensating for visual studio's block comment closing generation if (typedChar == '*' && currentLine.Trim() == "/**/") { // Calculate how many spaces string spaces = currentLine.Replace(currentLine.TrimStart(), ""); TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection; //Remember where the cursor was when command was triggered int oldLine = ts.ActivePoint.Line; int oldOffset = ts.ActivePoint.LineCharOffset; ts.LineDown(); ts.EndOfLine(); ts.SelectLine(); //Detect and skip over Unreal Engine Function Macros string trimmedFuncLine = ts.Text.Trim(); if (trimmedFuncLine != "" && trimmedFuncLine.StartsWith("UFUNCTION(")) { ts.EndOfLine(); } else { ts.MoveToLineAndOffset(oldLine, oldOffset); 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("*"); bool isNoArgsNoReturn = true; foreach (CodeElement child in codeElement.Children) { CodeParameter parameter = child as CodeParameter; if (parameter != null) { sb.AppendFormat("\r\n" + spaces + " * @param {0} ", parameter.Name); isNoArgsNoReturn = false; } } if (function.Type.AsString != "void") { isNoArgsNoReturn = false; if (function.Type.AsString == "bool") { sb.AppendFormat("\r\n" + spaces + " * @return true \r\n" + spaces + " * @return false "); } else { sb.AppendFormat("\r\n" + spaces + " * @return "); } } //If function has a return type or parameters then we generate them and return, otherwise we skip to generate a single line comment if (!isNoArgsNoReturn) { sb.Insert(1, "\r\n" + spaces + " * "); sb.AppendFormat("\r\n" + spaces + " "); ts.MoveToLineAndOffset(oldLine, oldOffset); ts.Insert(sb.ToString()); ts.MoveToLineAndOffset(oldLine, oldOffset); ts.LineDown(); ts.EndOfLine(); return(VSConstants.S_OK); } } //For variables and void functions with no parameters we can do a single line comment ts.MoveToLineAndOffset(oldLine, oldOffset); ts.Insert("* "); ts.MoveToLineAndOffset(oldLine, oldOffset + 2); return(VSConstants.S_OK); } else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN) { //Get text on current line before and after cursor TextSelection ts = m_dte.ActiveDocument.Selection as TextSelection; int oldLine = ts.ActivePoint.Line; int oldOffset = ts.ActivePoint.LineCharOffset; ts.EndOfLine(true); string afterCursor = ts.Text; ts.MoveToLineAndOffset(oldLine, oldOffset); ts.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, true); string beforeCursor = ts.Text; string beforeCursorTrimmed = beforeCursor.TrimStart(); ts.MoveToLineAndOffset(oldLine, oldOffset); // Calculate how many spaces string spaces = beforeCursorTrimmed == "" ? beforeCursor : beforeCursor.Replace(beforeCursorTrimmed, ""); bool hasAsteriskBeforeCursor = beforeCursorTrimmed == "" ? false : beforeCursorTrimmed.StartsWith("* "); bool hasBlockTerminatorAfterCursor = afterCursor == "" ? false : afterCursor.EndsWith("*/"); bool hasBlockTerminatorDirectlyAfterCursor = hasBlockTerminatorAfterCursor && afterCursor.Trim() == "*/"; //Add a space to maintain correct asterisk alignment if needed if (beforeCursorTrimmed != "" && beforeCursorTrimmed.StartsWith("/*")) { hasAsteriskBeforeCursor = true; spaces += " "; } if (hasAsteriskBeforeCursor) { ts.Insert("\r\n" + spaces); if (!hasBlockTerminatorAfterCursor) { ts.Insert("* "); } else if (hasBlockTerminatorDirectlyAfterCursor) { ts.Delete(afterCursor.Length); ts.Insert("*/"); ts.MoveToLineAndOffset(ts.ActivePoint.Line, ts.ActivePoint.LineCharOffset - 2); } return(VSConstants.S_OK); } else if (hasBlockTerminatorAfterCursor) { ts.Insert("* \r\n" + spaces); if (hasBlockTerminatorDirectlyAfterCursor) { ts.Delete(afterCursor.Length); ts.Insert("*/"); ts.MoveToLineAndOffset(ts.ActivePoint.Line, ts.ActivePoint.LineCharOffset - 2); } return(VSConstants.S_OK); } } } // pass along the command so the char is added to the buffer return(m_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut)); } catch { } return(VSConstants.E_FAIL); }
private void button_ok_Click(object sender, EventArgs e) { try { assertiveToolDS dafnyCreate = new assertiveToolDS(); dafnyCreate.Name = p.currentMethod.FullName; if (this.methodName.Text == string.Empty) { MessageBox.Show("Please enter Method Name.", "Empty input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } dafnyCreate.NewMethod.Name = this.methodName.Text; //Add var names and types bool isFound = false; for (int i = 1; i <= this.index; i++) { string t = String.Empty; string n = String.Empty; foreach (Control x in this.Controls) { if (x is TextBox && x.Name.StartsWith("NameBox" + i)) { n = x.Text; } if (x is TextBox && x.Name.StartsWith("TypeBox" + i)) { t = x.Text; } if (n != String.Empty && t != String.Empty) { break; } } if (n == String.Empty) { continue; } else { isFound = true; Variable newVar = new Variable(n, t); dafnyCreate.AddLoclVar(newVar); } } if (!isFound) { MessageBox.Show("Please enter at least one variable and type.", "Empty input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (this.pre_cond.Enabled) { if (pre_cond.Text == string.Empty) { MessageBox.Show("Please enter preCondition.", "Empty input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (preCondName.Text == string.Empty) { MessageBox.Show("Please enter Lema name.", "Empty input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } dafnyCreate.weakenPreCond(pre_cond.Text); dafnyCreate.WeakLemma.Name = this.preCondName.Text; } if (this.post_cond.Enabled) { if (post_cond.Text == string.Empty) { MessageBox.Show("Please enter preCondition.", "Empty input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (postLemaName.Text == string.Empty) { MessageBox.Show("Please enter Lema name.", "Empty input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } dafnyCreate.strengthenPostCond(post_cond.Text); dafnyCreate.StrengthLemma.Name = this.postLemaName.Text; } // Add parser try { // DafnyCodeParser p = new DafnyCodeParser(); // p.parse_file(dte.ActiveDocument.FullName, dafnyCreate.Name); //vars: List <String> varNames = p.get_var_names(); List <String> varTypes = p.get_var_types(); for (int i = 0; i < varNames.Count; i++) { Variable arg1 = new Variable(varNames[i], varTypes[i]); dafnyCreate.AddArgument(arg1); } //ret: List <String> retNames = p.get_ret_names(); List <String> retTypes = p.get_ret_types(); for (int i = 0; i < retNames.Count; i++) { Variable arg1 = new Variable(retNames[i], retTypes[i]); dafnyCreate.AddRetValue(arg1); } //precond List <String> precond = p.get_req(); for (int i = 0; i < precond.Count; i++) { dafnyCreate.AddPreCond(precond[i]); } //post List <String> postcond = p.get_ens(); for (int i = 0; i < postcond.Count; i++) { dafnyCreate.AddPostCond(postcond[i]); } } catch { MessageBox.Show("Error in parsing the file.", "Parser Exeption", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.Close(); return; } // insert text string pre_and_post = String.Empty; if (pre_cond.Enabled) { pre_and_post += "\n\n" + dafnyCreate.generateWeakLemma(); } if (post_cond.Enabled) { pre_and_post += "\n\n" + dafnyCreate.generateStrengthLemma(); } toInsert.Insert("\n{\n" + dafnyCreate.generateBody() + "}\n\n" + dafnyCreate.generateMethod() + pre_and_post + "\n"); this.Close(); } catch { MessageBox.Show("Unexpected Exeption occurred during the execution.", "Unexpected Exeption", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.Close(); return; } }
private static void MoveUsingsInsideNameSpace(ProjectItem projectItem, TextSelection txtSel, CodeNamespace nameSpace) { var usingsOutsideNameSpace = SearchService.FindUsings(projectItem.FileCodeModel.CodeElements); if (usingsOutsideNameSpace.Any()) { List<string> linesToMove = new List<string>(); for (int i = 0; i < usingsOutsideNameSpace.Count(); i++) { linesToMove.Add(usingsOutsideNameSpace[i].InnerText()); usingsOutsideNameSpace[i].Delete(); } var editPoint = nameSpace.GetStartPoint().CreateEditPoint(); editPoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsNone, ref editPoint); txtSel.MoveToPoint(editPoint); txtSel.NewLine(); foreach (var line in linesToMove) { txtSel.Insert(line); txtSel.NewLine(); } } }
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; } }
/// <summary></summary> bool ChangeSelectedTextCase(TextSelection selection, TextTransformationOption option) { string before = selection.Text; string after = CodeManager.TransformText(before, option); bool changed = (before != after); if (changed) { selection.Delete(); selection.Insert(after); } return changed; }
private void UpdateComment(CodeFunction function, string oldDoc, int docLine, TextSelection ts, int oldLine, int offset, string lineEnding) { ThreadHelper.ThrowIfNotOnUIThread(); // Get the old parameters and return valus var _oldParameters = GetDocLinesOfType(lineEnding, oldDoc, DocLineType._params); var oldParameters = _oldParameters.Keys.Except(new[] { "__default__" }).ToList(); var oldReturns = GetDocLinesOfType(lineEnding, oldDoc, DocLineType._return); string oldReturn = null; if (oldReturns.ContainsKey("return")) { oldReturn = oldReturns["return"]; } // Get all new function parameters and return value var updatedParams = GetFunctionParams(function); var updatedType = function.Type.AsString; // Create new comment step by step... string newDoc = oldDoc; // Remove all old parameters foreach (var param in oldParameters) { // Delete the line(s) var pattern = Regex.Escape(_oldParameters[param]) + "( .*" + lineEnding + "|" + lineEnding + ")"; newDoc = Regex.Replace(newDoc, pattern, ""); } // Remove old return statement if (oldReturn != null) { // Delete the line(s) var pattern = Regex.Escape(oldReturns["return"]) + "( .*" + lineEnding + "|" + lineEnding + ")"; newDoc = Regex.Replace(newDoc, pattern, ""); } // Then add all parameters of the new function var _oldParams = oldParameters.ToList(); var _uncertainNewParams = new List <string>(); var newParams = new Dictionary <string, string>(); foreach (var param in updatedParams) { // If there was the exact same parameter, add it again if (_oldParams.Contains(param)) { _oldParams.Remove(param); newParams.Add(param, _oldParameters[param]); } else { newParams.Add(param, null); _uncertainNewParams.Add(param); } } // Check for special cases if (_uncertainNewParams.Count > 0 && _oldParams.Count == 0) { _uncertainNewParams.Clear(); } // If there are no special cases, but still open issues, ask the user else if (_uncertainNewParams.Count > 0) { var dialog = new UpdateDoxygenCommentDialog(_oldParams, _uncertainNewParams); if (dialog.ShowDialog() == DialogResult.OK) { // Add the selected parameters to the new parameter list var selectedParams = dialog.finalParams; foreach (var param in _uncertainNewParams) { var oldParam = selectedParams[param]; if (oldParam != null) { newParams[param] = _oldParameters[oldParam].Replace(oldParam, param); } } } } // Add the new params to the documentation foreach (var param in newParams) { newDoc = AddParamToDoc(lineEnding, newDoc, param.Key, param.Value, _oldParameters); } // Then add the return statement if (!updatedType.Equals("void")) { newDoc = AddReturnToDoc(lineEnding, newDoc, oldReturn, oldReturns); } var oldDocLines = oldDoc.Split('\n'); var lineDiff = newDoc.Split('\n').Length - oldDocLines.Length; ts.MoveToLineAndOffset(docLine + 1, 1); ts.MoveToLineAndOffset(docLine + oldDocLines.Length - 1, 1, true); ts.EndOfLine(true); ts.Insert(newDoc.TrimSuffix(lineEnding)); ts.MoveToLineAndOffset(oldLine + lineDiff, offset); }