Browse Source

- Added Monaco editor to text input fields

- Started work on template renderer
master
Claire Davis 4 years ago
parent
commit
13b8e871c0
  1. 26
      Adaptive Card Editor UWP.sln
  2. 9
      Adaptive Card Editor UWP/Adaptive Card Editor UWP.csproj
  3. 41
      Adaptive Card Editor UWP/MainPage.xaml
  4. 123
      Adaptive Card Editor UWP/MainPage.xaml.cs
  5. 164
      MonacoEditorComponent/CodeEditor.Events.cs
  6. 178
      MonacoEditorComponent/CodeEditor.Methods.cs
  7. 311
      MonacoEditorComponent/CodeEditor.Properties.cs
  8. 279
      MonacoEditorComponent/CodeEditor.cs
  9. 206
      MonacoEditorComponent/Extensions/WebViewExtensions.cs
  10. 16
      MonacoEditorComponent/Helpers/DebugLogger.cs
  11. 35
      MonacoEditorComponent/Helpers/DispatcherTaskExtensions.cs
  12. 35
      MonacoEditorComponent/Helpers/InterfaceToClassConverter.cs
  13. 64
      MonacoEditorComponent/Helpers/KeyboardListener.cs
  14. 247
      MonacoEditorComponent/Helpers/ParentAccessor.cs
  15. 116
      MonacoEditorComponent/Helpers/ThemeListener.cs
  16. 65
      MonacoEditorComponent/Monaco/Editor/ContextKey.cs
  17. 57
      MonacoEditorComponent/Monaco/Editor/IActionDescriptor.cs
  18. 34
      MonacoEditorComponent/Monaco/Editor/IContextKey.cs
  19. 218
      MonacoEditorComponent/Monaco/Editor/IEditorConstructionOptions.cs
  20. 24
      MonacoEditorComponent/Monaco/Editor/IEditorFindOptions.cs
  21. 28
      MonacoEditorComponent/Monaco/Editor/IEditorMinimapOptions.cs
  22. 165
      MonacoEditorComponent/Monaco/Editor/IEditorOptions.cs
  23. 42
      MonacoEditorComponent/Monaco/Editor/IEditorScrollbarOptions.cs
  24. 22
      MonacoEditorComponent/Monaco/Editor/IMarker.cs
  25. 27
      MonacoEditorComponent/Monaco/Editor/IMarkerData.cs
  26. 92
      MonacoEditorComponent/Monaco/Editor/IModel.cs
  27. 75
      MonacoEditorComponent/Monaco/Editor/IModelDecorationOptions.cs
  28. 31
      MonacoEditorComponent/Monaco/Editor/IModelDeltaDecoration.cs
  29. 30
      MonacoEditorComponent/Monaco/Editor/IWordAtPosition.cs
  30. 50
      MonacoEditorComponent/Monaco/Editor/Marker.cs
  31. 44
      MonacoEditorComponent/Monaco/Editor/MarkerData.cs
  32. 13
      MonacoEditorComponent/Monaco/Editor/TrackedRangeStickiness.cs
  33. 28
      MonacoEditorComponent/Monaco/Editor/WordAtPosition.cs
  34. 25
      MonacoEditorComponent/Monaco/Helpers/CssGlyphStyle.cs
  35. 82
      MonacoEditorComponent/Monaco/Helpers/CssInlineStyle.cs
  36. 43
      MonacoEditorComponent/Monaco/Helpers/CssLineStyle.cs
  37. 74
      MonacoEditorComponent/Monaco/Helpers/CssStyleBroker.cs
  38. 70
      MonacoEditorComponent/Monaco/Helpers/Json.cs
  39. 57
      MonacoEditorComponent/Monaco/IMarkdownString.cs
  40. 15
      MonacoEditorComponent/Monaco/IPosition.cs
  41. 19
      MonacoEditorComponent/Monaco/IRange.cs
  42. 35
      MonacoEditorComponent/Monaco/IUri.cs
  43. 186
      MonacoEditorComponent/Monaco/KeyCode.cs
  44. 43
      MonacoEditorComponent/Monaco/KeyMod.cs
  45. 28
      MonacoEditorComponent/Monaco/Languages/Command.cs
  46. 21
      MonacoEditorComponent/Monaco/Languages/CompletionContext.cs
  47. 53
      MonacoEditorComponent/Monaco/Languages/CompletionItem.cs
  48. 28
      MonacoEditorComponent/Monaco/Languages/CompletionItemKind.cs
  49. 21
      MonacoEditorComponent/Monaco/Languages/CompletionItemProvider.cs
  50. 32
      MonacoEditorComponent/Monaco/Languages/CompletionList.cs
  51. 30
      MonacoEditorComponent/Monaco/Languages/Hover.cs
  52. 11
      MonacoEditorComponent/Monaco/Languages/HoverProvider.cs
  53. 35
      MonacoEditorComponent/Monaco/Languages/ILanguageExtensionPoint.cs
  54. 35
      MonacoEditorComponent/Monaco/Languages/SnippetString.cs
  55. 12
      MonacoEditorComponent/Monaco/Languages/SuggestTriggerKind.cs
  56. 102
      MonacoEditorComponent/Monaco/LanguagesHelper.cs
  57. 350
      MonacoEditorComponent/Monaco/ModelHelper.cs
  58. 123
      MonacoEditorComponent/Monaco/Position.cs
  59. 122
      MonacoEditorComponent/Monaco/Range.cs
  60. 89
      MonacoEditorComponent/Monaco/Selection.cs
  61. 19
      MonacoEditorComponent/Monaco/Severity.cs
  62. 241
      MonacoEditorComponent/MonacoEditor.html
  63. 212
      MonacoEditorComponent/MonacoEditorComponent.csproj
  64. 42
      MonacoEditorComponent/MonacoEditorComponent.nuspec
  65. 29
      MonacoEditorComponent/Properties/AssemblyInfo.cs
  66. 21
      MonacoEditorComponent/Properties/MonacoEditorComponent.rd.xml
  67. 26
      MonacoEditorComponent/Themes/generic.xaml
  68. 344
      MonacoEditorComponent/monaco-editor/CHANGELOG.md
  69. 21
      MonacoEditorComponent/monaco-editor/LICENSE
  70. 98
      MonacoEditorComponent/monaco-editor/README.md
  71. 278
      MonacoEditorComponent/monaco-editor/ThirdPartyNotices.txt
  72. 5311
      MonacoEditorComponent/monaco-editor/dev/bundleInfo.json
  73. 1691
      MonacoEditorComponent/monaco-editor/dev/nls.metadata.json
  74. 11890
      MonacoEditorComponent/monaco-editor/dev/vs/base/worker/workerMain.js
  75. 1
      MonacoEditorComponent/monaco-editor/dev/vs/base/worker/workerMain.js.map
  76. 35
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/_.contribution.js
  77. 16
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/bat/bat.contribution.js
  78. 99
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/bat/bat.js
  79. 17
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/coffee/coffee.contribution.js
  80. 173
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/coffee/coffee.js
  81. 22
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/cpp/cpp.contribution.js
  82. 325
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/cpp/cpp.js
  83. 16
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/csharp/csharp.contribution.js
  84. 187
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/csharp/csharp.js
  85. 16
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/csp/csp.contribution.js
  86. 58
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/csp/csp.js
  87. 17
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/css/css.contribution.js
  88. 174
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/css/css.js
  89. 17
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/dockerfile/dockerfile.contribution.js
  90. 118
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/dockerfile/dockerfile.js
  91. 16
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/fsharp/fsharp.contribution.js
  92. 139
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/fsharp/fsharp.js
  93. 16
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/go/go.contribution.js
  94. 173
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/go/go.js
  95. 17
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/handlebars/handlebars.contribution.js
  96. 196
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/handlebars/handlebars.js
  97. 17
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/html/html.contribution.js
  98. 210
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/html/html.js
  99. 17
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/ini/ini.contribution.js
  100. 71
      MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/ini/ini.js
  101. Some files were not shown because too many files changed in this diff diff.show_more

26
Adaptive Card Editor UWP.sln

@ -5,18 +5,23 @@ VisualStudioVersion = 16.0.29521.150
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adaptive Card Editor UWP", "Adaptive Card Editor UWP\Adaptive Card Editor UWP.csproj", "{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonacoEditorComponent", "MonacoEditorComponent\MonacoEditorComponent.csproj", "{DD49485C-2D9B-4824-B64E-52193B43E4CB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|ARM = Debug|ARM
Debug|ARM64 = Debug|ARM64
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|ARM = Release|ARM
Release|ARM64 = Release|ARM64
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Debug|Any CPU.ActiveCfg = Debug|x86
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Debug|ARM.ActiveCfg = Debug|ARM
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Debug|ARM.Build.0 = Debug|ARM
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Debug|ARM.Deploy.0 = Debug|ARM
@ -29,6 +34,7 @@ Global
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Debug|x86.ActiveCfg = Debug|x86
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Debug|x86.Build.0 = Debug|x86
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Debug|x86.Deploy.0 = Debug|x86
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Release|Any CPU.ActiveCfg = Release|x86
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Release|ARM.ActiveCfg = Release|ARM
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Release|ARM.Build.0 = Release|ARM
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Release|ARM.Deploy.0 = Release|ARM
@ -41,6 +47,26 @@ Global
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Release|x86.ActiveCfg = Release|x86
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Release|x86.Build.0 = Release|x86
{E2F5AF78-D3E6-43F9-AF44-F342449B63A5}.Release|x86.Deploy.0 = Release|x86
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Debug|ARM.ActiveCfg = Debug|ARM
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Debug|ARM.Build.0 = Debug|ARM
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Debug|ARM64.ActiveCfg = Debug|Any CPU
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Debug|ARM64.Build.0 = Debug|Any CPU
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Debug|x64.ActiveCfg = Debug|x64
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Debug|x64.Build.0 = Debug|x64
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Debug|x86.ActiveCfg = Debug|x86
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Debug|x86.Build.0 = Debug|x86
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Release|Any CPU.Build.0 = Release|Any CPU
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Release|ARM.ActiveCfg = Release|ARM
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Release|ARM.Build.0 = Release|ARM
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Release|ARM64.ActiveCfg = Release|Any CPU
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Release|ARM64.Build.0 = Release|Any CPU
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Release|x64.ActiveCfg = Release|x64
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Release|x64.Build.0 = Release|x64
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Release|x86.ActiveCfg = Release|x86
{DD49485C-2D9B-4824-B64E-52193B43E4CB}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

9
Adaptive Card Editor UWP/Adaptive Card Editor UWP.csproj

@ -159,6 +159,15 @@
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>6.2.9</Version>
</PackageReference>
<PackageReference Include="Newtonsoft.Json">
<Version>12.0.3</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MonacoEditorComponent\MonacoEditorComponent.csproj">
<Project>{dd49485c-2d9b-4824-b64e-52193b43e4cb}</Project>
<Name>MonacoEditorComponent</Name>
</ProjectReference>
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
<VisualStudioVersion>14.0</VisualStudioVersion>

41
Adaptive Card Editor UWP/MainPage.xaml

@ -3,6 +3,7 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Adaptive_Card_Editor_UWP"
xmlns:monaco="using:Monaco"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
@ -16,24 +17,44 @@
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition Height="*" />
<RowDefinition Height="50*" />
<RowDefinition Height="20" />
<RowDefinition Height="50*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0">
<TextBlock Grid.Row="0" Grid.Column="0" Padding="20 0">
Adaptive Card JSON Input:
</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1">
Rendered Output (UWP Library):
<TextBlock Grid.Row="0" Grid.Column="1" Padding="20 0">
Adaptive Card Data Model:
</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="2">
Rendered Output (Template Library):
<TextBlock Grid.Row="0" Grid.Column="2" Padding="20 0">
Rendered Output (UWP Library):
</TextBlock>
<TextBox Grid.Row="1" Grid.Column="0" x:Name="txtInput" Margin="20" KeyUp="txtInput_KeyUp" TextWrapping="Wrap"></TextBox>
<Border Grid.Row="1" BorderBrush="#777" BorderThickness="1" Grid.Column="1" Margin="20">
<Border Grid.Row="1" Grid.RowSpan="3" Grid.Column="0" BorderBrush="#777" BorderThickness="1" Margin="20 10">
<monaco:CodeEditor x:Name="txtInput"
TabIndex="0"
HasGlyphMargin="False"
CodeLanguage="json"
KeyDown="txtInput_KeyDown">
</monaco:CodeEditor>
</Border>
<Border Grid.Row="1" Grid.RowSpan="3" Grid.Column="1" BorderBrush="#777" BorderThickness="1" Margin="20 10">
<monaco:CodeEditor x:Name="txtData"
TabIndex="0"
HasGlyphMargin="False"
CodeLanguage="json"
KeyDown="txtData_KeyDown">
</monaco:CodeEditor>
</Border>
<Border Grid.Row="1" Grid.Column="2" BorderBrush="#777" BorderThickness="1" Margin="20 10">
<Grid x:Name="grdCard">
</Grid>
</Border>
<Border Grid.Row="1" BorderBrush="#777" BorderThickness="1" Grid.Column="2" Margin="20">
<TextBlock Grid.Row="2" Grid.Column="2" Padding="20 0">
Rendered Output (Template Library):
</TextBlock>
<Border Grid.Row="3" Grid.Column="2" BorderBrush="#777" BorderThickness="1" Margin="20 10">
<Grid x:Name="grdTemplated">
</Grid>

123
Adaptive Card Editor UWP/MainPage.xaml.cs

@ -1,19 +1,27 @@
using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using AdaptiveCards.Rendering.Uwp;
using Monaco;
using Monaco.Helpers;
using Newtonsoft.Json;
// probs don't need these
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using AdaptiveCards.Rendering.Uwp;
using System.Threading.Tasks;
using Monaco.Editor;
using Monaco.Languages;
using Newtonsoft.Json.Linq;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
@ -24,29 +32,82 @@ namespace Adaptive_Card_Editor_UWP
/// </summary>
public sealed partial class MainPage : Page
{
/// <summary>
/// Create DispatcherTimer for handling input delay logic
/// </summary>
public DispatcherTimer keyTimer = new DispatcherTimer();
/// <summary>
/// timestamp in ticks (hundred nanoseconds) of last captured KeyUp event
/// </summary>
public long lastKeyUp;
/// <summary>
/// boolean indicating whether input has changed since last tick
/// </summary>
public bool isRendered;
/// <summary>
/// timer interval in ticks (hundred nanoseconds)
/// </summary>
public long interval = 5000000;
/// <summary>
/// list of known entities that contain templated content
/// </summary>
/// <remarks>
/// If the data referenced in the container doesn't exist, the container shouldn't be included in the rendered output
/// </remarks>
public List<string> Containers = new List<string>
{
"ActionSet",
"Container",
"ColumnSet",
"Column",
"FactSheet",
"Fact",
"ImageSet"
};
public MainPage()
{
// set up a window timer for handling the keyup delay
TimerSetup();
this.InitializeComponent();
}
/// <summary>
/// Sets up a window timer with a 500ms tick interval and starts the timer
/// </summary>
public void TimerSetup()
{
// on every timer tick, run TimerTick()
keyTimer.Tick += TimerTick;
// keyTimer.Interval = new TimeSpan(0, 0, 1);
// set the timer interval to half a second
keyTimer.Interval = TimeSpan.Parse("00:00:00.05");
// start the timer
keyTimer.Start();
}
/// <summary>
/// fires when txtInput sees keyboard input
/// </summary>
private void txtInput_KeyDown(CodeEditor sender, WebKeyEventArgs e)
{
// last key up event = integer value of current time
lastKeyUp = DateTime.Now.Ticks;
// user is inputting text, so we're going to rerender
isRendered = false;
}
private void txtInput_KeyUp(object sender, KeyRoutedEventArgs e)
/// <summary>
/// fires when txtData sees keyboard input
/// </summary>
private void txtData_KeyDown(CodeEditor sender, WebKeyEventArgs args)
{
// last key up event = integer value of current time
lastKeyUp = DateTime.Now.Ticks;
@ -55,12 +116,17 @@ namespace Adaptive_Card_Editor_UWP
isRendered = false;
}
/// <summary>
/// Fires when the timer ticks
/// </summary>
void TimerTick(object sender, object args)
{
// if isRendered is true, there have been no changes to input since the last tick
if (isRendered)
{
return;
}
// otherwise, we done got input, so do the thing
else
{
if (DateTime.Now.Ticks >= lastKeyUp + interval )
@ -87,9 +153,33 @@ namespace Adaptive_Card_Editor_UWP
}
catch (Exception ex)
{
// this means bad data was ingested by the adaptive card renderer
// so just display the exception details
txtOutput.Text = ex.ToString();
grdCard.Children.Add(txtOutput);
}
// render a card using template and data
try
{
string Template = txtInput.Text;
string Data = txtData.Text;
string Rendered = JsonFromTemplate(Template, Data);
// render the card from the rendered template + data
AdaptiveCardRenderer cardRenderer = new AdaptiveCardRenderer();
AdaptiveCardParseResult parsedCard = AdaptiveCard.FromJsonString(Rendered);
RenderedAdaptiveCard theCard = cardRenderer.RenderAdaptiveCard(parsedCard.AdaptiveCard);
grdTemplated.Children.Add(theCard.FrameworkElement);
}
catch (Exception ex)
{
// this means bad data was ingested by the adaptive card renderer
// so just display the exception details
txtOutput.Text = ex.ToString();
grdTemplated.Children.Add(txtOutput);
}
grdCard.UpdateLayout();
isRendered = true;
@ -100,5 +190,24 @@ namespace Adaptive_Card_Editor_UWP
}
}
}
/// <summary>
/// Creates an adaptive card JSON payload from a template and data model. Follows the official templating language.
/// </summary>
/// <param name="Template">JSON adaptive card template</param>
/// <param name="Data">JSON data model</param>
/// <returns>JSON string to be ingested by adaptive card renderer</returns>
public string JsonFromTemplate(string strTemplate, string strData)
{
string output = "";
// first create JSON objects out of the input
JObject Template = JObject.Parse(strTemplate);
JObject Data = JObject.Parse(strData);
return output;
}
}
}

164
MonacoEditorComponent/CodeEditor.Events.cs

@ -0,0 +1,164 @@
using Monaco.Helpers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace Monaco
{
public partial class CodeEditor
{
// Override default Loaded/Loading event so we can make sure we've initialized our WebView contents with the CodeEditor.
/// <summary>
/// When Editor is Loading, it is ready to receive commands to the Monaco Engine.
/// </summary>
public new event RoutedEventHandler Loading;
/// <summary>
/// When Editor is Loaded, it has been rendered and is ready to be displayed.
/// </summary>
public new event RoutedEventHandler Loaded;
/// <summary>
/// Called when a link is Ctrl+Clicked on in the editor, set Handled to true to prevent opening.
/// </summary>
public event TypedEventHandler<WebView, WebViewNewWindowRequestedEventArgs> OpenLinkRequested;
/// <summary>
/// Called when an internal exception is encountered while executing a command. (for testing/reporting issues)
/// </summary>
public event TypedEventHandler<CodeEditor, Exception> InternalException;
/// <summary>
/// Custom Keyboard Handler.
/// </summary>
public new event WebKeyEventHandler KeyDown;
private ThemeListener _themeListener;
private void WebView_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
{
#if DEBUG
Debug.WriteLine("DOM Content Loaded");
#endif
this._initialized = true;
}
private async void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
this.IsLoaded = true;
// Make sure inner editor is focused
await SendScriptAsync("editor.focus();");
// If we're supposed to have focus, make sure we try and refocus on our now loaded webview.
if (FocusManager.GetFocusedElement() == this)
{
this._view.Focus(FocusState.Programmatic);
}
Loaded?.Invoke(this, new RoutedEventArgs());
}
internal ParentAccessor _parentAccessor;
private KeyboardListener _keyboardListener;
private long _themeToken;
private void WebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
#if DEBUG
Debug.WriteLine("Navigation Starting");
#endif
_parentAccessor = new ParentAccessor(this);
_parentAccessor.AddAssemblyForTypeLookup(typeof(Range).GetTypeInfo().Assembly);
_parentAccessor.RegisterAction("Loaded", CodeEditorLoaded);
_themeListener = new ThemeListener();
_themeListener.ThemeChanged += _themeListener_ThemeChanged;
_themeToken = RegisterPropertyChangedCallback(RequestedThemeProperty, RequestedTheme_PropertyChanged);
_keyboardListener = new KeyboardListener(this);
this._view.AddWebAllowedObject("Debug", new DebugLogger());
this._view.AddWebAllowedObject("Parent", _parentAccessor);
this._view.AddWebAllowedObject("Theme", _themeListener);
this._view.AddWebAllowedObject("Keyboard", _keyboardListener);
}
private async void CodeEditorLoaded()
{
if (Decorations != null && Decorations.Count > 0)
{
// Need to retrigger highlights after load if they were set before load.
await DeltaDecorationsHelperAsync(Decorations.ToArray());
}
// Now we're done loading
Loading?.Invoke(this, new RoutedEventArgs());
}
private void WebView_NewWindowRequested(WebView sender, WebViewNewWindowRequestedEventArgs args)
{
// TODO: Should probably create own event args here as we don't want to expose the referrer to our internal page?
OpenLinkRequested?.Invoke(sender, args);
}
private async void RequestedTheme_PropertyChanged(DependencyObject obj, DependencyProperty property)
{
var editor = obj as CodeEditor;
var theme = editor.RequestedTheme;
var tstr = string.Empty;
if (theme == ElementTheme.Default)
{
tstr = _themeListener.CurrentThemeName;
}
else
{
tstr = theme.ToString();
}
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
await this.InvokeScriptAsync("changeTheme", new string[] { tstr, _themeListener.IsHighContrast.ToString() });
});
}
private async void _themeListener_ThemeChanged(ThemeListener sender)
{
if (RequestedTheme == ElementTheme.Default)
{
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
await this.InvokeScriptAsync("changeTheme", args: new string[] { sender.CurrentTheme.ToString(), sender.IsHighContrast.ToString() });
});
}
}
internal bool TriggerKeyDown(WebKeyEventArgs args)
{
this.KeyDown?.Invoke(this, args);
return args.Handled;
}
protected override void OnGotFocus(RoutedEventArgs e)
{
base.OnGotFocus(e);
if (this._view != null && FocusManager.GetFocusedElement() == this)
{
// Forward Focus onto our inner WebView
this._view.Focus(FocusState.Programmatic);
}
}
}
}

178
MonacoEditorComponent/CodeEditor.Methods.cs

@ -0,0 +1,178 @@
using Monaco.Editor;
using Monaco.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Data.Json;
using Windows.Foundation;
namespace Monaco
{
/// <summary>
/// Action delegate for <see cref="CodeEditor.AddCommandAsync(int, CommandHandler)"/> and <see cref="CodeEditor.AddCommandAsync(int, CommandHandler, string)"/>.
/// </summary>
public delegate void CommandHandler();
/// <summary>
/// This file contains Monaco IEditor method implementations we can call on our control.
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditor.html
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.icommoncodeeditor.html
/// </summary>
#pragma warning disable CS1591
public partial class CodeEditor
{
#region Reveal Methods
public IAsyncAction RevealLineAsync(uint lineNumber)
{
return SendScriptAsync("editor.revealLine(" + lineNumber + ")").AsAsyncAction();
}
public IAsyncAction RevealLineInCenterAsync(uint lineNumber)
{
return SendScriptAsync("editor.revealLineInCenter(" + lineNumber + ")").AsAsyncAction();
}
public IAsyncAction RevealLineInCenterIfOutsideViewportAsync(uint lineNumber)
{
return SendScriptAsync("editor.revealLineInCenterIfOutsideViewport(" + lineNumber + ")").AsAsyncAction();
}
public IAsyncAction RevealLinesAsync(uint startLineNumber, uint endLineNumber)
{
return SendScriptAsync("editor.revealLines(" + startLineNumber + ", " + endLineNumber + ")").AsAsyncAction();
}
public IAsyncAction RevealLinesInCenterAsync(uint startLineNumber, uint endLineNumber)
{
return SendScriptAsync("editor.revealLinesInCenter(" + startLineNumber + ", " + endLineNumber + ")").AsAsyncAction();
}
public IAsyncAction RevealLinesInCenterIfOutsideViewportAsync(uint startLineNumber, uint endLineNumber)
{
return SendScriptAsync("editor.revealLinesInCenterIfOutsideViewport(" + startLineNumber + ", " + endLineNumber + ")").AsAsyncAction();
}
public IAsyncAction RevealPositionAsync(IPosition position)
{
return RevealPositionAsync(position, false, false);
}
public IAsyncAction RevealPositionAsync(IPosition position, bool revealVerticalInCenter)
{
return RevealPositionAsync(position, revealVerticalInCenter, false);
}
public IAsyncAction RevealPositionAsync(IPosition position, bool revealVerticalInCenter, bool revealHorizontal)
{
return SendScriptAsync("editor.revealPosition(JSON.parse('" + position.ToJson() + "'), " + JsonConvert.ToString(revealVerticalInCenter) + ", " + JsonConvert.ToString(revealHorizontal) + ")").AsAsyncAction();
}
public IAsyncAction RevealPositionInCenterAsync(IPosition position)
{
return SendScriptAsync("editor.revealPositionInCenter(JSON.parse('" + position.ToJson() + "'))").AsAsyncAction();
}
public IAsyncAction RevealPositionInCenterIfOutsideViewportAsync(IPosition position)
{
return SendScriptAsync("editor.revealPositionInCenterIfOutsideViewport(JSON.parse('" + position.ToJson() + "'))").AsAsyncAction();
}
public IAsyncAction RevealRangeAsync(IRange range)
{
return SendScriptAsync("editor.revealRange(JSON.parse('" + range.ToJson() + "'))").AsAsyncAction();
}
public IAsyncAction RevealRangeAtTopAsync(IRange range)
{
return SendScriptAsync("editor.revealRangeAtTop(JSON.parse('" + range.ToJson() + "'))").AsAsyncAction();
}
public IAsyncAction RevealRangeInCenterAsync(IRange range)
{
return SendScriptAsync("editor.revealRangeInCenter(JSON.parse('" + range.ToJson() + "'))").AsAsyncAction();
}
public IAsyncAction RevealRangeInCenterIfOutsideViewportAsync(IRange range)
{
return SendScriptAsync("editor.revealRangeInCenterIfOutsideViewport(JSON.parse('" + range.ToJson() + "'))").AsAsyncAction();
}
#endregion
public IAsyncAction AddActionAsync(IActionDescriptor action)
{
var wref = new WeakReference<CodeEditor>(this);
_parentAccessor.RegisterAction("Action" + action.Id, new Action(() => { if (wref.TryGetTarget(out CodeEditor editor)) { action?.Run(editor); }}));
return InvokeScriptAsync("addAction", action).AsAsyncAction();
}
public IAsyncOperation<string> AddCommandAsync(int keybinding, CommandHandler handler)
{
return AddCommandAsync(keybinding, handler, string.Empty);
}
public IAsyncOperation<string> AddCommandAsync(int keybinding, CommandHandler handler, string context)
{
var name = "Command" + keybinding;
_parentAccessor.RegisterAction(name, new Action(() => { handler?.Invoke(); }));
return InvokeScriptAsync<string>("addCommand", new object[] { keybinding, name, context }).AsAsyncOperation();
}
public IAsyncOperation<ContextKey> CreateContextKeyAsync(string key, bool defaultValue)
{
var ck = new ContextKey(this, key, defaultValue);
return InvokeScriptAsync("createContext", ck).ContinueWith((noop) =>
{
return ck;
}).AsAsyncOperation();
}
public IModel GetModel()
{
return _model;
}
public IAsyncOperation<IEnumerable<Marker>> GetModelMarkersAsync() // TODO: Filter (string? owner, Uri? resource, int? take)
{
return SendScriptAsync<IEnumerable<Marker>>("monaco.editor.getModelMarkers();").AsAsyncOperation();
}
public IAsyncAction SetModelMarkersAsync(string owner, [ReadOnlyArray] IMarkerData[] markers)
{
return SendScriptAsync("monaco.editor.setModelMarkers(model, " + JsonConvert.ToString(owner) + ", " + JsonConvert.SerializeObject(markers) + ");").AsAsyncAction();
}
public IAsyncOperation<Position> GetPositionAsync()
{
return SendScriptAsync<Position>("editor.getPosition();").AsAsyncOperation();
}
public IAsyncAction SetPositionAsync(IPosition position)
{
return SendScriptAsync("editor.setPosition(" + JsonConvert.SerializeObject(position) + ");").AsAsyncAction();
}
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.icommoncodeeditor.html#deltadecorations
///
/// Using <see cref="Decorations"/> Property to manipulate decorations instead of calling this directly.
/// </summary>
/// <param name="newDecorations"></param>
/// <returns></returns>
private IAsyncAction DeltaDecorationsHelperAsync([ReadOnlyArray] IModelDeltaDecoration[] newDecorations)
{
var newDecorationsAdjust = newDecorations ?? Array.Empty<IModelDeltaDecoration>();
// Update Styles
return InvokeScriptAsync("updateStyle", CssStyleBroker.Instance.GetStyles()).ContinueWith((noop) =>
{
// Send Command to Modify Decorations
// IMPORTANT: Need to cast to object here as we want this to be a single array object passed as a parameter, not a list of parameters to expand.
return InvokeScriptAsync("updateDecorations", (object)newDecorationsAdjust);
}).AsAsyncAction();
}
}
#pragma warning restore CS1591
}

311
MonacoEditorComponent/CodeEditor.Properties.cs

@ -0,0 +1,311 @@
using Monaco.Editor;
using Monaco.Helpers;
using Nito.AsyncEx;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
namespace Monaco
{
partial class CodeEditor : IParentAccessorAcceptor
{
public bool IsSettingValue { get; set; }
/// <summary>
/// Get or Set the CodeEditor Text.
/// </summary>
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for HorizontalLayout. This enables animation, styling, binding, etc...
private static readonly DependencyProperty TextPropertyField =
DependencyProperty.Register("Text", typeof(string), typeof(CodeEditor), new PropertyMetadata(string.Empty, (d, e) => {
if (!(d as CodeEditor).IsSettingValue)
{
(d as CodeEditor)?.InvokeScriptAsync("updateContent", e.NewValue.ToString());
}
}));
public static DependencyProperty TextProperty
{
get
{
return TextPropertyField;
}
}
/// <summary>
/// Get the current Primary Selected CodeEditor Text.
/// </summary>
public string SelectedText
{
get { return (string)GetValue(SelectedTextProperty); }
set { SetValue(SelectedTextProperty, value); }
}
// Using a DependencyProperty as the backing store for HorizontalLayout. This enables animation, styling, binding, etc...
private static readonly DependencyProperty SelectedTextPropertyField =
DependencyProperty.Register(nameof(SelectedText), typeof(string), typeof(CodeEditor), new PropertyMetadata(string.Empty, (d, e) => {
if (!(d as CodeEditor).IsSettingValue)
{
(d as CodeEditor)?.InvokeScriptAsync("updateSelectedContent", e.NewValue.ToString());
}
}));
public static DependencyProperty SelectedTextProperty
{
get
{
return SelectedTextPropertyField;
}
}
public Selection SelectedRange
{
get { return (Selection)GetValue(SelectedRangeProperty); }
set { SetValue(SelectedRangeProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedRange. This enables animation, styling, binding, etc...
private static readonly DependencyProperty SelectedRangePropertyField =
DependencyProperty.Register(nameof(SelectedRange), typeof(Selection), typeof(CodeEditor), new PropertyMetadata(null));
public static DependencyProperty SelectedRangeProperty
{
get
{
return SelectedRangePropertyField;
}
}
/// <summary>
/// Set the Syntax Language for the Code CodeEditor.
///
/// Note: Most likely to change or move location.
/// </summary>
public string CodeLanguage
{
get { return (string)GetValue(CodeLanguageProperty); }
set { SetValue(CodeLanguageProperty, value); }
}
// Using a DependencyProperty as the backing store for HorizontalLayout. This enables animation, styling, binding, etc...
private static readonly DependencyProperty CodeLanguagePropertyField =
DependencyProperty.Register("CodeLanguage", typeof(string), typeof(CodeEditor), new PropertyMetadata("xml", (d, e) => {
var editor = d as CodeEditor;
if (editor.Options != null)
{
// Will trigger its own update of Options, but need this for initialization changes.
editor.Options.Language = e.NewValue.ToString();
}
// TODO: Push this to Options property change check instead...
// Changes to Language are ignored in Updated Options.
// https://microsoft.github.io/monaco-editor/api/modules/monaco.editor.html#setmodellanguage.
(d as CodeEditor)?.InvokeScriptAsync("updateLanguage", e.NewValue.ToString());
}));
internal static DependencyProperty CodeLanguageProperty
{
get
{
return CodeLanguagePropertyField;
}
}
/// <summary>
/// Get or set the CodeEditor Options.
/// </summary>
public IEditorConstructionOptions Options
{
get { return (IEditorConstructionOptions)GetValue(OptionsProperty); }
set { SetValue(OptionsProperty, value); }
}
// Using a DependencyProperty as the backing store for Options. This enables animation, styling, binding, etc...
private static readonly DependencyProperty OptionsPropertyField =
DependencyProperty.Register("Options", typeof(IEditorConstructionOptions), typeof(CodeEditor), new PropertyMetadata(new IEditorConstructionOptions(), (d, e) => {
var value = e.NewValue as IEditorConstructionOptions;
if (value != null)
{
var editor = d as CodeEditor;
if (editor != null)
{
editor.InvokeScriptAsync("updateOptions", value.ToJson());
// Register for sub-property changes on new object
value.PropertyChanged -= editor.Options_PropertyChanged;
value.PropertyChanged += editor.Options_PropertyChanged;
}
}
}));
public static DependencyProperty OptionsProperty
{
get
{
return OptionsPropertyField;
}
}
/// <summary>
/// Get or Set the CodeEditor Text.
/// </summary>
public bool HasGlyphMargin
{
get { return (bool)GetValue(HasGlyphMarginProperty); }
set { SetValue(HasGlyphMarginProperty, value); }
}
// Using a DependencyProperty as the backing store for HorizontalLayout. This enables animation, styling, binding, etc...
private static readonly DependencyProperty HasGlyphMarginPropertyField =
DependencyProperty.Register("HasGlyphMargin", typeof(bool), typeof(CodeEditor), new PropertyMetadata(false, (d, e) => {
(d as CodeEditor).Options.GlyphMargin = e.NewValue as bool?;
}));
public static DependencyProperty HasGlyphMarginProperty
{
get
{
return HasGlyphMarginPropertyField;
}
}
/// <summary>
/// Gets or sets text Decorations.
/// </summary>
public IObservableVector<IModelDeltaDecoration> Decorations
{
get { return (IObservableVector<IModelDeltaDecoration>)GetValue(DecorationsProperty); }
set { SetValue(DecorationsProperty, value); }
}
private AsyncLock _mutexLineDecorations = new AsyncLock();
// Using a DependencyProperty as the backing store for Options. This enables animation, styling, binding, etc...
private static readonly DependencyProperty DecorationsPropertyField =
DependencyProperty.Register("Decorations", typeof(IModelDeltaDecoration), typeof(CodeEditor), new PropertyMetadata(null, async (d, e) => {
var editor = d as CodeEditor;
if (editor != null)
{
// We only want to do this one at a time per editor.
using (await editor._mutexLineDecorations.LockAsync())
{
var old = e.OldValue as IObservableVector<IModelDeltaDecoration>;
// Clear out the old line decorations if we're replacing them or setting back to null
if ((old != null && old.Count > 0) ||
e.NewValue == null)
{
await editor.DeltaDecorationsHelperAsync(null);
}
var value = e.NewValue as IObservableVector<IModelDeltaDecoration>;
if (value != null)
{
if (value.Count > 0)
{
await editor.DeltaDecorationsHelperAsync(value.ToArray());
}
value.VectorChanged -= editor.Decorations_VectorChanged;
value.VectorChanged += editor.Decorations_VectorChanged;
}
}
}
}));
private async void Decorations_VectorChanged(IObservableVector<IModelDeltaDecoration> sender, IVectorChangedEventArgs @event)
{
if (sender != null)
{
// Need to recall mutex as this is called from outside of this initial callback setting it up.
using (await _mutexLineDecorations.LockAsync())
{
await DeltaDecorationsHelperAsync(sender.ToArray());
}
}
}
public static DependencyProperty DecorationsProperty
{
get
{
return DecorationsPropertyField;
}
}
/// <summary>
/// Gets or sets the hint Markers.
/// Note: This property is a helper for <see cref="SetModelMarkersAsync(string, IMarkerData[])"/>; use this property or the method, not both.
/// </summary>
public IObservableVector<IMarkerData> Markers
{
get { return (IObservableVector<IMarkerData>)GetValue(MarkersProperty); }
set { SetValue(MarkersProperty, value); }
}
private AsyncLock _mutexMarkers = new AsyncLock();
// Using a DependencyProperty as the backing store for Options. This enables animation, styling, binding, etc...
private static readonly DependencyProperty MarkersPropertyField =
DependencyProperty.Register("Markers", typeof(IMarkerData), typeof(CodeEditor), new PropertyMetadata(null, async (d, e) => {
var editor = d as CodeEditor;
if (editor != null)
{
// We only want to do this one at a time per editor.
using (await editor._mutexMarkers.LockAsync())
{
var old = e.OldValue as IObservableVector<IMarkerData>;
// Clear out the old markers if we're replacing them or setting back to null
if ((old != null && old.Count > 0) ||
e.NewValue == null)
{
// TODO: Can I simplify this in this case?
await editor.SetModelMarkersAsync("CodeEditor", Array.Empty<IMarkerData>());
}
var value = e.NewValue as IObservableVector<IMarkerData>;
if (value != null)
{
if (value.Count > 0)
{
await editor.SetModelMarkersAsync("CodeEditor", value.ToArray());
}
value.VectorChanged -= editor.Markers_VectorChanged;
value.VectorChanged += editor.Markers_VectorChanged;
}
}
}
}));
private async void Markers_VectorChanged(IObservableVector<IMarkerData> sender, IVectorChangedEventArgs @event)
{
if (sender != null)
{
// Need to recall mutex as this is called from outside of this initial callback setting it up.
using (await _mutexMarkers.LockAsync())
{
await SetModelMarkersAsync("CodeEditor", sender.ToArray());
}
}
}
public static DependencyProperty MarkersProperty
{
get
{
return MarkersPropertyField;
}
}
}
}

279
MonacoEditorComponent/CodeEditor.cs

@ -0,0 +1,279 @@
using Collections.Generic;
using Monaco.Editor;
using Monaco.Extensions;
using Monaco.Helpers;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Templated Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234235
namespace Monaco
{
/// <summary>
/// UWP Windows Runtime Component wrapper for the Monaco CodeEditor
/// https://microsoft.github.io/monaco-editor/
/// </summary>
[TemplatePart(Name = "View", Type = typeof(WebView))]
public sealed partial class CodeEditor : Control, INotifyPropertyChanged
{
private bool _initialized;
private WebView _view;
private ModelHelper _model;
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Template Property used during loading to prevent blank control visibility when it's still loading WebView.
/// </summary>
public bool IsLoaded
{
get { return (bool)GetValue(IsLoadedProperty); }
private set { SetValue(IsLoadedProperty, value); }
}
// Using a DependencyProperty as the backing store for HorizontalLayout. This enables animation, styling, binding, etc...
private static readonly DependencyProperty IsLoadedPropertyField =
DependencyProperty.Register("IsLoaded", typeof(string), typeof(CodeEditor), new PropertyMetadata(false));
public static DependencyProperty IsLoadedProperty
{
get
{
return IsLoadedPropertyField;
}
}
/// <summary>
/// Construct a new IStandAloneCodeEditor.
/// </summary>
public CodeEditor()
{
DefaultStyleKey = typeof(CodeEditor);
if (Options != null)
{
// Set Pass-Thru Properties
Options.GlyphMargin = HasGlyphMargin;
Options.Language = CodeLanguage;
// Register for changes
Options.PropertyChanged += Options_PropertyChanged;
}
// Initialize this here so property changed event will fire and register collection changed event.
Decorations = new ObservableVector<IModelDeltaDecoration>();
Markers = new ObservableVector<IMarkerData>();
_model = new ModelHelper(this);
base.Loaded += CodeEditor_Loaded;
Unloaded += CodeEditor_Unloaded;
}
private async void Options_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// TODO: Check for Language property and call other method instead?
await InvokeScriptAsync("updateOptions", sender);
}
private void CodeEditor_Loaded(object sender, RoutedEventArgs e)
{
// Do this the 2nd time around.
if (_model == null && _view != null)
{
_model = new ModelHelper(this);
_parentAccessor = new ParentAccessor(this);
_parentAccessor.AddAssemblyForTypeLookup(typeof(Range).GetTypeInfo().Assembly);
_parentAccessor.RegisterAction("Loaded", CodeEditorLoaded);
_themeListener = new ThemeListener();
_themeListener.ThemeChanged += _themeListener_ThemeChanged;
_themeToken = RegisterPropertyChangedCallback(RequestedThemeProperty, RequestedTheme_PropertyChanged);
_keyboardListener = new KeyboardListener(this);
_view.AddWebAllowedObject("Parent", _parentAccessor);
_view.AddWebAllowedObject("Theme", _themeListener);
_view.AddWebAllowedObject("Keyboard", _keyboardListener);
Options.PropertyChanged += Options_PropertyChanged;
Decorations.VectorChanged += Decorations_VectorChanged;
Markers.VectorChanged += Markers_VectorChanged;
_view.NewWindowRequested += WebView_NewWindowRequested;
_initialized = true;
Loading?.Invoke(this, new RoutedEventArgs());
Unloaded += CodeEditor_Unloaded;
Loaded?.Invoke(this, new RoutedEventArgs());
}
}
private void CodeEditor_Unloaded(object sender, RoutedEventArgs e)
{
Unloaded -= CodeEditor_Unloaded;
if (_view != null)
{
_view.NavigationStarting -= WebView_NavigationStarting;
_view.DOMContentLoaded -= WebView_DOMContentLoaded;
_view.NavigationCompleted -= WebView_NavigationCompleted;
_view.NewWindowRequested -= WebView_NewWindowRequested;
_initialized = false;
}
Decorations.VectorChanged -= Decorations_VectorChanged;
Markers.VectorChanged -= Markers_VectorChanged;
_parentAccessor?.Dispose();
_parentAccessor = null;
Options.PropertyChanged -= Options_PropertyChanged;
_themeListener.ThemeChanged -= _themeListener_ThemeChanged;
_themeListener = null;
UnregisterPropertyChangedCallback(RequestedThemeProperty, _themeToken);
_keyboardListener = null;
_model = null;
}
protected override void OnApplyTemplate()
{
if (_view != null)
{
_view.NavigationStarting -= WebView_NavigationStarting;
_view.DOMContentLoaded -= WebView_DOMContentLoaded;
_view.NavigationCompleted -= WebView_NavigationCompleted;
_view.NewWindowRequested -= WebView_NewWindowRequested;
_initialized = false;
}
_view = (WebView)GetTemplateChild("View");
if (_view != null)
{
_view.NavigationStarting += WebView_NavigationStarting;
_view.DOMContentLoaded += WebView_DOMContentLoaded;
_view.NavigationCompleted += WebView_NavigationCompleted;
_view.NewWindowRequested += WebView_NewWindowRequested;
_view.Source = new Uri("ms-appx-web:///Monaco/MonacoEditor.html");
}
base.OnApplyTemplate();
}
internal async Task SendScriptAsync(string script,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
await SendScriptAsync<object>(script, member, file, line);
}
internal async Task<T> SendScriptAsync<T>(string script,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
if (_initialized)
{
try
{
return await this._view.RunScriptAsync<T>(script, member, file, line);
}
catch (Exception e)
{
InternalException?.Invoke(this, e);
}
}
else
{
#if DEBUG
Debug.WriteLine("WARNING: Tried to call '" + script + "' before initialized.");
#endif
}
return default(T);
}
internal async Task InvokeScriptAsync(
string method,
object arg,
bool serialize = true,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
await this.InvokeScriptAsync<object>(method, new object[] { arg }, serialize, member, file, line);
}
internal async Task InvokeScriptAsync(
string method,
object[] args,
bool serialize = true,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
await this.InvokeScriptAsync<object>(method, args, serialize, member, file, line);
}
internal async Task<T> InvokeScriptAsync<T>(
string method,
object arg,
bool serialize = true,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
return await this.InvokeScriptAsync<T>(method, new object[] { arg }, serialize, member, file, line);
}
internal async Task<T> InvokeScriptAsync<T>(
string method,
object[] args,
bool serialize = true,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
if (_initialized)
{
try
{
return await this._view.InvokeScriptAsync<T>(method, args, serialize, member, file, line);
}
catch (Exception e)
{
InternalException?.Invoke(this, e);
}
}
else
{
#if DEBUG
Debug.WriteLine("WARNING: Tried to call " + method + " before initialized.");
#endif
}
return default(T);
}
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}

206
MonacoEditorComponent/Extensions/WebViewExtensions.cs

@ -0,0 +1,206 @@
using Monaco.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.UI.Xaml.Controls;
namespace Monaco.Extensions
{
internal static class WebViewExtensions
{
public static async Task RunScriptAsync(
this WebView _view,
string script,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
await _view.RunScriptAsync<object>(script, member, file, line);
}
public static async Task<T> RunScriptAsync<T>(
this WebView _view,
string script,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
var start = "try {\n";
if (typeof(T) != typeof(object))
{
script = script.Trim(';');
start += "JSON.stringify(" + script + ");";
}
else
{
start += script;
}
var fullscript = start +
"\n} catch (err) { JSON.stringify({ wv_internal_error: true, message: err.message, description: err.description, number: err.number, stack: err.stack }); }";
if (_view.Dispatcher.HasThreadAccess)
{
try
{
return await RunScriptHelperAsync<T>(_view, fullscript);
}
catch (Exception e)
{
throw new JavaScriptExecutionException(member, file, line, script, e);
}
}
else
{
return await _view.Dispatcher.RunTaskAsync(async () =>
{
try
{
return await RunScriptHelperAsync<T>(_view, fullscript);
}
catch (Exception e)
{
throw new JavaScriptExecutionException(member, file, line, script, e);
}
});
}
}
private static async Task<T> RunScriptHelperAsync<T>(WebView _view, string script)
{
var returnstring = await _view.InvokeScriptAsync("eval", new string[] { script });
if (JsonObject.TryParse(returnstring, out JsonObject result))
{
if (result.ContainsKey("wv_internal_error") && result["wv_internal_error"].ValueType == JsonValueType.Boolean && result["wv_internal_error"].GetBoolean())
{
throw new JavaScriptInnerException(result["message"].GetString(), result["stack"].GetString());
}
}
if (returnstring != null && returnstring != "null")
{
return JsonConvert.DeserializeObject<T>(returnstring);
}
return default(T);
}
private static JsonSerializerSettings _settings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
public static async Task InvokeScriptAsync(
this WebView _view,
string method,
object arg,
bool serialize = true,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
await _view.InvokeScriptAsync<object>(method, arg, serialize, member, file, line);
}
public static async Task InvokeScriptAsync(
this WebView _view,
string method,
object[] args,
bool serialize = true,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
await _view.InvokeScriptAsync<object>(method, args, serialize, member, file, line);
}
public static async Task<T> InvokeScriptAsync<T>(
this WebView _view,
string method,
object arg,
bool serialize = true,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
return await _view.InvokeScriptAsync<T>(method, new object[] { arg }, serialize, member, file, line);
}
public static async Task<T> InvokeScriptAsync<T>(
this WebView _view,
string method,
object[] args,
bool serialize = true,
[CallerMemberName] string member = null,
[CallerFilePath] string file = null,
[CallerLineNumber] int line = 0)
{
string[] sanitizedargs;
if (serialize)
{
sanitizedargs = args.Select(item =>
{
if (item is int || item is double)
{
return item.ToString();
}
else if (item is string)
{
return JsonConvert.ToString(item);
}
else
{
// TODO: Need JSON.parse?
return JsonConvert.SerializeObject(item, _settings);
}
}).ToArray();
}
else
{
sanitizedargs = args.Select(item => item.ToString()).ToArray();
}
var script = method + "(" + string.Join(",", sanitizedargs) + ");";
return await RunScriptAsync<T>(_view, script, member, file, line);
}
}
internal sealed class JavaScriptExecutionException : Exception
{
public string Script { get; private set; }
public string Member { get; private set; }
public string FileName { get; private set; }
public int LineNumber { get; private set; }
public JavaScriptExecutionException(string member, string filename, int line, string script, Exception inner)
: base("Error Executing JavaScript Code for " + member + "\nLine " + line + " of " + filename + "\n" + script + "\n", inner)
{
this.Member = member;
this.FileName = filename;
this.LineNumber = line;
this.Script = script;
}
}
internal sealed class JavaScriptInnerException : Exception
{
public string JavaScriptStackTrace { get; private set; } // TODO Use Enum of JS error types https://www.w3schools.com/js/js_errors.asp
public JavaScriptInnerException(string message, string stack)
: base(message)
{
this.JavaScriptStackTrace = stack;
}
}
}

16
MonacoEditorComponent/Helpers/DebugLogger.cs

@ -0,0 +1,16 @@
using System.Diagnostics;
using Windows.Foundation.Metadata;
namespace Monaco.Helpers
{
[AllowForWeb]
public sealed class DebugLogger
{
public void Log(string message)
{
#if DEBUG
Debug.WriteLine(message);
#endif
}
}
}

35
MonacoEditorComponent/Helpers/DispatcherTaskExtensions.cs

@ -0,0 +1,35 @@
namespace Monaco.Helpers
{
using System;
using System.Threading.Tasks;
using Windows.UI.Core;
/// <summary>
/// https://github.com/Microsoft/Windows-task-snippets/blob/master/tasks/UI-thread-task-await-from-background-thread.md
/// </summary>
internal static class DispatcherTaskExtensions
{
internal static async Task<T> RunTaskAsync<T>(this CoreDispatcher dispatcher,
Func<Task<T>> func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
{
var taskCompletionSource = new TaskCompletionSource<T>();
await dispatcher.RunAsync(priority, async () =>
{
try
{
taskCompletionSource.SetResult(await func());
}
catch (Exception ex)
{
taskCompletionSource.SetException(ex);
}
});
return await taskCompletionSource.Task;
}
// There is no TaskCompletionSource<void> so we use a bool that we throw away.
internal static async Task RunTaskAsync(this CoreDispatcher dispatcher,
Func<Task> func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal) =>
await RunTaskAsync(dispatcher, async () => { await func(); return false; }, priority);
}
}

35
MonacoEditorComponent/Helpers/InterfaceToClassConverter.cs

@ -0,0 +1,35 @@
using Newtonsoft.Json;
using System;
using System.Reflection;
namespace Monaco.Helpers
{
/// <summary>
/// Used to upcast an interface to its object type during deserialization of JSON.
/// </summary>
/// <typeparam name="TInterface">Type of base Interface.</typeparam>
/// <typeparam name="TClass">Type of class to use for deserializing object with interface.</typeparam>
internal class InterfaceToClassConverter<TInterface, TClass> : JsonConverter where TClass : TInterface, new()
{
public override bool CanConvert(Type objectType)
{
// We only want to convert objects that are of the interface.
return objectType == typeof(TInterface);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Use the implementation type for the deserialization of the interface.
var pop = new TClass();
serializer.Populate(reader, pop);
return pop;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
}

64
MonacoEditorComponent/Helpers/KeyboardListener.cs

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation.Metadata;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace Monaco.Helpers
{
public delegate void WebKeyEventHandler(CodeEditor sender, WebKeyEventArgs args);
public sealed class WebKeyEventArgs
{
public int KeyCode { get; set; }
// TODO: Make these some sort of flagged state enum?
public bool CtrlKey { get; set; }
public bool ShiftKey { get; set; }
public bool AltKey { get; set; }
public bool MetaKey { get; set; }
public bool Handled { get; set; }
}
[AllowForWeb]
public sealed class KeyboardListener
{
private WeakReference<CodeEditor> parent;
public KeyboardListener(CodeEditor parent) // TODO: Make Interface for event usage
{
this.parent = new WeakReference<CodeEditor>(parent);
}
/// <summary>
/// Called from JavaScript, returns if event was handled or not.
/// </summary>
/// <param name="keycode"></param>
/// <param name="ctrl"></param>
/// <param name="shift"></param>
/// <param name="alt"></param>
/// <param name="meta"></param>
/// <returns></returns>
public bool KeyDown(int keycode, bool ctrl, bool shift, bool alt, bool meta)
{
if (parent.TryGetTarget(out CodeEditor editor))
{
return editor.TriggerKeyDown(new WebKeyEventArgs()
{
KeyCode = keycode, // TODO: Convert to a virtual key or something?
CtrlKey = ctrl,
ShiftKey = shift,
AltKey = alt,
MetaKey = meta
});
}
return false;
}
}
}

247
MonacoEditorComponent/Helpers/ParentAccessor.cs

@ -0,0 +1,247 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Metadata;
namespace Monaco.Helpers
{
/// <summary>
/// Class to aid in accessing WinRT values from JavaScript.
/// Not Thread Safe.
/// </summary>
[AllowForWeb]
public sealed class ParentAccessor : IDisposable
{
private WeakReference<IParentAccessorAcceptor> parent;
private Type typeinfo;
private Dictionary<string, Action> actions;
private Dictionary<string, Func<string[], Task<string>>> events;
private List<Assembly> Assemblies { get; set; } = new List<Assembly>();
/// <summary>
/// Constructs a new reflective parent Accessor for the provided object.
/// </summary>
/// <param name="parent">Object to provide Property Access.</param>
public ParentAccessor(IParentAccessorAcceptor parent)
{
this.parent = new WeakReference<IParentAccessorAcceptor>(parent);
typeinfo = parent.GetType();
actions = new Dictionary<string, Action>();
events = new Dictionary<string, Func<string[], Task<string>>>();
}
/// <summary>
/// Registers an action from the .NET side which can be called from within the JavaScript code.
/// </summary>
/// <param name="name">String Key.</param>
/// <param name="action">Action to perform.</param>
internal void RegisterAction(string name, Action action)
{
actions[name] = action;
}
/// <summary>
/// Registers an event from the .NET side which can be called with the given jsonified string arguments within the JavaScript code.
/// </summary>
/// <param name="name">String Key.</param>
/// <param name="function">Event to call.</param>
internal void RegisterEvent(string name, Func<string[], Task<string>> function)
{
events[name] = function;
}
/// <summary>
/// Calls an Event registered before wit hthe <see cref="RegisterEvent(string, Func{string[], string})"/>.
/// </summary>
/// <param name="name">Name of event to call.</param>
/// <param name="parameters">JSON string Parameters.</param>
/// <returns></returns>
public IAsyncOperation<string> CallEvent(string name, [ReadOnlyArray] string[] parameters)
{
if (events.ContainsKey(name))
{
return events[name]?.Invoke(parameters).AsAsyncOperation();
}
return (new Task<string>(() => { return null; })).AsAsyncOperation();
}
/// <summary>
/// Adds an Assembly to use for looking up types by name for <see cref="SetValue(string, string, string)"/>.
/// </summary>
/// <param name="assembly">Assembly to add.</param>
internal void AddAssemblyForTypeLookup(Assembly assembly)
{
Assemblies.Add(assembly);
}
/// <summary>
/// Calls an Action registered before with <see cref="RegisterAction(string, Action)"/>.
/// </summary>
/// <param name="name">String Key.</param>
/// <returns>True if method was found in registration.</returns>
public bool CallAction(string name)
{
if (actions.ContainsKey(name))
{
actions[name]?.Invoke();
return true;
}
return false;
}
/// <summary>
/// Returns the winrt primative object value for the specified Property.
/// </summary>
/// <param name="name">Property name on Parent Object.</param>
/// <returns>Property Value or null.</returns>
public object GetValue(string name)
{
if (parent.TryGetTarget(out IParentAccessorAcceptor tobj))
{
var propinfo = typeinfo.GetProperty(name);
return propinfo?.GetValue(tobj);
}
return null;
}
public string GetJsonValue(string name)
{
if (parent.TryGetTarget(out IParentAccessorAcceptor tobj))
{
var propinfo = typeinfo.GetProperty(name);
var obj = propinfo?.GetValue(tobj);
return JsonConvert.SerializeObject(obj, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
});
}
return "{}";
}
/// <summary>
/// Returns the winrt primative object value for a child property off of the specified Property.
///
/// Useful for providing complex types to users of Parent but still access primatives in JavaScript.
/// </summary>
/// <param name="name">Parent Property name.</param>
/// <param name="child">Property's Property name to retrieve.</param>
/// <returns>Value of Child Property or null.</returns>
public object GetChildValue(string name, string child)
{
if (parent.TryGetTarget(out IParentAccessorAcceptor tobj))
{
// TODO: Support params for multi-level digging?
var propinfo = typeinfo.GetProperty(name);
var prop = propinfo?.GetValue(tobj);
if (prop != null)
{
var childinfo = prop.GetType().GetProperty(child);
return childinfo?.GetValue(prop);
}
}
return null;
}
/// <summary>
/// Sets the value for the specified Property.
/// </summary>
/// <param name="name">Parent Property name.</param>
/// <param name="value">Value to set.</param>
public void SetValue(string name, object value)
{
if (parent.TryGetTarget(out IParentAccessorAcceptor tobj))
{
var propinfo = typeinfo.GetProperty(name); // TODO: Cache these?
tobj.IsSettingValue = true;
propinfo?.SetValue(tobj, value);
tobj.IsSettingValue = false;
}
}
/// <summary>
/// Sets the value for the specified Property after deserializing the value as the given type name.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="type"></param>
public void SetValue(string name, string value, string type)
{
if (parent.TryGetTarget(out IParentAccessorAcceptor tobj))
{
var propinfo = typeinfo.GetProperty(name);
var typeobj = LookForTypeByName(type);
var obj = JsonConvert.DeserializeObject(value, typeobj);
tobj.IsSettingValue = true;
propinfo?.SetValue(tobj, obj);
tobj.IsSettingValue = false;
}
}
private Type LookForTypeByName(string name)
{
// First search locally
var result = Type.GetType(name);
if (result != null)
{
return result;
}
// Search in Other Assemblies
foreach (var assembly in Assemblies)
{
foreach (var typeInfo in assembly.ExportedTypes)
{
if (typeInfo.Name == name)
{
return typeInfo;
}
}
}
return null;
}
public void Dispose()
{
if (actions != null)
{
actions.Clear();
}
actions = null;
if (events != null)
{
events.Clear();
}
events = null;
}
}
//// TODO: Find better approach than this. Issue #21.
/// <summary>
/// Interface used on objects to be accessed.
/// </summary>
public interface IParentAccessorAcceptor
{
/// <summary>
/// Property to tell object the value is being set by ParentAccessor.
/// </summary>
bool IsSettingValue { get; set; }
}
}

116
MonacoEditorComponent/Helpers/ThemeListener.cs

@ -0,0 +1,116 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Foundation.Metadata;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
namespace Monaco.Helpers
{
public delegate void ThemeChangedEvent(ThemeListener sender);
/// <summary>
/// Class which listens for changes to Application Theme or High Contrast Modes
/// and Signals an Event when they occur.
/// </summary>
[AllowForWeb]
public sealed class ThemeListener
{
public string CurrentThemeName { get { return this.CurrentTheme.ToString(); } } // For Web Retrieval
public ApplicationTheme CurrentTheme { get; set; }
public bool IsHighContrast { get; set; }
public event ThemeChangedEvent ThemeChanged;
private AccessibilitySettings _accessible = new AccessibilitySettings();
private UISettings _settings = new UISettings();
public ThemeListener()
{
CurrentTheme = Application.Current.RequestedTheme;
IsHighContrast = _accessible.HighContrast;
_accessible.HighContrastChanged += _accessible_HighContrastChanged;
_settings.ColorValuesChanged += _settings_ColorValuesChanged;
// Fallback in case either of the above fail, we'll check when we get activated next.
Window.Current.CoreWindow.Activated += CoreWindow_Activated;
}
~ThemeListener()
{
_accessible.HighContrastChanged -= _accessible_HighContrastChanged;
_settings.ColorValuesChanged -= _settings_ColorValuesChanged;
Window.Current.CoreWindow.Activated -= CoreWindow_Activated;
}
private void _accessible_HighContrastChanged(AccessibilitySettings sender, object args)
{
#if DEBUG
Debug.WriteLine("HighContrast Changed");
#endif
UpdateProperties();
}
// Note: This can get called multiple times during HighContrast switch, do we care?
private async void _settings_ColorValuesChanged(UISettings sender, object args)
{
// Getting called off thread, so we need to dispatch to request value.
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
// TODO: This doesn't stop the multiple calls if we're in our faked 'White' HighContrast Mode below.
if (CurrentTheme != Application.Current.RequestedTheme ||
IsHighContrast != _accessible.HighContrast)
{
#if DEBUG
Debug.WriteLine("Color Values Changed");
#endif
UpdateProperties();
}
});
}
private void CoreWindow_Activated(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.WindowActivatedEventArgs args)
{
if (CurrentTheme != Application.Current.RequestedTheme ||
IsHighContrast != _accessible.HighContrast)
{
#if DEBUG
Debug.WriteLine("CoreWindow Activated Changed");
#endif
UpdateProperties();
}
}
/// <summary>
/// Set our current properties and fire a change notification.
/// </summary>
private void UpdateProperties()
{
// TODO: Not sure if HighContrastScheme names are localized?
if (_accessible.HighContrast && _accessible.HighContrastScheme.IndexOf("white", StringComparison.OrdinalIgnoreCase) != -1)
{
// If our HighContrastScheme is ON & a lighter one, then we should remain in 'Light' theme mode for Monaco Themes Perspective
IsHighContrast = false;
CurrentTheme = ApplicationTheme.Light;
}
else
{
// Otherwise, we just set to what's in the system as we'd expect.
IsHighContrast = _accessible.HighContrast;
CurrentTheme = Application.Current.RequestedTheme;
}
ThemeChanged?.Invoke(this);
}
}
}

65
MonacoEditorComponent/Monaco/Editor/ContextKey.cs

@ -0,0 +1,65 @@
using Monaco.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Editor
{
#pragma warning disable CS1591
public sealed class ContextKey : IContextKey
{
[JsonIgnore]
private WeakReference<CodeEditor> _editor;
[JsonProperty("key")]
public string Key { get; private set; }
[JsonProperty("defaultValue")]
public bool DefaultValue { get; private set; }
[JsonProperty("value")]
public bool Value { get; private set; }
internal ContextKey(CodeEditor editor, string key, bool defaultValue)
{
_editor = new WeakReference<CodeEditor>(editor);
Key = key;
DefaultValue = defaultValue;
}
private async void UpdateValueAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
await editor.InvokeScriptAsync("updateContext", new object[] { Key, Value });
}
}
public bool Get()
{
return Value;
}
public void Reset()
{
Value = DefaultValue;
UpdateValueAsync();
}
public void Set(bool value)
{
Value = value;
UpdateValueAsync();
}
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
}
#pragma warning restore CS1591
}

57
MonacoEditorComponent/Monaco/Editor/IActionDescriptor.cs

@ -0,0 +1,57 @@
using System;
using Monaco.Helpers;
using Newtonsoft.Json;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.iactiondescriptor.html
/// https://microsoft.github.io/monaco-editor/playground.html#interacting-with-the-editor-adding-an-action-to-an-editor-instance
/// </summary>
#pragma warning disable CS1591
public interface IActionDescriptor
{
/**
* https://github.com/Microsoft/vscode/blob/master/src/vs/monaco.d.ts#L1907
* Control if the action should show up in the context menu and where.
* The context menu of the editor has these default:
* navigation - The navigation group comes first in all cases.
* 1_modification - This group comes next and contains commands that modify your code.
* 9_cutcopypaste - The last default group with the basic editing commands.
* You can also create your own group.
* Defaults to null (don't show in context menu).
*/
[JsonProperty("contextMenuGroupId", NullValueHandling = NullValueHandling.Ignore)]
string ContextMenuGroupId { get; }
[JsonProperty("contextMenuOrder", NullValueHandling = NullValueHandling.Ignore)]
float ContextMenuOrder { get; }
[JsonProperty("id")]
string Id { get; }
/// <summary>
/// <see cref="IContextKey"/>
/// </summary>
[JsonProperty("keybindingContext", NullValueHandling = NullValueHandling.Ignore)]
string KeybindingContext { get; }
/// <summary>
/// <see cref="Monaco.KeyMod"/>, <see cref="Monaco.KeyCode"/>, and <see cref="Monaco.KeyMod.Chord(int, int)"/>
/// </summary>
[JsonProperty("keybindings")]
int[] Keybindings { get; }
[JsonProperty("label")]
string Label { get; }
/// <summary>
/// <see cref="IContextKey"/>
/// </summary>
[JsonProperty("precondition", NullValueHandling = NullValueHandling.Ignore)]
string Precondition { get; }
void Run(CodeEditor editor);
}
#pragma warning restore CS1591
}

34
MonacoEditorComponent/Monaco/Editor/IContextKey.cs

@ -0,0 +1,34 @@
using Monaco.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.icontextkey.html
///
/// Supports bools only as Windows Runtime Type doesn't support generics.
/// </summary>
public interface IContextKey: IJsonable
{
/// <summary>
/// Get the current value of the key.
/// </summary>
/// <returns></returns>
bool Get();
/// <summary>
/// Resets the key to the default value.
/// </summary>
void Reset();
/// <summary>
/// Set the key to the specified value.
/// </summary>
/// <param name="value"></param>
void Set(bool value);
}
}

218
MonacoEditorComponent/Monaco/Editor/IEditorConstructionOptions.cs

@ -0,0 +1,218 @@
using Monaco.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditorconstructionoptions.html
/// </summary>
#pragma warning disable CS1591
public sealed class IEditorConstructionOptions : IEditorOptions, IJsonable, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[JsonProperty("acceptSuggestionOnCommitCharacter")]
public bool? AcceptSuggestionOnCommitCharacter { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("acceptSuggestionOnEnter")]
public string AcceptSuggestionOnEnter { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("accessibilitySupport")]
public string AccessibilitySupport { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("ariaLabel")]
public string AriaLabel { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("autoClosingBrackets")]
public bool? AutoClosingBrackets { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("codeLens")]
public bool? CodeLens { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("contextMenu")]
public bool? ContextMenu { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("cursorBlinking")]
public string CursorBlinking { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("cursorStyle")]
public string CursorStyle { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("disableLayerHinting")]
public bool? DisableLayerHinting { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("disableMonospaceOptimizations")]
public bool? DisableMonospaceOptimizations { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("dragAndDrop")]
public bool? DragAndDrop { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("emptySelectionClipboard")]
public bool? EmptySelectionClipboard { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("find")]
public IEditorFindOptions Find { get { return GetPropertyValue<IEditorFindOptions>(); } set { SetPropertyValue(value); } }
[JsonProperty("fixedOverflowWidgets")]
public bool? FixedOverflowWidgets { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("folding")]
public bool? Folding { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("fontFamily")]
public string FontFamily { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("fontLigatures")]
public bool? FontLigatures { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("fontSize")]
public uint? FontSize { get { return GetPropertyValue<uint?>(); } set { SetPropertyValue(value); } }
[JsonProperty("fontWeight")]
public string FontWeight { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("formatOnPaste")]
public bool? FormatOnPaste { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("glyphMargin")]
public bool? GlyphMargin { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("hideCursorInOverviewRuler")]
public bool? HideCursorInOverviewRuler { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("hover")]
public bool? Hover { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("iconsInSuggestions")]
public bool? IconsInSuggestions { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("letterSpacing")]
public int? LetterSpacing { get { return GetPropertyValue<int?>(); } set { SetPropertyValue(value); } }
[JsonProperty("lineDecorationsWidth")]
public int? LineDecorationsWidth { get { return GetPropertyValue<int?>(); } set { SetPropertyValue(value); } }
[JsonProperty("lineHeight")]
public int? LineHeight { get { return GetPropertyValue<int?>(); } set { SetPropertyValue(value); } }
[JsonProperty("lineNumbers")]
public string LineNumbers { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("lineNumbersMinChars")]
public int? LineNumbersMinChars { get { return GetPropertyValue<int?>(); } set { SetPropertyValue(value); } }
[JsonProperty("links")]
public bool? Links { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("matchBrackets")]
public bool? MatchBrackets { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("minimap")]
public IEditorMinimapOptions Minimap { get { return GetPropertyValue<IEditorMinimapOptions>(); } set { SetPropertyValue(value); } }
[JsonProperty("mouseWheelScrollSensitivity")]
public int? MouseWheelScrollSensitivity { get { return GetPropertyValue<int?>(); } set { SetPropertyValue(value); } }
[JsonProperty("mouseWheelZoom")]
public bool? MouseWheelZoom { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("multiCursorModifier")]
public string MultiCursorModifier { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("occurrencesHighlight")]
public bool? OccurrencesHighlight { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("overviewRulerBorder")]
public bool? OverviewRulerBorder { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("overviewRulerLanes")]
public uint? OverviewRulerLanes { get { return GetPropertyValue<uint?>(); } set { SetPropertyValue(value); } }
[JsonProperty("parameterHints")]
public bool? ParameterHints { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("quickSuggestions")]
public bool? QuickSuggestions { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("quickSuggestionsDelay")]
public uint? QuickSuggestionsDelay { get { return GetPropertyValue<uint?>(); } set { SetPropertyValue(value); } }
[JsonProperty("readOnly")]
public bool? ReadOnly { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("renderControlCharacters")]
public bool? RenderControlCharacters { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("renderIndentGuides")]
public bool? RenderIndentGuides { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("renderLineHighlight")]
public string RenderLineHighlight { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("renderWhitespace")]
public string RenderWhitespace { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("revealHorizontalRightPadding")]
public uint? RevealHorizontalRightPadding { get { return GetPropertyValue<uint?>(); } set { SetPropertyValue(value); } }
[JsonProperty("roundedSelection")]
public bool? RoundedSelection { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("rulers")]
public uint[] Rulers { get { return GetPropertyValue<uint[]>(); } set { SetPropertyValue(value); } }
[JsonProperty("scrollBeyondLastLine")]
public bool? ScrollBeyondLastLine { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("scrollbar")]
public IEditorScrollbarOptions Scrollbar { get { return GetPropertyValue<IEditorScrollbarOptions>(); } set { SetPropertyValue(value); } }
[JsonProperty("selectOnLineNumbers")]
public bool? SelectOnLineNumbers { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("selectionClipboard")]
public bool? SelectionClipboard { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("selectionHighlight")]
public bool? SelectionHighlight { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("showFoldingControls")]
public string ShowFoldingControls { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("snipperSuggestions")]
public string SnippetSuggestions { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("stopRenderingLineAfter")]
public int? StopRenderingLineAfter { get { return GetPropertyValue<int?>(); } set { SetPropertyValue(value); } }
[JsonProperty("suggestFontSize")]
public uint? SuggestFontSize { get { return GetPropertyValue<uint?>(); } set { SetPropertyValue(value); } }
[JsonProperty("suggestLineHeight")]
public int? SuggestLineHeight { get { return GetPropertyValue<int?>(); } set { SetPropertyValue(value); } }
[JsonProperty("suggestOnTriggerCharacters")]
public bool? SuggestOnTriggerCharacters { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("useTabStops")]
public bool? UseTabStops { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("wordBasedSuggestions")]
public bool? WordBasedSuggestions { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("wordSeparators")]
public string WordSeparators { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("wordWrap")]
public string WordWrap { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("wordWrapBreakAfterCharacters")]
public string WordWrapBreakAfterCharacters { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("wordWrapBeforeCharacters")]
public string WordWrapBreakBeforeCharacters { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("wordWrapObtrusiveCharacters")]
public string WordWrapBreakObtrusiveCharacters { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
[JsonProperty("wordWrapColumn")]
public uint? WordWrapColumn { get { return GetPropertyValue<uint?>(); } set { SetPropertyValue(value); } }
[JsonProperty("wordWrapMinified")]
public bool? WordWrapMinified { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } }
[JsonProperty("wrappingIndent")]
public string WrappingIndent { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
// Construction Specific Properties Below
// --------------------------------------
[JsonProperty("autoIndent")]
public bool? AutoIndent { get { return GetPropertyValue<bool?>(); } set { SetPropertyValue(value); } } // = false;
// public CssStyle ExtraEditorClassName?
/// <summary>
/// Gets or Sets the language of the Editor. This property is only read for initialization, changes should go through <see cref="CodeEditor.CodeLanguage"/>.
/// </summary>
[JsonProperty("language")]
public string Language { get { return GetPropertyValue<string>(); } set { SetPropertyValue(value); } }
//[JsonProperty("theme")]
//public string Theme { get; set; } // = 'vs' (default), 'vs-dark', 'hc-black'
// Value (initial value of model)
public string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
}); // TODO
}
private readonly Dictionary<string, object> _propertyBackingDictionary = new Dictionary<string, object>();
private T GetPropertyValue<T>([CallerMemberName] string propertyName = null)
{
if (propertyName == null) throw new ArgumentNullException("propertyName");
object value;
if (_propertyBackingDictionary.TryGetValue(propertyName, out value))
{
return (T)value;
}
return default(T);
}
private bool SetPropertyValue<T>(T newValue, [CallerMemberName] string propertyName = null)
{
if (propertyName == null) throw new ArgumentNullException("propertyName");
if (EqualityComparer<T>.Default.Equals(newValue, GetPropertyValue<T>(propertyName))) return false;
_propertyBackingDictionary[propertyName] = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
}
#pragma warning restore CS1591
}

24
MonacoEditorComponent/Monaco/Editor/IEditorFindOptions.cs

@ -0,0 +1,24 @@
using System;
using Monaco.Helpers;
using Newtonsoft.Json;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditorfindoptions.html
/// </summary>
#pragma warning disable CS1591
public sealed class IEditorFindOptions : IJsonable
{
[JsonProperty("autoFindInSelection")]
public bool AutoFindInSelection { get; set; }
[JsonProperty("seedSearchStringFromSelection")]
public bool SeedSearchStringFromSelection { get; set; } //= true;
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
}
#pragma warning restore CS1591
}

28
MonacoEditorComponent/Monaco/Editor/IEditorMinimapOptions.cs

@ -0,0 +1,28 @@
using System;
using Monaco.Helpers;
using Newtonsoft.Json;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditorminimapoptions.html
/// </summary>
#pragma warning disable CS1591
public sealed class IEditorMinimapOptions : IJsonable
{
[JsonProperty("enabled")]
public bool? Enabled { get; set; }
[JsonProperty("maxColumn")]
public int? MaxColumn { get; set; } // = 120
[JsonProperty("renderCharacters")]
public bool? RenderCharacters { get; set; } // = true
[JsonProperty("showSlider")]
public string ShowSlider { get; set; } // = "mouseover"; always
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
}
#pragma warning restore CS1591
}

165
MonacoEditorComponent/Monaco/Editor/IEditorOptions.cs

@ -0,0 +1,165 @@
using Monaco.Helpers;
using Monaco.Editor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
using Newtonsoft.Json;
namespace Monaco.Editor
{
/// <summary>
/// Object Parser for https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditoroptions.html
/// </summary>
#pragma warning disable CS1591
public interface IEditorOptions
{
[JsonProperty("acceptSuggestionOnCommitCharacter")]
bool? AcceptSuggestionOnCommitCharacter { get; set; } // = true;
[JsonProperty("acceptSuggestionOnEnter")]
string AcceptSuggestionOnEnter { get; set; } // = "on"; // on, smart, off
[JsonProperty("accessibilitySupport")]
string AccessibilitySupport { get; set; } // = "auto"; // auto, off, on
[JsonProperty("ariaLabel")]
string AriaLabel { get; set; }
[JsonProperty("autoClosingBrackets")]
bool? AutoClosingBrackets { get; set; } // = true;
//bool AutomaticLayout { get; } // We handle this smartly as part of being a control, don't think it's needed to be exposed.
[JsonProperty("codeLens")]
bool? CodeLens { get; set; } // = true;
[JsonProperty("contextMenu")]
bool? ContextMenu { get; set; } // = true;
[JsonProperty("cursorBlinking")]
string CursorBlinking { get; set; } // = "blink"; // blink, smooth, phase, expand, solid
[JsonProperty("cursorStyle")]
string CursorStyle { get; set; } // = "line"; // line, block
[JsonProperty("disableLayerHinting")]
bool? DisableLayerHinting { get; set; }
[JsonProperty("disableMonospaceOptimizations")]
bool? DisableMonospaceOptimizations { get; set; }
[JsonProperty("dragAndDrop")]
bool? DragAndDrop { get; set; }
[JsonProperty("emptySelectionClipboard")]
bool? EmptySelectionClipboard { get; set; } // = true;
//string ExtraEditorClassName { get; set; } // CSS Class?
[JsonProperty("find")]
IEditorFindOptions Find { get; set; } // = new IEditorFindOptions();
[JsonProperty("fixedOverflowWidgets")]
bool? FixedOverflowWidgets { get; set; }
[JsonProperty("folding")]
bool? Folding { get; set; }
[JsonProperty("fontFamily")]
string FontFamily { get; set; }
[JsonProperty("fontLigatures")]
bool? FontLigatures { get; set; }
[JsonProperty("fontSize")]
uint? FontSize { get; set; }
[JsonProperty("fontWeight")]
string FontWeight { get; set; } // = "normal"; // 'normal' | 'bold' | 'bolder' | 'lighter' | 'initial' | 'inherit' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900';
[JsonProperty("formatOnPaste")]
bool? FormatOnPaste { get; set; }
[JsonProperty("glyphMargin")]
bool? GlyphMargin { get; set; }
[JsonProperty("hideCursorInOverviewRuler")]
bool? HideCursorInOverviewRuler { get; set; }
[JsonProperty("hover")]
bool? Hover { get; set; } // = true;
[JsonProperty("iconsInSuggestions")]
bool? IconsInSuggestions { get; set; } // = true;
[JsonProperty("letterSpacing")]
int? LetterSpacing { get; set; }
[JsonProperty("lineDecorationsWidth")]
int? LineDecorationsWidth { get; set; } // = 10; // TODO: Figure out support for union
[JsonProperty("lineHeight")]
int? LineHeight { get; set; }
[JsonProperty("lineNumbers")]
string LineNumbers { get; set; } // = "on"; // off, relative, function // TODO: Figure out function support for line numbers, probably separate add-on to interface
[JsonProperty("lineNumbersMinChars")]
int? LineNumbersMinChars { get; set; } //= 5;
[JsonProperty("links")]
bool? Links { get; set; } // = true;
[JsonProperty("matchBrackets")]
bool? MatchBrackets { get; set; } // = true;
[JsonProperty("minimap")]
IEditorMinimapOptions Minimap { get; set; }
[JsonProperty("mouseWheelScrollSensitivity")]
int? MouseWheelScrollSensitivity { get; set; } // = 1;
[JsonProperty("mouseWheelZoom")]
bool? MouseWheelZoom { get; set; }
[JsonProperty("multiCursorModifier")]
string MultiCursorModifier { get; set; } // = "alt"; ctrlCmd
[JsonProperty("occurrencesHighlight")]
bool? OccurrencesHighlight { get; set; } // = true;
[JsonProperty("overviewRulerBorder")]
bool? OverviewRulerBorder { get; set; } // = true;
[JsonProperty("overviewRulerLanes")]
uint? OverviewRulerLanes { get; set; } // = 2;
[JsonProperty("parameterHints")]
bool? ParameterHints { get; set; } // default?
[JsonProperty("quickSuggestions")]
bool? QuickSuggestions { get; set; } // = true; not sure what object option is...
[JsonProperty("quickSuggestionsDelay")]
uint? QuickSuggestionsDelay { get; set; } // = 500; (ms)
[JsonProperty("readOnly")]
bool? ReadOnly { get; set; }
[JsonProperty("renderControlCharacters")]
bool? RenderControlCharacters { get; set; }
[JsonProperty("renderIndentGuides")]
bool? RenderIndentGuides { get; set; }
[JsonProperty("renderLineHighlight")]
string RenderLineHighlight { get; set; } // = "all"; none, gutter, line
[JsonProperty("renderWhitespace")]
string RenderWhitespace { get; set; } // = "none"; boundary, all
[JsonProperty("revealHorizontalRightPadding")]
uint? RevealHorizontalRightPadding { get; set; } // = 30; (px)
[JsonProperty("roundedSelection")]
bool? RoundedSelection { get; set; } // = true;
[JsonProperty("rulers")]
uint[] Rulers { get; set; }
[JsonProperty("scrollBeyondLastLine")]
bool? ScrollBeyondLastLine { get; set; } // = true;
[JsonProperty("scrollbar")]
IEditorScrollbarOptions Scrollbar { get; set; }
[JsonProperty("selectOnLineNumbers")]
bool? SelectOnLineNumbers { get; set; } // = true;
[JsonProperty("selectionClipboard")]
bool? SelectionClipboard { get; set; } // = true;
[JsonProperty("selectionHighlight")]
bool? SelectionHighlight { get; set; } // = true;
[JsonProperty("showFoldingControls")]
string ShowFoldingControls { get; set; } // = "mouseover"; always
[JsonProperty("snipperSuggestions")]
string SnippetSuggestions { get; set; } // = "true"; top, bottom, inline, none
[JsonProperty("stopRenderingLineAfter")]
int? StopRenderingLineAfter { get; set; } // = 10000;
[JsonProperty("suggestFontSize")]
uint? SuggestFontSize { get; set; }
[JsonProperty("suggestLineHeight")]
int? SuggestLineHeight { get; set; }
[JsonProperty("suggestOnTriggerCharacters")]
bool? SuggestOnTriggerCharacters { get; set; } // = true;
[JsonProperty("useTabStops")]
bool? UseTabStops { get; set; } // default?
[JsonProperty("wordBasedSuggestions")]
bool? WordBasedSuggestions { get; set; } // = true;
[JsonProperty("wordSeparators")]
string WordSeparators { get; set; } // A string containing the word separators used when doing word navigation. Defaults to `~!@#$%^&*()-=+[{]}\|;:\'",.<>/?
[JsonProperty("wordWrap")]
string WordWrap { get; set; } // = "off"; on, wordWrapColumn, bounded
[JsonProperty("wordWrapBreakAfterCharacters")]
string WordWrapBreakAfterCharacters { get; set; } // Configure word wrapping characters. A break will be introduced after these characters. Defaults to ' \t})]?|&,;'
[JsonProperty("wordWrapBeforeCharacters")]
string WordWrapBreakBeforeCharacters { get; set; } // Configure word wrapping characters. A break will be introduced before these characters. Defaults to '{([+'
[JsonProperty("wordWrapObtrusiveCharacters")]
string WordWrapBreakObtrusiveCharacters { get; set; } // Configure word wrapping characters. A break will be introduced after these characters only if no wordWrapBreakBeforeCharacters or wordWrapBreakAfterCharacters were found. Defaults to '.'
[JsonProperty("wordWrapColumn")]
uint? WordWrapColumn { get; set; } // = 80;
[JsonProperty("wordWrapMinified")]
bool? WordWrapMinified { get; set; }
[JsonProperty("wrappingIndent")]
string WrappingIndent { get; set; } // = "none"; same, indent
}
#pragma warning restore CS1591
}

42
MonacoEditorComponent/Monaco/Editor/IEditorScrollbarOptions.cs

@ -0,0 +1,42 @@
using System;
using Monaco.Helpers;
using Newtonsoft.Json;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditorscrollbaroptions.html
/// </summary>
#pragma warning disable CS1591
public sealed class IEditorScrollbarOptions : IJsonable
{
[JsonProperty("arrowSize")]
public int? ArrowSize { get; set; } // = 11;
[JsonProperty("handleMouseWheel")]
public bool? HandleMouseWheel { get; set; } // = true;
[JsonProperty("horizontal")]
public string Horizontal { get; set; } // = "auto"; visible, hidden
[JsonProperty("horizontalHasArrows")]
public bool? HorizontalHasArrows { get; set; }
[JsonProperty("horizontalScrollbarSize")]
public uint? HorizontalScrollbarSize { get; set; } // = 10; (px)
[JsonProperty("horizontalSliderSize")]
public uint? HorizontalSliderSize { get; set; } // = 10; (px)
[JsonProperty("useShadows")]
public bool? UseShadows { get; set; }
[JsonProperty("vertical")]
public string Vertical { get; set; } // = "auto"; visible, hidden
[JsonProperty("verticalHasArrows")]
public bool? VerticalHasArrows { get; set; }
[JsonProperty("verticalScrollbarSize")]
public uint? VerticalScrollbarSize { get; set; } // = 10; (px)
[JsonProperty("verticalSliderSize")]
public uint? VerticalSliderSize { get; set; } // = 10; (px)
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
}
#pragma warning restore CS1591
}

22
MonacoEditorComponent/Monaco/Editor/IMarker.cs

@ -0,0 +1,22 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imarker.html
/// </summary>
public interface IMarker : IMarkerData
{
[JsonProperty("owner")]
string Owner { get; }
// TODO: Should I port over Monaco.Uri? https://microsoft.github.io/monaco-editor/api/classes/monaco.uri.html
[JsonProperty("resource")]
IUri Resource { get; }
}
}

27
MonacoEditorComponent/Monaco/Editor/IMarkerData.cs

@ -0,0 +1,27 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imarkerdata.html
/// </summary>
public interface IMarkerData : IRange
{
[JsonProperty("code")]
string Code { get; }
[JsonProperty("message")]
string Message { get; }
[JsonProperty("severity")]
Severity Severity { get; }
[JsonProperty("source")]
string Source { get; }
}
}

92
MonacoEditorComponent/Monaco/Editor/IModel.cs

@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
namespace Monaco.Editor
{
#pragma warning disable CS1591
/// <summary>
/// https://github.com/Microsoft/vscode/blob/master/src/vs/editor/common/editorCommon.ts#L228
/// </summary>
public enum EndOfLinePreference
{
TextDefined = 0,
LF = 1,
CRLF = 2
}
/// <summary>
/// https://github.com/Microsoft/vscode/blob/master/src/vs/editor/common/editorCommon.ts#L260
/// </summary>
public enum EndOfLineSequence
{
LF = 0,
CRLF = 1
}
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imodel.html
/// </summary>
public interface IModel
{
// TODO: Events
string Id { get; }
Uri Uri { get; }
//IIdentifiedSingleEditOperation[] ApplyEditsAsync(IIdentifiedSingleEditOperation[] operations)
//DeltaDecorationsAsync
IAsyncAction DetectIndentationAsync(bool defaultInsertSpaces, bool defaultTabSize);
//FindMatchesAsync(string searchString, bool searchOnlyEditableRange, bool isRegex, ...)
//FindNextMatchAsync
//FindPreviousMatchAsync
//GetAllDecorationsAsync
IAsyncOperation<uint> GetAlternativeVersionIdAsync();
//GetDecorationOptionsAsync
//GetDecorationRangeAsync
//GetDecorationsInRangeAsync
IAsyncOperation<string> GetEOLAsync();
IAsyncOperation<Range> GetFullModelRangeAsync();
IAsyncOperation<string> GetLineContentAsync(uint lineNumber);
IAsyncOperation<uint> GetLineCountAsync();
//GetLineDecorationsAsync
IAsyncOperation<uint> GetLineFirstNonWhitespaceColumnAsync(uint lineNumber);
IAsyncOperation<uint> GetLineLastNonWhitespaceColumnAsync(uint lineNumber);
IAsyncOperation<uint> GetLineLengthAsync(uint lineNumber);
IAsyncOperation<uint> GetLineMaxColumnAsync(uint lineNumber);
IAsyncOperation<uint> GetLineMinColumnAsync(uint lineNumber);
IAsyncOperation<IEnumerable<string>> GetLinesContentAsync();
//GetLinesDecorationsAsync
IAsyncOperation<string> GetModelIdAsync();
IAsyncOperation<uint> GetOffsetAtAsync(IPosition position);
IAsyncOperation<string> GetOneIndentAsync();
//GetOptionsAsync
IAsyncOperation<Position> GetPositionAtAsync(uint offset);
IAsyncOperation<string> GetValueAsync();
// TextDefined is default eol
IAsyncOperation<string> GetValueAsync(EndOfLinePreference eol);
IAsyncOperation<string> GetValueAsync(EndOfLinePreference eol, bool preserveBOM);
IAsyncOperation<string> GetValueInRangeAsync(IRange range);
IAsyncOperation<string> GetValueInRangeAsync(IRange range, EndOfLinePreference eol);
IAsyncOperation<uint> GetValueLengthAsync();
IAsyncOperation<uint> GetValueLengthAsync(EndOfLinePreference eol);
IAsyncOperation<uint> GetValueLengthAsync(EndOfLinePreference eol, bool preserveBOM);
IAsyncOperation<uint> GetValueLengthInRangeAsync(IRange range);
IAsyncOperation<uint> GetVersionIdAsync();
IAsyncOperation<WordAtPosition> GetWordAtPositionAsync(IPosition position);
IAsyncOperation<WordAtPosition> GetWordUntilPositionAsync(IPosition position);
IAsyncOperation<Position> ModifyPositionAsync(IPosition position, int number);
IAsyncOperation<string> NormalizeIndentationAsync(string str);
//PushEditOperationsAsync
IAsyncAction PushStackElementAsync();
IAsyncAction SetEOLAsync(EndOfLineSequence eol);
IAsyncAction SetValue(string newValue);
//IAsyncAction UpdateOptions(ITextModelUpdateOptions newOpts);
IAsyncOperation<Position> ValidatePositionAsync(IPosition position);
IAsyncOperation<Range> ValidateRangeAsync(IRange range);
}
#pragma warning restore CS1591
}

75
MonacoEditorComponent/Monaco/Editor/IModelDecorationOptions.cs

@ -0,0 +1,75 @@
using Monaco.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
namespace Monaco.Editor
{
/// <summary>
/// Object Parser for https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imodeldecorationoptions.html
/// </summary>
#pragma warning disable CS1591
public sealed class IModelDecorationOptions
{
[JsonProperty("isWholeLine")]
public bool IsWholeLine { get; set; }
[JsonProperty("hoverMessage")]
public IMarkdownString[] HoverMessage { get; set; }
[JsonProperty("glyphMarginHoverMessage")]
public IMarkdownString[] GlyphMarginHoverMessage { get; set; }
[JsonConverter(typeof(CssStyleConverter))]
[JsonProperty("className")]
public CssLineStyle ClassName { get; set; }
[JsonConverter(typeof(CssStyleConverter))]
[JsonProperty("glyphMarginClassName")]
public CssGlyphStyle GlyphMarginClassName { get; set; }
[JsonConverter(typeof(CssStyleConverter))]
[JsonProperty("inlineClassName")]
public CssInlineStyle InlineClassName { get; set; }
// TODO: Provide LinesDecorationsClassName
[JsonProperty("inlineClassNameAffectsLetterSpacing")]
public bool InlineClassNameAffectsLetterSpacing { get; set; }
[JsonProperty("stickiness")]
public TrackedRangeStickiness Stickiness { get; set; }
[JsonProperty("zIndex")]
public int ZIndex { get; set; }
}
#pragma warning restore CS1591
internal class CssStyleConverter: JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var style = value as ICssStyle;
writer.WriteValue(style.Name);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false.");
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ICssStyle);
}
}
}

31
MonacoEditorComponent/Monaco/Editor/IModelDeltaDecoration.cs

@ -0,0 +1,31 @@
using Monaco.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
namespace Monaco.Editor
{
/// <summary>
/// Object Parser for https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imodeldeltadecoration.html
/// </summary>
#pragma warning disable CS1591
public sealed class IModelDeltaDecoration
{
[JsonProperty("options")]
public IModelDecorationOptions Options { get; private set; }
[JsonProperty("range")]
public IRange Range { get; private set; }
public IModelDeltaDecoration(IRange range, IModelDecorationOptions options)
{
this.Range = range;
this.Options = options;
}
}
#pragma warning restore CS1591
}

30
MonacoEditorComponent/Monaco/Editor/IWordAtPosition.cs

@ -0,0 +1,30 @@
using Newtonsoft.Json;
using Monaco.Helpers;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.iwordatposition.html
/// </summary>
[JsonConverter(typeof(InterfaceToClassConverter<IWordAtPosition, WordAtPosition>))]
public interface IWordAtPosition
{
/// <summary>
/// Column where the word ends.
/// </summary>
[JsonProperty("endColumn")]
uint EndColumn { get; }
/// <summary>
/// Column where the word starts.
/// </summary>
[JsonProperty("startColumn")]
uint StartColumn { get; }
/// <summary>
/// The word.
/// </summary>
[JsonProperty("word")]
string Word { get; }
}
}

50
MonacoEditorComponent/Monaco/Editor/Marker.cs

@ -0,0 +1,50 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imarker.html
/// </summary>
public sealed class Marker : IMarker
{
[JsonProperty("owner")]
public string Owner { get; set; }
[JsonProperty("resource")]
public IUri Resource { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("severity")]
public Severity Severity { get; set; }
[JsonProperty("source")]
public string Source { get; set; }
[JsonProperty("startLineNumber")]
public uint StartLineNumber { get; set; }
[JsonProperty("startColumn")]
public uint StartColumn { get; set; }
[JsonProperty("endLineNumber")]
public uint EndLineNumber { get; set; }
[JsonProperty("endColumn")]
public uint EndColumn { get; set; }
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
}
}

44
MonacoEditorComponent/Monaco/Editor/MarkerData.cs

@ -0,0 +1,44 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imarkerdata.html
/// </summary>
public sealed class MarkerData : IMarkerData
{
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("severity")]
public Severity Severity { get; set; }
[JsonProperty("source")]
public string Source { get; set; }
[JsonProperty("startLineNumber")]
public uint StartLineNumber { get; set; }
[JsonProperty("startColumn")]
public uint StartColumn { get; set; }
[JsonProperty("endLineNumber")]
public uint EndLineNumber { get; set; }
[JsonProperty("endColumn")]
public uint EndColumn { get; set; }
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
}
}

13
MonacoEditorComponent/Monaco/Editor/TrackedRangeStickiness.cs

@ -0,0 +1,13 @@
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/enums/monaco.editor.trackedrangestickiness.html
/// </summary>
public enum TrackedRangeStickiness
{
AlwaysGrowsWhenTypingAtEdges = 0,
NeverGrowsWhenTypingAtEdges = 1,
GrowsOnlyWhenTypingBefore = 2,
GrowsOnlyWhenTypingAfter = 3,
}
}

28
MonacoEditorComponent/Monaco/Editor/WordAtPosition.cs

@ -0,0 +1,28 @@
using Newtonsoft.Json;
namespace Monaco.Editor
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.iwordatposition.html
/// </summary>
public sealed class WordAtPosition : IWordAtPosition
{
/// <summary>
/// Column where the word ends.
/// </summary>
[JsonProperty("endColumn")]
public uint EndColumn { get; private set; }
/// <summary>
/// Column where the word starts.
/// </summary>
[JsonProperty("startColumn")]
public uint StartColumn { get; private set; }
/// <summary>
/// The word.
/// </summary>
[JsonProperty("word")]
public string Word { get; private set; }
}
}

25
MonacoEditorComponent/Monaco/Helpers/CssGlyphStyle.cs

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Helpers
{
public sealed class CssGlyphStyle : ICssStyle
{
public Uri GlyphImage { get; set; }
public string Name { get; private set; }
public CssGlyphStyle()
{
Name = CssStyleBroker.Instance.Register(this);
}
public string ToCss()
{
return CssStyleBroker.WrapCssClassName(this, string.Format("background: url(\"{0}\");", GlyphImage.AbsoluteUri));
}
}
}

82
MonacoEditorComponent/Monaco/Helpers/CssInlineStyle.cs

@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Text;
using Windows.UI.Xaml.Media;
namespace Monaco.Helpers
{
public enum TextDecoration
{
None,
Underline,
Overline,
LineThrough, // line-through
Initial,
Inherit
}
// Inline styles modify the text style itself and are useful for manipulating the colors and styles of text to indicate conditions.
public sealed class CssInlineStyle: ICssStyle
{
public TextDecoration TextDecoration { get; set; }
public FontWeight? FontWeight { get; set; }
public FontStyle FontStyle { get; set; }
// TODO: Provide Cursor: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
// Setting a background inline will override any CssLineStyle.
public SolidColorBrush BackgroundColor { get; set; }
public SolidColorBrush ForegroundColor { get; set; }
public string Name { get; private set; }
public CssInlineStyle()
{
Name = CssStyleBroker.Instance.Register(this);
}
public string ToCss()
{
StringBuilder output = new StringBuilder(40);
if (TextDecoration != TextDecoration.None)
{
string text = TextDecoration.ToString().ToLower();
if (TextDecoration == TextDecoration.LineThrough)
{
text = "line-through";
}
output.AppendLine(string.Format("text-decoration: {0};", text));
}
if (FontWeight != null && FontWeight.HasValue)
{
output.AppendLine(string.Format("font-weight: {0};", FontWeight.Value.Weight));
}
if (FontStyle != FontStyle.Normal)
{
output.AppendLine(string.Format("font-style: {0};", FontStyle.ToString().ToLower()));
}
if (BackgroundColor != null)
{
output.AppendLine(string.Format("background: #{0:X2}{1:X2}{2:X2};", BackgroundColor.Color.R,
BackgroundColor.Color.G,
BackgroundColor.Color.B));
}
if (ForegroundColor != null)
{
output.AppendLine(string.Format("color: #{0:X2}{1:X2}{2:X2} !important;", ForegroundColor.Color.R,
ForegroundColor.Color.G,
ForegroundColor.Color.B));
}
return CssStyleBroker.WrapCssClassName(this, output.ToString());
}
}
}

43
MonacoEditorComponent/Monaco/Helpers/CssLineStyle.cs

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Media;
namespace Monaco.Helpers
{
// Simple Proxy to general CSS Line Styles
// Line styles are overlayed behind text in the editor and are useful for highlighting sections of text efficiently
public sealed class CssLineStyle : ICssStyle
{
public SolidColorBrush BackgroundColor { get; set; }
[Obsolete("Use ForegroundColor on CssInlineStyle instead, this is an overlay.")]
public SolidColorBrush ForegroundColor { get; set; }
public string Name { get; private set; }
public CssLineStyle() {
Name = CssStyleBroker.Instance.Register(this);
}
public string ToCss()
{
StringBuilder output = new StringBuilder(40);
if (BackgroundColor != null)
{
output.AppendLine(string.Format("background: #{0:X2}{1:X2}{2:X2};", BackgroundColor.Color.R,
BackgroundColor.Color.G,
BackgroundColor.Color.B));
}
if (ForegroundColor != null)
{
output.AppendLine(string.Format("color: #{0:X2}{1:X2}{2:X2} !important;", ForegroundColor.Color.R,
ForegroundColor.Color.G,
ForegroundColor.Color.B));
}
return CssStyleBroker.WrapCssClassName(this, output.ToString());
}
}
}

74
MonacoEditorComponent/Monaco/Helpers/CssStyleBroker.cs

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Helpers
{
public interface ICssStyle
{
string Name { get; }
string ToCss();
}
/// <summary>
/// Singleton Broker to help us manage CSS Styles
/// </summary>
public sealed class CssStyleBroker
{
private static uint Id = 0;
private Dictionary<string, ICssStyle> _registered = new Dictionary<string, ICssStyle>();
// http://csharpindepth.com/Articles/General/Singleton.aspx
private static readonly CssStyleBroker _instance = new CssStyleBroker();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static CssStyleBroker()
{
}
private CssStyleBroker()
{
}
public static CssStyleBroker Instance // TODO: Probably need to tie this to a specific Editor
{
get
{
return _instance;
}
}
/// <summary>
/// Returns the name for a style to use after registered.
/// </summary>
/// <param name="style"></param>
/// <returns></returns>
public string Register(ICssStyle style)
{
CssStyleBroker.Id += 1;
var name = "generated-style-" + Id;
this._registered.Add(name, style);
return name;
}
/// <summary>
/// Returns the CSS block for all registered styles.
/// </summary>
/// <returns></returns>
public string GetStyles()
{
StringBuilder rules = new StringBuilder(100);
foreach (ICssStyle css in _registered.Values)
{
rules.AppendLine(css.ToCss());
}
return rules.ToString();
}
public static string WrapCssClassName(ICssStyle style, string inner)
{
return String.Format(".{0} {{ {1} }}", style.Name, inner);
}
}
}

70
MonacoEditorComponent/Monaco/Helpers/Json.cs

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Helpers
{
public interface IJsonable
{
string ToJson();
}
public static class Json
{
/// <summary>
/// Converts an array of strings to a JSON based string array.
/// </summary>
/// <param name="strings"></param>
/// <returns></returns>
public static string StringArray([ReadOnlyArray] string[] strings)
{
StringBuilder output = new StringBuilder("[", 100);
foreach (string msg in strings)
{
output.Append(String.Format("\"{0}\",", msg));
}
if (strings.Length > 0)
{
output.Remove(output.Length - 1, 1); // Remove Trailing Comma
}
output.Append("]");
return output.ToString();
}
/// <summary>
/// Converts an array of Jsonable objects to JSON based array.
/// </summary>
/// <param name="objects"></param>
/// <returns></returns>
public static string ObjectArray(IEnumerable<IJsonable> objects)
{
StringBuilder output = new StringBuilder("[", 100);
foreach (var obj in objects)
{
output.Append(String.Format("{0},", obj.ToJson()));
}
if (objects.Count() > 0)
{
output.Remove(output.Length - 1, 1); // Remove Trailing Comma
}
output.Append("]");
return output.ToString();
}
/// <summary>
/// Wrap a JSON string in a Parse statement for export.
/// Escapes double-quotes.
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static string Parse(string json)
{
return String.Format("JSON.parse(\"{0}\")", json.Replace("\"", "\\\""));
}
}
}

57
MonacoEditorComponent/Monaco/IMarkdownString.cs

@ -0,0 +1,57 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation.Metadata;
namespace Monaco
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.imarkdownstring.html
/// </summary>
public sealed class IMarkdownString
{
[JsonProperty("isTrusted")]
public bool IsTrusted { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
public IMarkdownString(string svalue) : this(svalue, false) { }
public IMarkdownString(string svalue, bool isTrusted)
{
Value = svalue;
IsTrusted = isTrusted;
}
}
public static class StringExtensions
{
[DefaultOverload]
public static IMarkdownString ToMarkdownString(this string svalue)
{
return ToMarkdownString(svalue, false);
}
[DefaultOverload]
public static IMarkdownString ToMarkdownString(this string svalue, bool isTrusted)
{
return new IMarkdownString(svalue, isTrusted);
}
public static IMarkdownString[] ToMarkdownString([ReadOnlyArray] this string[] values)
{
return ToMarkdownString(values, false);
}
public static IMarkdownString[] ToMarkdownString([ReadOnlyArray] this string[] values, bool isTrusted)
{
return values.Select(value => new IMarkdownString(value, isTrusted)).ToArray();
}
}
}

15
MonacoEditorComponent/Monaco/IPosition.cs

@ -0,0 +1,15 @@
using Monaco.Helpers;
using Newtonsoft.Json;
namespace Monaco
{
#pragma warning disable CS1591
public interface IPosition: IJsonable
{
[JsonProperty("column")]
uint Column { get; }
[JsonProperty("lineNumber")]
uint LineNumber { get; }
}
#pragma warning restore CS1591
}

19
MonacoEditorComponent/Monaco/IRange.cs

@ -0,0 +1,19 @@
using Monaco.Helpers;
using Newtonsoft.Json;
namespace Monaco
{
#pragma warning disable CS1591
public interface IRange: IJsonable
{
[JsonProperty("startLineNumber")]
uint StartLineNumber { get; }
[JsonProperty("startColumn")]
uint StartColumn { get; }
[JsonProperty("endLineNumber")]
uint EndLineNumber { get; }
[JsonProperty("endColumn")]
uint EndColumn { get; }
}
#pragma warning restore CS1591
}

35
MonacoEditorComponent/Monaco/IUri.cs

@ -0,0 +1,35 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/classes/monaco.uri.html
/// </summary>
public sealed class IUri
{
[JsonProperty("authority")]
public string Authority { get; set; }
[JsonProperty("fragment")]
public string Fragment { get; set; }
[JsonProperty("fsPath")]
public string FSPath { get; set; }
[JsonProperty("path")]
public string Path { get; set; }
[JsonProperty("query")]
public string Query { get; set; }
[JsonProperty("scheme")]
public string Scheme { get; set; }
public IUri() { }
}
}

186
MonacoEditorComponent/Monaco/KeyCode.cs

@ -0,0 +1,186 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/enums/monaco.keycode.html
/// Transposed from 'standaloneBase.ts'
/// </summary>
public static class KeyCode
{
#pragma warning disable CS1591
/**
* Placed first to cover the 0 value of the enum.
*/
public static int Unknown => 0;
public static int Backspace => 1;
public static int Tab => 2;
public static int Enter => 3;
public static int Shift => 4;
public static int Ctrl => 5;
public static int Alt => 6;
public static int PauseBreak => 7;
public static int CapsLock => 8;
public static int Escape => 9;
public static int Space => 10;
public static int PageUp => 11;
public static int PageDown => 12;
public static int End => 13;
public static int Home => 14;
public static int LeftArrow => 15;
public static int UpArrow => 16;
public static int RightArrow => 17;
public static int DownArrow => 18;
public static int Insert => 19;
public static int Delete => 20;
public static int KEY_0 => 21;
public static int KEY_1 => 22;
public static int KEY_2 => 23;
public static int KEY_3 => 24;
public static int KEY_4 => 25;
public static int KEY_5 => 26;
public static int KEY_6 => 27;
public static int KEY_7 => 28;
public static int KEY_8 => 29;
public static int KEY_9 => 30;
public static int KEY_A => 31;
public static int KEY_B => 32;
public static int KEY_C => 33;
public static int KEY_D => 34;
public static int KEY_E => 35;
public static int KEY_F => 36;
public static int KEY_G => 37;
public static int KEY_H => 38;
public static int KEY_I => 39;
public static int KEY_J => 40;
public static int KEY_K => 41;
public static int KEY_L => 42;
public static int KEY_M => 43;
public static int KEY_N => 44;
public static int KEY_O => 45;
public static int KEY_P => 46;
public static int KEY_Q => 47;
public static int KEY_R => 48;
public static int KEY_S => 49;
public static int KEY_T => 50;
public static int KEY_U => 51;
public static int KEY_V => 52;
public static int KEY_W => 53;
public static int KEY_X => 54;
public static int KEY_Y => 55;
public static int KEY_Z => 56;
public static int Meta => 57;
public static int ContextMenu => 58;
public static int F1 => 59;
public static int F2 => 60;
public static int F3 => 61;
public static int F4 => 62;
public static int F5 => 63;
public static int F6 => 64;
public static int F7 => 65;
public static int F8 => 66;
public static int F9 => 67;
public static int F10 => 68;
public static int F11 => 69;
public static int F12 => 70;
public static int F13 => 71;
public static int F14 => 72;
public static int F15 => 73;
public static int F16 => 74;
public static int F17 => 75;
public static int F18 => 76;
public static int F19 => 77;
public static int NumLock => 78;
public static int ScrollLock => 79;
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ';:' key
*/
public static int US_SEMICOLON => 80;
/**
* For any country/region, the '+' key
* For the US standard keyboard, the '=+' key
*/
public static int US_EQUAL => 81;
/**
* For any country/region, the ',' key
* For the US standard keyboard, the ',&lt;' key
*/
public static int US_COMMA => 82;
/**
* For any country/region, the '-' key
* For the US standard keyboard, the '-_' key
*/
public static int US_MINUS => 83;
/**
* For any country/region, the '.' key
* For the US standard keyboard, the '.>' key
*/
public static int US_DOT => 84;
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '/?' key
*/
public static int US_SLASH => 85;
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '`~' key
*/
public static int US_BACKTICK => 86;
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '[{' key
*/
public static int US_OPEN_SQUARE_BRACKET => 87;
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the '\|' key
*/
public static int US_BACKSLASH => 88;
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ']}' key
*/
public static int US_CLOSE_SQUARE_BRACKET => 89;
/**
* Used for miscellaneous characters; it can vary by keyboard.
* For the US standard keyboard, the ''"' key
*/
public static int US_QUOTE => 90;
/**
* Used for miscellaneous characters; it can vary by keyboard.
*/
public static int OEM_8 => 91;
/**
* Either the angle bracket key or the backslash key on the RT 102-key keyboard.
*/
public static int OEM_102 => 92;
public static int NUMPAD_0 => 93;
public static int NUMPAD_1 => 94;
public static int NUMPAD_2 => 95;
public static int NUMPAD_3 => 96;
public static int NUMPAD_4 => 97;
public static int NUMPAD_5 => 98;
public static int NUMPAD_6 => 99;
public static int NUMPAD_7 => 100;
public static int NUMPAD_8 => 101;
public static int NUMPAD_9 => 102;
public static int NUMPAD_MULTIPLY => 103;
public static int NUMPAD_ADD => 104;
public static int NUMPAD_SEPARATOR => 105;
public static int NUMPAD_SUBTRACT => 106;
public static int NUMPAD_DECIMAL => 107;
public static int NUMPAD_DIVIDE => 108;
/**
* Cover all key codes when IME is processing input.
*/
public static int KEY_IN_COMPOSITION => 109;
public static int ABNT_C1 => 110;
public static int ABNT_C2 => 111;
#pragma warning restore CS1591
}
}

43
MonacoEditorComponent/Monaco/KeyMod.cs

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/classes/monaco.keymod.html
/// </summary>
public sealed class KeyMod
{
#pragma warning disable CS1591
public static int WinCtrl => 256;
public static int Alt => 512;
public static int Shift => 1024;
public static int CtrlCmd => 2048;
public static int Chord(int firstPart, int secondPart)
{
// https://github.com/Microsoft/vscode/blob/master/src/vs/base/common/keyCodes.ts#L410
var chordPart = ZeroFillRightShift((secondPart & 0x0000ffff) << 16, 0);
return ZeroFillRightShift(firstPart | chordPart, 0);
}
#pragma warning restore CS1591
// Info on Zero-Fill Right Shift http://www.vanguardsw.com/dphelp4/dph00369.htm
// Supported natively by JavaScript, but not C#
private static Int32 ZeroFillRightShift(Int32 i, Int32 j)
{
bool negativemask = (i < 0);
i = i >> j;
if (negativemask)
{
i &= 0x7FFFFFFF;
}
return i;
}
}
}

28
MonacoEditorComponent/Monaco/Languages/Command.cs

@ -0,0 +1,28 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Languages
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.command.html
/// </summary>
public sealed class Command
{
//// TODO: Find a usage example for this in Monaco.
[JsonProperty("arguments", NullValueHandling = NullValueHandling.Ignore)]
public object[] Arguments { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("tooltip", NullValueHandling = NullValueHandling.Ignore)]
public string Tooltip { get; set; }
}
}

21
MonacoEditorComponent/Monaco/Languages/CompletionContext.cs

@ -0,0 +1,21 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Languages
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.completioncontext.html
/// </summary>
public sealed class CompletionContext
{
[JsonProperty("triggerCharacter", NullValueHandling = NullValueHandling.Ignore)]
public string TriggerCharacter { get; set; }
[JsonProperty("triggerKind")]
public SuggestTriggerKind TriggerKind { get; set; }
}
}

53
MonacoEditorComponent/Monaco/Languages/CompletionItem.cs

@ -0,0 +1,53 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Languages
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.completionitem.html
/// </summary>
public sealed class CompletionItem
{
////public ISingleEditOperation[] AdditionalTextEdits { get; set; }
[JsonProperty("command", NullValueHandling = NullValueHandling.Ignore)]
public Command Command { get; set; }
[JsonProperty("commitCharacters", NullValueHandling = NullValueHandling.Ignore)]
public string[] CommitCharacters { get; set; }
[JsonProperty("detail", NullValueHandling = NullValueHandling.Ignore)]
public string Detail { get; set; }
[JsonProperty("documentation", NullValueHandling = NullValueHandling.Ignore)]
public IMarkdownString Documentation { get; set; }
[JsonProperty("filterText", NullValueHandling = NullValueHandling.Ignore)]
public string FilterText { get; set; }
[JsonProperty("insertText", NullValueHandling = NullValueHandling.Ignore)]
public SnippetString InsertText { get; set; }
[JsonProperty("kind")]
public CompletionItemKind Kind { get; set; }
[JsonProperty("label")]
public string Label { get; set; }
[JsonProperty("range", NullValueHandling = NullValueHandling.Ignore)]
public IRange Range { get; set; }
[JsonProperty("sortText", NullValueHandling = NullValueHandling.Ignore)]
public string SortText { get; set; }
public CompletionItem(string label, CompletionItemKind kind)
{
Label = label;
Kind = kind;
}
}
}

28
MonacoEditorComponent/Monaco/Languages/CompletionItemKind.cs

@ -0,0 +1,28 @@
namespace Monaco.Languages
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/enums/monaco.languages.completionitemkind.html
/// </summary>
public enum CompletionItemKind
{
Class = 6,
Color = 15,
Constructor = 3,
Enum = 12,
Field = 4,
File = 16,
Folder = 18,
Function = 2,
Interface = 7,
Keyword = 13,
Method = 1,
Module = 8,
Property = 9,
Reference = 17,
Snippet = 14,
Text = 0,
Unit = 10,
Value = 11,
Variable = 5
}
}

21
MonacoEditorComponent/Monaco/Languages/CompletionItemProvider.cs

@ -0,0 +1,21 @@
using Monaco.Editor;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
namespace Monaco.Languages
{
public interface CompletionItemProvider
{
[JsonProperty("triggerCharacters")]
string[] TriggerCharacters { get; }
IAsyncOperation<CompletionList> ProvideCompletionItemsAsync(IModel document, IPosition position, CompletionContext context);
IAsyncOperation<CompletionItem> ResolveCompletionItemAsync(CompletionItem item);
}
}

32
MonacoEditorComponent/Monaco/Languages/CompletionList.cs

@ -0,0 +1,32 @@
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Languages
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.completionlist.html
/// </summary>
public sealed class CompletionList : IEnumerable<CompletionItem> // TODO: Could I somehow also just make this a list? Investigate Json Serialization Converter helper for that?
{
[JsonProperty("isIncomplete", NullValueHandling = NullValueHandling.Ignore)]
public bool IsIncomplete { get; set; }
[JsonProperty("items")]
public IList<CompletionItem> Items { get; set; } = new List<CompletionItem>();
public IEnumerator<CompletionItem> GetEnumerator()
{
return Items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return Items.GetEnumerator();
}
}
}

30
MonacoEditorComponent/Monaco/Languages/Hover.cs

@ -0,0 +1,30 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
namespace Monaco.Languages
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.hover.html
/// </summary>
public sealed class Hover
{
[JsonProperty("contents")]
public IMarkdownString[] Contents { get; set; }
[JsonProperty("range")]
public IRange Range { get; set; }
public Hover([ReadOnlyArray] string[] contents, IRange range) : this(contents, range, false) { }
public Hover([ReadOnlyArray] string[] contents, IRange range, bool isTrusted)
{
Contents = contents.ToMarkdownString(isTrusted);
Range = range;
}
}
}

11
MonacoEditorComponent/Monaco/Languages/HoverProvider.cs

@ -0,0 +1,11 @@
using Monaco.Editor;
using Windows.Foundation;
namespace Monaco.Languages
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.hoverprovider.html
/// Simplify things here with a delegate vs. forcing to use a custom class instance.
/// </summary>
public delegate IAsyncOperation<Hover> HoverProvider(IModel model, IPosition position);
}

35
MonacoEditorComponent/Monaco/Languages/ILanguageExtensionPoint.cs

@ -0,0 +1,35 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
namespace Monaco.Languages
{
/// <summary>
/// Object Parser for https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.ilanguageextensionpoint.html
/// </summary>
public sealed class ILanguageExtensionPoint
{
#pragma warning disable CS1591
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("aliases")]
public string[] Aliases { get; set; }
[JsonProperty("configuration")]
public string Configuration { get; set; }
[JsonProperty("extensions")]
public string[] Extensions { get; set; }
[JsonProperty("filenames")]
public string[] Filenames { get; set; }
[JsonProperty("filenamePatterns")]
public string[] FilenamePatterns { get; set; }
[JsonProperty("firstLine")]
public string FirstLine { get; set; }
[JsonProperty("mimetypes")]
public string[] Mimetypes { get; set; }
#pragma warning restore CS1591
}
}

35
MonacoEditorComponent/Monaco/Languages/SnippetString.cs

@ -0,0 +1,35 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation.Metadata;
namespace Monaco
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.languages.snippetstring.html
/// https://code.visualstudio.com/docs/editor/userdefinedsnippets#_creating-your-own-snippets
/// </summary>
public sealed class SnippetString
{
[JsonProperty("value")]
public string Value { get; set; }
public SnippetString(string svalue)
{
Value = svalue;
}
}
public static class StringExtensions2
{
public static SnippetString ToSnippetString(this string svalue)
{
return new SnippetString(svalue);
}
}
}

12
MonacoEditorComponent/Monaco/Languages/SuggestTriggerKind.cs

@ -0,0 +1,12 @@
namespace Monaco.Languages
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/enums/monaco.languages.suggesttriggerkind.html
/// </summary>
public enum SuggestTriggerKind
{
Invoke = 0,
TriggerCharacter = 1,
TriggerForIncompleteCompletions = 2,
}
}

102
MonacoEditorComponent/Monaco/LanguagesHelper.cs

@ -0,0 +1,102 @@
using Monaco.Languages;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Foundation;
namespace Monaco
{
/// <summary>
/// Helper to static Monaco.Languages Namespace methods.
/// https://microsoft.github.io/monaco-editor/api/modules/monaco.languages.html
/// </summary>
public sealed class LanguagesHelper
{
private WeakReference<CodeEditor> _editor;
public LanguagesHelper(CodeEditor editor)
{
// We need the editor component in order to execute JavaScript within
// the WebView environment to retrieve data (even though this Monaco class is static).
_editor = new WeakReference<CodeEditor>(editor);
}
public IAsyncOperation<IList<ILanguageExtensionPoint>> GetLanguagesAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<IList<ILanguageExtensionPoint>>("monaco.languages.getLanguages()").AsAsyncOperation();
}
return null;
}
public IAsyncAction RegisterAsync(ILanguageExtensionPoint language)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.InvokeScriptAsync("monaco.languages.register", language).AsAsyncAction();
}
return null;
}
public IAsyncAction RegisterCompletionItemProviderAsync(string languageId, CompletionItemProvider provider)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
// Wrapper around CompletionItem Provider to Monaco editor.
// TODO: Add Incremented Id so that we can register multiple providers per language?
editor._parentAccessor.RegisterEvent("CompletionItemProvider" + languageId, async (args) =>
{
if (args != null && args.Length >= 2)
{
var items = await provider.ProvideCompletionItemsAsync(editor.GetModel(), JsonConvert.DeserializeObject<Position>(args[0]), JsonConvert.DeserializeObject<CompletionContext>(args[1]));
if (items != null)
{
return JsonConvert.SerializeObject(items);
}
}
return null;
});
return editor.InvokeScriptAsync("registerCompletionItemProvider", new object[] { languageId, provider.TriggerCharacters }).AsAsyncAction();
}
return null;
}
public IAsyncAction RegisterHoverProviderAsync(string languageId, HoverProvider provider)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
// Wrapper around Hover Provider to Monaco editor.
// TODO: Add Incremented Id so that we can register multiple providers per language?
editor._parentAccessor.RegisterEvent("HoverProvider" + languageId, async (args) =>
{
if (args != null && args.Length >= 1)
{
var hover = await provider.Invoke(editor.GetModel(), JsonConvert.DeserializeObject<Position>(args[0]));
if (hover != null)
{
return JsonConvert.SerializeObject(hover);
}
}
return string.Empty;
});
return editor.InvokeScriptAsync("registerHoverProvider", languageId).AsAsyncAction();
}
return null;
}
}
}

350
MonacoEditorComponent/Monaco/ModelHelper.cs

@ -0,0 +1,350 @@
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Collections.Generic;
using Windows.Foundation;
namespace Monaco.Editor
{
/// <summary>
/// Helper to access IModel interface methods off of CodeEditor object.
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.imodel.html
/// https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.itextmodel.html
/// </summary>
#pragma warning disable CS1591
public sealed class ModelHelper : IModel
{
private WeakReference<CodeEditor> _editor;
public ModelHelper(CodeEditor editor)
{
this._editor = new WeakReference<CodeEditor>(editor);
}
public string Id => throw new NotImplementedException();
public Uri Uri => throw new NotImplementedException();
public IAsyncAction DetectIndentationAsync(bool defaultInsertSpaces, bool defaultTabSize)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.InvokeScriptAsync("model.detectIndentationAsync", new object[] { defaultInsertSpaces, defaultTabSize }).AsAsyncAction();
}
return null;
}
public IAsyncOperation<uint> GetAlternativeVersionIdAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<uint>("model.getAlternativeVersionId();").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<string> GetEOLAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<string>("model.getEOL();").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<Range> GetFullModelRangeAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<Range>("model.getFullModelRange();").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<string> GetLineContentAsync(uint lineNumber)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<string>("model.getLineContent(" + lineNumber + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<uint> GetLineCountAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<uint>("model.getLineCount();").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<uint> GetLineFirstNonWhitespaceColumnAsync(uint lineNumber)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<uint>("model.getLineFirstNonWhitespaceColumn(" + lineNumber + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<uint> GetLineLastNonWhitespaceColumnAsync(uint lineNumber)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<uint>("model.getLineLastNonWhitespaceColumn(" + lineNumber + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<uint> GetLineLengthAsync(uint lineNumber)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<uint>("model.getLineLength(" + lineNumber + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<uint> GetLineMaxColumnAsync(uint lineNumber)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<uint>("model.getLineMaxColumn(" + lineNumber + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<uint> GetLineMinColumnAsync(uint lineNumber)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<uint>("model.getLineMinColumn(" + lineNumber + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<IEnumerable<string>> GetLinesContentAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<IEnumerable<string>>("model.getLinesContent();").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<string> GetModelIdAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<string>("model.getModelId();").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<uint> GetOffsetAtAsync(IPosition position)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<uint>("model.getOffsetAt(" + JsonConvert.SerializeObject(position) + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<string> GetOneIndentAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<string>("model.getOneIndent();").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<Position> GetPositionAtAsync(uint offset)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<Position>("model.getPositionAt(" + offset + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<string> GetValueAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<string>("model.getValue();").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<string> GetValueAsync(EndOfLinePreference eol)
{
throw new NotImplementedException();
}
public IAsyncOperation<string> GetValueAsync(EndOfLinePreference eol, bool preserveBOM)
{
throw new NotImplementedException();
}
public IAsyncOperation<string> GetValueInRangeAsync(IRange range)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<string>("model.getValueInRange(" + JsonConvert.SerializeObject(range) + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<string> GetValueInRangeAsync(IRange range, EndOfLinePreference eol)
{
throw new NotImplementedException();
}
public IAsyncOperation<uint> GetValueLengthAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<uint>("model.getValueLength();").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<uint> GetValueLengthAsync(EndOfLinePreference eol)
{
throw new NotImplementedException();
}
public IAsyncOperation<uint> GetValueLengthAsync(EndOfLinePreference eol, bool preserveBOM)
{
throw new NotImplementedException();
}
public IAsyncOperation<uint> GetValueLengthInRangeAsync(IRange range)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<uint>("model.getValueLengthInRange(" + JsonConvert.SerializeObject(range) + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<uint> GetVersionIdAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<uint>("model.getVersionId();").AsAsyncOperation();
}
return null;
}
// TODO: Need to investigate why with .NET Native the InterfaceToClassConverter isn't working anymore?
public IAsyncOperation<WordAtPosition> GetWordAtPositionAsync(IPosition position)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<WordAtPosition>("model.getWordAtPosition(" + JsonConvert.SerializeObject(position) + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<WordAtPosition> GetWordUntilPositionAsync(IPosition position)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<WordAtPosition>("model.getWordUntilPosition(" + JsonConvert.SerializeObject(position) + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<Position> ModifyPositionAsync(IPosition position, int number)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<Position>("model.modifyPosition(" + JsonConvert.SerializeObject(position) + ", " + number + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<string> NormalizeIndentationAsync(string str)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<string>("model.normalizeIndentations(JSON.parse(" + JsonConvert.ToString(str) + "));").AsAsyncOperation();
}
return null;
}
public IAsyncAction PushStackElementAsync()
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync("model.pushStackElement();").AsAsyncAction();
}
return null;
}
public IAsyncAction SetEOLAsync(EndOfLineSequence eol)
{
throw new NotImplementedException();
}
public IAsyncAction SetValue(string newValue)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync("model.setValue(JSON.parse(" + JsonConvert.ToString(newValue) + "));").AsAsyncAction();
}
return null;
}
public IAsyncOperation<Position> ValidatePositionAsync(IPosition position)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<Position>("model.validatePosition(" + JsonConvert.SerializeObject(position) + ");").AsAsyncOperation();
}
return null;
}
public IAsyncOperation<Range> ValidateRangeAsync(IRange range)
{
if (_editor.TryGetTarget(out CodeEditor editor))
{
return editor.SendScriptAsync<Range>("model.validateRange(" + JsonConvert.SerializeObject(range) + ");").AsAsyncOperation();
}
return null;
}
}
#pragma warning restore CS1591
}

123
MonacoEditorComponent/Monaco/Position.cs

@ -0,0 +1,123 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Metadata;
namespace Monaco
{
/// <summary>
/// A position in the editor.
/// https://microsoft.github.io/monaco-editor/api/classes/monaco.position.html
/// </summary>
#pragma warning disable CS1591
public sealed class Position: IPosition
{
// TODO: Investigate why with .NET Native the interface attributes aren't carried forward?
[JsonProperty("column")]
public uint Column { get; private set; }
[JsonProperty("lineNumber")]
public uint LineNumber { get; private set; }
public Position(uint lineNumber, uint column)
{
this.Column = column;
this.LineNumber = lineNumber;
}
public Position Clone()
{
return new Position(this.LineNumber, this.Column);
}
public override bool Equals(object obj)
{
if (obj is Position)
{
var other = obj as Position;
return this.LineNumber == other.LineNumber && this.Column == other.Column;
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return new Point(this.LineNumber, this.Column).GetHashCode();
}
public override string ToString()
{
return String.Format("({0}, {1})", this.LineNumber, this.Column);
}
public bool IsBefore(Position other)
{
// TODO:
throw new NotImplementedException();
}
public bool IsBeforeOrEqual(Position other)
{
// TODO:
throw new NotImplementedException();
}
[DefaultOverload]
public int CompareTo(Position other)
{
throw new NotImplementedException();
}
public int CompareTo(object obj)
{
if (obj is IPosition)
{
return this.CompareTo(Position.Lift(obj as IPosition));
}
throw new NotImplementedException();
}
public static int Compare(Position a, Position b)
{
return a.CompareTo(b);
}
// Can't Export static Method with same name in Windows Runtime Component
/*public static bool Equals(Position a, Position b)
{
return a.Equals(b);
}
public static bool IsBefore(Position a, Position b)
{
return a.IsBefore(b);
}
public static bool IsBeforeOrEqual(Position a, Position b)
{
return a.IsBeforeOrEqual(b);
}*/
public static bool IsIPosition(object a)
{
return a is Position;
}
public static Position Lift(IPosition pos)
{
return new Position(pos.LineNumber, pos.Column);
}
public string ToJson()
{
return String.Format("{{ \"lineNumber\": {0}, \"column\": {1} }}", this.LineNumber, this.Column);
}
}
#pragma warning restore CS1591
}

122
MonacoEditorComponent/Monaco/Range.cs

@ -0,0 +1,122 @@
using Monaco.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco
{
/// <summary>
/// Monaco Range in the editor. (startLineNumber,startColumn) is &lt;= (endLineNumber,endColumn)
/// https://microsoft.github.io/monaco-editor/api/classes/monaco.range.html
/// </summary>
#pragma warning disable CS1591
public sealed class Range : IRange
{
[JsonProperty("endColumn")]
public uint EndColumn { get; private set; }
[JsonProperty("endLineNumber")]
public uint EndLineNumber { get; private set; }
[JsonProperty("startColumn")]
public uint StartColumn { get; private set; }
[JsonProperty("startLineNumber")]
public uint StartLineNumber { get; private set; }
public Range(uint startLineNumber, uint startColumn, uint endLineNumber, uint endColumn)
{
// TODO: Range Check? Monaco doesn't seem to do it currently...
StartLineNumber = startLineNumber;
StartColumn = startColumn;
EndLineNumber = endLineNumber;
EndColumn = endColumn;
}
public Range CloneRange()
{
return new Range(StartLineNumber, StartColumn, EndLineNumber, EndColumn);
}
public Range CollapseToStart()
{
return new Range(StartColumn, StartColumn, StartLineNumber, StartColumn);
}
public Range ContainsPosition(IPosition position)
{
// TODO
throw new NotImplementedException();
}
public bool ContainsRange(IRange range)
{
// TODO
throw new NotImplementedException();
}
public bool EqualsRange(Range other)
{
return (this.StartColumn == other.StartColumn &&
this.StartLineNumber == other.StartLineNumber &&
this.EndColumn == other.EndColumn &&
this.EndLineNumber == other.EndLineNumber);
}
public Position GetEndPosition()
{
return new Position(this.EndLineNumber, this.EndColumn);
}
public Position GetStartPosition()
{
return new Position(this.StartLineNumber, this.StartColumn);
}
public Range IntersectRanges(IRange range)
{
// TODO
throw new NotImplementedException();
}
public bool IsEmpty()
{
return this.StartLineNumber == this.EndLineNumber && this.StartColumn == this.EndColumn;
}
public Range PlusRange(IRange range)
{
// TODO
throw new NotImplementedException();
}
public Range SetEndPosition(uint endLineNumber, uint endColumn)
{
return new Range(this.StartLineNumber, this.StartColumn, endLineNumber, endColumn);
}
public Range SetStartPosition(uint startLineNumber, uint startColumn)
{
return new Range(startLineNumber, startColumn, this.EndLineNumber, this.EndColumn);
}
public override string ToString()
{
return String.Format("[{0}, {1}-> {2}, {3}]", this.StartLineNumber, this.StartColumn, this.EndLineNumber, this.EndColumn);
}
public string ToJson()
{
// Right json helper for this? Or use JsonObject? Or do I want a json lib dependency?
return String.Format("{{ \"startLineNumber\": {0}, \"startColumn\": {1}, \"endLineNumber\": {2}, \"endColumn\": {3} }}", this.StartLineNumber, this.StartColumn, this.EndLineNumber, this.EndColumn);
}
public static Range Lift(IRange range)
{
return new Range(range.StartLineNumber, range.StartColumn, range.EndLineNumber, range.EndColumn);
}
// TODO: Weed out unique static method to put here.
}
#pragma warning restore CS1591
}

89
MonacoEditorComponent/Monaco/Selection.cs

@ -0,0 +1,89 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco
{
public sealed class Selection : IRange
{
[JsonProperty("startLineNumber")]
public uint StartLineNumber { get; private set; }
[JsonProperty("startColumn")]
public uint StartColumn { get; private set; }
[JsonProperty("endLineNumber")]
public uint EndLineNumber { get; private set; }
[JsonProperty("endColumn")]
public uint EndColumn { get; private set; }
[JsonProperty("positionLineNumber")]
public uint PositionLineNumber { get; private set; }
[JsonProperty("positionColumn")]
public uint PositionColumn { get; private set; }
[JsonProperty("selectionStartLineNumber")]
public uint SelectionStartLineNumber { get; private set; }
[JsonProperty("selectionStartColumn")]
public uint SelectionStartColumn { get; private set; }
[JsonIgnore]
public SelectionDirection Direction { get; private set; }
public Selection(uint selectionStartLineNumber, uint selectionStartColumn, uint positionLineNumber, uint positionColumn)
{
SelectionStartLineNumber = selectionStartLineNumber;
SelectionStartColumn = selectionStartColumn;
PositionLineNumber = positionLineNumber;
PositionColumn = positionColumn;
if (selectionStartLineNumber < positionLineNumber || (selectionStartLineNumber == positionLineNumber && selectionStartColumn <= positionColumn))
{
// Start is first
StartLineNumber = SelectionStartLineNumber;
StartColumn = SelectionStartColumn;
EndLineNumber = PositionLineNumber;
EndColumn = PositionColumn;
Direction = SelectionDirection.LTR;
}
else
{
// Flipped
StartLineNumber = PositionLineNumber;
StartColumn = PositionColumn;
EndLineNumber = SelectionStartLineNumber;
EndColumn = SelectionStartColumn;
Direction = SelectionDirection.RTL;
}
}
public SelectionDirection GetDirection()
{
return Direction;
}
public override string ToString()
{
return String.Format("[{0}, {1}-> {2}, {3}]", this.SelectionStartLineNumber, this.SelectionStartColumn, this.PositionLineNumber, this.PositionColumn);
}
public string ToJson()
{
throw new NotImplementedException();
}
}
public enum SelectionDirection
{
LTR,
RTL
}
}

19
MonacoEditorComponent/Monaco/Severity.cs

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Monaco
{
/// <summary>
/// https://microsoft.github.io/monaco-editor/api/enums/monaco.severity.html
/// </summary>
public enum Severity
{
Ignore = 0,
Info = 1,
Warning = 2,
Error = 3
}
}

241
MonacoEditorComponent/MonacoEditor.html

@ -0,0 +1,241 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<style>
html, body {
height: 100%;
margin: 0;
}
/* Just have Monaco Fill All Available Space within control */
#container {
height: 100%;
width: 100%;
}
</style>
<style id="dynamic">
</style>
</head>
<body>
<div id="container" onkeydown="keyDown(event)"></div>
<script src="ms-appx-web:///Monaco/monaco-editor/min/vs/loader.js"></script>
<script>
var editor;
var model;
var contexts = {};
var decorations = [];
var modifingSelection = false; // Supress updates to selection when making edits.
Debug.log("Starting Monaco Load");
require.config({ paths: { 'vs': 'ms-appx-web:///Monaco/monaco-editor/min/vs' }});
require(['vs/editor/editor.main'], function () {
Debug.log("Grabbing Monaco Options");
let opt = getOptions();
opt["value"] = Parent.getValue("Text");
editor = monaco.editor.create(document.getElementById('container'), opt);
model = editor.getModel();
// Listen for Content Changes
model.onDidChangeContent((event) => {
Parent.setValue("Text", model.getValue());
//console.log("buffers: " + JSON.stringify(model._buffer._pieceTree._buffers));
//console.log("commandMgr: " + JSON.stringify(model._commandManager));
//console.log("viewState:" + JSON.stringify(editor.saveViewState()));
});
// Listen for Selection Changes
editor.onDidChangeCursorSelection((event) => {
if (!modifingSelection) {
console.log(event.source);
Parent.setValue("SelectedText", model.getValueInRange(event.selection));
Parent.setValue("SelectedRange", JSON.stringify(event.selection), "Selection");
}
})
// Set theme
let theme = Parent.getJsonValue("RequestedTheme");
theme = {
"0": "Default",
"1": "Light",
"2": "Dark"
}[theme];
if (theme == "Default") {
theme = Theme.currentThemeName.toString();
}
changeTheme(theme, Theme.isHighContrast.toString());
// Update Monaco Size when we receive a window resize event
window.addEventListener("resize", () => {
editor.layout();
});
// Disable WebView Scrollbar so Monaco Scrollbar can do heavy lifting
document.body.style.overflow = 'hidden';
// Callback to Parent that we're loaded
Debug.log("Loaded Monaco");
Parent.callAction("Loaded");
});
// TODO: Split these helper functions out into separate .js/.ts files.
var registerCompletionItemProvider = function (languageId, characters) {
return monaco.languages.registerCompletionItemProvider(languageId, {
triggerCharacters: characters,
provideCompletionItems: function (model, position, token, context) {
return Parent.callEvent("CompletionItemProvider" + languageId, [JSON.stringify(position), JSON.stringify(context)]).then(result => {
if (result) {
return JSON.parse(result);
}
});
}
//// TODO: support resolve method as well.
});
}
var registerHoverProvider = function (languageId) {
return monaco.languages.registerHoverProvider(languageId, {
provideHover: function (model, position) {
return Parent.callEvent("HoverProvider" + languageId, [JSON.stringify(position)]).then(result => {
if (result) {
return JSON.parse(result);
}
});
}
});
}
var addAction = function (action) {
action.run = function (ed) {
Parent.callAction("Action" + action.id)
};
editor.addAction(action);
};
var addCommand = function (keybindingStr, handlerName, context) {
return editor.addCommand(parseInt(keybindingStr), () => {
Parent.callAction(handlerName);
}, context);
};
var createContext = function (context) {
if (context) {
contexts[context.key] = editor.createContextKey(context.key, context.defaultValue);
}
};
var updateContext = function (key, value) {
contexts[key].set(value);
}
var updateContent = function (content) {
// Need to ignore updates from us notifying of a change
if (content != model.getValue()) {
model.setValue(content);
}
};
var updateSelectedContent = function (content) {
let selection = editor.getSelection();
// Need to ignore updates from us notifying of a change
if (content != model.getValueInRange(selection)) {
modifingSelection = true;
let range = new monaco.Range(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn);
let op = { identifier: { major: 1, minor: 1 }, range, text: content, forceMoveMarkers: true };
// Make change to selection
model.pushEditOperations([], [op]);
// Update selection to new text.
selection.endLineNumber = selection.startLineNumber + content.split('\r').length - 1; // TODO: Not sure if line end is situational/platform specific... investigate more.
if (selection.startLineNumber === selection.endLineNumber) {
selection.endColumn = selection.startColumn + content.length;
} else {
selection.endColumn = content.length - content.lastIndexOf('\r');
}
// Update other selection bound for direction.
if (selection.getDirection() == monaco.SelectionDirection.LTR) {
selection.positionColumn = selection.endColumn;
selection.positionLineNumber = selection.endLineNumber;
} else {
selection.selectionStartColumn = selection.endColumn;
selection.selectionStartLineNumber = selection.endLineNumber;
}
modifingSelection = false;
editor.setSelection(selection);
}
};
var updateDecorations = function (newHighlights) {
if (newHighlights) {
decorations = editor.deltaDecorations(decorations, newHighlights);
} else {
decorations = editor.deltaDecorations(decorations, []);
}
};
var updateStyle = function (innerStyle) {
var style = document.getElementById("dynamic");
style.innerHTML = innerStyle;
};
var getOptions = function () {
let opt = null;
try {
opt = JSON.parse(Parent.getJsonValue("Options"));
} finally {
}
if (opt != null && typeof opt === "object") {
return opt;
}
return {};
};
var updateOptions = function (opt) {
if (opt != null && typeof opt === "object") {
editor.updateOptions(opt);
}
};
var updateLanguage = function (language) {
monaco.editor.setModelLanguage(model, language);
};
var changeTheme = function (theme, highcontrast) {
var newTheme = 'vs';
if (highcontrast == "True" || highcontrast == "true") {
newTheme = 'hc-black';
} else if (theme == "Dark") {
newTheme = 'vs-dark';
}
monaco.editor.setTheme(newTheme);
};
var keyDown = function (event) {
//Debug.log("Key Down:" + event.keyCode + " " + event.ctrlKey);
var result = Keyboard.keyDown(event.keyCode, event.ctrlKey, event.shiftKey, event.altKey, event.metaKey);
if (result) {
// TODO: Figure out which of these things actually works...
event.keyCode = 0;
event.cancelBubble = true;
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
return false;
}
};
</script>
</body>
</html>

212
MonacoEditorComponent/MonacoEditorComponent.csproj

@ -0,0 +1,212 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{DD49485C-2D9B-4824-B64E-52193B43E4CB}</ProjectGuid>
<OutputType>winmdobj</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Monaco</RootNamespace>
<AssemblyName>MonacoEditorComponent</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.17134.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.14393.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<AllowCrossPlatformRetargeting>false</AllowCrossPlatformRetargeting>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>bin\Release\Monaco.xml</DocumentationFile>
<GenerateLibraryLayout>false</GenerateLibraryLayout>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<PlatformTarget>x86</PlatformTarget>
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
<PlatformTarget>ARM</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
<PlatformTarget>ARM</PlatformTarget>
<OutputPath>bin\ARM\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<PlatformTarget>x64</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<DocumentationFile>bin\x64\Debug\Monaco.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<PlatformTarget>x64</PlatformTarget>
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<DocumentationFile>bin\x64\Release\Monaco.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup>
<RestoreProjectStyle>PackageReference</RestoreProjectStyle>
</PropertyGroup>
<ItemGroup>
<Compile Include="CodeEditor.cs" />
<Compile Include="CodeEditor.Methods.cs" />
<Compile Include="CodeEditor.Properties.cs" />
<Compile Include="Extensions\WebViewExtensions.cs" />
<Compile Include="Helpers\DebugLogger.cs" />
<Compile Include="Helpers\DispatcherTaskExtensions.cs" />
<Compile Include="Helpers\InterfaceToClassConverter.cs" />
<Compile Include="Helpers\KeyboardListener.cs" />
<Compile Include="Helpers\ParentAccessor.cs" />
<Compile Include="Helpers\ThemeListener.cs" />
<Compile Include="Monaco\Editor\ContextKey.cs" />
<Compile Include="Monaco\Editor\IContextKey.cs" />
<Compile Include="Monaco\Editor\IEditorConstructionOptions.cs" />
<Compile Include="Monaco\Editor\IActionDescriptor.cs" />
<Compile Include="Monaco\Editor\IEditorFindOptions.cs" />
<Compile Include="Monaco\Editor\IEditorMinimapOptions.cs" />
<Compile Include="Monaco\Editor\IEditorOptions.cs" />
<Compile Include="Monaco\Editor\IEditorScrollbarOptions.cs" />
<Compile Include="Monaco\Editor\IMarker.cs" />
<Compile Include="Monaco\Editor\IMarkerData.cs" />
<Compile Include="Monaco\Editor\IModel.cs" />
<Compile Include="Monaco\Editor\IModelDecorationOptions.cs" />
<Compile Include="Monaco\Editor\IModelDeltaDecoration.cs" />
<Compile Include="Monaco\Editor\Marker.cs" />
<Compile Include="Monaco\Editor\MarkerData.cs" />
<Compile Include="Monaco\Editor\TrackedRangeStickiness.cs" />
<Compile Include="Monaco\Editor\WordAtPosition.cs" />
<Compile Include="Monaco\Editor\IWordAtPosition.cs" />
<Compile Include="Monaco\Helpers\CssInlineStyle.cs" />
<Compile Include="Monaco\Helpers\CssLineStyle.cs" />
<Compile Include="Monaco\Helpers\CssStyleBroker.cs" />
<Compile Include="Monaco\Helpers\Json.cs" />
<Compile Include="Monaco\IMarkdownString.cs" />
<Compile Include="Monaco\IPosition.cs" />
<Compile Include="Monaco\IRange.cs" />
<Compile Include="Monaco\KeyCode.cs" />
<Compile Include="Monaco\KeyMod.cs" />
<Compile Include="Monaco\Languages\Command.cs" />
<Compile Include="Monaco\Languages\CompletionContext.cs" />
<Compile Include="Monaco\Languages\CompletionItem.cs" />
<Compile Include="Monaco\Languages\CompletionItemKind.cs" />
<Compile Include="Monaco\Languages\CompletionItemProvider.cs" />
<Compile Include="Monaco\Languages\CompletionList.cs" />
<Compile Include="Monaco\Languages\Hover.cs" />
<Compile Include="Monaco\Languages\HoverProvider.cs" />
<Compile Include="Monaco\Languages\ILanguageExtensionPoint.cs" />
<Compile Include="Monaco\LanguagesHelper.cs" />
<Compile Include="Monaco\Languages\SnippetString.cs" />
<Compile Include="Monaco\Languages\SuggestTriggerKind.cs" />
<Compile Include="Monaco\ModelHelper.cs" />
<Compile Include="Monaco\Position.cs" />
<Compile Include="Monaco\Range.cs" />
<Compile Include="Monaco\Selection.cs" />
<Compile Include="Monaco\Severity.cs" />
<Compile Include="Monaco\IUri.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>5.2.3</Version>
</PackageReference>
<PackageReference Include="Newtonsoft.Json">
<Version>10.0.3</Version>
</PackageReference>
<PackageReference Include="Nito.AsyncEx">
<Version>5.0.0-pre-05</Version>
</PackageReference>
<PackageReference Include="ObservableVector">
<Version>2.1.0</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Page Include="Themes\Generic.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
</ItemGroup>
<ItemGroup>
<Content Include="MonacoEditor.html" />
<Content Include="monaco-editor\*.*" />
<Content Include="monaco-editor\min\**\*.*" />
<Compile Include="Monaco\Helpers\CssGlyphStyle.cs" />
<EmbeddedResource Include="Properties\MonacoEditorComponent.rd.xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CodeEditor.Events.cs" />
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
<VisualStudioVersion>14.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

42
MonacoEditorComponent/MonacoEditorComponent.nuspec

@ -0,0 +1,42 @@
<?xml version="1.0"?>
<package >
<metadata>
<id>Monaco.Editor</id>
<version>0.8.1-alpha</version>
<title>Monaco Editor UWP Component</title>
<authors>Michael A. Hawker</authors>
<owners>Michael A. Hawker</owners>
<license type="expression">MIT</license>
<projectUrl>https://github.com/hawkerm/monaco-editor-uwp</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>A Windows Runtime Component wrapper around the web-based Monaco Editor</description>
<releaseNotes>Minor fixes, better .NET Native support.</releaseNotes>
<copyright>Copyright 2019</copyright>
<tags>uwp monaco editor controls</tags>
<dependencies>
<dependency id="Newtonsoft.Json" version="10.0.3"/>
<dependency id="Nito.AsyncEx" version="5.0.0-pre-05"/>
<dependency id="ObservableVector" version="2.1.0"/>
</dependencies>
</metadata>
<files>
<!-- WinMd and IntelliSense files -->
<file src="bin\Release\Monaco.pri" target="lib\uap10.0"/>
<file src="bin\Release\Monaco.winmd" target="lib\uap10.0"/>
<file src="bin\Release\Monaco.xml" target="lib\uap10.0"/>
<file src="bin\Release\MonacoEditorComponent.xr.xml" target="lib\uap10.0\Monaco"/>
<!-- XAML controls -->
<!--<file src="Themes\Generic.xaml" target="lib\uap10.0\Themes"/>
<file src="bin\Release\Themes\Generic.xbf" target="lib\uap10.0\Themes"/>-->
<file src="Themes\Generic.xaml" target="lib\uap10.0\Monaco\Themes"/>
<file src="bin\Release\Themes\Generic.xbf" target="lib\uap10.0\Monaco\Themes"/>
<!-- Dependencies -->
<file src="MonacoEditor.html" target="lib\uap10.0\Monaco"/>
<file src="monaco-editor\*" target="lib\uap10.0\Monaco\monaco-editor"/>
<file src="monaco-editor\min\**\*.*" target="lib\uap10.0\Monaco\monaco-editor\min"/>
<!-- Docs -->
<file src="..\README.md" target="content"/>
<file src="..\changelog.md" target="content"/>
<file src="..\LICENSE*" target="content"/>
</files>
</package>

29
MonacoEditorComponent/Properties/AssemblyInfo.cs

@ -0,0 +1,29 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MonacoEditorComponent")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MonacoEditorComponent")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.8.1.0")]
[assembly: AssemblyFileVersion("0.8.1.0")]
[assembly: ComVisible(false)]

21
MonacoEditorComponent/Properties/MonacoEditorComponent.rd.xml

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
<Library Name="MonacoEditorComponent">
<!-- Add your library directives here -->
<Namespace Name="Monaco.Editor" Serialize="All" Dynamic="All"/>
<Namespace Name="Monaco.Helpers" Serialize="All" Dynamic="All"/>
<Namespace Name="Monaco.Languages" Serialize="All" Dynamic="All"/>
<Namespace Name="Monaco" Serialize="All" Dynamic="All"/>
<Type Name="Monaco.Helpers.InterfaceToClassConverter{TInterface, TClass}">
<GenericParameter Name="TInterface" Dynamic="All" />
<GenericParameter Name="TClass" Dynamic="All" />
</Type>
<Type Name="Newtonsoft.Json.JsonConvert">
<Method Name="SerializeObject">
<Parameter Name="value" Serialize="Required All" />
</Method>
</Type>
</Library>
</Directives>

26
MonacoEditorComponent/Themes/generic.xaml

@ -0,0 +1,26 @@
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:monaco="using:Monaco">
<Style TargetType="monaco:CodeEditor" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="monaco:CodeEditor">
<Border
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<WebView x:Name="View"
Margin="{TemplateBinding Padding}"
Visibility="{Binding IsLoaded,RelativeSource={RelativeSource TemplatedParent}}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

344
MonacoEditorComponent/monaco-editor/CHANGELOG.md

@ -0,0 +1,344 @@
# Monaco Editor Change log
## [0.12.0] (11.04.2018)
* Special thanks to [Tim Kendrick](https://github.com/timkendrick) for contributing a webpack plugin - `monaco-editor-webpack-plugin` - now available on [npm](https://www.npmjs.com/package/monaco-editor-webpack-plugin).
### Breaking changes
* Introduced `MarkerSeverity` instead of `Severity` for markers serverity.
* Replaced `RenameProvider.resolveInitialRenameValue` with `RenameProvider.resolveRenameLocation`.
* Fixed typo in `monaco-typescript`, renamed `setMaximunWorkerIdleTime` to `setMaximumWorkerIdleTime`.
### Thank you
* [Remy Suen @rcjsuen](https://github.com/rcjsuen): Fix conversion code from MarkedString to IMarkdownString in hovers [PR monaco-css#5](https://github.com/Microsoft/monaco-css/pull/5)
* [Peng Xiao @pengx17](https://github.com/pengx17): fix an issue of `fromMarkdownString` [PR monaco-json#4](https://github.com/Microsoft/monaco-json/pull/4)
* [TJ Kells @systemsoverload](https://github.com/systemsoverload): Add rust colorization support [PR monaco-languages#31](https://github.com/Microsoft/monaco-languages/pull/31)
## [0.11.1] (15.03.2018)
- Fixes [issue #756](https://github.com/Microsoft/monaco-editor/issues/756): Can't use "Enter" key to accept an IntelliSense item
- Fixes [issue #757](https://github.com/Microsoft/monaco-editor/issues/757): TypeScript errors in `editor.api.d.ts` typings
## [0.11.0] (14.03.2018)
### New & Noteworthy
* **ESM distribution** (compatible with e.g. webpack).
* New interval tree decorations implementation.
* New piece tree text buffer implementation.
* The minimap can be placed to the left.
* Line numbers can be displayed in an interval.
* The cursor width can be customized.
* Smooth scrolling can be turned on.
* Color decorators and color picker via `DocumentColorProvider`.
### Breaking changes
* Replaced `MarkedString` with `IMarkdownString`. Source code snippets can be expressed using the GH markdown syntax.
* Renamed `IResourceEdit` to `ResourceTextEdit`.
### API changes
* Merged `IModel`, `IReadOnlyModel`, `IEditableTextModel`, `ITextModelWithMarkers`, `ITokenizedModel`, `ITextModelWithDecorations` to `ITextModel`. A type alias for `IModel` is defined for compatibility.
* Merged `ICommonCodeEditor` and `ICodeEditor` to `ICodeEditor`.
* Merged `ICommonDiffEditor` and `IDiffEditor` to `IDiffEditor`.
* `CompletionItem.documentation`, `ParameterInformation.documentation` and `SignatureInformation.documentation` can now be an `IMarkdownString`.
* Added `CompetionItem.command`, `CompletionItem.commitCharacters` and `CompletionItem.additionalTextEdits`.
* Added language configuration `folding` which can define markers for code patterns where a folding regions should be created. See for example the [Python configuration](https://github.com/Microsoft/monaco-languages/blob/d2db3faa76b741bf4ee822c403fc355c913bc46d/src/python/python.ts#L35-L41).
* Added by accident `ResourceFileEdit` (due to how `monaco.d.ts` is generated from vscode). That is not honoured by the editor, and should not be used.
### Thank you
* [Remy Suen @rcjsuen](https://github.com/rcjsuen):
* Fix a small typo in README.md [PR monaco-typescript#18](https://github.com/Microsoft/monaco-typescript/pull/18)
* Remove unused IDisposable array [PR monaco-typescript#19](https://github.com/Microsoft/monaco-typescript/pull/19)
* Add HEALTHCHECK as a Dockerfile keyword [PR monaco-languages#29](https://github.com/Microsoft/monaco-languages/pull/29)
* Add ARG as a Dockerfile keyword [PR monaco-languages#30](https://github.com/Microsoft/monaco-languages/pull/30)
* [Can Abacigil @abacigil](https://github.com/abacigil): MySQL, Postgres, Redshift and Redis Language Support [PR monaco-languages#26](https://github.com/Microsoft/monaco-languages/pull/26)
* [Matthias Kadenbach @mattes](https://github.com/mattes): Support Content-Security-Policy syntax highlighting [PR monaco-languages#27](https://github.com/Microsoft/monaco-languages/pull/27)
* [e.vakili @evakili](https://github.com/evakili): Whitespaces after # are allowed in C++ preprocessor statements [PR monaco-languages#28](https://github.com/Microsoft/monaco-languages/pull/28)
* [Pankaj Kumar Gautam @PAPERPANKS](https://github.com/PAPERPANKS): adding microsoft logo to footer [PR monaco-editor#577](https://github.com/Microsoft/monaco-editor/pull/577)
* [Dominik Moritz @domoritz](https://github.com/domoritz): Fix code in changelog [PR monaco-editor#582](https://github.com/Microsoft/monaco-editor/pull/582)
* [ItsPugle @ItsPugle](https://github.com/ItsPugle): Updating the footer to reflect change of year [PR monaco-editor#707](https://github.com/Microsoft/monaco-editor/pull/707)
* [Michael Seifert @MSeifert04](https://github.com/MSeifert04): Add linebreak for if [PR monaco-editor#726](https://github.com/Microsoft/monaco-editor/pull/726)
* [Andrew Palm @apalm](https://github.com/apalm): Fix 'Configure JSON defaults' sample [PR monaco-editor#731](https://github.com/Microsoft/monaco-editor/pull/731)
* [Niklas Mollenhauer @nikeee](https://github.com/nikeee): Fix line number API usage [PR monaco-editor#740](https://github.com/Microsoft/monaco-editor/pull/740)
* [Andre @anc](https://github.com/anc): More realistic terminal shell [PR monaco-editor#742](https://github.com/Microsoft/monaco-editor/pull/742)
* to the many others that have contributed PRs to [vscode](https://github.com/Microsoft/vscode) which have also made their way into the monaco-editor.
## [0.10.1] (16.10.2017)
- Fixes [issue #601](https://github.com/Microsoft/monaco-editor/issues/601): window.opener should be set to null to protect against malicious code
## [0.10.0] (17.08.2017)
### Breaking changes
* Removed `CodeAction`.
* Method `provideCodeActions` in `CodeActionProvider` now returns `Command[] | Thenable<Command[]>` instead of `CodeAction[] | Thenable<CodeAction[]>`, which is already removed.
### API changes
* added `monaco.editor.getModelMarkers`. Get markers for owner and/or resource.
### Notable Fixes
* No longer use CSS class `.row` for command palette to avoid CSS conflicts with Bootstrap.
* Fix Accessibility Help Dialog accessible issue on IE/Edge.
* Fix Find Widget CSS compability issues with IE11.
* Toggle Block Comment can remove extra whitespaces.
### Thank you
* [Kitson Kelly @kitsonk](https://github.com/kitsonk): Update monaco-typescript to TypeScript 2.4.1 [PR monaco-typescript#15](https://github.com/Microsoft/monaco-typescript/pull/15)
* [@duncanwerner](https://github.com/duncanwerner): Add hex number tokenization to R language [PR monaco-languages#21](https://github.com/Microsoft/monaco-languages/pull/21)
* [Remy Suen @rcjsuen](https://github.com/rcjsuen): Update Dockerfile grammar with STOPSIGNAL and SHELL instructions [PR monaco-languages#22](https://github.com/Microsoft/monaco-languages/pull/22)
* [Marlene Cota @marlenecota](https://github.com/marlenecota): Add Small Basic support [PR monaco-languages#23](https://github.com/Microsoft/monaco-languages/pull/23)
* [Ben Jacobson @bjacobso](https://github.com/bjacobso): Add LIMIT to sql keywords [PR monaco-languages#24](https://github.com/Microsoft/monaco-languages/pull/24)
* to the many others that have contributed PRs to [vscode](https://github.com/Microsoft/vscode) which have also made their way into the monaco-editor.
## [0.9.0] (03.07.2017)
### New & Noteworthy
* Minimap (on by default, use `editor.minimap` to disable it).
* Drag and Drop (on by default, use `editor.dragAndDrop` to disable it).
* Copy text with formatting.
### Accessibility
* There is a new [guide for making the editor accessible to all](https://github.com/Microsoft/monaco-editor/wiki/Accessibility-Guide-for-Integrators).
* There is a new Alt+F1 (Ctrl+F1 in IE) accessibility help panel.
* There is a new F8/Shift+F8 diff review panel in the diff editor.
* Many bugfixes, including now respecting the Windows High Contrast Theme on Edge.
### Breaking changes
* A lot has changed w.r.t. how themes work in the editor, mostly driven by the work to support theming in VS Code. `editor.updateOptions()` **no longer accepts `theme`**; the theme can be changed via the newly introduced `monaco.editor.setTheme()`. Additionally, we recommend editor colors be customized via `monaco.editor.defineTheme()` instead of via CSS -- see [sample](https://microsoft.github.io/monaco-editor/playground.html#customizing-the-appearence-exposed-colors). The color names will be stable, while the CSS class names might break at any time.
* Support for the internal snippet syntax **has been discontinued** and snippet must now use the official, TextMate-like syntax. Find its grammar and samples [here](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax).
* Changed `IModel.findMatches` to accept a list of word separators.
* Changed the shape of the `IModelContentChangedEvent` emitted via `IModel.onDidChangeContent` to **now contain a batch** of all the changes that the model had.
* No longer using `transform: translate3d`, now using `will-change: transform` for browser layer hinting. Use the `disableLayerHinting` option if you have any trouble with browser layers (bluriness or high GPU memory usage).
* Simplified wrapping settings: `wordWrap`, `wordWrapColumn` and `wordWrapMinified`.
### API changes
* added `monaco.languages.registerTypeDefinitionProvider`.
* new editor options:
* `accessibilityHelpUrl` - the url of a page to open for documentation about how to operate the editor when using a Screen Reader.
* `find.seedSearchStringFromSelection` - Ctrl+F/Cmd+F seeds search string from the editor selection.
* `find.autoFindInSelection` - Ctrl+F/Cmd+F turns on the find in selection toggle if the editor selection is multiline.
* `minimap.enabled` - enable minimap.
* `minimap.showSlider` - control when to render the minimap slider.
* `minimap.renderCharacters` - render characters or blocks in the minimap.
* `minimap.maxColumn` - maximum number of columns the minimap shows.
* `overviewRulerBorder` - toggle that the overview ruler renders a border.
* `links` - enable link detection.
* `multiCursorModifier` - change the multi cursor modifier key.
* `accessibilitySupport` - optimize the editor for use with a Screen Reader.
* `autoIndent` - automatically fix indentation when moving lines, pasting or typing.
* `dragAndDrop` - dragging and dropping editor selection within the editor.
* `occurrencesHighlight` - enable highlighting of occurences.
* `showFoldingControls` - fine-tune when the folding icons should show
* `matchBrackets` - enable bracket matching
* `letterSpacing` - configure font's letter-spacing.
### Thank you
* [Joey Marianer (@jmarianer)](https://github.com/jmarianer): Support literal interpolated strings ($@"") [PR monaco-languages#13](https://github.com/Microsoft/monaco-languages/pull/13)
* [@AndersMad](https://github.com/AndersMad): HTML Tags: Add support for dash and fix colon in end tag [PR monaco-languages#14](https://github.com/Microsoft/monaco-languages/pull/14)
* [Sandy Armstrong (@sandyarmstrong)](https://github.com/sandyarmstrong): csharp: add support for binary literals and _ as separator [PR monaco-languages#16](https://github.com/Microsoft/monaco-languages/pull/16)
* [Anton Kosyakov (@akosyakov)](https://github.com/akosyakov): Include src as a part of npm package [PR monaco-languages#17](https://github.com/Microsoft/monaco-languages/pull/17)
* [Andrew Bonventre (@andybons)](https://github.com/andybons): Fix typo: concering → concerning [PR monaco-languages#18](https://github.com/Microsoft/monaco-languages/pull/18)
* [Scott McMaster (@scottmcmaster)](https://github.com/scottmcmaster): MSDAX support [PR monaco-languages#19](https://github.com/Microsoft/monaco-languages/pull/19)
* [Luzian Serafin (@lserafin)](https://github.com/lserafin): Add Solidity [PR monaco-languages#20](https://github.com/Microsoft/monaco-languages/pull/20)
* [Kitson Kelly (@kitsonk)](https://github.com/kitsonk): Update to TypeScript 2.3.4 [PR monaco-typescript#13](https://github.com/Microsoft/monaco-typescript/pull/13)
* [Kitson Kelly (@kitsonk)](https://github.com/kitsonk): Add documentation support on hover [PR monaco-typescript#14](https://github.com/Microsoft/monaco-typescript/pull/14)
* [@replacepreg](https://github.com/replacepreg): Updating date at footer [PR monaco-editor#409](https://github.com/Microsoft/monaco-editor/pull/409)
* [Aarin Smith (@aarinsmith)](https://github.com/aarinsmith): Fixed spelling error in README.md:85 'instantion' -> 'instantiation' [PR monaco-editor#440](https://github.com/Microsoft/monaco-editor/pull/440)
* to the many others that have contributed PRs to [`vscode`](https://github.com/Microsoft/vscode) which have also made their way into the `monaco-editor`.
---
## [0.8.3] (03.03.2017)
- Fixes an issue in monaco-typescript where it would attempt to validate a disposed model.
---
## [0.8.2] (01.03.2017)
- Fixes the following regressions:
- [issue #385](https://github.com/Microsoft/monaco-editor/issues/385): Cannot add action to the left-hand-side of the diff editor
- [issue #386](https://github.com/Microsoft/monaco-editor/issues/386): Shortcuts for actions added via editor.addAction don't show up in the Command Palette
- [issue #387](https://github.com/Microsoft/monaco-editor/issues/387): Cannot change diff editor to a custom theme based on high contrast
---
## [0.8.1] (27.01.2017)
- CSS/JSON/HTML language supports updated:
- CSS: Support for @apply
- SCSS: Map support
- New HTML formatter options: unformatedContent, wrapAttributes
- Fixed issue where the editor was throwing in Safari due to `Intl` missing.
- Fixed multiple issues where the editor would not position the cursor correctly when using browser zooming.
### API
- Added `disableMonospaceOptimizations` editor option that can be used in case browser zooming exposes additional issues.
- Added `formatOnPaste` editor option.
- Added `IActionDescriptor.precondition`.
- **Breaking change**: renamed `registerTypeDefinitionProvider` to `registerImplementationProvider` and associated types.
---
## [0.8.0] (18.01.2017)
- This release has been brewing for a while and comes with quite a number of important changes.
- There are many bugfixes and speed/memory usage improvements.
- Now shipping TypeScript v2.1.5 in `monaco-typescript` (JS and TS language support).
### No longer supporting IE9 and IE10
- we have not made the editor fail on purpose in these browsers, but we have removed IE9/IE10 targeted workarounds from our codebase;
- now using **Typed Arrays** in a number of key places resulting in considerable speed boosts and lower memory consumption.
### Monarch Tokenizer
- Monarch states are now memoized up to a depth of 5. This results in considerable memory improvements for files with many lines.
- Speed improvements to Monarch tokenizer that resulted in one **breaking change**:
- when entering an embedded mode (i.e. `nextEmbedded`), the state ending up in must immediately contain a `nextEmbedded: "@pop"` rule. This helps in quickly figuring out where the embedded mode should be left. The editor will throw an error if the Monarch grammar does not respect this condition.
### Tokens are styled in JS (not in CSS anymore)
- This is a **breaking change**
- Before, token types would be rendered on the `span` node of text, and CSS rules would match token types and assign styling to them (i.e. color, boldness, etc.to style tokens)
- To enable us to build something like a minimap, we need to know the text color in JavaScript, and we have therefore moved the token style matching all to JavaScript. In the future, we foresee that even decorations will have to define their color in JavaScript.
- It is possible to create a custom theme via a new API method `monaco.editor.defineTheme()` and the playground contains a sample showing how that works.
- Token types can be inspected via `F1` > `Developer: Inspect tokens`. This will bring up a widget showing the token type and the applied styles.
### API changes:
#### Namespaces
- added `monaco.editor.onDidCreateEditor` that will be fired whenever an editor is created (will fire even for a diff editor, with the two editors that a diff editor consists of).
- added `monaco.editor.tokenize` that returns logical tokens (before theme matching, as opposed to `monaco.editor.colorize`).
- added `monaco.languages.registerTypeDefinitionProvider`
#### Models
- removed `IModel.getMode()`.
- structural changes in the events `IModelLanguageChangedEvent`, `IModelDecorationsChangedEvent` and `IModelTokensChangedEvent`;
- changed `IModel.findMatches`, `IModel.findNextMatch` and `IModel.findPreviousMatch` to be able to capture matches while searching.
#### Editors
- `ICodeEditor.addAction` and `IDiffEditor.addAction` now return an `IDisposable` to be able to remove a previously added action.
- renamed `ICodeEditor.onDidChangeModelMode ` to `ICodeEditor.onDidChangeModelLanguage`;
- `ICodeEditor.executeEdits` can now take resulting selection for better undo/redo stack management;
- added `ICodeEditor.getTargetAtClientPoint(clientX, clientY)` to be able to do hit testing.
- added `IViewZone.marginDomNode` to be able to insert a dom node in the margin side of a view zone.
- settings:
- `lineDecorationsWidth` can now take a value in the form of `"1.2ch"` besides the previous accepted number (in px)
- `renderLineHighlight` can now take a value in the set `'none' | 'gutter' | 'line' | 'all'`.
- added `fixedOverflowWidgets` to render overflowing content widgets as `'fixed'` (defaults to false)
- added `acceptSuggestionOnCommitCharacter` to accept suggestions on provider defined characters (defaults to true)
- added `emptySelectionClipboard` - copying without a selection copies the current line (defaults to true)
- added `suggestFontSize` - the font size for the suggest widget
- added `suggestLineHeight` - the line height for the suggest widget
- diff editor settings:
- added `renderIndicators` - Render +/- indicators for added/deleted changes. (defaults to true)
### Thank you
* [Nico Tonozzi (@nicot)](https://github.com/nicot): Register React file extensions [PR monaco-typescript#12](https://github.com/Microsoft/monaco-typescript/pull/12)
* [Jeong Woo Chang (@inspiredjw)](https://github.com/inspiredjw): Cannot read property 'uri' of null fix [PR vscode#13263](https://github.com/Microsoft/vscode/pull/13263)
* [Jan Pilzer(@Hirse)](https://github.com/Hirse): Add YAML samples [PR monaco-editor#242](https://github.com/Microsoft/monaco-editor/pull/242)
---
## [0.7.1] (07.10.2016)
- Bugfixes in monaco-html, including fixing formatting.
---
## [0.7.0] (07.10.2016)
- Adopted TypeScript 2.0 in all the repos (also reflected in `monaco.d.ts`).
- Added YAML colorization support.
- Brought back the ability to use `editor.addAction()` and have the action show in the context menu.
- Web workers now get a nice label next to the script name.
### API changes:
- settings:
- new values for `lineNumbers`: `'on' | 'off' | 'relative'`
- new values for `renderWhitespace`: `'none' | 'boundary' | 'all'`
- removed `model.setMode()`, as `IMode` will soon disappear from the API.
### Debt work
- Removed html, razor, php and handlebars from `monaco-editor-core`:
- the `monaco-editor-core` is now finally language agnostic.
- coloring for html, razor, php and handlebars is now coming in from `monaco-languages`.
- language smarts for html, razor and handlebars now comes from `monaco-html`.
- Packaging improvements:
- thanks to the removal of the old languages from `monaco-editor-core`, we could improve the bundling and reduce the number of .js files we ship.
- we are thinking about simplifying this further in the upcoming releases.
### Thank you
* [Sandy Armstrong (@sandyarmstrong)](https://github.com/sandyarmstrong): csharp: allow styling #r/#load [PR monaco-languages#9](https://github.com/Microsoft/monaco-languages/pull/9)
* [Nico Tonozzi (@nicot)](https://github.com/nicot): Go: add raw string literal syntax [PR monaco-languages#10](https://github.com/Microsoft/monaco-languages/pull/10)
* [Jason Killian (@JKillian)](https://github.com/JKillian): Add vmin and vmax CSS units [PR monaco-languages#11](https://github.com/Microsoft/monaco-languages/pull/11)
* [Jan Pilzer (@Hirse)](https://github.com/Hirse): YAML colorization [PR monaco-languages#12](https://github.com/Microsoft/monaco-languages/pull/12)
* [Sam El-Husseini (@microsoftsam)](https://github.com/microsoftsam): Using Cmd+Scroll to zoom on a mac [PR vscode#12477](https://github.com/Microsoft/vscode/pull/12477)
---
## [0.6.1] (06.09.2016)
- Fixed regression where `editor.addCommand` was no longer working.
---
## [0.6.0] (05.09.2016)
- This will be the last release that contains specific IE9 and IE10 fixes/workarounds. We will begin cleaning our code-base and remove them.
- We plan to adopt TypeScript 2.0, so this will be the last release where `monaco.d.ts` is generated by TypeScript 1.8.
- `javascript` and `typescript` language services:
- exposed API to get to the underlying language service.
- fixed a bug that prevented modifying `extraLibs`.
- Multiple improvements/bugfixes to the `css`, `less`, `scss` and `json` language services.
- Added support for ATS/Postiats.
### API changes:
- settings:
- new: `mouseWheelZoom`, `wordWrap`, `snippetSuggestions`, `tabCompletion`, `wordBasedSuggestions`, `renderControlCharacters`, `renderLineHighlight`, `fontWeight`.
- removed: `tabFocusMode`, `outlineMarkers`.
- renamed: `indentGuides` -> `renderIndentGuides`, `referenceInfos` -> `codeLens`
- added `editor.pushUndoStop()` to explicitly push an undo stop
- added `suppressMouseDown` to `IContentWidget`
- added optional `resolveLink` to `ILinkProvider`
- removed `enablement`, `contextMenuGroupId` from `IActionDescriptor`
- removed exposed constants for editor context keys.
### Notable bugfixes:
- Icons missing in the find widget in IE11 [#148](https://github.com/Microsoft/monaco-editor/issues/148)
- Multiple context menu issues
- Multiple clicking issues in IE11/Edge ([#137](https://github.com/Microsoft/monaco-editor/issues/137), [#118](https://github.com/Microsoft/monaco-editor/issues/118))
- Multiple issues with the high-contrast theme.
- Multiple IME issues in IE11, Edge and Firefox.
### Thank you
* [Pavel Kolev (@paveldk)](https://github.com/paveldk): Fix sending message to terminated worker [PR vscode#10833](https://github.com/Microsoft/vscode/pull/10833)
* [Pavel Kolev (@paveldk)](https://github.com/paveldk): Export getTypeScriptWorker & getJavaScriptWorker to monaco.languages.typescript [PR monaco-typescript#8](https://github.com/Microsoft/monaco-typescript/pull/8)
* [Sandy Armstrong (@sandyarmstrong)](https://github.com/sandyarmstrong): Support CompletionItemKind.Method. [PR vscode#10225](https://github.com/Microsoft/vscode/pull/10225)
* [Sandy Armstrong (@sandyarmstrong)](https://github.com/sandyarmstrong): Fix show in IE11 [PR vscode#10309](https://github.com/Microsoft/vscode/pull/10309)
* [Sandy Armstrong (@sandyarmstrong)](https://github.com/sandyarmstrong): Correct docs for IEditorScrollbarOptions.useShadows [PR vscode#11312](https://github.com/Microsoft/vscode/pull/11312)
* [Artyom Shalkhakov (@ashalkhakov)](https://github.com/ashalkhakov): Adding support for ATS/Postiats [PR monaco-languages#5](https://github.com/Microsoft/monaco-languages/pull/5)
---
## [0.5.1] (24.06.2016)
- Fixed mouse handling in IE
---
## [0.5.0] (24.06.2016)
### Breaking changes
- `monaco.editor.createWebWorker` now loads the AMD module and calls `create` and passes in as first argument a context of type `monaco.worker.IWorkerContext` and as second argument the `initData`. This **breaking change** was needed to allow handling the case of misconfigured web workers (running on a file protocol or the cross-domain case)
- the `CodeActionProvider.provideCodeActions` now gets passed in a `CodeActionContext` that contains the markers at the relevant range.
- the `hoverMessage` of a decoration is now a `MarkedString | MarkedString[]`
- the `contents` of a `Hover` returned by a `HoverProvider` is now a `MarkedString | MarkedString[]`
- removed deprecated `IEditor.onDidChangeModelRawContent`, `IModel.onDidChangeRawContent`
### Notable fixes
- Broken configurations (loading from `file://` or misconfigured cross-domain loading) now load the web worker code in the UI thread. This caused a **breaking change** in the behaviour of `monaco.editor.createWebWorker`
- The right-pointing mouse pointer is oversized in high DPI - [issue](https://github.com/Microsoft/monaco-editor/issues/5)
- The editor functions now correctly when hosted inside a `position:fixed` element.
- Cross origin configuration is now picked up (as advertised in documentation from MonacoEnvironment)
[0.11.1]: https://github.com/Microsoft/monaco-editor/compare/v0.11.0...v0.11.1
[0.11.0]: https://github.com/Microsoft/monaco-editor/compare/v0.10.1...v0.11.0
[0.10.1]: https://github.com/Microsoft/monaco-editor/compare/v0.10.0...v0.10.1
[0.10.0]: https://github.com/Microsoft/monaco-editor/compare/v0.9.0...v0.10.0
[0.9.0]: https://github.com/Microsoft/monaco-editor/compare/v0.8.3...v0.9.0
[0.8.3]: https://github.com/Microsoft/monaco-editor/compare/v0.8.2...v0.8.3
[0.8.2]: https://github.com/Microsoft/monaco-editor/compare/v0.8.1...v0.8.2
[0.8.1]: https://github.com/Microsoft/monaco-editor/compare/v0.8.0...v0.8.1
[0.6.1]: https://github.com/Microsoft/monaco-editor/compare/v0.6.0...v0.6.1
[0.6.0]: https://github.com/Microsoft/monaco-editor/compare/v0.5.1...v0.6.0
[0.5.1]: https://github.com/Microsoft/monaco-editor/compare/v0.5.0...v0.5.1

21
MonacoEditorComponent/monaco-editor/LICENSE

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 - present Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

98
MonacoEditorComponent/monaco-editor/README.md

@ -0,0 +1,98 @@
# Monaco Editor
The Monaco Editor is the code editor that powers [VS Code](https://github.com/Microsoft/vscode), a good page describing the code editor's features is [here](https://code.visualstudio.com/docs/editor/editingevolved).
![image](https://cloud.githubusercontent.com/assets/5047891/19600675/5eaae9e6-97a6-11e6-97ad-93903167d8ba.png)
## Try it out
See the editor in action [on the website](https://microsoft.github.io/monaco-editor/index.html).
## Installing
```
$ npm install monaco-editor
```
You will get:
* inside `esm`: ESM version of the editor (compatible with e.g. webpack)
* inside `dev`: AMD bundled, not minified
* inside `min`: AMD bundled, and minified
* inside `min-maps`: source maps for `min`
* `monaco.d.ts`: this specifies the API of the editor (this is what is actually versioned, everything else is considered private and might break with any release).
It is recommended to develop against the `dev` version, and in production to use the `min` version.
## Documentation
* Learn how to integrate the editor with these [complete samples](https://github.com/Microsoft/monaco-editor-samples/).
* [Integrate the AMD version](./docs/integrate-amd.md).
* [Integrate the AMD version cross-domain](./docs/integrate-amd-cross.md)
* [Integrate the ESM version](./docs/integrate-esm.md)
* Learn how to use the editor API and try out your own customizations in the [playground](https://microsoft.github.io/monaco-editor/playground.html).
* Explore the [API docs](https://microsoft.github.io/monaco-editor/api/index.html) or read them straight from [`monaco.d.ts`](https://github.com/Microsoft/monaco-editor/blob/master/website/playground/monaco.d.ts.txt).
* Read [this guide](https://github.com/Microsoft/monaco-editor/wiki/Accessibility-Guide-for-Integrators) to ensure the editor is accessible to all your users!
* Create a Monarch tokenizer for a new programming language [in the Monarch playground](https://microsoft.github.io/monaco-editor/monarch.html).
* Ask questions on [StackOverflow](https://stackoverflow.com/questions/tagged/monaco-editor)!
* Search open and closed issues, there are a lot of tips in there!
## Issues
Create issues in this repository for anything Monaco Editor related. Always mention **the version** of the editor when creating issues and **the browser** you're having trouble in. Please search for existing issues to avoid duplicates.
## Known issues
In IE 11, the editor must be completely surrounded in the body element, otherwise the hit testing we do for mouse operations does not work. You can inspect this using F12 and clicking on the body element and confirm that visually it surrounds the editor.
## FAQ
❓ **What is the relationship between VS Code and the Monaco Editor?**
The Monaco Editor is generated straight from VS Code's sources with some shims around services the code needs to make it run in a web browser outside of its home.
❓ **What is the relationship between VS Code's version and the Monaco Editor's version?**
None. The Monaco Editor is a library and it reflects directly the source code.
❓ **I've written an extension for VS Code, will it work on the Monaco Editor in a browser?**
No.
> Note: If the extension is fully based on the [LSP](https://microsoft.github.io/language-server-protocol/) and if the language server is authored in JavaScript, then it would be possible.
❓ **Why all these web workers and why should I care?**
Language services create web workers to compute heavy stuff outside the UI thread. They cost hardly anything in terms of resource overhead and you shouldn't worry too much about them, as long as you get them to work (see above the cross-domain case).
❓ **What is this `loader.js`? Can I use `require.js`?**
It is an AMD loader that we use in VS Code. Yes.
❓ **I see the warning "Could not create web worker". What should I do?**
HTML5 does not allow pages loaded on `file://` to create web workers. Please load the editor with a web server on `http://` or `https://` schemes. Please also see the cross domain case above.
❓ **Is the editor supported in mobile browsers or mobile web app frameworks?**
No.
❓ **Why doesn't the editor support TextMate grammars?**
* all the regular expressions in TM grammars are based on [oniguruma](https://github.com/kkos/oniguruma), a regular expression library written in C.
* the only way to interpret the grammars and get anywhere near original fidelity is to use the exact same regular expression library (with its custom syntax constructs)
* in VSCode, our runtime is node.js and we can use a node native module that exposes the library to JavaScript
* in Monaco, we are constrained to a browser environment where we cannot do anything similar
* we have experimented with Emscripten to compile the C library to asm.js, but performance was very poor even in Firefox (10x slower) and extremely poor in Chrome (100x slower).
* we can revisit this once WebAssembly gets traction in the major browsers, but we will still need to consider the browser matrix we support. i.e. if we support IE11 and only Edge will add WebAssembly support, what will the experience be in IE11, etc.
## Development setup
Please see [CONTRIBUTING](./CONTRIBUTING.md)
## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
## License
[MIT](https://github.com/Microsoft/monaco-editor/blob/master/LICENSE.md)

278
MonacoEditorComponent/monaco-editor/ThirdPartyNotices.txt

@ -0,0 +1,278 @@
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
Do Not Translate or Localize
This project incorporates components from the projects listed below. The original copyright notices and the licenses
under which Microsoft received such components are set forth below. Microsoft reserves all rights not expressly granted
herein, whether by implication, estoppel or otherwise.
%% winjs version 4.4.0 (https://github.com/winjs/winjs)
=========================================
WinJS
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
END OF winjs NOTICES AND INFORMATION
%% string_scorer version 0.1.20 (https://github.com/joshaven/string_score)
=========================================
This software is released under the MIT license:
Copyright (c) Joshaven Potter
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
END OF string_scorer NOTICES AND INFORMATION
%% chjj-marked NOTICES AND INFORMATION BEGIN HERE
=========================================
The MIT License (MIT)
Copyright (c) 2011-2014, Christopher Jeffrey (https://github.com/chjj/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=========================================
END OF chjj-marked NOTICES AND INFORMATION
%% typescript version 2.7.2 (https://github.com/Microsoft/TypeScript)
=========================================
Copyright (c) Microsoft Corporation. All rights reserved.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
=========================================
END OF typescript NOTICES AND INFORMATION
%% HTML 5.1 W3C Working Draft version 08 October 2015 (http://www.w3.org/TR/2015/WD-html51-20151008/)
=========================================
Copyright © 2015 W3C® (MIT, ERCIM, Keio, Beihang). This software or document includes material copied
from or derived from HTML 5.1 W3C Working Draft (http://www.w3.org/TR/2015/WD-html51-20151008/.)
THIS DOCUMENT IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT
NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE CONTENTS OF
THE DOCUMENT ARE SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY
PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE
DOCUMENT OR THE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF.
The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to this document or its contents
without specific, written prior permission. Title to copyright in this document will at all times remain with copyright holders.
=========================================
END OF HTML 5.1 W3C Working Draft NOTICES AND INFORMATION
%% JS Beautifier version 1.6.2 (https://github.com/beautify-web/js-beautify)
=========================================
The MIT License (MIT)
Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
END OF js-beautify NOTICES AND INFORMATION
%% Ionic documentation version 1.2.4 (https://github.com/driftyco/ionic-site)
=========================================
Copyright Drifty Co. http://drifty.com/.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
=========================================
END OF Ionic documentation NOTICES AND INFORMATION
%% vscode-swift version 0.0.1 (https://github.com/owensd/vscode-swift)
=========================================
The MIT License (MIT)
Copyright (c) 2015 David Owens II
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=========================================
END OF vscode-swift NOTICES AND INFORMATION

5311
MonacoEditorComponent/monaco-editor/dev/bundleInfo.json

File diff suppressed because it is too large diff.load

1691
MonacoEditorComponent/monaco-editor/dev/nls.metadata.json

File diff suppressed because it is too large diff.load

11890
MonacoEditorComponent/monaco-editor/dev/vs/base/worker/workerMain.js

File diff suppressed because it is too large diff.load

1
MonacoEditorComponent/monaco-editor/dev/vs/base/worker/workerMain.js.map

diff.file_suppressed_line_too_long

35
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/_.contribution.js

@ -0,0 +1,35 @@
define(["require", "exports", "vs/editor/editor.api"], function (require, exports) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
var languageDefinitions = {};
function _loadLanguage(languageId) {
var loader = languageDefinitions[languageId].loader;
return loader().then(function (mod) {
_monaco.languages.setMonarchTokensProvider(languageId, mod.language);
_monaco.languages.setLanguageConfiguration(languageId, mod.conf);
});
}
var languagePromises = {};
function loadLanguage(languageId) {
if (!languagePromises[languageId]) {
languagePromises[languageId] = _loadLanguage(languageId);
}
return languagePromises[languageId];
}
exports.loadLanguage = loadLanguage;
function registerLanguage(def) {
var languageId = def.id;
languageDefinitions[languageId] = def;
_monaco.languages.register(def);
_monaco.languages.onLanguage(languageId, function () {
loadLanguage(languageId);
});
}
exports.registerLanguage = registerLanguage;
});

16
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/bat/bat.contribution.js

@ -0,0 +1,16 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'bat',
extensions: ['.bat', '.cmd'],
aliases: ['Batch', 'bat'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./bat'], resolve_1, reject_1); })); }
});
});

99
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/bat/bat.js

@ -0,0 +1,99 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.conf = {
comments: {
lineComment: 'REM'
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
],
surroundingPairs: [
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
],
folding: {
markers: {
start: new RegExp("^\\s*(::\\s*|REM\\s+)#region"),
end: new RegExp("^\\s*(::\\s*|REM\\s+)#endregion")
}
}
};
exports.language = {
defaultToken: '',
ignoreCase: true,
tokenPostfix: '.bat',
brackets: [
{ token: 'delimiter.bracket', open: '{', close: '}' },
{ token: 'delimiter.parenthesis', open: '(', close: ')' },
{ token: 'delimiter.square', open: '[', close: ']' }
],
keywords: /call|defined|echo|errorlevel|exist|for|goto|if|pause|set|shift|start|title|not|pushd|popd/,
// we include these common regular expressions
symbols: /[=><!~?&|+\-*\/\^;\.,]+/,
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
// The main tokenizer for our languages
tokenizer: {
root: [
[/^(\s*)(rem(?:\s.*|))$/, ['', 'comment']],
[/(\@?)(@keywords)(?!\w)/, [{ token: 'keyword' }, { token: 'keyword.$2' }]],
// whitespace
[/[ \t\r\n]+/, ''],
// blocks
[/setlocal(?!\w)/, 'keyword.tag-setlocal'],
[/endlocal(?!\w)/, 'keyword.tag-setlocal'],
// words
[/[a-zA-Z_]\w*/, ''],
// labels
[/:\w*/, 'metatag'],
// variables
[/%[^%]+%/, 'variable'],
[/%%[\w]+(?!\w)/, 'variable'],
// punctuations
[/[{}()\[\]]/, '@brackets'],
[/@symbols/, 'delimiter'],
// numbers
[/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
[/0[xX][0-9a-fA-F_]*[0-9a-fA-F]/, 'number.hex'],
[/\d+/, 'number'],
// punctuation: after number because of .\d floats
[/[;,.]/, 'delimiter'],
// strings:
[/"/, 'string', '@string."'],
[/'/, 'string', '@string.\''],
],
string: [
[/[^\\"'%]+/, {
cases: {
'@eos': { token: 'string', next: '@popall' },
'@default': 'string'
}
}],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/%[\w ]+%/, 'variable'],
[/%%[\w]+(?!\w)/, 'variable'],
[/["']/, {
cases: {
'$#==$S2': { token: 'string', next: '@pop' },
'@default': 'string'
}
}],
[/$/, 'string', '@popall']
],
}
};
});

17
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/coffee/coffee.contribution.js

@ -0,0 +1,17 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'coffeescript',
extensions: ['.coffee'],
aliases: ['CoffeeScript', 'coffeescript', 'coffee'],
mimetypes: ['text/x-coffeescript', 'text/coffeescript'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./coffee'], resolve_1, reject_1); })); }
});
});

173
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/coffee/coffee.js

@ -0,0 +1,173 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.conf = {
wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#%\^\&\*\(\)\=\$\-\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
comments: {
blockComment: ['###', '###'],
lineComment: '#'
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
],
folding: {
markers: {
start: new RegExp("^\\s*#region\\b"),
end: new RegExp("^\\s*#endregion\\b")
}
}
};
exports.language = {
defaultToken: '',
ignoreCase: true,
tokenPostfix: '.coffee',
brackets: [
{ open: '{', close: '}', token: 'delimiter.curly' },
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' }
],
regEx: /\/(?!\/\/)(?:[^\/\\]|\\.)*\/[igm]*/,
keywords: [
'and', 'or', 'is', 'isnt', 'not', 'on', 'yes', '@', 'no', 'off',
'true', 'false', 'null', 'this',
'new', 'delete', 'typeof', 'in', 'instanceof',
'return', 'throw', 'break', 'continue', 'debugger',
'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally',
'class', 'extends', 'super',
'undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when'
],
// we include these common regular expressions
symbols: /[=><!~?&%|+\-*\/\^\.,\:]+/,
escapes: /\\(?:[abfnrtv\\"'$]|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
// The main tokenizer for our languages
tokenizer: {
root: [
// identifiers and keywords
[/\@[a-zA-Z_]\w*/, 'variable.predefined'],
[/[a-zA-Z_]\w*/, {
cases: {
'this': 'variable.predefined',
'@keywords': { token: 'keyword.$0' },
'@default': ''
}
}],
// whitespace
[/[ \t\r\n]+/, ''],
// Comments
[/###/, 'comment', '@comment'],
[/#.*$/, 'comment'],
// regular expressions
['///', { token: 'regexp', next: '@hereregexp' }],
[/^(\s*)(@regEx)/, ['', 'regexp']],
[/(\()(\s*)(@regEx)/, ['@brackets', '', 'regexp']],
[/(\,)(\s*)(@regEx)/, ['delimiter', '', 'regexp']],
[/(\=)(\s*)(@regEx)/, ['delimiter', '', 'regexp']],
[/(\:)(\s*)(@regEx)/, ['delimiter', '', 'regexp']],
[/(\[)(\s*)(@regEx)/, ['@brackets', '', 'regexp']],
[/(\!)(\s*)(@regEx)/, ['delimiter', '', 'regexp']],
[/(\&)(\s*)(@regEx)/, ['delimiter', '', 'regexp']],
[/(\|)(\s*)(@regEx)/, ['delimiter', '', 'regexp']],
[/(\?)(\s*)(@regEx)/, ['delimiter', '', 'regexp']],
[/(\{)(\s*)(@regEx)/, ['@brackets', '', 'regexp']],
[/(\;)(\s*)(@regEx)/, ['', '', 'regexp']],
// delimiters
[/}/, {
cases: {
'$S2==interpolatedstring': { token: 'string', next: '@pop' },
'@default': '@brackets'
}
}],
[/[{}()\[\]]/, '@brackets'],
[/@symbols/, 'delimiter'],
// numbers
[/\d+[eE]([\-+]?\d+)?/, 'number.float'],
[/\d+\.\d+([eE][\-+]?\d+)?/, 'number.float'],
[/0[xX][0-9a-fA-F]+/, 'number.hex'],
[/0[0-7]+(?!\d)/, 'number.octal'],
[/\d+/, 'number'],
// delimiter: after number because of .\d floats
[/[,.]/, 'delimiter'],
// strings:
[/"""/, 'string', '@herestring."""'],
[/'''/, 'string', '@herestring.\'\'\''],
[/"/, {
cases: {
'@eos': 'string',
'@default': { token: 'string', next: '@string."' }
}
}],
[/'/, {
cases: {
'@eos': 'string',
'@default': { token: 'string', next: '@string.\'' }
}
}],
],
string: [
[/[^"'\#\\]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\./, 'string.escape.invalid'],
[/\./, 'string.escape.invalid'],
[/#{/, {
cases: {
'$S2=="': { token: 'string', next: 'root.interpolatedstring' },
'@default': 'string'
}
}],
[/["']/, {
cases: {
'$#==$S2': { token: 'string', next: '@pop' },
'@default': 'string'
}
}],
[/#/, 'string']
],
herestring: [
[/("""|''')/, {
cases: {
'$1==$S2': { token: 'string', next: '@pop' },
'@default': 'string'
}
}],
[/[^#\\'"]+/, 'string'],
[/['"]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\./, 'string.escape.invalid'],
[/#{/, { token: 'string.quote', next: 'root.interpolatedstring' }],
[/#/, 'string']
],
comment: [
[/[^#]+/, 'comment',],
[/###/, 'comment', '@pop'],
[/#/, 'comment'],
],
hereregexp: [
[/[^\\\/#]+/, 'regexp'],
[/\\./, 'regexp'],
[/#.*$/, 'comment'],
['///[igm]*', { token: 'regexp', next: '@pop' }],
[/\//, 'regexp'],
],
},
};
});

22
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/cpp/cpp.contribution.js

@ -0,0 +1,22 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'c',
extensions: ['.c', '.h'],
aliases: ['C', 'c'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./cpp'], resolve_1, reject_1); })); }
});
__contribution_1.registerLanguage({
id: 'cpp',
extensions: ['.cpp', '.cc', '.cxx', '.hpp', '.hh', '.hxx'],
aliases: ['C++', 'Cpp', 'cpp'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_2, reject_2) { require(['./cpp'], resolve_2, reject_2); })); }
});
});

325
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/cpp/cpp.js

@ -0,0 +1,325 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.conf = {
comments: {
lineComment: '//',
blockComment: ['/*', '*/'],
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '[', close: ']' },
{ open: '{', close: '}' },
{ open: '(', close: ')' },
{ open: '\'', close: '\'', notIn: ['string', 'comment'] },
{ open: '"', close: '"', notIn: ['string'] },
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
],
folding: {
markers: {
start: new RegExp("^\\s*#pragma\\s+region\\b"),
end: new RegExp("^\\s*#pragma\\s+endregion\\b")
}
}
};
exports.language = {
defaultToken: '',
tokenPostfix: '.cpp',
brackets: [
{ token: 'delimiter.curly', open: '{', close: '}' },
{ token: 'delimiter.parenthesis', open: '(', close: ')' },
{ token: 'delimiter.square', open: '[', close: ']' },
{ token: 'delimiter.angle', open: '<', close: '>' }
],
keywords: [
'abstract',
'amp',
'array',
'auto',
'bool',
'break',
'case',
'catch',
'char',
'class',
'const',
'constexpr',
'const_cast',
'continue',
'cpu',
'decltype',
'default',
'delegate',
'delete',
'do',
'double',
'dynamic_cast',
'each',
'else',
'enum',
'event',
'explicit',
'export',
'extern',
'false',
'final',
'finally',
'float',
'for',
'friend',
'gcnew',
'generic',
'goto',
'if',
'in',
'initonly',
'inline',
'int',
'interface',
'interior_ptr',
'internal',
'literal',
'long',
'mutable',
'namespace',
'new',
'noexcept',
'nullptr',
'__nullptr',
'operator',
'override',
'partial',
'pascal',
'pin_ptr',
'private',
'property',
'protected',
'public',
'ref',
'register',
'reinterpret_cast',
'restrict',
'return',
'safe_cast',
'sealed',
'short',
'signed',
'sizeof',
'static',
'static_assert',
'static_cast',
'struct',
'switch',
'template',
'this',
'thread_local',
'throw',
'tile_static',
'true',
'try',
'typedef',
'typeid',
'typename',
'union',
'unsigned',
'using',
'virtual',
'void',
'volatile',
'wchar_t',
'where',
'while',
'_asm',
'_based',
'_cdecl',
'_declspec',
'_fastcall',
'_if_exists',
'_if_not_exists',
'_inline',
'_multiple_inheritance',
'_pascal',
'_single_inheritance',
'_stdcall',
'_virtual_inheritance',
'_w64',
'__abstract',
'__alignof',
'__asm',
'__assume',
'__based',
'__box',
'__builtin_alignof',
'__cdecl',
'__clrcall',
'__declspec',
'__delegate',
'__event',
'__except',
'__fastcall',
'__finally',
'__forceinline',
'__gc',
'__hook',
'__identifier',
'__if_exists',
'__if_not_exists',
'__inline',
'__int128',
'__int16',
'__int32',
'__int64',
'__int8',
'__interface',
'__leave',
'__m128',
'__m128d',
'__m128i',
'__m256',
'__m256d',
'__m256i',
'__m64',
'__multiple_inheritance',
'__newslot',
'__nogc',
'__noop',
'__nounwind',
'__novtordisp',
'__pascal',
'__pin',
'__pragma',
'__property',
'__ptr32',
'__ptr64',
'__raise',
'__restrict',
'__resume',
'__sealed',
'__single_inheritance',
'__stdcall',
'__super',
'__thiscall',
'__try',
'__try_cast',
'__typeof',
'__unaligned',
'__unhook',
'__uuidof',
'__value',
'__virtual_inheritance',
'__w64',
'__wchar_t'
],
operators: [
'=', '>', '<', '!', '~', '?', ':',
'==', '<=', '>=', '!=', '&&', '||', '++', '--',
'+', '-', '*', '/', '&', '|', '^', '%', '<<',
'>>', '>>>', '+=', '-=', '*=', '/=', '&=', '|=',
'^=', '%=', '<<=', '>>=', '>>>='
],
// we include these common regular expressions
symbols: /[=><!~?:&|+\-*\/\^%]+/,
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
integersuffix: /(ll|LL|u|U|l|L)?(ll|LL|u|U|l|L)?/,
floatsuffix: /[fFlL]?/,
encoding: /u|u8|U|L/,
// The main tokenizer for our languages
tokenizer: {
root: [
// C++ 11 Raw String
[/@encoding?R\"(?:([^ ()\\\t]*))\(/, { token: 'string.raw.begin', next: '@raw.$1' }],
// identifiers and keywords
[/[a-zA-Z_]\w*/, {
cases: {
'@keywords': { token: 'keyword.$0' },
'@default': 'identifier'
}
}],
// whitespace
{ include: '@whitespace' },
// [[ attributes ]].
[/\[\[.*\]\]/, 'annotation'],
[/^\s*#include/, { token: 'keyword.directive.include', next: '@include' }],
// Preprocessor directive
[/^\s*#\s*\w+/, 'keyword'],
// delimiters and operators
[/[{}()\[\]]/, '@brackets'],
[/[<>](?!@symbols)/, '@brackets'],
[/@symbols/, {
cases: {
'@operators': 'delimiter',
'@default': ''
}
}],
// numbers
[/\d*\d+[eE]([\-+]?\d+)?(@floatsuffix)/, 'number.float'],
[/\d*\.\d+([eE][\-+]?\d+)?(@floatsuffix)/, 'number.float'],
[/0[xX][0-9a-fA-F']*[0-9a-fA-F](@integersuffix)/, 'number.hex'],
[/0[0-7']*[0-7](@integersuffix)/, 'number.octal'],
[/0[bB][0-1']*[0-1](@integersuffix)/, 'number.binary'],
[/\d[\d']*\d(@integersuffix)/, 'number'],
[/\d(@integersuffix)/, 'number'],
// delimiter: after number because of .\d floats
[/[;,.]/, 'delimiter'],
// strings
[/"([^"\\]|\\.)*$/, 'string.invalid'],
[/"/, 'string', '@string'],
// characters
[/'[^\\']'/, 'string'],
[/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
[/'/, 'string.invalid']
],
whitespace: [
[/[ \t\r\n]+/, ''],
[/\/\*\*(?!\/)/, 'comment.doc', '@doccomment'],
[/\/\*/, 'comment', '@comment'],
[/\/\/.*$/, 'comment'],
],
comment: [
[/[^\/*]+/, 'comment'],
[/\*\//, 'comment', '@pop'],
[/[\/*]/, 'comment']
],
//Identical copy of comment above, except for the addition of .doc
doccomment: [
[/[^\/*]+/, 'comment.doc'],
[/\*\//, 'comment.doc', '@pop'],
[/[\/*]/, 'comment.doc']
],
string: [
[/[^\\"]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/"/, 'string', '@pop']
],
raw: [
[/(.*)(\))(?:([^ ()\\\t]*))(\")/, {
cases: {
'$3==$S2': ['string.raw', 'string.raw.end', 'string.raw.end', { token: 'string.raw.end', next: '@pop' }],
'@default': ['string.raw', 'string.raw', 'string.raw', 'string.raw']
}
}
],
[/.*/, 'string.raw']
],
include: [
[/(\s*)(<)([^<>]*)(>)/, ['', 'keyword.directive.include.begin', 'string.include.identifier', { token: 'keyword.directive.include.end', next: '@pop' }]],
[/(\s*)(")([^"]*)(")/, ['', 'keyword.directive.include.begin', 'string.include.identifier', { token: 'keyword.directive.include.end', next: '@pop' }]]
]
},
};
});

16
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/csharp/csharp.contribution.js

@ -0,0 +1,16 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'csharp',
extensions: ['.cs', '.csx'],
aliases: ['C#', 'csharp'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./csharp'], resolve_1, reject_1); })); }
});
});

187
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/csharp/csharp.js

@ -0,0 +1,187 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.conf = {
wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\#\$\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
comments: {
lineComment: '//',
blockComment: ['/*', '*/'],
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')'],
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '\'', close: '\'', notIn: ['string', 'comment'] },
{ open: '"', close: '"', notIn: ['string', 'comment'] },
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '<', close: '>' },
{ open: '\'', close: '\'' },
{ open: '"', close: '"' },
],
folding: {
markers: {
start: new RegExp("^\\s*#region\\b"),
end: new RegExp("^\\s*#endregion\\b")
}
}
};
exports.language = {
defaultToken: '',
tokenPostfix: '.cs',
brackets: [
{ open: '{', close: '}', token: 'delimiter.curly' },
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' },
{ open: '<', close: '>', token: 'delimiter.angle' }
],
keywords: [
'extern', 'alias', 'using', 'bool', 'decimal', 'sbyte', 'byte', 'short',
'ushort', 'int', 'uint', 'long', 'ulong', 'char', 'float', 'double',
'object', 'dynamic', 'string', 'assembly', 'is', 'as', 'ref',
'out', 'this', 'base', 'new', 'typeof', 'void', 'checked', 'unchecked',
'default', 'delegate', 'var', 'const', 'if', 'else', 'switch', 'case',
'while', 'do', 'for', 'foreach', 'in', 'break', 'continue', 'goto',
'return', 'throw', 'try', 'catch', 'finally', 'lock', 'yield', 'from',
'let', 'where', 'join', 'on', 'equals', 'into', 'orderby', 'ascending',
'descending', 'select', 'group', 'by', 'namespace', 'partial', 'class',
'field', 'event', 'method', 'param', 'property', 'public', 'protected',
'internal', 'private', 'abstract', 'sealed', 'static', 'struct', 'readonly',
'volatile', 'virtual', 'override', 'params', 'get', 'set', 'add', 'remove',
'operator', 'true', 'false', 'implicit', 'explicit', 'interface', 'enum',
'null', 'async', 'await', 'fixed', 'sizeof', 'stackalloc', 'unsafe', 'nameof',
'when'
],
namespaceFollows: [
'namespace', 'using',
],
parenFollows: [
'if', 'for', 'while', 'switch', 'foreach', 'using', 'catch', 'when'
],
operators: [
'=', '??', '||', '&&', '|', '^', '&', '==', '!=', '<=', '>=', '<<',
'+', '-', '*', '/', '%', '!', '~', '++', '--', '+=',
'-=', '*=', '/=', '%=', '&=', '|=', '^=', '<<=', '>>=', '>>', '=>'
],
symbols: /[=><!~?:&|+\-*\/\^%]+/,
// escape sequences
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
// The main tokenizer for our languages
tokenizer: {
root: [
// identifiers and keywords
[/\@?[a-zA-Z_]\w*/, {
cases: {
'@namespaceFollows': { token: 'keyword.$0', next: '@namespace' },
'@keywords': { token: 'keyword.$0', next: '@qualified' },
'@default': { token: 'identifier', next: '@qualified' }
}
}],
// whitespace
{ include: '@whitespace' },
// delimiters and operators
[/}/, {
cases: {
'$S2==interpolatedstring': { token: 'string.quote', next: '@pop' },
'$S2==litinterpstring': { token: 'string.quote', next: '@pop' },
'@default': '@brackets'
}
}],
[/[{}()\[\]]/, '@brackets'],
[/[<>](?!@symbols)/, '@brackets'],
[/@symbols/, {
cases: {
'@operators': 'delimiter',
'@default': ''
}
}],
// numbers
[/[0-9_]*\.[0-9_]+([eE][\-+]?\d+)?[fFdD]?/, 'number.float'],
[/0[xX][0-9a-fA-F_]+/, 'number.hex'],
[/0[bB][01_]+/, 'number.hex'],
[/[0-9_]+/, 'number'],
// delimiter: after number because of .\d floats
[/[;,.]/, 'delimiter'],
// strings
[/"([^"\\]|\\.)*$/, 'string.invalid'],
[/"/, { token: 'string.quote', next: '@string' }],
[/\$\@"/, { token: 'string.quote', next: '@litinterpstring' }],
[/\@"/, { token: 'string.quote', next: '@litstring' }],
[/\$"/, { token: 'string.quote', next: '@interpolatedstring' }],
// characters
[/'[^\\']'/, 'string'],
[/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
[/'/, 'string.invalid']
],
qualified: [
[/[a-zA-Z_][\w]*/, {
cases: {
'@keywords': { token: 'keyword.$0' },
'@default': 'identifier'
}
}],
[/\./, 'delimiter'],
['', '', '@pop'],
],
namespace: [
{ include: '@whitespace' },
[/[A-Z]\w*/, 'namespace'],
[/[\.=]/, 'delimiter'],
['', '', '@pop'],
],
comment: [
[/[^\/*]+/, 'comment'],
// [/\/\*/, 'comment', '@push' ], // no nested comments :-(
['\\*/', 'comment', '@pop'],
[/[\/*]/, 'comment']
],
string: [
[/[^\\"]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/"/, { token: 'string.quote', next: '@pop' }]
],
litstring: [
[/[^"]+/, 'string'],
[/""/, 'string.escape'],
[/"/, { token: 'string.quote', next: '@pop' }]
],
litinterpstring: [
[/[^"{]+/, 'string'],
[/""/, 'string.escape'],
[/{{/, 'string.escape'],
[/}}/, 'string.escape'],
[/{/, { token: 'string.quote', next: 'root.litinterpstring' }],
[/"/, { token: 'string.quote', next: '@pop' }]
],
interpolatedstring: [
[/[^\\"{]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/{{/, 'string.escape'],
[/}}/, 'string.escape'],
[/{/, { token: 'string.quote', next: 'root.interpolatedstring' }],
[/"/, { token: 'string.quote', next: '@pop' }]
],
whitespace: [
[/^[ \t\v\f]*#((r)|(load))(?=\s)/, 'directive.csx'],
[/^[ \t\v\f]*#\w.*$/, 'namespace.cpp'],
[/[ \t\v\f\r\n]+/, ''],
[/\/\*/, 'comment', '@comment'],
[/\/\/.*$/, 'comment'],
],
},
};
});

16
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/csp/csp.contribution.js

@ -0,0 +1,16 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'csp',
extensions: [],
aliases: ['CSP', 'csp'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./csp'], resolve_1, reject_1); })); }
});
});

58
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/csp/csp.js

@ -0,0 +1,58 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.conf = {
brackets: [],
autoClosingPairs: [],
surroundingPairs: []
};
exports.language = {
// Set defaultToken to invalid to see what you do not tokenize yet
// defaultToken: 'invalid',
keywords: [],
typeKeywords: [],
tokenPostfix: '.csp',
operators: [],
symbols: /[=><!~?:&|+\-*\/\^%]+/,
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
tokenizer: {
root: [
[/child-src/, 'string.quote'],
[/connect-src/, 'string.quote'],
[/default-src/, 'string.quote'],
[/font-src/, 'string.quote'],
[/frame-src/, 'string.quote'],
[/img-src/, 'string.quote'],
[/manifest-src/, 'string.quote'],
[/media-src/, 'string.quote'],
[/object-src/, 'string.quote'],
[/script-src/, 'string.quote'],
[/style-src/, 'string.quote'],
[/worker-src/, 'string.quote'],
[/base-uri/, 'string.quote'],
[/plugin-types/, 'string.quote'],
[/sandbox/, 'string.quote'],
[/disown-opener/, 'string.quote'],
[/form-action/, 'string.quote'],
[/frame-ancestors/, 'string.quote'],
[/report-uri/, 'string.quote'],
[/report-to/, 'string.quote'],
[/upgrade-insecure-requests/, 'string.quote'],
[/block-all-mixed-content/, 'string.quote'],
[/require-sri-for/, 'string.quote'],
[/reflected-xss/, 'string.quote'],
[/referrer/, 'string.quote'],
[/policy-uri/, 'string.quote'],
[/'self'/, 'string.quote'],
[/'unsafe-inline'/, 'string.quote'],
[/'unsafe-eval'/, 'string.quote'],
[/'strict-dynamic'/, 'string.quote'],
[/'unsafe-hashed-attributes'/, 'string.quote']
]
}
};
});

17
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/css/css.contribution.js

@ -0,0 +1,17 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'css',
extensions: ['.css'],
aliases: ['CSS', 'css'],
mimetypes: ['text/css'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./css'], resolve_1, reject_1); })); }
});
});

174
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/css/css.js

@ -0,0 +1,174 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.conf = {
wordPattern: /(#?-?\d*\.\d\w*%?)|((::|[@#.!:])?[\w-?]+%?)|::|[@#.!:]/g,
comments: {
blockComment: ['/*', '*/']
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}', notIn: ['string', 'comment'] },
{ open: '[', close: ']', notIn: ['string', 'comment'] },
{ open: '(', close: ')', notIn: ['string', 'comment'] },
{ open: '"', close: '"', notIn: ['string', 'comment'] },
{ open: '\'', close: '\'', notIn: ['string', 'comment'] }
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' }
],
folding: {
markers: {
start: new RegExp("^\\s*\\/\\*\\s*#region\\b\\s*(.*?)\\s*\\*\\/"),
end: new RegExp("^\\s*\\/\\*\\s*#endregion\\b.*\\*\\/")
}
}
};
exports.language = {
defaultToken: '',
tokenPostfix: '.css',
ws: '[ \t\n\r\f]*',
identifier: '-?-?([a-zA-Z]|(\\\\(([0-9a-fA-F]{1,6}\\s?)|[^[0-9a-fA-F])))([\\w\\-]|(\\\\(([0-9a-fA-F]{1,6}\\s?)|[^[0-9a-fA-F])))*',
brackets: [
{ open: '{', close: '}', token: 'delimiter.bracket' },
{ open: '[', close: ']', token: 'delimiter.bracket' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' },
{ open: '<', close: '>', token: 'delimiter.angle' }
],
tokenizer: {
root: [
{ include: '@selector' },
],
selector: [
{ include: '@comments' },
{ include: '@import' },
{ include: '@strings' },
['[@](keyframes|-webkit-keyframes|-moz-keyframes|-o-keyframes)', { token: 'keyword', next: '@keyframedeclaration' }],
['[@](page|content|font-face|-moz-document)', { token: 'keyword' }],
['[@](charset|namespace)', { token: 'keyword', next: '@declarationbody' }],
['(url-prefix)(\\()', ['attribute.value', { token: 'delimiter.parenthesis', next: '@urldeclaration' }]],
['(url)(\\()', ['attribute.value', { token: 'delimiter.parenthesis', next: '@urldeclaration' }]],
{ include: '@selectorname' },
['[\\*]', 'tag'],
['[>\\+,]', 'delimiter'],
['\\[', { token: 'delimiter.bracket', next: '@selectorattribute' }],
['{', { token: 'delimiter.bracket', next: '@selectorbody' }]
],
selectorbody: [
{ include: '@comments' },
['[*_]?@identifier@ws:(?=(\\s|\\d|[^{;}]*[;}]))', 'attribute.name', '@rulevalue'],
['}', { token: 'delimiter.bracket', next: '@pop' }]
],
selectorname: [
['(\\.|#(?=[^{])|%|(@identifier)|:)+', 'tag'],
],
selectorattribute: [
{ include: '@term' },
[']', { token: 'delimiter.bracket', next: '@pop' }],
],
term: [
{ include: '@comments' },
['(url-prefix)(\\()', ['attribute.value', { token: 'delimiter.parenthesis', next: '@urldeclaration' }]],
['(url)(\\()', ['attribute.value', { token: 'delimiter.parenthesis', next: '@urldeclaration' }]],
{ include: '@functioninvocation' },
{ include: '@numbers' },
{ include: '@name' },
['([<>=\\+\\-\\*\\/\\^\\|\\~,])', 'delimiter'],
[',', 'delimiter']
],
rulevalue: [
{ include: '@comments' },
{ include: '@strings' },
{ include: '@term' },
['!important', 'keyword'],
[';', 'delimiter', '@pop'],
['(?=})', { token: '', next: '@pop' }] // missing semicolon
],
warndebug: [
['[@](warn|debug)', { token: 'keyword', next: '@declarationbody' }]
],
import: [
['[@](import)', { token: 'keyword', next: '@declarationbody' }]
],
urldeclaration: [
{ include: '@strings' },
['[^)\r\n]+', 'string'],
['\\)', { token: 'delimiter.parenthesis', next: '@pop' }]
],
parenthizedterm: [
{ include: '@term' },
['\\)', { token: 'delimiter.parenthesis', next: '@pop' }]
],
declarationbody: [
{ include: '@term' },
[';', 'delimiter', '@pop'],
['(?=})', { token: '', next: '@pop' }] // missing semicolon
],
comments: [
['\\/\\*', 'comment', '@comment'],
['\\/\\/+.*', 'comment']
],
comment: [
['\\*\\/', 'comment', '@pop'],
[/[^*/]+/, 'comment'],
[/./, 'comment'],
],
name: [
['@identifier', 'attribute.value']
],
numbers: [
['-?(\\d*\\.)?\\d+([eE][\\-+]?\\d+)?', { token: 'attribute.value.number', next: '@units' }],
['#[0-9a-fA-F_]+(?!\\w)', 'attribute.value.hex']
],
units: [
['(em|ex|ch|rem|vmin|vmax|vw|vh|vm|cm|mm|in|px|pt|pc|deg|grad|rad|turn|s|ms|Hz|kHz|%)?', 'attribute.value.unit', '@pop']
],
keyframedeclaration: [
['@identifier', 'attribute.value'],
['{', { token: 'delimiter.bracket', switchTo: '@keyframebody' }],
],
keyframebody: [
{ include: '@term' },
['{', { token: 'delimiter.bracket', next: '@selectorbody' }],
['}', { token: 'delimiter.bracket', next: '@pop' }],
],
functioninvocation: [
['@identifier\\(', { token: 'attribute.value', next: '@functionarguments' }],
],
functionarguments: [
['\\$@identifier@ws:', 'attribute.name'],
['[,]', 'delimiter'],
{ include: '@term' },
['\\)', { token: 'attribute.value', next: '@pop' }],
],
strings: [
['~?"', { token: 'string', next: '@stringenddoublequote' }],
['~?\'', { token: 'string', next: '@stringendquote' }]
],
stringenddoublequote: [
['\\\\.', 'string'],
['"', { token: 'string', next: '@pop' }],
[/[^\\"]+/, 'string'],
['.', 'string']
],
stringendquote: [
['\\\\.', 'string'],
['\'', { token: 'string', next: '@pop' }],
[/[^\\']+/, 'string'],
['.', 'string']
]
}
};
});

17
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/dockerfile/dockerfile.contribution.js

@ -0,0 +1,17 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'dockerfile',
extensions: ['.dockerfile'],
filenames: ['Dockerfile'],
aliases: ['Dockerfile'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./dockerfile'], resolve_1, reject_1); })); }
});
});

118
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/dockerfile/dockerfile.js

@ -0,0 +1,118 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.conf = {
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
]
};
exports.language = {
defaultToken: '',
tokenPostfix: '.dockerfile',
instructions: /FROM|MAINTAINER|RUN|EXPOSE|ENV|ADD|ARG|VOLUME|LABEL|USER|WORKDIR|COPY|CMD|STOPSIGNAL|SHELL|HEALTHCHECK|ENTRYPOINT/,
instructionAfter: /ONBUILD/,
variableAfter: /ENV/,
variable: /\${?[\w]+}?/,
tokenizer: {
root: [
{ include: '@whitespace' },
{ include: '@comment' },
[/(@instructionAfter)(\s+)/, ['keyword', { token: '', next: '@instructions' }]],
['', 'keyword', '@instructions']
],
instructions: [
[/(@variableAfter)(\s+)([\w]+)/, ['keyword', '', { token: 'variable', next: '@arguments' }]],
[/(@instructions)/, 'keyword', '@arguments']
],
arguments: [
{ include: '@whitespace' },
{ include: '@strings' },
[/(@variable)/, {
cases: {
'@eos': { token: 'variable', next: '@popall' },
'@default': 'variable'
}
}],
[/\\/, {
cases: {
'@eos': '',
'@default': ''
}
}],
[/./, {
cases: {
'@eos': { token: '', next: '@popall' },
'@default': ''
}
}],
],
// Deal with white space, including comments
whitespace: [
[/\s+/, {
cases: {
'@eos': { token: '', next: '@popall' },
'@default': ''
}
}],
],
comment: [
[/(^#.*$)/, 'comment', '@popall']
],
// Recognize strings, including those broken across lines with \ (but not without)
strings: [
[/'$/, 'string', '@popall'],
[/'/, 'string', '@stringBody'],
[/"$/, 'string', '@popall'],
[/"/, 'string', '@dblStringBody']
],
stringBody: [
[/[^\\\$']/, {
cases: {
'@eos': { token: 'string', next: '@popall' },
'@default': 'string'
}
}],
[/\\./, 'string.escape'],
[/'$/, 'string', '@popall'],
[/'/, 'string', '@pop'],
[/(@variable)/, 'variable'],
[/\\$/, 'string'],
[/$/, 'string', '@popall']
],
dblStringBody: [
[/[^\\\$"]/, {
cases: {
'@eos': { token: 'string', next: '@popall' },
'@default': 'string'
}
}],
[/\\./, 'string.escape'],
[/"$/, 'string', '@popall'],
[/"/, 'string', '@pop'],
[/(@variable)/, 'variable'],
[/\\$/, 'string'],
[/$/, 'string', '@popall']
]
}
};
});

16
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/fsharp/fsharp.contribution.js

@ -0,0 +1,16 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'fsharp',
extensions: ['.fs', '.fsi', '.ml', '.mli', '.fsx', '.fsscript'],
aliases: ['F#', 'FSharp', 'fsharp'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./fsharp'], resolve_1, reject_1); })); }
});
});

139
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/fsharp/fsharp.js

@ -0,0 +1,139 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.conf = {
comments: {
lineComment: '//',
blockComment: ['(*', '*)'],
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' }
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' }
],
folding: {
markers: {
start: new RegExp("^\\s*//\\s*#region\\b|^\\s*\\(\\*\\s*#region(.*)\\*\\)"),
end: new RegExp("^\\s*//\\s*#endregion\\b|^\\s*\\(\\*\\s*#endregion\\s*\\*\\)")
}
}
};
exports.language = {
defaultToken: '',
tokenPostfix: '.fs',
keywords: [
'abstract', 'and', 'atomic', 'as',
'assert', 'asr', 'base', 'begin',
'break', 'checked', 'component',
'const', 'constraint', 'constructor',
'continue', 'class', 'default',
'delegate', 'do', 'done', 'downcast',
'downto', 'elif', 'else', 'end',
'exception', 'eager', 'event', 'external',
'extern', 'false', 'finally', 'for',
'fun', 'function', 'fixed', 'functor',
'global', 'if', 'in', 'include', 'inherit',
'inline', 'interface', 'internal', 'land',
'lor', 'lsl', 'lsr', 'lxor', 'lazy', 'let',
'match', 'member', 'mod', 'module', 'mutable',
'namespace', 'method', 'mixin', 'new', 'not',
'null', 'of', 'open', 'or', 'object',
'override', 'private', 'parallel', 'process',
'protected', 'pure', 'public', 'rec', 'return',
'static', 'sealed', 'struct', 'sig', 'then',
'to', 'true', 'tailcall', 'trait',
'try', 'type', 'upcast', 'use',
'val', 'void', 'virtual', 'volatile',
'when', 'while', 'with', 'yield'
],
// we include these common regular expressions
symbols: /[=><!~?:&|+\-*\^%;\.,\/]+/,
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
integersuffix: /[uU]?[yslnLI]?/,
floatsuffix: /[fFmM]?/,
// The main tokenizer for our languages
tokenizer: {
root: [
// identifiers and keywords
[/[a-zA-Z_]\w*/, {
cases: {
'@keywords': { token: 'keyword.$0' },
'@default': 'identifier'
}
}],
// whitespace
{ include: '@whitespace' },
// [< attributes >].
[/\[<.*>\]/, 'annotation'],
// Preprocessor directive
[/^#(if|else|endif)/, 'keyword'],
// delimiters and operators
[/[{}()\[\]]/, '@brackets'],
[/[<>](?!@symbols)/, '@brackets'],
[/@symbols/, 'delimiter'],
// numbers
[/\d*\d+[eE]([\-+]?\d+)?(@floatsuffix)/, 'number.float'],
[/\d*\.\d+([eE][\-+]?\d+)?(@floatsuffix)/, 'number.float'],
[/0x[0-9a-fA-F]+LF/, 'number.float'],
[/0x[0-9a-fA-F]+(@integersuffix)/, 'number.hex'],
[/0b[0-1]+(@integersuffix)/, 'number.bin'],
[/\d+(@integersuffix)/, 'number'],
// delimiter: after number because of .\d floats
[/[;,.]/, 'delimiter'],
// strings
[/"([^"\\]|\\.)*$/, 'string.invalid'],
[/"""/, 'string', '@string."""'],
[/"/, 'string', '@string."'],
// literal string
[/\@"/, { token: 'string.quote', next: '@litstring' }],
// characters
[/'[^\\']'B?/, 'string'],
[/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
[/'/, 'string.invalid']
],
whitespace: [
[/[ \t\r\n]+/, ''],
[/\(\*(?!\))/, 'comment', '@comment'],
[/\/\/.*$/, 'comment'],
],
comment: [
[/[^\*]+/, 'comment'],
[/\*\)/, 'comment', '@pop'],
[/\*/, 'comment']
],
string: [
[/[^\\"]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/("""|"B?)/, {
cases: {
'$#==$S2': { token: 'string', next: '@pop' },
'@default': 'string'
}
}]
],
litstring: [
[/[^"]+/, 'string'],
[/""/, 'string.escape'],
[/"/, { token: 'string.quote', next: '@pop' }]
],
},
};
});

16
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/go/go.contribution.js

@ -0,0 +1,16 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'go',
extensions: ['.go'],
aliases: ['Go'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./go'], resolve_1, reject_1); })); }
});
});

173
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/go/go.js

@ -0,0 +1,173 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.conf = {
comments: {
lineComment: '//',
blockComment: ['/*', '*/'],
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '`', close: '`', notIn: ['string'] },
{ open: '"', close: '"', notIn: ['string'] },
{ open: '\'', close: '\'', notIn: ['string', 'comment'] },
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '`', close: '`' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
]
};
exports.language = {
defaultToken: '',
tokenPostfix: '.go',
keywords: [
'break',
'case',
'chan',
'const',
'continue',
'default',
'defer',
'else',
'fallthrough',
'for',
'func',
'go',
'goto',
'if',
'import',
'interface',
'map',
'package',
'range',
'return',
'select',
'struct',
'switch',
'type',
'var',
'bool',
'true',
'false',
'uint8',
'uint16',
'uint32',
'uint64',
'int8',
'int16',
'int32',
'int64',
'float32',
'float64',
'complex64',
'complex128',
'byte',
'rune',
'uint',
'int',
'uintptr',
'string',
'nil',
],
operators: [
'+', '-', '*', '/', '%', '&', '|', '^', '<<', '>>', '&^',
'+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '<<=', '>>=', '&^=',
'&&', '||', '<-', '++', '--', '==', '<', '>', '=', '!', '!=', '<=', '>=', ':=', '...',
'(', ')', '', ']', '{', '}', ',', ';', '.', ':'
],
// we include these common regular expressions
symbols: /[=><!~?:&|+\-*\/\^%]+/,
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
// The main tokenizer for our languages
tokenizer: {
root: [
// identifiers and keywords
[/[a-zA-Z_]\w*/, {
cases: {
'@keywords': { token: 'keyword.$0' },
'@default': 'identifier'
}
}],
// whitespace
{ include: '@whitespace' },
// [[ attributes ]].
[/\[\[.*\]\]/, 'annotation'],
// Preprocessor directive
[/^\s*#\w+/, 'keyword'],
// delimiters and operators
[/[{}()\[\]]/, '@brackets'],
[/[<>](?!@symbols)/, '@brackets'],
[/@symbols/, {
cases: {
'@operators': 'delimiter',
'@default': ''
}
}],
// numbers
[/\d*\d+[eE]([\-+]?\d+)?/, 'number.float'],
[/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
[/0[xX][0-9a-fA-F']*[0-9a-fA-F]/, 'number.hex'],
[/0[0-7']*[0-7]/, 'number.octal'],
[/0[bB][0-1']*[0-1]/, 'number.binary'],
[/\d[\d']*/, 'number'],
[/\d/, 'number'],
// delimiter: after number because of .\d floats
[/[;,.]/, 'delimiter'],
// strings
[/"([^"\\]|\\.)*$/, 'string.invalid'],
[/"/, 'string', '@string'],
[/`/, "string", "@rawstring"],
// characters
[/'[^\\']'/, 'string'],
[/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
[/'/, 'string.invalid']
],
whitespace: [
[/[ \t\r\n]+/, ''],
[/\/\*\*(?!\/)/, 'comment.doc', '@doccomment'],
[/\/\*/, 'comment', '@comment'],
[/\/\/.*$/, 'comment'],
],
comment: [
[/[^\/*]+/, 'comment'],
// [/\/\*/, 'comment', '@push' ], // nested comment not allowed :-(
// [/\/\*/, 'comment.invalid' ], // this breaks block comments in the shape of /* //*/
[/\*\//, 'comment', '@pop'],
[/[\/*]/, 'comment']
],
//Identical copy of comment above, except for the addition of .doc
doccomment: [
[/[^\/*]+/, 'comment.doc'],
// [/\/\*/, 'comment.doc', '@push' ], // nested comment not allowed :-(
[/\/\*/, 'comment.doc.invalid'],
[/\*\//, 'comment.doc', '@pop'],
[/[\/*]/, 'comment.doc']
],
string: [
[/[^\\"]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/"/, 'string', '@pop']
],
rawstring: [
[/[^\`]/, "string"],
[/`/, "string", "@pop"]
],
},
};
});

17
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/handlebars/handlebars.contribution.js

@ -0,0 +1,17 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'handlebars',
extensions: ['.handlebars', '.hbs'],
aliases: ['Handlebars', 'handlebars'],
mimetypes: ['text/x-handlebars-template'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./handlebars'], resolve_1, reject_1); })); }
});
});

196
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/handlebars/handlebars.js

@ -0,0 +1,196 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
var EMPTY_ELEMENTS = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'];
exports.conf = {
wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\$\^\&\*\(\)\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\s]+)/g,
comments: {
blockComment: ['{{!--', '--}}']
},
brackets: [
['<!--', '-->'],
['<', '>'],
['{{', '}}'],
['{', '}'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' }
],
surroundingPairs: [
{ open: '<', close: '>' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' }
],
onEnterRules: [
{
beforeText: new RegExp("<(?!(?:" + EMPTY_ELEMENTS.join('|') + "))(\\w[\\w\\d]*)([^/>]*(?!/)>)[^<]*$", 'i'),
afterText: /^<\/(\w[\w\d]*)\s*>$/i,
action: { indentAction: _monaco.languages.IndentAction.IndentOutdent }
},
{
beforeText: new RegExp("<(?!(?:" + EMPTY_ELEMENTS.join('|') + "))(\\w[\\w\\d]*)([^/>]*(?!/)>)[^<]*$", 'i'),
action: { indentAction: _monaco.languages.IndentAction.Indent }
}
],
};
exports.language = {
defaultToken: '',
tokenPostfix: '',
// ignoreCase: true,
// The main tokenizer for our languages
tokenizer: {
root: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.root' }],
[/<!DOCTYPE/, 'metatag.html', '@doctype'],
[/<!--/, 'comment.html', '@comment'],
[/(<)(\w+)(\/>)/, ['delimiter.html', 'tag.html', 'delimiter.html']],
[/(<)(script)/, ['delimiter.html', { token: 'tag.html', next: '@script' }]],
[/(<)(style)/, ['delimiter.html', { token: 'tag.html', next: '@style' }]],
[/(<)([:\w]+)/, ['delimiter.html', { token: 'tag.html', next: '@otherTag' }]],
[/(<\/)(\w+)/, ['delimiter.html', { token: 'tag.html', next: '@otherTag' }]],
[/</, 'delimiter.html'],
[/\{/, 'delimiter.html'],
[/[^<{]+/] // text
],
doctype: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.comment' }],
[/[^>]+/, 'metatag.content.html'],
[/>/, 'metatag.html', '@pop'],
],
comment: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.comment' }],
[/-->/, 'comment.html', '@pop'],
[/[^-]+/, 'comment.content.html'],
[/./, 'comment.content.html']
],
otherTag: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.otherTag' }],
[/\/?>/, 'delimiter.html', '@pop'],
[/"([^"]*)"/, 'attribute.value'],
[/'([^']*)'/, 'attribute.value'],
[/[\w\-]+/, 'attribute.name'],
[/=/, 'delimiter'],
[/[ \t\r\n]+/],
],
// -- BEGIN <script> tags handling
// After <script
script: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.script' }],
[/type/, 'attribute.name', '@scriptAfterType'],
[/"([^"]*)"/, 'attribute.value'],
[/'([^']*)'/, 'attribute.value'],
[/[\w\-]+/, 'attribute.name'],
[/=/, 'delimiter'],
[/>/, { token: 'delimiter.html', next: '@scriptEmbedded.text/javascript', nextEmbedded: 'text/javascript' }],
[/[ \t\r\n]+/],
[/(<\/)(script\s*)(>)/, ['delimiter.html', 'tag.html', { token: 'delimiter.html', next: '@pop' }]]
],
// After <script ... type
scriptAfterType: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.scriptAfterType' }],
[/=/, 'delimiter', '@scriptAfterTypeEquals'],
[/>/, { token: 'delimiter.html', next: '@scriptEmbedded.text/javascript', nextEmbedded: 'text/javascript' }],
[/[ \t\r\n]+/],
[/<\/script\s*>/, { token: '@rematch', next: '@pop' }]
],
// After <script ... type =
scriptAfterTypeEquals: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.scriptAfterTypeEquals' }],
[/"([^"]*)"/, { token: 'attribute.value', switchTo: '@scriptWithCustomType.$1' }],
[/'([^']*)'/, { token: 'attribute.value', switchTo: '@scriptWithCustomType.$1' }],
[/>/, { token: 'delimiter.html', next: '@scriptEmbedded.text/javascript', nextEmbedded: 'text/javascript' }],
[/[ \t\r\n]+/],
[/<\/script\s*>/, { token: '@rematch', next: '@pop' }]
],
// After <script ... type = $S2
scriptWithCustomType: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.scriptWithCustomType.$S2' }],
[/>/, { token: 'delimiter.html', next: '@scriptEmbedded.$S2', nextEmbedded: '$S2' }],
[/"([^"]*)"/, 'attribute.value'],
[/'([^']*)'/, 'attribute.value'],
[/[\w\-]+/, 'attribute.name'],
[/=/, 'delimiter'],
[/[ \t\r\n]+/],
[/<\/script\s*>/, { token: '@rematch', next: '@pop' }]
],
scriptEmbedded: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInEmbeddedState.scriptEmbedded.$S2', nextEmbedded: '@pop' }],
[/<\/script/, { token: '@rematch', next: '@pop', nextEmbedded: '@pop' }]
],
// -- END <script> tags handling
// -- BEGIN <style> tags handling
// After <style
style: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.style' }],
[/type/, 'attribute.name', '@styleAfterType'],
[/"([^"]*)"/, 'attribute.value'],
[/'([^']*)'/, 'attribute.value'],
[/[\w\-]+/, 'attribute.name'],
[/=/, 'delimiter'],
[/>/, { token: 'delimiter.html', next: '@styleEmbedded.text/css', nextEmbedded: 'text/css' }],
[/[ \t\r\n]+/],
[/(<\/)(style\s*)(>)/, ['delimiter.html', 'tag.html', { token: 'delimiter.html', next: '@pop' }]]
],
// After <style ... type
styleAfterType: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.styleAfterType' }],
[/=/, 'delimiter', '@styleAfterTypeEquals'],
[/>/, { token: 'delimiter.html', next: '@styleEmbedded.text/css', nextEmbedded: 'text/css' }],
[/[ \t\r\n]+/],
[/<\/style\s*>/, { token: '@rematch', next: '@pop' }]
],
// After <style ... type =
styleAfterTypeEquals: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.styleAfterTypeEquals' }],
[/"([^"]*)"/, { token: 'attribute.value', switchTo: '@styleWithCustomType.$1' }],
[/'([^']*)'/, { token: 'attribute.value', switchTo: '@styleWithCustomType.$1' }],
[/>/, { token: 'delimiter.html', next: '@styleEmbedded.text/css', nextEmbedded: 'text/css' }],
[/[ \t\r\n]+/],
[/<\/style\s*>/, { token: '@rematch', next: '@pop' }]
],
// After <style ... type = $S2
styleWithCustomType: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInSimpleState.styleWithCustomType.$S2' }],
[/>/, { token: 'delimiter.html', next: '@styleEmbedded.$S2', nextEmbedded: '$S2' }],
[/"([^"]*)"/, 'attribute.value'],
[/'([^']*)'/, 'attribute.value'],
[/[\w\-]+/, 'attribute.name'],
[/=/, 'delimiter'],
[/[ \t\r\n]+/],
[/<\/style\s*>/, { token: '@rematch', next: '@pop' }]
],
styleEmbedded: [
[/\{\{/, { token: '@rematch', switchTo: '@handlebarsInEmbeddedState.styleEmbedded.$S2', nextEmbedded: '@pop' }],
[/<\/style/, { token: '@rematch', next: '@pop', nextEmbedded: '@pop' }]
],
// -- END <style> tags handling
handlebarsInSimpleState: [
[/\{\{\{?/, 'delimiter.handlebars'],
[/\}\}\}?/, { token: 'delimiter.handlebars', switchTo: '@$S2.$S3' }],
{ include: 'handlebarsRoot' }
],
handlebarsInEmbeddedState: [
[/\{\{\{?/, 'delimiter.handlebars'],
[/\}\}\}?/, { token: 'delimiter.handlebars', switchTo: '@$S2.$S3', nextEmbedded: '$S3' }],
{ include: 'handlebarsRoot' }
],
handlebarsRoot: [
[/[#/][^\s}]+/, 'keyword.helper.handlebars'],
[/else\b/, 'keyword.helper.handlebars'],
[/[\s]+/],
[/[^}]/, 'variable.parameter.handlebars'],
],
},
};
});

17
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/html/html.contribution.js

@ -0,0 +1,17 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'html',
extensions: ['.html', '.htm', '.shtml', '.xhtml', '.mdoc', '.jsp', '.asp', '.aspx', '.jshtm'],
aliases: ['HTML', 'htm', 'html', 'xhtml'],
mimetypes: ['text/html', 'text/x-jshtm', 'text/template', 'text/ng-template'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./html'], resolve_1, reject_1); })); }
});
});

210
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/html/html.js

@ -0,0 +1,210 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
var EMPTY_ELEMENTS = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'];
exports.conf = {
wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\$\^\&\*\(\)\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\s]+)/g,
comments: {
blockComment: ['<!--', '-->']
},
brackets: [
['<!--', '-->'],
['<', '>'],
['{', '}'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' }
],
surroundingPairs: [
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '<', close: '>' },
],
onEnterRules: [
{
beforeText: new RegExp("<(?!(?:" + EMPTY_ELEMENTS.join('|') + "))([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$", 'i'),
afterText: /^<\/([_:\w][_:\w-.\d]*)\s*>$/i,
action: { indentAction: _monaco.languages.IndentAction.IndentOutdent }
},
{
beforeText: new RegExp("<(?!(?:" + EMPTY_ELEMENTS.join('|') + "))(\\w[\\w\\d]*)([^/>]*(?!/)>)[^<]*$", 'i'),
action: { indentAction: _monaco.languages.IndentAction.Indent }
}
],
folding: {
markers: {
start: new RegExp("^\\s*<!--\\s*#region\\b.*-->"),
end: new RegExp("^\\s*<!--\\s*#endregion\\b.*-->")
}
}
};
exports.language = {
defaultToken: '',
tokenPostfix: '.html',
ignoreCase: true,
// The main tokenizer for our languages
tokenizer: {
root: [
[/<!DOCTYPE/, 'metatag', '@doctype'],
[/<!--/, 'comment', '@comment'],
[/(<)((?:[\w\-]+:)?[\w\-]+)(\s*)(\/>)/, ['delimiter', 'tag', '', 'delimiter']],
[/(<)(script)/, ['delimiter', { token: 'tag', next: '@script' }]],
[/(<)(style)/, ['delimiter', { token: 'tag', next: '@style' }]],
[/(<)((?:[\w\-]+:)?[\w\-]+)/, ['delimiter', { token: 'tag', next: '@otherTag' }]],
[/(<\/)((?:[\w\-]+:)?[\w\-]+)/, ['delimiter', { token: 'tag', next: '@otherTag' }]],
[/</, 'delimiter'],
[/[^<]+/],
],
doctype: [
[/[^>]+/, 'metatag.content'],
[/>/, 'metatag', '@pop'],
],
comment: [
[/-->/, 'comment', '@pop'],
[/[^-]+/, 'comment.content'],
[/./, 'comment.content']
],
otherTag: [
[/\/?>/, 'delimiter', '@pop'],
[/"([^"]*)"/, 'attribute.value'],
[/'([^']*)'/, 'attribute.value'],
[/[\w\-]+/, 'attribute.name'],
[/=/, 'delimiter'],
[/[ \t\r\n]+/],
],
// -- BEGIN <script> tags handling
// After <script
script: [
[/type/, 'attribute.name', '@scriptAfterType'],
[/"([^"]*)"/, 'attribute.value'],
[/'([^']*)'/, 'attribute.value'],
[/[\w\-]+/, 'attribute.name'],
[/=/, 'delimiter'],
[/>/, { token: 'delimiter', next: '@scriptEmbedded', nextEmbedded: 'text/javascript' }],
[/[ \t\r\n]+/],
[/(<\/)(script\s*)(>)/, ['delimiter', 'tag', { token: 'delimiter', next: '@pop' }]]
],
// After <script ... type
scriptAfterType: [
[/=/, 'delimiter', '@scriptAfterTypeEquals'],
[/>/, { token: 'delimiter', next: '@scriptEmbedded', nextEmbedded: 'text/javascript' }],
[/[ \t\r\n]+/],
[/<\/script\s*>/, { token: '@rematch', next: '@pop' }]
],
// After <script ... type =
scriptAfterTypeEquals: [
[/"([^"]*)"/, { token: 'attribute.value', switchTo: '@scriptWithCustomType.$1' }],
[/'([^']*)'/, { token: 'attribute.value', switchTo: '@scriptWithCustomType.$1' }],
[/>/, { token: 'delimiter', next: '@scriptEmbedded', nextEmbedded: 'text/javascript' }],
[/[ \t\r\n]+/],
[/<\/script\s*>/, { token: '@rematch', next: '@pop' }]
],
// After <script ... type = $S2
scriptWithCustomType: [
[/>/, { token: 'delimiter', next: '@scriptEmbedded.$S2', nextEmbedded: '$S2' }],
[/"([^"]*)"/, 'attribute.value'],
[/'([^']*)'/, 'attribute.value'],
[/[\w\-]+/, 'attribute.name'],
[/=/, 'delimiter'],
[/[ \t\r\n]+/],
[/<\/script\s*>/, { token: '@rematch', next: '@pop' }]
],
scriptEmbedded: [
[/<\/script/, { token: '@rematch', next: '@pop', nextEmbedded: '@pop' }],
[/[^<]+/, '']
],
// -- END <script> tags handling
// -- BEGIN <style> tags handling
// After <style
style: [
[/type/, 'attribute.name', '@styleAfterType'],
[/"([^"]*)"/, 'attribute.value'],
[/'([^']*)'/, 'attribute.value'],
[/[\w\-]+/, 'attribute.name'],
[/=/, 'delimiter'],
[/>/, { token: 'delimiter', next: '@styleEmbedded', nextEmbedded: 'text/css' }],
[/[ \t\r\n]+/],
[/(<\/)(style\s*)(>)/, ['delimiter', 'tag', { token: 'delimiter', next: '@pop' }]]
],
// After <style ... type
styleAfterType: [
[/=/, 'delimiter', '@styleAfterTypeEquals'],
[/>/, { token: 'delimiter', next: '@styleEmbedded', nextEmbedded: 'text/css' }],
[/[ \t\r\n]+/],
[/<\/style\s*>/, { token: '@rematch', next: '@pop' }]
],
// After <style ... type =
styleAfterTypeEquals: [
[/"([^"]*)"/, { token: 'attribute.value', switchTo: '@styleWithCustomType.$1' }],
[/'([^']*)'/, { token: 'attribute.value', switchTo: '@styleWithCustomType.$1' }],
[/>/, { token: 'delimiter', next: '@styleEmbedded', nextEmbedded: 'text/css' }],
[/[ \t\r\n]+/],
[/<\/style\s*>/, { token: '@rematch', next: '@pop' }]
],
// After <style ... type = $S2
styleWithCustomType: [
[/>/, { token: 'delimiter', next: '@styleEmbedded.$S2', nextEmbedded: '$S2' }],
[/"([^"]*)"/, 'attribute.value'],
[/'([^']*)'/, 'attribute.value'],
[/[\w\-]+/, 'attribute.name'],
[/=/, 'delimiter'],
[/[ \t\r\n]+/],
[/<\/style\s*>/, { token: '@rematch', next: '@pop' }]
],
styleEmbedded: [
[/<\/style/, { token: '@rematch', next: '@pop', nextEmbedded: '@pop' }],
[/[^<]+/, '']
],
},
};
});
// TESTED WITH:
// <!DOCTYPE html>
// <html>
// <head>
// <title>Monarch Workbench</title>
// <meta http-equiv="X-UA-Compatible" content="IE=edge" />
// <!----
// -- -- -- a comment -- -- --
// ---->
// <style bah="bah">
// body { font-family: Consolas; } /* nice */
// </style>
// </head
// >
// a = "asd"
// <body>
// <br/>
// <div
// class
// =
// "test"
// >
// <script>
// function() {
// alert("hi </ script>"); // javascript
// };
// </script>
// <script
// bah="asdfg"
// type="text/css"
// >
// .bar { text-decoration: underline; }
// </script>
// </div>
// </body>
// </html>

17
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/ini/ini.contribution.js

@ -0,0 +1,17 @@
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) {
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
// Allow for running under nodejs/requirejs in tests
var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco);
__contribution_1.registerLanguage({
id: 'ini',
extensions: ['.ini', '.properties', '.gitconfig'],
filenames: ['config', '.gitattributes', '.gitconfig', '.editorconfig'],
aliases: ['Ini', 'ini'],
loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./ini'], resolve_1, reject_1); })); }
});
});

71
MonacoEditorComponent/monaco-editor/dev/vs/basic-languages/ini/ini.js

@ -0,0 +1,71 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
define(["require", "exports"], function (require, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.conf = {
comments: {
lineComment: '#'
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')'],
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: '\'', close: '\'' },
]
};
exports.language = {
defaultToken: '',
tokenPostfix: '.ini',
// we include these common regular expressions
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
// The main tokenizer for our languages
tokenizer: {
root: [
// sections
[/^\[[^\]]*\]/, 'metatag'],
// keys
[/(^\w+)(\s*)(\=)/, ['key', '', 'delimiter']],
// whitespace
{ include: '@whitespace' },
// numbers
[/\d+/, 'number'],
// strings: recover on non-terminated strings
[/"([^"\\]|\\.)*$/, 'string.invalid'],
[/'([^'\\]|\\.)*$/, 'string.invalid'],
[/"/, 'string', '@string."'],
[/'/, 'string', '@string.\''],
],
whitespace: [
[/[ \t\r\n]+/, ''],
[/^\s*[#;].*$/, 'comment'],
],
string: [
[/[^\\"']+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/["']/, {
cases: {
'$#==$S2': { token: 'string', next: '@pop' },
'@default': 'string'
}
}]
],
},
};
});

Some files were not shown because too many files changed in this diff diff.show_more

Loading…
Cancel
Save