public static void GetHelp (CommandExecutionContext* context) { if (context->parameters == null || context->parameters->Length == 0) { ADC.MemoryUtil.Call ((void*) Stubs.GetFunctionPointer (lblExecute), (void*) context); } else { CommandExecutionAttemptResult result; result = Prompter.CommandTable->HandleLine (context->parameters, false, true); if (result == CommandExecutionAttemptResult.NotFound) { int indexOfSpace = context->parameters->IndexOf (" "); CString8* tempStr; if (indexOfSpace >= 0) tempStr = context->parameters->Substring (0, indexOfSpace); else tempStr = CString8.Copy (context->parameters); TextMode.Write ("No command '"); TextMode.Write (tempStr); TextMode.WriteLine ("' is available to retrieve help for."); TextMode.WriteLine (CommandTableHeader.inform_USE_HELP_COMMANDS); CString8.DISPOSE (tempStr); return; } if (result == CommandExecutionAttemptResult.BlankEntry) { ADC.MemoryUtil.Call ((void*) Stubs.GetFunctionPointer (Help.lblGetHelp), (void*) context); } } }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" mount <target> <source>"); TextMode.WriteLine (); TextMode.WriteLine ("Mounts a file system at <target> from block device at <source>."); }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" stage"); TextMode.WriteLine (""); TextMode.WriteLine ("Prints the current kernel stage."); }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" panic"); TextMode.WriteLine (""); TextMode.WriteLine ("Causes a RSOD (Red Screen Of Death)."); }
public static void Execute (CommandExecutionContext* context) { if (context->parameters->Compare ("--set", 0, 5) == 0) { CString8 *substr; int result; if (context->parameters->Length <= 6) { GetHelp (context); return; } substr = context->parameters->Substring (6); result = Convert.ToInt32 (substr); MemoryManager.Free (substr); TextMode.WriteLine ("Setting timezone to `", result, "'"); Clock.Timezone = (System.SByte)result; return; } TextMode.Write ("Current timezone: "); TextMode.Write ((int)Clock.Timezone); TextMode.WriteLine (); }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" halt"); TextMode.WriteLine (""); TextMode.WriteLine ("Halts the system."); }
public static void Execute (CommandExecutionContext* context) { try { TextMode.WriteLine ("Mounting"); string parameters = Foundation.Convert.ToString (context->parameters); // for testing... if (string.IsNullOrEmpty (parameters)) parameters = "/IDE_496/Disk0/Partition1 /Disk1"; int space = parameters.IndexOf (' '); if (space <= 0) { TextMode.WriteLine ("Incorrect syntax"); return; } string source = parameters.Substring (0, space); string target = parameters.Substring (space + 1, parameters.Length - 1 - space); TextMode.Write ("Source:"); TextMode.WriteLine (source); TextMode.Write ("Target:"); TextMode.WriteLine (target); Vfs.VirtualFileSystem.Mount (source, target); } catch (Exception e) { TextMode.Write ("Exception: "); TextMode.Write (e.ToString ()); TextMode.WriteLine (); } }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" more <filename>"); TextMode.WriteLine (); TextMode.WriteLine ("Displays the contents of a file"); }
public static void Execute (CommandExecutionContext* context) { try { TextMode.WriteLine ("Reading.."); string filename = Foundation.Convert.ToString (context->parameters); // for testing... if (string.IsNullOrEmpty (filename)) filename = "/embedded/TEST0.TXT"; TextMode.Write ("File:"); TextMode.WriteLine (filename); TextMode.WriteLine ("More.Execute.1"); System.IO.Stream filestream = (System.IO.Stream) Vfs.VirtualFileSystem.Open (filename, System.IO.FileAccess.Read, System.IO.FileShare.Read); TextMode.WriteLine ("More.Execute.2"); } catch (Exception e) { TextMode.Write ("Exception: "); TextMode.Write (e.ToString ()); TextMode.WriteLine (); } }
public static void Execute (CommandExecutionContext* context) { byte* rawbuf = stackalloc byte [EntryModule.MaxKeyMapNameLength]; if (context->parameters->Compare ("--list") == 0) { ListKeyMaps (); } else if (context->parameters->Compare (0, "--set ", 0, 6) == 0 && context->parameters->Length > 6) { PString8* buf = PString8.Wrap (rawbuf, EntryModule.MaxKeyMapNameLength); buf->Clear (); TextMode.Write (context->parameters->Length); TextMode.WriteLine (); buf->Concat (context->parameters, 6, context->parameters->Length - 6); if (KeyMap.GetBuiltinKeyMap (buf) == null) { TextMode.SaveAttributes (); TextMode.Foreground = TextColor.Red; TextMode.Write ("Unknown keymap `"); TextMode.Write (buf); TextMode.Write ("'"); TextMode.RestoreAttributes (); } else { TextMode.Write ("Setting key map to `"); TextMode.Write (buf); TextMode.Write ("'"); KeyMap.SetKeyMap (buf); } } else if (context->parameters->Length == 0) { TextMode.Write ("Current key map: "); TextMode.WriteLine (KeyMap.GetCurrentKeyMapName ()); } else { TextMode.WriteLine ("Usage: keymap [--list|--set NAME]"); } }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" memdump"); TextMode.WriteLine (""); TextMode.WriteLine ("Displays memory usage."); }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" version"); TextMode.WriteLine (""); TextMode.WriteLine ("Prints version and licensing information about SharpOS."); }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" memview <hex-address>"); TextMode.WriteLine (""); TextMode.WriteLine ("Displays 256 bytes of memory at the requested address."); }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" cls"); TextMode.WriteLine (""); TextMode.WriteLine ("Clears the screen."); }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" lspci"); TextMode.WriteLine (""); TextMode.WriteLine ("Gets information about PCI."); }
public void Execute(CommandLine commandLine, CommandExecutionContext context) { Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("=================================================="); Console.WriteLine(" Welcome to {0} {1}", ApplicationInfo.Title, ApplicationInfo.Version.ToString(2)); Console.WriteLine(" " + ApplicationInfo.Description); Console.WriteLine(" " + ApplicationInfo.CopyrightHolder); Console.WriteLine("=================================================="); Console.ResetColor(); Console.WriteLine(); Console.WriteLine("Available commands are:"); foreach (var cmd in CommandFactory.All) { Console.Write("-" + cmd.Name); Console.Write("\t"); if (!String.IsNullOrEmpty(cmd.ShortName)) { Console.Write("[" + cmd.ShortName + "] "); } Console.Write(cmd.Description); if (!String.IsNullOrEmpty(cmd.Usage)) { Console.Write(" Usage: " + cmd.Usage); } Console.WriteLine(); } }
public void Execute(CommandLine commandLine, CommandExecutionContext context) { if (commandLine.Parameters.Count != 2) { ConsoleUtil.ErrorLine("Invalid request. Please check syntax: " + Usage); return; } var host = commandLine.Parameters[1]; var ip = commandLine.Parameters[0]; if (context.Hosts.Contains(host)) { if (commandLine.Options.Count > 0 && commandLine.Options[0].Name == "override") { context.Hosts.Set(ip, host); context.Hosts.Save(); Console.WriteLine("1 entry updated: " + commandLine.Parameters[0] + " " + commandLine.Parameters[1]); } else { ConsoleUtil.ErrorLine(host + " already exists. Use -override to override the existing entry."); } } else { context.Hosts.Set(commandLine.Parameters[0], commandLine.Parameters[1]); context.Hosts.Save(); Console.WriteLine("1 entry added: " + commandLine.Parameters[0] + " " + commandLine.Parameters[1]); } }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" egg"); TextMode.WriteLine (""); TextMode.WriteLine ("And we a proud of it!"); }
internal static async Task ExportPartstudio(CommandExecutionContext context, Dictionary<string, List<string>> options, List<string> values) { string documentId = options[Constants.DOCUMENT_ID][0]; string wvmSelector = (options.ContainsKey(Constants.WORKSPACE_ID)) ? "w" : "v"; string selectorId = (options.ContainsKey(Constants.WORKSPACE_ID)) ? options[Constants.WORKSPACE_ID][0] : options[Constants.VERSION_ID][0]; string elementId = options[Constants.ELEMENT_ID][0]; string format = options[Constants.FORMAT][0]; switch (format.ToUpperInvariant()) { case "STL": using (Stream contentStream = await context.Client.ExportPartstudioToStl(documentId, wvmSelector, selectorId, elementId, Utils.createStlExportParams(options), values != null ? values.ToArray() : null)) { await Utils.ProcessContentStream(contentStream, options); } break; case "PARASOLID": string formatVersion = options.GetOptionValue(Constants.FORMAT_VERSION); using (Stream contentStream = await context.Client.ExportPartstudioToParasolid(documentId, wvmSelector, selectorId, elementId, formatVersion, values != null?values.ToArray():null)) { await Utils.ProcessContentStream(contentStream, options); } break; default: Console.WriteLine("Invalid format"); break; } }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" keymap : shows the active keymap."); TextMode.WriteLine (" keymap --list : shows all the installed keymaps."); TextMode.WriteLine (" keymap <keymap> : sets the keymap to <keymap>."); TextMode.WriteLine (CommandTableHeader.inform_USE_HELP_COMMANDS); }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" help <command>"); TextMode.WriteLine (""); TextMode.WriteLine ("Prints help information about the given command."); TextMode.WriteLine (CommandTableHeader.inform_USE_HELP_COMMANDS); }
public static void GetHelp (CommandExecutionContext* context) { TextMode.WriteLine ("Syntax: "); TextMode.WriteLine (" show w : shows the warranty."); TextMode.WriteLine (" show c : shows the copyright."); TextMode.WriteLine (" show d : shows the developers."); TextMode.WriteLine (CommandTableHeader.inform_USE_HELP_COMMANDS); }
// method that executes the command and blocks on the reuslt... public static void ExecuteAndBlock(this ICommand command) { // create a context and run... CommandExecutionContext context = new CommandExecutionContext(); command.Execute(context); // wait... context.WaitUntilComplete(); }
internal static async Task ConsumePurchase(CommandExecutionContext context, Dictionary<string, List<string>> options, List<string> values) { if (values != null && values.Count > 0) { await context.Client.ConsumePurchase(values[0]); } else { Console.WriteLine("Error: 'sku' is required"); } }
public static void Execute (CommandExecutionContext* context) { if (context->parameters->Compare ("w") == 0) ShowWarranty (); else if (context->parameters->Compare ("c") == 0) ShowCopyright (); else if (context->parameters->Compare ("d") == 0) ShowDevelopers (); else GetHelp (context); }
public void ShouldCorrectlyExecuteTheCommands() { //arrange var obj = new ValueObject() { Number = 1 }; var context = new CommandExecutionContext(handler); //act context.Execute(new AddOneCommand(obj)); //assert Assert.AreEqual(2, obj.Number); }
internal static async Task GetPlans(CommandExecutionContext context, Dictionary<string, List<string>> options, List<string> values) { if (values != null && values.Count > 0) { OnshapeBillingPlan plan = await context.Client.GetBillingPlan(values[0]); Console.WriteLine(JsonConvert.SerializeObject(plan)); } else { List<OnshapeBillingPlan> plans = await context.Client.GetClientBillingPlans(); plans.Print(); } }
internal static async Task CreateAssemblyTranslation(CommandExecutionContext context, Dictionary<string, List<string>> options, List<string> values) { OnshapeTranslationParameters translationParameters = new OnshapeTranslationParameters() { formatName = options.GetOptionValue(Constants.FORMAT), versionString = options.GetOptionValue(Constants.FORMAT_VERSION) }; string storeInDocumentStr = options.GetOptionValue(Constants.STORE_IN_DOCUMENT); if (!String.IsNullOrEmpty(storeInDocumentStr)) { translationParameters.storeInDocument = Boolean.Parse(storeInDocumentStr); } OnshapeTranslationStatus status = await context.Client.CreateAssemblyTranslation(options[Constants.DOCUMENT_ID][0], options[Constants.WORKSPACE_ID][0], options[Constants.ELEMENT_ID][0], translationParameters); Console.WriteLine(JsonConvert.SerializeObject(status, Formatting.Indented)); }
public void Execute(CommandLine commandLine, CommandExecutionContext context) { var entries = context.Hosts.AllEntries(); if (entries.Count == 0) { Console.WriteLine("No entry was found."); } else { foreach (var entry in entries) { Console.WriteLine(entry.IP + "\t" + entry.Host); } } }
internal static async Task UploadBlobelement(CommandExecutionContext context, Dictionary<string, List<string>> options, List<string> values) { string flattenAssembliesStr = options.GetOptionValue(Constants.FLATTEN_ASSEMBLIES); string yAxisIsUpStr = options.GetOptionValue(Constants.Y_AXIS_IS_UP); Dictionary<String, String> formFields = new Dictionary<String, String> { {"encodedFileName", HttpUtility.UrlEncode(System.IO.Path.GetFileName(options[Constants.FILE][0]))} }; if (flattenAssembliesStr != null) { formFields["flattenAssemblies"] = flattenAssembliesStr; } if (yAxisIsUpStr != null) { formFields["yAxisIsUp"] = yAxisIsUpStr; } var response = await context.Client.CreateBlobelement(options[Constants.DOCUMENT_ID][0], options[Constants.WORKSPACE_ID][0], formFields, options[Constants.FILE][0]); Console.WriteLine(JsonConvert.SerializeObject(response, Formatting.Indented)); }
public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { // Attempt to convert the block-namespace to a file-scoped namespace if we're at the right location. var(convertedText, semicolonSpan) = ConvertNamespace(args, executionContext); // No matter if we succeeded or not, insert the semicolon. This way, when we convert, the user can still // hit ctrl-z to get back to the code with just the semicolon inserted. nextCommandHandler(); // If we weren't on a block namespace (or couldn't convert it for some reason), then bail out after // inserting the semicolon. if (convertedText == null) { return; } // Otherwise, make a transaction for the edit and replace the buffer with the final text. using var transaction = CaretPreservingEditTransaction.TryCreate( this.DisplayName, args.TextView, _textUndoHistoryRegistry, _editorOperationsFactoryService); var edit = args.SubjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null); edit.Replace(new Span(0, args.SubjectBuffer.CurrentSnapshot.Length), convertedText.ToString()); edit.Apply(); // Place the caret right after the semicolon of the file-scoped namespace. args.TextView.Caret.MoveTo(new SnapshotPoint(args.SubjectBuffer.CurrentSnapshot, semicolonSpan.End)); transaction?.Complete(); }
public bool ExecuteCommand(ReturnKeyCommandArgs args, CommandExecutionContext context) { var textView = args.TextView; var subjectBuffer = args.SubjectBuffer; var spans = textView.Selection.GetSnapshotSpansOnBuffer(subjectBuffer); // Don't do anything special if there is multi-selection. It's not clear what sort of semantics that should have. if (spans.Count != 1) { return(false); } var snapshot = subjectBuffer.CurrentSnapshot; var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return(false); } if (!_globalOptions.GetOption(SplitCommentOptions.Enabled, document.Project.Language)) { return(false); } var splitCommentService = document.GetLanguageService <ISplitCommentService>(); if (splitCommentService == null) { return(false); } // If there is a selection, ensure that it's all on one-line. It's not clear what sort of semantics we // would want if this spanned multiple lines. var selectionSpan = spans[0].Span; var position = selectionSpan.Start; var line = subjectBuffer.CurrentSnapshot.GetLineFromPosition(position); var endLine = subjectBuffer.CurrentSnapshot.GetLineFromPosition(selectionSpan.End); if (line.LineNumber != endLine.LineNumber) { return(false); } // Quick check. If the line doesn't contain a comment in it before the caret, // then no point in doing any more expensive synchronous work. if (!LineProbablyContainsComment(splitCommentService, new SnapshotPoint(snapshot, position))) { return(false); } using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Split_comment)) { var cancellationToken = context.OperationContext.UserCancellationToken; var result = SplitCommentAsync(textView, document, new SnapshotSpan(snapshot, selectionSpan), cancellationToken).WaitAndGetResult(cancellationToken); if (result == null) { return(false); } using var transaction = CaretPreservingEditTransaction.TryCreate( EditorFeaturesResources.Split_comment, textView, _undoHistoryRegistry, _editorOperationsFactoryService); subjectBuffer.Replace(result.Value.replacementSpan, result.Value.replacementText); transaction?.Complete(); return(true); } }
public bool ExecuteCommand(RemoveParametersCommandArgs args, CommandExecutionContext context) { CommitIfActive(args); return(false); }
private void BeforeExecuteCommand(TypeCharCommandArgs args, CommandExecutionContext executionContext) { if (args.TypedChar != ';') { return; } var caretOpt = args.TextView.GetCaretPoint(args.SubjectBuffer); if (!caretOpt.HasValue) { return; } var caret = caretOpt.Value; var document = caret.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return; } // on the UI thread var root = document.GetSyntaxRootSynchronously(executionContext.OperationContext.UserCancellationToken); var caretPosition = caret.Position; var token = root.FindToken(caretPosition); var currentNode = token.Parent; // If cursor is right before an opening delimiter, start with node outside of delimiters since analysis // starting with a node containing delimiters assumes the caret is placed inside those delimiters. // This covers cases like `obj.ToString$()`, where `token` references `(` but the caret isn't actually // inside the argument list. if (token.IsKind(SyntaxKind.OpenBraceToken, SyntaxKind.OpenBracketToken, SyntaxKind.OpenParenToken) && token.Span.Start >= caretPosition) { currentNode = currentNode.Parent; } if (currentNode == null) { return; } var syntaxFacts = document.GetLanguageService <ISyntaxFactsService>(); if (!LooksLikeNodeInArgumentList(currentNode, caret, syntaxFacts)) { return; } // verify all delimiters exist until you reach statement syntax that requires a semicolon while (!IsStatementOrFieldDeclaration(currentNode, syntaxFacts)) { if (RequiredDelimiterIsMissing(currentNode)) { // A required delimiter is missing; do not treat semicolon as statement completion // Example: missing final `)` in `obj.Method($` return; } if (currentNode.Parent == null) { return; } currentNode = currentNode.Parent; } // if the statement syntax itself requires a closing delimiter, verify it is there if (StatementClosingDelimiterIsMissing(currentNode)) { // Example: missing final `)` in `do { } while (x$$` return; } var semicolonPosition = GetSemicolonLocation(root, currentNode, caretPosition); // Place cursor after the statement args.TextView.TryMoveCaretToAndEnsureVisible(args.SubjectBuffer.CurrentSnapshot.GetPoint(semicolonPosition)); }
public bool ExecuteCommand(CopyCommandArgs args, CommandExecutionContext executionContext) { ITextSelection selection = args.TextView.Selection; if (selection.SelectedSpans.Count != 1 || // Only handle single selections selection.Start.Position == selection.End.Position || // Don't handle zero-width selections !Options.Instance.CopyWithoutIndentation) { return(false); } ITextSnapshot snapshot = args.TextView.TextBuffer.CurrentSnapshot; // Only handle selections that starts with indented if (args.TextView.TryGetTextViewLineContainingBufferPosition(selection.Start.Position, out ITextViewLine viewLine)) { if (viewLine.Start.Position == selection.Start.Position) { return(false); } } IEnumerable <ITextViewLine> lines = from line in args.TextView.TextViewLines where line.IntersectsBufferSpan(selection.SelectedSpans[0]) select line; // Only handle when multiple lines are selected if (lines.Count() == 1) { return(false); } var indentation = selection.Start.Position.Position - viewLine.Start.Position; var spans = new List <SnapshotSpan>(); var sb = new StringBuilder(); var text = args.TextView.TextBuffer.CurrentSnapshot.GetText(viewLine.Start.Position, indentation); // Only handle cases when selection starts is on an empty indentation if (!string.IsNullOrWhiteSpace(text)) { return(false); } foreach (ITextViewLine line in lines) { if (line.Extent.IsEmpty) { spans.Add(line.Extent); sb.AppendLine(); } else { var end = line.Length - indentation; if (selection.End.Position.Position < line.End.Position) { end -= (line.End.Position - selection.End.Position.Position); } var span = new SnapshotSpan(snapshot, line.Start + indentation, end); if (!span.IsEmpty) { spans.Add(span); sb.AppendLine(span.GetText()); } } } var rtf = _rtfService.GenerateRtf(new NormalizedSnapshotSpanCollection(spans), args.TextView); var data = new DataObject(); data.SetText(rtf.TrimEnd(), TextDataFormat.Rtf); data.SetText(sb.ToString().TrimEnd(), TextDataFormat.UnicodeText); Clipboard.SetDataObject(data, false); return(true); }
void IChainedCommandHandler <TypeCharCommandArgs> .ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) { AssertIsForeground(); var allProviders = GetProviders(); if (allProviders == null) { nextHandler(); return; } // Note: while we're doing this, we don't want to hear about buffer changes (since we // know they're going to happen). So we disconnect and reconnect to the event // afterwards. That way we can hear about changes to the buffer that don't happen // through us. this.TextView.TextBuffer.PostChanged -= OnTextViewBufferPostChanged; try { nextHandler(); } finally { this.TextView.TextBuffer.PostChanged += OnTextViewBufferPostChanged; } // We only want to process typechar if it is a normal typechar and no one else is // involved. i.e. if there was a typechar, but someone processed it and moved the caret // somewhere else then we don't want signature help. Also, if a character was typed but // something intercepted and placed different text into the editor, then we don't want // to proceed. // // Note: we do not want to pass along a text version here. It is expected that multiple // version changes may happen when we call 'nextHandler' and we will still want to // proceed. For example, if the user types "WriteL(", then that will involve two text // changes as completion commits that out to "WriteLine(". But we still want to provide // sig help in this case. if (this.TextView.TypeCharWasHandledStrangely(this.SubjectBuffer, args.TypedChar)) { // If we were computing anything, we stop. We only want to process a typechar // if it was a normal character. DismissSessionIfActive(); return; } // Separate the sig help providers into two buckets; one bucket for those that were triggered // by the typed character, and those that weren't. To keep our queries to a minimum, we first // check with the textually triggered providers. If none of those produced any sig help items // then we query the other providers to see if they can produce anything viable. This takes // care of cases where the filtered set of providers didn't provide anything but one of the // other providers could still be valid, but doesn't explicitly treat the typed character as // a trigger character. var(textuallyTriggeredProviders, untriggeredProviders) = FilterProviders(allProviders, args.TypedChar); var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.TypeCharCommand, args.TypedChar); if (!IsSessionActive) { // No computation at all. If this is not a trigger character, we just ignore it and // stay in this state. Otherwise, if it's a trigger character, start up a new // computation and start computing the model in the background. if (textuallyTriggeredProviders.Any()) { // First create the session that represents that we now have a potential // signature help list. Then tell it to start computing. StartSession(textuallyTriggeredProviders, triggerInfo); return; } else { // No need to do anything. Just stay in the state where we have no session. return; } } else { var computed = false; if (allProviders.Any(p => p.IsRetriggerCharacter(args.TypedChar))) { // The user typed a character that might close the scope of the current model. // In this case, we should requery all providers. // // e.g. Math.Max(Math.Min(1,2)$$ sessionOpt.ComputeModel(allProviders, new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.RetriggerCommand, triggerInfo.TriggerCharacter)); computed = true; } if (textuallyTriggeredProviders.Any()) { // The character typed was something like "(". It can both filter a list if // it was in a string like: Goo(bar, "( // // Or it can trigger a new list. Ask the computation to compute again. sessionOpt.ComputeModel( textuallyTriggeredProviders.Concat(untriggeredProviders), triggerInfo); computed = true; } if (!computed) { // A character was typed and we haven't updated our model; do so now. sessionOpt.ComputeModel(allProviders, new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.RetriggerCommand)); } } }
protected override bool TryExecuteCommand(int caretPosition, Document document, CommandExecutionContext context) { var streamingPresenter = base.GetStreamingPresenter(); if (streamingPresenter != null) { _ = FindDerivedSymbolsAsync(document, caretPosition, streamingPresenter); return(true); } return(false); }
public bool ExecuteCommand(SkimDownCommandArgs args, CommandExecutionContext executionContext) { Debug.WriteLine("Omg, it worked !"); return(false); }
public bool ExecuteCommand(FormatDocXmlInSelectionCommandArgs args, CommandExecutionContext executionContext) { if (args == null) { throw new ArgumentNullException(nameof(args)); } if (executionContext == null) { throw new ArgumentNullException(nameof(executionContext)); } var textView = args.TextView; var snapshot = textView.TextSnapshot; var textBuffer = textView.TextBuffer; if (textBuffer.EditInProgress) { return(false); } var selection = textView.Selection; if (selection.Mode != TextSelectionMode.Stream) { return(false); } var startPosition = selection.Start.Position; var endPosition = selection.End.Position; if (startPosition == endPosition) { // Extend the caret to a selection. var line = textView.GetTextViewLineContainingBufferPosition(startPosition); if (startPosition != line.Start) { startPosition -= 1; } if (endPosition != line.End) { endPosition += 1; } } var selectionSpan = TextSpan.FromBounds(startPosition, endPosition); var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return(false); } _ = _joinableTaskContext.Factory.RunAsync(() => FormatDocXmlInSelectionAsync(document, selectionSpan, executionContext.OperationContext.UserCancellationToken)); return(true); }
void IChainedCommandHandler <InvokeSignatureHelpCommandArgs> .ExecuteCommand(InvokeSignatureHelpCommandArgs args, Action nextHandler, CommandExecutionContext context) { AssertIsForeground(); ExecuteCommandWorker(args, nextHandler, context); }
void IChainedCommandHandler <TypeCharCommandArgs> .ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) { AssertIsForeground(); ExecuteCommandWorker(args, nextHandler, context); }
public bool ExecuteCommand(FormatSelectionCommandArgs args, CommandExecutionContext context) { return(TryExecuteCommand(args, context)); }
public void ExecuteCommand(OpenLineBelowCommandArgs args, Action nextHandler, CommandExecutionContext context) { HandlePossibleTypingCommand(args, nextHandler, span => { if (_renameService.ActiveSession != null) { _renameService.ActiveSession.Commit(); } nextHandler(); }); }
public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { // We need to check for the token *after* the opening quote is typed, so defer to the editor first nextCommandHandler(); if (args.TypedChar == '"') { var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (caret != null) { var position = caret.Value.Position; var snapshot = caret.Value.Snapshot; if (position >= 3 && snapshot[position - 1] == '"' && snapshot[position - 2] == '$' && snapshot[position - 3] == '@') { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var root = document.GetSyntaxRootSynchronously(executionContext.OperationContext.UserCancellationToken); var token = root.FindToken(position - 3); if (token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken)) { args.SubjectBuffer.Replace(new Span(position - 3, 2), "$@"); } } } } } }
public int Execute(CommandExecutionContext ctx) { return(_dep.GetNumber()); }
public int Execute(CommandExecutionContext ctx) { throw new NotImplementedException(); }
public bool ExecuteCommand(ToggleLineCommentCommandArgs args, CommandExecutionContext context) => ExecuteCommand(args.TextView, args.SubjectBuffer, ValueTuple.Create(), context);
private bool BeforeExecuteCommand(bool speculative, TypeCharCommandArgs args, CommandExecutionContext executionContext) { if (args.TypedChar != ';' || !args.TextView.Selection.IsEmpty) { return(false); } var caretOpt = args.TextView.GetCaretPoint(args.SubjectBuffer); if (!caretOpt.HasValue) { return(false); } if (!_globalOptions.GetOption(FeatureOnOffOptions.AutomaticallyCompleteStatementOnSemicolon)) { return(false); } var caret = caretOpt.Value; var document = caret.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return(false); } var cancellationToken = executionContext.OperationContext.UserCancellationToken; var syntaxFacts = document.GetLanguageService <ISyntaxFactsService>(); var root = document.GetSyntaxRootSynchronously(cancellationToken); if (!TryGetStartingNode(root, caret, out var currentNode, cancellationToken)) { return(false); } return(MoveCaretToSemicolonPosition(speculative, args, document, root, originalCaret: caret, caret, syntaxFacts, currentNode, isInsideDelimiters: false, cancellationToken)); }
public void ExecuteCommand(AutomaticLineEnderCommandArgs args, Action nextHandler, CommandExecutionContext context) { // get editor operation var operations = _editorOperationsFactoryService.GetEditorOperations(args.TextView); if (operations == null) { nextHandler(); return; } var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { NextAction(operations, nextHandler); return; } // feature off if (!document.Project.Solution.Workspace.Options.GetOption(InternalFeatureOnOffOptions.AutomaticLineEnder)) { NextAction(operations, nextHandler); return; } using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Automatically_completing)) { var cancellationToken = context.OperationContext.UserCancellationToken; // caret is not on the subject buffer. nothing we can do var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (!caret.HasValue) { NextAction(operations, nextHandler); return; } var caretPosition = caret.Value; // special cases where we treat this command simply as Return. if (TreatAsReturn(document, caretPosition, cancellationToken)) { // leave it to the VS editor to handle this command. // VS editor's default implementation of SmartBreakLine is simply BreakLine, which inserts // a new line and positions the caret with smart indent. nextHandler(); return; } var subjectLineWhereCaretIsOn = caretPosition.GetContainingLine(); // Two possible operations // 1. Add/remove the brace for the selected syntax node (only for C#) // 2. Append an ending string to the line. (For C#, it is semicolon ';', For VB, it is underline '_') // Check if the node could be used to add/remove brace. var selectNodeAndOperationKind = GetValidNodeToModifyBraces(document, caretPosition, cancellationToken); if (selectNodeAndOperationKind != null) { var(selectedNode, addBrace) = selectNodeAndOperationKind.Value; using var transaction = args.TextView.CreateEditTransaction(EditorFeaturesResources.Automatic_Line_Ender, _undoRegistry, _editorOperationsFactoryService); ModifySelectedNode(args, document, selectedNode, addBrace, caretPosition, cancellationToken); NextAction(operations, nextHandler); transaction.Complete(); return; } // Check if we could find the ending position var endingInsertionPosition = GetInsertionPositionForEndingString(document, subjectLineWhereCaretIsOn, cancellationToken); if (endingInsertionPosition != null) { using var transaction = args.TextView.CreateEditTransaction(EditorFeaturesResources.Automatic_Line_Ender, _undoRegistry, _editorOperationsFactoryService); InsertEnding(args.TextView, document, endingInsertionPosition.Value, caretPosition, cancellationToken); NextAction(operations, nextHandler); transaction.Complete(); return; } // Neither of the two operations could be performed using var editTransaction = args.TextView.CreateEditTransaction(EditorFeaturesResources.Automatic_Line_Ender, _undoRegistry, _editorOperationsFactoryService); NextAction(operations, nextHandler); editTransaction.Complete(); } }
public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { var willMoveSemicolon = BeforeExecuteCommand(speculative: true, args, executionContext); if (!willMoveSemicolon) { // Pass this on without altering the undo stack nextCommandHandler(); return; } using var transaction = CaretPreservingEditTransaction.TryCreate(CSharpEditorResources.Complete_statement_on_semicolon, args.TextView, _textUndoHistoryRegistry, _editorOperationsFactoryService); // Determine where semicolon should be placed and move caret to location BeforeExecuteCommand(speculative: false, args, executionContext); // Insert the semicolon using next command handler nextCommandHandler(); transaction.Complete(); }
public bool ExecuteCommand(SyncClassViewCommandArgs args, CommandExecutionContext context) { this.AssertIsForeground(); var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1; if (caretPosition < 0) { return(false); } var snapshot = args.SubjectBuffer.CurrentSnapshot; using var waitScope = context.OperationContext.AddScope(allowCancellation: true, string.Format(ServicesVSResources.Synchronizing_with_0, ClassView)); var document = snapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync( context.OperationContext).WaitAndGetResult(context.OperationContext.UserCancellationToken); if (document == null) { return(true); } var syntaxFactsService = document.GetLanguageService <ISyntaxFactsService>(); if (syntaxFactsService == null) { return(true); } var libraryService = document.GetLanguageService <ILibraryService>(); if (libraryService == null) { return(true); } var userCancellationToken = context.OperationContext.UserCancellationToken; var semanticModel = document .GetSemanticModelAsync(userCancellationToken) .WaitAndGetResult(userCancellationToken); var root = semanticModel.SyntaxTree .GetRootAsync(userCancellationToken) .WaitAndGetResult(userCancellationToken); var memberDeclaration = syntaxFactsService.GetContainingMemberDeclaration(root, caretPosition); var symbol = memberDeclaration != null ? semanticModel.GetDeclaredSymbol(memberDeclaration, userCancellationToken) : null; while (symbol != null && !IsValidSymbolToSynchronize(symbol)) { symbol = symbol.ContainingSymbol; } IVsNavInfo navInfo = null; if (symbol != null) { navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, document.Project, semanticModel.Compilation, useExpandedHierarchy: true); } if (navInfo == null) { navInfo = libraryService.NavInfoFactory.CreateForProject(document.Project); } if (navInfo == null) { return(true); } var navigationTool = _serviceProvider.GetService <SVsClassView, IVsNavigationTool>(); navigationTool.NavigateToNavInfo(navInfo); return(true); }
public bool ExecuteCommand(EncapsulateFieldCommandArgs args, CommandExecutionContext context) { CommitIfActive(args); return(false); }
public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { // Determine where semicolon should be placed and move caret to location BeforeExecuteCommand(args, executionContext); // Insert the semicolon using next command handler nextCommandHandler(); }
public bool ExecuteCommand(ExtractInterfaceCommandArgs args, CommandExecutionContext context) { CommitIfActive(args); return(false); }
bool ICommandHandler <ExecuteInInteractiveCommandArgs> .ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context) { var window = OpenInteractiveWindow(focus: false); using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesWpfResources.Executing_selection_in_Interactive_Window)) { var submission = GetSelectedText(args, context.OperationContext.UserCancellationToken); if (!string.IsNullOrWhiteSpace(submission)) { window.SubmitAsync(new string[] { submission }); } } return(true); }
void IChainedCommandHandler <TypeCharCommandArgs> .ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) { AssertIsForeground(); // When a character is typed it is *always* sent through to the editor. This way the // editor always represents what would have been typed had completion not been involved // at this point. That means that if we decide to commit, then undo'ing the commit will // return you to the code that you would have typed if completion was not up. // // The steps we follow for commit are as follows: // // 1) send the commit character through to the buffer. // 2) open a transaction. // 2a) roll back the text to before the text was sent through // 2b) commit the item. // 2c) send the commit character through again.* // 2d) commit the transaction. // // 2c is very important. it makes sure that post our commit all our normal features // run depending on what got typed. For example if the commit character was ( // then brace completion may run. If it was ; then formatting may run. But, importantly // this code doesn't need to know anything about that. Furthermore, because that code // runs within this transaction, then the user can always undo and get to what the code // would have been if completion was not involved. // // 2c*: note sending the commit character through to the buffer again can be controlled // by the completion item. For example, completion items that want to totally handle // what gets output into the buffer can ask for this not to happen. An example of this // is override completion. If the user types "override Method(" then we'll want to // spit out the entire method and *not* also spit out "(" again. // In order to support 2a (rolling back), we capture hte state of the buffer before // we send the character through. We then just apply the edits in reverse order to // roll us back. var initialTextSnapshot = this.SubjectBuffer.CurrentSnapshot; var initialCaretPosition = GetCaretPointInViewBuffer(); // Note: while we're doing this, we don't want to hear about buffer changes (since we // know they're going to happen). So we disconnect and reconnect to the event // afterwards. That way we can hear about changes to the buffer that don't happen // through us. // Automatic Brace Completion may also move the caret, so unsubscribe from that too this.TextView.TextBuffer.PostChanged -= OnTextViewBufferPostChanged; this.TextView.Caret.PositionChanged -= OnCaretPositionChanged; // In Venus/Razor, the user might be typing on the buffer's seam. This means that, // depending on the character typed, the character may not go into our buffer. var isOnSeam = IsOnSeam(); try { nextHandler(); } finally { this.TextView.TextBuffer.PostChanged += OnTextViewBufferPostChanged; this.TextView.Caret.PositionChanged += OnCaretPositionChanged; } var typedChar = args.TypedChar; // We only want to process typechar if it is a normal typechar and no one else is // involved. i.e. if there was a typechar, but someone processed it and moved the caret // somewhere else then we don't want completion. Also, if a character was typed but // something intercepted and placed different text into the editor, then we don't want // to proceed. if (this.TextView.TypeCharWasHandledStrangely(this.SubjectBuffer, typedChar)) { if (sessionOpt != null) { // If we're on a seam (razor) with a computation, and the user types a character // that goes into the other side of the seam, the character may be a commit character. // If it's a commit character, just commit without trying to check caret position, // since the caret is no longer in our buffer. if (isOnSeam) { var model = this.WaitForModel(); if (this.CommitIfCommitCharacter(typedChar, model, initialTextSnapshot, nextHandler)) { return; } } if (_autoBraceCompletionChars.Contains(typedChar) && this.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.AutomaticPairCompletion)) { var model = this.WaitForModel(); if (this.CommitIfCommitCharacter(typedChar, model, initialTextSnapshot, nextHandler)) { // I don't think there is any better way than this. if typed char is one of auto brace completion char, // we don't do multiple buffer change check return; } } // If we were computing anything, we stop. We only want to process a typechar // if it was a normal character. this.DismissSessionIfActive(); } return; } var completionService = this.GetCompletionService(); if (completionService == null) { return; } var options = GetOptions(); Contract.ThrowIfNull(options); var isTextuallyTriggered = IsTextualTriggerCharacter(completionService, typedChar, options); var isPotentialFilterCharacter = ItemManager.IsPotentialFilterCharacter(typedChar); var trigger = CompletionTrigger.CreateInsertionTrigger(typedChar); if (sessionOpt == null) { // No computation at all. If this is not a trigger character, we just ignore it and // stay in this state. Otherwise, if it's a trigger character, start up a new // computation and start computing the model in the background. if (isTextuallyTriggered) { // First create the session that represents that we now have a potential // completion list. Then tell it to start computing. StartNewModelComputation(completionService, trigger); return; } else { // No need to do anything. Just stay in the state where we have no session. return; } } else { sessionOpt.UpdateModelTrackingSpan(initialCaretPosition); // If the session is up, it may be in one of many states. It may know nothing // (because it is currently computing the list of completions). Or it may have a // list of completions that it has filtered. // If the user types something which is absolutely known to be a filter character // then we can just proceed without blocking. if (isPotentialFilterCharacter) { if (isTextuallyTriggered) { // The character typed was something like "a". It can both filter a list if // we have computed one, or it can trigger a new list. Ask the computation // to compute again. If nothing has been computed, then it will try to // compute again, otherwise it will just ignore this request. sessionOpt.ComputeModel(completionService, trigger, _roles, options); } // Now filter whatever result we have. sessionOpt.FilterModel(CompletionFilterReason.Insertion, filterState: null); } else { // It wasn't a trigger or filter character. At this point, we make our // determination on what to do based on what has actually been computed and // what's being typed. This means waiting on the session and will effectively // block the user. var model = WaitForModel(); // What they type may end up filtering, committing, or else will dismiss. // // For example, we may filter in cases like this: "Color." // // "Color" will have already filtered the list down to some things like // "Color", "Color.Red", "Color.Blue", etc. When we process the 'dot', we // actually want to filter some more. But we can't know that ahead of time until // we have computed the list of completions. if (this.IsFilterCharacter(typedChar, model)) { // Known to be a filter character for the currently selected item. So just // filter the session. sessionOpt.FilterModel(CompletionFilterReason.Insertion, filterState: null); return; } // It wasn't a filter character. We'll either commit what's selected, or we'll // dismiss the completion list. First, ensure that what was typed is in the // buffer. // Now, commit if it was a commit character. this.CommitIfCommitCharacter(typedChar, model, initialTextSnapshot, nextHandler); // At this point we don't want a session anymore (either because we committed, or // because we got a character we don't know how to handle). Unilaterally dismiss // the session. DismissSessionIfActive(); // The character may commit/dismiss and then trigger completion again. So check // for that here. if (isTextuallyTriggered) { StartNewModelComputation( completionService, trigger); return; } } } }
void IChainedCommandHandler <SaveCommandArgs> .ExecuteCommand(SaveCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { var textContainer = args.SubjectBuffer.AsTextContainer(); if (Workspace.TryGetWorkspace(textContainer, out var workspace)) { var encService = workspace.Services.GetService <IEditAndContinueWorkspaceService>(); if (encService != null) { var documentId = workspace.GetDocumentIdInCurrentContext(textContainer); if (documentId != null) { encService.OnSourceFileUpdated(documentId); } } } nextCommandHandler(); }
bool ICommandHandler <CopyToInteractiveCommandArgs> .ExecuteCommand(CopyToInteractiveCommandArgs args, CommandExecutionContext context) { var window = OpenInteractiveWindow(focus: true); var buffer = window.CurrentLanguageBuffer; if (buffer != null) { CopyToWindow(window, args, context); } else { Action action = null; action = new Action(() => { window.ReadyForInput -= action; CopyToWindow(window, args, context); }); window.ReadyForInput += action; } return(true); }
/// <summary> /// Uncomment the selected spans, and reset the selection. /// </summary> public bool ExecuteCommand(UncommentSelectionCommandArgs args, CommandExecutionContext context) { return(this.ExecuteCommand(args.TextView, args.SubjectBuffer, Operation.Uncomment, context)); }
private void CopyToWindow(IInteractiveWindow window, CopyToInteractiveCommandArgs args, CommandExecutionContext context) { var buffer = window.CurrentLanguageBuffer; Debug.Assert(buffer != null); using (var edit = buffer.CreateEdit()) using (var waitScope = context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesWpfResources.Copying_selection_to_Interactive_Window)) { var text = GetSelectedText(args, context.OperationContext.UserCancellationToken); // If the last line isn't empty in the existing submission buffer, we will prepend a // newline var lastLine = buffer.CurrentSnapshot.GetLineFromLineNumber(buffer.CurrentSnapshot.LineCount - 1); if (lastLine.Extent.Length > 0) { var editorOptions = _editorOptionsFactoryService.GetOptions(args.SubjectBuffer); text = editorOptions.GetNewLineCharacter() + text; } edit.Insert(buffer.CurrentSnapshot.Length, text); edit.Apply(); } // Move the caret to the end var editorOperations = _editorOperationsFactoryService.GetEditorOperations(window.TextView); var endPoint = new VirtualSnapshotPoint(window.TextView.TextBuffer.CurrentSnapshot, window.TextView.TextBuffer.CurrentSnapshot.Length); editorOperations.SelectAndMoveCaret(endPoint, endPoint); }