AutocompleteFilepathContext.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using NStack;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.IO.Abstractions;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. namespace Terminal.Gui {
  9. internal class AutocompleteFilepathContext : AutocompleteContext {
  10. public FileDialogState State { get; set; }
  11. public AutocompleteFilepathContext (ustring currentLine, int cursorPosition, FileDialogState state)
  12. : base (currentLine.ToRuneList (), cursorPosition)
  13. {
  14. this.State = state;
  15. }
  16. }
  17. internal class FilepathSuggestionGenerator : ISuggestionGenerator {
  18. FileDialogState state;
  19. public IEnumerable<Suggestion> GenerateSuggestions (AutocompleteContext context)
  20. {
  21. if (context is AutocompleteFilepathContext fileState) {
  22. this.state = fileState.State;
  23. }
  24. if (state == null) {
  25. return Enumerable.Empty<Suggestion> ();
  26. }
  27. var path = ustring.Make (context.CurrentLine).ToString ();
  28. var last = path.LastIndexOfAny (FileDialog.Separators);
  29. if(string.IsNullOrWhiteSpace(path) || !Path.IsPathRooted(path)) {
  30. return Enumerable.Empty<Suggestion> ();
  31. }
  32. var term = path.Substring (last + 1);
  33. // If path is /tmp/ then don't just list everything in it
  34. if(string.IsNullOrWhiteSpace(term))
  35. {
  36. return Enumerable.Empty<Suggestion> ();
  37. }
  38. if (term.Equals (state?.Directory?.Name)) {
  39. // Clear suggestions
  40. return Enumerable.Empty<Suggestion> ();
  41. }
  42. bool isWindows = RuntimeInformation.IsOSPlatform (OSPlatform.Windows);
  43. var suggestions = state.Children.Where(d=> !d.IsParent).Select (
  44. e => e.FileSystemInfo is IDirectoryInfo d
  45. ? d.Name + System.IO.Path.DirectorySeparatorChar
  46. : e.FileSystemInfo.Name)
  47. .ToArray ();
  48. var validSuggestions = suggestions
  49. .Where (s => s.StartsWith (term, isWindows ?
  50. StringComparison.InvariantCultureIgnoreCase :
  51. StringComparison.InvariantCulture))
  52. .OrderBy (m => m.Length)
  53. .ToArray ();
  54. // nothing to suggest
  55. if (validSuggestions.Length == 0 || validSuggestions [0].Length == term.Length) {
  56. return Enumerable.Empty<Suggestion> ();
  57. }
  58. return validSuggestions.Select (
  59. f => new Suggestion (term.Length, f, f)).ToList ();
  60. }
  61. public bool IsWordChar (Rune rune)
  62. {
  63. if (rune == '\n') {
  64. return false;
  65. }
  66. return true;
  67. }
  68. }
  69. }